private void RunnerLoop()
        {
            IPEndPoint remoteEndpoint = new IPEndPoint(IPAddress.Any, 0);

            while (true)
            {
                try
                {
                    byte[] payload = _client.Receive(ref remoteEndpoint);
                    try
                    {
                        SyslogMessage newMessage = SyslogMessage.Parse(payload);
                        OnMessageReceived(new SyslogMessageEventArgs(newMessage));
                    }
                    catch (FormatException)
                    {
                        //Skip
                    }
                }
                catch (SocketException)
                {
                    //We are closing, or an I/O error occurred
                    //if (Stopped) //Yes, we are closing
                    return;
                }
                catch (Exception)
                {
                } //Really do nothing? Shouldn't we stop the service?
            }
        }
        private void thread_Client(object Logbus)
        {
            try
            {
                ILogBus ctrl = Logbus as ILogBus;
                ctrl.CreateChannel("simple", "Simple", new TrueFilter(), "Very simple channel", 0);
                Dictionary <string, string> input;
                input = new Dictionary <string, string>();
                IEnumerable <KeyValuePair <string, string> > output;
                input.Add("ip", "127.0.0.1");
                input.Add("port", MONITOR_PORT.ToString());
                string clientid = ctrl.SubscribeClient("simple", "udp", input, out output);
                TestContext.WriteLine("Client ID obtained by logbus: {0}", clientid);

                //Go ahead and send
                step1.Set();


                IPEndPoint remote_ep = new IPEndPoint(IPAddress.Any, 0);
                using (UdpClient client = new UdpClient(MONITOR_PORT))
                {
                    byte[]        payload = client.Receive(ref remote_ep);
                    SyslogMessage msg     = SyslogMessage.Parse(payload);
                    TestContext.WriteLine("Message1: {0}", msg);
                    payload = client.Receive(ref remote_ep);
                    msg     = SyslogMessage.Parse(payload);
                    TestContext.WriteLine("Message2: {0}", msg);
                }

                ctrl.UnsubscribeClient(clientid);
                finish.Set();
            }
            catch (Exception ex) { Assert.Fail("Test failed: {0}", ex); }
        }
Exemple #3
0
        private void t2_thread_Client(object Logbus)
        {
            try
            {
                ILogBus ctrl = Logbus as ILogBus;
                ctrl.CreateChannel("simple", "Simple", new TrueFilter(), "Very simple channel", 0);
                Dictionary <string, string> input;
                input = new Dictionary <string, string>();
                IEnumerable <KeyValuePair <string, string> > output;
                input.Add("ip", "127.0.0.1");
                input.Add("port", t2_client_port.ToString());
                string clientid = ctrl.SubscribeClient("simple", "udp", input, out output);
                TestContext.WriteLine("Client ID obtained by logbus: {0}", clientid);

                //Go ahead and send
                t2_step1.Set();

                //Only 6 messages expected
                IPEndPoint remote_ep = new IPEndPoint(IPAddress.Any, 0);
                using (UdpClient client = new UdpClient(t2_client_port))
                {
                    byte[] payload = client.Receive(ref remote_ep);
                    TestContext.WriteLine("Time occurred for a message to traverse the bus: {0} milliseconds", (DateTime.Now - t2_start).TotalMilliseconds.ToString(CultureInfo.CurrentUICulture));
                    SyslogMessage msg = SyslogMessage.Parse(payload);
                }

                ctrl.UnsubscribeClient(clientid);
                t2_finish.Set();
            }
            catch (Exception ex) { Assert.Fail("Test failed: {0}", ex); }
        }
Exemple #4
0
        private static void Server_MessageReceived(object sender, MessageReceivedArgs e)
        {
            var receivedData = Encoding.ASCII.GetString(e.Data, 0, e.Data.Length);
            var msg          = SyslogMessage.Parse(e.IPEndPoint, receivedData);

            Console.WriteLine(msg.ToString());
        }
