protected internal RuntimeValue_Primitive( Engine eng, WireProtocol.Commands.Debugging_Value handle ) : base( eng, handle )
        {
            Type t;

            switch((RuntimeDataType)handle.m_dt)
            {
            case RuntimeDataType.DATATYPE_BOOLEAN: t = typeof( bool  ); break;
            case RuntimeDataType.DATATYPE_I1     : t = typeof(sbyte  ); break;
            case RuntimeDataType.DATATYPE_U1     : t = typeof( byte  ); break;

            case RuntimeDataType.DATATYPE_CHAR   : t = typeof( char  ); break;
            case RuntimeDataType.DATATYPE_I2     : t = typeof( short ); break;
            case RuntimeDataType.DATATYPE_U2     : t = typeof(ushort ); break;

            case RuntimeDataType.DATATYPE_I4     : t = typeof( int   ); break;
            case RuntimeDataType.DATATYPE_U4     : t = typeof(uint   ); break;
            case RuntimeDataType.DATATYPE_R4     : t = typeof( float ); break;

            case RuntimeDataType.DATATYPE_I8     : t = typeof( long  ); break;
            case RuntimeDataType.DATATYPE_U8     : t = typeof(ulong  ); break;
            case RuntimeDataType.DATATYPE_R8     : t = typeof( double); break;

            default: throw new ArgumentException( String.Format( "Not a primitive: {0}", handle.m_dt ) );
            }

            m_value = System.Runtime.Serialization.FormatterServices.GetUninitializedObject( t );

            m_eng.CreateConverter().Deserialize( m_value, handle.m_builtinValue );
        }
 protected internal RuntimeValue_Indirect( Engine eng, WireProtocol.Commands.Debugging_Value[] array, int pos ) : base( eng, array[pos] )
 {
     if(++pos < array.Length)
     {
         m_value = Convert( eng, array, pos );
     }
 }
Beispiel #3
0
        /// <summary>
        /// Sends a message to the remote application.
        /// </summary>
        /// <param name="message">Message to be sent</param>
        protected override void SendMessageInternal(IScsMessage message)
        {
            //Send message
            var totalSent = 0;

            lock (_syncLock)
            {
                //Create a byte array from message according to current protocol
                var messageBytes = WireProtocol.GetBytes(message);
                //Send all bytes to the remote application
                while (totalSent < messageBytes.Length)
                {
                    var sent = _clientSocket.Send(messageBytes, totalSent, messageBytes.Length - totalSent, SocketFlags.None);
                    if (sent <= 0)
                    {
                        throw new CommunicationException("Message could not be sent via TCP socket. Only " + totalSent + " bytes of " + messageBytes.Length + " bytes are sent.");
                    }

                    totalSent += sent;
                }

                LastSentMessageTime = DateTime.Now;
                OnMessageSent(message);
            }
        }
        /// <summary>
        /// Sends a message to the remote application.
        /// </summary>
        /// <param name="message">Message to be sent</param>
        protected override void SendMessageInternal(IScsMessage message)
        {
            //Send message
            var totalSent = 0;

            lock (_syncLock)
            {
                //Create a byte array from message according to current protocol
                var messageBytes = WireProtocol.GetBytes(message);
                //Send all bytes to the remote application

                try
                {
                    _sslStream.Write(messageBytes, totalSent, messageBytes.Length);
                }
                catch
                {
                    throw new CommunicationException("Cannot send data on the SSL stream");
                }


                LastSentMessageTime = DateTime.Now;
                OnMessageSent(message);
            }
        }
        /// <summary>
        /// This method is used as callback method in _clientSocket's BeginReceive method. It
        /// reveives bytes from socker.
        /// </summary>
        /// <param name="result">Asyncronous call result</param>
        private void ReceiveCallback(IAsyncResult result)
        {
            if (!_running)
            {
                return;
            }

            try
            {
                int bytesRead = -1;

                // Get received bytes count
                bytesRead = _clientSocket.EndReceive(result);

                if (bytesRead > 0)
                {
                    switch (BitConverter.ToUInt16(_buffer, 0))
                    {
                    case PING_REQUEST:
                        _clientSocket.Send(BitConverter.GetBytes(PING_RESPONSE));
                        goto CONT_RECEIVE;

                    case PING_RESPONSE:
                        _running = false;
                        return;
                    }

                    LastReceivedMessageTime = DateTime.Now;

                    // Copy received bytes to a new byte array
                    byte[] receivedBytes = new byte[bytesRead];
                    Array.Copy(_buffer, receivedBytes, bytesRead);

                    // Read messages according to current wire protocol and raise MessageReceived
                    // event for all received messages
                    foreach (IScsMessage message in WireProtocol.CreateMessages(receivedBytes))
                    {
                        OnMessageReceived(message, DateTime.Now);
                    }
                }
                else
                {
                    Logger.Warn(Language.Instance.GetMessageFromKey("CLIENT_DISCONNECTED"));
                    Disconnect();
                }

CONT_RECEIVE:
                // Read more bytes if still running
                if (_running)
                {
                    _clientSocket.BeginReceive(_buffer, 0, _buffer.Length, 0, ReceiveCallback, null);
                }
            }
            catch (Exception)
            {
                Disconnect();
            }
        }
Beispiel #6
0
        public Task HandleStream(IReceiverCallback callback, Stream stream)
        {
            if (Status == ListeningStatus.TooBusy)
            {
                return(stream.SendBuffer(WireProtocol.ProcessingFailureBuffer));
            }

            return(WireProtocol.Receive(stream, callback, Address));
        }
 /// <summary>
 /// Sends a message to the remote application.
 /// </summary>
 /// <param name="message">Message to be sent</param>
 /// <param name="priority">Priority of message to send</param>
 protected override void SendMessagepublic(IScsMessage message, byte priority)
 {
     if (priority > 5)
     {
         _highPriorityBuffer.Enqueue(WireProtocol.GetBytes(message));
     }
     else
     {
         _lowPriorityBuffer.Enqueue(WireProtocol.GetBytes(message));
     }
 }
 protected internal RuntimeValue_ByRef( Engine eng, WireProtocol.Commands.Debugging_Value[] array, int pos ) : base( eng, array, pos )
 {
     if(m_value == null && m_handle.m_arrayref_referenceID != 0)
     {
         m_value = m_eng.GetArrayElement( m_handle.m_arrayref_referenceID, m_handle.m_arrayref_index );
     }
  
     if(m_value == null)
     {
         throw new ArgumentException();
     }            
 }
