Example #1
0
        public static void ConnectedPipeWriteBufferNullThrows(PipeStream pipe)
        {
            Assert.True(pipe.IsConnected);
            Assert.True(pipe.CanWrite);

            Assert.Throws<ArgumentNullException>("buffer", () => pipe.Write(null, 0, 1));
            Assert.Throws<ArgumentNullException>("buffer", () => { pipe.WriteAsync(null, 0, 1); } );
        }
        protected static void WriteBytes(PipeStream pipeStream, byte[] buffer)
        {
            Assert.True(pipeStream.IsConnected);
            Assert.True(buffer.Length > 0);

            pipeStream.WriteByte(buffer[0]);
            if (buffer.Length > 1)
            {
                pipeStream.Write(buffer, 1, buffer.Length - 1);
            }
        }
Example #3
0
 protected static void DoStreamOperations(PipeStream stream)
 {
     if (stream.CanWrite)
     {
         stream.Write(new byte[] { 123, 124 }, 0, 2);
     }
     if (stream.CanRead)
     {
         Assert.Equal(123, stream.ReadByte());
         Assert.Equal(124, stream.ReadByte());
     }
 }
Example #4
0
        public static void ConnectedPipeWriteNegativeOffsetThrows(PipeStream pipe)
        {
            Assert.True(pipe.IsConnected);
            Assert.True(pipe.CanWrite);

            Assert.Throws<ArgumentOutOfRangeException>("offset", () => pipe.Write(new byte[5], -1, 1));

            // array is checked first
            Assert.Throws<ArgumentNullException>("buffer", () => pipe.Write(null, -1, 1));

            Assert.Throws<ArgumentNullException>("buffer", () => { pipe.WriteAsync(null, -1, 1); } );
        }
    void Awake()
    {
        // Get Unity Buffer size
        int bufferLength = 0, numBuffers = 0;
        AudioSettings.GetDSPBufferSize(out bufferLength, out numBuffers);
        _samplesAvailable = bufferLength;

        // Prepare our buffer
        _pipeStream = new PipeStream();
        _pipeStream.MaxBufferLength = _samplesAvailable * 2 * 2;
        _buffer = new byte[_samplesAvailable * 2];
    }
        protected static byte[] ReadBytes(PipeStream pipeStream, int length)
        {
            Assert.True(pipeStream.IsConnected);

            byte[] buffer = new byte[length];
            Assert.True(length > 0);

            buffer[0] = (byte)pipeStream.ReadByte();
            if (length > 1)
            {
                int len = pipeStream.Read(buffer, 1, length - 1);
                Assert.Equal(length - 1, len);
            }

            return buffer;
        }
Example #7
0
        public static void ConnectedPipeWriteArrayOutOfBoundsThrows(PipeStream pipe)
        {
            Assert.True(pipe.IsConnected);
            Assert.True(pipe.CanWrite);

            // offset out of bounds
            Assert.Throws<ArgumentException>(null, () => pipe.Write(new byte[1], 1, 1));

            // offset out of bounds for 0 count read
            Assert.Throws<ArgumentException>(null, () => pipe.Write(new byte[1], 2, 0));

            // offset out of bounds even for 0 length buffer
            Assert.Throws<ArgumentException>(null, () => pipe.Write(new byte[0], 1, 0));

            // combination offset and count out of bounds
            Assert.Throws<ArgumentException>(null, () => pipe.Write(new byte[2], 1, 2));

            // edges
            Assert.Throws<ArgumentException>(null, () => pipe.Write(new byte[0], int.MaxValue, 0));
            Assert.Throws<ArgumentException>(null, () => pipe.Write(new byte[0], int.MaxValue, int.MaxValue));

            Assert.Throws<ArgumentException>(() => pipe.Write(new byte[5], 3, 4));

            // offset out of bounds
            Assert.Throws<ArgumentException>(null, () => { pipe.WriteAsync(new byte[1], 1, 1); } );

            // offset out of bounds for 0 count read
            Assert.Throws<ArgumentException>(null, () => { pipe.WriteAsync(new byte[1], 2, 0); } );

            // offset out of bounds even for 0 length buffer
            Assert.Throws<ArgumentException>(null, () => { pipe.WriteAsync(new byte[0], 1, 0); } );

            // combination offset and count out of bounds
            Assert.Throws<ArgumentException>(null, () => { pipe.WriteAsync(new byte[2], 1, 2); } );

            // edges
            Assert.Throws<ArgumentException>(null, () => { pipe.WriteAsync(new byte[0], int.MaxValue, 0); } );
            Assert.Throws<ArgumentException>(null, () => { pipe.WriteAsync(new byte[0], int.MaxValue, int.MaxValue); } );

            Assert.Throws<ArgumentException>(() => { pipe.WriteAsync(new byte[5], 3, 4); } );
        }
Example #8
0
        public static void ConnectedPipeReadBufferNullThrows(PipeStream pipe)
        {
            Assert.True(pipe.IsConnected);
            Assert.True(pipe.CanRead);

            Assert.Throws<ArgumentNullException>(() => pipe.Read(null, 0, 1));

            Assert.Throws<ArgumentNullException>(() => { pipe.ReadAsync(null, 0, 1); } );
        }