Exemple #5
0
        private void t1_thread_Client(object Logbus)
        {
            try
            {
                ILogBus ctrl = Logbus as ILogBus;
                ctrl.CreateChannel("simple", "Simple", new TrueFilter(), "Very simple channel", 0);
                Dictionary <string, string> input;
                input = new Dictionary <string, string>();
                IEnumerable <KeyValuePair <string, string> > output;
                input.Add("ip", "127.0.0.1");
                input.Add("port", t1_client_port.ToString());
                string clientid = ctrl.SubscribeClient("simple", "udp", input, out output);
                TestContext.WriteLine("Client ID obtained by logbus: {0}", clientid);

                //Go ahead and send
                t1_step1.Set();

                //Only 6 messages expected
                IPEndPoint remote_ep = new IPEndPoint(IPAddress.Any, 0);
                using (UdpClient client = new UdpClient(t1_client_port))
                    for (int i = 0; i < 5; i++)
                    {
                        byte[] payload = client.Receive(ref remote_ep);

                        SyslogMessage msg = SyslogMessage.Parse(payload);
                        Assert.AreEqual(SyslogFacility.Audit, msg.Facility);
                    }

                ctrl.UnsubscribeClient(clientid);
                t1_finish.Set();
            }
            catch (Exception ex) { Assert.Fail("Test failed: {0}", ex); }
        }
Exemple #6
0
        [Test] public void Parsing()
        {
            IPAddress ip = IPAddress.Loopback;

            SyslogMessage m1 = SyslogMessage.Parse(ip,
                                                   "<13>Dec  1 16:12:15 localhost test message!");

            Assert.AreEqual(SyslogMessage.FacilityCode.UserLevel, m1.Facility,
                            "Facility Code Parsing");
            Assert.AreEqual(SyslogMessage.SeverityCode.Notice, m1.Severity,
                            "Severity Code Parsing");
            Assert.AreEqual(ip.ToString(), m1.LocalHost, "Host parsing");
            Assert.AreEqual("localhost test message!", m1.Message, "Message parsing");
            Assert.AreEqual(12, m1.LocalTime.Month, "Message month");
            Assert.AreEqual(16, m1.LocalTime.Hour, "Message hour");

            SyslogMessage m2 = SyslogMessage.Parse(ip,
                                                   "<34>Oct 11 22:14:15 mymachine su: 'su root' failed for lonvick on /dev/pts/8");

            Assert.AreEqual(SyslogMessage.FacilityCode.Security1, m2.Facility,
                            "Facility Code Parsing");
            Assert.AreEqual(SyslogMessage.SeverityCode.Critical, m2.Severity,
                            "Severity Code Parsing");
            Assert.AreEqual(ip.ToString(), m2.LocalHost, "Host parsing");
            Assert.AreEqual("mymachine su: 'su root' failed for lonvick on /dev/pts/8",
                            m2.Message, "Message parsing");
            Assert.AreEqual(10, m2.LocalTime.Month, "Message month");
            Assert.AreEqual(22, m2.LocalTime.Hour, "Message hour");

            SyslogMessage m3 = SyslogMessage.Parse(ip, "No header");

            Assert.AreEqual(SyslogMessage.FacilityCode.UserLevel, m3.Facility,
                            "Facility Code Parsing");
            Assert.AreEqual(SyslogMessage.SeverityCode.Notice, m3.Severity,
                            "Severity Code Parsing");
            Assert.AreEqual("No header", m3.Message, "Message parsing");

            SyslogMessage m4 = SyslogMessage.Parse(ip, "<999>Invalid header");

            Assert.AreEqual("<999>Invalid header", m4.Message, "Message parsing");

            SyslogMessage m5 = SyslogMessage.Parse(ip, "<1>Invalid date");

            Assert.AreEqual(SyslogMessage.FacilityCode.Kernel, m5.Facility,
                            "Facility Code Parsing");
            Assert.AreEqual(SyslogMessage.SeverityCode.Alert, m5.Severity,
                            "Severity Code Parsing");
            Assert.AreEqual("Invalid date", m5.Message, "Message parsing");
        }
