Exemple #1
0
 /// <summary>
 /// Message received
 /// </summary>
 /// <param name="message"></param>
 protected void OnMessageReceived(Hl7MessageReceivedEventArgs messageArgs)
 {
     if (this.MessageReceived != null)
     {
         this.MessageReceived(this, messageArgs);
     }
 }
Exemple #2
0
        /// <summary>
        /// Receive and process message
        /// </summary>
        private void ReceiveMessage(object client)
        {
            TcpClient     tcpClient = client as TcpClient;
            NetworkStream stream    = tcpClient.GetStream();

            try
            {
                // Now read to a string
                NHapi.Base.Parser.PipeParser parser = new NHapi.Base.Parser.PipeParser();

                StringBuilder messageData = new StringBuilder();
                byte[]        buffer      = new byte[1024];
                while (stream.DataAvailable)
                {
                    int br = stream.Read(buffer, 0, 1024);
                    messageData.Append(Encoding.ASCII.GetString(buffer, 0, br));
                }

                var message        = parser.Parse(messageData.ToString());
                var localEp        = tcpClient.Client.LocalEndPoint as IPEndPoint;
                var remoteEp       = tcpClient.Client.RemoteEndPoint as IPEndPoint;
                Uri localEndpoint  = new Uri(String.Format("tcp://{0}:{1}", localEp.Address, localEp.Port));
                Uri remoteEndpoint = new Uri(String.Format("tcp://{0}:{1}", remoteEp.Address, remoteEp.Port));
                var messageArgs    = new Hl7MessageReceivedEventArgs(message, localEndpoint, remoteEndpoint, DateTime.Now);
                HL7OperationContext.Current = new HL7OperationContext(messageArgs);

                this.MessageReceived(this, messageArgs);

                // Send the response back
                StreamWriter writer = new StreamWriter(stream);
                if (messageArgs.Response != null)
                {
                    writer.Write(parser.Encode(messageArgs.Response));
                    writer.Flush();
                }
            }
            catch (Exception e)
            {
                this.m_traceSource.TraceEvent(EventLevel.Error, e.ToString());
                // TODO: NACK
            }
            finally
            {
                stream.Close();
                HL7OperationContext.Current = null;
            }
        }
