示例#1
0
 internal override DataRowMessage Load(NpgsqlBuffer buf)
 {
     buf.Ensure(sizeof(short));
     NumColumns = buf.ReadInt16();
     Buffer = buf;
     Column = -1;
     ColumnLen = -1;
     PosInColumn = 0;
     return this;
 }
示例#2
0
 internal NpgsqlTextWriter(NpgsqlBuffer npgsqlBuffer = null)
 {
     _outBuf = npgsqlBuffer;
     if (npgsqlBuffer != null)
     {
         Contract.Assert(npgsqlBuffer.WriteSpaceLeft >= 1000, "Sholud have write space in NpgsqlBuffer");
         _writePosition = npgsqlBuffer.WritePosition;
         _startPosition = _writePosition;
         _currentBuffer = npgsqlBuffer._buf;
     }
     else
     {
         _buffers = new List<byte[]>();
         _writePositions = new List<int>();
         _currentBuffer = new byte[32];
         _buffers.Add(_currentBuffer);
     }
 }
示例#3
0
 internal NpgsqlRawCopyStream(NpgsqlConnector connector, string copyCommand)
 {
     _connector = connector;
     _buf = connector.Buffer;
     _connector.SendSingleMessage(new QueryMessage(copyCommand));
     var msg = _connector.ReadSingleMessage();
     switch (msg.Code)
     {
     case BackendMessageCode.CopyInResponse:
         var copyInResponse = (CopyInResponseMessage) msg;
         IsBinary = copyInResponse.IsBinary;
         _canWrite = true;
         break;
     case BackendMessageCode.CopyOutResponse:
         var copyOutResponse = (CopyOutResponseMessage) msg;
         IsBinary = copyOutResponse.IsBinary;
         _canRead = true;
         break;
     default:
         throw _connector.UnexpectedMessageReceived(msg.Code);
     }
 }
示例#4
0
 internal NpgsqlNotificationEventArgs(NpgsqlBuffer buf)
 {
     PID                   = buf.ReadInt32();
     Condition             = buf.ReadNullTerminatedString();
     AdditionalInformation = buf.ReadNullTerminatedString();
 }
示例#5
0
        // TODO: [GenerateAsync]
        internal void WriteToOutputBuffer(NpgsqlBuffer buffer)
        {
            Contract.Assert(_outBuf == null, "This version of WriteToOutputBuffer requires that no NpgsqlBuffer has been set upon initialization");

            for (var i = 0; i < _buffers.Count - 1; i++)
            {
                buffer.Write(_buffers[i], 0, _writePositions[i]);
            }

            buffer.Write(_buffers[_buffers.Count - 1], 0, _writePosition);
        }
示例#6
0
 internal void CopyTo(NpgsqlBuffer other)
 {
     Contract.Assert(other.Size - other._filledBytes >= ReadBytesLeft);
     Array.Copy(_buf, ReadPosition, other._buf, other._filledBytes, ReadBytesLeft);
     other._filledBytes += ReadBytesLeft;
 }
示例#7
0
        protected override void Dispose(bool disposing)
        {
            if (_isDisposed || !disposing) { return; }

            if (CanWrite)
            {
                Flush();
                _connector.SendSingleMessage(CopyDoneMessage.Instance);
                _connector.ReadExpecting<CommandCompleteMessage>();
                _connector.ReadExpecting<ReadyForQueryMessage>();
            }
            else
            {
                if (!_isConsumed) {
                    _buf.Skip(_leftToReadInDataMsg);
                    _connector.SkipUntil(BackendMessageCode.ReadyForQuery);
                }
            }

            _connector.EndUserAction();
            _connector = null;
            _buf = null;
            _isDisposed = true;
        }
示例#8
0
 internal NpgsqlNotice(NpgsqlBuffer buf)
 {
     _msg = new ErrorOrNoticeMessage(buf);
 }
示例#9
0
 internal NpgsqlException(NpgsqlBuffer buf) : this(new NpgsqlError(buf)) {}
示例#10
0
 internal void CopyTo(NpgsqlBuffer other)
 {
     Contract.Assert(other.Size - other._filledBytes >= ReadBytesLeft);
     Array.Copy(_buf, ReadPosition, other._buf, other._filledBytes, ReadBytesLeft);
     other._filledBytes += ReadBytesLeft;
 }
