Beispiel #1
0
        static System.Collections.Generic.IEnumerable <string> convertToSplunkList(string newClientContent, ILogger log)
        {
            foreach (var messageList in denormalizedSplunkEvents(newClientContent, null, log))
            {
                StringBuilder outgoingJson = StringBuilderPool.Allocate();
                outgoingJson.Capacity = MAXTRANSMISSIONSIZE;

                try
                {
                    foreach (var message in messageList)
                    {
                        var messageAsString = JsonConvert.SerializeObject(message, new JsonSerializerSettings
                        {
                            NullValueHandling = NullValueHandling.Ignore
                        });
                        outgoingJson.Append(messageAsString);
                    }
                    yield return(outgoingJson.ToString());
                }
                finally
                {
                    StringBuilderPool.Free(outgoingJson);
                }
            }
        }
        private static string Describe(ErrorResponseMessage errorMessage)
        {
            if (errorMessage.ErrorCount == 0)
            {
                return("Server returned an error with no description.");
            }

            var sb = StringBuilderPool.Get();

            try
            {
                for (var i = 0;
                     i < errorMessage.ErrorCount - 1;
                     ++i, sb.Append(", "))
                {
                    var error = errorMessage.Errors[i];

                    sb.Append(error.Value);
                }

                return(sb.ToString());
            }
            finally
            {
                StringBuilderPool.Free(ref sb);
            }
        }
Beispiel #3
0
        /// <summary>
        /// Returns a string representation for the given transponders.
        /// </summary>
        public static String ToString(IEnumerable <FeigTransponder> transponders)
        {
            if (transponders == null)
            {
                return(String.Empty);
            }

            StringBuilder?sb = null;

            try
            {
                sb = StringBuilderPool.Rent();

                var i = 0;

                foreach (var item in transponders)
                {
                    if (i++ > 0)
                    {
                        sb.Append(", ");
                    }

                    sb.Append("{ ");
                    sb.Append(item);
                    sb.Append(" }");
                }

                return(sb.ToString());
            }
            finally
            {
                StringBuilderPool.Free(sb);
            }
        }
Beispiel #4
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposed != null && !disposed.EnsureCalledOnce())
     {
         if (buffer != null)
         {
             StringBuilderPool.Free(buffer);
             buffer = null;
         }
     }
 }
Beispiel #5
0
        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (buffer != null)
                {
                    StringBuilderPool.Free(buffer);
                    buffer = null;
                }

                disposed = true;
            }
        }
Beispiel #6
0
        /// <summary>
        /// Returns a string that represents the current instance.
        /// </summary>
        public override String ToString()
        {
            StringBuilder?sb = null;

            try
            {
                sb = StringBuilderPool.Rent();

                sb.Append("Type: ");
                sb.Append(TransponderType);
                sb.Append(", ID: ");
                sb.Append(Identifier);

                return(sb.ToString());
            }
            finally
            {
                StringBuilderPool.Free(sb);
            }
        }
Beispiel #7
0
        /// <summary>
        /// Returns a string that represents the current instance.
        /// </summary>
        public override String ToString()
        {
            StringBuilder?sb = null;

            try
            {
                sb = StringBuilderPool.Rent();

                sb.Append("Status: ");
                sb.Append(Status);
                sb.Append(", Response: { ");
                sb.Append(Response?.ToString() ?? "<null>");
                sb.Append(" }");

                return(sb.ToString());
            }
            finally
            {
                StringBuilderPool.Free(sb);
            }
        }
        /// <summary>
        /// Returns a string that represents the current instance.
        /// </summary>
        public override String ToString()
        {
            StringBuilder?sb = null;

            try
            {
                sb = StringBuilderPool.Rent();

                sb.Append("Address: ");
                sb.Append(Address);
                sb.Append(", Command: ");
                sb.Append(Command);
                sb.Append(", Data: ");
                sb.Append(Data);

                return(sb.ToString());
            }
            finally
            {
                StringBuilderPool.Free(sb);
            }
        }
