Example #1
0
            protected internal override void HandleInternal(ChannelHandlerContext ctx, RpcInfo
                                                            info)
            {
                // This is just like what's done in RpcProgramMountd#handleInternal and
                // RpcProgramNfs3#handleInternal.
                RpcCall rpcCall   = (RpcCall)info.Header();
                int     procedure = rpcCall.GetProcedure();

                if (procedure != 0)
                {
                    bool portMonitorSuccess = DoPortMonitoring(info.RemoteAddress());
                    if (!portMonitorSuccess)
                    {
                        SendRejectedReply(rpcCall, info.RemoteAddress(), ctx);
                        return;
                    }
                }
                resultSize = info.Data().ReadableBytes();
                RpcAcceptedReply reply = RpcAcceptedReply.GetAcceptInstance(1234, new VerifierNone
                                                                                ());
                XDR @out = new XDR();

                reply.Write(@out);
                ChannelBuffer b   = ChannelBuffers.WrappedBuffer(@out.AsReadOnlyWrap().Buffer());
                RpcResponse   rsp = new RpcResponse(b, info.RemoteAddress());

                RpcUtil.SendRpcResponse(ctx, rsp);
            }
Example #2
0
            public override void MessageReceived(ChannelHandlerContext ctx, MessageEvent e)
            {
                ChannelBuffer buf = (ChannelBuffer)e.GetMessage();

                // Read reply
                if (!ValidMessageLength(buf.ReadableBytes()))
                {
                    e.GetChannel().Close();
                    return;
                }
                // handling fragment header for TCP, 4 bytes.
                byte[] fragmentHeader = Arrays.CopyOfRange(buf.Array(), 0, 4);
                int    fragmentSize   = XDR.FragmentSize(fragmentHeader);
                bool   isLast         = XDR.IsLastFragment(fragmentHeader);

                System.Diagnostics.Debug.Assert((fragmentSize == 28 && isLast == true));
                XDR xdr = new XDR();

                xdr.WriteFixedOpaque(Arrays.CopyOfRange(buf.Array(), 4, buf.ReadableBytes()));
                RpcReply reply = RpcReply.Read(xdr);

                if (reply.GetState() == RpcReply.ReplyState.MsgAccepted)
                {
                    RpcAcceptedReply acceptedReply = (RpcAcceptedReply)reply;
                    Handle(acceptedReply, xdr);
                }
                else
                {
                    RpcDeniedReply deniedReply = (RpcDeniedReply)reply;
                    Handle(deniedReply);
                }
                e.GetChannel().Close();
            }
Example #3
0
        private void ReadNextChunk()
        {
            ChannelBuffer readBuffer = ReadNext();

            /* Header layout:
             * [    ,    ][    ,   x] 0: last chunk in message, 1: there a more chunks after this one
             * [    ,    ][    ,  x ] 0: success, 1: failure
             * [    ,    ][xxxx,xx  ] internal protocol version
             * [xxxx,xxxx][    ,    ] application protocol version */
            sbyte[] header = new sbyte[2];
            readBuffer.readBytes(header);
            _more    = (header[0] & 0x1) != 0;
            _failure = (header[0] & 0x2) != 0;
            AssertSameProtocolVersion(header, _internalProtocolVersion, _applicationProtocolVersion);

            if (!_more && _buffer == null)
            {
                // Optimization: this is the first chunk and it'll be the only chunk
                // in this message.
                _buffer = readBuffer;
            }
            else
            {
                _buffer = _buffer == null?ChannelBuffers.dynamicBuffer() : _buffer;

                DiscardReadBytes();
                _buffer.writeBytes(readBuffer);
            }

            if (_failure)
            {
                ReadAndThrowFailureResponse();
            }
        }
        protected internal void DecodeHeader(ChannelBuffer buf, IMessageTree tree)
        {
            BufferHelper helper = _mBufferHelper;
            String id = helper.Read(buf, TAB);
            String domain = helper.Read(buf, TAB);
            String hostName = helper.Read(buf, TAB);
            String ipAddress = helper.Read(buf, TAB);
            String threadGroupName = helper.Read(buf, TAB);
            String threadId = helper.Read(buf, TAB);
            String threadName = helper.Read(buf, TAB);
            String messageId = helper.Read(buf, TAB);
            String parentMessageId = helper.Read(buf, TAB);
            String rootMessageId = helper.Read(buf, TAB);
            String sessionToken = helper.Read(buf, LF);

            if (ID.Equals(id))
            {
                tree.Domain = domain;
                tree.HostName = hostName;
                tree.IpAddress = ipAddress;
                tree.ThreadGroupName = threadGroupName;
                tree.ThreadId = threadId;
                tree.ThreadName = threadName;
                tree.MessageId = messageId;
                tree.ParentMessageId = parentMessageId;
                tree.RootMessageId = rootMessageId;
                tree.SessionToken = sessionToken;
            }
            else
            {
                throw new Exception("Unrecognized id(" + id + ") for plain text message codec!");
            }
        }