Beispiel #9
0
 /// <summary>
 /// Connects to server.
 /// </summary>
 public void Connect()
 {
     WireProtocol.Reset();
     _communicationChannel = CreateCommunicationChannel();
     _communicationChannel.WireProtocol     = WireProtocol;
     _communicationChannel.Disconnected    += CommunicationChannel_Disconnected;
     _communicationChannel.MessageReceived += CommunicationChannel_MessageReceived;
     _communicationChannel.MessageSent     += CommunicationChannel_MessageSent;
     _communicationChannel.Start();
     //_pingTimer.Start();
     OnConnected();
 }
Beispiel #10
0
 /// <summary>
 /// Connects to server.
 /// </summary>
 public void Connect(params Tuple <SocketOptionLevel, SocketOptionName, object>[] socketOptions)
 {
     WireProtocol.Reset();
     _communicationChannel = CreateCommunicationChannel(socketOptions);
     _communicationChannel.WireProtocol     = WireProtocol;
     _communicationChannel.Disconnected    += CommunicationChannel_Disconnected;
     _communicationChannel.MessageReceived += CommunicationChannel_MessageReceived;
     _communicationChannel.MessageSent     += CommunicationChannel_MessageSent;
     _communicationChannel.Start();
     _pingTimer.Start();
     OnConnected();
 }
 public static void updateWindowCap(int hWnd, Bitmap cap)
 {
     try
     {
         _processDict[hWnd].WindowCap = cap;
         CompRequest updateCapRequest = WireProtocol.createProgramMessage(Guid.NewGuid().ToString(), hWnd, (byte[])converter.ConvertTo(cap, typeof(byte[])));
         //cListener.phoneCommChannel.sendMessage(WireProtocol.serializeMessage(updateCapRequest));
     }
     catch (KeyNotFoundException e)
     {
         Console.WriteLine(e.ToString());
     }
 }
        static void MouseAndPingerLoop(UsbStream mouse, UsbStream pinger)
        {
            // Allocate in and out packets for "TinyBooter" simulation
            WireProtocol.WP_Packet inPacket;                                        // Allocate packet for Pinger input
            UInt16 seq = 0;                                                         // Initialize Pinger packet sequence number

            // While done button is not pressed
            while (buttons.done.Read())
            {
                // Perform these operations once every 10 milliseconds (actually a bit more than 10 milliseconds)
                // We've asked the host to query for mouse info at least every 10 milliseconds, but it actually
                // queries every 8 milliseconds - it's OK not to respond to every query.
                Thread.Sleep(10);

                byte xChange = 0;
                byte yChange = 0;

                // Make the mouse move by 3 steps each sample time if any movement button is pressed
                if (!buttons.up.Read())
                {
                    yChange = 0xFD;
                }
                if (!buttons.down.Read())
                {
                    yChange = 3;
                }
                if (!buttons.left.Read())
                {
                    xChange = 0xFD;
                }
                if (!buttons.right.Read())
                {
                    xChange = 3;
                }

                // Report to host the condition of "movement" or of the buttons
                SendMouseReport(mouse, !buttons.b1.Read(), !buttons.b2.Read(), !buttons.b3.Read(), xChange, yChange);

                // If a good WireProtocol packet was received from the host
                if (WireProtocol.ReadPacket(pinger, out inPacket))
                {
                    RespondToPacket(pinger, inPacket, seq);
                }
            }

            // Wait for the done button to be released
            while (!buttons.done.Read())
            {
                ;
            }
        }