示例#11
0
文件: Common.cs 项目: kraaden/npgsql
 /// <param name="buf">the buffer into which to write the message.</param>
 /// <param name="directBuf">
 /// an option buffer that, if returned, will be written to the server directly, bypassing our
 /// NpgsqlBuffer. This is an optimization hack for bytea.
 /// </param>
 /// <returns>
 /// Whether there was enough space in the buffer to contain the entire message.
 /// If false, the buffer should be flushed and write should be called again.
 /// </returns>
 internal abstract bool Write(NpgsqlBuffer buf, ref DirectBuffer directBuf);
示例#12
0
 /// <param name="buf">the buffer into which to write the message.</param>
 /// <param name="directBuf">
 /// an option buffer that, if returned, will be written to the server directly, bypassing our
 /// NpgsqlBuffer. This is an optimization hack for bytea.
 /// </param>
 /// <returns>
 /// Whether there was enough space in the buffer to contain the entire message.
 /// If false, the buffer should be flushed and write should be called again.
 /// </returns>
 internal abstract bool Write(NpgsqlBuffer buf, ref DirectBuffer directBuf);
示例#13
0
 internal NpgsqlNotice(NpgsqlBuffer buf)
 {
     _msg = new ErrorOrNoticeMessage(buf);
 }
示例#14
0
 /// <summary>
 /// Writes the message contents into the buffer.
 /// </summary>
 internal abstract void Write(NpgsqlBuffer buf);
示例#15
0
 internal NpgsqlException(NpgsqlBuffer buf)
 {
     _msg = new ErrorOrNoticeMessage(buf);
 }
示例#16
0
 void Cleanup()
 {
     _connector  = null;
     _buf        = null;
     _isDisposed = true;
 }
示例#17
0
 internal NpgsqlException(NpgsqlBuffer buf)
 {
     _msg = new ErrorOrNoticeMessage(buf);
 }
示例#18
0
 void Cleanup()
 {
     _connector = null;
     _buf = null;
     _isDisposed = true;
 }
示例#19
0
文件: Common.cs 项目: kraaden/npgsql
 /// <summary>
 /// Writes the message contents into the buffer.
 /// </summary>
 internal abstract void Write(NpgsqlBuffer buf);
示例#20
0
 /// <param name="buf">the buffer into which to write the message.</param>
 /// <param name="directBuf">
 /// an option buffer that, if returned, will be written to the server directly, bypassing our
 /// NpgsqlBuffer. This is an optimization hack for bytea.
 /// </param>
 /// <returns>
 /// Whether there was enough space in the buffer to contain the entire message.
 /// If false, the buffer should be flushed and write should be called again.
 /// </returns>
 internal virtual bool Write(NpgsqlBuffer buf)
 {
     throw new NotImplementedException("Write()");
 }
