Ejemplo n.º 1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="stream">Stream containing the content</param>
        /// <param name="contentType">Content type header</param>
        /// <param name="encoding">Stream encoding</param>
        /// <returns>Collection with all parameters.</returns>
        /// <exception cref="FormatException">Body format is invalid for the specified content type.</exception>
        /// <exception cref="InternalServerException">Failed to read all bytes from body stream.</exception>
        public DecodedData Decode(Stream stream, ContentTypeHeader contentType, Encoding encoding)
        {
            if (stream == null || stream.Length == 0)
            {
                return(null);
            }

            if (encoding == null)
            {
                encoding = Encoding.UTF8;
            }

            try
            {
                var content   = new byte[stream.Length];
                int bytesRead = stream.Read(content, 0, content.Length);
                if (bytesRead != content.Length)
                {
                    throw new InternalServerException("Failed to read all bytes from body stream.");
                }

                return(new DecodedData {
                    Parameters = ParameterParser.Parse(new BufferReader(content, encoding))
                });
            }
            catch (ArgumentException err)
            {
                throw new FormatException(err.Message, err);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Decode body stream
        /// </summary>
        /// <param name="stream">Stream containing the content</param>
        /// <param name="contentType">Content type header</param>
        /// <param name="encoding">Stream encoding</param>
        /// <returns>Decoded data.</returns>
        /// <exception cref="FormatException">Body format is invalid for the specified content type.</exception>
        /// <exception cref="InternalServerException">Something unexpected failed.</exception>
        public DecodedData Decode(Stream stream, ContentTypeHeader contentType, Encoding encoding)
        {
            IBodyDecoder decoder;

            return(!_decoders.TryGetValue(contentType.Value, out decoder)
                       ? null
                       : decoder.Decode(stream, contentType, encoding));
        }
Ejemplo n.º 3
0
 public void Shall_parse_header()
 {
     Assert.That(ContentTypeHeader.TryParse("application/sdp; foo=bar", out ContentTypeHeader header), Is.True);
     Assert.That(header.Type, Is.EqualTo("application"));
     Assert.That(header.SubType, Is.EqualTo("sdp"));
     Assert.That(header.Parameters[0].Name, Is.EqualTo("foo"));
     Assert.That(header.Parameters[0].Value, Is.EqualTo("bar"));
 }
Ejemplo n.º 4
0
        public void WhenConstructedSetsTheValueProperty()
        {
            string expectedValue = "application/json";

            var header = new ContentTypeHeader(expectedValue);

            header.Value.Should().Be(expectedValue);
        }
Ejemplo n.º 5
0
        public void contenttype___equals_overload_not_string_or_equivelent_sccess()
        {
            ContentTypeHeader header1 = "text/json";
            var other = 2;

            var equals = header1.Equals(other);

            equals.Should().BeFalse();
        }
Ejemplo n.º 6
0
        public void contenttype___equals_overload_null_sccess()
        {
            ContentTypeHeader header1 = "text/json";
            ContentTypeHeader header2 = null;

            var equals = header1.Equals(header2);

            equals.Should().BeFalse();
        }
Ejemplo n.º 7
0
        public void contenttype___notequals_operator_header_success(string contentType)
        {
            var contentType1 = new ContentTypeHeader(contentType);
            var contentType2 = new ContentTypeHeader("text/json; charset=UTF-8; boundary=--iuhfisdhfiuushdfhisudhfhsiduhf=sdhf=");

            var equals = contentType1 != contentType2;

            equals.Should().Be(true);
        }
Ejemplo n.º 8
0
        internal static MimePart CreateBodyPart(string type, string charsetName)
        {
            MimePart          mimePart          = new MimePart();
            ContentTypeHeader contentTypeHeader = new ContentTypeHeader(type);
            MimeParameter     newChild          = new MimeParameter("charset", charsetName);

            contentTypeHeader.AppendChild(newChild);
            mimePart.Headers.AppendChild(contentTypeHeader);
            return(mimePart);
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Response"/> class.
 /// </summary>
 /// <param name="context">Context that the response will be sent through.</param>
 /// <param name="request">Request that the response is for.</param>
 /// <exception cref="FormatException">Version must start with 'HTTP/'</exception>
 public Response(IHttpContext context, IRequest request)
 {
     _context    = context;
     HttpVersion = request.HttpVersion;
     Reason      = "Made by Jonas Gauffin";
     Status      = HttpStatusCode.OK;
     ContentType = new ContentTypeHeader("text/html");
     Encoding    = request.Encoding;
     _headers    = CreateHeaderCollection();
 }
Ejemplo n.º 10
0
        public void contenttype___gethashcode_success()
        {
            ContentTypeHeader header = "text/json";

            header.Should().NotBeNull();

            var hashCode = header.GetHashCode();

            hashCode.Should().NotBe(0);
        }
Ejemplo n.º 11
0
        public void contenttype___assignment_returns_default_for_null_or_whitespace(string value)
        {
            ContentTypeHeader header = value;

            header.Should().NotBeNull();
            header.Boundary.Should().BeEmpty();
            header.Charset.Should().BeEmpty();
            header.Value.Should().Be(value);
            header.MediaType.Should().BeEmpty();
        }
Ejemplo n.º 12
0
        public void contenttype___notequals_operator_string_success(string contentType)
        {
            var header = new ContentTypeHeader(contentType);

            var equals = header != "text/json; charset=UTF-8; boundary=--iuhfisdhfiuushdfhisudhfhsiduhf=sdhf=";

            equals.Should().Be(true);

            equals = "text/json; charset=UTF-8; boundary=--iuhfisdhfiuushdfhisudhfhsiduhf=sdhf=" != header;
            equals.Should().Be(true);
        }
Ejemplo n.º 13
0
        public void Shall_clone_header()
        {
            ContentTypeHeader original = ContentTypeHeader.Parse("application/sdp");
            ContentTypeHeader cloned   = original.DeepClone();

            original.Type    = "multipart";
            original.SubType = "alternative";
            original.Parameters.Add(new GenericParameter("foo", "bar"));

            Assert.That(cloned.ToString(), Is.EqualTo("application/sdp"));
            Assert.That(original.ToString(), Is.EqualTo("multipart/alternative; foo=bar"));
        }
Ejemplo n.º 14
0
        public void contenttype___equals_override_success(string contentType)
        {
            string value = "application/json; charset=UTF-8; boundary=--iuhfisdhfiuushdfhisudhfhsiduhf=sdhf=";

            var header = new ContentTypeHeader(contentType);

            var equals = header.Equals(value);

            equals.Should().Be(true);

            equals = header.Equals(new ContentTypeHeader(value));
            equals.Should().Be(true);
        }
Ejemplo n.º 15
0
        public void contenttype___charset_ctor_has_correct_charset(string contentType, string charset)
        {
            var header = new ContentTypeHeader($"{contentType}{charset}");

            header.Should().NotBeNull();
            header.Value.Should().Be($"{contentType}{charset}");
            header.MediaType.Should().Be("application/json");
            header.Type.Should().Be("application");
            header.SubType.Should().Be("json");

            header.Boundary.Should().BeEmpty();
            header.Charset.Should().Be("utf-8");
        }
Ejemplo n.º 16
0
        public void FormTest()
        {
            FileStream       stream  = new FileStream("C:\\temp\\bodymime.mime", FileMode.Open);
            MultiPartDecoder decoder = new MultiPartDecoder();
            var header = new ContentTypeHeader("multipart/form-data");

            header.Parameters.Add("boundary", "----WebKitFormBoundaryQsuJaNmu3FVqrYwp");
            var data = decoder.Decode(stream, header, Encoding.Default);

            if (data.Files.Count > 0)
            {
            }
        }
Ejemplo n.º 17
0
        public void contenttype___boundaryand_charset_assignment_is_correct(string contentType, string charset, string boundary, string expectedBoundary)
        {
            ContentTypeHeader header = $"{contentType}{charset}{boundary}";

            header.Should().NotBeNull();
            header.Value.Should().Be($"{contentType}{charset}{boundary}");
            header.MediaType.Should().Be("application/json");
            header.Type.Should().Be("application");
            header.SubType.Should().Be("json");

            header.Charset.Should().Be("utf-8");
            header.Boundary.Should().Be(expectedBoundary);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Decode body stream
        /// </summary>
        /// <param name="stream">Stream containing the content</param>
        /// <param name="contentType">Content type header</param>
        /// <param name="encoding">Stream encoding</param>
        /// <returns>Decoded data.</returns>
        /// <exception cref="FormatException">Body format is invalid for the specified content type.</exception>
        /// <exception cref="InternalServerException">Something unexpected failed.</exception>
        public DecodedData Decode(Stream stream, ContentTypeHeader contentType, Encoding encoding)
        {
            IBodyDecoder decoder;

            if (contentType == null || contentType.Value == "")
            {
                contentType = new ContentTypeHeader("application/octet-stream");
            }

            return(!_decoders.TryGetValue(contentType.Value, out decoder)
                       ? null
                       : decoder.Decode(stream, contentType, encoding));
        }
Ejemplo n.º 19
0
        private static bool IsMessageOpaqueSigned(ICoreItem coreItem, StreamAttachment attachment)
        {
            Util.ThrowOnNullArgument(coreItem, "coreItem");
            string valueOrDefault = coreItem.PropertyBag.GetValueOrDefault <string>(InternalSchema.ItemClass, string.Empty);

            if (!ObjectClass.IsSmime(valueOrDefault))
            {
                return(false);
            }
            coreItem.PropertyBag.Load(new PropertyDefinition[]
            {
                InternalSchema.NamedContentType
            });
            string valueOrDefault2 = coreItem.PropertyBag.GetValueOrDefault <string>(InternalSchema.NamedContentType);

            if (valueOrDefault2 != null)
            {
                byte[]            bytes  = CTSGlobals.AsciiEncoding.GetBytes(valueOrDefault2);
                ContentTypeHeader header = (ContentTypeHeader)Header.Create(HeaderId.ContentType);
                MimeInternalHelpers.SetHeaderRawValue(header, bytes);
                string headerParameter = MimeHelpers.GetHeaderParameter(header, "smime-type", 100);
                if (headerParameter == null || (!ConvertUtils.MimeStringEquals(headerParameter, "signed-data") && !ConvertUtils.MimeStringEquals(headerParameter, "certs-only")))
                {
                    return(false);
                }
            }
            string contentType = attachment.ContentType;

            if (string.Compare(contentType, "application/pkcs7-mime", StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(contentType, "application/x-pkcs7-mime", StringComparison.OrdinalIgnoreCase) == 0)
            {
                return(true);
            }
            if (string.Compare(contentType, "application/octet-stream", StringComparison.OrdinalIgnoreCase) == 0)
            {
                string fileName = attachment.FileName;
                string strA     = string.Empty;
                if (fileName != null)
                {
                    string[] array = fileName.Split(new char[]
                    {
                        '.'
                    });
                    if (array.Length > 0)
                    {
                        strA = array[array.Length - 1];
                    }
                }
                return(string.Compare(strA, "p7m", StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(strA, "p7c", StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(strA, "p7s", StringComparison.OrdinalIgnoreCase) == 0);
            }
            return(false);
        }
Ejemplo n.º 20
0
        public void contenttype___assignment_basic_returns_type_and_subtype(string type, string subtype)
        {
            ContentTypeHeader header = $"{type}/{subtype}";

            header.Should().NotBeNull();
            header.Value.Should().Be($"{type}/{subtype}");
            header.Boundary.Should().BeEmpty();
            header.Charset.Should().BeEmpty();
            header.MediaType.Should().Be("application/json");
            header.Type.Should().Be("application");
            header.SubType.Should().Be("json");
            header.Charset.Should().BeEmpty();
            header.Boundary.Should().BeEmpty();
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Response"/> class.
        /// </summary>
        /// <param name="version">HTTP Version.</param>
        /// <param name="code">HTTP status code.</param>
        /// <param name="reason">Why the status code was selected.</param>
        /// <exception cref="FormatException">Version must start with 'HTTP/'</exception>
        public Response(string version, HttpStatusCode code, string reason)
        {
            if (!version.StartsWith("HTTP/"))
            {
                throw new FormatException("Version must start with 'HTTP/'");
            }

            Status      = code;
            Reason      = reason;
            HttpVersion = version;
            ContentType = new ContentTypeHeader("text/html");
            Encoding    = Encoding.UTF8;
            _headers    = CreateHeaderCollection();
        }
Ejemplo n.º 22
0
        public void Shall_stringify_body()
        {
            var body = new SipBody
            {
                Data        = "abc",
                ContentType = ContentTypeHeader.Parse("text/plain"),
                Headers     =
                {
                    new GenericHeader("foo", "bar")
                }
            };

            Assert.That(body.ToString(), Is.EqualTo("content-type: text/plain\r\nFoo: bar\r\n\r\nabc"));
        }
Ejemplo n.º 23
0
        public void Shall_stringify_header()
        {
            var header = new ContentTypeHeader
            {
                Type       = "application",
                SubType    = "sdp",
                Parameters =
                {
                    new GenericParameter("foo", "bar")
                }
            };

            Assert.That(header.ToString(), Is.EqualTo("application/sdp; foo=bar"));
        }
Ejemplo n.º 24
0
        public void SendString(IHttpContext context, string str)
        {
            byte[] buf = Encoding.UTF8.GetBytes(str);
            if (context.Response.Headers["Content-Type"] != null)
            {
            }
            Headers.ContentTypeHeader head = new ContentTypeHeader("Content-Type");
            head.Value = "text/html; charset=utf-8";
            context.Response.ContentType = head;

            context.Response.ContentLength.Value = buf.Length;
            //context.Response.Add("Pragma",new PragmaHeader());
            //context.Response.Add("Expires",new ExpiresHeader());
            context.Response.Body.Write(buf, 0, buf.Length);

            Send(context, context.Response);
        }
Ejemplo n.º 25
0
 private static void Analyse(ContentTypeHeader typeHeader, out bool embedded, out bool multipart, out bool useQP)
 {
     embedded  = false;
     multipart = false;
     useQP     = true;
     if (typeHeader != null)
     {
         multipart = typeHeader.IsMultipart;
         if (!multipart)
         {
             embedded = typeHeader.IsEmbeddedMessage;
             if (!embedded)
             {
                 useQP = (typeHeader.MediaType == "text");
             }
         }
     }
 }
Ejemplo n.º 26
0
        /// <summary>Gets the content type formatter.</summary>
        /// <param name="mediaHeader">The media header.</param>
        /// <param name="objType">Type of the object.</param>
        /// <param name="formatterType">Type of the formatter.</param>
        /// <param name="readableFormatters">The overriding formatters.</param>
        /// <param name="readableMediaTypes">The readable media types.</param>
        /// <returns></returns>
        public virtual Task <IDeepSleepMediaSerializer> GetContentTypeFormatter(
            ContentTypeHeader mediaHeader,
            Type objType,
            out string formatterType,
            IList <IDeepSleepMediaSerializer> readableFormatters = null,
            IList <string> readableMediaTypes = null)
        {
            var formatter = this.Get(
                contentType: $"{mediaHeader.Type}/{mediaHeader.SubType}",
                objType: objType,
                parameters: mediaHeader.ParameterString(),
                forRead: true,
                overridingFormatters: readableFormatters,
                overridingMediaTypes: readableMediaTypes,
                formatterType: out formatterType);

            return(Task.FromResult(formatter));
        }
Ejemplo n.º 27
0
            public override bool FilterHeaderList(HeaderList headerList, Stream stream)
            {
                Header header = headerList.FindFirst(HeaderId.ContentTransferEncoding);

                if (header != null)
                {
                    ContentTransferEncoding encodingType = MimePart.GetEncodingType(header.FirstRawToken);
                    if (encodingType == ContentTransferEncoding.EightBit || encodingType == ContentTransferEncoding.Binary)
                    {
                        ContentTypeHeader typeHeader = headerList.FindFirst(HeaderId.ContentType) as ContentTypeHeader;
                        bool flag;
                        bool flag2;
                        EightToSevenBitConverter.Analyse(typeHeader, out this.embedded, out flag, out flag2);
                        for (MimeNode mimeNode = headerList.FirstChild; mimeNode != null; mimeNode = mimeNode.NextSibling)
                        {
                            if (HeaderId.ContentTransferEncoding == (mimeNode as Header).HeaderId)
                            {
                                if (flag || this.embedded)
                                {
                                    this.encoder = null;
                                }
                                else if (flag2)
                                {
                                    stream.Write(EightToSevenBitConverter.CteQP, 0, EightToSevenBitConverter.CteQP.Length);
                                    this.encoder = new QPEncoder();
                                }
                                else
                                {
                                    stream.Write(EightToSevenBitConverter.CteBase64, 0, EightToSevenBitConverter.CteBase64.Length);
                                    this.encoder = new Base64Encoder();
                                }
                            }
                            else
                            {
                                mimeNode.WriteTo(stream);
                            }
                        }
                        stream.Write(MimeString.CrLf, 0, MimeString.CrLf.Length);
                        return(true);
                    }
                }
                return(false);
            }
Ejemplo n.º 28
0
        public void SendJson(IHttpContext context, string jsonString)
        {
            byte[] buf = Encoding.UTF8.GetBytes(jsonString);
            if (context.Response.Headers["Content-Type"] != null)
            {
            }
            Headers.ContentTypeHeader head = new ContentTypeHeader("Content-Type");
            head.Value = "text/json; charset=utf-8";
            context.Response.ContentType         = head;
            context.Response.ContentLength.Value = buf.Length;
            //context.Response.Add("Pragma", new PragmaHeader());
            //context.Response.Add("Expires", new ExpiresHeader());

            //using (System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(context.Response.Body, System.IO.Compression.CompressionMode.Compress,true)) {
            //    gzip.Write(buf, 0, buf.Length);
            //    gzip.Flush();
            //}

            context.Response.Body.Write(buf, 0, buf.Length);
            Send(context, context.Response);
        }
Ejemplo n.º 29
0
 internal static Header Create(string name, HeaderId headerId)
 {
     if (headerId < HeaderId.Unknown || headerId > (HeaderId) MimeData.nameIndex.Length)
         throw new System.ArgumentException(Resources.Strings.InvalidHeaderId, nameof(headerId));
     if (headerId == HeaderId.Unknown)
         throw new System.ArgumentException(Resources.Strings.CannotDetermineHeaderNameFromId, nameof(headerId));
     Header header;
     switch (MimeData.headerNames[(int) MimeData.nameIndex[(int) headerId]].headerType) {
         case HeaderType.AsciiText:
             header = new AsciiTextHeader(MimeData.headerNames[(int) MimeData.nameIndex[(int) headerId]].name, headerId);
             break;
         case HeaderType.Date:
             header = new DateHeader(MimeData.headerNames[(int) MimeData.nameIndex[(int) headerId]].name, headerId);
             break;
         case HeaderType.Received:
             header = new ReceivedHeader();
             break;
         case HeaderType.ContentType:
             header = new ContentTypeHeader();
             break;
         case HeaderType.ContentDisposition:
             header = new ContentDispositionHeader();
             break;
         case HeaderType.Address:
             header = new AddressHeader(MimeData.headerNames[(int) MimeData.nameIndex[(int) headerId]].name, headerId);
             break;
         default:
             header = new TextHeader(MimeData.headerNames[(int) MimeData.nameIndex[(int) headerId]].name, headerId);
             break;
     }
     if (!string.IsNullOrEmpty(name) && !header.MatchName(name))
         throw new System.ArgumentException("name");
     return header;
 }
Ejemplo n.º 30
0
        /// <summary>
        /// Decode body stream
        /// </summary>
        /// <param name="stream">Stream containing the content</param>
        /// <param name="contentType">Content type header</param>
        /// <param name="encoding">Stream encoding</param>
        /// <returns>Decoded data.</returns>
        /// <exception cref="FormatException">Body format is invalid for the specified content type.</exception>
        /// <exception cref="InternalServerException">Something unexpected failed.</exception>
        /// <exception cref="ArgumentNullException"><c>stream</c> is <c>null</c>.</exception>
        public DecodedData Decode(Stream stream, ContentTypeHeader contentType, Encoding encoding)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            if (contentType == null)
            {
                throw new ArgumentNullException("contentType");
            }
            if (encoding == null)
            {
                throw new ArgumentNullException("encoding");
            }

            //multipart/form-data, boundary=AaB03x
            string boundry = contentType.Parameters["boundary"];

            if (boundry == null)
            {
                throw new FormatException("Missing boundary in content type.");
            }

            var multipart = new HttpMultipart(stream, boundry, encoding);

            var form = new DecodedData();

            /*
             * FileStream stream1 = new FileStream("C:\\temp\\mimebody.tmp", FileMode.Create);
             * byte[] bytes = new byte[stream.Length];
             * stream.Read(bytes, 0, bytes.Length);
             * stream1.Write(bytes, 0, bytes.Length);
             * stream1.Flush();
             * stream1.Close();
             */

            HttpMultipart.Element element;
            while ((element = multipart.ReadNextElement()) != null)
            {
                if (string.IsNullOrEmpty(element.Name))
                {
                    throw new FormatException("Error parsing request. Missing value name.\nElement: " + element);
                }

                if (!string.IsNullOrEmpty(element.Filename))
                {
                    if (string.IsNullOrEmpty(element.ContentType))
                    {
                        throw new FormatException("Error parsing request. Value '" + element.Name +
                                                  "' lacks a content type.");
                    }

                    // Read the file data
                    var buffer = new byte[element.Length];
                    stream.Seek(element.Start, SeekOrigin.Begin);
                    stream.Read(buffer, 0, (int)element.Length);

                    // Generate a filename
                    string originalFileName = element.Filename;
                    //string internetCache = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);
                    string internetCache = Utils.Instance.InternetCacheDir;

                    // if the internet path doesn't exist, assume mono and /var/tmp
                    string path = string.IsNullOrEmpty(internetCache)
                                      ? Path.Combine("var", "tmp")
                                      : Path.Combine(internetCache.Replace("\\\\", "\\"), "tmp");

                    element.Filename = Path.Combine(path, Math.Abs(element.Filename.GetHashCode()) + ".tmp");

                    // If the file exists generate a new filename
                    while (File.Exists(element.Filename))
                    {
                        element.Filename = Path.Combine(path, Math.Abs(element.Filename.GetHashCode() + 1) + ".tmp");
                    }

                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }

                    File.WriteAllBytes(element.Filename, buffer);

                    var file = new HttpFile
                    {
                        Name             = element.Name,
                        OriginalFileName = originalFileName,
                        ContentType      = element.ContentType,
                        TempFileName     = element.Filename
                    };
                    form.Files.Add(file);
                }
                else
                {
                    var buffer = new byte[element.Length];
                    stream.Seek(element.Start, SeekOrigin.Begin);
                    stream.Read(buffer, 0, (int)element.Length);

                    form.Parameters.Add(HttpUtility.UrlDecode(element.Name), encoding.GetString(buffer));
                }
            }

            return(form);
        }
Ejemplo n.º 31
0
        public void Shall_byteify_request()
        {
            var request = new SipRequest
            {
                Version     = "SIP/2.0",
                Method      = "INVITE",
                RequestUri  = SipUri.Parse("sip:[email protected]"),
                From        = NameAddressHeader.Parse("John Smith <sip:[email protected]>"),
                To          = NameAddressHeader.Parse("Joe Shmoe <sip:[email protected]>"),
                CallId      = CallIdHeader.Parse("*****@*****.**"),
                CSeq        = CSeqHeader.Parse("1 INVITE"),
                ContentType = ContentTypeHeader.Parse("text/plain"),
                MimeVersion = ContentLengthHeader.Parse("1.0")
            };

            request.Vias.Add(ViaHeader.Parse("SIP/2.0/UDP foo.bar.com"));
            request.RecordRoutes.Add(NameAddressHeader.Parse("Tommy Atkins <sip:[email protected]>"));
            request.Routes.Add(NameAddressHeader.Parse("John Doe <sip:[email protected]>"));
            request.Contacts.Add(NameAddressHeader.Parse("Prisoner X <sip:[email protected]>"));
            request.Authorizations.Add(AuthorizationHeader.Parse("Digest username=\"Alice\""));
            request.WwwAuthenticates.Add(WwwAuthenticateHeader.Parse("Digest realm=\"abc.com\""));
            request.ProxyAuthenticates.Add(WwwAuthenticateHeader.Parse("Digest realm=\"xyz.com\""));
            request.ProxyAuthorizations.Add(AuthorizationHeader.Parse("Digest username=\"Bob\""));
            request.CallInfos.Add(CallInfoHeader.Parse("<http://www.abc.com/photo.png>;purpose=icon"));
            request.Allows.Add(ContentLengthHeader.Parse("INVITE, ACK, BYE"));
            request.ContentEncodings.Add(ContentLengthHeader.Parse("deflate"));
            request.AlertInfos.Add(CallInfoHeader.Parse("<http://www.abc.com/sound.wav>"));
            request.ErrorInfos.Add(CallInfoHeader.Parse("<sip:[email protected]>"));
            request.Accepts.Add(ContentTypeHeader.Parse("application/sdp"));
            request.AcceptEncodings.Add(AcceptEncodingHeader.Parse("gzip"));
            request.AcceptLanguages.Add(AcceptEncodingHeader.Parse("en"));
            request.AuthenticationInfos.Add(AuthenticationInfoHeader.Parse("nextnonce=\"abc\""));
            request.ProxyAuthenticationInfos.Add(AuthenticationInfoHeader.Parse("nextnonce=\"def\""));
            request.OtherHeaders.Add(new GenericHeader("P-Asserted-Identity", "sip:[email protected]"));
            request.Bodies.Add(SipBody.Parse("Hello world!"));

            var buffer  = new byte[ushort.MaxValue];
            var success = request.TryCopyTo(buffer, 0, out int length);

            Assert.That(success, Is.True);

            var request2 = SipMessage.Parse(new ArraySegment <byte>(buffer, 0, length));

            Assert.That(request2.ToString(), Is.EqualTo(
                            "INVITE sip:[email protected] SIP/2.0\r\n" +
                            "Via: SIP/2.0/UDP foo.bar.com\r\n" +
                            "Record-Route: Tommy Atkins <sip:[email protected]>\r\n" +
                            "Route: John Doe <sip:[email protected]>\r\n" +
                            "From: John Smith <sip:[email protected]>\r\n" +
                            "To: Joe Shmoe <sip:[email protected]>\r\n" +
                            "Call-ID: [email protected]\r\n" +
                            "CSeq: 1 INVITE\r\n" +
                            "Contact: Prisoner X <sip:[email protected]>\r\n" +
                            "Authorization: Digest username=\"Alice\"\r\n" +
                            "WWW-Authenticate: Digest realm=\"abc.com\"\r\n" +
                            "Proxy-Authenticate: Digest realm=\"xyz.com\"\r\n" +
                            "Proxy-Authorization: Digest username=\"Bob\"\r\n" +
                            "Call-Info: <http://www.abc.com/photo.png>;purpose=icon\r\n" +
                            "Content-Type: text/plain\r\n" +
                            "Mime-Version: 1.0\r\n" +
                            "Allow: INVITE\r\n" +
                            "Allow: ACK\r\n" +
                            "Allow: BYE\r\n" +
                            "Content-Encoding: deflate\r\n" +
                            "Alert-Info: <http://www.abc.com/sound.wav>\r\n" +
                            "Error-Info: <sip:[email protected]>\r\n" +
                            "Accept: application/sdp\r\n" +
                            "Accept-Encoding: gzip\r\n" +
                            "Accept-Language: en\r\n" +
                            "Authentication-Info: nextnonce=\"abc\"\r\n" +
                            "Proxy-Authentication-Info: nextnonce=\"def\"\r\n" +
                            "P-asserted-identity: sip:[email protected]\r\n" +
                            "Content-Length:    12\r\n" +
                            "\r\n" +
                            "Hello world!"));
        }