Пример #1
0
        internal static void Trace(this ProtocolHeader header, bool send, AmqpConnection connection)
        {
            if (!AmqpTrace.AmqpDebug)
            {
                return;
            }

            string message = string.Format(
                "{0} [{1:X3}.{2:X3} {3:HH:mm:ss.fff}] {4} {5}",
                AppDomain.CurrentDomain.FriendlyName,
                Process.GetCurrentProcess().Id,
                Environment.CurrentManagedThreadId,
                DateTime.UtcNow,
                send ? "SEND" : "RECV",
                header.ToString());

            if (AmqpTrace.TraceCallback != null)
            {
                AmqpTrace.TraceCallback(message);
            }
            else
            {
                System.Diagnostics.Trace.WriteLine(message);
            }
        }
Пример #2
0
 public override void Init(Channel ch, ProtocolHeader hdr)
 {
     if (hdr.Major != 0 && hdr.Minor != 10)
     {
         throw new ProtocolVersionException((sbyte) hdr.Major, (sbyte) hdr.Minor);
     }
 }
Пример #3
0
        public static StreamBuffer GetPacketBufferWithHeader(ref RawStreamBuffer cReceiveBuffer)
        {
            try
            {
                ProtocolHeader pHeader = Packing.GetPacketHeader(cReceiveBuffer.ByteBuffer, cReceiveBuffer.ReadIndex, cReceiveBuffer.WriteIndex);
                if (pHeader != null)
                {
                    if (pHeader.BodyLength > 0)
                    {
                        if ((pHeader.BodyLength + ProtocolHeader.HeadLength) <= (cReceiveBuffer.WriteIndex - cReceiveBuffer.ReadIndex))
                        {
                            byte[] buffer = cReceiveBuffer.Read(pHeader.BodyLength, ProtocolHeader.HeadLength);
                            if (buffer != null)
                            {
                                StreamBuffer sb = new StreamBuffer(pHeader, buffer);
                                return(sb);
                            }
                        }
                    }
                    else if (pHeader.BodyLength == 0)
                    {
                        cReceiveBuffer.Read(ProtocolHeader.HeadLength);
                        StreamBuffer sb = new StreamBuffer(pHeader.ProtocolID, 0);
                        return(sb);
                    }
                }
            }
            catch (Exception e)
            {
                WriteFiles.WritFile.Log(e);
            }

            return(null);
        }
Пример #4
0
            void PumpThread()
            {
                try
                {
                    ProtocolHeader header = Reader.ReadHeader(this.transport);
                    this.connection.OnHeader(header);
                }
                catch (Exception exception)
                {
                    this.connection.OnIoException(exception);
                    return;
                }

                byte[] sizeBuffer = new byte[FixedWidth.UInt];
                while (this.connection.state != ConnectionState.End)
                {
                    try
                    {
                        ByteBuffer buffer = Reader.ReadFrameBuffer(this.transport, sizeBuffer, this.connection.maxFrameSize);
                        this.connection.OnFrame(buffer);
                    }
                    catch (Exception exception)
                    {
                        this.connection.OnIoException(exception);
                    }
                }
            }
Пример #5
0
        internal static async Task <IAsyncTransport> OpenAsync(this SaslProfile saslProfile, string hostname,
                                                               IBufferManager bufferManager, IAsyncTransport transport, DescribedList command)
        {
            // if transport is closed, pump reader should throw exception
            TransportWriter writer = new TransportWriter(transport, e => { });

            ProtocolHeader myHeader = saslProfile.Start(writer, command);

            AsyncPump pump = new AsyncPump(bufferManager, transport);
            SaslCode  code = SaslCode.Auth;

            await pump.PumpAsync(
                SaslProfile.MaxFrameSize,
                header =>
            {
                saslProfile.OnHeader(myHeader, header);
                return(true);
            },
                buffer =>
            {
                return(saslProfile.OnFrame(hostname, writer, buffer, out code));
            });

            await writer.FlushAsync();

            if (code != SaslCode.Ok)
            {
                throw new AmqpException(ErrorCode.UnauthorizedAccess,
                                        Fx.Format(SRAmqp.SaslNegoFailed, code));
            }

            return((IAsyncTransport)saslProfile.UpgradeTransportInternal(transport));
        }
