public static dynamic Decode(RequestStream ioStream) { int length = (int)ioStream.Length; byte[] data = new byte[length]; ioStream.Read(data, 0, length); return(JsonConvert.DeserializeObject <dynamic>(System.Text.Encoding.Default.GetString(data))); }
/// <summary> /// Modifies our application startup to enable CSRF, and reparse thrown exceptions into messages and status codes. /// </summary> /// <remarks> /// To use this functionality, within every 'form' block, after all the inputs add '@Html.AntiForgeryToken()'. /// Then, within your POST reception, call 'this.ValidateCsrfToken();, catch the CsrfValidationException, and handle the result appropriately. /// </remarks> protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines) { base.ApplicationStartup(container, pipelines); Csrf.Enable(pipelines); pipelines.BeforeRequest += (ctx) => { NancyContext context = ctx as NancyContext; logger.Info(context.Request.UserHostAddress + ": " + context.Request.Url); if (Global.SystemStats.AddCall(context.Request.UserHostAddress)) { logger.Info($"Throttling a request from {context.Request.UserHostAddress}"); return(this.GenerateJsonException(new ExcessiveQueriesException(), HttpStatusCode.TooManyRequests)); } // Technically this is 7.4% over 1 MiB. I'm not going to be pedantic. int maxIterations = 12; int hundredKiB = 100 * 1024; byte[] hundredK = new byte[hundredKiB]; RequestStream requestStream = context.Request.Body; for (int i = 0; i < maxIterations; i++) { // This unfortunately means we're processing the request stream twice. if (requestStream.Read(hundredK, 0, hundredKiB) != hundredKiB) { // The request is under 1 MiB, so continue processing. Reset the stream so deserializing the JSON works. requestStream.Seek(0, SeekOrigin.Begin); return(null); } } logger.Info($"Request from {context.Request.UserHostAddress} to {context.Request.Url} over 1 MiB"); return(this.GenerateJsonException(new ExcessiveNapackException(), HttpStatusCode.BadRequest)); }; StaticConfiguration.DisableErrorTraces = false; pipelines.OnError += (context, exception) => { HttpStatusCode code = HttpStatusCode.InternalServerError; Exception parsedException = exception as Exception; if (parsedException != null) { if (!exceptionStatusCodeMapping.TryGetValue(parsedException.GetType(), out code)) { code = HttpStatusCode.InternalServerError; } } else { parsedException = new Exception("Unable to decode the detected exception!"); } logger.Warn($"Hit a {parsedException.GetType()} exception: {parsedException.Message}"); return(this.GenerateJsonException(parsedException, code)); }; }
public static T DecodeFromSnakeCase <T>(RequestStream ioStream) { var length = (int)ioStream.Length; var data = new byte[length]; ioStream.Read(data, 0, length); return(JsonConvert.DeserializeObject <T>(Encoding.Default.GetString(data), new JsonSerializerSettings { ContractResolver = new SnakeCaseContractResolver() })); }
public SignModule() : base("api/v1") { Post["/checksign"] = _ => { RequestStream requestStream = this.Request.Body; byte[] bytes = new byte[requestStream.Length]; requestStream.Read(bytes, 0, (int)requestStream.Length); string jsonString = Encoding.UTF8.GetString(bytes); PayData payData = new PayData(); payData.FromJson(jsonString); return(payData.CheckSign(key)); }; }
public GossipModule() { Post["/chat/{id}"] = _ => { User user = UserManager.get().getShortUser(_.id); if (user == null) { //HeadResponse response = new HeadResponse(Response.Context.Response); //response.StatusCode = HttpStatusCode.BadRequest; //response.ReasonPhrase = _.id + " is not a valid user at this endpoint."; return(HttpStatusCode.BadRequest); } RequestStream requestStream = Request.Body; int requestLength = (int)requestStream.Length; byte[] requestBytes = new byte[requestLength]; requestStream.Read(requestBytes, 0, requestLength); string requestBody = System.Text.Encoding.Default.GetString(requestBytes); WantMessage want = JsonConvert.DeserializeObject <WantMessage>(requestBody); RumorMessage rumor = JsonConvert.DeserializeObject <RumorMessage>(requestBody); if (VerifyRumor(rumor) && !user.MessageState.ReceivedMessages.Contains(rumor)) { if (!user.Neighbors.Contains(new Peer { Endpoint = rumor.EndPoint })) { user.AddPeer(rumor.EndPoint); } user.MessageState.AddMessage(rumor); } else if (VerifyWant(want)) { if (!user.Neighbors.Contains(new Peer { Endpoint = rumor.EndPoint })) { user.AddPeer(rumor.EndPoint); } List <RumorMessage> missingMessages = user.MessageState.GetMissingRumors(want.WantList); foreach (RumorMessage mm in missingMessages) { mm.EndPoint = user.Endpoint; bool success = Sender.SendMessage(want.EndPoint, mm); if (success) { user.MessageState.AddSentTo(want.EndPoint, mm); } } } else { //HeadResponse response = new HeadResponse(Response.Context.Response); //response.StatusCode = HttpStatusCode.BadRequest; //response.ReasonPhrase = "The following is not a valid request body:\n" + requestBody; return(HttpStatusCode.BadRequest); } // this is the endpoint that external nodes will use // it must implement the following algorithm: /* * t = getMessage(); * if ( isRumor(t) ) { * store(t) * } elsif ( isWant(t) ) { * work_queue = addWorkToQueue(t) * foreach w work_queue { * s = prepareMsg(state, w) * <url> = getUrl(w) * send(<url>, s) * state = update(state, s) * } * } */ return(HttpStatusCode.OK); }; Get["/timer/{milliseconds}"] = _ => { int repeatMilliSeconds = (int)_.milliseconds; GossipLoop.ChangeLoopTime(repeatMilliSeconds); return(null); }; }