Beispiel #13
0
        /// <summary>
        /// This method is used as callback method in _clientSocket's BeginReceive method.
        /// It reveives bytes from socker.
        /// </summary>
        /// <param name="ar">Asyncronous call result</param>
        private void ReceiveCallback(IAsyncResult ar)
        {
            if (!_running)
            {
                return;
            }

            try
            {
                //Get received bytes count
                var bytesRead = _clientSocket.EndReceive(ar);
                if (bytesRead > 0)
                {
                    LastReceivedMessageTime = DateTime.Now;

                    //Copy received bytes to a new byte array
                    var receivedBytes = new byte[bytesRead];
                    Array.Copy(_buffer, 0, receivedBytes, 0, bytesRead);

                    try
                    {
                        //Read messages according to current wire protocol
                        var messages = WireProtocol.CreateMessages(receivedBytes);
                        //Raise MessageReceived event for all received messages
                        foreach (var message in messages)
                        {
                            OnMessageReceived(message);
                        }
                    }
                    catch (SerializationException ex)
                    {
                        System.Diagnostics.Trace.Write($"Error while deserializing message: {ex}");
                    }
                }
                else
                {
                    throw new CommunicationException("Tcp socket is closed");
                }

                //Read more bytes if still running
                if (_running)
                {
                    _clientSocket.BeginReceive(_buffer, 0, _buffer.Length, 0, new AsyncCallback(ReceiveCallback), null);
                }
            }
            catch (Exception exception)
            {
                System.Diagnostics.Trace.Write($"ReceiveCallback: {exception}");
                Disconnect();
            }
        }
        /// <summary>
        /// This method is used as callback method in _clientSocket's BeginReceive method.
        /// It reveives bytes from socker.
        /// </summary>
        /// <param name="ar">Asyncronous call result</param>
        private void ReceiveCallback(IAsyncResult ar)
        {
            if (!_running)
            {
                return;
            }

            // stop timer to receives bytes from socket
            _timerConnect.Stop();

            try
            {
                //Get received bytes count
                var bytesRead = _clientSocket.EndReceive(ar);
                if (bytesRead > 0)
                {
                    LastReceivedMessageTime = DateTime.Now;

                    //Copy received bytes to a new byte array
                    var receivedBytes = new byte[bytesRead];
                    Array.Copy(_buffer, 0, receivedBytes, 0, bytesRead);

                    //Read messages according to current wire protocol
                    var messages = WireProtocol.CreateMessages(receivedBytes);

                    //Raise MessageReceived event for all received messages
                    foreach (var message in messages)
                    {
                        OnMessageReceived(message);
                    }
                }
                else
                {
                    throw new CommunicationException("Tcp socket is closed");
                }

                //Read more bytes if still running
                if (_running)
                {
                    _clientSocket.BeginReceive(_buffer, 0, _buffer.Length, 0, new AsyncCallback(ReceiveCallback), null);
                }
            }
            catch
            {
                Disconnect();
            }

            // Start timer again
            _timerConnect.Start();
        }
 public static void addProgram(int key, ProgramBase pInt)
 {
     _processDict.Add(key, pInt);
     currentProcess = pInt;
     try
     {
         CompRequest message = WireProtocol.createProgramMessage(Guid.NewGuid().ToString(), key, pInt.WindowTitle, (byte[])converter.ConvertTo(pInt.WindowCap, typeof(byte[])), pInt.ProgramType);
         //cListener.phoneCommChannel.startThread(WireProtocol.serializeMessage(message));
     }
     catch (NullReferenceException e) {
         Console.WriteLine(e.ToString());
     }
     //send phone update on process
 }
        protected internal RuntimeValue_String( Engine eng, WireProtocol.Commands.Debugging_Value handle ) : base( eng, handle )
        {
            byte[] buf = handle.m_builtinValue;

            if(handle.m_bytesInString >= buf.Length)
            {
                if(m_eng.ReadMemory( m_handle.m_charsInString, m_handle.m_bytesInString, out buf ) == false)
                {
                    // Revert to the preview on failure
                    buf = handle.m_builtinValue;
                }
            }

            m_value = WireProtocol.Commands.GetZeroTerminatedString( buf, true );
        }
        /// <summary>
        /// This method is used as callback method in _clientSocket's BeginReceive method. It
        /// reveives bytes from socker.
        /// </summary>
        /// <param name="ar">Asyncronous call result</param>
        private void ReceiveCallback(IAsyncResult ar)
        {
            if (!_running)
            {
                return;
            }

            try
            {
                var bytesRead = -1;

                // Get received bytes count
                bytesRead = _clientSocket.EndReceive(ar);

                if (bytesRead > 0)
                {
                    LastReceivedMessageTime = DateTime.Now;

                    // Copy received bytes to a new byte array
                    var receivedBytes = new byte[bytesRead];
                    Array.Copy(_buffer, receivedBytes, bytesRead);

                    // Read messages according to current wire protocol
                    var messages = WireProtocol.CreateMessages(receivedBytes);

                    // Raise MessageReceived event for all received messages
                    foreach (var message in messages)
                    {
                        OnMessageReceived(message, DateTime.Now);
                    }
                }
                else
                {
                    Logger.Log.Warn(Language.Instance.GetMessageFromKey("CLIENT_DISCONNECTED"));
                    Disconnect();
                }

                // Read more bytes if still running
                if (_running)
                {
                    _clientSocket.BeginReceive(_buffer, 0, _buffer.Length, 0, new AsyncCallback(ReceiveCallback), null);
                }
            }
            catch
            {
                Disconnect();
            }
        }
Beispiel #18
0
        public PcapParser(string pcappath, string serverIp, string clientIp)
        {
            _serverIp = serverIp;
            _clientIp = clientIp;

            _capturedPackets = new List<PacketWrapper>();
            _serverWireProtocol = new WireProtocol<ConanPacket>();
            _clientWireProtocol = new WireProtocol<ConanPacket>();

            _device = new CaptureFileReaderDevice(pcappath)
            {
                //Filter = "(ip and tcp) and (host " + serverIp + " or host " + clientIp + ")"
                Filter = "(ip and tcp) and host " + serverIp
            };
            _device.OnPacketArrival += OnPacketArrival;
        }
Beispiel #19
0
        public PcapParser(string pcappath, string serverIp, string clientIp)
        {
            _serverIp = serverIp;
            _clientIp = clientIp;

            _capturedPackets    = new List <PacketWrapper>();
            _serverWireProtocol = new WireProtocol <ConanPacket>();
            _clientWireProtocol = new WireProtocol <ConanPacket>();

            _device = new CaptureFileReaderDevice(pcappath)
            {
                //Filter = "(ip and tcp) and (host " + serverIp + " or host " + clientIp + ")"
                Filter = "(ip and tcp) and host " + serverIp
            };
            _device.OnPacketArrival += OnPacketArrival;
        }
