Beispiel #1
0
        public void StreamMultiPart(Stream stream)
        {
            stream.WriteString(_boundary);

            if (_multipartFormData != null)
            {
                foreach (var entry in _multipartFormData)
                {
                    stream.WriteString(CreateFormBoundaryHeader(entry.Key, entry.Value));
                    stream.WriteString(_boundary);
                }
            }

            if (_multipartFileData != null)
            {
                foreach (var fileData in _multipartFileData)
                {
                    using (var file = new FileStream(fileData.Filename, FileMode.Open))
                    {
                        stream.WriteString(CreateFileBoundaryHeader(fileData));

                        StreamFileContents(file, fileData, stream);

                        stream.WriteString(_boundary);
                    }
                }
            }
            stream.WriteString("--");
        }
Beispiel #2
0
        public virtual bool SaveTo(Stream stream)
        {
            stream.Write((uint)KeyValues.Count);
            foreach (var keyValue in KeyValues)
            {
                stream.WriteString(keyValue.Key);
                stream.WriteString(keyValue.Value);
            }

            return true;
        }
 public override void RenderCommand(Stream stream)
 {
     if (Blob != null)
     {
         stream.WriteString("M 644 ");
         Blob.RenderMarkReference(stream);
         stream.WriteString(string.Format(" \"{0}\"", Path));
         stream.WriteLineFeed();
     }
     else
     {
         stream.WriteLine(string.Format("M 644 inline \"{0}\"", Path));
         stream.RenderCommand(Data);
     }
 }
        public void Serialize(Stream dest, Exception value)
        {
            if (dest == null)
                throw new ArgumentNullException("dest");
            if (value == null)
                throw new ArgumentNullException("value");

            var type = value.GetType();
            int typeAlias = _data.TypeTable.GetAlias(type);
            var typeSerializable = _data.MessageSerializer.CanSerialize(type);

            dest.WriteByte((byte)((typeAlias != 0 ? 1 : 0) | (typeSerializable ? 2 : 0)));

            if (typeAlias != 0)
                dest.Write32BitEncodedInt(typeAlias);
            else
                dest.WriteString(type.FullName);

            if (typeSerializable)
            {
                var lengthMarker = new StreamLengthMarker(dest, true);
                _data.MessageSerializer.Serialize(dest, value);
                lengthMarker.WriteLength(true);
            }
        }
Beispiel #5
0
        public void Serialize(Stream output)
        {
            if (this.Version < 1 || this.Version > 2)
            {
                throw new InvalidOperationException("unsupported blob version");
            }

            output.WriteValueU32(this.Version);
            output.WriteValueS32(this.Entries.Count);

            var nameLength = this.Version == 2 ? 32 : 14;

            foreach (var entry in this.Entries)
            {
                var name = entry.Name;

                if (name.Length + 1 > nameLength)
                {
                    throw new InvalidOperationException();
                }

                output.WriteString(name.PadRight(nameLength, '\0'));
                output.WriteValueU32((uint)entry.Offset);
                output.WriteValueU32(entry.Size);
            }
        }
        public void RenderMarkReference(Stream stream)
        {
            if (!_HasBeenRendered)
                throw new InvalidOperationException("A MarkCommand cannot be referenced if it has not been rendered.");

            var reference = string.Format(":{0}", MarkId);
            stream.WriteString(reference);
        }
 public override void RenderCommand(Stream stream)
 {
     stream.WriteLine(string.Format("reset {0}", Reference));
     if (From != null)
     {
         stream.WriteString("from ");
         From.RenderMarkReference(stream);
         stream.WriteLineFeed();
     }
 }
Beispiel #8
0
	    static void StreamFileContents(Stream file, FileData fileData, Stream requestStream)
        {
            var buffer = new byte[8192];

            int count;

            while ((count = file.Read(buffer, 0, buffer.Length)) > 0)
            {
                if (fileData.ContentTransferEncoding == HttpContentTransferEncoding.Base64)
                {
                    string str = Convert.ToBase64String(buffer, 0, count);

                    requestStream.WriteString(str);
                }
                else if (fileData.ContentTransferEncoding == HttpContentTransferEncoding.Binary)
                {
                    requestStream.Write(buffer, 0, count);
                }
            }
        }
		public static void Encode(Image image, Stream stream)
		{
			stream.WriteString(image.Header);
			stream.WriteBytes(image.LogicalScreenDescriptor.ToBytes());

			if (image.LogicalScreenDescriptor.GlobalColorTableFlag)
			{
				stream.WriteBytes(image.GlobalColorTable);
			}

			foreach (var applicationExtension in image.ApplictionExtensions)
			{
				stream.WriteBytes(applicationExtension.ToBytes());
			}

			foreach (var commentExtension in image.CommentExtensions)
			{
				stream.WriteBytes(commentExtension.ToBytes());
			}

			WriteFrames(image.Frames, stream);
		}
        private void AddFunctionColumnListSupport(Stream st)
        {
            bool isFirstOutputOrInputOutput = true;

            PGUtil.WriteString(st, " AS (");

            for (int i = 0 ; i < Parameters.Count ; i++)
            {
                var p = Parameters[i];

                switch(p.Direction)
                {
                    case ParameterDirection.Output: case ParameterDirection.InputOutput:
                        if (isFirstOutputOrInputOutput)
                        {
                            isFirstOutputOrInputOutput = false;
                        }
                        else
                        {
                            st.WriteString(", ");
                        }

                        st
                            .WriteString(p.CleanName)
                            .WriteBytes((byte)ASCIIBytes.Space)
                            .WriteString(p.TypeInfo.Name);

                        break;
                }
            }

            st.WriteByte((byte)ASCIIBytes.ParenRight);
        }
        private void AppendParameterPlaceHolder(Stream dest, NpgsqlParameter parameter, int paramNumber)
        {
            string parameterSize = "";

            dest.WriteBytes((byte)ASCIIBytes.ParenLeft);

            if (parameter.TypeInfo.UseSize && (parameter.Size > 0))
            {
                parameterSize = string.Format("({0})", parameter.Size);
            }

            if (parameter.UseCast)
            {
                dest.WriteString("${0}::{1}{2}", paramNumber, parameter.TypeInfo.CastName, parameterSize);
            }
            else
            {
                dest.WriteString("${0}{1}", paramNumber, parameterSize);
            }

            dest.WriteBytes((byte)ASCIIBytes.ParenRight);
        }
