public void AS4ComponentDoesntAlterEncryptedDataFromOriginalHolodeckMessage()
        {
            // Arrange
            Holodeck.CopyPModeToHolodeckB("8.1.22-pmode.xml");

            AS4Component.OverrideSettings(DynamicDiscoverySettings);
            AS4Component.Start();

            InsertSmpConfigurationForAS4Component(ReceiveAgentEndpoint, enableEncryption: false);

            var str = VirtualStream.Create();

            str.Write(Properties.Resources._8_1_22_message, 0, Properties.Resources._8_1_22_message.Length);
            str.Position = 0;

            const string contentType =
                "multipart/related; boundary= \"MIMEBoundary_4ac2a25e8a3af891754f9f7316ac08062c50de1368ddfada\"; type=\"application/soap+xml\";";

            // Act
            new StubSender().SendMessage(str, contentType);

            // Assert
            Assert.True(
                PollingAt(AS4ReceiptsPath),
                "No Receipt found at AS4.NET Component for Encrypted Dynamic Forwarding Test");
        }
예제 #2
0
        /// <summary>
        /// Loads a <see cref="Stream" /> at a given stored <paramref name="location" />.
        /// </summary>
        /// <param name="location">The location.</param>
        /// <returns></returns>
        public async Task <Stream> LoadMessageBodyAsync(string location)
        {
            if (location == null)
            {
                throw new ArgumentNullException(nameof(location));
            }

            string fileLocation = SubstringWithoutFileUri(location);

            if (string.IsNullOrEmpty(fileLocation))
            {
                return(null);
            }

            if (File.Exists(fileLocation))
            {
                using (FileStream fileStream = FileUtils.OpenReadAsync(fileLocation, options: FileOptions.SequentialScan))
                {
                    VirtualStream virtualStream =
                        VirtualStream.Create(
                            fileStream.CanSeek ? fileStream.Length : VirtualStream.ThresholdMax,
                            forAsync: true);

                    await fileStream.CopyToFastAsync(virtualStream).ConfigureAwait(false);

                    virtualStream.Position = 0;

                    return(virtualStream);
                }
            }

            return(null);
        }
예제 #3
0
        /// <summary>
        /// Create a new <see cref="AS4Response"/> instance.
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <param name="webResponse"></param>
        /// <returns></returns>
        public static async Task <AS4Response> Create(MessagingContext requestMessage, HttpWebResponse webResponse)
        {
            var response       = new AS4Response(requestMessage, webResponse);
            var responseStream = webResponse.GetResponseStream() ?? Stream.Null;
            var contentStream  = VirtualStream.Create(webResponse.ContentLength, forAsync: true);

            await responseStream.CopyToFastAsync(contentStream);

            contentStream.Position = 0;

            response.ReceivedStream =
                new ReceivedMessage(
                    contentStream,
                    webResponse.ContentType,
                    webResponse.ResponseUri?.AbsolutePath ?? "unknown",
                    webResponse.ContentLength);

            response.ReceivedAS4Message = await TryDeserializeReceivedStream(response.ReceivedStream, CancellationToken.None);

            if (Logger.IsInfoEnabled)
            {
                if (response.ReceivedAS4Message.IsEmpty == false)
                {
                    LogReceivedAS4Response(
                        requestMessage.AS4Message,
                        response.ReceivedAS4Message);
                }
            }

            return(response);
        }
예제 #4
0
        private void CompressAttachment(Attachment attachment)
        {
            PartInfo referenced = _partInfos.FirstOrDefault(attachment.Matches);

            if (referenced == null)
            {
                throw new InvalidOperationException(
                          $"Can't compress attachment {attachment.Id} because no matching PartInfo element was found in UserMessage");
            }

            VirtualStream outputStream =
                VirtualStream.Create(
                    attachment.EstimatedContentSize > -1
                        ? attachment.EstimatedContentSize
                        : VirtualStream.ThresholdMax);

            CompressionLevel compressionLevel = DetermineCompressionLevelFor(attachment);

            using (var gzipCompression = new GZipStream(outputStream, compressionLevel, leaveOpen: true))
            {
                attachment.Content.CopyTo(gzipCompression);
            }

            outputStream.Position      = 0;
            attachment.MimeType        = attachment.ContentType;
            attachment.CompressionType = CompressionType;
            referenced.CompressionType = CompressionType;
            attachment.UpdateContent(outputStream, CompressionType);
        }