Beispiel #20
0
        protected async Task afterSending()
        {
            _listener.Start();

            using (var client = new TcpClient())
            {
                if (Dns.GetHostName() == destination.Host)
                {
                    await client.ConnectAsync(IPAddress.Loopback, destination.Port);
                }

                await client.ConnectAsync(destination.Host, destination.Port);

                await WireProtocol.Send(client.GetStream(), theMessageBatch, null, theSender);
            }
        }
		Event DecodeEventInfo (WireProtocol.EventInfo info) {
			EventRequest req = FindRequest (info.requestId);
			if (info.eventKind == WireProtocol.EVENT_VM_START) {
				WireProtocol.VMStartEventInfo einfo = (WireProtocol.VMStartEventInfo)info;
				return new VMStartEventImpl (vm, req, new ThreadReferenceImpl (vm, einfo.thread), new AppDomainMirrorImpl (vm, einfo.domain));
			} else if (info.eventKind == WireProtocol.EVENT_VM_DEATH) {
				return new VMDeathEventImpl (vm, req);
			} else if (info.eventKind == WireProtocol.EVENT_THREAD_START) {
				WireProtocol.ThreadStartEventInfo einfo = (WireProtocol.ThreadStartEventInfo)info;
				return new ThreadStartEventImpl (vm, req, new ThreadReferenceImpl (vm, einfo.thread));
			} else if (info.eventKind == WireProtocol.EVENT_THREAD_DEATH) {
				WireProtocol.ThreadDeathEventInfo einfo = (WireProtocol.ThreadDeathEventInfo)info;
				return new ThreadDeathEventImpl (vm, req, new ThreadReferenceImpl (vm, einfo.thread));
			} else {
				throw new NotImplementedException ();
			}
		}
 /// <summary>
 /// Sends a message to the remote application.
 /// </summary>
 /// <param name="message">Message to be sent</param>
 protected override void SendMessagepublic(IScsMessage message)
 {
     try
     {
         if (_clientSocket.Connected)
         {
             // Create a byte array from message according to current protocol
             var messageBytes = WireProtocol.GetBytes(message);
             // Begin sending the data to the remote device
             _clientSocket.BeginSend(messageBytes, 0, messageBytes.Length, SocketFlags.None,
                                     new AsyncCallback(SendCallback), _clientSocket);
         }
     }
     catch (Exception e)
     {
         // disconnect
     }
 }
Beispiel #23
0
        void receiver_thread_main()
        {
            Connection conn = vm.Connection;

            while (true)
            {
                byte[] packet = conn.ReadPacket();

                if (packet.Length == 0)
                {
                    disconnected = true;

                    VMDisconnectEventImpl ev = new VMDisconnectEventImpl(vm, null);
                    add_event_set(new EventSetImpl(vm, new Event [] { ev }, SuspendPolicy.SuspendNone));
                    break;
                }

                if (WireProtocol.IsReplyPacket(packet))
                {
                    /* Reply packet */
                    int id = WireProtocol.GetPacketId(packet);
                    lock (reply_packets_monitor)
                    {
                        reply_packets [id] = packet;
                        Monitor.PulseAll(reply_packets_monitor);
                    }
                }
                else
                {
                    WireProtocol.Packet decoded = WireProtocol.DecodePacket(packet);
                    if (decoded is WireProtocol.Event.CompositePacket)
                    {
                        WireProtocol.Event.CompositePacket p = (WireProtocol.Event.CompositePacket)decoded;
                        Event[] events = new Event [p.events.Length];
                        for (int i = 0; i < p.events.Length; ++i)
                        {
                            events [i] = DecodeEventInfo(p.events [i]);
                        }

                        add_event_set(new EventSetImpl(vm, events, p.suspendPolicy));
                    }
                }
            }
        }
Beispiel #24
0
        public ListeningAgent(IReceiverCallback callback, IPAddress ipaddr, int port, string protocol, CancellationToken cancellationToken)
        {
            Port               = port;
            _callback          = callback;
            _cancellationToken = cancellationToken;

            _listener = new TcpListener(new IPEndPoint(ipaddr, port));
            _listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

            _socketHandling = new ActionBlock <Socket>(async s =>
            {
                using (var stream = new NetworkStream(s, true))
                {
                    await WireProtocol.Receive(stream, _callback, _uri);
                }
            });

            _uri = $"{protocol}://{ipaddr}:{port}/".ToUri();
        }
        // Accepts only a good packet.  If the packet is a Ping, the Ping response (ACK) is sent.
        // Otherwise, the command is NAK'ed.
        static bool RespondToPacket(UsbStream pinger, WireProtocol.WP_Packet inPacket, UInt16 seq)
        {
            WireProtocol.WP_Packet outPacket = new WireProtocol.WP_Packet();

            // Allocate space for any data following the packet
            int size = (int)(inPacket.m_size & 0xFFFF);

            byte[] buffer = new byte[size];

            // Read in the data that came with the packet
            if (inPacket.m_size != 0)
            {
                pinger.Read(buffer, 0, size);
            }

            // Fill in the blanks of the response packet
            outPacket.m_signature = "MSdbgV1";                // Standard target signature
            outPacket.m_cmd       = inPacket.m_cmd;           // Show which command this is a response to
            outPacket.m_seq       = seq++;                    // Keep track of the target message sequence number
            outPacket.m_seqReply  = inPacket.m_seq;           // Show which host packet sequence number this is a response to

            // If the host packet was a Ping
            if (inPacket.m_cmd == WireProtocol.Commands.Ping)
            {
                byte[] data = new byte[8];                          // The Ping has an 8 byte data response
                outPacket.m_flags = 0x8003;                         // Return a low-priority ACK
                for (int i = 0; i < 8; i++)
                {
                    data[i] = 0;                                    // Initialize all bytes of the data response to zero
                }
                data[0] = 1;                                        // This tells the host that we are TinyBooter
                data[4] = 2;                                        // This is an innoccuous flag value
                WireProtocol.SendPacket(pinger, outPacket, data);   // Send response to the Ping
            }
            else
            {
                outPacket.m_flags = 0x4003;                                     // Return a low-priority NACK
                WireProtocol.SendPacket(pinger, outPacket, new byte[0]);        // Signal to the host that we don't know what to do with the command
            }
            return(true);
        }
Beispiel #26
0
        public async Task SendBatch(ISenderCallback callback, OutgoingMessageBatch batch)
        {
            if (batch.Data.Length == 0)
            {
                throw new Exception("No data to be sent");
            }

            using (var client = new TcpClient())
            {
                var connection = connect(client, batch.Destination)
                                 .TimeoutAfter(5000);

                await connection;

                if (connection.IsCompleted)
                {
                    using (var stream = client.GetStream())
                    {
                        var protocolTimeout = WireProtocol.Send(stream, batch, batch.Data, callback);
                        //var protocolTimeout = .TimeoutAfter(5000);
                        await protocolTimeout.ConfigureAwait(false);

                        if (!protocolTimeout.IsCompleted)
                        {
                            await callback.TimedOut(batch);
                        }

                        if (protocolTimeout.IsFaulted)
                        {
                            await callback.ProcessingFailure(batch, protocolTimeout.Exception);
                        }
                    }
                }
                else
                {
                    await callback.TimedOut(batch);
                }
            }
        }
