Ejemplo n.º 1
0
#pragma warning restore IDE0052 // Remove unread private members

        /// <summary>
        /// Initializes a new instance of the <see cref="MllpServer"/> class.
        /// </summary>
        /// <param name="endPoint">The <see cref="IPEndPoint"/> the server will listen on.</param>
        /// <param name="messageLog">The <see cref="IMessageLog"/> to use for logging incoming messages.</param>
        /// <param name="middleware">The message handling middleware.</param>
        /// <param name="cleanupInterval">The interval between cleaning up client connections.</param>
        /// <param name="parser">The <see cref="PipeParser"/> to use for parsing and encoding.</param>
        /// <param name="encoding">The <see cref="Encoding"/> to use for network transfers.</param>
        /// <param name="serverCertificate">The certificates to use for secure connections.</param>
        /// <param name="userCertificateValidationCallback">Optional certificate validation callback.</param>
        public MllpServer(
            IPEndPoint endPoint,
            IMessageLog messageLog,
            IHl7MessageMiddleware middleware,
            TimeSpan cleanupInterval          = default,
            PipeParser?parser                 = null,
            Encoding?encoding                 = null,
            X509Certificate?serverCertificate = null,
            RemoteCertificateValidationCallback?userCertificateValidationCallback = null)
        {
            _messageLog        = messageLog;
            _middleware        = middleware;
            _parser            = parser;
            _encoding          = encoding ?? Encoding.ASCII;
            _serverCertificate = serverCertificate;
            _userCertificateValidationCallback = userCertificateValidationCallback;
            _listener       = new TcpListener(endPoint);
            cleanupInterval = cleanupInterval == default
                ? TimeSpan.FromSeconds(5)
                : cleanupInterval;
            _timer = new Timer(
                CleanConnections,
                null,
                cleanupInterval,
                cleanupInterval);
        }
Ejemplo n.º 2
0
        private readonly IDisposable _server;        public IheHttpServer(IEnumerable <string> urls, IHl7MessageMiddleware middleware)
        {
            _middleware = middleware;
            var startOptions = new StartOptions();

            foreach (var url in urls)
            {
                startOptions.Urls.Add(url);
            }
            _server = WebApp.Start(startOptions, a =>
            {
                a.Run(async ctx =>
                {
                    using (var reader = new StreamReader(ctx.Request.Body))
                    {
                        var hl7      = await reader.ReadToEndAsync().ConfigureAwait(false);
                        var response = await _middleware.Handle(new Hl7Message(hl7, ctx.Request.RemoteIpAddress))
                                       .ConfigureAwait(false);                        if (!string.IsNullOrWhiteSpace(response))
                        {
                            var owinResponse         = ctx.Response;
                            owinResponse.ContentType = "application/hl7-v2";
                            owinResponse.StatusCode  = 200;
                            using (var writer = new StreamWriter(owinResponse.Body))
                            {
                                await writer.WriteAsync(response).ConfigureAwait(false);
                            }
                        }
                    }
                });
            });
        }
Ejemplo n.º 3
0
 private MllpHost(TcpClient client, Encoding encoding, IHl7MessageMiddleware middleware, Stream stream, CancellationToken cancellationToken)
 {
     _client     = client;
     _encoding   = encoding;
     _middleware = middleware;
     _stream     = stream;
     _token      = cancellationToken;
 }
Ejemplo n.º 4
0
        public MllpServer(ServerConnectionDetails connectionDetails, IHl7MessageMiddleware middleware, CancellationToken cancellationToken = default(CancellationToken))
        {
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(connectionDetails.Address), connectionDetails.Port);

            _token             = cancellationToken;
            _connectionDetails = connectionDetails;
            _middleware        = middleware;
            _listener          = new TcpListener(endPoint);
            _timer             = new Timer(CleanConnections, null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5));
        }
Ejemplo n.º 5
0
#pragma warning restore IDE0052 // Remove unread private members

        private MllpHost(
            TcpClient client,
            IMessageLog messageLog,
            PipeParser parser,
            Encoding encoding,
            IHl7MessageMiddleware middleware)
        {
            _client     = client;
            _messageLog = messageLog;
            _parser     = parser;
            _encoding   = encoding;
            _middleware = middleware;
        }
