Exemple #1
0
 public NpgsqlParameterStatus(Stream stream, ByteBuffer queue)
 {
     //Read message length
     PGUtil.EatStreamBytes(stream, 4);
     Parameter      = PGUtil.ReadString(stream, queue);
     ParameterValue = PGUtil.ReadString(stream, queue);
 }
 public FieldData(Stream stream, NpgsqlBackendTypeMapping typeMapping, byte[] buffer, ByteBuffer queue)
 {
     Name     = PGUtil.ReadString(stream, queue);
     TableOID = PGUtil.ReadInt32(stream, buffer);
     ColumnAttributeNumber = PGUtil.ReadInt16(stream, buffer);
     TypeOID      = PGUtil.ReadInt32(stream, buffer);
     TypeInfo     = typeMapping[TypeOID];
     TypeSize     = PGUtil.ReadInt16(stream, buffer);
     TypeModifier = PGUtil.ReadInt32(stream, buffer);
     FormatCode   = (FormatCode)PGUtil.ReadInt16(stream, buffer);
 }
Exemple #3
0
        protected IEnumerable <IServerResponseObject> ProcessBackendResponses_Ver_3(NpgsqlConnector context)
        {
            try
            {
                Stream         stream   = context.Stream;
                NpgsqlMediator mediator = context.Mediator;

                var buffer = context.TmpBuffer;
                var queue  = context.ArrayBuffer;
                List <NpgsqlError> errors = null;
                SCRAM scram = null;

                for (; ;)
                {
                    // Check the first Byte of response.
                    BackEndMessageCode message = (BackEndMessageCode)stream.ReadByte();
                    switch (message)
                    {
                    case BackEndMessageCode.ErrorResponse:

                        NpgsqlError error = new NpgsqlError(stream, buffer, queue);
                        error.ErrorSql = mediator.SqlSent;

                        if (errors == null)
                        {
                            errors = new List <NpgsqlError>();
                        }
                        errors.Add(error);

                        // Return imediately if it is in the startup state or connected state as
                        // there is no more messages to consume.
                        // Possible error in the NpgsqlStartupState:
                        //        Invalid password.
                        // Possible error in the NpgsqlConnectedState:
                        //        No pg_hba.conf configured.

                        if (!context.RequireReadyForQuery)
                        {
                            throw new NpgsqlException(errors);
                        }

                        break;

                    case BackEndMessageCode.AuthenticationRequest:

                        // Get the length in case we're getting AuthenticationGSSContinue
                        int authDataLength = PGUtil.ReadInt32(stream, buffer) - 8;

                        AuthenticationRequestType authType = (AuthenticationRequestType)PGUtil.ReadInt32(stream, buffer);
                        switch (authType)
                        {
                        case AuthenticationRequestType.AuthenticationOk:
                            break;

                        case AuthenticationRequestType.AuthenticationClearTextPassword:
                            // Send the PasswordPacket.

                            ChangeState(context, NpgsqlStartupState.Instance);
                            context.Authenticate(context.Password);

                            break;

                        case AuthenticationRequestType.AuthenticationMD5Password:
                            // Now do the "MD5-Thing"
                            // for this the Password has to be:
                            // 1. md5-hashed with the username as salt
                            // 2. md5-hashed again with the salt we get from the backend


                            MD5 md5 = MD5.Create();


                            // 1.
                            byte[] passwd       = context.Password;
                            byte[] saltUserName = ENCODING_UTF8.GetBytes(context.UserName);

                            byte[] crypt_buf = new byte[passwd.Length + saltUserName.Length];

                            passwd.CopyTo(crypt_buf, 0);
                            saltUserName.CopyTo(crypt_buf, passwd.Length);


                            StringBuilder sb         = new StringBuilder();
                            byte[]        hashResult = md5.ComputeHash(crypt_buf);
                            foreach (byte b in hashResult)
                            {
                                sb.Append(b.ToString("x2"));
                            }


                            String prehash = sb.ToString();

                            byte[] prehashbytes = ENCODING_UTF8.GetBytes(prehash);
                            crypt_buf = new byte[prehashbytes.Length + 4];


                            stream.Read(crypt_buf, prehashbytes.Length, 4);
                            // Send the PasswordPacket.
                            ChangeState(context, NpgsqlStartupState.Instance);


                            // 2.
                            prehashbytes.CopyTo(crypt_buf, 0);

                            sb         = new StringBuilder("md5");                                     // This is needed as the backend expects md5 result starts with "md5"
                            hashResult = md5.ComputeHash(crypt_buf);
                            foreach (byte b in hashResult)
                            {
                                sb.Append(b.ToString("x2"));
                            }

                            context.Authenticate(ENCODING_UTF8.GetBytes(sb.ToString()));

                            break;

#if WINDOWS && UNMANAGED
                        case AuthenticationRequestType.AuthenticationSSPI:
                        {
                            if (context.IntegratedSecurity)
                            {
                                // For SSPI we have to get the IP-Address (hostname doesn't work)
                                string ipAddressString = ((IPEndPoint)context.Socket.RemoteEndPoint).Address.ToString();
                                context.SSPI = new SSPIHandler(ipAddressString, "POSTGRES");
                                ChangeState(context, NpgsqlStartupState.Instance);
                                context.Authenticate(context.SSPI.Continue(null));
                                break;
                            }
                            else
                            {
                                // TODO: correct exception
                                throw new Exception();
                            }
                        }


                        case AuthenticationRequestType.AuthenticationGSSContinue:
                        {
                            byte[] authData = new byte[authDataLength];
                            PGUtil.CheckedStreamRead(stream, authData, 0, authDataLength);
                            byte[] passwd_read = context.SSPI.Continue(authData);
                            if (passwd_read.Length != 0)
                            {
                                context.Authenticate(passwd_read);
                            }
                            break;
                        }
#endif
                        case AuthenticationRequestType.AuthenticationSASL:
                            var saslAuthMechanism = PGUtil.ReadString(stream, queue);
                            if (saslAuthMechanism == "SCRAM-SHA-256")
                            {
                                stream.ReadByte();
                                scram = new SCRAM(saslAuthMechanism, context.UserName);

                                stream.WriteByte((byte)FrontEndMessageCode.SASL);
                                var schemeBytes             = Encoding.UTF8.GetBytes(scram.Scheme);
                                var clientFirstMessageBytes = Encoding.UTF8.GetBytes(scram.getClientFirstMessage());
                                PGUtil.WriteInt32(stream, 9 + schemeBytes.Length + clientFirstMessageBytes.Length);
                                stream.Write(schemeBytes, 0, schemeBytes.Length);
                                stream.WriteByte(0);
                                PGUtil.WriteInt32(stream, clientFirstMessageBytes.Length);
                                stream.Write(clientFirstMessageBytes, 0, clientFirstMessageBytes.Length);
                                stream.Flush();
                            }
                            else
                            {
                                throw new NpgsqlException("Only Scram SHA 256 is supported");
                            }
                            break;

                        case AuthenticationRequestType.AuthenticationSASLContinue:
                            if (scram == null)
                            {
                                throw new NpgsqlException("Invalid authentication message");
                            }
                            var continueData = new byte[authDataLength];
                            PGUtil.CheckedStreamRead(stream, continueData, 0, authDataLength);
                            scram.parseServerFirstMessage(Encoding.UTF8.GetString(continueData));
                            scram.Password = Encoding.UTF8.GetString(context.Password);
                            var mesageBytes = Encoding.UTF8.GetBytes(scram.getClientFinalMessage());
                            stream.WriteByte((byte)FrontEndMessageCode.SASL);
                            PGUtil.WriteInt32(stream, 4 + mesageBytes.Length);
                            stream.Write(mesageBytes, 0, mesageBytes.Length);
                            stream.Flush();
                            break;

                        case AuthenticationRequestType.AuthenticationSASLFinal:
                            if (scram == null)
                            {
                                throw new NpgsqlException("Invalid authentication message");
                            }
                            var finalData = new byte[authDataLength];
                            PGUtil.CheckedStreamRead(stream, finalData, 0, authDataLength);
                            scram.verifyServerSignature(Encoding.UTF8.GetString(finalData));
                            break;

                        default:
                            // Only AuthenticationClearTextPassword, AuthenticationMD5Password and AuthenticationSASL supported for now.
                            if (errors == null)
                            {
                                errors = new List <NpgsqlError>();
                            }
                            errors.Add(
                                new NpgsqlError(String.Format(resman.GetString("Exception_AuthenticationMethodNotSupported"), authType)));
                            throw new NpgsqlException(errors);
                        }
                        break;

                    case BackEndMessageCode.RowDescription:
                        yield return(context.RowDescription());

                        break;

                    case BackEndMessageCode.ParameterDescription:

                        // Do nothing,for instance,  just read...
                        int length   = PGUtil.ReadInt32(stream, buffer);
                        int nb_param = PGUtil.ReadInt16(stream, buffer);
                        //WTF
                        for (int i = 0; i < nb_param; i++)
                        {
                            int typeoid = PGUtil.ReadInt32(stream, buffer);
                        }

                        break;

                    case BackEndMessageCode.DataRow:
                        yield return(context.NextRow());

                        break;

                    case BackEndMessageCode.ReadyForQuery:

                        // Possible status bytes returned:
                        //   I = Idle (no transaction active).
                        //   T = In transaction, ready for more.
                        //   E = Error in transaction, queries will fail until transaction aborted.
                        // Just eat the status byte, we have no use for it at this time.
                        PGUtil.ReadInt32(stream, buffer);
                        stream.ReadByte();

                        ChangeState(context, NpgsqlReadyState.Instance);

                        if (errors != null)
                        {
                            throw new NpgsqlException(errors);
                        }

                        yield break;

                    case BackEndMessageCode.BackendKeyData:
                        // BackendKeyData message.
                        NpgsqlBackEndKeyData backend_keydata = new NpgsqlBackEndKeyData(stream, buffer);
                        context.BackEndKeyData = backend_keydata;


                        // Wait for ReadForQuery message
                        break;

                    case BackEndMessageCode.NoticeResponse:
                        // Notices and errors are identical except that we
                        // just throw notices away completely ignored.
                        context.FireNotice(new NpgsqlError(stream, buffer, queue));
                        break;

                    case BackEndMessageCode.CompletedResponse:
                        PGUtil.ReadInt32(stream, buffer);
                        yield return(new CompletedResponse(stream, queue));

                        break;

                    case BackEndMessageCode.ParseComplete:
                        // Just read up the message length.
                        PGUtil.ReadInt32(stream, buffer);
                        yield break;

                    case BackEndMessageCode.BindComplete:
                        // Just read up the message length.
                        PGUtil.ReadInt32(stream, buffer);
                        yield break;

                    case BackEndMessageCode.EmptyQueryResponse:
                        PGUtil.ReadInt32(stream, buffer);
                        break;

                    case BackEndMessageCode.NotificationResponse:
                        // Eat the length
                        PGUtil.ReadInt32(stream, buffer);
                        context.FireNotification(new NpgsqlNotificationEventArgs(stream, true, buffer, queue));
                        if (context.IsNotificationThreadRunning)
                        {
                            yield break;
                        }
                        break;

                    case BackEndMessageCode.ParameterStatus:
                        NpgsqlParameterStatus parameterStatus = new NpgsqlParameterStatus(stream, queue);

                        context.AddParameterStatus(parameterStatus);

                        if (parameterStatus.Parameter == "server_version")
                        {
                            // Deal with this here so that if there are
                            // changes in a future backend version, we can handle it here in the
                            // protocol handler and leave everybody else put of it.
                            string versionString = parameterStatus.ParameterValue.Trim();
                            for (int idx = 0; idx != versionString.Length; ++idx)
                            {
                                char c = parameterStatus.ParameterValue[idx];
                                if (!char.IsDigit(c) && c != '.')
                                {
                                    versionString = versionString.Substring(0, idx);
                                    break;
                                }
                            }
                            context.ServerVersion = new Version(versionString);
                        }
                        break;

                    case BackEndMessageCode.NoData:
                        // This nodata message may be generated by prepare commands issued with queries which doesn't return rows
                        // for example insert, update or delete.
                        // Just eat the message.
                        PGUtil.ReadInt32(stream, buffer);
                        break;

                    case BackEndMessageCode.CopyInResponse:
                        // Enter COPY sub protocol and start pushing data to server
                        ChangeState(context, NpgsqlCopyInState.Instance);
                        PGUtil.ReadInt32(stream, buffer);                                 // length redundant
                        context.CurrentState.StartCopy(context, ReadCopyHeader(stream, buffer));
                        yield break;
                    // Either StartCopy called us again to finish the operation or control should be passed for user to feed copy data

                    case BackEndMessageCode.CopyOutResponse:
                        // Enter COPY sub protocol and start pulling data from server
                        ChangeState(context, NpgsqlCopyOutState.Instance);
                        PGUtil.ReadInt32(stream, buffer);                                 // length redundant
                        context.CurrentState.StartCopy(context, ReadCopyHeader(stream, buffer));
                        yield break;
                    // Either StartCopy called us again to finish the operation or control should be passed for user to feed copy data

                    case BackEndMessageCode.CopyData:
                        Int32  len = PGUtil.ReadInt32(stream, buffer) - 4;
                        byte[] buf = new byte[len];
                        PGUtil.ReadBytes(stream, buf, 0, len);
                        context.Mediator.ReceivedCopyData = buf;
                        yield break;                                 // read data from server one chunk at a time while staying in copy operation mode

                    case BackEndMessageCode.CopyDone:
                        PGUtil.ReadInt32(stream, buffer);                                 // CopyDone can not have content so this is always 4
                        // This will be followed by normal CommandComplete + ReadyForQuery so no op needed
                        break;

                    case BackEndMessageCode.IO_ERROR:
                        // Connection broken. Mono returns -1 instead of throwing an exception as ms.net does.
                        throw new IOException();

                    default:
                        // This could mean a number of things
                        //   We've gotten out of sync with the backend?
                        //   We need to implement this type?
                        //   Backend has gone insane?
                        // FIXME
                        // what exception should we really throw here?
                        throw new NotSupportedException(String.Format("Backend sent unrecognized response type: {0}", (Char)message));
                    }
                }
            }
            finally
            {
                context.RequireReadyForQuery = true;
            }
        }
