Пример #1
0
        public async Task Check(string host)
        {
            var client = new AsyncHttpClient(GetBaseUri(host), true);

            var result = await client.DoRequestAsync(HttpMethod.Get, "/", null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false);

            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new CheckerException(result.StatusCode.ToExitCode(), "get / failed");
            }

            await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false);

            var query = "?query=" + WebUtility.UrlEncode(RndText.RandomWord(RndUtil.GetInt(2, 10)));

            result = await client.DoRequestAsync(HttpMethod.Get, ApiNotesSearch + query, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false);

            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new CheckerException(result.StatusCode.ToExitCode(), $"get {ApiNotesSearch} failed");
            }

            var notes = DoIt.TryOrDefault(() => JsonSerializer.Deserialize <List <Note> >(result.BodyAsString));

            if (notes == default)
            {
                throw new CheckerException(ExitCode.MUMBLE, $"invalid {ApiNotesSearch} response");
            }

            await Console.Error.WriteLineAsync($"found '{notes.Count}' notes by query '{query}'").ConfigureAwait(false);
        }
Пример #2
0
 public static void GetRandomInsideCircle(int count, float radius, Vector3 center, List <Vector3> list)
 {
     list.Clear();
     for (int i = 0; i < count; ++i)
     {
         Vector3 p   = center;
         Vector2 rnd = RndUtil.RandomInsideUnitCircle() * radius;
         p.x += rnd.x;
         p.y += rnd.y;
         list.Add(p);
     }
 }
Пример #3
0
        private string GetRandomQuery(Note note)
        {
            var titleWords = note.Title.Split();
            var textWords  = note.Text.Split();

            var allWords    = titleWords.Concat(textWords).ToArray();
            var randomQuery = string.Join(' ', Enumerable.Range(0, RndUtil.GetInt(2, 4)).Select(i => RndUtil.Choice(allWords)).Distinct());

            var words             = RndUtil.Choice(note.Title, note.Text).Split();
            var skip              = RndUtil.GetInt(0, Math.Max(0, words.Length - 2));
            var randomPhraseQuery = '\"' + string.Join(' ', words.Skip(skip).Take(RndUtil.GetInt(2, 6))) + '\"';

            return(RndUtil.Choice(randomQuery, randomPhraseQuery));
        }
Пример #4
0
    public override void Fire(Transform weaponTrans, Vector3 direction, int sortingLayer, out float recoil)
    {
        lastFire_ = Time.time;
        recoil    = 0.0f;
        Color color = new Color(0.8f, 0.6f, 0.1f);

        Vector3 worldMuzzle = weaponTrans.TransformPoint(Muzzle);

        worldMuzzle += -direction * 0.2f; // Start a little behind muzzle because its very unfun missing an enemy that is too close

        GameManager.Instance.MakePoof(worldMuzzle, 1);
        GameManager.Instance.MakeFlash(worldMuzzle);
        AudioManager.Instance.PlayClip(AudioManager.Instance.PlayerAudioSource, FireAudio, volumeScale: 0.7f);

        float   spreadFactor = 15f; // Increase this to limit spread (unit circle is moved further away)
        Vector3 dir          = direction * spreadFactor;
        Vector2 spread       = RndUtil.RandomInsideUnitCircle();

        dir.x += spread.x;
        dir.y += spread.y;
        dir.Normalize();

        ProjectileManager.Basic basic = ProjectileManager.Instance.GetProjectile();
        basic.SpriteInfo = ProjectileCache.Instance.GetSprite();
        basic.Type       = ProjectileManager.ProjectileType.HarmsEnemies;

        basic.Speed                   = 10.0f + Random.value * 2;
        basic.Damage                  = 25.0f;
        basic.MaxDistance             = 12.0f;
        basic.Radius                  = 0.3f;
        basic.DieOnCollision          = false;
        basic.CustomCounter           = 1;
        basic.CustomCollisionResponse = OnCollision;
        Vector3 scale = basic.SpriteInfo.Transform.localScale;

        scale.x = 3.0f;
        scale.y = 3.0f;
        scale.z = 1.0f;

        basic.Position = worldMuzzle;
        basic.SpriteInfo.Renderer.sprite         = BulletSprite;
        basic.SpriteInfo.Renderer.sortingLayerID = sortingLayer;
        basic.Direction = dir;
        basic.Color     = color;
        basic.DieTime   = 0.0f;
        basic.SpriteInfo.Transform.localScale = scale;

        ProjectileManager.Instance.Fire(basic);
    }