Beispiel #12
0
 public override void WriteTo(Stream stream)
 {
     stream.WriteString("Content-Type: application/octet-stream\r\n");
     stream.WriteString(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n\r\n",
         this.Key,
         this.FileName != null
             ? this.FileName.Replace("\n", "%0A").Replace("\r", "%0D").Replace("\"", "%22")
             : "file"
     ));
     this.WriteContent(stream);
 }
Beispiel #13
0
 public override void WriteTo(Stream stream)
 {
     stream.WriteString($"Content-Disposition: form-data; name=\"{this.Key}\"\r\n\r\n");
     stream.WriteString(this.Value);
 }
Beispiel #14
0
 public static void Write(object obj, Stream stream)
 {
     stream.WriteString((string)obj);
 }
Beispiel #15
0
        public override bool SaveTo(Stream stream)
        {
            base.SaveTo(stream);
            Attribute.SaveTo(stream);
            stream.WriteString(BaseTypeName);

            //types
            uint typeCount = (uint)Types.Count;
            stream.Write(typeCount);
            foreach (var baseSirenCustomType in Types)
            {
                byte isClass = baseSirenCustomType.Value.IsCustomClass ? (byte)1 : (byte)0;
                stream.WriteByte(isClass);
                baseSirenCustomType.Value.SaveTo(stream);
            }

            //fields
            uint filedCount = (uint)FieldNameDict.Count;
            stream.Write(filedCount);
            foreach (var sirenField in FieldNameDict)
            {
                sirenField.Value.SaveTo(stream);
            }

            return true;
        }
        // +--------+--------+--+----------+-----------+-------------+-----------+------------+-------+
        // | LEN(4) | CRC(4) |H1| ID (1~6) | AID (1~6) | M_SIG (1~6) | M_LEN (4) | M_DATA (~) | E (~) |
        // +--------+--------+--+----------+-----------+-------------+-----------+------------+-------+
        // H=[ME....TT] T=Type, M=Message?, E=Exception?
        // ID=RequestId, AID=ActorId, M=Message, E=Exception

        public void Serialize(Stream stream, object packet)
        {
            var p = (Packet)packet;

            // Jump 8 Bytes for writing Length | Checksum
            var packetLengthMarker = new StreamLengthMarker(stream, false);
            stream.Seek(8, SeekOrigin.Current);

            // Write Packet Header
            var header = (byte)((byte)(p.Type) |
                                (byte)(p.Message != null ? 0x80 : 0) |
                                (byte)(p.Exception != null ? 0x40 : 0));
            stream.WriteByte(header);
            stream.Write7BitEncodedInt(p.ActorId);
            stream.Write7BitEncodedInt(p.RequestId);

            // Write Message
            if (p.Message != null)
            {
                if (p.Type == PacketType.System)
                {
                    // System message: Always string.
                    stream.WriteString((string)p.Message);
                }
                else
                {
                    // User message: Length, Signature, and Data
                    var messageTypeAlias = _data.TypeTable.GetAlias(p.Message.GetType());
                    stream.Write7BitEncodedInt(messageTypeAlias);
                    var messageLengthMarker = new StreamLengthMarker(stream, true);
                    _data.MessageSerializer.Serialize(stream, p.Message);
                    messageLengthMarker.WriteLength(true);
                }
            }

            // Write Exception
            if (p.Exception != null)
            {
                _exceptionSerializer.Serialize(stream, p.Exception);
            }

            // Write Length
            packetLengthMarker.WriteLength(false);

            // Encrypt and Calc Checksum
            ArraySegment<byte> s0, s1;
            GetBuffers(stream, (int)packetLengthMarker.StartPosition + 8, packetLengthMarker.Length - 4,
                       out s0, out s1);
            var ctx = new EncryptContext { Key = _serializeWrapKey };
            Encrypt(s0.Array, s0.Offset, s0.Array, s0.Offset, s0.Count, ref ctx);
            Encrypt(s1.Array, s1.Offset, s1.Array, s1.Offset, s1.Count, ref ctx);
            if (_serializeWrapKey != 0)
            {
                _serializeWrapKey += 1;
                if (_serializeWrapKey == 0)
                    _serializeWrapKey = 1;
            }

            // Write Checksum
            var hashBytes = BitConverter.GetBytes(ctx.Hash);
            stream.Write(hashBytes, 0, hashBytes.Length);

            // End of stream, again.
            stream.Seek(packetLengthMarker.EndPosition, SeekOrigin.Begin);

            // Pending WrapKey
            if (_serializeWrapPendingKey != 0)
            {
                _serializeWrapKey = _serializeWrapPendingKey;
                _serializeWrapPendingKey = 0;
            }
        }