示例#21
0
 internal NpgsqlError(NpgsqlBuffer buf) : this()
 {
     while (true)
     {
         var code = (ErrorFieldTypeCode)buf.ReadByte();
         switch (code)
         {
             case ErrorFieldTypeCode.Done:
                 // Null terminator; error message fully consumed.
                 return;
             case ErrorFieldTypeCode.Severity:
                 Severity = buf.ReadNullTerminatedString();
                 break;
             case ErrorFieldTypeCode.Code:
                 Code = buf.ReadNullTerminatedString();
                 break;
             case ErrorFieldTypeCode.Message:
                 Message = buf.ReadNullTerminatedString();
                 break;
             case ErrorFieldTypeCode.Detail:
                 Detail = buf.ReadNullTerminatedString();
                 break;
             case ErrorFieldTypeCode.Hint:
                 Hint = buf.ReadNullTerminatedString();
                 break;
             case ErrorFieldTypeCode.Position:
                 Position = buf.ReadNullTerminatedString();
                 break;
             case ErrorFieldTypeCode.InternalPosition:
                 InternalPosition = buf.ReadNullTerminatedString();
                 break;
             case ErrorFieldTypeCode.InternalQuery:
                 InternalQuery = buf.ReadNullTerminatedString();
                 break;
             case ErrorFieldTypeCode.Where:
                 Where = buf.ReadNullTerminatedString();
                 break;
             case ErrorFieldTypeCode.File:
                 File = buf.ReadNullTerminatedString();
                 break;
             case ErrorFieldTypeCode.Line:
                 Line = buf.ReadNullTerminatedString();
                 break;
             case ErrorFieldTypeCode.Routine:
                 Routine = buf.ReadNullTerminatedString();
                 break;
             case ErrorFieldTypeCode.SchemaName:
                 SchemaName = buf.ReadNullTerminatedString();
                 break;
             case ErrorFieldTypeCode.TableName:
                 TableName = buf.ReadNullTerminatedString();
                 break;
             case ErrorFieldTypeCode.ColumnName:
                 ColumnName = buf.ReadNullTerminatedString();
                 break;
             case ErrorFieldTypeCode.DataTypeName:
                 DataTypeName = buf.ReadNullTerminatedString();
                 break;
             case ErrorFieldTypeCode.ConstraintName:
                 ConstraintName = buf.ReadNullTerminatedString();
                 break;
             default:
                 // Unknown error field; consume and discard.
                 buf.ReadNullTerminatedString();
                 break;
         }
     }
 }
示例#22
0
 internal virtual bool Write(NpgsqlBuffer buf, ref DirectBuffer directBuf)
 {
     return Write(buf);
 }
示例#23
0
 public void PrepareRead(NpgsqlBuffer buf, int len, FieldDescription fieldDescription)
 {
     Contract.Requires(buf != null);
 }
 internal NpgsqlNotificationEventArgs(NpgsqlBuffer buf)
 {
     PID = buf.ReadInt32();
     Condition = buf.ReadNullTerminatedString();
     AdditionalInformation = buf.ReadNullTerminatedString();
 }
示例#25
0
        /// <summary>
        /// Reads in the requested bytes into the buffer, or if the buffer isn't big enough, allocates a new
        /// temporary buffer and reads into it. Returns the buffer that contains the data (either itself or the
        /// temp buffer). Used in cases where we absolutely have to have an entire value in memory and cannot
        /// read it in sequentially.
        /// </summary>
        internal NpgsqlBuffer EnsureOrAllocateTemp(int count)
        {
            if (count <= Size) {
                Ensure(count);
                return this;
            }

            // Worst case: our buffer isn't big enough. For now, allocate a new buffer
            // and copy into it
            // TODO: Optimize with a pool later?
            var tempBuf = new NpgsqlBuffer(Underlying, count, TextEncoding);
            CopyTo(tempBuf);
            Clear();
            tempBuf.Ensure(count);
            return tempBuf;
        }