Пример #5
0
 protected override void OnDeath()
 {
     GameManager.Instance.MakePoof(position_, 3, 1.0f);
     ParticleSystem.EmitParams ep = new ParticleSystem.EmitParams();
     ep.startColor    = new Color32(255, 255, 255, 255);
     ep.position      = position_;
     ep.startSize     = 0.5f;
     ep.startLifetime = 0.5f;
     for (int i = 0; i < Mathf.RoundToInt(15 * GameMode.ExplosionModifier); ++i)
     {
         Vector2 rndDir = RndUtil.RandomInsideUnitCircle().normalized;
         ep.velocity = rndDir * 2.5f;
         GameManager.Instance.NpcFlameParticles.Emit(ep, 1);
     }
 }
Пример #6
0
        public async Task Get(string host, string id, string flag, int vuln)
        {
            var parts = id.Split(':');

            if (parts.Length != 3)
            {
                throw new Exception($"Invalid flag id '{id}'");
            }

            var login  = parts[0];
            var pass   = parts[1];
            var cookie = Encoding.UTF8.GetString(Convert.FromBase64String(parts[2]));

            var client = new AsyncHttpClient(GetBaseUri(host), true);

            var result = await client.DoRequestAsync(HttpMethod.Get, ApiScoreboard, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false);

            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new CheckerException(result.StatusCode.ToExitCode(), $"get {ApiScoreboard} failed");
            }

            var solutions = DoIt.TryOrDefault(() => JsonSerializer.Deserialize <List <Solution> >(result.BodyAsString));

            if (solutions == default || solutions.Count == 0 || solutions.All(sln => sln.Login != login))
            {
                throw new CheckerException(ExitCode.MUMBLE, $"invalid {ApiScoreboard} response");
            }

            await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false);

            client = new AsyncHttpClient(GetBaseUri(host), true);
            client.Cookies.SetCookies(GetBaseUri(host), cookie);

            result = await client.DoRequestAsync(HttpMethod.Get, ApiAuth, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false);

            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new CheckerException(result.StatusCode.ToExitCode(), $"get {ApiAuth} failed");
            }

            var user = DoIt.TryOrDefault(() => JsonSerializer.Deserialize <User>(result.BodyAsString));

            if (user == default || user.Login != login || user.Bio != flag)
            {
                throw new CheckerException(ExitCode.CORRUPT, "flag not found");
            }
        }
Пример #7
0
    IEnumerator Think()
    {
        while (isSpawning_)
        {
            yield return(null);
        }

        const float DelayBeforeFirstCharge = 1.0f;
        float       nextCharge             = Time.time + DelayBeforeFirstCharge;

        while (true)
        {
            float       distanceToPlayer = BlackboardScript.DistanceToPlayer(position_);
            const float MinDistToCharge  = 3.0f;
            if (IsFullyReady && Time.time > nextCharge && distanceToPlayer > MinDistToCharge)
            {
                target_      = GameManager.Instance.PlayerTrans.position + (Vector3)(RndUtil.RandomInsideUnitCircle() * 2);
                target_      = GameManager.Instance.ClampToBounds(target_, renderer_.sprite);
                chargeSpeed_ = Speed * 5;
                if (chargeSpeed_ > 8.0f)
                {
                    chargeSpeed_ = 8.0f;
                }

                material_.color = ChargeColor;

                while ((transform_.position - target_).magnitude > 0.2f)
                {
                    if (Random.value < 0.1f)
                    {
                        GameManager.Instance.MakePoof(transform_.position + Vector3.down * 0.2f, 1, 0.3f);
                    }

                    yield return(null);
                }

                material_.color = Color.white;
                chargeSpeed_    = 0.0f;
                float cd = (1.0f + Random.value * 3) * GameMode.ChargeCdModifier;
                nextCharge = Time.time + cd;
            }

            yield return(null);
        }
    }
Пример #8
0
    public void EnemyExplosion(ActorTypeEnum type, Vector3 pos, int count, float force)
    {
        if (currentDeed_.Deed == DeedEnum.Sandbox)
        {
            // Not pretty... but we have to add these newly spawned enemies to the total count of the sandbox
            currentDeed_.UpdatedKillReq += count;
            TextHowTo.text = string.Format(currentDeed_.Req, currentDeed_.UpdatedKillReq);
        }

        for (int i = 0; i < count; ++i)
        {
            var spawn = EnemyManager.Instance.GetEnemyFromCache(type);
            spawn.transform.position = pos;
            var actor = spawn.GetComponent <ActorBase>();
            actor.AddForce(RndUtil.RandomInsideUnitCircle().normalized *force);
            spawn.SetActive(true);
        }
    }