Exemple #7
0
        private void ParserLoop(object queue)
        {
            int queueId = (int)queue;

            try
            {
                while (true)
                {
                    byte[] payload = _byteQueues[queueId].Dequeue();

                    try
                    {
                        SyslogMessage newMessage = SyslogMessage.Parse(payload);
                        ForwardMessage(newMessage);
                    }
                    catch (FormatException ex)
                    {
                        ParseErrorEventArgs e = new ParseErrorEventArgs(payload, ex, false);
                        OnParseError(e);
                    }
                }
            }
            catch (ThreadInterruptedException)
            {
            }
            finally
            {
                byte[][] finalMessages = _byteQueues[queueId].FlushAndDispose();
                if (finalMessages.GetLength(0) > 0)
                {
                    Log.Notice("Inbound channel {0} still needs to process {0} pending messages. Delaying stop.",
                               ToString(), finalMessages.GetLength(0));
                }
                foreach (byte[] payload in finalMessages)
                {
                    try
                    {
                        SyslogMessage newMessage = SyslogMessage.Parse(payload);
                        ForwardMessage(newMessage);
                    }
                    catch (FormatException ex)
                    {
                        ParseErrorEventArgs e = new ParseErrorEventArgs(payload, ex, false);
                        OnParseError(e);
                    }
                }
            }
        }
Exemple #8
0
        /// <summary>
        /// Process a syslog message
        /// </summary>
        private void ProcessSyslogMessage(string strMessage, TcpClient client, Stream sourceStream, Guid sessionId)
        {
            var localEp        = client.Client.LocalEndPoint as IPEndPoint;
            var remoteEp       = client.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));

            // Get rid of length
            Regex messageLengthMatch = new Regex(@"^(\d*)\s(.*)$");
            var   match = messageLengthMatch.Match(strMessage);

            if (match.Success)
            {
                strMessage = match.Groups[2].Value;
            }

            if (strMessage.Length == 0)
            {
                return;                         // no message
            }
            try
            {
                var message = SyslogMessage.Parse(strMessage, sessionId);
                SyslogMessageReceivedEventArgs messageArgs = null;
                if (sourceStream is SslStream)
                {
                    messageArgs = new AuthenticatedSyslogMessageReceivedEventArgs(message, remoteEndpoint, localEndpoint, DateTime.Now, (sourceStream as SslStream).RemoteCertificate);
                }
                else
                {
                    messageArgs = new SyslogMessageReceivedEventArgs(message, remoteEndpoint, localEndpoint, DateTime.Now);
                }

                this.FireMessageReceived(this, messageArgs);
            }
            catch (SyslogMessageException e)
            {
                this.FireInvalidMessageReceived(this, new SyslogMessageReceivedEventArgs(e.FaultingMessage, remoteEndpoint, localEndpoint, DateTime.Now));
                this.m_traceSource.TraceError(e.Message);
            }
            catch (Exception e)
            {
                this.m_traceSource.TraceError(e.ToString());
            }
        }