Beispiel #9
0
    public int AppendToTransmission(ref byte[] transmission, int maxSize, int offset)
    {
        StringBuilder sb       = StringBuilderPool.Allocate();
        var           bytePool = ArrayPool <byte> .Shared;

        byte[] buffer        = bytePool.Rent((int)1000);
        byte[] crlf          = new Byte[] { 0x0D, 0x0A };
        int    bytesToAppend = 0;

        try
        {
            BuildCEF(ref sb);

            string s = sb.ToString();
            bytesToAppend += s.Length + 2;

            if (maxSize > offset + bytesToAppend)
            {
                Buffer.BlockCopy(Encoding.ASCII.GetBytes(s), 0, buffer, 0, s.Length);
                Buffer.BlockCopy(crlf, 0, buffer, s.Length, 2);

                Buffer.BlockCopy(buffer, 0, transmission, offset, bytesToAppend);
            }
            else
            {
                throw new System.IO.InternalBufferOverflowException("ArcSight transmission buffer overflow");
            }
        }
        finally
        {
            StringBuilderPool.Free(sb);
            bytePool.Return(buffer);
        }

        return(bytesToAppend);
    }
Beispiel #10
0
    private string MakeMAC()
    {
        StringBuilder sb           = StringBuilderPool.Allocate();
        string        delimitedMac = "";

        try
        {
            sb.Append(mac.Substring(0, 2)).Append(":");
            sb.Append(mac.Substring(2, 2)).Append(":");
            sb.Append(mac.Substring(4, 2)).Append(":");
            sb.Append(mac.Substring(6, 2)).Append(":");
            sb.Append(mac.Substring(8, 2)).Append(":");
            sb.Append(mac.Substring(10, 2));

            delimitedMac = sb.ToString();
        }
        finally
        {
            StringBuilderPool.Free(sb);
        }


        return(delimitedMac);
    }
        /// <summary>
        /// Returns a string that represents the current instance.
        /// </summary>
        public override String ToString()
        {
            StringBuilder?sb = null;

            try
            {
                sb = StringBuilderPool.Rent();

                sb.Append("FirmwareVersion: ");
                sb.Append(FirmwareVersion);
                sb.Append(", HardwareType: 0x");
                sb.Append(HardwareType.ToString("X2", CultureInfo.InvariantCulture));
                sb.Append(", ReaderType: ");
                sb.Append(ReaderType);
                sb.Append(", SupportedTransponders: 0x");
                sb.Append(SupportedTransponders.ToString("X4", CultureInfo.InvariantCulture));

                return(sb.ToString());
            }
            finally
            {
                StringBuilderPool.Free(sb);
            }
        }
        /// <summary>
        /// Returns a string that represents the current instance.
        /// </summary>
        public override String ToString()
        {
            StringBuilder?sb = null;

            try
            {
                sb = StringBuilderPool.Rent();

                sb.Append("Transport: '");
                sb.Append(TransportSettings);
                sb.Append("', Address: ");
                sb.Append(Address);
                sb.Append(", Timeout: ");
                sb.Append(Timeout.TotalMilliseconds);
                sb.Append(" ms, Protocol: ");
                sb.Append(Protocol);

                return(sb.ToString());
            }
            finally
            {
                StringBuilderPool.Free(sb);
            }
        }
        internal static FileHeader ParseFileHeader(SyntaxNode root)
        {
            var firstToken = root.GetFirstToken(includeZeroWidth: true);
            var firstNonWhitespaceTrivia = TriviaHelper.IndexOfFirstNonWhitespaceTrivia(firstToken.LeadingTrivia, true);

            if (firstNonWhitespaceTrivia == -1)
            {
                return(FileHeader.MissingFileHeader);
            }

            var sb              = StringBuilderPool.Allocate();
            var endOfLineCount  = 0;
            var done            = false;
            var fileHeaderStart = int.MaxValue;
            var fileHeaderEnd   = int.MinValue;

            for (var i = firstNonWhitespaceTrivia; !done && (i < firstToken.LeadingTrivia.Count); i++)
            {
                var trivia = firstToken.LeadingTrivia[i];

                switch (trivia.Kind())
                {
                case SyntaxKind.WhitespaceTrivia:
                    endOfLineCount = 0;
                    break;

                case SyntaxKind.SingleLineCommentTrivia:
                    endOfLineCount = 0;

                    var commentString = trivia.ToFullString();

                    fileHeaderStart = Math.Min(trivia.FullSpan.Start, fileHeaderStart);
                    fileHeaderEnd   = trivia.FullSpan.End;

                    sb.AppendLine(commentString.Substring(2).Trim());
                    break;

                case SyntaxKind.MultiLineCommentTrivia:
                    // only process a MultiLineCommentTrivia if no SingleLineCommentTrivia have been processed
                    if (sb.Length == 0)
                    {
                        var triviaString = trivia.ToFullString();

                        var startIndex = triviaString.IndexOf("/*", StringComparison.Ordinal) + 2;
                        var endIndex   = triviaString.LastIndexOf("*/", StringComparison.Ordinal);
                        if (endIndex == -1)
                        {
                            // While editing, it is possible to have a multiline comment trivia that does not contain the closing '*/' yet.
                            return(FileHeader.MissingFileHeader);
                        }

                        var commentContext = triviaString.Substring(startIndex, endIndex - startIndex).Trim();

                        var triviaStringParts = commentContext.Replace("\r\n", "\n").Split('\n');

                        foreach (var part in triviaStringParts)
                        {
                            var trimmedPart = part.TrimStart(' ', '*');
                            sb.AppendLine(trimmedPart);
                        }

                        fileHeaderStart = trivia.FullSpan.Start;
                        fileHeaderEnd   = trivia.FullSpan.End;
                    }

                    done = true;
                    break;

                case SyntaxKind.EndOfLineTrivia:
                    endOfLineCount++;
                    done = endOfLineCount > 1;
                    break;

                default:
                    done = (fileHeaderStart < fileHeaderEnd) || !trivia.IsDirective;
                    break;
                }
            }

            if (fileHeaderStart > fileHeaderEnd)
            {
                StringBuilderPool.Free(sb);
                return(FileHeader.MissingFileHeader);
            }

            if (sb.Length > 0)
            {
                // remove the final newline
                var eolLength = Environment.NewLine.Length;
                sb.Remove(sb.Length - eolLength, eolLength);
            }

            return(new FileHeader(StringBuilderPool.ReturnAndFree(sb), fileHeaderStart, fileHeaderEnd));
        }
