Пример #1
0
            /// <summary>
            /// Run a the message receiver and state machines once. Can be used if no threads should be used.
            /// </summary>
            public void Run()
            {
                if (initialized == false)
                {
                    linkLayer = new LinkLayer(buffer, linkLayerParameters, transceiver, DebugLog);
                    linkLayer.LinkLayerMode = linkLayerMode;

                    if (linkLayerMode == LinkLayerMode.BALANCED)
                    {
                        PrimaryLinkLayerBalanced primaryLinkLayerBalanced = new PrimaryLinkLayerBalanced(linkLayer, GetUserData, DebugLog);
                        primaryLinkLayerBalanced.LinkLayerAddressOtherStation = linkLayerAddressOtherStation;

                        linkLayer.SetPrimaryLinkLayer(primaryLinkLayerBalanced);

                        linkLayer.SetSecondaryLinkLayer(new SecondaryLinkLayerBalanced(linkLayer, linkLayerAddressOtherStation, HandleApplicationLayer, DebugLog));
                    }
                    else
                    {
                        linkLayer.SetSecondaryLinkLayer(new SecondaryLinkLayerUnbalanced(linkLayer, linkLayerAddress, this, DebugLog));
                    }

                    initialized = true;
                }

                if (fileServer != null)
                {
                    fileServer.HandleFileTransmission();
                }

                linkLayer.Run();
            }
Пример #2
0
 public Wireshark(string sinkName, LinkLayer layer, string wiresharkPath)
 {
     currentEmulation = EmulationManager.Instance.CurrentEmulation;
     EmulationManager.Instance.EmulationChanged += ClearLog;
     currentEmulation.MachineRemoved            += OnMachineRemoved;
     wiresharkSinkName = sinkName;
     wiresharkSender   = new WiresharkSender(wiresharkSinkName, (uint)layer, wiresharkPath);
     this.layer        = layer;
 }
Пример #3
0
 public FloodingNetworkLayer(string localAddress, SimulationConfiguration configuration, Logger logger, LinkLayer link, StatisticsCollector results)
 {
     _localAddress = localAddress;
     _conf         = configuration;
     _logger       = logger;
     _linkLayer    = link;
     _statistics   = results;
     _time         = TimeHelper.GetInstance();
 }
Пример #4
0
            /// <summary>
            /// Switches to the specified layer.
            /// </summary>
            /// <param name="layer"></param>
            public bool SwitchLayer(LinkLayer layer)
            {
                // If the layer does not exist...
                if (!layer)
                {
                    throw new Exception("No layer was passed!");
                }

                return(SwitchLayer(layer.name));
            }
            /// <summary>
            /// Switches to a new link layer.
            /// </summary>
            /// <param name="layer">The layer which to switch to. </param>
            /// <param name="resetState">Whether to reset to the default state of this layer.</param>
            public void SwitchLayer(LinkLayer layer, bool resetState = true)
            {
                if (!Controller.SwitchLayer(layer))
                {
                    return;
                }

                // If resetting the state..
                ResetLayer(resetState);
            }
 public AodvNetworkLayer(string localAddress, SimulationConfiguration configuration, Logger logger, LinkLayer link, StatisticsCollector results)
 {
     _aodvHelper     = new AodvHelper(localAddress, configuration, logger);
     _localAddress   = localAddress;
     _logger         = logger;
     _time           = TimeHelper.GetInstance();
     _linkLayer      = link;
     _statistics     = results;
     _conf           = configuration;
     _aodvParameters = _conf.AodvConfiguration;
 }
Пример #7
0
        static void DNP3Response(LinkLayer ll, TransportLayer tl, ApplicationLayer al, ref byte[] buffer)
        {
            var appData = ApplicationLayer.ApplicationResponse(al);

            al.ApplicationData = appData;
            var transData = TransportLayer.TransportResponse(tl, al);

            tl.TransportData = transData;
            var linkData = LinkLayer.LinkResponse(ll, tl);

            buffer = linkData;
        }
Пример #8
0
        public CS101MasterUnbalanced(SerialPort port, LinkLayerParameters llParameters)
        {
            this.linkLayerParameters = llParameters;
            this.transceiver         = new SerialTransceiverFT12(port, linkLayerParameters, DebugLog);

            linkLayer = new LinkLayer(buffer, linkLayerParameters, transceiver, DebugLog);
            linkLayer.LinkLayerMode = LinkLayerMode.UNBALANCED;

            linkLayerUnbalanced = new PrimaryLinkLayerUnbalanced(linkLayer, this, DebugLog);
            linkLayer.SetPrimaryLinkLayer(linkLayerUnbalanced);

            this.fileClient = null;
        }