Exemple #9
0
        private void ProcessLoop()
        {
            try
            {
                while (true)
                {
                    byte[] data = _queue.Dequeue();

                    try
                    {
                        SyslogMessage msg = SyslogMessage.Parse(data);

                        OnMessageReceived(new SyslogMessageEventArgs(msg));
                    }
                    catch (FormatException ex)
                    {
                        OnError(new UnhandledExceptionEventArgs(ex, false));
                        continue;
                    }
                }
            }
            catch (ThreadInterruptedException)
            {
                return;
            }
            catch (Exception ex)
            {
                OnError(new UnhandledExceptionEventArgs(ex, true));

                Log.Error("Error receiving Syslog messages from Logbus-ng server");
                Log.Debug("Error details: {0}", ex.Message);

                new Thread(delegate()
                {
                    try
                    {
                        Stop();
                    }
                    catch { }
                }).Start();
                return;
            }
        }
        private void Injector()
        {
            try
            {
                //The injector will basically read Syslog messages, encoded in raw base64 form and collected with the proper tool by djechelon (or equivalent)
                //The collector tool can be found at http://logbus-ng.svn.sourceforge.net/viewvc/logbus-ng/developers/djechelon/SyslogCollector/

                IPEndPoint endpoint = new IPEndPoint(IPAddress.Loopback, SyslogUdpReceiver.DEFAULT_PORT);

                using (StreamReader sr = new StreamReader(GetType().Assembly.GetManifestResourceStream("Unit_Tests.TestLogs.Syslog.base64.txt"), Encoding.GetEncoding(1252)))
                {
                    using (UdpClient client = new UdpClient())
                        while (!sr.EndOfStream)
                        {
                            string base64line = sr.ReadLine();
                            byte[] raw_log    = Convert.FromBase64String(base64line);

                            //See from here if it matches filter
                            SyslogMessage msg = SyslogMessage.Parse(raw_log);
                            if (msg.Facility == SyslogFacility.Security)
                            {
                                messages_to_match += 1;
                            }

                            client.Send(raw_log, raw_log.Length, endpoint);

                            //Wait a sec... otherwise UDP channel would be flooded and log message missed
                            //Timeout can be adjusted or replaced with a semaphore
                            Thread.Sleep(10);
                        }
                }
            }
            finally
            {
                inject_finish.Set();
            }
        }
        public void SyslogParserTestReal()
        {
            //Just test that messages are being parset. Stop.

            using (StreamReader sr = new StreamReader(GetType().Assembly.GetManifestResourceStream("Unit_Tests.TestLogs.Syslog.base64.txt"), Encoding.GetEncoding(1252)))
            {
                while (!sr.EndOfStream)
                {
                    string base64Line = sr.ReadLine();
                    byte[] rawLog     = Convert.FromBase64String(base64Line);
                    try
                    {
                        SyslogMessage.Parse(rawLog);
                    }
                    catch (FormatException ex)
                    {
                        Assert.Fail("Test failed: {0}", ex);
                    }
                }
            }
            using (StreamReader sr = new StreamReader(GetType().Assembly.GetManifestResourceStream("Unit_Tests.TestLogs.Syslog.plain.txt"), Encoding.UTF8))
            {
                while (!sr.EndOfStream)
                {
                    string rawLog = sr.ReadLine();
                    try
                    {
                        SyslogMessage.Parse(rawLog);
                    }
                    catch (FormatException ex)
                    {
                        TestContext.WriteLine("Failed parsing: {0}", rawLog);
                        Assert.Fail("Test failed: {0}", ex);
                    }
                }
            }
        }
        public void IsMatchTest()
        {
            {
                FilterBase f1 = new FacilityEqualsFilter
                {
                    facility = SyslogFacility.Ftp
                },
                           f2 = new MessageRegexMatchFilter
                {
                    pattern = "^FFDA"
                };

                OrFilter target = new OrFilter();
                target.filter = new FilterBase[] { f1, f2 };


                SyslogMessage message = new SyslogMessage
                {
                    Facility = SyslogFacility.Internally,
                    Severity = SyslogSeverity.Error,
                    Text     = "FFDA WOW!"
                };


                bool expected = true;
                bool actual;
                actual = target.IsMatch(message);
                Assert.AreEqual(expected, actual);
            }

            {
                FilterBase f1 = new FacilityEqualsFilter
                {
                    facility = SyslogFacility.Ftp
                },
                           f2 = new MessageRegexMatchFilter
                {
                    pattern = "^FFDA"
                };

                OrFilter target = new OrFilter();
                target.filter = new FilterBase[] { f1, f2 };


                SyslogMessage message = new SyslogMessage
                {
                    Facility = SyslogFacility.Ftp,
                    Severity = SyslogSeverity.Error,
                    Text     = "Nobody!"
                };


                bool expected = true;
                bool actual;
                actual = target.IsMatch(message);
                Assert.AreEqual(expected, actual);
            }

            {
                string msg =
                    @"<34>1 2003-10-11T22:14:15.003Z mymachine.example.com su - ID47 - ’su root’ failed for lonvick on /dev/pts/8";
                FilterBase f1 = new FacilityEqualsFilter
                {
                    facility = SyslogFacility.Security
                },
                           f2 = new MessageRegexMatchFilter
                {
                    //Ok, that should be the real UNIX user pattern but let's assume only letters and numbers here :)
                    pattern = "’su root’ failed for [a-zA-Z0-9]"
                },
                           f3 = new SeverityFilter
                {
                    comparison = ComparisonOperator.neq,
                    severity   = SyslogSeverity.Emergency
                };

                OrFilter target = new OrFilter();
                target.filter = new FilterBase[] { f1, f2, f3 };


                SyslogMessage message = SyslogMessage.Parse(msg);


                bool expected = true;
                bool actual;
                actual = target.IsMatch(message);
                Assert.AreEqual(expected, actual);
            }
        }