Пример #6
0
        protected override void OnProtocolHeader(ProtocolHeader header)
        {
            Utils.Trace(TraceLevel.Frame, "RECV  {0}", header);
            this.TransitState("R:HDR", StateTransition.ReceiveHeader);
            Exception exception = null;

            if (this.isInitiator)
            {
                if (!this.initialHeader.Equals(header))
                {
                    exception = new AmqpException(AmqpError.NotImplemented, SRClient.ProtocolVersionNotSupported(this.initialHeader.ToString(), header.ToString()));
                }
            }
            else
            {
                ProtocolHeader supportedHeader = this.amqpSettings.GetSupportedHeader(header);
                this.SendProtocolHeader(supportedHeader);
                if (!supportedHeader.Equals(header))
                {
                    exception = new AmqpException(AmqpError.NotImplemented, SRClient.ProtocolVersionNotSupported(this.initialHeader.ToString(), header.ToString()));
                }
            }

            if (exception != null)
            {
                this.CompleteOpen(false, exception);
            }
        }
Пример #7
0
        public bool TryGetTransportProvider(ProtocolHeader header, out TransportProvider provider)
        {
            bool flag;

            if (this.TransportProviders.Count == 0)
            {
                throw new ArgumentException("TransportProviders");
            }
            provider = null;
            using (IEnumerator <TransportProvider> enumerator = this.TransportProviders.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    TransportProvider current = enumerator.Current;
                    if (current.ProtocolId != header.ProtocolId)
                    {
                        continue;
                    }
                    provider = current;
                    flag     = true;
                    return(flag);
                }
                provider = this.GetDefaultProvider();
                return(false);
            }
            return(flag);
        }
Пример #8
0
        internal ProtocolHeader Start(string hostname, ITransport transport)
        {
            ProtocolHeader myHeader = new ProtocolHeader()
            {
                Id = 3, Major = 1, Minor = 0, Revision = 0
            };

            ByteBuffer headerBuffer = new ByteBuffer(
                new byte[] { (byte)'A', (byte)'M', (byte)'Q', (byte)'P', myHeader.Id, myHeader.Major, myHeader.Minor, myHeader.Revision },
                0,
                8,
                8);

            transport.Send(headerBuffer);
            Trace.WriteLine(TraceLevel.Frame, "SEND AMQP {0}", myHeader);

            DescribedList command = this.GetStartCommand(hostname);

            if (command != null)
            {
                this.SendCommand(transport, command);
            }

            return(myHeader);
        }
Пример #9
0
        public async Task PumpAsync(Func <ProtocolHeader, bool> onHeader, Func <ByteBuffer, bool> onBuffer)
        {
            byte[] header = new byte[FixedWidth.ULong];

            if (onHeader != null)
            {
                // header
                await this.ReceiveBufferAsync(header, 0, FixedWidth.ULong);

                if (!onHeader(ProtocolHeader.Create(header, 0)))
                {
                    return;
                }
            }

            // frames
            while (true)
            {
                await this.ReceiveBufferAsync(header, 0, FixedWidth.UInt);

                int frameSize = AmqpBitConverter.ReadInt(header, 0);

                byte[] buffer = new byte[frameSize];
                Buffer.BlockCopy(header, 0, buffer, 0, FixedWidth.UInt);

                await this.ReceiveBufferAsync(buffer, FixedWidth.UInt, frameSize - FixedWidth.UInt);

                if (!onBuffer(new ByteBuffer(buffer, 0, frameSize, frameSize)))
                {
                    break;
                }
            }
        }
Пример #10
0
        void OnReceiveFrameBuffer(ByteBuffer buffer)
        {
            if (this.State <= AmqpObjectState.OpenClosePipe)
            {
                Fx.Assert(buffer.Length == AmqpConstants.ProtocolHeaderSize, "protocol header size is wrong");
                try
                {
                    ProtocolHeader header = new ProtocolHeader();
                    header.Decode(buffer);
                    this.OnProtocolHeader(header);
                }
                catch (Exception exception) when(!Fx.IsFatal(exception))
                {
                    AmqpTrace.Provider.AmqpLogError(this, "OnProtocolHeader", exception);

                    this.TerminalException = exception;
                    this.Abort();
                }
            }
            else
            {
                try
                {
                    this.OnFrameBuffer(buffer);
                }
                catch (Exception exception) when(!Fx.IsFatal(exception))
                {
                    AmqpTrace.Provider.AmqpLogError(this, "OnFrame", exception);

                    this.SafeClose(exception);
                }
            }
        }