Beispiel #14
0
        public static async Task <int> SendMessagesDownstreamAsync(string nsgMessagesString, ExecutionContext executionContext, Binder cefLogBinder, ILogger log)
        {
            //
            // nsgMessagesString looks like this:
            //
            // ,{...}  <-- note leading comma
            // ,{...}
            //  ...
            // ,{...}
            //
            // - OR -
            //
            // {...}   <-- note lack of leading comma
            // ,{...}
            //  ...
            // ,{...}
            //
            string outputBinding = Util.GetEnvironmentVariable("outputBinding");

            if (outputBinding.Length == 0)
            {
                log.LogError("Value for outputBinding is required. Permitted values are: 'arcsight', 'splunk', 'eventhub'.");
                return(0);
            }

            // skip past the leading comma
            //string trimmedMessages = nsgMessagesString.Trim();
            //int curlyBrace = trimmedMessages.IndexOf('{');
            //string newClientContent = "{\"records\":[";
            //newClientContent += trimmedMessages.Substring(curlyBrace);
            //newClientContent += "]}";

            StringBuilder sb = StringBuilderPool.Allocate();
            string        newClientContent = "";

            try
            {
                sb.Append("{\"records\":[").Append(nsgMessagesString).Append("]}");
                newClientContent = sb.ToString();
            }
            finally
            {
                StringBuilderPool.Free(sb);
            }

            //
            // newClientContent looks like this:
            // {
            //   "records":[
            //     {...},
            //     {...}
            //     ...
            //   ]
            // }
            //

            string  logIncomingJSON = Util.GetEnvironmentVariable("logIncomingJSON");
            Boolean flag;

            if (Boolean.TryParse(logIncomingJSON, out flag))
            {
                if (flag)
                {
                    Util.logIncomingRecord(newClientContent, cefLogBinder, log).Wait();
                }
            }

            int bytesSent = 0;

            switch (outputBinding)
            {
            //case "logstash":
            //    await Util.obLogstash(newClientContent, log);
            //    break;
            case "arcsight":
                bytesSent = await Util.obArcsightNew(newClientContent, executionContext, cefLogBinder, log);

                break;

            case "splunk":
                bytesSent = await Util.obSplunk(newClientContent, log);

                break;

            case "eventhub":
                bytesSent = await Util.obEventHub(newClientContent, log);

                break;
            }
            return(bytesSent);
        }
        public static unsafe IReadOnlyList <string> Perform(
            IReadOnlyList <PostgresPropertySetting> settings,
            PostgresCommand command)
        {
            var parameters = command.Parameters;
            var sql        = command.CommandText;

            if (sql == null)
            {
                return(EmptyList <string> .Value);
            }

            DemandStandardSettings(settings);

            var queries  = new List <string>();
            var sb       = StringBuilderPool.Get(sql.Length);
            var lastChar = '\0';

            fixed(char *sqlPtr = sql)
            for (var i = 0; i < sql.Length; ++i)
            {
                var chr     = sqlPtr[i];
                var nextChr = i == sql.Length - 1 ? '\0' : sqlPtr[i + 1];

                switch (chr)
                {
                // Handle strings made with quotes, 'foo' and E'foo'
                case '\'':
                    var escapedQuotes = lastChar == 'E';

                    sb.Append(chr);
                    lastChar = '\0';

                    for (++i; i < sql.Length; ++i)
                    {
                        chr = sqlPtr[i];
                        sb.Append(chr);

                        // Quotes (chr == '\'') can be inside a string
                        // in several ways:
                        // * If they're doubled up.
                        // * If we're inside an escape string escaped
                        //   with a backslash.
                        if (chr == '\'' && lastChar != '\'' &&
                            !(escapedQuotes && lastChar == '\\'))
                        {
                            goto next;
                        }

                        lastChar = chr;
                    }

                    continue;

                // Handle dollar strings, $$foo$$ and $bar$foo$bar$
                case '$':
                    var k = i + 1;

                    // Syntax is "$abc$" or "$$", if "named" then "a"
                    // must be a letter. bc+ can be letter or digit.
                    // But "$5" is also valid syntax for parameter
                    // access, so we must respect those.

                    if (k >= sql.Length)
                    {
                        goto default;
                    }

                    var chrK = sqlPtr[k];

                    if (chrK == '$')
                    {
                        var indexOf = sql.IndexOf("$$", k,
                                                  StringComparison.Ordinal);

                        // Really... it's invalid syntax.
                        if (indexOf == -1)
                        {
                            goto default;
                        }

                        // 2 is length of "$$"
                        sb.Append(sql, i, indexOf - i + 2);

                        i = indexOf + 1;
                        goto next;
                    }

                    if (!char.IsLetter(chrK))
                    {
                        goto default;
                    }

                    sb.Append('$');
                    sb.Append(chrK);

                    for (++k; k < sql.Length; ++k)
                    {
                        chrK = sqlPtr[k];
                        sb.Append(chrK);
                        if (chrK == '$')
                        {
                            break;
                        }
                        if (!char.IsLetterOrDigit(chrK))
                        {
                            goto default;
                        }
                    }

                    // +1 to account for final $.
                    ++k;

                    var namedStringStart = i;
                    var matchIndex       = namedStringStart;
                    var matchedCount     = 0;
                    var matchLength      = k - namedStringStart;

                    for (i = k; i < sql.Length; ++i)
                    {
                        for (var m = i; m < sql.Length; ++m, ++matchIndex)
                        {
                            chr = sqlPtr[m];

                            sb.Append(chr);
                            lastChar = chr;

                            if (chr != sqlPtr[matchIndex])
                            {
                                i            = m;
                                matchedCount = 0;
                                matchIndex   = namedStringStart;
                                break;
                            }

                            if (++matchedCount == matchLength)
                            {
                                i = m;
                                // Match success.
                                goto next;
                            }
                        }
                    }

                    // If we enumerate the entire string and do not
                    // find a match, it's technically invalid syntax
                    // but that's the user's problem. They're better
                    // off getting the actual error from postgres.

                    continue;

                // Handle @@NotNamedParameter
                case '@' when nextChr == '@':
                    // Append and fast forward past next one.
                    sb.Append(chr);
                    ++i;
                    lastChar = '\0';
                    continue;

                // Handle @NamedParameter
                case '@':
                    var start = i + 1;

                    var offset = 0;
                    for (i = start; i < sql.Length; ++i)
                    {
                        if (!char.IsLetterOrDigit(sqlPtr[i]))
                        {
                            --i;
                            offset = 1;
                            break;
                        }
                    }

                    var name       = sql.Substring(start, i - start + offset);
                    var paramIndex = parameters.IndexOf(name);

                    if (paramIndex == -1)
                    {
                        throw new ArgumentOutOfRangeException(
                                  "parameterName", name,
                                  "Parameter inside query was not found inside parameter list.");
                    }

                    sb.Append('$');
                    sb.Append(paramIndex + 1);
                    lastChar = '\0';
                    continue;

                // Handle -- quotes.
                case '-' when lastChar == '-':
                    sb.Append(chr);
                    lastChar = '\0';

                    for (++i; i < sql.Length; ++i)
                    {
                        chr = sqlPtr[i];

                        sb.Append(chr);
                        lastChar = chr;

                        if (chr == '\n')
                        {
                            break;
                        }
                    }
                    continue;

                // Handle /* */ quotes.
                case '*' when lastChar == '/':
                    if (i == sql.Length - 1)
                    {
                        goto default;
                    }

                    var indexOfComment = sql.IndexOf("*/", i + 1);

                    // Really... it's invalid syntax.
                    if (indexOfComment == -1)
                    {
                        goto default;
                    }

                    // 2 is length of "*/"
                    sb.Append(sql, i, indexOfComment - i + 2);

                    i = indexOfComment + 1;
                    continue;

                case ';':
                    var singleSqlCommand = sb.ToStringTrim();
                    sb.Clear();

                    if (!string.IsNullOrWhiteSpace(singleSqlCommand))
                    {
                        queries.Add(singleSqlCommand);
                    }

                    continue;

                default:
                    sb.Append(chr);
                    lastChar = chr;
                    continue;
                }

                next :;
            }

            if (sb.Length > 0)
            {
                var singleSqlCommand = sb.ToStringTrim();

                if (!string.IsNullOrWhiteSpace(singleSqlCommand))
                {
                    queries.Add(singleSqlCommand);
                }
            }

            StringBuilderPool.Free(ref sb);
            return(queries);
        }