Exemple #3
0
        /// <summary>
        /// Receive and process message
        /// </summary>
        protected virtual void OnReceiveMessage(object client)
        {
            TcpClient     tcpClient = client as TcpClient;
            NetworkStream stream    = tcpClient.GetStream();

            try
            {
                // Now read to a string
                DateTime lastReceive = DateTime.Now;

                while (DateTime.Now.Subtract(lastReceive) < this.m_timeout)
                {
                    if (!stream.DataAvailable)
                    {
                        Thread.Sleep(10);
                        continue;
                    }

                    // Read LLP head byte
                    int llpByte = stream.ReadByte();
                    if (llpByte != START_TX)                     // first byte must be HT
                    {
                        throw new InvalidOperationException("Invalid LLP First Byte");
                    }

                    // Standard stream stuff, read until the stream is exhausted
                    StringBuilder messageData = new StringBuilder();
                    byte[]        buffer = new byte[1024];
                    bool          receivedEOF = false, scanForCr = false;

                    while (!receivedEOF)
                    {
                        if (DateTime.Now.Subtract(lastReceive) > this.m_timeout)
                        {
                            throw new TimeoutException("Data not received in the specified amount of time. Increase the timeout or check the network connection");
                        }

                        if (!stream.DataAvailable)
                        {
                            Thread.Sleep(10);
                            continue;
                        }

                        int br = stream.Read(buffer, 0, 1024);
                        messageData.Append(System.Text.Encoding.UTF8.GetString(buffer, 0, br));

                        // Need to check for CR?
                        if (scanForCr)
                        {
                            receivedEOF = buffer[0] == END_TXNL;
                        }
                        else
                        {
                            // Look for FS
                            int fsPos = Array.IndexOf(buffer, (byte)END_TX);

                            if (fsPos == -1)                             // not found
                            {
                                continue;
                            }
                            else if (fsPos < buffer.Length - 1)                             // more room to read
                            {
                                receivedEOF = buffer[fsPos + 1] == END_TXNL;
                            }
                            else
                            {
                                scanForCr = true;                                 // Cannot check the end of message for CR because there is no more room in the message buffer
                            }
                            // so need to check on the next loop
                        }
                    }

                    // Use the nHAPI parser to process the data
                    Hl7MessageReceivedEventArgs messageArgs = null;
                    String originalVersion = null;
                    try
                    {
                        // Setup local and remote receive endpoint data for auditing
                        var localEp        = tcpClient.Client.LocalEndPoint as IPEndPoint;
                        var remoteEp       = tcpClient.Client.RemoteEndPoint as IPEndPoint;
                        Uri localEndpoint  = new Uri(String.Format("llp://{0}:{1}", localEp.Address, localEp.Port));
                        Uri remoteEndpoint = new Uri(String.Format("llp://{0}:{1}", remoteEp.Address, remoteEp.Port));

#if DEBUG
                        this.m_traceSource.TraceInfo("Received message from llp://{0}:{1} : {2}", remoteEp.Address, remoteEp.Port, messageData);
#endif

                        // HACK: nHAPI doesn't like URLs ... Will fix this later
                        string messageString = messageData.ToString().Replace("|URL|", "|ST|");

                        var message = MessageUtils.ParseMessage(messageString, out originalVersion);
                        messageArgs = new Hl7MessageReceivedEventArgs(message, localEndpoint, remoteEndpoint, DateTime.Now);

                        HL7OperationContext.Current = new HL7OperationContext(messageArgs);

                        // Call any bound event handlers that there is a message available
                        OnMessageReceived(messageArgs);
                    }
                    finally
                    {
                        // Send the response back
                        using (MemoryStream memoryWriter = new MemoryStream())
                        {
                            using (StreamWriter streamWriter = new StreamWriter(memoryWriter))
                            {
                                memoryWriter.Write(new byte[] { START_TX }, 0, 1);                                 // header
                                if (messageArgs != null && messageArgs.Response != null)
                                {
                                    var strMessage = MessageUtils.EncodeMessage(messageArgs.Response, originalVersion);
#if DEBUG
                                    this.m_traceSource.TraceInfo("Sending message to llp://{0} : {1}", tcpClient.Client.RemoteEndPoint, strMessage);
#endif
                                    // Since nHAPI only emits a string we just send that along the stream
                                    streamWriter.Write(strMessage);
                                    streamWriter.Flush();
                                }
                                memoryWriter.Write(new byte[] { END_TX, END_TXNL }, 0, 2);                                 // Finish the stream with FSCR
                                stream.Write(memoryWriter.ToArray(), 0, (int)memoryWriter.Position);
                                stream.Flush();
                            }
                        }
                        lastReceive = DateTime.Now;                         // Update the last receive time so the timeout function works
                    }
                }
            }
            catch (Exception e)
            {
                this.m_traceSource.TraceEvent(EventLevel.Error, e.ToString());
            }
            finally
            {
                stream.Close();
                tcpClient.Close();
                HL7OperationContext.Current = null;
            }
        }