Example #5
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public org.neo4j.kernel.impl.transaction.TransactionRepresentation read(org.jboss.netty.buffer.ChannelBuffer buffer, ByteBuffer temporaryBuffer) throws java.io.IOException
            public override TransactionRepresentation Read(ChannelBuffer buffer, ByteBuffer temporaryBuffer)
            {
                NetworkReadableClosableChannel channel = new NetworkReadableClosableChannel(buffer);

                int  authorId = channel.Int;
                int  masterId = channel.Int;
                long latestCommittedTxWhenStarted = channel.Long;
                long timeStarted   = channel.Long;
                long timeCommitted = channel.Long;

                int headerLength = channel.Int;

                sbyte[] header = new sbyte[headerLength];
                channel.Get(header, headerLength);

                LogEntryCommand        entryRead;
                IList <StorageCommand> commands = new LinkedList <StorageCommand>();

                while ((entryRead = ( LogEntryCommand )Reader.readLogEntry(channel)) != null)
                {
                    commands.Add(entryRead.Command);
                }

                PhysicalTransactionRepresentation toReturn = new PhysicalTransactionRepresentation(commands);

                toReturn.SetHeader(header, masterId, authorId, timeStarted, latestCommittedTxWhenStarted, timeCommitted, -1);
                return(toReturn);
            }
        public virtual IMessageTree Decode(ChannelBuffer buf)
        {
            DefaultMessageTree tree = new DefaultMessageTree();

            Decode(buf, tree);
            return tree;
        }
            public override void MessageReceived(ChannelHandlerContext ctx, MessageEvent e)
            {
                // Get handle from create response
                ChannelBuffer buf = (ChannelBuffer)e.GetMessage();
                XDR           rsp = new XDR(buf.Array());

                if (rsp.GetBytes().Length == 0)
                {
                    Log.Info("rsp length is zero, why?");
                    return;
                }
                Log.Info("rsp length=" + rsp.GetBytes().Length);
                RpcReply reply = RpcReply.Read(rsp);
                int      xid   = reply.GetXid();

                // Only process the create response
                if (xid != unchecked ((int)(0x8000004c)))
                {
                    return;
                }
                int status = rsp.ReadInt();

                if (status != Nfs3Status.Nfs3Ok)
                {
                    Log.Error("Create failed, status =" + status);
                    return;
                }
                Log.Info("Create succeeded");
                rsp.ReadBoolean();
                // value follow
                handle = new FileHandle();
                handle.Deserialize(rsp);
                channel = e.GetChannel();
            }
Example #8
0
 internal PartialRequest(Server <T, R> outerInstance, RequestType type, RequestContext context, ChannelBuffer buffer)
 {
     this._outerInstance = outerInstance;
     this.Type           = type;
     this.Context        = context;
     this.Buffer         = buffer;
 }
Example #9
0
        public virtual void TestSingleFrame()
        {
            RpcUtil.RpcFrameDecoder decoder = new RpcUtil.RpcFrameDecoder();
            // Test "Length field is not received yet"
            ByteBuffer    buffer        = ByteBuffer.Allocate(1);
            ChannelBuffer buf           = new ByteBufferBackedChannelBuffer(buffer);
            ChannelBuffer channelBuffer = (ChannelBuffer)decoder.Decode(Org.Mockito.Mockito.Mock
                                                                        <ChannelHandlerContext>(), Org.Mockito.Mockito.Mock <Org.Jboss.Netty.Channel.Channel
                                                                                                                             >(), buf);

            Assert.True(channelBuffer == null);
            // Test all bytes are not received yet
            byte[] fragment = new byte[4 + 9];
            fragment[0] = unchecked ((byte)(1 << 7));
            // final fragment
            fragment[1] = 0;
            fragment[2] = 0;
            fragment[3] = unchecked ((byte)10);
            // fragment size = 10 bytes
            Assert.True(XDR.IsLastFragment(fragment));
            Assert.True(XDR.FragmentSize(fragment) == 10);
            buffer = ByteBuffer.Allocate(4 + 9);
            buffer.Put(fragment);
            buffer.Flip();
            buf           = new ByteBufferBackedChannelBuffer(buffer);
            channelBuffer = (ChannelBuffer)decoder.Decode(Org.Mockito.Mockito.Mock <ChannelHandlerContext
                                                                                    >(), Org.Mockito.Mockito.Mock <Org.Jboss.Netty.Channel.Channel>(), buf);
            Assert.True(channelBuffer == null);
        }
Example #10
0
 public static void WriteChars(ChannelBuffer buffer, char[] chars)
 {
     // TODO optimize?
     foreach (char ch in chars)
     {
         buffer.writeChar(ch);
     }
 }
Example #11
0
 public RpcInfo(RpcMessage header, ChannelBuffer data, ChannelHandlerContext channelContext
                , Org.Jboss.Netty.Channel.Channel channel, EndPoint remoteAddress)
 {
     this.header        = header;
     this.data          = data;
     this.channel       = channel;
     this.remoteAddress = remoteAddress;
 }
Example #12
0
 private static void WriteStoreId(StoreId storeId, ChannelBuffer targetBuffer)
 {
     targetBuffer.writeLong(storeId.CreationTime);
     targetBuffer.writeLong(storeId.RandomId);
     targetBuffer.writeLong(storeId.StoreVersion);
     targetBuffer.writeLong(storeId.UpgradeTime);
     targetBuffer.writeLong(storeId.UpgradeId);
 }
Example #13
0
 internal TargetCaller(Server <T, R> outerInstance, RequestType type, Channel channel, RequestContext context, ChunkingChannelBuffer targetBuffer, ChannelBuffer bufferToReadFrom)
 {
     this._outerInstance   = outerInstance;
     this.Type             = type;
     this.Channel          = channel;
     this.Context          = context;
     this.TargetBuffer     = targetBuffer;
     this.BufferToReadFrom = bufferToReadFrom;
 }
Example #14
0
//JAVA TO C# CONVERTER WARNING: 'final' parameters are ignored unless the option to convert to C# 7.2 'in' parameters is selected:
//ORIGINAL LINE: protected org.jboss.netty.channel.ChannelFutureListener newChannelFutureListener(final org.jboss.netty.buffer.ChannelBuffer buffer)
        protected internal override ChannelFutureListener NewChannelFutureListener(ChannelBuffer buffer)
        {
            return(future =>
            {
                buffer.clear();
                _freeBuffers.AddLast(buffer);
                BufferReusingChunkingChannelBuffer.this.OperationComplete(future);
            });
        }
Example #15
0
 public override ChannelFuture Write(object message)
 {
     if (message is ChannelBuffer)
     {
         ChannelBuffer buffer = ( ChannelBuffer )message;
         _receivedMessages.AddLast(buffer.duplicate());
     }
     return(immediateFuture);
 }
        public ProducerChannel(string uri, bool isReliable, bool isInOrder)
        {
            Uri = uri;
            IsReliable = isReliable;
            IsInOrder = isInOrder;

            Buffer = new ChannelBuffer();
            _isOpen = new ThreadSafe.Boolean(false);
        }