Пример #9
0
    void Shoot()
    {
        if (Hp <= 0.0f)
        {
            return;
        }

        Vector2 direction = BlackboardScript.PlayerTrans.position - position_;

        direction.Normalize();
        direction = RndUtil.RandomSpread(direction, 3);

        Vector3 muzzlePoint = direction * 0.6f;

        AddForce(-direction * 0.05f);

        ProjectileManager.Basic basic = ProjectileManager.Instance.GetProjectile();
        basic.SpriteInfo = ProjectileCache.Instance.GetSprite();
        basic.Type       = ProjectileManager.ProjectileType.HarmsPlayer;

        basic.Speed       = 4.0f;
        basic.Damage      = 100.0f;
        basic.MaxDistance = 15.0f;
        basic.Radius      = 0.3f;
        Vector3 scale = basic.SpriteInfo.Transform.localScale;

        scale.x = 3.0f;
        scale.y = 3.0f;
        scale.z = 1.0f;

        basic.Position = transform_.position + muzzlePoint;
        basic.SpriteInfo.Renderer.sprite         = SpriteData.Instance.Bullet;
        basic.SpriteInfo.Renderer.sortingLayerID = GameManager.Instance.SortLayerTopEffects;
        basic.Direction = direction;
        basic.Color     = Color.white;
        basic.DieTime   = 0.0f;
        basic.SpriteInfo.Transform.localScale = scale;
        float rot_z = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;

        basic.SpriteInfo.Transform.rotation = Quaternion.Euler(0f, 0f, rot_z);

        ProjectileManager.Instance.Fire(basic);
        AudioManager.Instance.PlayClipWithRandomPitch(AudioManager.Instance.EnemyShootAudioSource, AudioManager.Instance.AudioData.EnemyShoot, 0.5f);
    }
Пример #10
0
        public static string RandomSolution(int minLength, int maxLength)
        {
            var length = RndUtil.GetInt(minLength, maxLength);
            var sln    = new char[length];

            int chg = 0;
            var chr = Alphabet[RndUtil.ThreadStaticRnd.Next(Alphabet.Length)];

            for (int i = 0; i < length; i++)
            {
                if (i >= chg)
                {
                    chg = i + 1 + RndUtil.ThreadStaticRnd.Next(4);
                    chr = Alphabet[RndUtil.ThreadStaticRnd.Next(Alphabet.Length)];
                }

                sln[i] = chr;
            }

            return(new string(sln));
        }
Пример #11
0
    IEnumerator ExplodeCo(float delay)
    {
        float explodeTime = Time.time + delay;
        float flashOffset = UnityEngine.Random.value;

        while (Time.time < explodeTime)
        {
            material_.SetFloat(flashParamId_, 0.6f + (Mathf.Sin(((Time.time + flashOffset) * 10) + 1.0f) * 0.5f) * 0.25f);
            yield return(null);
        }

        const float ExplodeRadius = 3.0f;

        AudioManager.Instance.PlayClipWithRandomPitch(AudioManager.Instance.MiscAudioSource, AudioManager.Instance.AudioData.LivingBombExplode);
        GameManager.Instance.MakeCircle(transform_.position, ExplodeRadius);
        GameManager.Instance.MakePoof(transform_.position, 2, ExplodeRadius * 0.2f);
        GameManager.Instance.ShakeCamera(0.4f);

        int  aliveCount = BlackboardScript.GetEnemies(transform_.position, ExplodeRadius);
        bool isFirstHit = true;

        for (int i = 0; i < aliveCount; ++i)
        {
            int       idx   = BlackboardScript.Matches[i].Idx;
            ActorBase enemy = BlackboardScript.Enemies[idx];
            if (enemy != this)
            {
                enemy.OnLivingBombHit(livingBombDamage_ * 0.9f, isFirstHit);
                isFirstHit = false;
            }
        }

        if (BlackboardScript.DistanceToPlayer(transform_.position) < ExplodeRadius * 0.5f)
        {
            GameManager.Instance.PlayerScript.KillPlayer();
        }

        ApplyDamage(livingBombDamage_, RndUtil.RandomInsideUnitCircle().normalized, 0.25f, true);
    }