Beispiel #17
0
 public virtual bool SaveTo(Stream stream)
 {
     stream.WriteString(Name);
     return true;
 }
Beispiel #18
0
        private PythonProcess(Stream stream, int pid, PythonLanguageVersion version, PythonDebugOptions debugOptions) {
            _pid = pid;
            _process = Process.GetProcessById(pid);
            _process.EnableRaisingEvents = true;
            _process.Exited += new EventHandler(_process_Exited);
            
            _delayUnregister = true;
            
            ListenForConnection();

            stream.WriteInt32(DebugConnectionListener.ListenerPort);
            stream.WriteString(_processGuid.ToString());
            stream.WriteString(debugOptions.ToString());
        }
        /// <summary>
        /// Append a region of a source command text to an output command, performing parameter token
        /// substitutions.
        /// </summary>
        /// <param name="dest">Stream to which to append output.</param>
        /// <param name="src">Command text.</param>
        /// <param name="prepare"></param>
        /// <param name="allowMultipleStatements"></param>
        /// <returns>false if the query has multiple statements which are not allowed</returns>
        private bool AppendCommandReplacingParameterValues(Stream dest, string src, bool prepare, bool allowMultipleStatements)
        {
            bool standardConformantStrings = connection != null && connection.Connector != null && connection.Connector.IsInitialized ? connection.UseConformantStrings : true;

            int currCharOfs = 0;
            int end = src.Length;
            char ch = '\0';
            char lastChar = '\0';
            int dollarTagStart = 0;
            int dollarTagEnd = 0;
            int currTokenBeg = 0;
            int blockCommentLevel = 0;

            Dictionary<NpgsqlParameter, int> paramOrdinalMap = null;

            if (prepare)
            {
                paramOrdinalMap = new Dictionary<NpgsqlParameter, int>();

                for (int i = 0 ; i < parameters.Count ; i++)
                {
                    paramOrdinalMap[parameters[i]] = i + 1;
                }
            }

            if (allowMultipleStatements && parameters.Count == 0)
            {
                dest.WriteString(src);
                return true;
            }

        None:
            if (currCharOfs >= end)
            {
                goto Finish;
            }
            lastChar = ch;
            ch = src[currCharOfs++];
        NoneContinue:
            for (; ; lastChar = ch, ch = src[currCharOfs++])
            {
                switch (ch)
                {
                    case '/':                                           goto BlockCommentBegin;
                    case '-':                                           goto LineCommentBegin;
                    case '\'': if (standardConformantStrings)           goto Quoted;                else goto Escaped;
                    case '$':  if (!IsIdentifier(lastChar))             goto DollarQuotedStart;     else break;
                    case '"':                                           goto DoubleQuoted;
                    case ':':  if (lastChar != ':')                     goto ParamStart;            else break;
                    case '@':  if (lastChar != '@')                     goto ParamStart;            else break;
                    case ';':  if (!allowMultipleStatements)            goto SemiColon;             else break;

                    case 'e':
                    case 'E':  if (!IsLetter(lastChar))                 goto EscapedStart;          else break;
                }

                if (currCharOfs >= end)
                {
                    goto Finish;
                }
            }
            
        ParamStart:
            if (currCharOfs < end)
            {
                lastChar = ch;
                ch = src[currCharOfs];
                if (IsParamNameChar(ch))
                {
                    if (currCharOfs - 1 > currTokenBeg)
                    {
                        dest.WriteString(src.Substring(currTokenBeg, currCharOfs - 1 - currTokenBeg));
                    }
                    currTokenBeg = currCharOfs++ - 1;
                    goto Param;
                }
                else
                {
                    currCharOfs++;
                    goto NoneContinue;
                }
            }
            goto Finish;

        Param:
            // We have already at least one character of the param name
            for (; ; )
            {
                lastChar = ch;
                if (currCharOfs >= end || !IsParamNameChar(ch = src[currCharOfs]))
                {
                    string paramName = src.Substring(currTokenBeg, currCharOfs - currTokenBeg);
                    NpgsqlParameter parameter;

                    if (parameters.TryGetValue(paramName, out parameter))
                    {
                        if (parameter.Direction == ParameterDirection.Input || parameter.Direction == ParameterDirection.InputOutput)
                        {
                            if (prepare)
                            {
                                AppendParameterPlaceHolder(dest, parameter, paramOrdinalMap[parameter]);
                            }
                            else
                            {
                                AppendParameterValue(dest, parameter);
                            }
                            currTokenBeg = currCharOfs;
                        }
                    }

                    if (currCharOfs >= end)
                    {
                        goto Finish;
                    }

                    currCharOfs++;
                    goto NoneContinue;
                }
                else
                {
                    currCharOfs++;
                }
            }

        Quoted:
            while (currCharOfs < end)
            {
                if (src[currCharOfs++] == '\'')
                {
                    ch = '\0';
                    goto None;
                }
            }
            goto Finish;

        DoubleQuoted:
            while (currCharOfs < end)
            {
                if (src[currCharOfs++] == '"')
                {
                    ch = '\0';
                    goto None;
                }
            }
            goto Finish;

        EscapedStart:
            if (currCharOfs < end)
            {
                lastChar = ch;
                ch = src[currCharOfs++];
                if (ch == '\'')
                {
                    goto Escaped;
                }
                goto NoneContinue;
            }
            goto Finish;

        Escaped:
            while (currCharOfs < end)
            {
                ch = src[currCharOfs++];
                if (ch == '\'')
                {
                    goto MaybeConcatenatedEscaped;
                }
                if (ch == '\\')
                {
                    if (currCharOfs >= end)
                    {
                        goto Finish;
                    }
                    currCharOfs++;
                }
            }
            goto Finish;

        MaybeConcatenatedEscaped:
            while (currCharOfs < end)
            {
                ch = src[currCharOfs++];
                if (ch == '\r' || ch == '\n')
                {
                    goto MaybeConcatenatedEscaped2;
                }
                if (ch != ' ' && ch != '\t' && ch != '\f')
                {
                    lastChar = '\0';
                    goto NoneContinue;
                }
            }
            goto Finish;

        MaybeConcatenatedEscaped2:
            while (currCharOfs < end)
            {
                ch = src[currCharOfs++];
                if (ch == '\'')
                {
                    goto Escaped;
                }
                if (ch == '-')
                {
                    if (currCharOfs >= end)
                    {
                        goto Finish;
                    }
                    ch = src[currCharOfs++];
                    if (ch == '-')
                    {
                        goto MaybeConcatenatedEscapeAfterComment;
                    }
                    lastChar = '\0';
                    goto NoneContinue;

                }
                if (ch != ' ' && ch != '\t' && ch != '\n' & ch != '\r' && ch != '\f')
                {
                    lastChar = '\0';
                    goto NoneContinue;
                }
            }
            goto Finish;

        MaybeConcatenatedEscapeAfterComment:
            while (currCharOfs < end)
            {
                ch = src[currCharOfs++];
                if (ch == '\r' || ch == '\n')
                {
                    goto MaybeConcatenatedEscaped2;
                }
            }
            goto Finish;

        DollarQuotedStart:
            if (currCharOfs < end)
            {
                ch = src[currCharOfs];
                if (ch == '$')
                {
                    // Empty tag
                    dollarTagStart = dollarTagEnd = currCharOfs;
                    currCharOfs++;
                    goto DollarQuoted;
                }
                if (IsIdentifierStart(ch))
                {
                    dollarTagStart = currCharOfs;
                    currCharOfs++;
                    goto DollarQuotedInFirstDelim;
                }
                lastChar = '$';
                currCharOfs++;
                goto NoneContinue;
            }
            goto Finish;

        DollarQuotedInFirstDelim:
            while (currCharOfs < end)
            {
                lastChar = ch;
                ch = src[currCharOfs++];
                if (ch == '$')
                {
                    dollarTagEnd = currCharOfs - 1;
                    goto DollarQuoted;
                }
                if (!IsDollarTagIdentifier(ch))
                {
                    goto NoneContinue;
                }
            }
            goto Finish;

        DollarQuoted:
            {
                string tag = src.Substring(dollarTagStart - 1, dollarTagEnd - dollarTagStart + 2);
                int pos = src.IndexOf(tag, dollarTagEnd + 1); // Not linear time complexity, but that's probably not a problem, since PostgreSQL backend's isn't either
                if (pos == -1)
                {
                    currCharOfs = end;
                    goto Finish;
                }
                currCharOfs = pos + dollarTagEnd - dollarTagStart + 2;
                ch = '\0';
                goto None;
            }

        LineCommentBegin:
            if (currCharOfs < end)
            {
                ch = src[currCharOfs++];
                if (ch == '-')
                {
                    goto LineComment;
                }
                lastChar = '\0';
                goto NoneContinue;
            }
            goto Finish;

        LineComment:
            while (currCharOfs < end)
            {
                ch = src[currCharOfs++];
                if (ch == '\r' || ch == '\n')
                {
                    goto None;
                }
            }
            goto Finish;

        BlockCommentBegin:
            while (currCharOfs < end)
            {
                ch = src[currCharOfs++];
                if (ch == '*')
                {
                    blockCommentLevel++;
                    goto BlockComment;
                }
                if (ch != '/')
                {
                    if (blockCommentLevel > 0)
                    {
                        goto BlockComment;
                    }
                    lastChar = '\0';
                    goto NoneContinue;
                }
            }
            goto Finish;

        BlockComment:
            while (currCharOfs < end)
            {
                ch = src[currCharOfs++];
                if (ch == '*')
                {
                    goto BlockCommentEnd;
                }
                if (ch == '/')
                {
                    goto BlockCommentBegin;
                }
            }
            goto Finish;

        BlockCommentEnd:
            while (currCharOfs < end)
            {
                ch = src[currCharOfs++];
                if (ch == '/')
                {
                    if (--blockCommentLevel > 0)
                    {
                        goto BlockComment;
                    }
                    goto None;
                }
                if (ch != '*')
                {
                    goto BlockComment;
                }
            }
            goto Finish;

        SemiColon:
            while (currCharOfs < end)
            {
                ch = src[currCharOfs++];
                if (ch != ' ' && ch != '\t' && ch != '\n' & ch != '\r' && ch != '\f') // We don't check for comments after the last ; yet
                {
                    return false;
                }
            }
            // implicit goto Finish

        Finish:
            dest.WriteString(src.Substring(currTokenBeg, end - currTokenBeg));
            return true;
        }