Example #17
0
 public ChunkingChannelBuffer(ChannelBuffer buffer, Channel channel, int capacity, sbyte internalProtocolVersion, sbyte applicationProtocolVersion)
 {
     this._buffer   = buffer;
     this._channel  = channel;
     this._capacity = capacity;
     this._internalProtocolVersion    = internalProtocolVersion;
     this._applicationProtocolVersion = applicationProtocolVersion;
     AddRoomForContinuationHeader();
 }
Example #18
0
 public static string ReadString(ChannelBuffer buffer, int length)
 {
     char[] chars = new char[length];
     for (int i = 0; i < length; i++)
     {
         chars[i] = buffer.readChar();
     }
     return(new string( chars ));
 }
Example #19
0
            /// <exception cref="System.Exception"/>
            public override void MessageReceived(ChannelHandlerContext ctx, MessageEvent e)
            {
                RpcResponse r = (RpcResponse)e.GetMessage();

                byte[]        fragmentHeader = XDR.RecordMark(r.Data().ReadableBytes(), true);
                ChannelBuffer header         = ChannelBuffers.WrappedBuffer(fragmentHeader);
                ChannelBuffer d = ChannelBuffers.WrappedBuffer(header, r.Data());

                e.GetChannel().Write(d);
            }
Example #20
0
 public BlockLogReader(ChannelBuffer source)
 {
     if (!InstanceFieldsInitialized)
     {
         InitializeInstanceFields();
         InstanceFieldsInitialized = true;
     }
     this._source = source;
     ReadNextBlock();
 }
Example #21
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void serializeRequest(org.jboss.netty.channel.Channel channel, org.jboss.netty.buffer.ChannelBuffer buffer, RequestType type, RequestContext ctx, Serializer payload) throws java.io.IOException
        public virtual void SerializeRequest(Channel channel, ChannelBuffer buffer, RequestType type, RequestContext ctx, Serializer payload)
        {
            buffer.clear();
            ChunkingChannelBuffer chunkingBuffer = new ChunkingChannelBuffer(buffer, channel, _chunkSize, _internalProtocolVersion, _applicationProtocolVersion);

            chunkingBuffer.WriteByte(type.Id());
            WriteContext(ctx, chunkingBuffer);
            payload.Write(chunkingBuffer);
            chunkingBuffer.Done();
        }
Example #22
0
        private void WriteContext(RequestContext context, ChannelBuffer targetBuffer)
        {
            targetBuffer.writeLong(context.Epoch);
            targetBuffer.writeInt(context.MachineId());
            targetBuffer.writeInt(context.EventIdentifier);
            long tx = context.LastAppliedTransaction();

            targetBuffer.writeLong(tx);
            targetBuffer.writeLong(context.Checksum);
        }
Example #23
0
        public static void WriteLog(string Text, ChannelBuffer buffer = null)
        {
            if (buffer == null)
            {
                buffer = CurrentChannelBuffer;
            }

            buffer.ChatBuf.PushMessage(null, Text, MessageType.Preview);
            buffer.SystemActivity = true;
        }
Example #24
0
        public override String ToString()
        {
            PlainTextMessageCodec codec = new PlainTextMessageCodec();
            ChannelBuffer         buf   = new ChannelBuffer(8192);

            codec.EncodeMessage(this, buf);
            buf.Reset();

            return(buf.ToString());
        }
Example #25
0
//JAVA TO C# CONVERTER WARNING: 'final' parameters are ignored unless the option to convert to C# 7.2 'in' parameters is selected:
//ORIGINAL LINE: protected void handleRequest(org.jboss.netty.buffer.ChannelBuffer buffer, final org.jboss.netty.channel.Channel channel)
        protected internal virtual void HandleRequest(ChannelBuffer buffer, Channel channel)
        {
            sbyte?continuation = ReadContinuationHeader(buffer, channel);

            if (continuation == null)
            {
                return;
            }
            if (continuation.Value == ChunkingChannelBuffer.CONTINUATION_MORE)
            {
                PartialRequest partialRequest = _partialRequests[channel];
                if (partialRequest == null)
                {
                    // This is the first chunk in a multi-chunk request
                    RequestType    type         = GetRequestContext(buffer.readByte());
                    RequestContext context      = ReadContext(buffer);
                    ChannelBuffer  targetBuffer = MapSlave(channel, context);
                    partialRequest            = new PartialRequest(this, type, context, targetBuffer);
                    _partialRequests[channel] = partialRequest;
                }
                partialRequest.Add(buffer);
            }
            else
            {
                PartialRequest partialRequest = _partialRequests.Remove(channel);
                RequestType    type;
                RequestContext context;
                ChannelBuffer  targetBuffer;
                ChannelBuffer  bufferToReadFrom;
                ChannelBuffer  bufferToWriteTo;
                if (partialRequest == null)
                {
                    // This is the one and single chunk in the request
                    type             = GetRequestContext(buffer.readByte());
                    context          = ReadContext(buffer);
                    targetBuffer     = MapSlave(channel, context);
                    bufferToReadFrom = buffer;
                    bufferToWriteTo  = targetBuffer;
                }
                else
                {
                    // This is the last chunk in a multi-chunk request
                    type         = partialRequest.Type;
                    context      = partialRequest.Context;
                    targetBuffer = partialRequest.Buffer;
                    partialRequest.Add(buffer);
                    bufferToReadFrom = targetBuffer;
                    bufferToWriteTo  = ChannelBuffers.dynamicBuffer();
                }

                bufferToWriteTo.clear();
                ChunkingChannelBuffer chunkingBuffer = NewChunkingBuffer(bufferToWriteTo, channel, _chunkSize, InternalProtocolVersion, _applicationProtocolVersion);
                SubmitSilent(_targetCallExecutor, new TargetCaller(this, type, channel, context, chunkingBuffer, bufferToReadFrom));
            }
        }