Beispiel #16
0
        public static async Task <int> SendMessagesDownstreamAsync(string nsgMessagesString, ExecutionContext executionContext, Binder cefLogBinder, ILogger log)
        {
            string outputBinding = Util.GetEnvironmentVariable("outputBinding");

            if (outputBinding.Length == 0)
            {
                log.LogError("Value for outputBinding is required. Permitted values are: 'arcsight', 'splunk', 'eventhub', 'loganalytics'.");
                return(0);
            }


            StringBuilder sb = StringBuilderPool.Allocate();
            string        newClientContent = "";

            try
            {
                sb.Append("{\"records\":[").Append(nsgMessagesString).Append("]}");
                newClientContent = sb.ToString();
            }
            finally
            {
                StringBuilderPool.Free(sb);
            }

            string  logIncomingJSON = Util.GetEnvironmentVariable("logIncomingJSON");
            Boolean flag;

            if (Boolean.TryParse(logIncomingJSON, out flag))
            {
                if (flag)
                {
                    Util.logIncomingRecord(newClientContent, cefLogBinder, log).Wait();
                }
            }

            int bytesSent = 0;

            switch (outputBinding)
            {
            //case "logstash":
            //    await Util.obLogstash(newClientContent, log);
            //    break;
            case "arcsight":
                bytesSent = await Util.obArcsightNew(newClientContent, executionContext, cefLogBinder, log);

                break;

            case "splunk":
                bytesSent = await Util.obSplunk(newClientContent, log);

                break;

            case "eventhub":
                bytesSent = await Util.obEventHub(newClientContent, log);

                break;

            case "loganalytics":
                bytesSent = await Util.obLogAnalytics(newClientContent, log);

                break;
            }
            return(bytesSent);
        }