Example #9
0
        public void WriteType(object data, PipeStream writer)
        {
            string name = GetTypeName(data.GetType());

            writer.WriteShortUTF(name);
        }
Example #10
0
 /// <summary>
 /// Constructs a new <c>PipeStreamWrapper</c> object that reads from and writes to the given <paramref name="stream"/>.
 /// </summary>
 /// <param name="stream">Stream to read from and write to</param>
 public PipeStreamWrapper(PipeStream stream) : base(stream)
 {
 }
Example #11
0
        public static void AfterDisconnectReadOnlyPipeThrows(PipeStream pipe)
        {
            byte[] buffer = new byte[] { 0, 0, 0, 0 };

            Assert.Throws<InvalidOperationException>(() => pipe.Read(buffer, 0, buffer.Length));
            Assert.Throws<InvalidOperationException>(() => pipe.ReadByte());
            Assert.Throws<InvalidOperationException>(() => { pipe.ReadAsync(buffer, 0, buffer.Length); } );
            Assert.Throws<InvalidOperationException>(() => pipe.IsMessageComplete);
        }
Example #12
0
 public static NamedPipeConnection <TRead, TWrite> CreateConnection <TRead, TWrite>(PipeStream pipeStream)
     where TRead : class
     where TWrite : class
 {
     return(new NamedPipeConnection <TRead, TWrite>(++_lastId, "Client " + _lastId, pipeStream));
 }
Example #13
0
 public static NamedPipeConnection <TRead, TWrite> CreateConnection <TRead, TWrite>(PipeStream pipeStream, ICustomSerializer <TRead> serializerRead, ICustomSerializer <TWrite> serializerWrite)
     where TRead : class
     where TWrite : class
 {
     return(new NamedPipeConnection <TRead, TWrite>(++_lastId, "Client " + _lastId, pipeStream, serializerRead, serializerWrite));
 }
Example #14
0
        internal void Write(PipeStream stream)
        {
            IResult result = mBody as IResult;

            if (result != null)
            {
                this.Header[HeaderTypeFactory.CONTENT_TYPE] = result.ContentType;
                result.Setting(this);
            }

            byte[] buffer = HttpParse.GetByteBuffer();
            //string line = string.Concat(HttpVersion, " ", mCode, " ", CodeMsg, "\r\n");
            //var hlen = Encoding.ASCII.GetBytes(line, 0, line.Length, buffer, 0);
            int hlen = 0;

            hlen         = hlen + Encoding.ASCII.GetBytes(HttpVersion, 0, HttpVersion.Length, buffer, hlen);
            buffer[hlen] = HeaderTypeFactory._SPACE_BYTE;
            hlen++;
            hlen         = hlen + Encoding.ASCII.GetBytes(mCode, 0, mCode.Length, buffer, hlen);
            buffer[hlen] = HeaderTypeFactory._SPACE_BYTE;
            hlen++;
            hlen = hlen + Encoding.ASCII.GetBytes(CodeMsg, 0, CodeMsg.Length, buffer, hlen);

            buffer[hlen] = HeaderTypeFactory._LINE_R;
            hlen++;
            buffer[hlen] = HeaderTypeFactory._LINE_N;
            hlen++;

            stream.Write(buffer, 0, hlen);
            stream.Write(HeaderTypeFactory.SERVAR_HEADER_BYTES, 0, HeaderTypeFactory.SERVAR_HEADER_BYTES.Length);
            Header.Write(stream);
            for (int i = 0; i < mSetCookies.Count; i++)
            {
                HeaderTypeFactory.Write(HeaderTypeFactory.SET_COOKIE, stream);
                stream.Write(mSetCookies[i]);
                stream.Write(HeaderTypeFactory.LINE_BYTES, 0, 2);
            }
            if (mBody != null)
            {
                StaticResurce.FileBlock fb = mBody as StaticResurce.FileBlock;
                if (fb != null)
                {
                    stream.Write(HeaderTypeFactory.LINE_BYTES, 0, 2);
                    fb.Write(stream);
                }
                else
                {
                    if (result.HasBody)
                    {
                        if (result.Length > 0)
                        {
                            stream.Write(HeaderTypeFactory.CONTENT_LENGTH_BYTES, 0, HeaderTypeFactory.CONTENT_LENGTH_BYTES.Length);
                            stream.Write(result.Length.ToString());
                            stream.Write(HeaderTypeFactory.TOW_LINE_BYTES, 0, 4);
                            result.Write(stream, this);
                        }
                        else
                        {
                            stream.Write(HeaderTypeFactory.CONTENT_LENGTH_BYTES, 0, HeaderTypeFactory.CONTENT_LENGTH_BYTES.Length);
                            MemoryBlockCollection contentLength = stream.Allocate(10);
                            stream.Write(HeaderTypeFactory.TOW_LINE_BYTES, 0, 4);
                            int len = stream.CacheLength;
                            result.Write(stream, this);
                            int count = stream.CacheLength - len;
                            //contentLength.Full("Content-Length: " + count.ToString().PadRight(10) + "\r\n\r\n", stream.Encoding);
                            contentLength.Full(count.ToString().PadRight(10), stream.Encoding);
                        }
                    }
                    else
                    {
                        stream.Write(HeaderTypeFactory.NULL_CONTENT_LENGTH_BYTES, 0, HeaderTypeFactory.NULL_CONTENT_LENGTH_BYTES.Length);
                        stream.Write(HeaderTypeFactory.LINE_BYTES, 0, 2);
                    }
                }
            }
            else
            {
                stream.Write(HeaderTypeFactory.NULL_CONTENT_LENGTH_BYTES, 0, HeaderTypeFactory.NULL_CONTENT_LENGTH_BYTES.Length);
                stream.Write(HeaderTypeFactory.LINE_BYTES, 0, 2);
            }

            if (Session.Server.EnableLog(EventArgs.LogType.Debug))
            {
                Session.Server.Log(EventArgs.LogType.Debug, Session, "{0} {1}", Request.ClientIPAddress, this.ToString());
            }

            if (Session.Server.EnableLog(EventArgs.LogType.Info))
            {
                Session.Server.Log(EventArgs.LogType.Info, Session, "{4} {0} {1} response {2} {3}", Request.Method, Request.Url, Code, CodeMsg, Request.ClientIPAddress);
            }
        }
 public virtual object FrameDeserialize(DataFrame data, PipeStream stream)
 {
     return(stream.ReadString((int)data.Length));
 }
 public void Initialize(PipeStream connection)
 {
 }
 public DockerPipeStream(PipeStream stream)
 {
     _stream = stream;
 }