示例#26
0
        public void RawOpen(int timeout)
        {
            // Keep track of time remaining; Even though there may be multiple timeout-able calls,
            // this allows us to still respect the caller's timeout expectation.
            var attemptStart = DateTime.Now;
            var result = Dns.BeginGetHostAddresses(Host, null, null);

            if (!result.AsyncWaitHandle.WaitOne(timeout, true))
            {
                // Timeout was used up attempting the Dns lookup
                throw new TimeoutException(L10N.DnsLookupTimeout);
            }

            timeout -= Convert.ToInt32((DateTime.Now - attemptStart).TotalMilliseconds);

            var ips = Dns.EndGetHostAddresses(result);
            Socket socket = null;
            Exception lastSocketException = null;

            // try every ip address of the given hostname, use the first reachable one
            // make sure not to exceed the caller's timeout expectation by splitting the
            // time we have left between all the remaining ip's in the list.
            for (var i = 0; i < ips.Length; i++)
            {
                _log.Trace("Attempting to connect to " + ips[i]);
                var ep = new IPEndPoint(ips[i], Port);
                socket = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                attemptStart = DateTime.Now;

                try
                {
                    result = socket.BeginConnect(ep, null, null);

                    if (!result.AsyncWaitHandle.WaitOne(timeout / (ips.Length - i), true))
                    {
                        throw new TimeoutException(L10N.ConnectionTimeout);
                    }

                    socket.EndConnect(result);

                    // connect was successful, leave the loop
                    break;
                }
                catch (Exception e)
                {
                    _log.Warn("Failed to connect to " + ips[i]);
                    timeout -= Convert.ToInt32((DateTime.Now - attemptStart).TotalMilliseconds);
                    lastSocketException = e;

                    socket.Close();
                    socket = null;
                }
            }

            if (socket == null)
            {
                throw lastSocketException;
            }

            var baseStream = new NpgsqlNetworkStream(socket, true);
            Stream sslStream = null;

            // If the PostgreSQL server has SSL connectors enabled Open SslClientStream if (response == 'S') {
            if (SSL || (SslMode == SslMode.Require) || (SslMode == SslMode.Prefer))
            {
                baseStream
                    .WriteInt32(8)
                    .WriteInt32(80877103);

                // Receive response
                var response = (Char)baseStream.ReadByte();

                if (response != 'S')
                {
                    if (SslMode == SslMode.Require) {
                        throw new InvalidOperationException(L10N.SslRequestError);
                    }
                }
                else
                {
                    //create empty collection
                    var clientCertificates = new X509CertificateCollection();

                    //trigger the callback to fetch some certificates
                    DefaultProvideClientCertificatesCallback(clientCertificates);

                    //if (context.UseMonoSsl)
                    if (!UseSslStream)
                    {
                        var sslStreamPriv = new SslClientStream(baseStream, Host, true, SecurityProtocolType.Default, clientCertificates)
                        {
                            ClientCertSelectionDelegate = DefaultCertificateSelectionCallback,
                            ServerCertValidationDelegate = DefaultCertificateValidationCallback,
                            PrivateKeyCertSelectionDelegate = DefaultPrivateKeySelectionCallback
                        };

                        sslStream = sslStreamPriv;
                        IsSecure = true;
                    }
                    else
                    {
                        var sslStreamPriv = new SslStream(baseStream, true, DefaultValidateRemoteCertificateCallback);
                        sslStreamPriv.AuthenticateAsClient(Host, clientCertificates, System.Security.Authentication.SslProtocols.Default, false);
                        sslStream = sslStreamPriv;
                        IsSecure = true;
                    }
                }
            }

            Socket = socket;
            BaseStream = baseStream;
            //Stream = new BufferedStream(sslStream ?? baseStream, 8192);
            Stream = BaseStream;
            Buffer = new NpgsqlBuffer(Stream, BufferSize, PGUtil.UTF8Encoding);
            _log.DebugFormat("Connected to {0}:{1 }", Host, Port);
        }
示例#27
0
 public void SetUp()
 {
     Underlying = new MemoryStream();
     Buffer = new NpgsqlBuffer(Underlying, NpgsqlBuffer.DefaultBufferSize, PGUtil.UTF8Encoding);
 }
示例#28
0
 /// <param name="buf">the buffer into which to write the message.</param>
 /// <param name="directBuf">
 /// an option buffer that, if returned, will be written to the server directly, bypassing our
 /// NpgsqlBuffer. This is an optimization hack for bytea.
 /// </param>
 /// <returns>
 /// Whether there was enough space in the buffer to contain the entire message.
 /// If false, the buffer should be flushed and write should be called again.
 /// </returns>
 internal virtual bool Write(NpgsqlBuffer buf)
 {
     throw new NotImplementedException("Write()");
 }
示例#29
0
 public void SetUp()
 {
     Underlying = new MemoryStream();
     Buffer = new NpgsqlBuffer(Underlying);
 }
示例#30
0
 public void PrepareWrite(object value, NpgsqlBuffer buf, LengthCache lengthCache, NpgsqlParameter parameter = null)
 {
     Contract.Requires(buf != null);
     Contract.Requires(value != null);
 }
