private Response CreateStreamedJsonResponse(dynamic model)
 {
     return(new Response
     {
         ContentType = "application/json",
         StatusCode = HttpStatusCode.OK,
         Contents = stream =>
         {
             // Serialize the model to the stream
             using (var streamWrapper = new UnclosableStreamWrapper(stream))
             {
                 using (var streamWriter = new StreamWriter(streamWrapper))
                 {
                     using (var jsonWriter = new JsonTextWriter(streamWriter))
                     {
                         var settings = new JsonSerializerSettings
                         {
                             NullValueHandling = NullValueHandling.Ignore
                         };
                         var serializer = JsonSerializer.Create(settings);
                         serializer.Serialize(jsonWriter, model);
                     }
                 }
             }
         }
     });
 }
Пример #2
0
        public void Should_return_action_value_as_response_with_content_set_as_value()
        {
            // Given
            var module = new ConfigurableNancyModule(with =>
            {
                with.Get("/action", (x, m) =>
                {
                    Action <Stream> result = stream =>
                    {
                        var wrapper = new UnclosableStreamWrapper(stream);
                        using (var writer = new StreamWriter(wrapper))
                        {
                            writer.Write("Hiya Nancy!");
                        }
                    };

                    return(result);
                });
            });

            var browser = new Browser(with =>
            {
                with.Module(module);
            });

            // When
            var response = browser.Get("/action");

            // Then
            Assert.Equal("Hiya Nancy!", response.Body.AsString());
        }
Пример #3
0
        private static MemoryStream GetContentStream(Response response)
        {
            var contentsStream = new MemoryStream();

            var unclosableStream = new UnclosableStreamWrapper(contentsStream);

            response.Contents.Invoke(unclosableStream);
            contentsStream.Position = 0;

            return(contentsStream);
        }
Пример #4
0
        private Action <Stream> GetXmlContents(IEnumerable <BlogPost> model)
        {
            var items = new List <SyndicationItem>();

            foreach (var post in model)
            {
                // Replace all relative urls with full urls.
                var contentHtml = Regex.Replace(post.Content, UrlRegex, m => siteUrl.TrimEnd('/') + "/" + m.Value.TrimStart('/'));
                var excerptHtml = Regex.Replace(post.Summary, UrlRegex, m => siteUrl.TrimEnd('/') + "/" + m.Value.TrimStart('/'));

                var item = new SyndicationItem(
                    post.Title,
                    contentHtml,
                    new Uri(siteUrl + post.Localink)
                    )
                {
                    Id = siteUrl + post.Localink,
                    LastUpdatedTime = post.PublishedDate.ToUniversalTime(),
                    PublishDate     = post.PublishedDate.ToUniversalTime(),
                    Content         = new TextSyndicationContent(contentHtml, TextSyndicationContentKind.Html),
                    Summary         = new TextSyndicationContent(excerptHtml, TextSyndicationContentKind.Html),
                };
                item.Authors.Add(new SyndicationPerson(post.AuthorEmail, post.Author, string.Empty));
                item.Categories.Add(new SyndicationCategory("nancy"));

                items.Add(item);
            }

            var feed = new SyndicationFeed(
                RssTitle,
                RssTitle, /* Using Title also as Description */
                new Uri(siteUrl + feedfileName),
                items);

            var formatter = new Rss20FeedFormatter(feed);

            return(stream =>
            {
                var encoding = new UTF8Encoding(false);
                var streamWrapper = new UnclosableStreamWrapper(stream);

                using (var writer = new XmlTextWriter(streamWrapper, encoding))
                {
                    formatter.WriteTo(writer);
                }
            });
        }
Пример #5
0
 private static Action <Stream> GetEncodedContents(TModel model, IMessageEncoder encoder)
 {
     return(outputStream =>
     {
         try
         {
             using (var stream = new UnclosableStreamWrapper(outputStream))
             {
                 var buffer = encoder.EncodeMessage(model);
                 stream.Write(buffer, 0, buffer.Length);
             }
         }
         catch (Exception ex)
         {
             _log.Error(ex.Message, ex);
         }
     });
 }