Пример #11
0
        internal static async Task <IAsyncTransport> OpenAsync(this SaslProfile saslProfile, string hostname,
                                                               IBufferManager bufferManager, IAsyncTransport transport)
        {
            // if transport is closed, pump reader should throw exception
            TransportWriter writer = new TransportWriter(transport, e => { });

            ProtocolHeader myHeader = saslProfile.Start(hostname, writer);

            AsyncPump pump = new AsyncPump(bufferManager, transport);

            await pump.PumpAsync(
                header =>
            {
                saslProfile.OnHeader(myHeader, header);
                return(true);
            },
                buffer =>
            {
                SaslCode code;
                return(saslProfile.OnFrame(writer, buffer, out code));
            });

            await writer.FlushAsync();

            return((IAsyncTransport)saslProfile.UpgradeTransportInternal(transport));
        }
Пример #12
0
        internal bool OnHeader(ProtocolHeader header)
        {
            Trace.WriteLine(TraceLevel.Frame, "RECV AMQP {0}", header);
            if (header.Id != 0 || header.Major != 1 || header.Minor != 0 || header.Revision != 0)
            {
                throw new AmqpException(ErrorCode.NotImplemented,
                                        Fx.Format(SRAmqp.AmqpProtocolMismatch, header, "0 1 0 0"));
            }

            lock (this.ThisLock)
            {
                if (this.state == ConnectionState.OpenPipe)
                {
                    this.state = ConnectionState.OpenSent;
                }
                else if (this.state == ConnectionState.OpenClosePipe)
                {
                    this.state = ConnectionState.ClosePipe;
                }
                else
                {
                    throw new AmqpException(ErrorCode.IllegalState,
                                            Fx.Format(SRAmqp.AmqpIllegalOperationState, "OnHeader", this.state));
                }
            }

            return(true);
        }
Пример #13
0
        protected virtual void OnReceiveFrameBuffer(ByteBuffer buffer)
        {
            string empty = string.Empty;

            try
            {
                empty = "UsageMeter";
                if (this.usageMeter != null)
                {
                    this.usageMeter.OnBytesRead(buffer.Length);
                }
                if (base.State > AmqpObjectState.OpenClosePipe)
                {
                    empty = "FrameBuffer";
                    this.OnFrameBuffer(buffer);
                }
                else
                {
                    empty = "ProtocolHeader";
                    ProtocolHeader protocolHeader = new ProtocolHeader();
                    protocolHeader.Decode(buffer);
                    this.OnProtocolHeader(protocolHeader);
                }
            }
            catch (Exception exception1)
            {
                Exception exception = exception1;
                if (Fx.IsFatal(exception))
                {
                    throw;
                }
                MessagingClientEtwProvider.TraceClient <AmqpConnectionBase, string, string>((AmqpConnectionBase a, string b, string c) => MessagingClientEtwProvider.Provider.EventWriteAmqpLogError(a, b, c), this, empty, exception.Message);
                base.SafeClose(exception);
            }
        }
Пример #14
0
            private void WriteReplyHeader(ProtocolHeader header, bool fail)
            {
                Action <TransportAsyncCallbackArgs> action;

                MessagingClientEtwProvider.TraceClient <AmqpTransportListener.TransportHandler, ProtocolHeader>((AmqpTransportListener.TransportHandler source, ProtocolHeader detail) => MessagingClientEtwProvider.Provider.EventWriteAmqpLogOperation(source, TraceOperation.Send, detail), this, header);
                header.Encode(new ByteBuffer(this.buffer));
                this.args.SetBuffer(this.buffer, 0, (int)this.buffer.Length);
                TransportAsyncCallbackArgs transportAsyncCallbackArg = this.args;

                if (fail)
                {
                    action = null;
                }
                else
                {
                    action = AmqpTransportListener.TransportHandler.writeCompleteCallback;
                }
                transportAsyncCallbackArg.CompletedCallback = action;
                this.bufferWriter.WriteBuffer(this.args);
                if (fail)
                {
                    this.args.Exception = new NotSupportedException(header.ToString());
                    this.parent.OnHandleTransportComplete(this.args);
                }
            }