예제 #5
0
 public void IsFileStreamWhenInitialCapacityIsLargerThenDefaultThreshold()
 {
     using (VirtualStream stream = VirtualStream.Create(VirtualStream.ThresholdMax + 1))
     {
         Assert.True(stream.UnderlyingStream is FileStream);
     }
 }
예제 #6
0
 public void IsFileStreamWhenInitialCapacityIsLargerThenSpecifiedThreshold()
 {
     using (VirtualStream stream = VirtualStream.Create(10, 7))
     {
         Assert.True(stream.UnderlyingStream is FileStream);
     }
 }
        /// <summary>
        /// Transform a given <see cref="ReceivedMessage"/> to a Canonical <see cref="MessagingContext"/> instance.
        /// </summary>
        /// <param name="message">Given message to transform.</param>
        /// <returns></returns>
        public async Task <MessagingContext> TransformAsync(ReceivedMessage message)
        {
            // We receive an AS4Message from Minder, we should convert it to a SubmitMessage if the action is submit.
            // In any other case, we should just return a MessagingContext which contains the as4Message.
            var receivedStream = VirtualStream.Create();

            await message.UnderlyingStream.CopyToAsync(receivedStream);

            receivedStream.Position = 0;

            var receivedMessage = new ReceivedMessage(
                receivedStream,
                message.ContentType,
                message.Origin,
                message.Length);

            try
            {
                var transformer      = new AS4MessageTransformer();
                var messagingContext = await transformer.TransformAsync(receivedMessage);

                if (messagingContext.AS4Message == null)
                {
                    throw new InvalidMessageException(
                              "Messaging context must contain an AS4 Message");
                }

                if (messagingContext.AS4Message?.FirstUserMessage?.CollaborationInfo?.Action?.Equals("Submit", StringComparison.OrdinalIgnoreCase) ?? false)
                {
                    var as4Message =
                        TransformMinderSubmitToAS4Message(messagingContext.AS4Message.FirstUserMessage, messagingContext.AS4Message.Attachments);
                    messagingContext = new MessagingContext(as4Message, MessagingContextMode.Submit);

                    AssignPModeToContext(messagingContext);

                    return(messagingContext);
                }

                receivedStream.Position = 0;
                return(new MessagingContext(
                           messagingContext.AS4Message,
                           receivedMessage,
                           MessagingContextMode.Receive));
            }
            catch (Exception ex)
            {
                var l = NLog.LogManager.GetCurrentClassLogger();
                l.Error(ex.Message);
                l.Trace(ex.StackTrace);

                if (ex.InnerException != null)
                {
                    l.Error(ex.InnerException.Message);
                }

                throw;
            }
        }
        private static void SendMultiHopAS4Message(AS4Message userMessage)
        {
            ISerializer   serializer = SerializerProvider.Default.Get(userMessage.ContentType);
            VirtualStream virtualStr = VirtualStream.Create();

            serializer.Serialize(userMessage, virtualStr);
            virtualStr.Position = 0;

            new StubSender().SendMessage(virtualStr, userMessage.ContentType);
        }
        private static async Task <Stream> RetrieveTempFileContents(string absolutePath)
        {
            var virtualStr = VirtualStream.Create();

            using (var fileStr = new FileStream(
                       absolutePath,
                       FileMode.Open,
                       FileAccess.Read,
                       FileShare.Read))
            {
                await fileStr.CopyToFastAsync(virtualStr);
            }

            virtualStr.Position = 0;
            return(virtualStr);
        }