Beispiel #20
0
        /// <summary>
        /// Append a region of a source command text to an output command, performing parameter token
        /// substitutions.
        /// </summary>
        /// <param name="dest">Stream to which to append output.</param>
        /// <param name="src">Command text.</param>
        /// <param name="begin">Starting index within src.</param>
        /// <param name="length">Length of region to be processed.</param>
        /// <param name="prepare"></param>
        /// <param name="forExtendedQuery"></param>
        private void AppendCommandReplacingParameterValues(Stream dest, string src, int begin, int length, bool prepare, bool forExtendedQuery)
        {
            char lastChar = '\0';
            TokenType currTokenType = TokenType.None;
            char paramMarker = '\0';
            int currTokenBeg = begin;
            int currTokenLen = 0;
            Dictionary<NpgsqlParameter, int> paramOrdinalMap = null;
            int end = begin + length;

            if (prepare)
            {
                paramOrdinalMap = new Dictionary<NpgsqlParameter, int>();

                for (int i = 0 ; i < parameters.Count ; i++)
                {
                    paramOrdinalMap[parameters[i]] = i + 1;
                }
            }

            for (int currCharOfs = begin ; currCharOfs < end ; currCharOfs++)
            {
                char ch = src[currCharOfs];

                // goto label for character re-evaluation:
                ProcessCharacter:

                switch (currTokenType)
                {
                    case TokenType.None :
                        switch (ch)
                        {
                            case '\'' :
                                if (currTokenLen > 0)
                                {
                                    dest.WriteString(src.Substring(currTokenBeg, currTokenLen));
                                }

                                currTokenType = TokenType.Quoted;

                                currTokenBeg = currCharOfs;
                                currTokenLen = 1;

                                break;

                            case ':' :
                                if (currTokenLen > 0)
                                {
                                    dest.WriteString(src.Substring(currTokenBeg, currTokenLen));
                                }

                                currTokenType = TokenType.Colon;

                                currTokenBeg = currCharOfs;
                                currTokenLen = 1;

                                break;

                            case '<' :
                            case '@' :
                                if (currTokenLen > 0)
                                {
                                    dest.WriteString(src.Substring(currTokenBeg, currTokenLen));
                                }

                                currTokenType = TokenType.FullTextMatchOp;

                                currTokenBeg = currCharOfs;
                                currTokenLen = 1;

                                break;

                            case '-' :
                                if (currTokenLen > 0)
                                {
                                    dest.WriteString(src.Substring(currTokenBeg, currTokenLen));
                                }

                                currTokenType = TokenType.LineCommentBegin;

                                currTokenBeg = currCharOfs;
                                currTokenLen = 1;

                                break;

                            case '/' :
                                if (currTokenLen > 0)
                                {
                                    dest.WriteString(src.Substring(currTokenBeg, currTokenLen));
                                }

                                currTokenType = TokenType.BlockCommentBegin;

                                currTokenBeg = currCharOfs;
                                currTokenLen = 1;

                                break;

                            default :
                                currTokenLen++;

                                break;

                        }

                        break;

                    case TokenType.Param :
                        if (IsParamNameChar(ch))
                        {
                            currTokenLen++;
                        }
                        else
                        {
                            string paramName = src.Substring(currTokenBeg, currTokenLen);
                            NpgsqlParameter parameter;
                            bool wroteParam = false;

                            if (parameters.TryGetValue(paramName, out parameter))
                            {
                                if (
                                    (parameter.Direction == ParameterDirection.Input) ||
                                    (parameter.Direction == ParameterDirection.InputOutput)
                                )
                                {
                                    if (prepare)
                                    {
                                        AppendParameterPlaceHolder(dest, parameter, paramOrdinalMap[parameter]);
                                    }
                                    else
                                    {
                                        AppendParameterValue(dest, parameter);
                                    }
                                }

                                wroteParam = true;
                            }

                            if (! wroteParam)
                            {
                                dest.WriteString("{0}{1}", paramMarker, paramName);
                            }

                            currTokenType = TokenType.None;
                            currTokenBeg = currCharOfs;
                            currTokenLen = 0;

                            // Re-evaluate this character
                            goto ProcessCharacter;
                        }

                        break;

                    case TokenType.Quoted :
                        switch (ch)
                        {
                            case '\'' :
                                currTokenLen++;

                                break;

                            default :
                                if (currTokenLen > 1 && lastChar == '\'')
                                {
                                    dest.WriteString(src.Substring(currTokenBeg, currTokenLen));

                                    currTokenType = TokenType.None;
                                    currTokenBeg = currCharOfs;
                                    currTokenLen = 0;

                                    // Re-evaluate this character
                                    goto ProcessCharacter;
                                }
                                else
                                {
                                    currTokenLen++;
                                }

                                break;

                        }

                        break;

                    case TokenType.LineComment :
                        if (ch == '\n')
                        {
                            currTokenType = TokenType.None;
                        }

                        currTokenLen++;

                        break;

                    case TokenType.BlockComment :
                        if (ch == '*')
                        {
                            currTokenType = TokenType.BlockCommentEnd;
                        }

                        currTokenLen++;

                        break;

                    case TokenType.Colon :
                        if (IsParamNameChar(ch))
                        {
                            // Switch to parameter name token, include this character.
                            currTokenType = TokenType.Param;

                            currTokenBeg = currCharOfs;
                            currTokenLen = 1;
                            paramMarker = ':';
                        }
                        else
                        {
                            // Demote to the unknown token type and continue.
                            currTokenType = TokenType.None;
                            currTokenLen++;
                        }

                        break;

                    case TokenType.FullTextMatchOp :
                        if (lastChar == '@' && IsParamNameChar(ch))
                        {
                            // Switch to parameter name token, include this character.
                            currTokenType = TokenType.Param;

                            currTokenBeg = currCharOfs;
                            currTokenLen = 1;
                            paramMarker = '@';
                        }
                        else
                        {
                            // Demote to the unknown token type.
                            currTokenType = TokenType.None;

                            // Re-evaluate this character
                            goto ProcessCharacter;
                        }

                        break;

                    case TokenType.LineCommentBegin :
                        if (ch == '-')
                        {
                            currTokenType = TokenType.LineComment;
                            currTokenLen++;
                        }
                        else
                        {
                            // Demote to the unknown token type.
                            currTokenType = TokenType.None;

                            // Re-evaluate this character
                            goto ProcessCharacter;
                        }

                        break;

                    case TokenType.BlockCommentBegin :
                        if (ch == '*')
                        {
                            currTokenType = TokenType.BlockComment;
                            currTokenLen++;
                        }
                        else
                        {
                            // Demote to the unknown token type.
                            currTokenType = TokenType.None;

                            // Re-evaluate this character
                            goto ProcessCharacter;
                        }

                        break;

                    case TokenType.BlockCommentEnd :
                        if (ch == '/')
                        {
                            currTokenType = TokenType.None;
                            currTokenLen++;
                        }
                        else
                        {
                            currTokenType = TokenType.BlockComment;
                            currTokenLen++;
                        }

                        break;

                }

                lastChar = ch;
            }

            switch (currTokenType)
            {
                case TokenType.Param :
                    string paramName = src.Substring(currTokenBeg, currTokenLen);
                    NpgsqlParameter parameter;
                    bool wroteParam = false;

                    if (parameters.TryGetValue(paramName, out parameter))
                    {
                        if (
                            (parameter.Direction == ParameterDirection.Input) ||
                            (parameter.Direction == ParameterDirection.InputOutput)
                        )
                        {
                            if (prepare)
                            {
                                AppendParameterPlaceHolder(dest, parameter, paramOrdinalMap[parameter]);
                            }
                            else
                            {
                                AppendParameterValue(dest, parameter);
                            }
                        }

                        wroteParam = true;
                    }

                    if (! wroteParam)
                    {
                        dest.WriteString("{0}{1}", paramMarker, paramName);
                    }

                    break;

                default :
                    if (currTokenLen > 0)
                    {
                        dest.WriteString(src.Substring(currTokenBeg, currTokenLen));
                    }

                    break;

            }
        }