Пример #9
0
        public static void Main()
        {
            // write your code here
            LinkLayer        ll      = new LinkLayer();
            NetworkLayer     network = new NetworkLayer(1, ll);
            ApplicationLayer app     = new ApplicationLayer(network);

            ll.NewMessageReceived += BlinkLed;

            _device = new LocalDevice(999, app, "Netduino", "Netduino");

            ll.Start();
        }
Пример #10
0
        public static Packet Parse(LinkLayer link_layer, byte[] data)
        {
            switch (link_layer)
            {
            case LinkLayer.Ethernet:
                return(new EthernetPacket(
                           new ReadOnlyMemory <byte>(data)));

            case LinkLayer.Raw:
            default:
                throw new NotImplementedException(nameof(link_layer));
            }
        }
Пример #11
0
        public CS101MasterBalanced(SerialPort port, LinkLayerParameters llParameters)
        {
            this.port = port;
            this.linkLayerParameters = llParameters;
            this.transceiver         = new SerialTransceiverFT12(port, linkLayerParameters, DebugLog);

            linkLayer = new LinkLayer(buffer, linkLayerParameters, transceiver, DebugLog);

            primaryLinkLayer = new PrimaryLinkLayerBalanced(linkLayer, GetUserData, DebugLog);

            linkLayer.SetPrimaryLinkLayer(primaryLinkLayer);
            linkLayer.SetSecondaryLinkLayer(new SecondaryLinkLayerBalanced(linkLayer, 0, HandleApplicationLayer, DebugLog));

            this.fileClient = null;
        }
Пример #12
0
        public void SetUp()
        {
            var conf = new SimulationConfiguration();

            conf.Initialize();
            conf.EnableSatelliteLogging = false;

            var results = new StatisticsCollector();

            results.NewSimulation();

            var logger = new Logger(string.Empty, conf);

            _uut = new LinkLayer(conf, null, null, logger, results);
        }
Пример #13
0
        public CS101Master(SerialPort port, LinkLayerMode mode, LinkLayerParameters llParams = null, ApplicationLayerParameters alParams = null)
        {
            if (llParams == null)
            {
                this.linkLayerParameters = new LinkLayerParameters();
            }
            else
            {
                this.linkLayerParameters = llParams;
            }

            if (alParams == null)
            {
                this.appLayerParameters = new ApplicationLayerParameters();
            }
            else
            {
                this.appLayerParameters = alParams;
            }


            this.transceiver = new SerialTransceiverFT12(port, linkLayerParameters, DebugLog);

            linkLayer = new LinkLayer(buffer, linkLayerParameters, transceiver, DebugLog);
            linkLayer.LinkLayerMode = mode;

            if (mode == LinkLayerMode.BALANCED)
            {
                linkLayer.DIR = true;

                primaryLinkLayer = new PrimaryLinkLayerBalanced(linkLayer, GetUserData, DebugLog);

                linkLayer.SetPrimaryLinkLayer(primaryLinkLayer);
                secondaryLinkLayer = new SecondaryLinkLayerBalanced(linkLayer, 0, HandleApplicationLayer, DebugLog);
                linkLayer.SetSecondaryLinkLayer(secondaryLinkLayer);

                userDataQueue = new Queue <BufferFrame>();
            }
            else
            {
                linkLayerUnbalanced = new PrimaryLinkLayerUnbalanced(linkLayer, this, DebugLog);
                linkLayer.SetPrimaryLinkLayer(linkLayerUnbalanced);
            }

            this.port = port;

            this.fileClient = null;
        }
Пример #14
0
            /// <summary>
            /// Registers all link layers under this controller, using a string dictionary
            /// to later access them.
            /// </summary>
            void ConnectLayers()
            {
                Layers.Clear();
                var layers = GetComponentsInChildren <LinkLayer>();

                foreach (var layer in layers)
                {
                    layer.AddLinksFromChildren();
                    Layers.Add(layer.name, layer);
                }
                // Use the first layer as the root layer
                if (layers.Length > 0)
                {
                    CurrentLayer = layers[0];
                }
            }