Example #18
0
    //</snippet2>

    private static void SendClientSign(PipeStream outStream)
    {
        outStream.Write(matchSign, 0, matchSign.Length);
    }
Example #19
0
        public static void ConnectedPipeUnsupportedOperationThrows(PipeStream pipe)
        {
            Assert.True(pipe.IsConnected);

            Assert.Throws<NotSupportedException>(() => pipe.Length);

            Assert.Throws<NotSupportedException>(() => pipe.SetLength(10L));

            Assert.Throws<NotSupportedException>(() => pipe.Position);

            Assert.Throws<NotSupportedException>(() => pipe.Position = 10L);

            Assert.Throws<NotSupportedException>(() => pipe.Seek(10L, System.IO.SeekOrigin.Begin));
        }
Example #20
0
        public static void AfterDisconnectReadWritePipeThrows(PipeStream pipe)
        {
            Assert.False(pipe.IsConnected);

            AfterDisconnectReadOnlyPipeThrows(pipe);
            AfterDisconnectWriteOnlyPipeThrows(pipe);
        }
Example #21
0
 internal NamedPipeConnection(int id, string name, PipeStream serverStream)
 {
     Id             = id;
     Name           = name;
     _streamWrapper = new PipeStreamWrapper <TRead, TWrite>(serverStream);
 }
Example #22
0
        public static void OtherSidePipeDisconnectWriteThrows(PipeStream pipe)
        {
            byte[] buffer = new byte[] { 0, 0, 0, 0 };

            Assert.Throws<IOException>(() => pipe.Write(buffer, 0, buffer.Length));
            Assert.Throws<IOException>(() => pipe.WriteByte(123));
            Assert.Throws<IOException>(() => { pipe.WriteAsync(buffer, 0, buffer.Length); } );
            Assert.Throws<IOException>(() => pipe.Flush());
        }
Example #23
0
 public override void Write(PipeStream stream, HttpResponse response)
 {
     JsonSerializer.NonGeneric.Utf8.SerializeAsync(Data, stream);
 }
Example #24
0
 private static ObjectSecurity GetPipeSecurity(PipeStream pipeStream) =>
 (ObjectSecurity)typeof(PipeStream)
 .GetTypeInfo()
 .GetDeclaredMethod("GetAccessControl")
 ?.Invoke(pipeStream, parameters: null);
Example #25
0
 private static ObjectSecurity GetPipeSecurity(PipeStream pipeStream)
 {
     return(pipeStream.GetAccessControl());
 }