Example #26
0
 public BlockLogBuffer(ChannelBuffer target, ByteCounterMonitor monitor)
 {
     if (!InstanceFieldsInitialized)
     {
         InitializeInstanceFields();
         InstanceFieldsInitialized = true;
     }
     this._target  = target;
     this._monitor = monitor;
     ClearInternalBuffer();
 }
Example #27
0
        public static void WriteChannelCommit(Org.Jboss.Netty.Channel.Channel channel, XDR
                                              @out, int xid)
        {
            if (RpcProgramNfs3.Log.IsDebugEnabled())
            {
                RpcProgramNfs3.Log.Debug("Commit done:" + xid);
            }
            ChannelBuffer outBuf = XDR.WriteMessageTcp(@out, true);

            channel.Write(outBuf);
        }
        public virtual void Decode(ChannelBuffer buf, IMessageTree tree)
        {

            // buf.ReadInt();// read body length

            DecodeHeader(buf, tree);

            if (buf.ReadableBytes() > 0)
            {
                DecodeMessage(buf, tree);
            }
        }
Example #29
0
 private void SendChunkIfNeeded(int bytesPlus)
 {
     // Note: This is wasteful, it should pack as much data as possible into the current chunk before sending it off.
     // Refactor when there is time.
     if (WriterIndex() + bytesPlus >= _capacity)
     {
         Continuation = CONTINUATION_MORE;
         WriteCurrentChunk();
         _buffer = NewChannelBuffer();
         AddRoomForContinuationHeader();
     }
 }
Example #30
0
        public override string ToString()
        {
            PlainTextMessageCodec codec = new PlainTextMessageCodec();
            ChannelBuffer         buf   = new ChannelBuffer(8192);

            codec.Encode(this, buf);

            buf.Reset();
            buf.Skip(4); // get rid of length

            return(buf.ToString());
        }
Example #31
0
        public override void ChannelConnected(ChannelHandlerContext ctx, ChannelStateEvent
                                              e)
        {
            // Send the request
            if (Log.IsDebugEnabled())
            {
                Log.Debug("sending PRC request");
            }
            ChannelBuffer outBuf = XDR.WriteMessageTcp(request, true);

            e.GetChannel().Write(outBuf);
        }
Example #32
0
        protected internal static void SendRejectedReply(RpcCall call, EndPoint remoteAddress
                                                         , ChannelHandlerContext ctx)
        {
            XDR            @out  = new XDR();
            RpcDeniedReply reply = new RpcDeniedReply(call.GetXid(), RpcReply.ReplyState.MsgDenied
                                                      , RpcDeniedReply.RejectState.AuthError, new VerifierNone());

            reply.Write(@out);
            ChannelBuffer buf = ChannelBuffers.WrappedBuffer(@out.AsReadOnlyWrap().Buffer());
            RpcResponse   rsp = new RpcResponse(buf, remoteAddress);

            RpcUtil.SendRpcResponse(ctx, rsp);
        }
Example #33
0
            // NOTICE: this assumes a "smart" ChannelBuffer that continues to next chunk
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public Void read(org.jboss.netty.buffer.ChannelBuffer buffer, ByteBuffer temporaryBuffer) throws java.io.IOException
            public override Void Read(ChannelBuffer buffer, ByteBuffer temporaryBuffer)
            {
                int pathLength;

                while (0 != (pathLength = buffer.readUnsignedShort()))
                {
                    string path    = ReadString(buffer, pathLength);
                    bool   hasData = buffer.readByte() == 1;
                    Writer.write(path, hasData ? new BlockLogReader(buffer) : null, temporaryBuffer, hasData, 1);
                }
                Writer.Dispose();
                return(null);
            }
Example #34
0
 public override void ReadBytes(ChannelBuffer dst, int length)
 {
     try
     {
         sbyte[] array = new sbyte[length];
         @delegate.Get(array, length);
         dst.writeBytes(array);
     }
     catch (ReadPastEndException e)
     {
         throw OutOfBounds(e);
     }
 }
        public virtual void Encode(IMessageTree tree, ChannelBuffer buf)
        {
            int count = 0;

            buf.WriteInt(0); // place-holder
            count += EncodeHeader(tree, buf);

            if (tree.Message != null)
            {
                count += EncodeMessage(tree.Message, buf);
            }

            buf.SetInt(0, count);
        }