Beispiel #21
0
        void AppendParameterValues(Stream dest)
        {
            var first = true;

            for (var i = 0; i < _parameters.Count; i++)
            {
                var parameter = _parameters[i];

                if (parameter.IsInputDirection)
                {
                    if (first)
                    {
                        first = false;
                    }
                    else
                    {
                        dest.WriteString(", ");
                    }

                    AppendParameterValue(dest, parameter);
                }
            }
        }
Beispiel #22
0
        void AppendParameterPlaceHolder(Stream dest, NpgsqlParameter parameter, int paramNumber)
        {
            dest.WriteByte((byte)ASCIIBytes.ParenLeft);

            if (parameter.UseCast && parameter.Size > 0)
            {
                dest.WriteString("${0}::{1}", paramNumber, parameter.TypeInfo.GetCastName(parameter.Size));
            }
            else
            {
                dest.WriteString("$" + paramNumber);
            }

            dest.WriteByte((byte)ASCIIBytes.ParenRight);
        }
        private void AppendParameterValues(Stream dest)
        {
            bool first = true;

            for (int i = 0 ; i < parameters.Count ; i++)
            {
                NpgsqlParameter parameter = parameters[i];

                if (
                    (parameter.Direction == ParameterDirection.Input) ||
                    (parameter.Direction == ParameterDirection.InputOutput)
                )
                {
                    if (first)
                    {
                        first = false;
                    }
                    else
                    {
                        dest.WriteString(", ");
                    }

                    AppendParameterValue(dest, parameter);
                }
            }
        }
