예제 #1
0
        public static InboundFrame ReadFrom(NetworkBinaryReader reader)
        {
            int type;

            try
            {
                type = reader.ReadByte();
            }
            catch (IOException ioe) when(
                ioe.InnerException != null &&
                (ioe.InnerException is SocketException) &&
                ((SocketException)ioe.InnerException).SocketErrorCode == SocketError.TimedOut)
            {
                throw ioe.InnerException;
            }

            if (type == 'A')
            {
                // Probably an AMQP protocol header, otherwise meaningless
                ProcessProtocolHeader(reader);
            }

            int channel     = reader.ReadUInt16();
            int payloadSize = reader.ReadInt32(); // FIXME - throw exn on unreasonable value

            byte[] payload = reader.ReadBytes(payloadSize);
            if (payload.Length != payloadSize)
            {
                // Early EOF.
                throw new MalformedFrameException("Short frame - expected " +
                                                  payloadSize + " bytes, got " +
                                                  payload.Length + " bytes");
            }

            int frameEndMarker = reader.ReadByte();

            if (frameEndMarker != Constants.FrameEnd)
            {
                throw new MalformedFrameException("Bad frame end marker: " + frameEndMarker);
            }

            return(new InboundFrame((FrameType)type, channel, payload));
        }
예제 #2
0
        public static List <PDataTF> ReadPDataTFs(NetworkBinaryReader dr)
        {
            var pDatas = new List <PDataTF>();

            do
            {
                try
                {
                    PDataTF pdu;
                    pdu = PDUReader.ReadPDFData(dr).Payload;
                    pDatas.Add(pdu);
                }
                catch (Exception e)
                {
                    throw new Exception("Problem reading PDataTF chain.\n" + e.Message);
                }
            } while (!pDatas.Any(p => p.Items.Any(it => it.Fragment.IsLastItem)));
            return(pDatas);
        }
        public SocketFrameHandler(AmqpTcpEndpoint endpoint,
                                  Func <StreamSocket> socketFactory,
                                  int connectionTimeout,
                                  int _readTimeout,
                                  int _writeTimeout)
        {
            Endpoint = endpoint;

            m_socket = socketFactory();
            Connect(m_socket, endpoint, connectionTimeout);

            if (endpoint.Ssl.Enabled)
            {
                IAsyncAction ar = null;
                try
                {
                    var cts = new CancellationTokenSource();
                    if (this.defaultTimeout.HasValue)
                    {
                        cts.CancelAfter(this.defaultTimeout.Value);
                    }

                    ar = this.m_socket.UpgradeToSslAsync(
                        SocketProtectionLevel.Ssl, new HostName(endpoint.Ssl.ServerName));
                    ar.AsTask(cts.Token).Wait();
                    ar.GetResults();
                }
                catch (Exception)
                {
                    Close();
                    throw;
                }
                finally
                {
                    if (ar != null)
                    {
                        ar.Close();
                    }
                }
            }
            m_reader = new NetworkBinaryReader(m_socket.InputStream.AsStreamForRead());
            m_writer = new NetworkBinaryWriter(m_socket.OutputStream.AsStreamForWrite());
        }
        public SocketFrameHandler(AmqpTcpEndpoint endpoint,
                                  Func <AddressFamily, ITcpClient> socketFactory,
                                  int connectionTimeout, int readTimeout, int writeTimeout)
        {
            Endpoint = endpoint;

            if (ShouldTryIPv6(endpoint))
            {
                try {
                    m_socket = ConnectUsingIPv6(endpoint, socketFactory, connectionTimeout);
                } catch (ConnectFailureException)
                {
                    m_socket = null;
                }
            }

            if (m_socket == null && endpoint.AddressFamily != AddressFamily.InterNetworkV6)
            {
                m_socket = ConnectUsingIPv4(endpoint, socketFactory, connectionTimeout);
            }

            Stream netstream = m_socket.GetStream();

            netstream.ReadTimeout  = readTimeout;
            netstream.WriteTimeout = writeTimeout;

            if (endpoint.Ssl.Enabled)
            {
                try
                {
                    netstream = SslHelper.TcpUpgrade(netstream, endpoint.Ssl);
                }
                catch (Exception)
                {
                    Close();
                    throw;
                }
            }
            m_reader = new NetworkBinaryReader(new BufferedStream(netstream));
            m_writer = new NetworkBinaryWriter(new BufferedStream(netstream));

            m_writeableStateTimeout = writeTimeout;
        }