Пример #12
0
        public async Task <string> Put(string host, string id, string flag, int vuln)
        {
            var client = new AsyncHttpClient(GetBaseUri(host), true);

            var result = await client.DoRequestAsync(HttpMethod.Get, ApiGenerate, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false);

            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new CheckerException(result.StatusCode.ToExitCode(), $"get {ApiGenerate} failed");
            }

            var rubik = DoIt.TryOrDefault(() => JsonSerializer.Deserialize <GeneratedRubik>(result.BodyAsString));

            if (rubik == default)
            {
                throw new CheckerException(ExitCode.MUMBLE, $"invalid {ApiGenerate} response");
            }

            await Console.Error.WriteLineAsync($"rubik '{rubik.Rubik}', signed '{rubik.Value}'").ConfigureAwait(false);

            string solution;

            try
            {
                solution = DoIt.TryOrDefault(() => SolveHelper.ConvertOutputSolution(RubikSolver.FindSolution(SolveHelper.ConvertInputCube(rubik.Rubik), 32, 10000)));
            }
            catch (RubikSolveException e)
            {
                await Console.Error.WriteLineAsync(e.Message).ConfigureAwait(false);

                throw new CheckerException(ExitCode.MUMBLE, $"invalid {ApiGenerate} response: unsolvable puzzle");
            }

            await Console.Error.WriteLineAsync($"solution '{solution}'").ConfigureAwait(false);

            await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false);

            var login = RndText.RandomWord(RndUtil.GetInt(MinRandomFieldLength, MaxRandomFieldLength)).RandomLeet().RandomUpperCase();
            var pass  = RndText.RandomWord(RndUtil.GetInt(MinRandomFieldLength, MaxRandomFieldLength)).RandomLeet().RandomUpperCase();

            await Console.Error.WriteLineAsync($"name '{login}', pass '{pass}', bio '{flag}'").ConfigureAwait(false);

            var query = $"?login={WebUtility.UrlEncode(login)}&pass={WebUtility.UrlEncode(pass)}&bio={WebUtility.UrlEncode(flag)}&puzzle={WebUtility.UrlEncode(rubik.Value)}&solution={WebUtility.UrlEncode(solution)}";

            result = await client.DoRequestAsync(HttpMethod.Post, ApiSolve + query, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false);

            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new CheckerException(result.StatusCode.ToExitCode(), $"post {ApiSolve} failed");
            }

            var sln = DoIt.TryOrDefault(() => JsonSerializer.Deserialize <Solution>(result.BodyAsString));

            if (sln == default || sln.Login != login || sln.MovesCount != solution.Length)
            {
                throw new CheckerException(ExitCode.MUMBLE, $"invalid {ApiSolve} response");
            }

            await Console.Error.WriteLineAsync($"solution '{solution}'").ConfigureAwait(false);

            var cookie = client.Cookies.GetCookieHeader(GetBaseUri(host));
            await Console.Error.WriteLineAsync($"cookie '{cookie}'").ConfigureAwait(false);

            if (string.IsNullOrEmpty(cookie) || cookie.Length > 512)
            {
                throw new CheckerException(result.StatusCode.ToExitCode(), $"invalid {ApiSolve} response: cookies");
            }

            return($"{login}:{pass}:{Convert.ToBase64String(Encoding.UTF8.GetBytes(cookie))}");
        }
