예제 #1
0
 public static async Task BroadcastAsync <T>(T msg, CancellationToken token)
 {
     using (var pooled = await ResponsePool.AcquireAsync().ConfigureAwait(false))
     {
         var buffer = ProtoBufHelper.SerializeAsArraySegment(pooled.Item, msg);
         await Task.WhenAll(Clients.Select(pair => Task.Run(() => TrySendAsync(pair.Key, buffer, token), token))).ConfigureAwait(false);
     }
 }
예제 #2
0
        public static async Task <HttpResult> ProcessRequest(HttpContext context)
        {
            var name = context.Request.Headers["X-SG1-Name"].FirstOrDefault().RemoveWhiteSpaces();

            if (string.IsNullOrEmpty(name))
            {
                return new HttpResult {
                           StatusCode = 404, Message = "Substance Not Found"
                }
            }
            ;

            var key = context.Request.Headers["X-SG1-Key"].FirstOrDefault().RemoveWhiteSpaces();

            if (string.IsNullOrEmpty(key))
            {
                return new HttpResult {
                           StatusCode = 403, Message = "Access Denied"
                }
            }
            ;

            try
            {
                using (var hmac = new HMACSHA256(Settings.Key))
                    if (!hmac.ComputeHash(Convert.FromBase64String(name)).FastTimingSecureEquals(Convert.FromBase64String(key)))
                    {
                        return new HttpResult {
                                   StatusCode = 403, Message = "Access Denied"
                        }
                    }
                ;
            }
            catch (FormatException)
            {
                return(new HttpResult {
                    StatusCode = 403, Message = "Access Denied"
                });
            }

            Transmission info;

            if ((info = TransmissionsDb.Find(name)) == null)
            {
                return new HttpResult {
                           StatusCode = 404, Message = "Substance Not Found"
                }
            }
            ;

            context.Response.ContentType = "application/protobuf";

            using (var pooled = await ResponsePool.AcquireAsync().ConfigureAwait(false))
            {
                var buffer = pooled.Item;

                var length = ProtoBufHelper.Serialize(buffer, info);

                context.Response.ContentLength = length;
                if (!await context.Response.Body.WriteAsync(buffer, 0, length, context.RequestAborted).Wrap().WithTimeout(Settings.ReadWriteTimeout).ConfigureAwait(false))
                {
                    context.TryAbort();
                    return(HttpResult.Cancelled);
                }
            }

            return(HttpResult.OK);
        }