Exemple #4
0
        internal NpgsqlError(Stream stream, byte[] buffer, ByteBuffer queue)
        {
            // Check the messageLength value. If it is 1178686529, this would be the
            // "FATA" string, which would mean a protocol 2.0 error string.
            if (PGUtil.ReadInt32(stream, buffer) == 1178686529)
            {
                string[] v2Parts = ("FATA" + PGUtil.ReadString(stream, queue)).Split(new char[] { ':' }, 2);
                if (v2Parts.Length == 2)
                {
                    _severity = v2Parts[0].Trim();
                    _message  = v2Parts[1].Trim();
                }
                else
                {
                    _severity = string.Empty;
                    _message  = v2Parts[0].Trim();
                }
            }
            else
            {
                for (char field = (char)stream.ReadByte(); field != 0; field = (char)stream.ReadByte())
                {
                    switch (field)
                    {
                    case 'S':
                        _severity = PGUtil.ReadString(stream, queue);
                        break;

                    case 'C':
                        _code = PGUtil.ReadString(stream, queue);
                        break;

                    case 'M':
                        _message = PGUtil.ReadString(stream, queue);
                        break;

                    case 'D':
                        _detail = PGUtil.ReadString(stream, queue);
                        break;

                    case 'H':
                        _hint = PGUtil.ReadString(stream, queue);
                        break;

                    case 'P':
                        _position = PGUtil.ReadString(stream, queue);
                        break;

                    case 'p':
                        _internalPosition = PGUtil.ReadString(stream, queue);
                        break;

                    case 'q':
                        _internalQuery = PGUtil.ReadString(stream, queue);
                        break;

                    case 'W':
                        _where = PGUtil.ReadString(stream, queue);
                        break;

                    case 'F':
                        _file = PGUtil.ReadString(stream, queue);
                        break;

                    case 'L':
                        _line = PGUtil.ReadString(stream, queue);
                        break;

                    case 'R':
                        _routine = PGUtil.ReadString(stream, queue);
                        break;

                    case 's':
                        _schemaName = PGUtil.ReadString(stream, queue);
                        break;

                    case 't':
                        _tableName = PGUtil.ReadString(stream, queue);
                        break;

                    case 'c':
                        _columnName = PGUtil.ReadString(stream, queue);
                        break;

                    case 'd':
                        _datatypeName = PGUtil.ReadString(stream, queue);
                        break;

                    case 'n':
                        _constraintName = PGUtil.ReadString(stream, queue);
                        break;

                    default:
                        // Unknown error field; consume and discard.
                        PGUtil.ReadString(stream, queue);
                        break;
                    }
                }
            }
        }
Exemple #5
0
 internal NpgsqlNotificationEventArgs(Stream stream, bool readAdditional, byte[] buffer, ByteBuffer queue)
 {
     PID                   = PGUtil.ReadInt32(stream, buffer);
     Condition             = PGUtil.ReadString(stream, queue);
     AdditionalInformation = readAdditional ? PGUtil.ReadString(stream, queue) : string.Empty;
 }