Beispiel #24
0
 public override bool SaveTo(Stream stream)
 {
     stream.Write((uint)Mode);
     stream.WriteString(Dir);
     return true;
 }
        private void AppendParameterValue(Stream dest, NpgsqlParameter parameter)
        {
            byte[] serialised = parameter.TypeInfo.ConvertToBackend(parameter.NpgsqlValue, false, Connector.NativeToBackendTypeConverterOptions);

            // Add parentheses wrapping parameter value before the type cast to avoid problems with Int16.MinValue, Int32.MinValue and Int64.MinValue
            // See bug #1010543
            // Check if this parenthesis can be collapsed with the previous one about the array support. This way, we could use
            // only one pair of parentheses for the two purposes instead of two pairs.
            dest
                .WriteBytes((byte)ASCIIBytes.ParenLeft)
                .WriteBytes((byte)ASCIIBytes.ParenLeft)
                .WriteBytes(serialised)
                .WriteBytes((byte)ASCIIBytes.ParenRight);

            if (parameter.UseCast)
            {
                dest.WriteString("::{0}", parameter.TypeInfo.CastName);

                if (parameter.TypeInfo.UseSize && (parameter.Size > 0))
                {
                    dest.WriteString("({0})", parameter.Size);
                }
            }

            dest.WriteBytes((byte)ASCIIBytes.ParenRight);
        }
        public override void RenderCommand(Stream stream)
        {
            foreach (var fc in FileCommands.OfType<FileModifyCommand>())
            {
                if (fc.Blob != null)
                    stream.RenderCommand(fc.Blob);
            }

            stream.WriteLine(string.Format("commit {0}", Reference));
            base.RenderMarkCommand(stream);

            if (Author != null)
                stream.RenderCommand(Author);
            stream.RenderCommand(Committer);
            stream.RenderCommand(CommitInfo);

            if (FromCommit != null)
            {
                stream.WriteString("from ");
                FromCommit.RenderMarkReference(stream);
                stream.WriteLineFeed();
            }

            foreach (var mc in MergeCommits)
            {
                stream.WriteString("merge ");
                mc.RenderMarkReference(stream);
                stream.WriteLineFeed();
            }

            foreach (var fc in FileCommands)
                stream.RenderCommand(fc);
            stream.WriteLineFeed();
        }