示例#31
0
        BackendMessage ParseServerMessage(NpgsqlBuffer buf, BackendMessageCode code, int len, DataRowLoadingMode dataRowLoadingMode)
        {
            switch (code)
            {
                case BackendMessageCode.RowDescription:
                    // TODO: Recycle
                    var rowDescriptionMessage = new RowDescriptionMessage();
                    return rowDescriptionMessage.Load(buf, TypeHandlerRegistry);
                case BackendMessageCode.DataRow:
                    Contract.Assert(dataRowLoadingMode == DataRowLoadingMode.NonSequential || dataRowLoadingMode == DataRowLoadingMode.Sequential);
                    return dataRowLoadingMode == DataRowLoadingMode.Sequential
                        ? _dataRowSequentialMessage.Load(buf)
                        : _dataRowNonSequentialMessage.Load(buf);
                case BackendMessageCode.CompletedResponse:
                    return _commandCompleteMessage.Load(buf, len);
                case BackendMessageCode.ReadyForQuery:
                    var rfq = _readyForQueryMessage.Load(buf);
                    TransactionStatus = rfq.TransactionStatusIndicator;
                    return rfq;
                case BackendMessageCode.EmptyQueryResponse:
                    return EmptyQueryMessage.Instance;
                case BackendMessageCode.ParseComplete:
                    return ParseCompleteMessage.Instance;
                case BackendMessageCode.ParameterDescription:
                    return _parameterDescriptionMessage.Load(buf);
                case BackendMessageCode.BindComplete:
                    return BindCompleteMessage.Instance;
                case BackendMessageCode.NoData:
                    return NoDataMessage.Instance;
                case BackendMessageCode.CloseComplete:
                    return CloseCompletedMessage.Instance;
                case BackendMessageCode.ParameterStatus:
                    HandleParameterStatus(buf.ReadNullTerminatedString(), buf.ReadNullTerminatedString());
                    return null;
                case BackendMessageCode.NoticeResponse:
                    // TODO: Recycle
                    FireNotice(new NpgsqlError(buf));
                    return null;
                case BackendMessageCode.NotificationResponse:
                    FireNotification(new NpgsqlNotificationEventArgs(buf));
                    return null;

                case BackendMessageCode.AuthenticationRequest:
                    var authType = (AuthenticationRequestType)buf.ReadInt32();
                    _log.Trace("Received AuthenticationRequest of type " + authType);
                    switch (authType)
                    {
                        case AuthenticationRequestType.AuthenticationOk:
                            return AuthenticationOkMessage.Instance;
                        case AuthenticationRequestType.AuthenticationCleartextPassword:
                            return AuthenticationCleartextPasswordMessage.Instance;
                        case AuthenticationRequestType.AuthenticationMD5Password:
                            return AuthenticationMD5PasswordMessage.Load(buf);
                        case AuthenticationRequestType.AuthenticationGSS:
                            return AuthenticationGSSMessage.Instance;
                        case AuthenticationRequestType.AuthenticationSSPI:
                            return AuthenticationSSPIMessage.Instance;
                        case AuthenticationRequestType.AuthenticationGSSContinue:
                            return AuthenticationGSSContinueMessage.Load(buf, len);
                        default:
                            throw new NotSupportedException(String.Format(L10N.AuthenticationMethodNotSupported, authType));
                    }

                case BackendMessageCode.BackendKeyData:
                    BackendProcessId = buf.ReadInt32();
                    BackendSecretKey = buf.ReadInt32();
                    return null;

                case BackendMessageCode.CopyData:
                case BackendMessageCode.CopyDone:
                case BackendMessageCode.CancelRequest:
                case BackendMessageCode.CopyDataRows:
                case BackendMessageCode.CopyInResponse:
                case BackendMessageCode.CopyOutResponse:
                    throw new NotImplementedException();

                case BackendMessageCode.PortalSuspended:
                case BackendMessageCode.IO_ERROR:
                    Debug.Fail("Unimplemented message: " + code);
                    throw new NotImplementedException("Unimplemented message: " + code);
                case BackendMessageCode.ErrorResponse:
                    return null;
                case BackendMessageCode.FunctionCallResponse:
                    // We don't use the obsolete function call protocol
                    throw new Exception("Unexpected backend message: " + code);
                default:
                    throw PGUtil.ThrowIfReached("Unknown backend message code: " + code);
            }
        }
示例#32
0
 internal virtual bool Write(NpgsqlBuffer buf, ref byte[] directBuf)
 {
     return(Write(buf));
 }