Пример #13
0
        public async Task Check(string host)
        {
            var client = new AsyncHttpClient(GetBaseUri(host), true);

            var result = await client.DoRequestAsync(HttpMethod.Get, "/", null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false);

            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new CheckerException(result.StatusCode.ToExitCode(), "get / failed");
            }

            await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false);

            result = await client.DoRequestAsync(HttpMethod.Get, ApiGenerate, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false);

            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new CheckerException(result.StatusCode.ToExitCode(), $"get {ApiGenerate} failed");
            }

            var rubik = DoIt.TryOrDefault(() => JsonSerializer.Deserialize <GeneratedRubik>(result.BodyAsString));

            if (rubik == default)
            {
                throw new CheckerException(ExitCode.MUMBLE, $"invalid {ApiGenerate} response");
            }

            await Console.Error.WriteLineAsync($"rubik '{rubik.Rubik}', signed '{rubik.Value}'").ConfigureAwait(false);

            await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false);

            var login = RndText.RandomWord(RndUtil.GetInt(MinRandomFieldLength, MaxRandomFieldLength)).RandomLeet().RandomUpperCase();
            var pass  = RndText.RandomWord(RndUtil.GetInt(MinRandomFieldLength, MaxRandomFieldLength)).RandomLeet().RandomUpperCase();
            var flag  = RndText.RandomWord(RndUtil.GetInt(MinRandomFieldLength, MaxRandomFieldLength)).RandomLeet().RandomUpperCase();

            await Console.Error.WriteLineAsync($"name '{login}', pass '{pass}', bio '{flag}'").ConfigureAwait(false);

            var solution = RndRubik.RandomSolution(MinRandomSolutionLength, MaxRandomSolutionLength);
            var query    = $"?login={WebUtility.UrlEncode(login)}&pass={WebUtility.UrlEncode(pass)}&bio={WebUtility.UrlEncode(flag)}&puzzle={WebUtility.UrlEncode(rubik.Value)}&solution={WebUtility.UrlEncode(solution)}";

            result = await client.DoRequestAsync(HttpMethod.Post, ApiSolve + query, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false);

            if (result.StatusCode != (HttpStatusCode)418)
            {
                throw new CheckerException(result.StatusCode == HttpStatusCode.OK ? ExitCode.MUMBLE : result.StatusCode.ToExitCode(), $"invalid {ApiSolve} response");
            }

            await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false);

            result = await client.DoRequestAsync(HttpMethod.Get, ApiAuth, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false);

            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new CheckerException(result.StatusCode.ToExitCode(), $"get {ApiAuth} failed");
            }

            var user = DoIt.TryOrDefault(() => JsonSerializer.Deserialize <User>(result.BodyAsString));

            if (user == default || user.Login != login || user.Bio != flag)
            {
                throw new CheckerException(ExitCode.MUMBLE, $"invalid {ApiAuth} response");
            }
        }
Пример #14
0
        public async Task <string> Put(string host, string id, string flag, int vuln)
        {
            var client = new AsyncHttpClient(GetBaseUri(host), true);

            var login = RndText.RandomWord(RndUtil.GetInt(MinRandomFieldLength, MaxRandomFieldLength)).RandomLeet().RandomUpperCase();
            var name  = RndText.RandomWord(RndUtil.GetInt(MinRandomFieldLength, MaxRandomFieldLength)).RandomLeet().RandomUpperCase();
            var pass  = RndText.RandomWord(RndUtil.GetInt(MinRandomFieldLength, MaxRandomFieldLength)).RandomLeet().RandomUpperCase();

            await Console.Error.WriteLineAsync($"login '{login}', name '{name}', pass '{pass}'").ConfigureAwait(false);

            var signUpQuery = $"?login={WebUtility.UrlEncode(login)}&name={WebUtility.UrlEncode(name)}&password={WebUtility.UrlEncode(pass)}";
            var result      = await client.DoRequestAsync(HttpMethod.Post, ApiAuthSignUp + signUpQuery, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false);

            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new CheckerException(result.StatusCode.ToExitCode(), $"get {ApiAuthSignUp} failed");
            }

            await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false);

            var items = Enumerable.Range(0, RndUtil.GetInt(1, 3)).Select(i => new Note {
                Title = RndText.RandomText(RndUtil.GetInt(MinRandomTitleLength, MaxRandomTitleLength)).RandomUmlauts(),
                Text  = RndText.RandomText(RndUtil.GetInt(MinRandomTextLength, MaxRandomTextLength)).RandomUmlauts()
            }).ToArray();

            var itemWithFlag = RndUtil.Choice(items);

            if (RndUtil.GetInt(0, 2) == 0)
            {
                itemWithFlag.Text = flag;
            }
            else
            {
                itemWithFlag.Title = flag;
            }
            itemWithFlag.IsPrivate = true;

            foreach (var item in items)
            {
                await Console.Error.WriteLineAsync($"title '{item.Title}', text '{item.Text}', isPrivate '{item.IsPrivate}'").ConfigureAwait(false);

                var q = $"?title={WebUtility.UrlEncode(item.Title)}&text={WebUtility.UrlEncode(item.Text)}" + (item.IsPrivate ? "&isPrivate=on" : null);
                result = await client.DoRequestAsync(HttpMethod.Post, ApiNotesAdd + q, null, NetworkOpTimeout).ConfigureAwait(false);

                if (result.StatusCode != HttpStatusCode.OK)
                {
                    throw new CheckerException(result.StatusCode.ToExitCode(), $"post {ApiNotesAdd} failed");
                }

                await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false);
            }

            var query = GetRandomQuery(itemWithFlag);

            if (query.Trim('\"', ' ').Length <= 4)            //NOTE: too low entropy
            {
                query = flag;
            }

            await Console.Error.WriteLineAsync($"random query '{query}'").ConfigureAwait(false);

            var cookie = client.Cookies.GetCookieHeader(GetBaseUri(host));
            await Console.Error.WriteLineAsync($"cookie '{cookie}'").ConfigureAwait(false);

            var bytes = DoIt.TryOrDefault(() => Encoding.UTF8.GetBytes(cookie));

            if (bytes == null || bytes.Length > 1024)
            {
                throw new CheckerException(result.StatusCode.ToExitCode(), "too large or invalid cookies");
            }

            return($"{login}:{pass}:{Convert.ToBase64String(bytes)}:{WebUtility.UrlEncode(query)}");
        }