Example #36
0
        /// <summary> DoReadChars -> doReadChars
        /// 
        /// Reads from the channel until the requested number of characters
        /// have been seen, EOF is seen, or the channel would block.  EOL
        /// and EOF translation is done.  If reading binary data, the raw
        /// bytes are wrapped in a Tcl byte array object.  Otherwise, the raw
        /// bytes are converted to characters using the channel's current
        /// encoding and stored in a Tcl string object.
        /// 
        /// </summary>
        /// <param name="obj">Input data is stored in this object.
        /// </param>
        /// <param name="toRead">Maximum number of characters to store,
        /// or -1 to read all available data (up to EOF
        /// or when channel blocks).
        /// </param>

        internal int doReadChars(TclObject obj, int toRead)
        {
            ChannelBuffer buf;
            int copied, copiedNow, result;
            IntPtr offset = new IntPtr(this);

            if ((System.Object)encoding == null)
            {
                TclByteArray.SetLength(null, obj, 0);
            }
            else
            {
                TclString.empty(obj);
            }
            offset.i = 0;

            // if toRead is negative, read until EOF
            if (toRead < 0)
            {
                toRead = System.Int32.MaxValue;
            }

            {
                for (copied = 0; toRead > 0; )
                {
                    copiedNow = -1;
                    if (inQueueHead != null)
                    {
                        if ((System.Object)encoding == null)
                        {
                            System.Diagnostics.Debug.WriteLine("calling readBytes " + toRead);
                            copiedNow = readBytes(obj, toRead, offset);
                        }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine("calling readChars " + toRead);
                            copiedNow = readChars(obj, toRead);
                        }

                        // If the current buffer is empty recycle it.

                        buf = inQueueHead;
                        System.Diagnostics.Debug.WriteLine("after read* buf.nextRemoved is " + buf.nextRemoved);
                        System.Diagnostics.Debug.WriteLine("after read* buf.nextAdded is " + buf.nextAdded);

                        if (buf.nextRemoved == buf.nextAdded)
                        {
                            System.Diagnostics.Debug.WriteLine("recycling empty buffer");
                            ChannelBuffer next;

                            next = buf.next;
                            recycleBuffer(buf, false);
                            inQueueHead = next;
                            if (next == null)
                            {
                                System.Diagnostics.Debug.WriteLine("inQueueTail set to null");
                                inQueueTail = null;
                            }
                            else
                            {
                                System.Diagnostics.Debug.WriteLine("inQueueTail is not null");
                            }
                        }
                    }
                    if (copiedNow < 0)
                    {
                        System.Diagnostics.Debug.WriteLine("copiedNow < 0");
                        if (eofCond)
                        {
                            System.Diagnostics.Debug.WriteLine("eofCond");
                            break;
                        }
                        if (blocked)
                        {
                            System.Diagnostics.Debug.WriteLine("blocked");
                            if (!blocking)
                            {
                                break;
                            }
                            blocked = false;
                        }
                        result = Input;
                        if (result != 0)
                        {
                            System.Diagnostics.Debug.WriteLine("non-zero result");
                            if (result == TclPosixException.EAGAIN)
                            {
                                break;
                            }
                            copied = -1;
                            goto done_brk; //goto done
                        }
                    }
                    else
                    {
                        copied += copiedNow;
                        System.Diagnostics.Debug.WriteLine("copied incremented to " + copied);
                        toRead -= copiedNow;
                        System.Diagnostics.Debug.WriteLine("toRead decremented to " + toRead);
                    }
                }

                blocked = false;

                if ((System.Object)encoding == null)
                {
                    TclByteArray.SetLength(null, obj, offset.i);
                    System.Diagnostics.Debug.WriteLine("set byte array length to " + offset.i);
                }
            }

        done_brk:
            ;
            // end done: block

            //done:
            updateInterest();

#if DEBUG
				System.Diagnostics.Debug.WriteLine("returning copied = " + copied);
				
				System.Diagnostics.Debug.WriteLine("returning string \"" + obj + "\"");
				obj.invalidateStringRep();
				
				System.Diagnostics.Debug.WriteLine("returning string \"" + obj + "\"");
#endif

            return copied;
        }
Example #37
0
        /// <summary> RecycleBuffer -> recycleBuffer
        /// 
        /// Helper function to recycle input buffers. Ensures that
        /// two input buffers are saved (one in the input queue and
        /// another in the saveInBuf field). Only if these conditions
        /// are met is the buffer released so that it can be
        /// garbage collected.
        /// </summary>

        private void recycleBuffer(ChannelBuffer buf, bool mustDiscard)
        {

            if (mustDiscard)
                return;

            // Only save buffers which are at least as big as the requested
            // buffersize for the channel. This is to honor dynamic changes
            // of the buffersize made by the user.

            if ((buf.bufLength - Tcl.Lang.ChannelBuffer.BUFFER_PADDING) < bufSize)
            {
                return;
            }

            if (inQueueHead == null)
            {
                inQueueHead = buf;
                inQueueTail = buf;

                buf.nextRemoved = Tcl.Lang.ChannelBuffer.BUFFER_PADDING;
                buf.nextAdded = Tcl.Lang.ChannelBuffer.BUFFER_PADDING;
                buf.next = null;
                return;
            }
            if (saveInBuf == null)
            {
                saveInBuf = buf;

                buf.nextRemoved = Tcl.Lang.ChannelBuffer.BUFFER_PADDING;
                buf.nextAdded = Tcl.Lang.ChannelBuffer.BUFFER_PADDING;
                buf.next = null;
                return;
            }
        }