Example #26
0
        internal void Write(PipeStream stream)
        {
            IResult result = mBody as IResult;

            if (result != null)
            {
                this.Header[HeaderTypeFactory.CONTENT_TYPE] = result.ContentType;
                result.Setting(this);
            }
            stream.Write(HttpVersion);
            stream.Write(HeaderTypeFactory.SPACE_BYTES[0]);
            stream.Write(mCode);
            stream.Write(HeaderTypeFactory.SPACE_BYTES[0]);
            stream.Write(CodeMsg);
            stream.Write(HeaderTypeFactory.LINE_BYTES);

            Header.Write(stream);
            for (int i = 0; i < mSetCookies.Count; i++)
            {
                HeaderTypeFactory.Write(HeaderTypeFactory.SET_COOKIE, stream);
                stream.Write(mSetCookies[i]);
                stream.Write(HeaderTypeFactory.LINE_BYTES);
            }
            if (mBody != null)
            {
                StaticResurce.FileBlock fb = mBody as StaticResurce.FileBlock;
                if (fb != null)
                {
                    stream.Write(HeaderTypeFactory.LINE_BYTES);
                    fb.Write(stream);
                }
                else
                {
                    if (result.HasBody)
                    {
                        MemoryBlockCollection contentLength = stream.Allocate(28);
                        stream.Write(HeaderTypeFactory.LINE_BYTES);
                        int len = stream.CacheLength;
                        result.Write(stream, this);
                        int count = stream.CacheLength - len;
                        contentLength.Full("Content-Length: " + count.ToString().PadRight(10) + "\r\n", stream.Encoding);
                    }
                    else
                    {
                        stream.Write(HeaderTypeFactory.NULL_CONTENT_LENGTH_BYTES);
                        stream.Write(HeaderTypeFactory.LINE_BYTES);
                    }
                }
            }
            else
            {
                stream.Write(HeaderTypeFactory.NULL_CONTENT_LENGTH_BYTES);
                stream.Write(HeaderTypeFactory.LINE_BYTES);
            }

            if (Session.Server.EnableLog(EventArgs.LogType.Debug))
            {
                Session.Server.Log(EventArgs.LogType.Debug, Session, "{0} {1}", Request.ClientIPAddress, this.ToString());
            }

            if (Session.Server.EnableLog(EventArgs.LogType.Info))
            {
                Session.Server.Log(EventArgs.LogType.Info, Session, "{4} {0} {1} response {2} {3}", Request.Method, Request.Url, Code, CodeMsg, Request.ClientIPAddress);
            }
        }
 public NamedPipeConnection(System.IO.Pipes.PipeStream stream)
 {
     this.stream = stream;
 }
Example #28
0
        public Type ReadType(PipeStream reader)
        {
            string typeName = reader.ReadShortUTF();

            return(GetType(typeName));
        }
Example #29
0
 public void OnDisconnect(PipeStream pipe, Object state)
 {
     Console.WriteLine("Disconnected :" + (Int32)state);
 }
Example #30
0
 public void Write(PipeStream stream)
 {
     stream.Write(mData, 0, mData.Length);
 }
Example #31
0
 /// <summary>
 /// Constructs a new <c>PipeStreamWriter</c> object that writes to given <paramref name="stream"/>.
 /// </summary>
 /// <param name="stream">Pipe to write to</param>
 public PipeStreamWriter(PipeStream stream)
 {
     BaseStream = stream;
 }