Пример #15
0
        public async Task <string> Put(string host, string id, string flag, int vuln)
        {
            var len  = vuln == 1 ? RndUtil.Choice(11, 14) : RndUtil.Choice(12, 15);
            var name = RndText.RandomWord(len).RandomLeet().RandomUpperCase();

            var b64Name    = Convert.ToBase64String(Encoding.ASCII.GetBytes(name));
            var b64Entropy = Convert.ToBase64String(Encoding.ASCII.GetBytes(flag));

            await Console.Error.WriteLineAsync($"name '{name}', b64name '{b64Name}', entropy '{b64Entropy}'").ConfigureAwait(false);

            using (var bmp = RndBitmap.RndBmp(RndUtil.ThreadStaticRnd.Next(32) + 96, RndUtil.ThreadStaticRnd.Next(32) + 96))
                using (var wsClient = await AsyncWebSocketClient.TryConnectAsync(GetBaseWsUri(host), MaxWsMsgSize, NetworkOpTimeout).ConfigureAwait(false))
                {
                    if (wsClient == null)
                    {
                        throw new CheckerException(ExitCode.DOWN, "ws connect failed");
                    }

                    await Console.Error.WriteLineAsync("ws connected").ConfigureAwait(false);

                    if (await wsClient.TryWaitMessageAsync(buffer => Tuple.Create(buffer.Count == 2 && buffer.Array[0] == (byte)'h' && buffer.Array[1] == (byte)'i', buffer), NetworkOpTimeout).ConfigureAwait(false) == default(ArraySegment <byte>))
                    {
                        throw new CheckerException(ExitCode.MUMBLE, "await hello failed");
                    }

                    await Console.Error.WriteLineAsync("ws hello received").ConfigureAwait(false);

                    // ReSharper disable once AccessToDisposedClosure
                    var wsTask = Task.Run(() => wsClient.TryWaitMessageAsync(buffer =>
                    {
                        if (!ProtoBufHelper.TryDeserialize <Transmission>(buffer, out var transmission))
                        {
                            throw new CheckerException(ExitCode.MUMBLE, "invalid ws data");
                        }
                        return(Tuple.Create(transmission.Name == b64Name, transmission));
                    }, NetworkOpTimeout));

                    await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false);

                    var httpClient = new AsyncHttpClient(GetBaseHttpUri(host));

                    var result = await httpClient.DoRequestAsync(WebRequestMethods.Http.Put, PutRelative, new WebHeaderCollection { { "X-SG1-Name", b64Name }, { "X-SG1-Entropy", b64Entropy } }, bmp.ToByteArray(), NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false);

                    if (result.StatusCode != HttpStatusCode.OK)
                    {
                        throw new CheckerException(result.StatusCode.ToExitCode(), $"put {PutRelative} failed");
                    }

                    var key = result.Headers?["X-SG1-Key"];
                    if (string.IsNullOrEmpty(key))
                    {
                        throw new CheckerException(ExitCode.MUMBLE, $"invalid {PutRelative} response");
                    }

                    if (!ProtoBufHelper.TryDeserialize(result.Body, out Spectrum spectrum))
                    {
                        throw new CheckerException(ExitCode.MUMBLE, $"invalid {PutRelative} response");
                    }

                    var expectedSpectrum = bmp.CalcSpectrum();

                    if (!spectrum.ComponentEquals(expectedSpectrum))
                    {
                        throw new CheckerException(ExitCode.MUMBLE, $"invalid {PutRelative} response");
                    }

                    await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false);

                    var msg = await wsTask.ConfigureAwait(false);

                    if (msg == null || msg.Name != b64Name)
                    {
                        throw new CheckerException(ExitCode.MUMBLE, "await msg failed");
                    }

                    var flagid = $"{b64Name}:{Convert.ToBase64String(Encoding.ASCII.GetBytes(key))}";
                    await Console.Out.WriteLineAsync(flagid).ConfigureAwait(false);

                    return(flagid);
                }
        }