Exemple #13
0
        static void Main(string[] args)
        {
            try
            {
                // Devi passare un argomento...
                if (args.Length != 1)
                {
                    Console.WriteLine("Usage: Syslog2Csv.exe filepath(or wildcard expression)");
                    Environment.Exit(1);
                }

                // Capisce il percorso e le eventuali espressioni wildcard...
                String path     = Path.GetDirectoryName(args[0]);
                String filename = Path.GetFileName(args[0]);
                if (String.IsNullOrEmpty(path) || String.IsNullOrEmpty(filename))
                {
                    return;
                }

                // Legge tutti i file di log passati:
                String[]             files = Directory.GetFiles(path, filename);
                List <SyslogMessage> list  = new List <SyslogMessage>();
                for (int i = 0; i < files.Length; i++)
                {
                    TextReader tr  = File.OpenText(Path.Combine(path, files[i]));
                    String     tmp = tr.ReadLine();
                    while (tmp != null)
                    {
                        list.Add(SyslogMessage.Parse(tmp));
                        tmp = tr.ReadLine();
                    }
                    tr.Close();
                }

                // Crea il file Csv a partire dalla lista caricata...
                if (File.Exists(OUTPUT_FILE))
                {
                    File.Delete(OUTPUT_FILE);
                }
                TextWriter tw = File.CreateText(OUTPUT_FILE);
                tw.WriteLine(@"Id;UtcTimestamp;Host;RTT");
                long index = 0, lost = 0;
                foreach (SyslogMessage message in list)
                {
                    if (message.Severity == SyslogSeverity.Debug)
                    {
                        try
                        {
                            double rtt = double.Parse(message.Text.Split(' ')[1], NumberStyles.Float,
                                                      CultureInfo.InvariantCulture);
                            String row = String.Join(";", new string[]
                            {
                                index.ToString(),
                                message.Timestamp.ToString(),
                                message.Host,
                                rtt.ToString("f3", CultureInfo.InvariantCulture)
                            });
                            index++;
                            tw.WriteLine(row);
                        }
                        catch (FormatException)
                        {
                            continue;
                        }
                        catch (IndexOutOfRangeException)
                        {
                            continue;
                        }
                    }
                    else if (message.Severity == SyslogSeverity.Warning)
                    {
                        if (message.Text.Contains("lost"))
                        {
                            lost++;
                        }
                        else if (message.Text.Contains("dropped"))
                        {
                            lost--;
                        }
                    }
                }
                tw.Close();
                Console.WriteLine("There were {0} messages lost complexively", lost);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Environment.Exit(1);
            }
        }
        /// <summary>
        /// Threads spawned after connection use this loop
        /// </summary>
        /// <param name="clientObj"></param>
        private void ProcessClient(object clientObj)
        {
            using (TcpClient client = (TcpClient)clientObj)
            {
                lock (_clients)
                    _clients.Add(client);

                // A client has connected. Create the
                // SslStream using the client's network stream.

                using (SslStream sslStream = new SslStream(client.GetStream(), false))
                    // Authenticate the server but don't require the client to authenticate.
                    try
                    {
                        sslStream.AuthenticateAsServer(Certificate, false, SslProtocols.Tls, true);

                        sslStream.ReadTimeout = 3600000; //1 hour


                        while (true)
                        {
                            StringBuilder sb = new StringBuilder();
                            do
                            {
                                char nextChar = (char)sslStream.ReadByte();
                                if (char.IsDigit(nextChar))
                                {
                                    sb.Append(nextChar);
                                }
                                else if (nextChar == ' ')
                                {
                                    break;
                                }
                                else
                                {
                                    throw new FormatException("Invalid TLS encoding of Syslog message");
                                }
                            } while (true);

                            int charLen = int.Parse(sb.ToString(), CultureInfo.InvariantCulture);
                            if (charLen == 0)
                            {
                                throw new FormatException("Syslog messages cannot have length of zero");
                            }

                            int    offset = 0, left = charLen;
                            byte[] buffer = new byte[charLen];
                            do
                            {
                                int read = sslStream.Read(buffer, offset, left);
                                offset += read;
                                left   -= read;
                            } while (left > 0);

                            SyslogMessage message;
                            try
                            {
                                message = SyslogMessage.Parse(buffer);
                            }
                            catch (FormatException ex)
                            {
                                //Failed to parse Syslog message
                                OnParseError(new ParseErrorEventArgs(buffer, ex, false));

                                //Try again
                                continue;
                            }
                            ForwardMessage(message);
                        }
                    }
                    catch (SocketException) { }
                catch (Exception ex)
                {
                    OnError(new UnhandledExceptionEventArgs(ex, true));

                    Log.Error("Error occurred during TLS conversation in channel {0}", ToString());
                    Log.Debug("Error details: {0}", ex.Message);
                }
                finally
                {
                    lock (_clients) _clients.Remove(client);
                }
            }
        }