Example #32
0
        public static void ConnectedPipeReadNegativeCountThrows(PipeStream pipe)
        {
            Assert.True(pipe.IsConnected);
            Assert.True(pipe.CanRead);

            Assert.Throws<System.ArgumentOutOfRangeException>("count", () => pipe.Read(new byte[3], 0, -1));

            // offset is checked before count
            Assert.Throws<ArgumentOutOfRangeException>("offset", () => pipe.Read(new byte[1], -1, -1));

            // array is checked first
            Assert.Throws<ArgumentNullException>("buffer", () => pipe.Read(null, -1, -1));

            Assert.Throws<System.ArgumentOutOfRangeException>("count", () => { pipe.ReadAsync(new byte[7], 0, -1); } );

            // offset is checked before count
            Assert.Throws<ArgumentOutOfRangeException>("offset", () => { pipe.ReadAsync(new byte[2], -1, -1); } );

            // array is checked first
            Assert.Throws<ArgumentNullException>("buffer", () => { pipe.ReadAsync(null, -1, -1); } );
        }
        /// <summary>
        /// This method handles the asynchronous message pump.  It waits for messages to show up on the queue
        /// and calls FireDataAvailable for each such packet.  It will terminate when the terminate event is
        /// set.
        /// </summary>
        private void PacketPumpProc()
        {
            NamedPipeServerStream localPipeServer = _pipeServer;
            PipeStream            localWritePipe  = _pipeServer;
            PipeStream            localReadPipe   = _pipeServer;

            AutoResetEvent localPacketAvailable            = _packetAvailable;
            AutoResetEvent localTerminatePacketPump        = _terminatePacketPump;
            ConcurrentQueue <INodePacket> localPacketQueue = _packetQueue;

            DateTime originalWaitStartTime = DateTime.UtcNow;
            bool     gotValidConnection    = false;

            while (!gotValidConnection)
            {
                DateTime restartWaitTime = DateTime.UtcNow;

                // We only wait to wait the difference between now and the last original start time, in case we have multiple hosts attempting
                // to attach.  This prevents each attempt from resetting the timer.
                TimeSpan usedWaitTime      = restartWaitTime - originalWaitStartTime;
                int      waitTimeRemaining = Math.Max(0, CommunicationsUtilities.NodeConnectionTimeout - (int)usedWaitTime.TotalMilliseconds);

                try
                {
                    // Wait for a connection
#if FEATURE_APM
                    IAsyncResult resultForConnection = localPipeServer.BeginWaitForConnection(null, null);
#else
                    Task connectionTask = localPipeServer.WaitForConnectionAsync();
#endif
                    CommunicationsUtilities.Trace("Waiting for connection {0} ms...", waitTimeRemaining);

#if FEATURE_APM
                    bool connected = resultForConnection.AsyncWaitHandle.WaitOne(waitTimeRemaining, false);
#else
                    bool connected = connectionTask.Wait(waitTimeRemaining);
#endif
                    if (!connected)
                    {
                        CommunicationsUtilities.Trace("Connection timed out waiting a host to contact us.  Exiting comm thread.");
                        ChangeLinkStatus(LinkStatus.ConnectionFailed);
                        return;
                    }

                    CommunicationsUtilities.Trace("Parent started connecting. Reading handshake from parent");
#if FEATURE_APM
                    localPipeServer.EndWaitForConnection(resultForConnection);
#endif

                    // The handshake protocol is a simple long exchange.  The host sends us a long, and we
                    // respond with another long.  Once the handshake is complete, both sides can be assured the
                    // other is ready to accept data.
                    // To avoid mixing client and server builds, the long is the MSBuild binary timestamp.

                    // Compatibility issue here.
                    // Previous builds of MSBuild 4.0 would exchange just a byte.
                    // Host would send either 0x5F or 0x60 depending on whether it was the toolset or not respectively.
                    // Client would return either 0xF5 or 0x06 respectively.
                    // Therefore an old host on a machine with new clients running will hang,
                    // sending a byte and waiting for a byte until it eventually times out;
                    // because the new client will want 7 more bytes before it returns anything.
                    // The other way around is not a problem, because the old client would immediately return the (wrong)
                    // byte on receiving the first byte of the long sent by the new host, and the new host would disconnect.
                    // To avoid the hang, special case here:
                    // Make sure our handshakes always start with 00.
                    // If we received ONLY one byte AND it's 0x5F or 0x60, return 0xFF (it doesn't matter what as long as
                    // it will cause the host to reject us; new hosts expect 00 and old hosts expect F5 or 06).
                    try
                    {
                        long handshake = localReadPipe.ReadLongForHandshake(/* reject these leads */ new byte[] { 0x5F, 0x60 }, 0xFF /* this will disconnect the host; it expects leading 00 or F5 or 06 */
#if NETCOREAPP2_1 || MONO
                                                                            , ClientConnectTimeout                                   /* wait a long time for the handshake from this side */
#endif
                                                                            );

#if FEATURE_SECURITY_PERMISSIONS
                        WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
#endif

                        if (handshake != GetHostHandshake())
                        {
                            CommunicationsUtilities.Trace("Handshake failed. Received {0} from host not {1}. Probably the host is a different MSBuild build.", handshake, GetHostHandshake());
                            localPipeServer.Disconnect();
                            continue;
                        }

#if FEATURE_SECURITY_PERMISSIONS
                        // We will only talk to a host that was started by the same user as us.  Even though the pipe access is set to only allow this user, we want to ensure they
                        // haven't attempted to change those permissions out from under us.  This ensures that the only way they can truly gain access is to be impersonating the
                        // user we were started by.
                        WindowsIdentity clientIdentity = null;
                        localPipeServer.RunAsClient(delegate() { clientIdentity = WindowsIdentity.GetCurrent(true); });

                        if (clientIdentity == null || !String.Equals(clientIdentity.Name, currentIdentity.Name, StringComparison.OrdinalIgnoreCase))
                        {
                            CommunicationsUtilities.Trace("Handshake failed. Host user is {0} but we were created by {1}.", (clientIdentity == null) ? "<unknown>" : clientIdentity.Name, currentIdentity.Name);
                            localPipeServer.Disconnect();
                            continue;
                        }
#endif
                    }
                    catch (IOException e)
                    {
                        // We will get here when:
                        // 1. The host (OOP main node) connects to us, it immediately checks for user privileges
                        //    and if they don't match it disconnects immediately leaving us still trying to read the blank handshake
                        // 2. The host is too old sending us bits we automatically reject in the handshake
                        CommunicationsUtilities.Trace("Client connection failed but we will wait for another connection. Exception: {0}", e.Message);
                        if (localPipeServer.IsConnected)
                        {
                            localPipeServer.Disconnect();
                        }

                        continue;
                    }

                    gotValidConnection = true;

                    CommunicationsUtilities.Trace("Writing handshake to parent");
                    localWritePipe.WriteLongForHandshake(GetClientHandshake());
                    ChangeLinkStatus(LinkStatus.Active);
                }
                catch (Exception e)
                {
                    if (ExceptionHandling.IsCriticalException(e))
                    {
                        throw;
                    }

                    CommunicationsUtilities.Trace("Client connection failed.  Exiting comm thread. {0}", e);
                    if (localPipeServer.IsConnected)
                    {
                        localPipeServer.Disconnect();
                    }

                    ExceptionHandling.DumpExceptionToFile(e);
                    ChangeLinkStatus(LinkStatus.Failed);
                    return;
                }
            }

            RunReadLoop(
                new BufferedReadStream(localReadPipe),
                localWritePipe,
                localPacketQueue, localPacketAvailable, localTerminatePacketPump);

            CommunicationsUtilities.Trace("Ending read loop");

            try
            {
                if (localPipeServer.IsConnected)
                {
                    localPipeServer.WaitForPipeDrain();
                    localPipeServer.Disconnect();
                }
            }
            catch (Exception)
            {
                // We don't really care if Disconnect somehow fails, but it gives us a chance to do the right thing.
            }
        }