Example #38
0
        /// <summary> FilterInputBytes -> filterBytes
        /// 
        /// Helper function for getsObj. Appends Unicode characters
        /// onto the TclObject associated with the GetsState after
        /// converting them from raw bytes encoded in the Channel.
        /// 
        /// Consumes available bytes from channel buffers.  When channel
        /// buffers are exhausted, reads more bytes from channel device into
        /// a new channel buffer.  It is the caller's responsibility to
        /// free the channel buffers that have been exhausted.
        /// 
        /// The return value is -1 if there was an error reading from the
        /// channel, 0 otherwise.
        /// 
        /// FIXME: Doc modification of object's StringBuffer
        /// 
        /// Status object keeps track of how much data from channel buffers
        /// has been consumed and where characters should be stored.
        /// </summary>

        internal int filterBytes(GetsState gs)
        {
            ChannelBuffer buf;
            byte[] raw;
            int rawStart, rawEnd;
            char[] dst;
            int offset, toRead, spaceLeft, result, rawLen, length;
            TclObject obj;
            int ENCODING_LINESIZE = 20; // Lower bound on how many bytes
            // to convert at a time. Since we
            // don't know a priori how many
            // bytes of storage this many
            // source bytes will use, we
            // actually need at least
            // ENCODING_LINESIZE bytes of room.

            bool goto_read = false; // Set to true when jumping to the read
            // label, used to simulate a goto.

            obj = gs.obj;

            // Subtract the number of bytes that were removed from channel buffer
            // during last call.

            buf = gs.buf;
            if (buf != null)
            {
                buf.nextRemoved += gs.rawRead.i;
                if (buf.nextRemoved >= buf.nextAdded)
                {
                    buf = buf.next;
                }
            }
            gs.totalChars += gs.charsWrote.i;

            while (true)
            {
                if (goto_read || (buf == null) || (buf.nextAdded == Tcl.Lang.ChannelBuffer.BUFFER_PADDING))
                {
                    // All channel buffers were exhausted and the caller still hasn't
                    // seen EOL.  Need to read more bytes from the channel device.
                    // Side effect is to allocate another channel buffer.

                    //read:
                    if (blocked)
                    {
                        if (!blocking)
                        {
                            gs.charsWrote.i = 0;
                            gs.rawRead.i = 0;
                            return -1;
                        }
                        blocked = false;
                    }
                    if (Input != 0)
                    {
                        gs.charsWrote.i = 0;
                        gs.rawRead.i = 0;
                        return -1;
                    }
                    buf = inQueueTail;
                    gs.buf = buf;
                }

                // Convert some of the bytes from the channel buffer to characters.
                // Space in obj's string rep is used to hold the characters.

                rawStart = buf.nextRemoved;
                raw = buf.buf;
                rawEnd = buf.nextAdded;
                rawLen = rawEnd - rawStart;

                //dst = *gsPtr->dstPtr;
                //offset = dst - objPtr->bytes;
                toRead = ENCODING_LINESIZE;
                if (toRead > rawLen)
                {
                    toRead = rawLen;
                }
                //dstNeeded = toRead * TCL_UTF_MAX + 1;
                //spaceLeft = objPtr->length - offset - TCL_UTF_MAX - 1;
                //if (dstNeeded > spaceLeft) {
                //    length = offset * 2;
                //    if (offset < dstNeeded) {
                //        length = offset + dstNeeded;
                //    }
                //    length += TCL_UTF_MAX + 1;
                //    Tcl_SetObjLength(objPtr, length);
                //    spaceLeft = length - offset;
                //    dst = objPtr->bytes + offset;
                //    *gsPtr->dstPtr = dst;
                //}
                dst = new char[toRead];
                gs.state = encodingState;
                result = externalToUnicode(raw, rawStart, rawLen, dst, 0, toRead, gs.rawRead, null, gs.charsWrote);
                TclString.append(gs.obj, dst, 0, gs.charsWrote.i);

                // Make sure that if we go through 'gets', that we reset the
                // TCL_ENCODING_START flag still.

                encodingStart = false;

                if (result == TCL_CONVERT_MULTIBYTE)
                {
                    // The last few bytes in this channel buffer were the start of a
                    // multibyte sequence.  If this buffer was full, then move them to
                    // the next buffer so the bytes will be contiguous.  

                    ChannelBuffer next;
                    int extra;

                    next = buf.next;
                    if (buf.nextAdded < buf.bufLength)
                    {
                        if (gs.rawRead.i > 0)
                        {
                            // Some raw bytes were converted to UTF-8.  Fall through,
                            // returning those UTF-8 characters because a EOL might be
                            // present in them.
                        }
                        else if (eofCond)
                        {
                            // There was a partial character followed by EOF on the
                            // device.  Fall through, returning that nothing was found.

                            buf.nextRemoved = buf.nextAdded;
                        }
                        else
                        {
                            // There are no more cached raw bytes left.  See if we can
                            // get some more.

                            goto_read = true;
                            goto read; //goto read;
                        }
                    }
                    else
                    {
                        if (next == null)
                        {
                            next = new ChannelBuffer(bufSize);
                            buf.next = next;
                            inQueueTail = next;
                        }
                        extra = rawLen - gs.rawRead.i;
                        Array.Copy(raw, gs.rawRead.i, next.buf, Tcl.Lang.ChannelBuffer.BUFFER_PADDING - extra, extra);
                        next.nextRemoved -= extra;
                        buf.nextAdded -= extra;
                    }
                }

                goto read_brk; // End loop in the normal case

      read:
                ;
            }

        read_brk:
            ;


            gs.buf = buf;
            return 0;
        }