예제 #5
0
        private async Task <InboundFrame> ReadFrom(Stream reader)
        {
            var buffer = _emptyBuffer;

            await ReadAsync(reader, buffer);

            NetworkBinaryReader headerReader = null;
            int type = buffer[0];

            try
            {
                if (type == 'A')
                {
                    throw new MalformedFrameException("Invalid AMQP protocol header from server");
                }

                var headerReaderBuffer = new byte[6];
                Array.Copy(buffer, 1, headerReaderBuffer, 0, 6);
                headerReader = new NetworkBinaryReader(new MemoryStream(headerReaderBuffer));

                int channel     = headerReader.ReadUInt16();
                int payloadSize = headerReader.ReadInt32(); // FIXME - throw exn on unreasonable value

                byte[] payload = new byte[payloadSize];
                await ReadAsync(reader, payload);

                var frameEndMarkerbuffer = new byte[1];
                await ReadAsync(reader, frameEndMarkerbuffer);

                int frameEndMarker = frameEndMarkerbuffer[0];
                if (frameEndMarker != Constants.FrameEnd)
                {
                    throw new MalformedFrameException("Bad frame end marker: " + frameEndMarker);
                }

                return(new InboundFrame((FrameType)type, channel, payload));
            }
            finally
            {
                headerReader?.Dispose();
            }
        }
        ///<summary>Reads an AMQP "table" definition from the reader.</summary>
        ///<remarks>
        /// Supports the AMQP 0-8/0-9 standard entry types S, I, D, T
        /// and F, as well as the QPid-0-8 specific b, d, f, l, s, t,
        /// x and V types and the AMQP 0-9-1 A type.
        ///</remarks>
        /// <returns>A <seealso cref="System.Collections.Generic.IDictionary{TKey,TValue}"/>.</returns>
        public static IDictionary <string, object> ReadTable(NetworkBinaryReader reader)
        {
            IDictionary <string, object> table = new Dictionary <string, object>();
            long tableLength = reader.ReadUInt32();

            Stream backingStream = reader.BaseStream;
            long   startPosition = backingStream.Position;

            while ((backingStream.Position - startPosition) < tableLength)
            {
                string key   = ReadShortstr(reader);
                object value = ReadFieldValue(reader);

                if (!table.ContainsKey(key))
                {
                    table[key] = value;
                }
            }

            return(table);
        }
예제 #7
0
        public static IDictionary <string, object> ReadMap(NetworkBinaryReader reader)
        {
            int entryCount = BytesWireFormatting.ReadInt32(reader);

            if (entryCount < 0)
            {
                string message = string.Format("Invalid (negative) entryCount: {0}", entryCount);
                throw new ProtocolViolationException(message);
            }

            IDictionary <string, object> table = new Dictionary <string, object>(entryCount);

            for (int entryIndex = 0; entryIndex < entryCount; entryIndex++)
            {
                string key   = StreamWireFormatting.ReadUntypedString(reader);
                object value = StreamWireFormatting.ReadObject(reader);
                table[key] = value;
            }

            return(table);
        }
예제 #8
0
        private static AbstractDIMSE ProcessCommand(List <PDataTF> pDatas, Association asc)
        {
            DICOMObject   dcm = GetCommandObject(pDatas);
            AbstractDIMSE dimse;
            bool          success = DIMSEReader.TryReadDIMSE(dcm, out dimse);

            if (!success)
            {
                asc.Logger.Log("DIMSE could not be read!");
            }
            if (dimse.HasData)
            {
                NetworkBinaryReader dr      = asc.Reader;
                List <PDataTF>      dataPds = ReadPDataTFs(dr);
                int id;
                var txSyntax = GetTransferSyntax(asc, dataPds, out id);
                dimse.DataPresentationContextId = id;
                dimse.Data = GetDataObject(dataPds, txSyntax);
            }
            DIMSEProcessor.Process(dimse, asc);
            return(dimse);
        }