Example #34
0
        public static void ConnectedPipeWriteOnlyThrows(PipeStream pipe)
        {
            Assert.True(pipe.IsConnected);
            Assert.False(pipe.CanRead);

            Assert.Throws<NotSupportedException>(() => pipe.Read(new byte[9], 0, 5));

            Assert.Throws<NotSupportedException>(() => pipe.ReadByte());

            Assert.Throws<NotSupportedException>(() => pipe.InBufferSize);

            Assert.Throws<NotSupportedException>(() => { pipe.ReadAsync(new byte[10], 0, 5); } );
        }
Example #35
0
        private void LoadArray(PipeStream pipeStream)
        {
START:
            if (Result.ArrayCount == -1 || Result.ArrayCount == 0)
            {
                OnCompleted(ResultType.Arrays, null);
                return;
            }
            else
            {
                if (Result.BodyLength == null)
                {
                    if (pipeStream.TryReadLine(out string line))
                    {
                        if (line[0] == ':')
                        {
                            var item = new ResultItem {
                                Type = ResultType.Integers, Data = long.Parse(line.Substring(1, line.Length - 1))
                            };
                            Result.Data.Add(item);
                            Result.ArrayReadCount++;
                            Result.ReadCount++;
                        }
                        else if (line[0] == '+')
                        {
                            var item = new ResultItem {
                                Type = ResultType.Simple, Data = line.Substring(1, line.Length - 1)
                            };
                            Result.Data.Add(item);
                            Result.ArrayReadCount++;
                            Result.ReadCount++;
                        }
                        else if (line[0] == '-')
                        {
                            var item = new ResultItem {
                                Type = ResultType.Error, Data = line.Substring(1, line.Length - 1)
                            };
                            Result.Data.Add(item);
                            Result.ArrayReadCount++;
                            Result.ReadCount++;
                        }
                        else
                        {
                            Result.BodyLength = int.Parse(line.Substring(1, line.Length - 1));
                        }
                    }
                    else
                    {
                        return;
                    }
                }
                if (Result.BodyLength != null)
                {
                    if ((Result.BodyLength == -1))
                    {
                        if (Command.Reader == null || Command.Reader(Result, pipeStream, Client))
                        {
                            var item = new ResultItem {
                                Type = ResultType.NotFound, Data = null
                            };
                            Result.Data.Add(item);
                        }
                        Result.BodyLength = null;
                        Result.ArrayReadCount++;
                        Result.ReadCount++;
                    }
                    else if (Result.BodyLength == 0)
                    {
                        if (pipeStream.Length >= 2)
                        {
                            if (Command.Reader == null || Command.Reader(Result, pipeStream, Client))
                            {
                                var item = new ResultItem {
                                    Type = ResultType.Null, Data = null
                                };
                                Result.Data.Add(item);
                            }
                            FreeLine(pipeStream);
                            //pipeStream.ReadFree(2);
                            Result.BodyLength = null;
                            Result.ArrayReadCount++;
                            Result.ReadCount++;
                        }
                    }
                    else if (pipeStream.Length >= Result.BodyLength)
                    {
                        object value;
                        if (Command.Reader == null || Command.Reader(Result, pipeStream, Client))
                        {
                            if (Command.DataFormater == null)
                            {
                                value = pipeStream.ReadString(Result.BodyLength.Value);
                            }
                            else
                            {
                                value = Command.DataFormater.DeserializeObject(Types[Result.Data.Count % Types.Length], Client, pipeStream, Result.BodyLength.Value);
                            }
                            var item = new ResultItem
                            {
                                Type = ResultType.Object,
                                Data = value
                            };
                            Result.Data.Add(item);
                        }
                        FreeLine(pipeStream);
                        //pipeStream.ReadFree(2);
                        Result.ReadCount++;
                        Result.BodyLength = null;
                        Result.ArrayReadCount++;
                    }
                    else
                    {
                        return;
                    }
                }
                if (Result.ArrayReadCount == Result.ArrayCount)
                {
                    OnCompleted(ResultType.Arrays, null);
                    return;
                }
            }
            if (pipeStream.Length > 0)
            {
                goto START;
            }
        }
Example #36
0
        public static void ConnectedPipeCancelReadTokenThrows(PipeStream pipe)
        {
            byte[] buffer11 = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            Assert.True(pipe.IsConnected);
            Assert.True(pipe.CanRead);

            var ctx = new CancellationTokenSource();
            Task readToken = pipe.ReadAsync(buffer11, 0, buffer11.Length, ctx.Token);
            ctx.Cancel();
            Assert.ThrowsAsync<TimeoutException>(() => readToken);
            Assert.ThrowsAsync<TimeoutException>(() => pipe.ReadAsync(buffer11, 0, buffer11.Length, ctx.Token));
        }