Пример #15
0
        public Diagram(DiagramOptions?options = null)
        {
            _behaviors = new Dictionary <Type, Behavior>();
            _componentByModelMapping = new Dictionary <Type, Type>();
            _groups = new List <GroupModel>();

            Options = options ?? new DiagramOptions();
            Nodes   = new NodeLayer(this);
            Links   = new LinkLayer(this);

            RegisterBehavior(new SelectionBehavior(this));
            RegisterBehavior(new DragMovablesBehavior(this));
            RegisterBehavior(new DragNewLinkBehavior(this));
            RegisterBehavior(new DeleteSelectionBehavior(this));
            RegisterBehavior(new PanBehavior(this));
            RegisterBehavior(new ZoomBehavior(this));
            RegisterBehavior(new GroupingBehavior(this));
            RegisterBehavior(new EventsBehavior(this));
        }
Пример #16
0
        //interface
        public static void Configure(XmlNode configuration)
        {
            XmlNode bundle = configuration[Bundle.BundleTag];

            if (bundle != null)
            {
                Bundle.Configure(bundle);
            }
            XmlNode ip = configuration[Ip.IpTag];

            if (ip != null)
            {
                Ip.Configure(ip);
            }
            XmlNode linkLayer = configuration[LinkLayer.LinLayerTag];

            if (linkLayer != null)
            {
                LinkLayer.Configure(linkLayer);
            }
            XmlNode udp = configuration[Udp.UdpTag];

            if (udp != null)
            {
                Udp.Configure(udp);
            }
            XmlNode dijkstra = configuration[Dijkstra.DijkstraTag];

            if (dijkstra != null)
            {
                Dijkstra.Configure(dijkstra);
            }
            XmlNode aodv = configuration[Aodv.AodvTag];

            if (aodv != null)
            {
                Aodv.Configure(aodv);
            }
        }
Пример #17
0
            /// <summary>
            /// Switches to the specified layer.
            /// </summary>
            /// <param name="layerName">The name of the layer to switch to.</param>
            public bool SwitchLayer(string layerName)
            {
                // If there's no layer, do nothing
                if (Layers.Count == 0)
                {
                    Trace.Script("No layers available!", this);
                    return(false);
                }

                // If the layer could not be found, do nothing
                if (!Layers.ContainsKey(layerName))
                {
                    Trace.Script("The layer '" + layerName + "' could not be found!", this);
                    return(false);
                }

                // If it's the same layer, do nothing
                if (CurrentLayer.name == layerName)
                {
                    if (Tracing)
                    {
                        Trace.Script(layerName + " is the same layer!", this);
                    }
                    return(false);
                }

                // Save the previous layer
                PreviousLayer = CurrentLayer;
                // Disable the previous layer
                CurrentLayer.Enable(false);
                // Change the layer
                CurrentLayer = Layers[layerName];
                CurrentLayer.Enable(true);
                //Trace.Script("Switched to " + layerName, this);
                return(true);
            }