Example #39
0
        public override String ToString()
        {
            try
            {
                PlainTextMessageCodec codec = new PlainTextMessageCodec();
                ChannelBuffer buf = new ChannelBuffer(8192);

                codec.Encode(this, buf);

                buf.Reset();
                buf.Skip(4); // get rid of length

                return buf.ToString();
            }
            catch (Exception ex)
            {
                Cat.lastException = ex;
                return "";
            }
        }
        protected internal IMessage DecodeLine(ChannelBuffer buf, ITransaction parent,
                                               Stack<ITransaction> stack, IMessageTree tree)
        {
            BufferHelper helper = _mBufferHelper;
            byte identifier = buf.ReadByte();
            String timestamp = helper.Read(buf, TAB);
            String type = helper.Read(buf, TAB);
            String name = helper.Read(buf, TAB);

            if (identifier == 'E')
            {
                IMessage evt = new DefaultEvent(type, name);
                String status = helper.Read(buf, TAB);
                String data = helper.ReadRaw(buf, TAB);

                helper.Read(buf, LF); // get rid of line feed
                evt.Timestamp = _mDateHelper.Parse(timestamp);
                evt.Status = status;
                evt.AddData(data);

                if (parent != null)
                {
                    parent.AddChild(evt);
                    tree.EstimatedByteSize += evt.EstimateByteSize();
                    return parent;
                }
                return evt;
            }
            if (identifier == 'M')
            {
                DefaultMetric metric = new DefaultMetric(type, name);
                String status = helper.Read(buf, TAB);
                String data = helper.ReadRaw(buf, TAB);

                helper.Read(buf, LF); // get rid of line feed
                metric.Timestamp = _mDateHelper.Parse(timestamp);
                metric.Status = status;
                metric.AddData(data);

                if (parent != null)
                {
                    parent.AddChild(metric);
                    tree.EstimatedByteSize += metric.EstimateByteSize();
                    return parent;
                }
                return metric;
            }
            if (identifier == 'H')
            {
                IMessage heartbeat = new DefaultHeartbeat(type, name);
                String status0 = helper.Read(buf, TAB);
                String data1 = helper.ReadRaw(buf, TAB);

                helper.Read(buf, LF); // get rid of line feed
                heartbeat.Timestamp = _mDateHelper.Parse(timestamp);
                heartbeat.Status = status0;
                heartbeat.AddData(data1);

                if (parent != null)
                {
                    parent.AddChild(heartbeat);
                    tree.EstimatedByteSize += heartbeat.EstimateByteSize();
                    return parent;
                }
                return heartbeat;
            }
            if (identifier == 't')
            {
                IMessage transaction = new DefaultTransaction(type, name,
                                                              null);

                helper.Read(buf, LF); // get rid of line feed
                transaction.Timestamp = _mDateHelper.Parse(timestamp);

                if (parent != null)
                {
                    parent.AddChild(transaction);
                }

                stack.Push(parent);
                return transaction;
            }
            if (identifier == 'A')
            {
                ITransaction transaction2 = new DefaultTransaction(type, name, null);
                String status3 = helper.Read(buf, TAB);
                String duration = helper.Read(buf, TAB);
                String data4 = helper.ReadRaw(buf, TAB);

                helper.Read(buf, LF); // get rid of line feed
                transaction2.Timestamp = _mDateHelper.Parse(timestamp);
                transaction2.Status = status3;
                transaction2.AddData(data4);

                long d = Int64.Parse(duration.Substring(0, duration.Length - 2), NumberStyles.Integer);
                transaction2.DurationInMicros = d;

                if (parent != null)
                {
                    parent.AddChild(transaction2);
                    tree.EstimatedByteSize += transaction2.EstimateByteSize();
                    return parent;
                }
                return transaction2;
            }
            if (identifier == 'T')
            {
                String status5 = helper.Read(buf, TAB);
                String duration6 = helper.Read(buf, TAB);
                String data7 = helper.ReadRaw(buf, TAB);

                helper.Read(buf, LF); // get rid of line feed
                parent.Status = status5;
                parent.AddData(data7);

                long d8 = Int64.Parse(
                    duration6.Substring(0, duration6.Length - 2),
                    NumberStyles.Integer);
                parent.DurationInMicros = d8;
                tree.EstimatedByteSize += parent.EstimateByteSize();
                return stack.Pop();
            }
            Logger.Error("Unknown identifier(" + identifier + ") of message: " + buf);

            // unknown message, ignore it
            return parent;
        }
        protected internal void DecodeMessage(ChannelBuffer buf, IMessageTree tree)
        {
            Stack<ITransaction> stack = new Stack<ITransaction>();
            IMessage parent = DecodeLine(buf, null, stack, tree);

            tree.Message = parent;
            tree.EstimatedByteSize = parent.EstimateByteSize();

            while (buf.ReadableBytes() > 0)
            {
                IMessage message = DecodeLine(buf, (ITransaction) parent, stack, tree);

                if (message is ITransaction)
                {
                    parent = message;
                }
                else
                {
                    break;
                }
            }
        }
            public String Read(ChannelBuffer buf, byte separator)
            {
                int count = buf.BytesBefore(separator);

                if (count < 0)
                {
                    return null;
                }
                byte[] data = new byte[count];

                buf.ReadBytes(data);
                buf.ReadByte(); // get rid of separator

                return Encoding.UTF8.GetString(data);
            }
        protected internal int EncodeHeader(IMessageTree tree, ChannelBuffer buf)
        {
            BufferHelper helper = _mBufferHelper;
            int count = 0;

            count += helper.Write(buf, ID);
            count += helper.Write(buf, TAB);
            count += helper.Write(buf, tree.Domain);
            count += helper.Write(buf, TAB);
            count += helper.Write(buf, tree.HostName);
            count += helper.Write(buf, TAB);
            count += helper.Write(buf, tree.IpAddress);
            count += helper.Write(buf, TAB);
            count += helper.Write(buf, tree.ThreadGroupName);
            count += helper.Write(buf, TAB);
            count += helper.Write(buf, tree.ThreadId);
            count += helper.Write(buf, TAB);
            count += helper.Write(buf, tree.ThreadName);
            count += helper.Write(buf, TAB);
            count += helper.Write(buf, tree.MessageId);
            count += helper.Write(buf, TAB);
            count += helper.Write(buf, tree.ParentMessageId);
            count += helper.Write(buf, TAB);
            count += helper.Write(buf, tree.RootMessageId);
            count += helper.Write(buf, TAB);
            count += helper.Write(buf, tree.SessionToken);
            count += helper.Write(buf, LF);

            return count;
        }
            public int WriteRaw(ChannelBuffer buf, String str)
            {
                if (str == null)
                {
                    str = "null";
                }

                byte[] data = _mEncoding.GetBytes(str);

                int len = data.Length;
                int count = len;
                int offset = 0;

                for (int i = 0; i < len; i++)
                {
                    byte b = data[i];

                    if (b == '\t' || b == '\r' || b == '\n' || b == '\\')
                    {
                        buf.WriteBytes(data, offset, i - offset);
                        buf.WriteByte('\\');

                        if (b == '\t')
                        {
                            buf.WriteByte('t');
                        }
                        else if (b == '\r')
                        {
                            buf.WriteByte('r');
                        }
                        else if (b == '\n')
                        {
                            buf.WriteByte('n');
                        }
                        else
                        {
                            buf.WriteByte(b);
                        }

                        count++;
                        offset = i + 1;
                    }
                }

                if (len > offset)
                {
                    buf.WriteBytes(data, offset, len - offset);
                }

                return count;
            }
            public int Write(ChannelBuffer buf, String str)
            {
                if (str == null)
                {
                    str = "null";
                }

                byte[] data = _mEncoding.GetBytes(str);

                buf.WriteBytes(data);
                return data.Length;
            }
 public int Write(ChannelBuffer buf, byte b)
 {
     buf.WriteByte(b);
     return 1;
 }
        protected internal int EncodeLine(IMessage message, ChannelBuffer buf, char type, Policy policy)
        {
            BufferHelper helper = _mBufferHelper;
            int count = 0;

            count += helper.Write(buf, (byte) type);

            if (type == 'T' && message is ITransaction)
            {
                long duration = ((ITransaction) message).DurationInMillis;

                count += helper.Write(buf, _mDateHelper.Format2(message.Timestamp + duration));
            }
            else
            {
                count += helper.Write(buf, _mDateHelper.Format2(message.Timestamp));
            }

            count += helper.Write(buf, TAB);
            count += helper.Write(buf, message.Type);
            count += helper.Write(buf, TAB);
            count += helper.Write(buf, message.Name);
            count += helper.Write(buf, TAB);

            if (policy != Policy.WITHOUT_STATUS)
            {
                count += helper.Write(buf, message.Status);
                count += helper.Write(buf, TAB);

                Object data = message.Data;

                if (policy == Policy.WITH_DURATION && message is ITransaction)
                {
                    long duration0 = ((ITransaction) message).DurationInMicros;

                    count += helper.Write(buf, duration0.ToString(CultureInfo.InvariantCulture));
                    //以微秒为单位
                    count += helper.Write(buf, "us");
                    count += helper.Write(buf, TAB);
                }

                count += helper.WriteRaw(buf, data.ToString());
                count += helper.Write(buf, TAB);
            }

            count += helper.Write(buf, LF);

            return count;
        }
            public String ReadRaw(ChannelBuffer buf, byte separator)
            {
                int count = buf.BytesBefore(separator);

                if (count < 0)
                {
                    return null;
                }
                byte[] data = new byte[count];

                buf.ReadBytes(data);
                buf.ReadByte(); // get rid of separator

                int length = data.Length;

                for (int i = 0; i < length; i++)
                {
                    if (data[i] == '\\')
                    {
                        if (i + 1 < length)
                        {
                            byte b = data[i + 1];

                            if (b == 't')
                            {
                                data[i] = (byte) '\t';
                            }
                            else if (b == 'r')
                            {
                                data[i] = (byte) '\r';
                            }
                            else if (b == 'n')
                            {
                                data[i] = (byte) '\n';
                            }
                            else
                            {
                                data[i] = b;
                            }

                            Array.Copy(data, i + 2, data, i + 1, length - i - 2);
                            length--;
                        }
                    }
                }

                return Encoding.UTF8.GetString(data, 0, length);
            }