Пример #16
0
    void UpdateOverheadText()
    {
        bool isRambo = Weapon != null && Weapon.Type == WeaponType.Rambo;

        if (isShooting_ && isRambo)
        {
            OverheadText.text    = "AAAARGH!";
            OverheadText.enabled = true;

            Vector2 uiPos = GameManager.Instance.UiPositionFromWorld(trans_.position + Vector3.up * 0.5f + ((Vector3)RndUtil.RandomInsideUnitCircle() * 0.07f));
            overheadTextTrans_.anchoredPosition = uiPos;
            Color col = Color.HSVToRGB(Random.value * 0.3f, 1.0f, 1.0f);
            OverheadText.color = col;
        }
        else if (Time.time < talkEndTime_)
        {
            Vector2 uiPos = GameManager.Instance.UiPositionFromWorld(trans_.position + Vector3.up * 0.5f);
            overheadTextTrans_.anchoredPosition = uiPos;
        }
        else
        {
            OverheadText.enabled = false;
        }
    }
Пример #17
0
    IEnumerator ThrowCo(Vector3 from, Vector3 to)
    {
        shadowRenderer_.enabled = false;
        var fuseEmission = fuseParticles_.emission;

        fuseEmission.enabled = true;

        float length    = (to - from).magnitude;
        float force     = Mathf.Min(5.0f, length);
        float velocityY = 1.0f * force;
        float downForce = -25.0f;
        float speed     = 5.0f * force;

        float   fuseT0  = Time.time;
        float   fuseT1  = fuseT0 + FuseTime;
        Vector3 dir     = (to - from).normalized;
        Vector3 pos     = from;
        float   offsetY = 0;

        audioSource_.clip   = AudioManager.Instance.AudioData.BombFuseBurn;
        audioSource_.volume = 0.5f * AudioManager.Instance.MasterVolume;
        audioSource_.Play();

        while (Time.time < fuseT1)
        {
            float delta = Time.deltaTime;

            Vector3 showPos = pos;
            showPos.y                 += offsetY;
            trans_.position            = showPos;
            bombRenderer_.sortingOrder = (Mathf.RoundToInt(trans_.position.y * 100f));
            bombMaterial_.SetFloat(flashParamId_, (Mathf.Sin((Time.time * 15) + 1.0f) * 0.5f) * 0.75f);

            offsetY   += velocityY * delta;
            velocityY += downForce * delta;
            if (offsetY <= 0)
            {
                shadowRenderer_.enabled = true;
                velocityY = -velocityY * 0.5f;
            }

            pos   += dir * speed * Time.deltaTime;
            speed *= 1.0f - (5.0f * delta);

            yield return(null);
        }

        fuseEmission.enabled = false;

        audioSource_.clip   = AudioManager.Instance.AudioData.BombExplode;
        audioSource_.volume = 1.0f * AudioManager.Instance.MasterVolume;
        audioSource_.Play();
        GameManager.Instance.MakeFlash(pos, Radius * 1.5f);
        GameManager.Instance.MakePoof(pos, 6, Radius * 1.5f);
        GameManager.Instance.ShakeCamera(4.0f);

        int deadCount = BlackboardScript.GetDeadEnemies(pos, Radius);

        for (int i = 0; i < deadCount; ++i)
        {
            int       idx   = BlackboardScript.Matches[i].Idx;
            ActorBase enemy = BlackboardScript.DeadEnemies[idx];
            enemy.AddForce((enemy.transform.position - pos) * 0.25f);
//            enemy.Explode(2.0f + Random.value * 2);
        }

        int aliveCount = BlackboardScript.GetEnemies(pos, Radius);

        for (int i = 0; i < aliveCount; ++i)
        {
            int       idx   = BlackboardScript.Matches[i].Idx;
            ActorBase enemy = BlackboardScript.Enemies[idx];
            enemy.ApplyDamage(Damage, enemy.transform.position - pos, 1.0f, true);
        }

        for (int i = 0; i < 10; ++i)
        {
            Vector2 rnd      = RndUtil.RandomInsideUnitCircle() * Radius * 0.5f;
            Vector3 flamePos = pos;
            flamePos.x += rnd.x;
            flamePos.y += rnd.y;
            GameManager.Instance.EmitFlame(flamePos, Random.value + 0.5f);
            yield return(null);
        }

        // Kill player if very close, else just push
        float playerDist = BlackboardScript.DistanceToPlayer(pos);

        if (playerDist < 3.0f)
        {
            GameManager.Instance.PlayerScript.AddForce((GameManager.Instance.PlayerTrans.position - pos) * 0.1f);
        }

        Hide();
    }