예제 #9
0
        public SocketFrameHandler_0_9(AmqpTcpEndpoint endpoint)
        {
            m_endpoint = endpoint;
            m_socket   = new TcpClient();
            m_socket.Connect(endpoint.HostName, endpoint.Port);
            // disable Nagle's algorithm, for more consistently low latency
            m_socket.NoDelay = true;

            Stream netstream = m_socket.GetStream();

            if (endpoint.Ssl.Enabled)
            {
                try {
                    netstream = SslHelper.TcpUpgrade(netstream, endpoint.Ssl);
                } catch (Exception) {
                    Close();
                    throw;
                }
            }
            m_reader = new NetworkBinaryReader(new BufferedStream(netstream));
            m_writer = new NetworkBinaryWriter(new BufferedStream(netstream));
        }
예제 #10
0
        public static object ReadFieldValue(NetworkBinaryReader reader)
        {
            byte discriminator = reader.ReadByte();

            return(((char)discriminator) switch
            {
                'S' => ReadLongstr(reader),
                'I' => reader.ReadInt32(),
                'i' => reader.ReadUInt32(),
                'D' => ReadDecimal(reader),
                'T' => ReadTimestamp(reader),
                'F' => ReadTable(reader),
                'A' => ReadArray(reader),
                'B' => reader.ReadByte(),
                'b' => reader.ReadSByte(),
                'd' => reader.ReadDouble(),
                'f' => reader.ReadSingle(),
                'l' => reader.ReadInt64(),
                's' => reader.ReadInt16(),
                't' => (ReadOctet(reader) != 0),
                'x' => new BinaryTableValue(ReadLongstr(reader)),
                'V' => null,
                _ => throw new SyntaxException("Unrecognised type in table: " + (char)discriminator),
            });
예제 #11
0

        
예제 #12
0
 public abstract ContentHeaderBase DecodeContentHeaderFrom(NetworkBinaryReader reader);
예제 #13
0
 public abstract MethodBase DecodeMethodFrom(NetworkBinaryReader reader);
 public static ushort ReadShort(NetworkBinaryReader reader)
 {
     return(reader.ReadUInt16());
 }
 public static ulong ReadLonglong(NetworkBinaryReader reader)
 {
     return(reader.ReadUInt64());
 }
        public static object ReadFieldValue(NetworkBinaryReader reader)
        {
            object value         = null;
            byte   discriminator = reader.ReadByte();

            switch ((char)discriminator)
            {
            case 'S':
                value = ReadLongstr(reader);
                break;

            case 'I':
                value = reader.ReadInt32();
                break;

            case 'D':
                value = ReadDecimal(reader);
                break;

            case 'T':
                value = ReadTimestamp(reader);
                break;

            case 'F':
                value = ReadTable(reader);
                break;

            case 'A':
                value = ReadArray(reader);
                break;

            case 'b':
                value = reader.ReadSByte();
                break;

            case 'd':
                value = reader.ReadDouble();
                break;

            case 'f':
                value = reader.ReadSingle();
                break;

            case 'l':
                value = reader.ReadInt64();
                break;

            case 's':
                value = reader.ReadInt16();
                break;

            case 't':
                value = (ReadOctet(reader) != 0);
                break;

            case 'x':
                value = new BinaryTableValue(ReadLongstr(reader));
                break;

            case 'V':
                value = null;
                break;

            default:
                throw new SyntaxError("Unrecognised type in table: " +
                                      (char)discriminator);
            }
            return(value);
        }
 public static double ReadDouble(NetworkBinaryReader reader)
 {
     return(reader.ReadDouble());
 }
 public static char ReadChar(NetworkBinaryReader reader)
 {
     return((char)reader.ReadUInt16());
 }
 public static byte[] ReadBytes(NetworkBinaryReader reader, int count)
 {
     return(reader.ReadBytes(count));
 }
 public static int Read(NetworkBinaryReader reader, byte[] target, int offset, int count)
 {
     return(reader.Read(target, offset, count));
 }
 public MethodArgumentReader(NetworkBinaryReader reader)
 {
     BaseReader = reader;
     ClearBits();
 }
예제 #22
0
        /// <exception cref="EndOfStreamException"/>
        /// <exception cref="ProtocolViolationException"/>
        public static object ReadObject(NetworkBinaryReader reader)
        {
            int typeTag = reader.ReadByte();

            switch (typeTag)
            {
            case -1:
                throw new EndOfStreamException("End of StreamMessage reached");

            case (int)StreamWireFormattingTag.Bool:
            {
                byte value = reader.ReadByte();
                switch (value)
                {
                case 0x00:
                    return(false);

                case 0x01:
                    return(true);

                default:
                {
                    string message =
                        string.Format("Invalid boolean value in StreamMessage: {0}", value);
                    throw new ProtocolViolationException(message);
                }
                }
            }

            case (int)StreamWireFormattingTag.Byte:
                return(reader.ReadByte());

            case (int)StreamWireFormattingTag.Bytes:
            {
                int length = reader.ReadInt32();
                if (length == -1)
                {
                    return(null);
                }
                return(reader.ReadBytes(length));
            }

            case (int)StreamWireFormattingTag.Int16:
                return(reader.ReadInt16());

            case (int)StreamWireFormattingTag.Char:
                return((char)reader.ReadUInt16());

            case (int)StreamWireFormattingTag.Int32:
                return(reader.ReadInt32());

            case (int)StreamWireFormattingTag.Int64:
                return(reader.ReadInt64());

            case (int)StreamWireFormattingTag.Single:
                return(reader.ReadSingle());

            case (int)StreamWireFormattingTag.Double:
                return(reader.ReadDouble());

            case (int)StreamWireFormattingTag.String:
                return(ReadUntypedString(reader));

            case (int)StreamWireFormattingTag.Null:
                return(null);

            default:
            {
                string message = string.Format("Invalid type tag in StreamMessage: {0}", typeTag);
                throw new ProtocolViolationException(message);
            }
            }
        }
예제 #23
0
 public ContentHeaderPropertyReader(NetworkBinaryReader reader)
 {
     BaseReader = reader;
     m_flagWord = 1;  // just the continuation bit
     m_bitCount = 15; // the correct position to force a m_flagWord read
 }
 public static int ReadInt32(NetworkBinaryReader reader)
 {
     return(reader.ReadInt32());
 }
 public static uint ReadLong(NetworkBinaryReader reader)
 {
     return(reader.ReadUInt32());
 }
 public static long ReadInt64(NetworkBinaryReader reader)
 {
     return(reader.ReadInt64());
 }
 public static byte ReadOctet(NetworkBinaryReader reader)
 {
     return(reader.ReadByte());
 }
 public static float ReadSingle(NetworkBinaryReader reader)
 {
     return(reader.ReadSingle());
 }
 public static short ReadInt16(NetworkBinaryReader reader)
 {
     return(reader.ReadInt16());
 }
        public Command HandleFrame(InboundFrame f)
        {
            switch (m_state)
            {
            case AssemblyState.ExpectingMethod:
            {
                if (!f.IsMethod())
                {
                    throw new UnexpectedFrameException(f);
                }
                m_method = m_protocol.DecodeMethodFrom(f.GetReader());
                m_state  = m_method.HasContent
                        ? AssemblyState.ExpectingContentHeader
                        : AssemblyState.Complete;
                return(CompletedCommand());
            }

            case AssemblyState.ExpectingContentHeader:
            {
                if (!f.IsHeader())
                {
                    throw new UnexpectedFrameException(f);
                }
                NetworkBinaryReader reader = f.GetReader();
                m_header = m_protocol.DecodeContentHeaderFrom(reader);
                var totalBodyBytes = m_header.ReadFrom(reader);
                if (totalBodyBytes > MaxArrayOfBytesSize)
                {
                    throw new UnexpectedFrameException(f);
                }
                m_remainingBodyBytes = (int)totalBodyBytes;
                m_body       = new byte[m_remainingBodyBytes];
                m_bodyStream = new MemoryStream(m_body, true);
                UpdateContentBodyState();
                return(CompletedCommand());
            }

            case AssemblyState.ExpectingContentBody:
            {
                if (!f.IsBody())
                {
                    throw new UnexpectedFrameException(f);
                }
                if (f.Payload.Length > m_remainingBodyBytes)
                {
                    throw new MalformedFrameException
                              (string.Format("Overlong content body received - {0} bytes remaining, {1} bytes received",
                                             m_remainingBodyBytes,
                                             f.Payload.Length));
                }
                m_bodyStream.Write(f.Payload, 0, f.Payload.Length);
                m_remainingBodyBytes -= f.Payload.Length;
                UpdateContentBodyState();
                return(CompletedCommand());
            }

            case AssemblyState.Complete:
            default:
#if NETFX_CORE
                Debug.WriteLine("Received frame in invalid state {0}; {1}", m_state, f);
#else
                //Trace.Fail(string.Format("Received frame in invalid state {0}; {1}", m_state, f));
#endif
                return(null);
            }
        }