Beispiel #27
0
        /// <summary>
        /// Sends a message to the remote application.
        /// </summary>
        /// <param name="message">Message to be sent</param>
        protected override void SendMessageInternal(IScsMessage message)
        {
            //Send message
            var totalSent = 0;

            lock (_syncLock)
            {
                //Create a byte array from message according to current protocol
                var messageBytes = WireProtocol.GetBytes(message);
                //Send all bytes to the remote application
                while (totalSent < messageBytes.Length)
                {
                    try
                    {
                        var sent = _clientSocket.Send(messageBytes, totalSent, messageBytes.Length - totalSent, SocketFlags.None);
                        if (sent <= 0)
                        {
                            throw new CommunicationException("Message could not be sent via TCP socket. Only " + totalSent + " bytes of " + messageBytes.Length + " bytes are sent.");
                        }

                        totalSent += sent;
                    }
                    catch (SocketException ex)
                    {
                        if (ex.SocketErrorCode == SocketError.WouldBlock ||
                            ex.SocketErrorCode == SocketError.IOPending ||
                            ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
                        {
                            // socket buffer is probably full, wait and try again
                            Thread.Sleep(30);
                        }
                    }
                }

                LastSentMessageTime = DateTime.Now;

                OnMessageSent(message);
            }
        }
        /// <summary>
        /// Sends a message to the remote application.
        /// </summary>
        /// <param name="message">Message to be sent</param>
        protected override void SendMessagepublic(IScsMessage message)
        {
            //Send message
            var totalSent = 0;

            lock (_syncLock)
            {
                //Create a byte array from message according to current protocol
                var messageBytes = WireProtocol.GetBytes(message);
                //Send all bytes to the remote application
                while (totalSent < messageBytes.Length)
                {
                    if (_clientSocket.Connected)
                    {
                        var sent = 0;
                        try
                        {
                            sent = _clientSocket.Send(messageBytes, totalSent, messageBytes.Length - totalSent, SocketFlags.None);
                        }
                        catch (Exception e)
                        {
                            //annoying bug
                            Logger.Log.Error("A packet would have been sent to a disconnected client. IGNORE THIS.", e);
                        }

                        if (sent <= 0)
                        {
                            throw new CommunicationException("Message could not be sent via TCP socket. Only " + totalSent + " bytes of " + messageBytes.Length + " bytes are sent.");
                        }

                        totalSent += sent;
                    }
                }

                LastSentMessageTime = DateTime.Now;
                OnMessageSent(message);
            }
        }
        static void PingerLoop(UsbStream pinger)
        {
            // Allocate in and out packets for "TinyBooter" simulation
            WireProtocol.WP_Packet inPacket;                                        // Allocate packet for Pinger input
            UInt16 seq = 0;                                                         // Initialize Pinger packet sequence number

            // While the done button is not pressed
            while (buttons.done.Read())
            {
                Thread.Sleep(10);       // No need to respond in a hurry

                if (WireProtocol.ReadPacket(pinger, out inPacket))
                {
                    RespondToPacket(pinger, inPacket, seq);
                }
            }

            // Wait for the done button to be released
            while (!buttons.done.Read())
            {
                ;
            }
        }
        public void Start(IReceiverCallback callback)
        {
            _listener = new TcpListener(new IPEndPoint(IPAddress.Loopback, _port));
            _listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

            _socketHandling = new ActionBlock <Socket>(async s =>
            {
                using (var stream = new NetworkStream(s, true))
                {
                    await WireProtocol.Receive(stream, callback, Address);
                }
            });

            _receivingLoop = Task.Run(async() =>
            {
                _listener.Start();

                while (!_cancellationToken.IsCancellationRequested)
                {
                    var socket = await _listener.AcceptSocketAsync();
                    _socketHandling.Post(socket);
                }
            }, _cancellationToken);
        }
 internal Message(EndPoint source, WireProtocol.Commands.Debugging_Messaging_Address addr, byte[] payload)
 {
     m_source = source;
     m_addr = addr;
     m_payload = payload;
 }
        public bool SetBreakpoints(WireProtocol.Commands.Debugging_Execution_BreakpointDef[] breakpoints)
        {
            WireProtocol.Commands.Debugging_Execution_Breakpoints cmd = new WireProtocol.Commands.Debugging_Execution_Breakpoints();

            cmd.m_data = breakpoints;

            return WireProtocol.IncomingMessage.IsPositiveAcknowledge(SyncMessage(WireProtocol.Commands.c_Debugging_Execution_Breakpoints, 0, cmd));
        }
        bool WireProtocol.IControllerHostLocal.ProcessMessage(WireProtocol.IncomingMessage msg, bool fReply)
        {
            msg.Payload = WireProtocol.Commands.ResolveCommandToPayload(msg.Header.m_cmd, fReply, m_capabilities);

            if (fReply == true)
            {
                Request reply = null;

                lock (m_requests.SyncRoot)
                {
                    foreach (Request req in m_requests)
                    {
                        if (req.MatchesReply(msg))
                        {
                            m_requests.Remove(req);

                            reply = req;
                            break;
                        }
                    }
                }

                if (reply != null)
                {
                    reply.Signal(msg);
                    return true;
                }
            }
            else
            {
                WireProtocol.Packet bp = msg.Header;

                switch (bp.m_cmd)
                {
                    case WireProtocol.Commands.c_Monitor_Ping:
                        {
                            WireProtocol.Commands.Monitor_Ping.Reply cmdReply = new Microsoft.SPOT.Debugger.WireProtocol.Commands.Monitor_Ping.Reply();

                            cmdReply.m_source = WireProtocol.Commands.Monitor_Ping.c_Ping_Source_Host;
                            cmdReply.m_dbg_flags = (m_stopDebuggerOnConnect ? WireProtocol.Commands.Monitor_Ping.c_Ping_DbgFlag_Stop : 0);

                            msg.Reply(CreateConverter(), WireProtocol.Flags.c_NonCritical, cmdReply);

                            m_evtPing.Set();

                            return true;
                        }

                    case WireProtocol.Commands.c_Monitor_Message:
                        {
                            WireProtocol.Commands.Monitor_Message payload = msg.Payload as WireProtocol.Commands.Monitor_Message;

                            Debug.Assert(payload != null);

                            if (payload != null)
                            {
                                QueueNotify(m_eventMessage, msg, payload.ToString());
                            }

                            return true;
                        }

                    case WireProtocol.Commands.c_Debugging_Messaging_Query:
                    case WireProtocol.Commands.c_Debugging_Messaging_Reply:
                    case WireProtocol.Commands.c_Debugging_Messaging_Send:
                        {
                            Debug.Assert(msg.Payload != null);

                            if (msg.Payload != null)
                            {
                                QueueRpc(msg);
                            }

                            return true;
                        }
                }
            }

            if (m_eventCommand != null)
            {
                QueueNotify(m_eventCommand, msg, fReply);
                return true;
            }

            return false;
        }
Beispiel #34
0
        // Accepts only a good packet.  If the packet is a Ping, the Ping response (ACK) is sent.
        // Otherwise, the command is NAK'ed.
        static bool RespondToPacket(UsbStream pinger, WireProtocol.WP_Packet inPacket, UInt16 seq)
        {
            WireProtocol.WP_Packet outPacket = new WireProtocol.WP_Packet();

            // Allocate space for any data following the packet
            int size = (int)(inPacket.m_size & 0xFFFF);
            byte[] buffer = new byte[size];

            // Read in the data that came with the packet
            if (inPacket.m_size != 0)
                pinger.Read(buffer, 0, size);

            // Fill in the blanks of the response packet
            outPacket.m_signature = "MSdbgV1";                      // Standard target signature
            outPacket.m_cmd = inPacket.m_cmd;                 // Show which command this is a response to
            outPacket.m_seq = seq++;                          // Keep track of the target message sequence number
            outPacket.m_seqReply = inPacket.m_seq;                 // Show which host packet sequence number this is a response to

            // If the host packet was a Ping
            if (inPacket.m_cmd == WireProtocol.Commands.Ping)
            {
                byte[] data = new byte[8];                          // The Ping has an 8 byte data response
                outPacket.m_flags = 0x8003;                         // Return a low-priority ACK
                for (int i = 0; i < 8; i++)
                    data[i] = 0;                                    // Initialize all bytes of the data response to zero
                data[0] = 1;                                        // This tells the host that we are TinyBooter
                data[4] = 2;                                        // This is an innoccuous flag value
                WireProtocol.SendPacket(pinger, outPacket, data);   // Send response to the Ping
            }
            else
            {
                outPacket.m_flags = 0x4003;                                     // Return a low-priority NACK
                WireProtocol.SendPacket(pinger, outPacket, new byte[0]);        // Signal to the host that we don't know what to do with the command
            }
            return true;
        }
Beispiel #35
0
        /// <summary>
        /// This method is used as callback method in _clientSocket's BeginReceive method.
        /// It reveives bytes from socker.
        /// </summary>
        /// <param name="ar">Asyncronous call result</param>
        private void ReceiveCallback(IAsyncResult ar)
        {
            if (!_running)
            {
                return;
            }

#if UTILIZA_DESCONEXION_AUTOMATICA
            //int valorAnterior = Interlocked.CompareExchange(ref timeoutFlag, 2, 1);
            if (Interlocked.CompareExchange(ref timeoutFlag, 2, 1) /*valorAnterior*/ != 0)
            {
                //El flag ya ha sido seteado con lo cual nada!!
                return;
            }

            if (timerTimeout != null)
            {
                timerTimeout.Stop();
            }
#endif

            try
            {
                //Get received bytes count
                var bytesRead = _clientSocket.EndReceive(ar);
                if (bytesRead > 0)
                {
                    LastReceivedMessageTime = DateTime.Now;

                    //Copy received bytes to a new byte array
                    var receivedBytes = new byte[bytesRead];
                    Array.Copy(_buffer, 0, receivedBytes, 0, bytesRead);

                    //Read messages according to current wire protocol
                    var messages = WireProtocol.CreateMessages(receivedBytes);

                    //Raise MessageReceived event for all received messages
                    foreach (var message in messages)
                    {
                        OnMessageReceived(message);
                    }
                }
                else
                {
                    throw new CommunicationException("Tcp socket is closed");
                }

                //Read more bytes if still running
                if (_running)
                {
                    _clientSocket.BeginReceive(_buffer, 0, _buffer.Length, 0, new AsyncCallback(ReceiveCallback), null);
#if UTILIZA_DESCONEXION_AUTOMATICA
                    timerTimeout.Start();
#endif
                }
            }
            catch
            {
                Disconnect();
            }
        }
            internal void Signal(WireProtocol.IncomingMessage res)
            {
                lock (this)
                {
                    if (m_timer != null)
                    {
                        m_timer.Dispose();

                        m_timer = null;
                    }

                    m_res = res;
                }

                Signal();
            }
        internal bool RpcReply(WireProtocol.Commands.Debugging_Messaging_Address addr, byte[] data)
        {
            WireProtocol.Commands.Debugging_Messaging_Reply cmd = new WireProtocol.Commands.Debugging_Messaging_Reply();

            cmd.m_addr = addr;
            cmd.m_data = data;

            WireProtocol.IncomingMessage reply = SyncMessage(WireProtocol.Commands.c_Debugging_Messaging_Reply, 0, cmd);
            if (reply != null)
            {
                WireProtocol.Commands.Debugging_Messaging_Reply.Reply res = new WireProtocol.Commands.Debugging_Messaging_Reply.Reply();

                if (res != null && res.m_found != 0)
                {
                    return true;
                }
            }

            return false;
        }
        private void RpcReceiveSend(WireProtocol.IncomingMessage msg, WireProtocol.Commands.Debugging_Messaging_Send send)
        {
            WireProtocol.Commands.Debugging_Messaging_Address addr = send.m_addr;
            EndPointRegistration eep;

            eep = RpcFind(addr.m_to_Type, addr.m_to_Id, true);

            WireProtocol.Commands.Debugging_Messaging_Send.Reply res = new WireProtocol.Commands.Debugging_Messaging_Send.Reply();

            res.m_found = (eep != null) ? 1u : 0u;
            res.m_addr = addr;

            msg.Reply(CreateConverter(), WireProtocol.Flags.c_NonCritical, res);

            if (eep != null)
            {
                Message msgNew = new Message(eep.m_ep, addr, send.m_data);

                EndPointRegistration.InboundRequest ir = new EndPointRegistration.InboundRequest(eep, msgNew);

                ThreadPool.QueueUserWorkItem(new WaitCallback(RpcReceiveSendDispatch), ir);
            }
        }
Beispiel #39
0
 protected internal RuntimeValue_Object( Engine eng, WireProtocol.Commands.Debugging_Value[] array, int pos ) : base( eng, array, pos )
 {
 }
Beispiel #40
0
 protected internal RuntimeValue_Array( Engine eng, WireProtocol.Commands.Debugging_Value handle ) : base( eng, handle )
 {
 }
        internal bool RpcCheck(WireProtocol.Commands.Debugging_Messaging_Address addr)
        {
            WireProtocol.Commands.Debugging_Messaging_Query cmd = new WireProtocol.Commands.Debugging_Messaging_Query();

            cmd.m_addr = addr;

            WireProtocol.IncomingMessage reply = SyncMessage(WireProtocol.Commands.c_Debugging_Messaging_Query, 0, cmd);
            if (reply != null)
            {
                WireProtocol.Commands.Debugging_Messaging_Query.Reply res = reply.Payload as WireProtocol.Commands.Debugging_Messaging_Query.Reply;

                if (res != null && res.m_found != 0)
                {
                    return true;
                }
            }

            return false;
        }
        private void RpcReceiveQuery(WireProtocol.IncomingMessage msg, WireProtocol.Commands.Debugging_Messaging_Query query)
        {
            WireProtocol.Commands.Debugging_Messaging_Address addr = query.m_addr;
            EndPointRegistration eep = RpcFind(addr.m_to_Type, addr.m_to_Id, true);

            WireProtocol.Commands.Debugging_Messaging_Query.Reply res = new WireProtocol.Commands.Debugging_Messaging_Query.Reply();

            res.m_found = (eep != null) ? 1u : 0u;
            res.m_addr = addr;

            msg.Reply(CreateConverter(), WireProtocol.Flags.c_NonCritical, res);
        }
 internal void QueueRpc(WireProtocol.IncomingMessage msg)
 {
     m_rpcQueue.Add(msg);
     m_rpcEvent.Set();
 }
            internal Request(Engine parent, WireProtocol.OutgoingMessage req, int retries, int timeout, CommandEventHandler callback)
            {
                if (retries < 0)
                {
                    throw new ArgumentException("Value cannot be negative", "retries");
                }

                if (timeout < 1 || timeout > 60 * 60 * 1000)
                {
                    throw new ArgumentException(String.Format("Value out of bounds: {0}", timeout), "timeout");
                }

                m_parent = parent;
                m_req = req;
                m_retries = retries;
                m_timeoutRetry = new TimeSpan(timeout * TimeSpan.TicksPerMillisecond);
                m_timeoutWait = new TimeSpan((retries == 0 ? 1 : 2 * retries) * timeout * TimeSpan.TicksPerMillisecond);
                m_callback = callback;

                if (callback == null)
                {
                    m_event = new ManualResetEvent(false);
                }
            }
            internal bool MatchesReply(WireProtocol.IncomingMessage res)
            {
                WireProtocol.Packet headerReq = m_req.Header;
                WireProtocol.Packet headerRes = res.Header;

                if (headerReq.m_cmd == headerRes.m_cmd &&
                   headerReq.m_seq == headerRes.m_seqReply)
                {
                    return true;
                }

                return false;
            }
        private void RpcReceiveReply(WireProtocol.IncomingMessage msg, WireProtocol.Commands.Debugging_Messaging_Reply reply)
        {
            WireProtocol.Commands.Debugging_Messaging_Address addr = reply.m_addr;
            EndPointRegistration eep;

            eep = RpcFind(addr.m_from_Type, addr.m_from_Id, false);

            WireProtocol.Commands.Debugging_Messaging_Reply.Reply res = new WireProtocol.Commands.Debugging_Messaging_Reply.Reply();

            res.m_found = (eep != null) ? 1u : 0u;
            res.m_addr = addr;

            msg.Reply(CreateConverter(), WireProtocol.Flags.c_NonCritical, res);

            if (eep != null)
            {
                lock (eep.m_req_Outbound.SyncRoot)
                {
                    foreach (EndPointRegistration.OutboundRequest or in eep.m_req_Outbound)
                    {
                        if (or.Seq == addr.m_seq && or.Type == addr.m_to_Type && or.Id == addr.m_to_Id)
                        {
                            or.Reply = reply.m_data;

                            break;
                        }
                    }
                }
            }
        }
Beispiel #47
0
        /// <summary>
        /// This method is used as callback method in _clientSocket's BeginReceive method.
        /// It reveives bytes from socker.
        /// </summary>
        /// <param name="ar">Asyncronous call result</param>
        private void ReceiveCallback(IAsyncResult ar)
        {
            Socket __clientSocket = ar.AsyncState as Socket;

            if (!_running)
            {
                return;
            }

            try
            {
                //Get received bytes count
                var bytesRead = __clientSocket.EndReceive(ar);
                if (bytesRead > 0)
                {
                    LastReceivedMessageTime = DateTime.Now;

                    //Copy received bytes to a new byte array
                    var receivedBytes = new byte[bytesRead];
                    Array.Copy(_buffer, 0, receivedBytes, 0, bytesRead);

                    //Read messages according to current wire protocol
                    var messages = WireProtocol.CreateMessages(receivedBytes);

                    //Raise MessageReceived event for all received messages
                    foreach (var message in messages)
                    {
                        OnMessageReceived(message);
                    }
                }
                else
                {
                    throw new CommunicationException("Tcp socket is closed");
                }

                //Read more bytes if still running
                if (_running)
                {
                    __clientSocket.BeginReceive(_buffer, 0, _buffer.Length, 0, new AsyncCallback(ReceiveCallback), __clientSocket);
                }
            }
            catch (SocketException ex)
            {
                if ((ex.SocketErrorCode == SocketError.ConnectionReset) ||
                    (ex.SocketErrorCode == SocketError.ConnectionAborted) ||
                    (ex.SocketErrorCode == SocketError.NotConnected) ||
                    (ex.SocketErrorCode == SocketError.Shutdown) ||
                    (ex.SocketErrorCode == SocketError.Disconnecting))
                {
                    Disconnect();
                }
                else
                {
                    OnMessageError(ex);
                }
            }
            catch (CommunicationException ex)
            {
                Disconnect();
            }
            catch (Exception ex)
            {
                OnMessageError(ex);
            }
        }
        internal Request AsyncRequest(WireProtocol.OutgoingMessage msg, int retries, int timeout)
        {
            try
            {
                Request req = new Request(this, msg, retries, timeout, null);

                lock (m_state.SyncObject)
                {

                    //Checking whether IsRunning and adding the request to m_requests
                    //needs to be atomic to avoid adding a request after the Engine
                    //has been stopped.

                    if (!this.IsRunning)
                    {
                        throw new ApplicationException("Engine is not running or process has exited.");
                    }

                    m_requests.Add(req);

                    req.SendAsync();
                }

                return req;
            }
            catch
            {
                return null;
            }
        }
        internal WireProtocol.IncomingMessage SyncRequest(WireProtocol.OutgoingMessage msg, int retries, int timeout)
        {
            /// Lock on m_ReqSyncLock object, so only one thread is active inside the block.
            lock (m_ReqSyncLock)
            {
                Request req = AsyncRequest(msg, retries, timeout);

                return req != null ? req.Wait() : null;
            }
        }
        private WireProtocol.IncomingMessage[] SyncMessages(WireProtocol.OutgoingMessage[] messages, int retries, int timeout)
        {
            int cMessage = messages.Length;
            WireProtocol.IncomingMessage[] replies = new WireProtocol.IncomingMessage[cMessage];
            Request[] requests = new Request[cMessage];

            for (int iMessage = 0; iMessage < cMessage; iMessage++)
            {
                replies[iMessage] = SyncRequest(messages[iMessage], retries, timeout);
            }

            return replies;
        }
		private static void DebugDump(WireProtocol.IncomingMessage m, string text)
		{
		}
 private WireProtocol.IncomingMessage[] SyncMessages(WireProtocol.OutgoingMessage[] messages)
 {
     return SyncMessages(messages, 2, 1000);
 }
        internal byte[] RpcSend(WireProtocol.Commands.Debugging_Messaging_Address addr, int timeout, byte[] data)
        {
            EndPointRegistration.OutboundRequest or = null;
            byte[] res = null;

            try
            {
                or = RpcSend_Setup(addr, data);
                if (or != null)
                {
                    or.WaitHandle.WaitOne(timeout, false);

                    res = or.Reply;
                }
            }
            finally
            {
                if (or != null)
                {
                    or.Owner.m_req_Outbound.Remove(or);
                }
            }

            return res;
        }
Beispiel #54
0
        protected internal RuntimeValue_Reflection( Engine eng, WireProtocol.Commands.Debugging_Value handle ) : base( eng, handle )
        {
            m_rd = (ReflectionDefinition)System.Runtime.Serialization.FormatterServices.GetUninitializedObject( typeof(ReflectionDefinition) );

            m_eng.CreateConverter().Deserialize( m_rd, handle.m_builtinValue );
        }
        public void SetController(WireProtocol.IController ctrl)
        {
            if (m_ctrl != null)
            {
                throw new ArgumentException("Controller already initialized");
            }

            if (ctrl == null)
            {
                throw new ArgumentNullException("ctrl");
            }

            m_ctrl = ctrl;
        }
        private EndPointRegistration.OutboundRequest RpcSend_Setup(WireProtocol.Commands.Debugging_Messaging_Address addr, byte[] data)
        {
            EndPointRegistration eep = RpcFind(addr.m_from_Type, addr.m_from_Id, false);
            EndPointRegistration.OutboundRequest or = null;

            if (eep != null)
            {
                bool fSuccess = false;

                or = new EndPointRegistration.OutboundRequest(eep, addr.m_seq, addr.m_to_Type, addr.m_to_Id);

                try
                {
                    eep.m_req_Outbound.Add(or);

                    WireProtocol.Commands.Debugging_Messaging_Send cmd = new WireProtocol.Commands.Debugging_Messaging_Send();

                    cmd.m_addr = addr;
                    cmd.m_data = data;

                    WireProtocol.IncomingMessage reply = SyncMessage(WireProtocol.Commands.c_Debugging_Messaging_Send, 0, cmd);
                    if (reply != null)
                    {
                        WireProtocol.Commands.Debugging_Messaging_Send.Reply res = reply.Payload as WireProtocol.Commands.Debugging_Messaging_Send.Reply;

                        if (res != null && res.m_found != 0)
                        {
                            fSuccess = true;
                        }
                    }
                }
                catch
                {
                }

                if (!this.IsRunning)
                {
                    fSuccess = false;
                }

                if (!fSuccess)
                {
                    eep.m_req_Outbound.Remove(or);

                    or = null;
                }
            }

            return or;
        }