Exemple #15
0
        /// <summary>
        /// Start the listener
        /// </summary>
        /// <param name="bind"></param>
        public void Start(Configuration.EndpointConfiguration config)
        {
            this.m_udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            this.m_udpSocket.DontFragment = true;
            this.m_configuration          = config;

            // Get the IP address
            IPEndPoint endpoint = null;

            if (config.Address.HostNameType == UriHostNameType.Dns)
            {
                endpoint = new IPEndPoint(Dns.GetHostEntry(config.Address.Host).AddressList[0], config.Address.Port);
            }
            else
            {
                endpoint = new IPEndPoint(IPAddress.Parse(config.Address.Host), config.Address.Port);
            }

            // Bind the socket
            this.m_udpSocket.Bind(endpoint);
            this.m_traceSource.TraceInfo("UDP transport bound to {0}", endpoint);

            // Run
            try
            {
                while (this.m_run)
                {
                    EndPoint remote_ep = new IPEndPoint(IPAddress.Any, 0);

                    try
                    {
                        Byte[] udpMessage = new Byte[this.m_configuration.MaxSize];

                        //bytesReceived = udpSocket.Receive(udpMessage);
                        int bytesReceived = this.m_udpSocket.ReceiveFrom(udpMessage, ref remote_ep);

                        IPEndPoint ipep  = (IPEndPoint)remote_ep;
                        IPAddress  ipadd = ipep.Address;

                        // Parse
                        String udpMessageStr = System.Text.Encoding.UTF8.GetString(udpMessage).TrimEnd('\0');
                        var    message       = SyslogMessage.Parse(udpMessageStr, Guid.NewGuid());
                        if (this.MessageReceived != null)
                        {
                            this.MessageReceived.BeginInvoke(this, new SyslogMessageReceivedEventArgs(message, new Uri(String.Format("udp://{0}", remote_ep)), this.m_configuration.Address, DateTime.Now), null, null);
                        }
                    }
                    catch (SyslogMessageException e)
                    {
                        if (this.InvalidMessageReceived != null)
                        {
                            this.InvalidMessageReceived.BeginInvoke(this, new SyslogMessageReceivedEventArgs(e.FaultingMessage, new Uri(String.Format("udp://{0}", remote_ep)), this.m_configuration.Address, DateTime.Now), null, null);
                        }
                        this.m_traceSource.TraceError(e.ToString());
                    }
                    catch (Exception e)
                    {
                        if (this.InvalidMessageReceived != null)
                        {
                            this.InvalidMessageReceived.BeginInvoke(this, new SyslogMessageReceivedEventArgs(new SyslogMessage(), new Uri(String.Format("udp://{0}", remote_ep)), this.m_configuration.Address, DateTime.Now), null, null);
                        }
                        this.m_traceSource.TraceError(e.ToString());
                    }
                }
            }
            finally
            {
                this.m_udpSocket.Dispose();
            }
        }
        public void ParseTest()
        {
            string payload = @"<34>1 2003-10-11T22:14:15.003Z mymachine.example.com su - ID47 - ’su root’ failed for lonvick on /dev/pts/8";


            SyslogMessage expected = new SyslogMessage
            {
                Facility        = SyslogFacility.Security,
                Severity        = SyslogSeverity.Critical,
                Timestamp       = new DateTime(2003, 10, 11, 22, 14, 15, 3),
                Host            = "mymachine.example.com",
                ApplicationName = "su",
                ProcessID       = null,
                MessageId       = "ID47",
                Text            = @"’su root’ failed for lonvick on /dev/pts/8"
            };                              // TODO: Eseguire l'inizializzazione a un valore appropriato

            SyslogMessage actual = null;

            try
            {
                actual = SyslogMessage.Parse(payload);
            }
            catch (FormatException ex)
            {
                Assert.Fail("Failed parsing: {0}", ex);
            }

            Assert.IsNotNull(actual);
            Assert.AreEqual(expected, actual);

            payload  = @"<165>1 2003-08-24T05:14:15.000003-07:00 192.0.2.1 myproc 8710 - - %% It’s time to make the do-nuts.";
            expected = new SyslogMessage
            {
                Facility        = SyslogFacility.Local4,
                Severity        = SyslogSeverity.Notice,
                Timestamp       = new DateTime(2003, 08, 23, 22, 14, 15, 0),
                Host            = "192.0.2.1",
                ApplicationName = "myproc",
                ProcessID       = "8710",
                MessageId       = null,
                Text            = @"%% It’s time to make the do-nuts."
            };

            actual = null;

            try
            {
                actual = SyslogMessage.Parse(payload);
            }
            catch (FormatException ex)
            {
                Assert.Fail("Failed parsing", ex);
            }
            Assert.IsNotNull(actual);
            Assert.AreEqual(expected, actual);

            payload = @"<165>1 2003-10-11T22:14:15.003Z mymachine.example.com evntslog - ID47 [exampleSDID@32473 iut=""3"" eventSource=""Application"" eventID=""1011""] An application event log entry...";
            actual  = null;

            try
            {
                actual = SyslogMessage.Parse(payload);
            }
            catch (FormatException ex)
            {
                Assert.Fail("Failed parsing: {0}", ex);
            }
            Assert.IsNotNull(actual);

            payload = @"<165>1 2003-10-11T22:14:15.003Z mymachine.example.com evntslog - ID47 [exampleSDID@32473 iut=""3"" eventSource=""Application"" eventID=""1011""][examplePriority@32473 class=""high""]";
            actual  = null;

            try
            {
                actual = SyslogMessage.Parse(payload);
            }
            catch (FormatException ex)
            {
                Assert.Fail("Failed parsing: {0}", ex);
            }
            Assert.IsNotNull(actual);

            // Test del formato 3164 BSD.....
            payload  = @"<43>Jun 27 23:43:47 marcus syslog-ng[21655]: Connection broken to AF_INET(127.0.0.1:3588), reopening in 60 seconds";
            expected = new SyslogMessage
            {
                Facility        = SyslogFacility.Internally,
                Severity        = SyslogSeverity.Error,
                Timestamp       = new DateTime(2010, 6, 27, 23, 43, 47, 0),
                Host            = "marcus",
                ApplicationName = "syslog-ng",
                ProcessID       = "21655",
                MessageId       = null,
                Text            = @"Connection broken to AF_INET(127.0.0.1:3588), reopening in 60 seconds"
            };
            actual = null;

            try
            {
                actual = SyslogMessage.Parse(payload);
            }
            catch (FormatException ex)
            {
                Assert.Fail("Failed parsing", ex);
            }
            Assert.IsNotNull(actual);
            Assert.AreEqual(expected, actual);

            //Testing with escape sequences in Data
            //RFC says that '"' and ']' in structured data values must be escaped
            payload = @"<165>1 2003-10-11T22:14:15.003Z mymachine.example.com evntslog - ID47 [exampleSDID@32473 escapeParentesis=""Wow\]"" escapeQuotes=""\"""" moreEscape=""\\\\\\\""""] Now it works....";

            actual = null;

            try
            {
                actual = SyslogMessage.Parse(payload);
            }
            catch (FormatException ex)
            {
                Assert.Fail("Failed parsing: {0}", ex);
            }
            Assert.IsNotNull(actual);
            IDictionary <String, String> test = actual.Data["exampleSDID@32473"];

            Assert.AreEqual("Wow\\]", test["escapeParentesis"]);
            Assert.AreEqual("\\\"", test["escapeQuotes"]);
            Assert.AreEqual("\\\\\\\\\\\\\\\"", test["moreEscape"]);

            /*
             * //Testing with spaces and equals in Data
             * payload = @"<165>1 2003-10-11T22:14:15.003Z mymachine.example.com evntslog - ID47 [exampleSDID@32473 Space=""Wow "" Equal=""a=1"" SpaceAndEquals=""---== ""] I don't think the current parser will accept this message";
             *
             * actual = null;
             *
             * try
             * {
             *  actual = SyslogMessage.Parse(payload);
             * }
             * catch (FormatException ex)
             * {
             *  Assert.Fail("Failed parsing: {0}", ex);
             * }
             * Assert.IsNotNull(actual);
             * test = actual.Value.Data["exampleSDID@32473"];
             * Assert.AreEqual("\"Wow \"", test["Space"]);
             * Assert.AreEqual("\"a=1\"", test["Equal"]);
             * Assert.AreEqual("\"---== \"", test["SpaceAndEquals"]);
             */

            /*Testing a message generated by Log4net SyslogAppender with SimpleLayout
             * payload = @"<179>UnitTestAdapterDomain_ForC:\Users\DJ Echelon\Documents\Visual Studio 2008\Projects\Logbus-ng-core\TestResults\DJ Echelon_MONSTR 2010-07-03 19_09_28\Out\Log4test.dll: ERROR - Test error message";
             * actual = null;
             *
             * try
             * {
             *  actual = SyslogMessage.Parse(payload);
             * }
             * catch (FormatException ex)
             * {
             *  Assert.Fail("Failed parsing: {0}", ex);
             * }
             * Assert.IsNotNull(actual);
             */

            //Testing FFDA Message
            payload = @"<134>1 2010-07-13T04:56:38Z HYPERCUBE VSTestHost 3696 FFDA [CallerData@8289 ClassName=""System.RuntimeMethodHandle"" MethodName=""_InvokeMethodFast""] SST";

            actual = null;

            try
            {
                actual = SyslogMessage.Parse(payload);
            }
            catch (FormatException ex)
            {
                Assert.Fail("Failed parsing: {0}", ex);
            }
            Assert.IsNotNull(actual);
            test = actual.Data["CallerData@8289"];
            Assert.AreEqual("System.RuntimeMethodHandle", test["ClassName"]);
            Assert.AreEqual("_InvokeMethodFast", test["MethodName"]);
        }