Пример #6
0
        private Action <Stream> GetXmlContents(IEnumerable <Post> model)
        {
            var items = new List <SyndicationItem>();

            foreach (var post in model)
            {
                // Replace all relative urls with full urls.
                var newHtml = Regex.Replace(post.Content, UrlRegex, m => siteUrl.TrimEnd('/') + "/" + m.Value.TrimStart('/'));

                var item = new SyndicationItem(
                    post.Title,
                    newHtml,
                    new Uri(siteUrl + post.Url)
                    )
                {
                    Id = siteUrl + post.Url,
                    LastUpdatedTime = post.Date.ToUniversalTime(),
                    PublishDate     = post.Date.ToUniversalTime(),
                    Summary         = new TextSyndicationContent(post.ContentExcerpt, TextSyndicationContentKind.Html)
                };

                items.Add(item);
            }

            var feed = new SyndicationFeed(
                RssTitle,
                RssTitle, /* Using Title also as Description */
                new Uri(siteUrl + "/" + feedfileName),
                items);

            var formatter = new Rss20FeedFormatter(feed);

            return(stream =>
            {
                var encoding = new UTF8Encoding(false);
                var streamWrapper = new UnclosableStreamWrapper(stream);

                using (var writer = new XmlTextWriter(streamWrapper, encoding))
                {
                    formatter.WriteTo(writer);
                }
            });
        }
Пример #7
0
        private Action <Stream> GetXmlContents(IEnumerable <Post> model)
        {
            var items = new List <SyndicationItem>();

            foreach (Post post in model)
            {
                var item = new SyndicationItem(
                    title: post.Title,
                    content: post.Content,
                    itemAlternateLink: new Uri(siteUrl + post.Url),
                    id: siteUrl + post.Url,
                    lastUpdatedTime: post.Date.ToUniversalTime()
                    );
                item.PublishDate = post.Date.ToUniversalTime();
                item.Summary     = new TextSyndicationContent(post.ContentExcerpt, TextSyndicationContentKind.Html);
                items.Add(item);
            }

            var feed = new SyndicationFeed(
                this.RssTitle,
                this.RssTitle, /* Using Title also as Description */
                new Uri(siteUrl + "/" + feedfileName),
                items);

            var formatter = new Rss20FeedFormatter(feed);

            return(stream =>
            {
                var encoding =
                    new UTF8Encoding(false);

                var streamWrapper =
                    new UnclosableStreamWrapper(stream);

                using (var writer = new XmlTextWriter(streamWrapper, encoding))
                {
                    formatter.WriteTo(writer);
                }
            });
        }