Beispiel #27
0
        private void HandleRequestHandlers(Stream stream) {
            string filename = stream.ReadString();

            Debug.WriteLine("Exception handlers requested for: " + filename);
            var statements = GetHandledExceptionRanges(filename);

            lock (_streamLock) {
                stream.Write(SetExceptionHandlerInfoCommandBytes);
                stream.WriteString(filename);

                stream.WriteInt32(statements.Count);

                foreach (var t in statements) {
                    stream.WriteInt32(t.Item1);
                    stream.WriteInt32(t.Item2);

                    foreach (var expr in t.Item3) {
                        stream.WriteString(expr);
                    }
                    stream.WriteString("-");
                }
            }
        }
Beispiel #28
0
        private static void WriteMultipartFormData(Stream stream, string boundary, KeyValuePair<string, object>[] prm)
        {
            var items = prm.ConvertAll(x => MultipartItem.Create(x.Key, x.Value));

            // Start writing
            foreach(var x in items)
            {
                stream.WriteString("--" + boundary + "\r\n");
                x.WriteTo(stream);
                stream.WriteString("\r\n");
            }
            stream.WriteString("--" + boundary + "--");
        }
Beispiel #29
0
        private static void WriteMultipartFormData(Stream stream, string boundary, IEnumerable<KeyValuePair<string, object>> prm)
        {
            const int bufferSize = 81920;

            prm.ForEach(x =>
            {
                var valueStream = x.Value as Stream;
                var valueBytes = x.Value as IEnumerable<byte>;
            #if !PCL
                var valueFile = x.Value as FileInfo;
            #endif
                var valueString = x.Value.ToString();
            #if WP
                var valueInputStream = x.Value as Windows.Storage.Streams.IInputStream;
                if(valueInputStream != null) valueStream = valueInputStream.AsStreamForRead();
            #endif

                stream.WriteString("--" + boundary + "\r\n");
                if(valueStream != null || valueBytes != null
            #if !PCL
                    || valueFile != null
            #endif
                   )
                {
                    stream.WriteString("Content-Type: application/octet-stream\r\n");
                }
                stream.WriteString(string.Format(@"Content-Disposition: form-data; name=""{0}""", x.Key));
            #if !PCL
                if(valueFile != null)
                    stream.WriteString(string.Format(@"; filename=""{0}""",
                        valueFile.Name.Replace("\n", "%0A").Replace("\r", "%0D").Replace("\"", "%22")));
                else
            #endif
                if(valueStream != null || valueBytes != null)
                    stream.WriteString(@"; filename=""file""");
                stream.WriteString("\r\n\r\n");

            #if !PCL
                if(valueFile != null)
                    valueStream = valueFile.OpenRead();
            #endif
                if(valueStream != null)
                {
                    var buffer = new byte[bufferSize];
                    int count;
                    while((count = valueStream.Read(buffer, 0, bufferSize)) > 0)
                        stream.Write(buffer, 0, count);
                }
                else if(valueBytes != null)
                {
                    var buffer = valueBytes as byte[];
                    if(buffer != null)
                        stream.Write(buffer, 0, buffer.Length);
                    else
                    {
                        buffer = new byte[bufferSize];
                        var i = 0;
                        foreach(var b in valueBytes)
                        {
                            buffer[i++] = b;
                            if(i == bufferSize)
                            {
                                stream.Write(buffer, 0, bufferSize);
                                i = 0;
                            }
                        }
                        if(i > 0)
                            stream.Write(buffer, 0, i);
                    }
                }
                else
                    stream.WriteString(valueString);

            #if !PCL
                if(valueFile != null)
                    valueStream.Close();
            #endif

                stream.WriteString("\r\n");
            });
            stream.WriteString("--" + boundary + "--");
        }