Пример #15
0
        void OnAcceptTransport(TransportListener innerListener, TransportAsyncCallbackArgs args)
        {
            TransportBase  transport  = args.Transport;
            AmqpConnection connection = null;
            string         operation  = "Create";

            try
            {
                AmqpSettings           amqpSettings = this.listener.AmqpSettings; // no need to clone
                ProtocolHeader         header       = (ProtocolHeader)args.UserToken;
                AmqpConnectionSettings settings     = this.connectionSettings.Clone();
                connection = this.runtime.CreateConnection(transport, header, false, this.listener.AmqpSettings, settings);

                operation = "BeginOpen";
                connection.BeginOpen(AmqpConstants.DefaultTimeout, OnConnectionOpenComplete, Tuple.Create(this, innerListener, connection));
            }
            catch (Exception ex) when(!Fx.IsFatal(ex))
            {
                AmqpTrace.Provider.AmqpLogError(innerListener, operation, ex);

                if (connection != null)
                {
                    connection.SafeClose(ex);
                }
                else
                {
                    transport.Abort();
                }
            }
        }
Пример #16
0
        private void OnReadHeaderComplete(TransportAsyncCallbackArgs args)
        {
            if (args.Exception != null)
            {
                CompleteOnException(args);
                return;
            }

            try
            {
                ProtocolHeader receivedHeader = new ProtocolHeader();
                receivedHeader.Decode(new ByteBuffer(args.Buffer, args.Offset, args.Count));
                if (!receivedHeader.Equals(_sentHeader))
                {
                    throw new AmqpException(AmqpErrorCode.NotImplemented, $"The requested protocol version {_sentHeader} is not supported. The supported version is {receivedHeader}");
                }

                SaslTransportProvider provider = _amqpSettings.GetTransportProvider <SaslTransportProvider>();
                var transport = provider.CreateTransport(args.Transport, true);
                _tcs.TrySetResult(transport);
            }
            catch (Exception ex)
            {
                args.Exception = ex;
                CompleteOnException(args);
            }
        }
Пример #17
0
        // this is only used by sync client connection
        internal ITransport Open(string hostname, ITransport transport)
        {
            ProtocolHeader myHeader    = this.Start(transport, null);
            ProtocolHeader theirHeader = Reader.ReadHeader(transport);

            Trace.WriteLine(TraceLevel.Frame, "RECV AMQP {0}", theirHeader);
            this.OnHeader(myHeader, theirHeader);

            SaslCode code = SaslCode.SysTemp;

            while (true)
            {
                ByteBuffer buffer = Reader.ReadFrameBuffer(transport, new byte[4], MaxFrameSize);
                if (buffer == null)
                {
                    throw new OperationCanceledException(Fx.Format(SRAmqp.TransportClosed, transport.GetType().Name));
                }

                if (!this.OnFrame(hostname, transport, buffer, out code))
                {
                    break;
                }
            }

            if (code != SaslCode.Ok)
            {
                throw new AmqpException(ErrorCode.UnauthorizedAccess,
                                        Fx.Format(SRAmqp.SaslNegoFailed, code));
            }

            return(this.UpgradeTransport(transport));
        }
Пример #18
0
 public void Init(Object v, ProtocolHeader header)
 {
     lock (_sendlock)
     {
         _sender.Send(header.ToMemoryStream());
         _sender.Flush();
     }
 }
Пример #19
0
 internal void OnHeader(ProtocolHeader myHeader, ProtocolHeader theirHeader)
 {
     if (theirHeader.Id != myHeader.Id || theirHeader.Major != myHeader.Major ||
         theirHeader.Minor != myHeader.Minor || theirHeader.Revision != myHeader.Revision)
     {
         throw new AmqpException(ErrorCode.NotImplemented, theirHeader.ToString());
     }
 }
Пример #20
0
        public ProtocolHeader ExtractProtocolHeader(ByteBuffer buffer)
        {
            if (buffer.Length < ProtocolHeader.Size)
            {
                return(null);
            }

            return(ProtocolHeader.Decode(buffer));
        }
Пример #21
0
 internal void OnHeader(ProtocolHeader myHeader, ProtocolHeader theirHeader)
 {
     if (theirHeader.Id != myHeader.Id || theirHeader.Major != myHeader.Major ||
         theirHeader.Minor != myHeader.Minor || theirHeader.Revision != myHeader.Revision)
     {
         throw new AmqpException(ErrorCode.NotImplemented,
                                 Fx.Format(SRAmqp.AmqpProtocolMismatch, theirHeader, myHeader));
     }
 }
Пример #22
0
        void SendProtocolHeader(ProtocolHeader header)
        {
#if DEBUG
            header.Trace(true);
            AmqpTrace.Provider.AmqpLogOperationVerbose(this, TraceOperation.Send, header);
#endif
            this.TransitState("S:HDR", StateTransition.SendHeader);
            this.SendDatablock(header);
        }