Exemple #4
0
        /// <summary>
        /// Receive a message
        /// </summary>
        protected override void OnReceiveMessage(object client)
        {
            TcpClient tcpClient = client as TcpClient;
            SslStream stream    = new SslStream(tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(RemoteCertificateValidation));

            try
            {
                // Setup local and remote receive endpoint data for auditing
                var localEp        = tcpClient.Client.LocalEndPoint as IPEndPoint;
                var remoteEp       = tcpClient.Client.RemoteEndPoint as IPEndPoint;
                Uri localEndpoint  = new Uri(String.Format("sllp://{0}:{1}", localEp.Address, localEp.Port));
                Uri remoteEndpoint = new Uri(String.Format("sllp://{0}:{1}", remoteEp.Address, remoteEp.Port));
                this.m_traceSource.TraceInfo("Accepted TCP connection from {0} > {1}", remoteEndpoint, localEndpoint);

                stream.AuthenticateAsServer(this.m_configuration.ServerCertificate.GetCertificate(), this.m_configuration.EnableClientCertNegotiation, System.Security.Authentication.SslProtocols.Tls, this.m_configuration.CheckCrl);

                // Now read to a string
                NHapi.Base.Parser.PipeParser parser = new NHapi.Base.Parser.PipeParser();

                DateTime lastReceive = DateTime.Now;

                while (DateTime.Now.Subtract(lastReceive) < this.m_timeout)
                {
                    int llpByte = 0;
                    // Read LLP head byte
                    try
                    {
                        llpByte = stream.ReadByte();
                    }
                    catch (SocketException)
                    {
                        break;
                    }

                    if (llpByte != START_TX)                     // first byte must be HT
                    {
                        this.m_traceSource.TraceEvent(EventLevel.Warning, "Invalid LLP First Byte expected 0x{0:x} got 0x{1:x} from {2}", START_TX, llpByte, remoteEndpoint);
                        break;
                    }
                    //                        throw new InvalidOperationException("Invalid LLP First Byte");

                    // Standard stream stuff, read until the stream is exhausted
                    StringBuilder messageData = new StringBuilder();
                    byte[]        buffer = new byte[1024];
                    bool          receivedEOF = false, scanForCr = false;

                    while (!receivedEOF)
                    {
                        int br = stream.Read(buffer, 0, 1024);
                        messageData.Append(System.Text.Encoding.UTF8.GetString(buffer, 0, br));

                        // Need to check for CR?
                        if (scanForCr)
                        {
                            receivedEOF = buffer[0] == END_TXNL;
                        }
                        else
                        {
                            // Look for FS
                            int fsPos = Array.IndexOf(buffer, END_TX);

                            if (fsPos == -1)                             // not found
                            {
                                continue;
                            }
                            else if (fsPos < buffer.Length - 1)                             // more room to read
                            {
                                receivedEOF = buffer[fsPos + 1] == END_TXNL;
                            }
                            else
                            {
                                scanForCr = true;                                 // Cannot check the end of message for CR because there is no more room in the message buffer
                            }
                            // so need to check on the next loop
                        }

                        // TODO: Timeout for this
                    }

                    // Use the nHAPI parser to process the data
                    Hl7MessageReceivedEventArgs messageArgs = null;
                    try
                    {
                        var message = parser.Parse(messageData.ToString());

#if DEBUG
                        this.m_traceSource.TraceInfo("Received message from sllp://{0} : {1}", tcpClient.Client.RemoteEndPoint, messageData.ToString());
#endif

                        messageArgs = new AuthenticatedHl7MessageReceivedEventArgs(message, localEndpoint, remoteEndpoint, DateTime.Now, stream.RemoteCertificate.GetPublicKey());

                        HL7OperationContext.Current = new HL7OperationContext(messageArgs);

                        // Call any bound event handlers that there is a message available
                        OnMessageReceived(messageArgs);
                    }
                    finally
                    {
                        // Send the response back
                        using (MemoryStream memoryWriter = new MemoryStream())
                        {
                            using (StreamWriter streamWriter = new StreamWriter(memoryWriter))
                            {
                                memoryWriter.Write(new byte[] { START_TX }, 0, 1);                                 // header
                                if (messageArgs != null && messageArgs.Response != null)
                                {
                                    var strMessage = parser.Encode(messageArgs.Response);
#if DEBUG
                                    this.m_traceSource.TraceInfo("Sending message to sllp://{0} : {1}", tcpClient.Client.RemoteEndPoint, strMessage);
#endif
                                    // Since nHAPI only emits a string we just send that along the stream
                                    streamWriter.Write(strMessage);
                                    streamWriter.Flush();
                                }
                                memoryWriter.Write(new byte[] { END_TX, END_TXNL }, 0, 2);                                 // Finish the stream with FSCR
                                stream.Write(memoryWriter.ToArray(), 0, (int)memoryWriter.Position);
                                stream.Flush();
                            }
                        }

                        lastReceive = DateTime.Now;                         // Update the last receive time so the timeout function works
                    }
                }
            }
            catch (AuthenticationException e)
            {
                // Trace authentication error
                AuditData ad = new AuditData(
                    DateTime.Now,
                    ActionType.Execute,
                    OutcomeIndicator.MinorFail,
                    EventIdentifierType.ApplicationActivity,
                    new AuditCode("110113", "DCM")
                {
                    DisplayName = "Security Alert"
                }
                    );
                ad.Actors = new List <AuditActorData>()
                {
                    new AuditActorData()
                    {
                        NetworkAccessPointId   = Dns.GetHostName(),
                        NetworkAccessPointType = NetworkAccessPointType.MachineName,
                        UserName        = Environment.UserName,
                        UserIsRequestor = false
                    },
                    new AuditActorData()
                    {
                        NetworkAccessPointId   = String.Format("sllp://{0}", tcpClient.Client.RemoteEndPoint.ToString()),
                        NetworkAccessPointType = NetworkAccessPointType.MachineName,
                        UserIsRequestor        = true
                    }
                };
                ad.AuditableObjects = new List <AuditableObject>()
                {
                    new AuditableObject()
                    {
                        Type       = AuditableObjectType.SystemObject,
                        Role       = AuditableObjectRole.SecurityResource,
                        IDTypeCode = AuditableObjectIdType.Uri,
                        ObjectId   = String.Format("sllp://{0}", this.m_listener.LocalEndpoint)
                    }
                };

                ApplicationServiceContext.Current.GetService <IAuditRepositoryService>()?.Insert(ad);
                ApplicationServiceContext.Current.GetService <IAuditDispatchService>()?.SendAudit(ad);
                this.m_traceSource.TraceEvent(EventLevel.Error, e.ToString());
            }
            catch (Exception e)
            {
                this.m_traceSource.TraceEvent(EventLevel.Error, e.ToString());
                // TODO: NACK
            }
            finally
            {
                stream.Close();
                tcpClient.Close();
                HL7OperationContext.Current = null;
            }
        }