Beispiel #30
0
        /// <summary>
        /// Performs the initial handshake with the remote debugging server, verifying signature and version number and setting up SSL,
        /// and returns the opened socket and the SSL stream for that socket.
        /// </summary>
        /// <param name="hostName">Name of the host to connect to.</param>
        /// <param name="portNumber">Port number to connect to.</param>
        /// <param name="secret">Secret to authenticate with.</param>
        /// <param name="useSsl">Whether to use SSL for this connection.</param>
        /// <param name="sslErrorHandling">If using SSL, specifies how SSL certificate errors should be handled.</param>
        /// <param name="socket">Opened socket to the remote debugging server. The returned socket is owned by <paramref name="stream"/>.</param>
        /// <param name="stream">Opened SSL network stream to the remote debugging server. This stream owns the <paramref name="socket"/>, and will automatically close it.</param>
        /// <returns>Error code.</returns>
        /// <remarks><paramref name="socket"/> should not be used to send or receive data, since it is wrapped in a stream, and is owned by that stream.
        /// It is exposed solely to enable querying it for endpoint information and connectivity status.</remarks>
        public static ConnErrorMessages TryConnect(string hostName, ushort portNumber, string secret, bool useSsl, SslErrorHandling sslErrorHandling, out Socket socket, out Stream stream)
        {
            stream = null;
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            bool connected = false;
            try {
                socket.Connect(hostName, portNumber);
                var rawStream = new NetworkStream(socket, ownsSocket: true);
                if (useSsl) {
                    var sslStream = new SslStream(rawStream, false, (sender, cert, chain, errs) => {
                        if (errs == SslPolicyErrors.None || sslErrorHandling == SslErrorHandling.Ignore) {
                            return true;
                        } else if (sslErrorHandling == SslErrorHandling.Fail) {
                            return false;
                        }

                        string errText = string.Format("Could not establish secure connection to {0}:{1} because of the following SSL issues:\n\n", hostName, portNumber);
                        if ((errs & SslPolicyErrors.RemoteCertificateNotAvailable) != 0) {
                            errText += "- no remote certificate provided\n";
                        }
                        if ((errs & SslPolicyErrors.RemoteCertificateNameMismatch) != 0) {
                            errText += "- remote certificate name does not match hostname\n";
                        }
                        if ((errs & SslPolicyErrors.RemoteCertificateChainErrors) != 0) {
                            errText += "- remote certificate is not trusted\n";
                        }

                        errText += "\nConnect anyway?";

                        var dlgRes = MessageBox.Show(errText, null, MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        return dlgRes == DialogResult.Yes;
                    });
                    try {
                        sslStream.AuthenticateAsClient(hostName);
                    } catch (AuthenticationException) {
                        return ConnErrorMessages.RemoteSslError;
                    }
                    stream = sslStream;
                } else {
                    stream = rawStream;
                }

                var buf = new byte[8];
                int bufLen = stream.Read(buf, 0, DebuggerSignature.Length);
                string sig = Encoding.ASCII.GetString(buf, 0, bufLen);
                if (sig != DebuggerSignature) {
                    return ConnErrorMessages.RemoteUnsupportedServer;
                }

                long ver = stream.ReadInt64();
                if (ver != DebuggerProtocolVersion) {
                    return ConnErrorMessages.RemoteUnsupportedServer;
                }

                stream.Write(DebuggerSignatureBytes);
                stream.WriteInt64(DebuggerProtocolVersion);

                stream.WriteString(secret);
                bufLen = stream.Read(buf, 0, Accepted.Length);
                string secretResp = Encoding.ASCII.GetString(buf, 0, bufLen);
                if (secretResp != Accepted) {
                    return ConnErrorMessages.RemoteSecretMismatch;
                }

                connected = true;
            } catch (IOException) {
                return ConnErrorMessages.RemoteNetworkError;
            } catch (SocketException) {
                return ConnErrorMessages.RemoteNetworkError;
            } finally {
                if (!connected) {
                    if (stream != null) {
                        stream.Close();
                    }
                    socket.Close();
                    socket = null;
                    stream = null;
                }
            }

            return ConnErrorMessages.None;
        }