Пример #18
0
        public async Task Get(string host, string id, string flag, int vuln)
        {
            var parts = id.Split(':', 4);

            if (parts.Length != 4)
            {
                throw new Exception($"Invalid flag id '{id}'");
            }

            var login        = parts[0];
            var pass         = parts[1];
            var cookie       = Encoding.UTF8.GetString(Convert.FromBase64String(parts[2]));
            var encodedQuery = parts[3];

            var client = new AsyncHttpClient(GetBaseUri(host), true);

            if (RndUtil.GetInt(0, 2) == 0)
            {
                await Console.Error.WriteLineAsync($"login by cookie '{cookie}'").ConfigureAwait(false);

                client.Cookies.SetCookies(GetBaseUri(host), cookie);
            }
            else
            {
                await Console.Error.WriteLineAsync($"login with login '{login}' and pass '{pass}'").ConfigureAwait(false);

                var loginQuery   = $"?login={WebUtility.UrlEncode(login)}&password={WebUtility.UrlEncode(pass)}";
                var signInResult = await client.DoRequestAsync(HttpMethod.Post, ApiAuthSignIn + loginQuery).ConfigureAwait(false);

                if (signInResult.StatusCode != HttpStatusCode.OK)
                {
                    throw new CheckerException(signInResult.StatusCode.ToExitCode(), $"get {ApiAuthSignIn} failed");
                }

                await Console.Error.WriteLineAsync($"cookie '{client.Cookies.GetCookieHeader(GetBaseUri(host))}'").ConfigureAwait(false);

                await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false);
            }

            var query = RndUtil.Choice("?query=&myOnly=on", "?query=" + encodedQuery);

            var result = await client.DoRequestAsync(HttpMethod.Get, ApiNotesSearch + query, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false);

            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new CheckerException(result.StatusCode.ToExitCode(), $"get {ApiNotesSearch} failed");
            }

            var notes = DoIt.TryOrDefault(() => JsonSerializer.Deserialize <List <Note> >(result.BodyAsString));

            if (notes == default)
            {
                throw new CheckerException(ExitCode.MUMBLE, $"invalid {ApiNotesSearch} response");
            }

            await Console.Error.WriteLineAsync($"found '{notes.Count}' notes by query '{query}'").ConfigureAwait(false);

            var note = notes.FirstOrDefault(note => note.Author.Contains(flag) || note.Title.Contains(flag) || note.Text.Contains(flag));

            if (note == null)
            {
                throw new CheckerException(ExitCode.CORRUPT, "flag not found");
            }

            //NOTE: Also check phrase query

            if (!query.StartsWith("?query=%22") || !query.EndsWith("%22"))
            {
                return;
            }

            var words = WebUtility.UrlDecode(encodedQuery).Trim('"', ' ').Split().Where(word => !string.IsNullOrWhiteSpace(word)).Distinct().ToArray();

            if (words.Length < 2)
            {
                return;
            }

            query = string.Join(' ', words.Reverse());
            if (note.Author.Contains(query, StringComparison.InvariantCultureIgnoreCase) || note.Title.Contains(query, StringComparison.InvariantCultureIgnoreCase) || note.Text.Contains(query, StringComparison.InvariantCultureIgnoreCase))
            {
                return;
            }

            query = "?query=" + WebUtility.UrlEncode('"' + query + '"');
            await Console.Error.WriteLineAsync($"check phrase query reversed '{query}'").ConfigureAwait(false);

            result = await client.DoRequestAsync(HttpMethod.Get, ApiNotesSearch + query, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false);

            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new CheckerException(result.StatusCode.ToExitCode(), $"get {ApiNotesSearch} failed");
            }

            notes = DoIt.TryOrDefault(() => JsonSerializer.Deserialize <List <Note> >(result.BodyAsString));
            if (notes == default)
            {
                throw new CheckerException(ExitCode.MUMBLE, $"invalid {ApiNotesSearch} response");
            }

            await Console.Error.WriteLineAsync($"found '{notes.Count}' notes by query '{query}'").ConfigureAwait(false);

            if (notes.Any(note => note.Author.Contains(flag) || note.Title.Contains(flag) || note.Text.Contains(flag)))
            {
                throw new CheckerException(ExitCode.MUMBLE, $"invalid {ApiNotesSearch} response: phrase query");
            }
        }