Exemple #5
0
        /// <summary>
        /// Receive and process message
        /// </summary>
        protected virtual void OnReceiveMessage(object client)
        {
            using (TcpClient tcpClient = client as TcpClient)
            {
                this.m_traceSource.TraceEvent(EventLevel.Verbose, "Accepted connection on {0} from {1}", this.m_listener.LocalEndpoint, tcpClient.Client.RemoteEndPoint);
                NetworkStream stream = tcpClient.GetStream();
                try
                {
                    // Now read to a string
                    DateTime lastReceive = DateTime.Now;

                    while (DateTime.Now.Subtract(lastReceive) < this.m_timeout)
                    {
                        if (!stream.DataAvailable)
                        {
                            Thread.Sleep(10);
                            continue;
                        }

                        // Read LLP head byte
                        int llpByte = stream.ReadByte();
                        if (llpByte != START_TX) // first byte must be HT
                        {
                            throw new InvalidOperationException("Invalid LLP First Byte");
                        }

                        // Standard stream stuff, read until the stream is exhausted
                        StringBuilder messageData = new StringBuilder();
                        byte[]        buffer = new byte[1024];
                        bool          receivedEOF = false, scanForCr = false;

                        while (!receivedEOF)
                        {
                            if (DateTime.Now.Subtract(lastReceive) > this.m_timeout)
                            {
                                throw new TimeoutException("Data not received in the specified amount of time. Increase the timeout or check the network connection");
                            }

                            if (!stream.DataAvailable)
                            {
                                Thread.Sleep(10);
                                continue;
                            }

                            int br = stream.Read(buffer, 0, 1024);
                            messageData.Append(System.Text.Encoding.UTF8.GetString(buffer, 0, br));

                            // Need to check for CR?
                            if (scanForCr)
                            {
                                receivedEOF = buffer[0] == END_TXNL;
                            }
                            else
                            {
                                // Look for FS
                                int fsPos = Array.IndexOf(buffer, (byte)END_TX);

                                if (fsPos == -1) // not found
                                {
                                    continue;
                                }
                                else if (fsPos < buffer.Length - 1) // more room to read
                                {
                                    receivedEOF = buffer[fsPos + 1] == END_TXNL;
                                }
                                else
                                {
                                    scanForCr = true; // Cannot check the end of message for CR because there is no more room in the message buffer
                                }
                                // so need to check on the next loop
                            }
                        }

                        // Use the nHAPI parser to process the data
                        Hl7MessageReceivedEventArgs messageArgs = null;
                        String originalVersion = null;

                        // Setup local and remote receive endpoint data for auditing
                        var localEp        = tcpClient.Client.LocalEndPoint as IPEndPoint;
                        var remoteEp       = tcpClient.Client.RemoteEndPoint as IPEndPoint;
                        Uri localEndpoint  = new Uri(String.Format("llp://{0}:{1}", localEp.Address, localEp.Port));
                        Uri remoteEndpoint = new Uri(String.Format("llp://{0}:{1}", remoteEp.Address, remoteEp.Port));

                        foreach (var messagePart in messageData.ToString().Split((char)END_TX))
                        {
                            if (messagePart == "\r")
                            {
                                continue;
                            }

                            try
                            {
                                this.m_traceSource.TraceInfo("Received message from llp://{0}:{1} : {2}", remoteEp.Address, remoteEp.Port, messagePart);
                                // HACK: nHAPI doesn't like URLs ... Will fix this later
                                string messageString = messagePart.Replace("|URL|", "|ST|");

                                var message = MessageUtils.ParseMessage(messageString, out originalVersion);
                                messageArgs = new Hl7MessageReceivedEventArgs(message, localEndpoint, remoteEndpoint, DateTime.Now);

                                HL7OperationContext.Current = new HL7OperationContext(messageArgs);

                                // Call any bound event handlers that there is a message available
                                OnMessageReceived(messageArgs);
                            }
                            catch (Exception e)
                            {
                                this.m_traceSource.TraceError("Error processing HL7 message: {0}", e);
                                if (messageArgs != null)
                                {
                                    var nack = new NHapi.Model.V25.Message.ACK();
                                    nack.MSH.SetDefault(messageArgs.Message.GetStructure("MSH") as NHapi.Model.V25.Segment.MSH);
                                    nack.MSA.AcknowledgmentCode.Value = "AE";
                                    nack.MSA.TextMessage.Value        = $"FATAL - {e.Message}";
                                    nack.MSA.MessageControlID.Value   = (messageArgs.Message.GetStructure("MSH") as NHapi.Model.V25.Segment.MSH).MessageControlID.Value;
                                    messageArgs.Response = nack;

                                    var icomps = PipeParser.Encode(messageArgs.Message.GetStructure("MSH") as NHapi.Base.Model.ISegment, new EncodingCharacters('|', "^~\\&")).Split('|');
                                    var ocomps = PipeParser.Encode(messageArgs.Response.GetStructure("MSH") as NHapi.Base.Model.ISegment, new EncodingCharacters('|', "^~\\&")).Split('|');
                                    AuditUtil.AuditNetworkRequestFailure(e, messageArgs.ReceiveEndpoint, Enumerable.Range(1, icomps.Length).ToDictionary(o => $"MSH-{o}", o => icomps[o - 1]), Enumerable.Range(1, icomps.Length).ToDictionary(o => $"MSH-{o}", o => ocomps[o - 1]));
                                }
                                else
                                {
                                    AuditUtil.AuditNetworkRequestFailure(e, localEndpoint, new System.Collections.Specialized.NameValueCollection(), new System.Collections.Specialized.NameValueCollection());
                                }
                            }
                            finally
                            {
                                // Send the response back
                                using (MemoryStream memoryWriter = new MemoryStream())
                                {
                                    using (StreamWriter streamWriter = new StreamWriter(memoryWriter))
                                    {
                                        memoryWriter.Write(new byte[] { START_TX }, 0, 1); // header
                                        if (messageArgs != null && messageArgs.Response != null)
                                        {
                                            var strMessage = MessageUtils.EncodeMessage(messageArgs.Response, originalVersion);
                                            this.m_traceSource.TraceInfo("Sending message to llp://{0} : {1}", tcpClient.Client.RemoteEndPoint, strMessage);
                                            // Since nHAPI only emits a string we just send that along the stream
                                            streamWriter.Write(strMessage);
                                            streamWriter.Flush();
                                        }
                                        memoryWriter.Write(new byte[] { END_TX, END_TXNL }, 0, 2); // Finish the stream with FSCR
                                        stream.Write(memoryWriter.ToArray(), 0, (int)memoryWriter.Position);
                                        stream.Flush();
                                    }
                                }
                                lastReceive = DateTime.Now; // Update the last receive time so the timeout function works
                            }
                        }

                        if (!stream.DataAvailable)
                        {
                            return;
                        }
                    }
                }
                catch (Exception e)
                {
                    this.m_traceSource.TraceEvent(EventLevel.Error, e.ToString());
                }
                finally
                {
                    stream.Close();
                    tcpClient.Close();
                    HL7OperationContext.Current = null;
                }
            }
        }