Ejemplo n.º 6
0
        public IheHttpServer(IEnumerable <string> urls, IHl7MessageMiddleware middleware, ParserBase parser)
        {
            _server = new TestServer(new WebHostBuilder()
                                     .UseUrls(urls.ToArray())
                                     .Configure(a =>
            {
                a.Use(async(HttpContext ctx, RequestDelegate next) =>
                {
                    var charset =
                        ctx.Request.ContentType?.Contains(';') == true
                                      ? ctx.Request.ContentType
                        ?.Split(
                            ';',
                            StringSplitOptions
                            .RemoveEmptyEntries)
                        .Last()
                        .Replace(
                            "charset=",
                            "",
                            StringComparison
                            .InvariantCultureIgnoreCase)
                        .Trim()
                                      : null;
                    var encoding = string.IsNullOrWhiteSpace(charset)
                               ? Encoding.ASCII
                               : Encoding.GetEncoding(charset);

                    var reader   = ctx.Request.BodyReader;
                    var hl7      = await reader.ReadAsync().ConfigureAwait(false);
                    var msg      = parser.Parse(encoding.GetString(hl7.Buffer.ToArray()));
                    var response = await middleware.Handle(new Hl7Message(msg, ctx.Connection.RemoteIpAddress?.ToString() ?? string.Empty))
                                   .ConfigureAwait(false);

                    var owinResponse        = ctx.Response;
                    owinResponse.StatusCode = (int)HttpStatusCode.OK;

                    owinResponse.ContentType = "application/hl7-v2; charset=" + encoding.WebName;
                    var output = parser.Encode(response);
                    await owinResponse.BodyWriter.WriteAsync(
                        encoding.GetBytes(output)
                        .AsMemory()).ConfigureAwait(false);
                    await owinResponse.CompleteAsync().ConfigureAwait(false);
                });
            }));
        }
Ejemplo n.º 7
0
        public static async Task <MllpHost> Create(
            TcpClient tcpClient,
            IMessageLog messageLog,
            IHl7MessageMiddleware middleware,
            PipeParser?parser = null,
            Encoding?encoding = null,
            X509Certificate?serverCertificate = null,
            RemoteCertificateValidationCallback?
            userCertificateValidationCallback = null)
        {
            var host = new MllpHost(
                tcpClient,
                messageLog,
                parser ?? new PipeParser(),
                encoding ?? Encoding.ASCII,
                middleware);
            Stream stream = tcpClient.GetStream();

            if (serverCertificate != null)
            {
                var ssl = new SslStream(
                    stream,
                    false,
                    userCertificateValidationCallback);
                await ssl.AuthenticateAsServerAsync(
                    serverCertificate,
                    true,
                    SslProtocols.Tls11 | SslProtocols.Tls12,
                    false)
                .ConfigureAwait(false);

                host._stream = ssl;
            }
            else
            {
                host._stream = stream;
            }

            host._readThread = host.ReadStream(host._tokenSource.Token);
            return(host);
        }
Ejemplo n.º 8
0
        public static async Task <MllpHost> Create(TcpClient tcpClient, IHl7MessageMiddleware middleware, Encoding encoding = null, ServerSecurityDetails securityDetails = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            Stream        stream;
            NetworkStream networkStream = tcpClient.GetStream();

            if (securityDetails != null)
            {
                var sslStream = new SslStream(networkStream, true, securityDetails.ClientCertificateValidationCallback, null);

                try
                {
                    bool askForClientCertificate = securityDetails.ForceClientAuthentciation;
                    await sslStream.AuthenticateAsServerAsync(securityDetails.ServerCertificate, askForClientCertificate, securityDetails.SupportedSslProtocols, false);

                    if (askForClientCertificate && !sslStream.IsMutuallyAuthenticated)
                    {
                        throw new AuthenticationException("mutual authentication failed.");
                    }
                }
                catch (Exception)
                {
                    sslStream.Dispose();
                    throw;
                }

                stream = sslStream;
            }
            else
            {
                stream = networkStream;
            }

            var host = new MllpHost(tcpClient, encoding ?? Encoding.ASCII, middleware, stream, cancellationToken);

            host.ReadStream(host._token);
            return(host);
        }
Ejemplo n.º 9
0
 public MllpServer CreateServerConnection(ServerConnectionDetails connectionDetails, IHl7MessageMiddleware middleware)
 {
     return(new MllpServer(connectionDetails, middleware));
 }