예제 #10
0
        private static void DecompressAttachment(IEnumerable <PartInfo> payloadInfo, Attachment attachment)
        {
            PartInfo referenced = payloadInfo.FirstOrDefault(attachment.Matches);

            if (referenced == null)
            {
                throw new InvalidDataException(
                          $"Can't decompress Attachment {attachment.Id} because no matching PartInfo was found");
            }

            if (String.IsNullOrWhiteSpace(referenced.MimeType))
            {
                throw new InvalidDataException(
                          $"Cannot decompress attachment {attachment.Id}: MimeType is not specified in referenced <PartInfo/> element");
            }

            if (referenced.MimeType.IndexOf("/", StringComparison.OrdinalIgnoreCase) < 0)
            {
                throw new InvalidDataException(
                          $"Cannot decompress attachment {attachment.Id}: Invalid MimeType {referenced.MimeType} in referenced <PartInfo/> element");
            }

            attachment.ResetContentPosition();

            long unzipLength = StreamUtilities.DetermineOriginalSizeOfCompressedStream(attachment.Content);

            VirtualStream outputStream =
                VirtualStream.Create(
                    unzipLength > -1 ? unzipLength : VirtualStream.ThresholdMax);

            if (unzipLength > 0)
            {
                outputStream.SetLength(unzipLength);
            }

            Stream decompressed = DecompressStream(attachment.Content);

            referenced.CompressionType = CompressionType;
            attachment.CompressionType = CompressionType;
            attachment.MimeType        = referenced.MimeType;
            attachment.UpdateContent(decompressed, referenced.MimeType);
        }
예제 #11
0
        private static async Task <VirtualStream> CopyIncomingStreamToVirtualStream(ReceivedMessage receivedMessage)
        {
            if (receivedMessage.UnderlyingStream is VirtualStream stream)
            {
                return(stream);
            }

            VirtualStream messageStream =
                VirtualStream.Create(
                    receivedMessage.UnderlyingStream.CanSeek
                        ? receivedMessage.UnderlyingStream.Length
                        : VirtualStream.ThresholdMax,
                    forAsync: true);

            await receivedMessage.UnderlyingStream.CopyToFastAsync(messageStream);

            messageStream.Position = 0;

            return(messageStream);
        }
예제 #12
0
        private static Stream DecompressStream(Stream input)
        {
            long unzipLength = StreamUtilities.DetermineOriginalSizeOfCompressedStream(input);

            VirtualStream outputStream =
                VirtualStream.Create(
                    unzipLength > -1 ? unzipLength : VirtualStream.ThresholdMax);

            if (unzipLength > 0)
            {
                outputStream.SetLength(unzipLength);
            }

            using (var gzipCompression = new GZipStream(input, CompressionMode.Decompress, true))
            {
                gzipCompression.CopyTo(outputStream);
                outputStream.Position = 0;

                return(outputStream);
            }
        }
예제 #13
0
        public void CorrectlyOverflowsToDiskWhenThresholdIsReached()
        {
            byte[] bytesToWrite = new byte[] { 0x01, 0x02, 0x03, 0x04 };

            using (VirtualStream stream = VirtualStream.Create(1, 10))
            {
                Assert.True(stream.UnderlyingStream is MemoryStream);

                stream.Write(bytesToWrite, 0, bytesToWrite.Length);

                Assert.True(stream.UnderlyingStream is MemoryStream);

                stream.Write(bytesToWrite, 0, bytesToWrite.Length);

                Assert.True(stream.UnderlyingStream is MemoryStream);

                stream.Write(bytesToWrite, 0, bytesToWrite.Length);

                Assert.True(stream.UnderlyingStream is FileStream);
                Assert.Equal(bytesToWrite.Length * 3, stream.Length);
            }
        }
        private static async Task <ReceivedMessage> EnsureIncomingStreamIsSeekable(ReceivedMessage m)
        {
            if (m.UnderlyingStream.CanSeek)
            {
                return(m);
            }

            VirtualStream str =
                VirtualStream.Create(
                    expectedSize: m.UnderlyingStream.CanSeek
                        ? m.UnderlyingStream.Length
                        : VirtualStream.ThresholdMax,
                    forAsync: true);

            await m.UnderlyingStream.CopyToFastAsync(str);

            str.Position = 0;

            return(new ReceivedMessage(
                       str,
                       m.ContentType,
                       m.Origin,
                       m.Length));
        }
예제 #15
0
 protected static VirtualStream CreateVirtualStreamOf(Stream innerStream)
 {
     return(VirtualStream.Create(
                expectedSize: innerStream.CanSeek?innerStream.Length: VirtualStream.ThresholdMax));
 }