private ReadLineStepResult ReadLineStep(ref StringBuilder?sb, ref bool consumeLineFeed) { const char carriageReturn = '\r'; const char lineFeed = '\n'; if (consumeLineFeed) { if (_charBuffer[_charBufferIndex] == lineFeed) { _charBufferIndex++; } return(ReadLineStepResult.Done); } var span = new Span <char>(_charBuffer, _charBufferIndex, _charsRead - _charBufferIndex); var index = span.IndexOfAny(carriageReturn, lineFeed); if (index != -1) { if (span[index] == carriageReturn) { span = span.Slice(0, index); _charBufferIndex += index + 1; if (_charBufferIndex < _charsRead) { // consume following line feed if (_charBuffer[_charBufferIndex] == lineFeed) { _charBufferIndex++; } if (sb != null) { sb.Append(span); return(ReadLineStepResult.Done); } // perf: if the new line is found in first pass, we skip the StringBuilder return(ReadLineStepResult.FromResult(span.ToString())); } // we where at the end of buffer, we need to read more to check for a line feed to consume sb ??= new StringBuilder(); sb.Append(span); consumeLineFeed = true; return(ReadLineStepResult.Continue); } if (span[index] == lineFeed) { span = span.Slice(0, index); _charBufferIndex += index + 1; if (sb != null) { sb.Append(span); return(ReadLineStepResult.Done); } // perf: if the new line is found in first pass, we skip the StringBuilder return(ReadLineStepResult.FromResult(span.ToString())); } } sb ??= new StringBuilder(); sb.Append(span); _charBufferIndex = _charsRead; return(ReadLineStepResult.Continue); }
// true -> done processing // false -> need more input private bool ProcessInput(MemoryStream ms) { byte[] buffer = ms.GetBuffer(); int len = (int)ms.Length; int used = 0; string?line; while (true) { if (_context.HaveError) { return(true); } if (_position >= len) { break; } try { line = ReadLine(buffer, _position, len - _position, ref used); _position += used; } catch { _context.ErrorMessage = HttpStatusDescription.Get(400) !; _context.ErrorStatus = 400; return(true); } if (line == null) { break; } if (line == "") { if (_inputState == InputState.RequestLine) { continue; } _currentLine = null; return(true); } if (_inputState == InputState.RequestLine) { _context.Request.SetRequestLine(line); _inputState = InputState.Headers; } else { try { _context.Request.AddHeader(line); } catch (Exception e) { _context.ErrorMessage = e.Message; _context.ErrorStatus = 400; return(true); } } } if (used == len) { ms.SetLength(0); _position = 0; } return(false); }
// String escaping implementation forked from System.Runtime.Serialization.Json to // avoid a large dependency graph for this small amount of code: // // https://github.com/dotnet/corefx/blob/master/src/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JavaScriptString.cs // private static string EscapeString(string value) { StringBuilder?b = null; if (string.IsNullOrEmpty(value)) { return(string.Empty); } int startIndex = 0; int count = 0; for (int i = 0; i < value.Length; i++) { char c = value[i]; if (c == '\"' || c == '\\' || ShouldAppendAsUnicode(c)) { if (b == null) { b = new StringBuilder(); } if (count > 0) { b.Append(value, startIndex, count); } startIndex = i + 1; count = 0; } switch (c) { case '\"': b !.Append("\\\""); break; case '\\': b !.Append("\\\\"); break; default: if (ShouldAppendAsUnicode(c)) { AppendCharAsUnicode(b !, c); } else { count++; } break; } } if (b == null) { return(value); } if (count > 0) { b.Append(value, startIndex, count); } return(b.ToString()); }
internal static string?ReescapeWin32String(string?str) { // If we don't have data, then don't try anything if (str == null) { return(null); } StringBuilder?result = null; bool inQuote = false; for (int i = 0; i < str.Length; i++) { // Look for quote if (str[i] == '\'') { // Already in quote? if (inQuote) { // See another single quote. Is this '' of 'fred''s' or '''', or is it an ending quote? if (i + 1 < str.Length && str[i + 1] == '\'') { // Found another ', so we have ''. Need to add \' instead. // 1st make sure we have our stringbuilder if (result == null) { result = new StringBuilder(str, 0, i, str.Length * 2); } // Append a \' and keep going (so we don't turn off quote mode) result.Append("\\'"); i++; continue; } // Turning off quote mode, fall through to add it inQuote = false; } else { // Found beginning quote, fall through to add it inQuote = true; } } // Is there a single \ character? else if (str[i] == '\\') { // Found a \, need to change it to \\ // 1st make sure we have our stringbuilder if (result == null) { result = new StringBuilder(str, 0, i, str.Length * 2); } // Append our \\ to the string & continue result.Append("\\\\"); continue; } // If we have a builder we need to add our character if (result != null) { result.Append(str[i]); } } // Unchanged string? , just return input string if (result == null) { return(str); } // String changed, need to use the builder return(result.ToString()); }
// This is called by underlying base class code, each time a new response is received from the wire or a protocol stage is resumed. // This function controls the setting up of a data socket/connection, and of saving off the server responses. protected override PipelineInstruction PipelineCallback(PipelineEntry?entry, ResponseDescription?response, bool timeout, ref Stream?stream) { if (NetEventSource.Log.IsEnabled()) { NetEventSource.Info(this, $"Command:{entry?.Command} Description:{response?.StatusDescription}"); } // null response is not expected if (response == null) { return(PipelineInstruction.Abort); } FtpStatusCode status = (FtpStatusCode)response.Status; // // Update global "current status" for FtpWebRequest // if (status != FtpStatusCode.ClosingControl) { // A 221 status won't be reflected on the user FTP response // Anything else will (by design?) StatusCode = status; StatusLine = response.StatusDescription; } // If the status code is outside the range defined in RFC (1xx to 5xx) throw if (response.InvalidStatusCode) { throw new WebException(SR.net_InvalidStatusCode, WebExceptionStatus.ProtocolError); } // Update the banner message if any, this is a little hack because the "entry" param is null if (_index == -1) { if (status == FtpStatusCode.SendUserCommand) { _bannerMessage = new StringBuilder(); _bannerMessage.Append(StatusLine); return(PipelineInstruction.Advance); } else if (status == FtpStatusCode.ServiceTemporarilyNotAvailable) { return(PipelineInstruction.Reread); } else { throw GenerateException(status, response.StatusDescription, null); } } // // Check for the result of our attempt to use UTF8 // if (entry !.Command == "OPTS utf8 on\r\n") { if (response.PositiveCompletion) { Encoding = Encoding.UTF8; } else { Encoding = Encoding.Default; } return(PipelineInstruction.Advance); } // If we are already logged in and the server returns 530 then // the server does not support re-issuing a USER command, // tear down the connection and start all over again if (entry.Command.IndexOf("USER", StringComparison.Ordinal) != -1) { // The server may not require a password for this user, so bypass the password command if (status == FtpStatusCode.LoggedInProceed) { _loginState = FtpLoginState.LoggedIn; _index++; } } // // Throw on an error with possible recovery option // if (response.TransientFailure || response.PermanentFailure) { if (status == FtpStatusCode.ServiceNotAvailable) { MarkAsRecoverableFailure(); } throw GenerateException(status, response.StatusDescription, null); } if (_loginState != FtpLoginState.LoggedIn && entry.Command.IndexOf("PASS", StringComparison.Ordinal) != -1) { // Note the fact that we logged in if (status == FtpStatusCode.NeedLoginAccount || status == FtpStatusCode.LoggedInProceed) { _loginState = FtpLoginState.LoggedIn; } else { throw GenerateException(status, response.StatusDescription, null); } } // // Parse special cases // if (entry.HasFlag(PipelineEntryFlags.CreateDataConnection) && (response.PositiveCompletion || response.PositiveIntermediate)) { bool isSocketReady; PipelineInstruction result = QueueOrCreateDataConection(entry, response, timeout, ref stream, out isSocketReady); if (!isSocketReady) { return(result); } // otherwise we have a stream to create } // // This is part of the above case and it's all about giving data stream back // if (status == FtpStatusCode.OpeningData || status == FtpStatusCode.DataAlreadyOpen) { if (_dataSocket == null) { return(PipelineInstruction.Abort); } if (!entry.HasFlag(PipelineEntryFlags.GiveDataStream)) { _abortReason = SR.Format(SR.net_ftp_invalid_status_response, status, entry.Command); return(PipelineInstruction.Abort); } // Parse out the Content length, if we can TryUpdateContentLength(response.StatusDescription !); // Parse out the file name, when it is returned and use it for our ResponseUri FtpWebRequest request = (FtpWebRequest)_request !; if (request.MethodInfo.ShouldParseForResponseUri) { TryUpdateResponseUri(response.StatusDescription !, request); } return(QueueOrCreateFtpDataStream(ref stream)); } // // Parse responses by status code exclusivelly // // Update welcome message if (status == FtpStatusCode.LoggedInProceed) { _welcomeMessage !.Append(StatusLine); } // OR set the user response ExitMessage else if (status == FtpStatusCode.ClosingControl) { _exitMessage !.Append(response.StatusDescription); // And close the control stream socket on "QUIT" CloseSocket(); } // OR set us up for SSL/TLS, after this we'll be writing securely else if (status == FtpStatusCode.ServerWantsSecureSession) { // If NetworkStream is a TlsStream, then this must be in the async callback // from completing the SSL handshake. // So just let the pipeline continue. if (!(NetworkStream is TlsStream)) { FtpWebRequest request = (FtpWebRequest)_request !; TlsStream tlsStream = new TlsStream(NetworkStream, Socket, request.RequestUri.Host, request.ClientCertificates); if (_isAsync) { tlsStream.BeginAuthenticateAsClient(ar => { try { tlsStream.EndAuthenticateAsClient(ar); NetworkStream = tlsStream; this.ContinueCommandPipeline(); } catch (Exception e) { this.CloseSocket(); this.InvokeRequestCallback(e); } }, null); return(PipelineInstruction.Pause); } else { tlsStream.AuthenticateAsClient(); NetworkStream = tlsStream; } } } // OR parse out the file size or file time, usually a result of sending SIZE/MDTM commands else if (status == FtpStatusCode.FileStatus) { if (entry.Command.StartsWith("SIZE ", StringComparison.Ordinal)) { _contentLength = GetContentLengthFrom213Response(response.StatusDescription !); } else if (entry.Command.StartsWith("MDTM ", StringComparison.Ordinal)) { _lastModified = GetLastModifiedFrom213Response(response.StatusDescription !); } } // OR parse out our login directory else if (status == FtpStatusCode.PathnameCreated) { if (entry.Command == "PWD\r\n" && !entry.HasFlag(PipelineEntryFlags.UserCommand)) { _loginDirectory = GetLoginDirectory(response.StatusDescription !); } } // Asserting we have some positive response else { // We only use CWD to reset ourselves back to the login directory. if (entry.Command.IndexOf("CWD", StringComparison.Ordinal) != -1) { _establishedServerDirectory = _requestedServerDirectory; } } // Intermediate responses require rereading if (response.PositiveIntermediate || (!UsingSecureStream && entry.Command == "AUTH TLS\r\n")) { return(PipelineInstruction.Reread); } return(PipelineInstruction.Advance); }
/// <summary>Writes a new JSON property with a string value (e.g. <c>"name": "value"</c>).</summary> /// <param name="writer">Writer to write the property to.</param> /// <param name="name">Name of the property to write.</param> /// <param name="value">Value of the property to write; can be null.</param> public static void WriteProperty(this IFastJsonWriter writer, string name, StringBuilder?value) { Argument.NotNull(nameof(writer), writer); writer.WritePropertyName(name); writer.WriteValue(value); }
public static string NormalizeSpace(string value) { StringBuilder?sb = null; int idx, idxStart = 0, idxSpace = 0; for (idx = 0; idx < value.Length; idx++) { if (XmlCharType.IsWhiteSpace(value[idx])) { if (idx == idxStart) { // Previous character was a whitespace character, so discard this character idxStart++; } else if (value[idx] != ' ' || idxSpace == idx) { // Space was previous character or this is a non-space character if (sb == null) { sb = new StringBuilder(value.Length); } else { sb.Append(' '); } // Copy non-space characters into string builder sb.Append(value, idxStart, idxSpace == idx ? idx - idxStart - 1 : idx - idxStart); idxStart = idx + 1; } else { // Single whitespace character doesn't cause normalization, but mark its position idxSpace = idx + 1; } } } if (sb == null) { // Check for string that is entirely composed of whitespace if (idxStart == idx) { return(string.Empty); } // If string does not end with a space, then it must already be normalized if (idxStart == 0 && idxSpace != idx) { return(value); } sb = new StringBuilder(value.Length); } else if (idx != idxStart) { sb.Append(' '); } // Copy non-space characters into string builder if (idxSpace == idx) { sb.Append(value, idxStart, idx - idxStart - 1); } else { sb.Append(value, idxStart, idx - idxStart); } return(sb.ToString()); }
private string?ReplaceNewLines(char[]?data, int offset, int len) { if (data == null) { return(null); } StringBuilder?sb = null; int start = offset; int endPos = offset + len; int i; for (i = offset; i < endPos; i++) { char ch; if ((ch = data[i]) >= 0x20) { continue; } if (ch == '\n') { if (_newLineChars == "\n") { continue; } if (sb == null) { sb = new StringBuilder(len + 5); } sb.Append(data, start, i - start); } else if (ch == '\r') { if (i + 1 < endPos && data[i + 1] == '\n') { if (_newLineChars == "\r\n") { i++; continue; } if (sb == null) { sb = new StringBuilder(len + 5); } sb.Append(data, start, i - start); i++; } else { if (_newLineChars == "\r") { continue; } if (sb == null) { sb = new StringBuilder(len + 5); } sb.Append(data, start, i - start); } } else { continue; } sb.Append(_newLineChars); start = i + 1; } if (sb == null) { return(null); } else { sb.Append(data, start, i - start); return(sb.ToString()); } }
private Token NextNumericLiteral() { int start = Index; char c = Code.GetChar(Index); char next = Code.GetChar(Index + 1); string? dec = null; StringBuilder?fstr = null; if (c != '.') { if (c == '&') { if (CharUtils.Equals(next, 'h')) { return(NextHexIntLiteral()); } else if (CharUtils.IsOctDigit(next)) { return(NextOctIntLiteral()); } else { throw VBSyntaxError(VBSyntaxErrorCode.SyntaxError); } } else { dec = GetDecStr(); if (CharUtils.IsIdentifierStart(Code.GetChar(Index))) { throw VBSyntaxError(VBSyntaxErrorCode.ExpectedEndOfStatement); } } } c = Code.GetChar(Index); if (c == '.') { ++Index; fstr ??= GetStringBuilder(); fstr.Append('.').Append(GetDecStr()); c = Code.GetChar(Index); } if (CharUtils.Equals(c, 'e')) { fstr ??= GetStringBuilder(); fstr.Append('e'); c = Code.GetChar(++Index); if (c == '+' || c == '-') { ++Index; fstr.Append(c); } c = Code.GetChar(Index); if (CharUtils.IsDecDigit(c)) { fstr.Append(GetDecStr()); } else { throw VBSyntaxError(VBSyntaxErrorCode.InvalidNumber); } } c = Code.GetChar(Index); if (CharUtils.IsIdentifierStart(c)) { throw VBSyntaxError(VBSyntaxErrorCode.ExpectedEndOfStatement); } if (fstr != null && dec != null) { fstr.Insert(0, dec); } if (fstr != null) { return(new FloatLiteralToken { Start = start, End = Index, LineNumber = CurrentLine, LineStart = CurrentLineStart, Value = ParseDouble(fstr.ToString()), }); } var result = ParseInteger(dec !, 10); result.Start = start; return(result); }
// Reads a line. A line is defined as a sequence of characters followed by // a carriage return ('\r'), a line feed ('\n'), or a carriage return // immediately followed by a line feed. The resulting string does not // contain the terminating carriage return and/or line feed. The returned // value is null if the end of the input stream has been reached. // public override string?ReadLine() { if (_stream == null) { throw new Exception("Reader Closed"); } if (_charPos == _charLen) { if (ReadBuffer() == 0) { return(null); } } StringBuilder?sb = null; do { var i = _charPos; do { var ch = _charBuffer[i]; // Note the following common line feed chars: // \n - UNIX \r\n - DOS \r - Mac if (ch == '\r' || ch == '\n') { string s; if (sb != null) { sb.Append(_charBuffer, _charPos, i - _charPos); s = sb.ToString(); } else { s = new string(_charBuffer, _charPos, i - _charPos); } _charPos = i + 1; if (ch == '\r' && (_charPos < _charLen || ReadBuffer() > 0)) { if (_charBuffer[_charPos] == '\n') { _charPos++; } } return(s); } i++; } while (i < _charLen); i = _charLen - _charPos; sb ??= new StringBuilder(i + 80); sb.Append(_charBuffer, _charPos, i); } while (ReadBuffer() > 0); return(sb.ToString()); }
private string?ReplaceNewLines(string?str) { if (str == null) { return(null); } StringBuilder?sb = null; int start = 0; int i; for (i = 0; i < str.Length; i++) { char ch; if ((ch = str[i]) >= 0x20) { continue; } if (ch == '\n') { if (_newLineChars == "\n") { continue; } sb ??= new StringBuilder(str.Length + 5); sb.Append(str, start, i - start); } else if (ch == '\r') { if (i + 1 < str.Length && str[i + 1] == '\n') { if (_newLineChars == "\r\n") { i++; continue; } sb ??= new StringBuilder(str.Length + 5); sb.Append(str, start, i - start); i++; } else { if (_newLineChars == "\r") { continue; } if (sb == null) { sb = new StringBuilder(str.Length + 5); } sb.Append(str, start, i - start); } } else { continue; } sb.Append(_newLineChars); start = i + 1; } if (sb == null) { return(str); } else { sb.Append(str, start, i - start); return(sb.ToString()); } }
#pragma warning disable CA1838 // Avoid 'StringBuilder' parameters for P/Invokes private static extern uint DragQueryFileWInternal(IntPtr hDrop, uint iFile, StringBuilder?lpszFile, uint cch);
public static string?ToSnake(this string?value) { if (value == null) { return(null); } if (value.Length == 0) { return(string.Empty); } Span <char> buffer = stackalloc char[1024]; int bufferIndex = 0; StringBuilder?builder = null; bool modified = false; void Append(char c, Span <char> buffer) { if (bufferIndex == buffer.Length) { if (builder == null) { builder = new StringBuilder((int)(value.Length * 1.5)); builder.Append(buffer); builder.Append(c); } return; } buffer[bufferIndex++] = c; } char c = value[0]; if (char.IsWhiteSpace(c) || c == '-') { Append('_', buffer); modified = true; } else { Append(c, buffer); } for (int i = 1; i < value.Length; i++) { c = value[i]; if (char.IsUpper(c)) { Append('_', buffer); modified = true; } else if (c == '-' || char.IsWhiteSpace(c)) { Append('_', buffer); modified = true; continue; } Append(c, buffer); } if (!modified) { return(value); } if (builder == null) { return(buffer.Slice(0, bufferIndex).ToString()); } return(builder.ToString()); }
/// <summary> /// Checks whether the growable string is <see langword="null"/> or empty. /// </summary> /// <param name="builder">The builder to check.</param> /// <returns><see langword="true"/>, if builder is <see langword="null"/> or empty.</returns> public static bool IsNullOrEmpty([NotNullWhen(false)] this StringBuilder?builder) => builder is null || builder.Length == 0;
public ConfigurableStringBuilder(StringBuilder?stringBuilder = null, string newline = "\n") : base(stringBuilder ?? new()) { this.Newline = newline; }
private static string DisplayUnsignedEnumConstant( TypedConstant constant, SpecialType specialType, ulong constantToDecode, string typeName ) { Debug.Assert(constant.Kind == TypedConstantKind.Enum); // Specified valueConstant might have an exact matching enum field // or it might be a bitwise Or of multiple enum fields. // For the later case, we keep track of the current value of // bitwise Or of possible enum fields. ulong curValue = 0; // Initialize the value string to empty PooledStringBuilder?pooledBuilder = null; StringBuilder? valueStringBuilder = null; // Iterate through all the constant members in the enum type var members = constant.Type !.GetMembers(); foreach (var member in members) { var field = member as IFieldSymbol; if (field is object && field.HasConstantValue) { ConstantValue memberConstant = ConstantValue.Create( field.ConstantValue, specialType ); ulong memberValue = memberConstant.UInt64Value; // Do we have an exact matching enum field if (memberValue == constantToDecode) { if (pooledBuilder != null) { pooledBuilder.Free(); } return(typeName + "." + field.Name); } // specifiedValue might be a bitwise Or of multiple enum fields // Is the current member included in the specified value? if ((memberValue & constantToDecode) == memberValue) { // update the current value curValue = curValue | memberValue; if (valueStringBuilder == null) { pooledBuilder = PooledStringBuilder.GetInstance(); valueStringBuilder = pooledBuilder.Builder; } else { valueStringBuilder.Append(" | "); } valueStringBuilder.Append(typeName); valueStringBuilder.Append("."); valueStringBuilder.Append(field.Name); } } } if (pooledBuilder != null) { if (curValue == constantToDecode) { // return decoded enum constant return(pooledBuilder.ToStringAndFree()); } // Unable to decode the enum constant pooledBuilder.Free(); } // Unable to decode the enum constant, just display the integral value Debug.Assert(constant.ValueInternal is object); var result = constant.ValueInternal.ToString(); Debug.Assert(result is object); return(result); }
public PgSqlStatementBuilder(SqlBuilderOptions?options, StringBuilder?externalBuilder) : base(options, externalBuilder) { this._exprBuilder = new PgSqlBuilder(this.Options, this.Builder); }
public string?Build() { if (!HasData()) { return(null); } int count = 0; if (_emails != null) { count += _emails.Count; } if (_ids != null) { count += _ids.Count; } if (_uris != null) { count += _uris.Count; } if (_sb == null) { _sb = new StringBuilder(100); } else { _sb.Clear(); } if (_emails != null && _emails.Count > 0) { foreach (string email in _emails) { _sb.Append("emailAddress=\"").Append(email).Append('"'); if (--count != 0) { _sb.Append(','); } } } if (_ids != null && _ids.Count > 0) { foreach (string id in _ids) { _sb.Append("id=\"").Append(id).Append('"'); if (--count != 0) { _sb.Append(','); } } } if (_uris != null && _uris.Count > 0) { foreach (string uri in _uris) { _sb.Append("uri=\"").Append(uri).Append('"'); if (--count != 0) { _sb.Append(','); } } } return(_sb.ToString()); }
private static string EncodeUriComponentFast(string uriComponent, bool allowSlash) { StringBuilder?res = null; var nativeEncodePos = -1; for (var pos = 0; pos < uriComponent.Length; pos++) { var code = uriComponent[pos]; // unreserved characters: https://tools.ietf.org/html/rfc3986#section-2.3 if ( code >= CharCode.a && code <= CharCode.z || code >= CharCode.A && code <= CharCode.Z || code >= CharCode.Digit0 && code <= CharCode.Digit9 || code == CharCode.Dash || code == CharCode.Period || code == CharCode.Underline || code == CharCode.Tilde || allowSlash && code == CharCode.Slash || allowSlash && (pos == 1 || pos == 2) && ( uriComponent.Length >= 3 && uriComponent[0] == CharCode.Slash && uriComponent[2] == CharCode.Colon || uriComponent.Length >= 2 && uriComponent[1] == CharCode.Colon ) ) { // check if we are delaying native encode if (nativeEncodePos != -1) { res ??= new StringBuilder(); res.Append(Uri.EscapeDataString(uriComponent.Substring(nativeEncodePos, pos - nativeEncodePos))); nativeEncodePos = -1; } // check if we write into a new string (by default we try to return the param) res?.Append(uriComponent[pos]); } else { // encoding needed, we need to allocate a new string if (res == null) { res ??= new StringBuilder(); res.Append(uriComponent.Substring(0, pos)); } // check with default table first if (EncodeTable.TryGetValue(code, out var escaped)) { // check if we are delaying native encode if (nativeEncodePos != -1) { res.Append(Uri.EscapeDataString(uriComponent.Substring(nativeEncodePos, pos - nativeEncodePos))); nativeEncodePos = -1; } // append escaped variant to result res.Append(escaped); } else if (nativeEncodePos == -1) { // use native encode only when needed nativeEncodePos = pos; } } } if (nativeEncodePos != -1) { res ??= new StringBuilder(); res.Append(Uri.EscapeDataString(uriComponent.Substring(nativeEncodePos))); } return(res != null?res.ToString() : uriComponent); }
internal static extern int forkpty(ref int master, StringBuilder?name, ref Termios termp, ref WinSize winsize);
// true -> done processing // false -> need more input private bool ProcessInput(MemoryStream ms) { var buffer = ms.ToArray(); var len = (int)ms.Length; var used = 0; while (true) { if (_context.HaveError) { return(true); } if (_position >= len) { break; } string?line; try { line = ReadLine(buffer, _position, len - _position, out used); _position += used; } catch { _context.ErrorMessage = "Bad request"; return(true); } if (line == null) { break; } if (string.IsNullOrEmpty(line)) { if (_inputState == InputState.RequestLine) { continue; } _currentLine = null; return(true); } if (_inputState == InputState.RequestLine) { _context.HttpListenerRequest.SetRequestLine(line); _inputState = InputState.Headers; } else { try { _context.HttpListenerRequest.AddHeader(line); } catch (Exception e) { _context.ErrorMessage = e.Message; return(true); } } } if (used == len) { ms.SetLength(0); _position = 0; } return(false); }
public CodeBuilder Append(StringBuilder?value) { builder.Append(value); return(this); }
public virtual string ReadString() { ThrowIfDisposed(); int currPos = 0; int n; int stringLength; int readLength; int charsRead; // Length of the string in bytes, not chars stringLength = Read7BitEncodedInt(); if (stringLength < 0) { throw new IOException(SR.Format(SR.IO_InvalidStringLen_Len, stringLength)); } if (stringLength == 0) { return(string.Empty); } if (_charBytes == null) { _charBytes = new byte[MaxCharBytesSize]; } if (_charBuffer == null) { _charBuffer = new char[_maxCharsSize]; } StringBuilder?sb = null; do { readLength = ((stringLength - currPos) > MaxCharBytesSize) ? MaxCharBytesSize : (stringLength - currPos); n = _stream.Read(_charBytes, 0, readLength); if (n == 0) { throw Error.GetEndOfFile(); } charsRead = _decoder.GetChars(_charBytes, 0, n, _charBuffer, 0); if (currPos == 0 && n == stringLength) { return(new string(_charBuffer, 0, charsRead)); } if (sb == null) { sb = StringBuilderCache.Acquire(stringLength); // Actual string length in chars may be smaller. } sb.Append(_charBuffer, 0, charsRead); currPos += n; } while (currPos < stringLength); return(StringBuilderCache.GetStringAndRelease(sb)); }
public CodeBuilder Append(StringBuilder?value, int startIndex, int count) { builder.Append(value, startIndex, count); return(this); }
/// <summary> /// <para>Creates an array of commands, that will be sent to the server</para> /// </summary> protected override PipelineEntry[] BuildCommandsList(WebRequest req) { bool resetLoggedInState = false; FtpWebRequest request = (FtpWebRequest)req; if (NetEventSource.Log.IsEnabled()) { NetEventSource.Info(this); } _responseUri = request.RequestUri; var commandList = new List <PipelineEntry>(); if (request.EnableSsl && !UsingSecureStream) { commandList.Add(new PipelineEntry(FormatFtpCommand("AUTH", "TLS"))); // According to RFC we need to re-authorize with USER/PASS after we re-authenticate. resetLoggedInState = true; } if (resetLoggedInState) { _loginDirectory = null; _establishedServerDirectory = null; _requestedServerDirectory = null; _currentTypeSetting = string.Empty; if (_loginState == FtpLoginState.LoggedIn) { _loginState = FtpLoginState.LoggedInButNeedsRelogin; } } if (_loginState != FtpLoginState.LoggedIn) { Credentials = request.Credentials !.GetCredential(request.RequestUri, "basic"); _welcomeMessage = new StringBuilder(); _exitMessage = new StringBuilder(); string domainUserName = string.Empty; string password = string.Empty; if (Credentials != null) { domainUserName = Credentials.UserName; string domain = Credentials.Domain; if (!string.IsNullOrEmpty(domain)) { domainUserName = domain + "\\" + domainUserName; } password = Credentials.Password; } if (domainUserName.Length == 0 && password.Length == 0) { domainUserName = "******"; // [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Suppression approved. Anonymous FTP credential in production code.")] password = "******"; } commandList.Add(new PipelineEntry(FormatFtpCommand("USER", domainUserName))); commandList.Add(new PipelineEntry(FormatFtpCommand("PASS", password), PipelineEntryFlags.DontLogParameter)); // If SSL, always configure data channel encryption after authentication to maximum RFC compatibility. The RFC allows for // PBSZ/PROT commands to come either before or after the USER/PASS, but some servers require USER/PASS immediately after // the AUTH TLS command. if (request.EnableSsl && !UsingSecureStream) { commandList.Add(new PipelineEntry(FormatFtpCommand("PBSZ", "0"))); commandList.Add(new PipelineEntry(FormatFtpCommand("PROT", "P"))); } commandList.Add(new PipelineEntry(FormatFtpCommand("OPTS", "utf8 on"))); commandList.Add(new PipelineEntry(FormatFtpCommand("PWD", null))); } GetPathOption getPathOption = GetPathOption.Normal; if (request.MethodInfo.HasFlag(FtpMethodFlags.DoesNotTakeParameter)) { getPathOption = GetPathOption.AssumeNoFilename; } else if (request.MethodInfo.HasFlag(FtpMethodFlags.ParameterIsDirectory)) { getPathOption = GetPathOption.AssumeFilename; } string requestPath; string requestDirectory; string requestFilename; GetPathInfo(getPathOption, request.RequestUri, out requestPath, out requestDirectory, out requestFilename); if (requestFilename.Length == 0 && request.MethodInfo.HasFlag(FtpMethodFlags.TakesParameter)) { throw new WebException(SR.net_ftp_invalid_uri); } // We optimize for having the current working directory staying at the login directory. This ensure that // our relative paths work right and reduces unnecessary CWD commands. // Usually, we don't change the working directory except for some FTP commands. If necessary, // we need to reset our working directory back to the login directory. if (_establishedServerDirectory != null && _loginDirectory != null && _establishedServerDirectory != _loginDirectory) { commandList.Add(new PipelineEntry(FormatFtpCommand("CWD", _loginDirectory), PipelineEntryFlags.UserCommand)); _requestedServerDirectory = _loginDirectory; } // For most commands, we don't need to navigate to the directory since we pass in the full // path as part of the FTP protocol command. However, some commands require it. if (request.MethodInfo.HasFlag(FtpMethodFlags.MustChangeWorkingDirectoryToPath) && requestDirectory.Length > 0) { commandList.Add(new PipelineEntry(FormatFtpCommand("CWD", requestDirectory), PipelineEntryFlags.UserCommand)); _requestedServerDirectory = requestDirectory; } if (!request.MethodInfo.IsCommandOnly) { string requestedTypeSetting = request.UseBinary ? "I" : "A"; if (_currentTypeSetting != requestedTypeSetting) { commandList.Add(new PipelineEntry(FormatFtpCommand("TYPE", requestedTypeSetting))); _currentTypeSetting = requestedTypeSetting; } if (request.UsePassive) { string passiveCommand = (ServerAddress.AddressFamily == AddressFamily.InterNetwork || ServerAddress.IsIPv4MappedToIPv6) ? "PASV" : "EPSV"; commandList.Add(new PipelineEntry(FormatFtpCommand(passiveCommand, null), PipelineEntryFlags.CreateDataConnection)); } else { string portCommand = (ServerAddress.AddressFamily == AddressFamily.InterNetwork || ServerAddress.IsIPv4MappedToIPv6) ? "PORT" : "EPRT"; CreateFtpListenerSocket(request); commandList.Add(new PipelineEntry(FormatFtpCommand(portCommand, GetPortCommandLine(request)))); } if (request.ContentOffset > 0) { // REST command must always be the last sent before the main file command is sent. commandList.Add(new PipelineEntry(FormatFtpCommand("REST", request.ContentOffset.ToString(CultureInfo.InvariantCulture)))); } } PipelineEntryFlags flags = PipelineEntryFlags.UserCommand; if (!request.MethodInfo.IsCommandOnly) { flags |= PipelineEntryFlags.GiveDataStream; if (!request.UsePassive) { flags |= PipelineEntryFlags.CreateDataConnection; } } if (request.MethodInfo.Operation == FtpOperation.Rename) { string baseDir = (requestDirectory.Length == 0) ? string.Empty : requestDirectory + "/"; commandList.Add(new PipelineEntry(FormatFtpCommand("RNFR", baseDir + requestFilename), flags)); string renameTo; if (request.RenameTo is not null && request.RenameTo.StartsWith('/')) { renameTo = request.RenameTo; // Absolute path } else { renameTo = baseDir + request.RenameTo; // Relative path } commandList.Add(new PipelineEntry(FormatFtpCommand("RNTO", renameTo), flags)); }
internal static string JavaScriptStringEncode(string?value) { if (string.IsNullOrEmpty(value)) { return(string.Empty); } StringBuilder?b = null; int startIndex = 0; int count = 0; for (int i = 0; i < value.Length; i++) { char c = value[i]; // Append the unhandled characters (that do not require special treament) // to the string builder when special characters are detected. if (CharRequiresJavaScriptEncoding(c)) { if (b == null) { b = new StringBuilder(value.Length + 5); } if (count > 0) { b.Append(value, startIndex, count); } startIndex = i + 1; count = 0; switch (c) { case '\r': b.Append("\\r"); break; case '\t': b.Append("\\t"); break; case '\"': b.Append("\\\""); break; case '\\': b.Append("\\\\"); break; case '\n': b.Append("\\n"); break; case '\b': b.Append("\\b"); break; case '\f': b.Append("\\f"); break; default: AppendCharAsUnicodeJavaScript(b, c); break; } } else { count++; } } if (b == null) { return(value); } if (count > 0) { b.Append(value, startIndex, count); } return(b.ToString()); }
public static extern int GetDllPath( [Out] StringBuilder?buf, [In] int len);
/// <summary> /// Destructively unescape a string: remove backslashes before punctuation or symbol characters. /// </summary> /// <param name="text">The string data that will be changed by unescaping any punctuation or symbol characters.</param> /// <param name="removeBackSlash">if set to <c>true</c> [remove back slash].</param> /// <returns></returns> public static string Unescape(string?text, bool removeBackSlash = true) { // Credits: code from CommonMark.NET // Copyright (c) 2014, Kārlis Gaņģis All rights reserved. // See license for details: https://github.com/Knagis/CommonMark.NET/blob/master/LICENSE.md if (string.IsNullOrEmpty(text)) { return(string.Empty); } // remove backslashes before punctuation chars: int searchPos = 0; int lastPos = 0; char c; char[] search = removeBackSlash ? SearchBackAndAmp : SearchAmp; StringBuilder?sb = null; while ((searchPos = text !.IndexOfAny(search, searchPos)) != -1) { sb ??= StringBuilderCache.Local(); c = text[searchPos]; if (removeBackSlash && c == '\\') { searchPos++; if (text.Length == searchPos) { break; } c = text[searchPos]; if (c.IsEscapableSymbol()) { sb.Append(text, lastPos, searchPos - lastPos - 1); lastPos = searchPos; } } else if (c == '&') { var match = ScanEntity(new StringSlice(text, searchPos, text.Length - 1), out int numericEntity, out int entityNameStart, out int entityNameLength); if (match == 0) { searchPos++; } else { searchPos += match; if (entityNameLength > 0) { var decoded = EntityHelper.DecodeEntity(text.AsSpan(entityNameStart, entityNameLength)); if (decoded != null) { sb.Append(text, lastPos, searchPos - match - lastPos); sb.Append(decoded); lastPos = searchPos; } } else if (numericEntity >= 0) { sb.Append(text, lastPos, searchPos - match - lastPos); EntityHelper.DecodeEntity(numericEntity, sb); lastPos = searchPos; } } } } if (sb is null || lastPos == 0) { return(text); } sb.Append(text, lastPos, text.Length - lastPos); return(sb.GetStringAndReset()); }
// Here you can provide your own root element Xpath which will replace the Xpath of the top level element public static string CreateFromDataContractSerializer(Type type, MemberInfo[] pathToMember, StringBuilder?rootElementXpath, out XmlNamespaceManager namespaces) { if (type == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(type))); } if (pathToMember == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(pathToMember))); } DataContract currentContract = DataContract.GetDataContract(type); ExportContext context; if (rootElementXpath == null) { context = new ExportContext(currentContract); } else { // use the provided xpath for top level element context = new ExportContext(rootElementXpath); } for (int pathToMemberIndex = 0; pathToMemberIndex < pathToMember.Length; pathToMemberIndex++) { currentContract = ProcessDataContract(currentContract, context, pathToMember[pathToMemberIndex]); } namespaces = context.Namespaces; return(context.XPath); }
private static string ToEscapedUriComponent(string value, int i) { StringBuilder?buffer = null; var start = 0; var count = i; var requiresEscaping = false; while (i < value.Length) { var isPercentEncodedChar = PathStringHelper.IsPercentEncodedChar(value, i); if (PathStringHelper.IsValidPathChar(value[i]) || isPercentEncodedChar) { if (requiresEscaping) { // the current segment requires escape if (buffer == null) { buffer = new StringBuilder(value.Length * 3); } buffer.Append(Uri.EscapeDataString(value.Substring(start, count))); requiresEscaping = false; start = i; count = 0; } if (isPercentEncodedChar) { count += 3; i += 3; } else { count++; i++; } } else { if (!requiresEscaping) { // the current segment doesn't require escape if (buffer == null) { buffer = new StringBuilder(value.Length * 3); } buffer.Append(value, start, count); requiresEscaping = true; start = i; count = 0; } count++; i++; } } if (count == value.Length && !requiresEscaping) { return(value); } else { if (count > 0) { if (buffer == null) { buffer = new StringBuilder(value.Length * 3); } if (requiresEscaping) { buffer.Append(Uri.EscapeDataString(value.Substring(start, count))); } else { buffer.Append(value, start, count); } } return(buffer?.ToString() ?? string.Empty); } }