Пример #8
0
        public unsafe void Run(Action <Stream> action, ResultsProcessor iterationCallback)
        {
            if (action is null)
            {
                throw new ArgumentNullException(nameof(action));
            }

            Logger.Write("Starting fuzzer client");

            using (var stdin = Console.OpenStandardInput())
                using (var stream = new UnclosableStreamWrapper(stdin))
                {
                    if (_shmid < 0)
                    {
                        Logger.Write("No afl-fuzz detected, dry run");
                        using (var memory = new UnclosableStreamWrapper(new MemoryStream()))
                        {
                            stream.CopyTo(memory);
                            memory.Seek(0, SeekOrigin.Begin);
                            action(memory);
                        }
                        return;
                    }

                    var ctrlSocket = new ControlSocket.Client();
                    ctrlSocket.Connect(_hostName, _controlPort);

                    Logger.Write("Control channel established");

                    var initial = true;

                    using (var r = new BinaryReader(new AnonymousPipeClientStream(PipeDirection.In, "198")))
                        using (var w = new BinaryWriter(new AnonymousPipeClientStream(PipeDirection.Out, "199")))
                        {
                            w.Write(0);

                            Logger.Write("Afl-fuzz greeting sent");

                            for (int nRun = 1; ; nRun++)
                            {
                                Logger.Write($"Starting test run {nRun}");

                                var pid = ctrlSocket.StartTest(_collectLocations);
                                if (pid == null)
                                {
                                    break;
                                }

                                Logger.Write($"Agent reports ready on {pid}");

                                var alfReq = r.ReadInt32();
                                Logger.Write($"Afz-fuzz ping request: {alfReq}");

                                w.Write(pid.Value);
                                Logger.Write("Afz-fuzz ping replied");

                                Fuzzer.Fault result;

                                using (var memory = new UnclosableStreamWrapper(new MemoryStream()))
                                {
                                    stream.CopyTo(memory);

                                    while (true)
                                    {
                                        memory.Seek(0, SeekOrigin.Begin);

                                        Logger.Write($"Executing test {nRun}");
                                        result = ExecuteAction(action, memory);
                                        if (initial)
                                        {
                                            // initial run
                                            // discard results and retry the test once
                                            Logger.Write("Re-executing initial test");

                                            initial = false;

                                            ctrlSocket.GetStatus(out var c, out var l);

                                            ctrlSocket.StartTest(_collectLocations);
                                            memory.Seek(0, SeekOrigin.Begin);
                                            result = ExecuteAction(action, memory);
                                        }

                                        Logger.Write($"Test execution result is {result}, requesting remote results");

                                        var res = ctrlSocket.GetStatus(out var coverage, out var locations).Value;

                                        if (res != (uint)Fuzzer.Fault.None)
                                        {
                                            result = (Fuzzer.Fault)res;
                                        }

                                        if (!iterationCallback(nRun, locations))
                                        {
                                            Logger.Write($"Test results were not accepted, repeating run {nRun}");
                                            ctrlSocket.StartTest(_collectLocations);
                                            continue;
                                        }

                                        if (coverage.Length == Fuzzer.MapSize)
                                        {
                                            Logger.Write($"Processing remote results");
                                            using (var shmaddr = shmat(_shmid, IntPtr.Zero, 0))
                                            {
                                                byte *sharedMem = (byte *)shmaddr.DangerousGetHandle();
                                                for (int i = 0; i < coverage.Length; ++i)
                                                {
                                                    // simulate instrumentation
                                                    sharedMem[i] += coverage[i];
                                                }
                                            }
                                        }
                                        else
                                        {
                                            throw new InvalidDataException("covarage bitmap is invalid");
                                        }

                                        break;
                                    }
                                }

                                Logger.Write($"Reporting run result to afl-fuzz: {result}");
                                w.Write((uint)result);
                            }
                        }
                }
        }
Пример #9
0
        private Action <Stream> GetXmlContents(IEnumerable <Post> model)
        {
            var items = new List <SyndicationItem>();

            foreach (var post in model)
            {
                // Replace all relative urls with full urls.
                var contentHtml = Regex.Replace(post.Content, UrlRegex, m => siteUrl.TrimEnd('/') + "/" + m.Value.TrimStart('/'));
                var excerptHtml = Regex.Replace(post.ContentExcerpt, UrlRegex, m => siteUrl.TrimEnd('/') + "/" + m.Value.TrimStart('/'));

                var item = new SyndicationItem(
                    post.Title,
                    contentHtml,
                    new Uri(siteUrl + post.Url)
                    )
                {
                    Id = siteUrl + post.Url,
                    LastUpdatedTime = post.Date.ToUniversalTime(),
                    PublishDate     = post.Date.ToUniversalTime(),
                    Content         = new TextSyndicationContent(contentHtml, TextSyndicationContentKind.Html),
                    Summary         = new TextSyndicationContent(excerptHtml, TextSyndicationContentKind.Html),
                };

                items.Add(item);
            }

            var feed = new SyndicationFeed(
                AtomTitle,
                AtomTitle, /* Using Title also as Description */
                new Uri(siteUrl + "/" + feedfileName),
                items)
            {
                Id = siteUrl + "/",
                LastUpdatedTime = new DateTimeOffset(DateTime.Now),
                Generator       = "Sandra.Snow Atom Generator"
            };

            feed.Authors.Add(new SyndicationPerson(authorEmail, author, siteUrl));

            var link = new SyndicationLink(new Uri(siteUrl + "/" + feedfileName))
            {
                RelationshipType = "self",
                MediaType        = "text/html",
                Title            = AtomTitle
            };

            feed.Links.Add(link);


            var formatter = new Atom10FeedFormatter(feed);

            return(stream =>
            {
                var encoding = new UTF8Encoding(false);
                var streamWrapper = new UnclosableStreamWrapper(stream);

                using (var writer = new XmlTextWriter(streamWrapper, encoding))
                {
                    formatter.WriteTo(writer);
                }
            });
        }