Example #49
0
        /// <summary> CommonGetsCleanup -> commonGetsCleanup
        /// 
        /// Helper function used by getsObj to restore the channel after
        /// a "gets" operation.
        /// 
        /// </summary>

        internal void commonGetsCleanup()
        {
            ChannelBuffer buf, next;

            buf = inQueueHead;
            for (; buf != null; buf = next)
            {
                next = buf.next;
                if (buf.nextRemoved < buf.nextAdded)
                {
                    break;
                }
                recycleBuffer(buf, false);
            }
            inQueueHead = buf;
            if (buf == null)
            {
                inQueueTail = null;
            }
            else
            {
                // If any multi-byte characters were split across channel buffer
                // boundaries, the split-up bytes were moved to the next channel
                // buffer by filterBytes().  Move the bytes back to their
                // original buffer because the caller could change the channel's
                // encoding which could change the interpretation of whether those
                // bytes really made up multi-byte characters after all.

                next = buf.next;
                for (; next != null; next = buf.next)
                {
                    int extra;

                    extra = buf.bufLength - buf.nextAdded;
                    if (extra > 0)
                    {
                        Array.Copy(next.buf, Tcl.Lang.ChannelBuffer.BUFFER_PADDING - extra, buf.buf, buf.nextAdded, extra);
                        buf.nextAdded += extra;
                        next.nextRemoved = Tcl.Lang.ChannelBuffer.BUFFER_PADDING;
                    }
                    buf = next;
                }
            }
            if ((System.Object)encoding != null)
            {
                //Tcl_FreeEncoding(encoding);
            }
        }
Example #50
0
        /// <summary> DiscardInputQueued -> discardQueued
        /// 
        /// Discards any input read from the channel but not yet consumed
        /// by Tcl reading commands.
        /// </summary>

        private void discardQueued(bool discardSavedBuffers)
        {
            ChannelBuffer buf, nxt;

            buf = inQueueHead;
            inQueueHead = null;
            inQueueTail = null;
            for (; buf != null; buf = nxt)
            {
                nxt = buf.next;
                recycleBuffer(buf, discardSavedBuffers);
            }

            // If discardSavedBuffers is true, must also discard any previously
            // saved buffer in the saveInBuf field.

            if (discardSavedBuffers)
            {
                if (saveInBuf != null)
                {
                    saveInBuf = null;
                }
            }
        }
        public int EncodeMessage(IMessage message, ChannelBuffer buf)
        {
            if (message is IEvent)
            {
                return EncodeLine(message, buf, 'E', Policy.DEFAULT);
            }
            var transaction = message as ITransaction;
            if (transaction != null)
            {
                IList<IMessage> children = transaction.Children;

                if ((children.Count == 0))
                {
                    return EncodeLine(transaction, buf, 'A', Policy.WITH_DURATION);
                }
                int count = 0;
                int len = children.Count;

                count += EncodeLine(transaction, buf, 't', Policy.WITHOUT_STATUS);

                for (int i = 0; i < len; i++)
                {
                    IMessage child = children[i];

                    count += EncodeMessage(child, buf);
                }

                count += EncodeLine(transaction, buf, 'T', Policy.WITH_DURATION);

                return count;
            }
            if (message is IHeartbeat)
            {
                return EncodeLine(message, buf, 'H', Policy.DEFAULT);
            }
            if (message is IMetric)
            {
                return EncodeLine(message, buf, 'M', Policy.DEFAULT);
            }
            throw new Exception("Unsupported message type: " + message.Type + ".");
        }