Пример #18
0
        /// <summary>
        /// This is the main function for the simple client. It parses the command line and creates
        /// a socket of the requested type. For TCP, it will resolve the name and attempt to connect
        /// to each resolved address until a successful connection is made. Once connected a request
        /// message is sent followed by shutting down the send connection. The client then receives
        /// data until the server closes its side at which point the client socket is closed. For
        /// UDP, the socket is created and if indicated connected to the server's address. A single
        /// request datagram message. The client then waits to receive a response and continues to
        /// do so until a zero byte datagram is receive which indicates the end of the response.
        /// </summary>

        /// <param name="args">Command line arguments</param>

        static void Main(string[] args)
        {
            SocketType   sockType = SocketType.Stream;
            ProtocolType sockProtocol = ProtocolType.Tcp;
            string       remoteName = "localhost";
            bool         udpConnect = false;
            int          remotePort = 5150, bufferSize = 4096;

            Console.WriteLine();
            usage();
            Console.WriteLine();
            // Parse the command line
            for (int i = 0; i < args.Length; i++)
            {
                try
                {
                    if ((args[i][0] == '-') || (args[i][0] == '/'))
                    {
                        switch (Char.ToLower(args[i][1]))
                        {
                        case 'c':           // "Connect" the UDP socket to the destination
                            udpConnect = true;
                            break;

                        case 'n':           // Destination address to connect to or send to
                            remoteName = args[++i];
                            break;

                        case 'p':           // Port number for the destination
                            remotePort = System.Convert.ToInt32(args[++i]);
                            break;

                        case 't':           // Specified TCP or UDP
                            i++;
                            if (String.Compare(args[i], "tcp", true) == 0)
                            {
                                sockType     = SocketType.Stream;
                                sockProtocol = ProtocolType.Tcp;
                            }
                            else if (String.Compare(args[i], "udp", true) == 0)
                            {
                                sockType     = SocketType.Dgram;
                                sockProtocol = ProtocolType.Udp;
                            }
                            else
                            {
                                usage();
                                return;
                            }
                            break;

                        case 'x':           // Size of the send and receive buffers
                            bufferSize = System.Convert.ToInt32(args[++i]);
                            break;

                        default:
                            usage();
                            return;
                        }
                    }
                }
                catch
                {
                    usage();
                    return;
                }
            }

            Socket      clientSocket = null;
            IPHostEntry resolvedHost = null;
            IPEndPoint  destination  = null;

            byte[] sendBuffer = new byte[bufferSize], recvBuffer = new Byte[bufferSize];
            int    rc;
            // Format the string message into the send buffer

            // we will send the DNP3 request
            ApplicationLayer al = new ApplicationLayer();

            al.ApplicationData    = new byte[] { 0x02, 0x00, 0x06 };
            al.FunctionCode       = (byte)FunctionCode.READ; // Read
            al.ApplicationControl = 0xc2;
            al.serialize(ref al.ApplicationData);

            TransportLayer tl = new TransportLayer();

            tl.TransportData = al.ApplicationData;
            tl.seq           = 1;
            tl.FIN           = 1;
            tl.FIR           = 1;
            tl.serialize(ref tl.TransportData);

            LinkLayer ll = new LinkLayer();

            ll.LinkData     = tl.TransportData;
            ll.source       = 3;
            ll.destination  = 4;
            ll.dir          = (byte)DIR.MASTER;
            ll.prm          = (byte)PRM.INITIATED;
            ll.fcb          = (byte)FCB.set;
            ll.fcv          = (byte)FCV.set;
            ll.functionCode = (byte)PrimaryFunctionCode.PRI_CONFIRMED_USER_DATA;
            ll.controlByte  = ll.GetControlByte(true);
            ll.serialize(ref ll.LinkData);

            var sb = new StringBuilder("new byte[] { ");

            for (var i = 0; i < ll.LinkData.Length; i++)
            {
                var b = ll.LinkData[i];
                sb.Append(b);
                if (i < ll.LinkData.Length - 1)
                {
                    sb.Append(", ");
                }
            }
            sb.Append(" }");
            Console.WriteLine("DNP3 data using String Builder " + sb.ToString());

            //FormatBuffer(sendBuffer, textMessage);
            BufferFormatting(ref sendBuffer, ll.LinkData);
            try
            {
                // Try to resolve the remote host name or address
                resolvedHost = Dns.GetHostEntry(remoteName);
                Console.WriteLine("Client: GetHostEntry() is OK...");

                // Try each address returned
                foreach (IPAddress addr in resolvedHost.AddressList)
                {
                    // Create a socket corresponding to the address family of the resolved address
                    clientSocket = new Socket(
                        addr.AddressFamily,
                        sockType,
                        sockProtocol
                        );

                    Console.WriteLine("Client: Socket() is OK...");
                    try
                    {
                        // Create the endpoint that describes the destination
                        destination = new IPEndPoint(addr, remotePort);
                        Console.WriteLine("Client: IPEndPoint() is OK. IP Address: {0}, server port: {1}", addr, remotePort);
                        if ((sockProtocol == ProtocolType.Udp) && (udpConnect == false))
                        {
                            Console.WriteLine("Client: Destination address is: {0}", destination.ToString());
                            break;
                        }
                        else
                        {
                            Console.WriteLine("Client: Attempting connection to: {0}", destination.ToString());
                        }
                        clientSocket.Connect(destination);
                        Console.WriteLine("Client: Connect() is OK...");
                        break;
                    }
                    catch (SocketException)
                    {
                        // Connect failed, so close the socket and try the next address
                        clientSocket.Close();
                        Console.WriteLine("Client: Close() is OK...");
                        clientSocket = null;
                        continue;
                    }
                }

                // Make sure we have a valid socket before trying to use it
                if ((clientSocket != null) && (destination != null))
                {
                    try
                    {
                        new Thread(() =>
                        {
                            int sendCount = 0;
                            while (true && sendCount < 1)
                            {
                                // Send the request to the server
                                if ((sockProtocol == ProtocolType.Udp) && (udpConnect == false))
                                {
                                    clientSocket.SendTo(sendBuffer, destination);
                                    sendCount++;
                                    Console.WriteLine("Client: SendTo() is OK...UDP...");
                                }
                                else
                                {
                                    rc = clientSocket.Send(sendBuffer);
                                    sendCount++;
                                    Console.WriteLine("Client: send() is OK...TCP...");
                                    Console.WriteLine("Client: Sent request of {0} bytes", rc);

                                    // For TCP, shutdown sending on our side since the client won't send any more data
                                    if (sockProtocol == ProtocolType.Tcp)
                                    {
                                        //clientSocket.Shutdown(SocketShutdown.Send);
                                        //Console.WriteLine("Client: Shutdown() is OK...");
                                    }
                                }
                            }
                        }).Start();

                        // Receive data in a loop until the server closes the connection. For
                        //    TCP this occurs when the server performs a shutdown or closes
                        //    the socket. For UDP, we'll know to exit when the remote host
                        //    sends a zero byte datagram.
                        new Thread(() =>
                        {
                            while (true)
                            {
                                if ((sockProtocol == ProtocolType.Tcp) || (udpConnect == true))
                                {
                                    rc = clientSocket.Receive(recvBuffer);
                                    Console.WriteLine("Client: Receive() is OK...");
                                    Console.WriteLine("Client: Read {0} bytes", rc);
                                    recvBuffer = recvBuffer.Where((v, i) => i < rc).ToArray();
                                    var sbs    = new StringBuilder("new byte[] { ");
                                    for (var i = 0; i < recvBuffer.Length; i++)
                                    {
                                        var b = recvBuffer[i];
                                        sbs.Append(b);
                                        if (i < recvBuffer.Length - 1)
                                        {
                                            sbs.Append(", ");
                                        }
                                    }
                                    sbs.Append(" }");
                                    Console.WriteLine("DNP3 Application response " + sbs.ToString());
                                }
                                else
                                {
                                    IPEndPoint fromEndPoint = new IPEndPoint(destination.Address, 0);
                                    Console.WriteLine("Client: IPEndPoint() is OK...");
                                    EndPoint castFromEndPoint = (EndPoint)fromEndPoint;
                                    rc = clientSocket.ReceiveFrom(recvBuffer, ref castFromEndPoint);
                                    Console.WriteLine("Client: ReceiveFrom() is OK...");
                                    fromEndPoint = (IPEndPoint)castFromEndPoint;
                                    Console.WriteLine("Client: Read {0} bytes from {1}", rc, fromEndPoint.ToString());
                                }
                                // Exit loop if server indicates shutdown
                                if (rc == 0)
                                {
                                    clientSocket.Close();
                                    Console.WriteLine("Client: Close() is OK...");
                                    break;
                                }
                            }
                        }).Start();
                    }
                    catch (SocketException err)
                    {
                        Console.WriteLine("Client: Error occurred while sending or receiving data.");
                        Console.WriteLine("   Error: {0}", err.Message);
                    }
                }
                else
                {
                    Console.WriteLine("Client: Unable to establish connection to server!");
                }
            }
            catch (SocketException err)
            {
                Console.WriteLine("Client: Socket error occurred: {0}", err.Message);
            }
        }