Example #37
0
        private void OnReceive(IClient c, ClientReceiveArgs reader)
        {
            ResultType resultType;
            string     msg;
            PipeStream pipeStream = reader.Stream.ToPipeStream();

            if (mFreeLength > 0)
            {
                pipeStream.ReadFree(mFreeLength);
                mFreeLength = 0;
            }
            if (Result.Status == ResultStatus.None)
            {
                if (pipeStream.TryReadLine(out string line))
                {
                    char type = line[0];
                    switch (type)
                    {
                    case '+':
                        resultType = ResultType.Simple;
                        msg        = line.Substring(1, line.Length - 1);
                        OnCompleted(resultType, msg);
                        return;

                    case '-':
                        resultType = ResultType.Error;
                        msg        = line.Substring(1, line.Length - 1);
                        OnCompleted(resultType, msg);
                        return;

                    case ':':
                        Result.Data.Add(new ResultItem {
                            Type = ResultType.Integers, Data = long.Parse(line.Substring(1, line.Length - 1))
                        });
                        Result.Status = ResultStatus.Completed;
                        OnCompleted(ResultType.Integers, null);
                        return;

                    case '$':
                        Result.ResultType = ResultType.Bulck;
                        Result.ArrayCount = 1;
                        Result.BodyLength = int.Parse(line.Substring(1, line.Length - 1));
                        Result.Status     = ResultStatus.Loading;
                        break;

                    case '*':
                        Result.ResultType = ResultType.Arrays;
                        Result.ArrayCount = int.Parse(line.Substring(1, line.Length - 1));
                        Result.Status     = ResultStatus.Loading;
                        break;
                    }
                }
            }
            if (Result.Status == ResultStatus.Loading)
            {
                if (Result.ResultType == ResultType.Arrays)
                {
                    LoadArray(pipeStream);
                }
                else if (Result.ResultType == ResultType.Bulck)
                {
                    LoadBulck(pipeStream);
                }
            }
        }
Example #38
0
        public static void AfterDisconnectWriteOnlyPipeThrows(PipeStream pipe)
        {
            byte[] buffer = new byte[] { 0, 0, 0, 0 };

            Assert.Throws<InvalidOperationException>(() => pipe.Write(buffer, 0, buffer.Length));
            Assert.Throws<InvalidOperationException>(() => pipe.WriteByte(5));
            Assert.Throws<InvalidOperationException>(() => { pipe.WriteAsync(buffer, 0, buffer.Length); } );
            Assert.Throws<InvalidOperationException>(() => pipe.Flush());
        }
Example #39
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PipeStreamWrapper"/> class.
 /// </summary>
 /// <param name="stream">The raw pipe stream to wrap.</param>
 /// <param name="logger">The action to run to log events.</param>
 public PipeStreamWrapper(PipeStream stream, Action <string> logger)
 {
     this.stream = stream;
     this.logger = logger;
 }
Example #40
0
        public static void WhenDisposedPipeThrows(PipeStream pipe)
        {
            byte[] buffer = new byte[] { 0, 0, 0, 0 };

            Assert.Throws<ObjectDisposedException>(() => pipe.Write(buffer, 0, buffer.Length));
            Assert.Throws<ObjectDisposedException>(() => pipe.WriteByte(5));
            Assert.Throws<ObjectDisposedException>(() => { pipe.WriteAsync(buffer, 0, buffer.Length); } );
            Assert.Throws<ObjectDisposedException>(() => pipe.Flush());
            Assert.Throws<ObjectDisposedException>(() => pipe.Read(buffer, 0, buffer.Length));
            Assert.Throws<ObjectDisposedException>(() => pipe.ReadByte());
            Assert.Throws<ObjectDisposedException>(() => { pipe.ReadAsync(buffer, 0, buffer.Length); } );
            Assert.Throws<ObjectDisposedException>(() => pipe.IsMessageComplete);
        }
 public void SetPipe(PipeStream Pipe)
 {
     this.Pipe = Pipe;
 }
Example #42
0
        public static void OtherSidePipeDisconnectVerifyRead(PipeStream pipe)
        {
            byte[] buffer = new byte[] { 0, 0, 0, 0 };

            int length = pipe.Read(buffer, 0, buffer.Length);  // for some reason these are ok
            Assert.Equal(0, length);
            int byt = pipe.ReadByte();
        }
        protected static async Task<byte[]> ReadBytesAsync(PipeStream pipeStream, int length)
        {
            Assert.True(pipeStream.IsConnected);

            byte[] buffer = new byte[length];
            Assert.True(length > 0);

            int readSoFar = 0;

            while (readSoFar < length)
            {
                int len = await pipeStream.ReadAsync(buffer, readSoFar, length - readSoFar);
                if (len == 0) break;
                readSoFar += len;
            }

            return buffer;
        }