Пример #23
0
 public TestHelperAmqpConnection(
     TransportBase transport,
     ProtocolHeader protocolHeader,
     bool
     isInitiator,
     AmqpSettings amqpSettings,
     AmqpConnectionSettings connectionSettings)
     : base(transport, protocolHeader, isInitiator, amqpSettings, connectionSettings)
 {
 }
Пример #24
0
        public static ProtocolHeader Deserialize(NetBuffer buffer)
        {
            ProtocolHeader head = new ProtocolHeader();

            head.pid      = buffer.ReadUInt();
            head.index    = buffer.ReadUInt();
            head.dataSize = buffer.ReadInt();
            head.checksum = buffer.ReadUShort();
            return(head);
        }
        public AmqpConnection CreateConnection(TransportBase transport, ProtocolHeader protocolHeader, bool isInitiator, AmqpSettings amqpSettings, AmqpConnectionSettings connectionSettings)
        {
            AmqpConnection amqpConnection = new AmqpConnection(transport, protocolHeader, isInitiator, amqpSettings, connectionSettings)
            {
                SessionFactory = this
            };

            MessagingClientEtwProvider.TraceClient(() => MessagingClientEtwProvider.Provider.EventWriteAmqpLogOperation(this, TraceOperation.Connect, amqpConnection));
            return(amqpConnection);
        }
Пример #26
0
 protected override void OnProtocolHeader(ProtocolHeader header)
 {
     if (!this.parent.encoding)
     {
         this.CompleteOpen(false, null);
     }
     else
     {
         this.State = AmqpObjectState.HeaderExchanged;
     }
 }
Пример #27
0
        public ProtocolHeader ExtractProtocolHeader(ByteBuffer buffer)
        {
            if (buffer.Length < 8)
            {
                return(null);
            }
            ProtocolHeader protocolHeader = new ProtocolHeader();

            protocolHeader.Decode(buffer);
            return(protocolHeader);
        }
Пример #28
0
        private void WriteSecurityHeader(TransportAsyncCallbackArgs args)
        {
            TransportProvider item = this.settings.TransportProviders[this.providerIndex];

            this.sentHeader = new ProtocolHeader(item.ProtocolId, item.DefaultVersion);
            ByteBuffer byteBuffer = new ByteBuffer(new byte[8]);

            this.sentHeader.Encode(byteBuffer);
            args.SetBuffer(byteBuffer.Buffer, byteBuffer.Offset, byteBuffer.Length);
            args.CompletedCallback = new Action <TransportAsyncCallbackArgs>(this.OnWriteHeaderComplete);
            this.writer.WriteBuffer(args);
        }
Пример #29
0
        public AmqpConnection CreateConnection(TransportBase transport, ProtocolHeader protocolHeader, bool isInitiator, AmqpSettings amqpSettings, AmqpConnectionSettings connectionSettings)
        {
            if (this.amqpSettings.RequireSecureTransport && !transport.IsSecure)
            {
                throw new AmqpException(AmqpError.NotAllowed, SR.AmqpTransportNotSecure);
            }

            AmqpConnection connection = new AmqpConnection(transport, protocolHeader, isInitiator, amqpSettings, connectionSettings);

            Utils.Trace(TraceLevel.Info, "{0}: Created {1}", this, connection);
            return(connection);
        }
Пример #30
0
        public void TransmitsProtocolHeader()
        {
            _context.Send(_subject, (Connect, new IPEndPoint(IPAddress.Loopback, _port)));

            var socket = _listener.AcceptSocket();
            var buffer = new Byte[8];

            socket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
            ProtocolHeader.Deserialize(buffer, out var result, out var _);

            Assert.Equal(expected: ProtocolHeader.Default, actual: result);
        }
Пример #31
0
        internal static async Task <IAsyncTransport> OpenAsync(this SaslProfile saslProfile, string hostname, IAsyncTransport transport)
        {
            ProtocolHeader header = saslProfile.Start(hostname, transport);

            AsyncPump pump = new AsyncPump(transport);

            await pump.PumpAsync(
                h => { saslProfile.OnHeader(header, h); return(true); },
                b => { SaslCode code; return(saslProfile.OnFrame(transport, b, out code)); });

            return((IAsyncTransport)saslProfile.UpgradeTransportInternal(transport));
        }