Пример #19
0
        private static Wireshark CreateWireshark(this Emulation emulation, string name, LinkLayer layer)
        {
#if PLATFORM_OSX
            throw new RecoverableException("Wireshark is not available on OS X.");
#else
            Wireshark result;
            var       wiresharkPath = ConfigurationManager.Instance.Get("wireshark", "wireshark-path", WiresharkPath);
            if (File.Exists(wiresharkPath))
            {
                result = new Wireshark(name, layer, wiresharkPath);
            }
            else
            {
                throw new RecoverableException("Wireshark is not installed or is not available in the default path. Please adjust the path in Renode configuration.");
            }

            emulation.HostMachine.AddHostMachineElement(result, name);
            return(result);
#endif
        }
Пример #20
0
 /// <summary>
 /// Called after the <paramref name="link"/> is removed from the diagram.
 /// </summary>
 /// <param name="link">a <see cref="Link"/></param>
 /// <param name="layer">the <see cref="LinkLayer"/> that the <paramref name="link"/> was removed from</param>
 /// <remarks>
 /// <para>
 /// By default this method does nothing.
 /// </para>
 /// <para>
 /// The implementation of this method should not modify the model.
 /// This method cannot and should not prevent or alter the removal of the link from the diagram.
 /// </para>
 /// </remarks>
 protected virtual void OnLinkRemoved(Link link, LinkLayer layer) {
 }
Пример #21
0
        // https://blogs.msdn.microsoft.com/ericlippert/2011/02/28/guidelines-and-rules-for-gethashcode/
        public override int GetHashCode()
        {
            var fieldsHashCode = HashCodeHelper.CombineHashCodes(Timestamp.GetHashCode(), LinkLayer.GetHashCode());
            var arrayHashCode  = HashCodeHelper.ArrayHashCode(this.Data);

            return(HashCodeHelper.CombineHashCodes(fieldsHashCode, arrayHashCode));
        }