Example #44
0
        public static void ConnectedPipeReadOnlyThrows(PipeStream pipe)
        {
            Assert.True(pipe.IsConnected);
            Assert.False(pipe.CanWrite);

            Assert.Throws<NotSupportedException>(() => pipe.Write(new byte[5], 0, 5));

            Assert.Throws<NotSupportedException>(() => pipe.WriteByte(123));

            Assert.Throws<NotSupportedException>(() => pipe.Flush());

            Assert.Throws<NotSupportedException>(() => pipe.OutBufferSize);

            Assert.Throws<NotSupportedException>(() => pipe.WaitForPipeDrain());

            Assert.Throws<NotSupportedException>(() => { pipe.WriteAsync(new byte[5], 0, 5); } );
        }
Example #45
0
 public Task Plaintext(PipeStream stream, HttpToken token, ISession session)
 {
     stream.Write(_result_plaintext.Data, 0, _result_plaintext.Length);
     OnCompleted(stream, session, token);
     return(Task.CompletedTask);
 }
 protected static Task WriteBytesAsync(PipeStream pipeStream, byte[] buffer)
 {
     Assert.True(pipeStream.IsConnected);
     Assert.True(buffer.Length > 0);
     return pipeStream.WriteAsync(buffer, 0, buffer.Length);
 }
Example #47
0
 protected override void OnWrite(object data, IClient client, PipeStream stream)
 {
     stream.Write((string)data);
 }
Example #48
0
        public static void Write(string name, PipeStream stream)
        {
            HeaderType type = Find(name);

            stream.Write(type.Bytes);
        }
Example #49
0
 /// <summary>
 /// Constructs a new <c>PipeStreamReader</c> object that reads data from the given <paramref name="stream"/>.
 /// </summary>
 /// <param name="stream">Pipe to read from</param>
 public PipeStreamReader(PipeStream stream)
 {
     BaseStream  = stream;
     IsConnected = stream.IsConnected;
 }
Example #50
0
 protected override object OnRead(IClient client, PipeStream stream)
 {
     return(stream.ReadString(CurrentSize));
 }
Example #51
0
        public async Task ParseArgumentsAsync(PipeStream connection, Dictionary <string, object> message, string arguments)
        {
            switch (arguments)
            {
            case "LoadContextMenu":
                var contextMenuResponse        = new ValueSet();
                var loadThreadWithMessageQueue = new ThreadWithMessageQueue <Dictionary <string, object> >(HandleMenuMessage);
                var cMenuLoad = await loadThreadWithMessageQueue.PostMessageAsync <ContextMenu>(message);

                contextMenuResponse.Add("Handle", handleTable.AddValue(loadThreadWithMessageQueue));
                contextMenuResponse.Add("ContextMenu", JsonConvert.SerializeObject(cMenuLoad));
                await Win32API.SendMessageAsync(connection, contextMenuResponse, message.Get("RequestID", (string)null));

                break;

            case "ExecAndCloseContextMenu":
                var menuKey = (string)message["Handle"];
                var execThreadWithMessageQueue = handleTable.GetValue <ThreadWithMessageQueue <Dictionary <string, object> > >(menuKey);
                if (execThreadWithMessageQueue != null)
                {
                    await execThreadWithMessageQueue.PostMessage(message);
                }
                // The following line is needed to cleanup resources when menu is closed.
                // Unfortunately if you uncomment it some menu items will randomly stop working.
                // Resource cleanup is currently done on app closing,
                // if we find a solution for the issue above, we should cleanup as soon as a menu is closed.
                //handleTable.RemoveValue(menuKey);
                break;

            case "InvokeVerb":
                var filePath = (string)message["FilePath"];
                var split    = filePath.Split('|').Where(x => !string.IsNullOrWhiteSpace(x));
                var verb     = (string)message["Verb"];
                using (var cMenu = ContextMenu.GetContextMenuForFiles(split.ToArray(), Shell32.CMF.CMF_DEFAULTONLY))
                {
                    var result = cMenu?.InvokeVerb(verb);
                    await Win32API.SendMessageAsync(connection, new ValueSet()
                    {
                        { "Success", result }
                    }, message.Get("RequestID", (string)null));
                }
                break;

            case "GetNewContextMenuEntries":
                var entries = await Extensions.IgnoreExceptions(() => ShellNewMenuHelper.GetNewContextMenuEntries(), Program.Logger);

                await Win32API.SendMessageAsync(connection, new ValueSet()
                {
                    { "Entries", JsonConvert.SerializeObject(entries) }
                }, message.Get("RequestID", (string)null));

                break;

            case "GetNewContextMenuEntryForType":
                var fileExtension = (string)message["extension"];
                var entry         = await Extensions.IgnoreExceptions(() => ShellNewMenuHelper.GetNewContextMenuEntryForType(fileExtension), Program.Logger);

                await Win32API.SendMessageAsync(connection, new ValueSet()
                {
                    { "Entry", JsonConvert.SerializeObject(entry) }
                }, message.Get("RequestID", (string)null));

                break;
            }
        }