Пример #1
0
        /// <summary>
        /// Called to create an instance
        /// </summary>
        /// <returns>The new instance</returns>
        protected override BasePipelineNode OnCreate(Logger logger, NetGraph graph, Dictionary<string, object> stateDictionary)
        {
            DelayPipelineNode node = new DelayPipelineNode();
            node.PacketDelayMs = PacketDelayMs;

            return node;
        }
Пример #2
0
        /// <summary>
        /// Method to dispatch edit packet event
        /// </summary>
        /// <param name="graph">The graph which originated the edit</param>
        /// <param name="e">The event arguments</param>
        /// <returns></returns>
        private void OnEditPacket(NetGraph graph, EditPacketEventArgs e)
        {
            EventHandler <EditPacketEventArgs> editPacketEvent = EditPacketEvent;

            if (editPacketEvent != null)
            {
                editPacketEvent(graph, e);
            }
        }
        /// <summary>
        /// Create the node if it doesn't exist
        /// </summary>
        /// <param name="logger">The logger to use when creating</param>
        /// <param name="graph">The associated netgraph</param>
        /// <param name="stateDictionary">The state dictionary</param>
        /// <returns>The created node</returns>
        protected override BasePipelineNode OnCreate(Logger logger, NetGraph graph, Dictionary<string, object> stateDictionary)
        {
            // If this is not the linked node use the master to create it and store master
            if (!stateDictionary.ContainsKey(Id.ToString()))
            {
                stateDictionary[MasterFactory.Id.ToString()] = MasterFactory.Create(logger, graph, stateDictionary);
            }

            return (BasePipelineNode)stateDictionary[Id.ToString()];
        }
Пример #4
0
        /// <summary>
        /// Edit a packet from the graph
        /// </summary>
        /// <param name="frame">The frame to edit</param>
        /// <param name="selectPath">A path to select when editing</param>
        /// <param name="sender">The sending nod</param>
        /// <param name="color">The colour to show in an edit window (if applicable)</param>
        /// <param name="tag">The textual tag to show in an edit window (if applicable)</param>
        /// <returns>The returned frame, this may or may not be the same frame as sent</returns>
        public DataFrame DoEditPacket(DataFrame frame, string selectPath, BasePipelineNode sender, ColorValue color, string tag)
        {
            NetGraph top = GetTopGraph();

            EditPacketEventArgs args = new EditPacketEventArgs(frame, selectPath, sender, color, tag);

            top.OnEditPacket(this, args);

            return(args.Frame);
        }
Пример #5
0
 public GraphEntry(LayerSectionFilter filter, LayerSectionDataAdapter clientAdapter,
                   LayerSectionDataAdapter serverAdapter, NetGraph graph, Guid clientEndpoint,
                   Guid serverEndpoint, NetworkLayerBinding defaultBinding)
 {
     Filter          = filter;
     _clientAdapter  = clientAdapter;
     _serverAdapter  = serverAdapter;
     Graph           = graph;
     _clientEndpoint = clientEndpoint;
     _serverEndpoint = serverEndpoint;
     _defaultBinding = defaultBinding;
 }
Пример #6
0
        /// <summary>
        /// Get the top graph on the stack of parents
        /// </summary>
        /// <returns>The top graph</returns>
        public NetGraph GetTopGraph()
        {
            // Walk to parent
            NetGraph top = this;

            while (top.Parent != null)
            {
                top = top.Parent;
            }

            return(top);
        }
Пример #7
0
        /// <summary>
        /// Constructor for when created a linked version of the node
        /// </summary>
        /// <param name="linkedNode">The linked master node</param>
        /// <param name="logger">The associated logger</param>
        public NetGraphContainerNode(NetGraphContainerNode linkedNode, Logger logger)
        {
            _graph = linkedNode._graph;

            // Reverse the nodes
            _inputNode  = linkedNode._outputNode;
            _outputNode = linkedNode._inputNode;

            _graph.BindEndpoint(_outputNode.Uuid, new EventDataAdapter(this));

            LinkedNode = true;

            // We don't bind logging and editing from the same graph, we assume the master did that
        }
Пример #8
0
        /// <summary>
        /// Constructor for when created a linked version of the node
        /// </summary>        
        /// <param name="linkedNode">The linked master node</param>                
        /// <param name="logger">The associated logger</param>        
        public NetGraphContainerNode(NetGraphContainerNode linkedNode, Logger logger)
        {
            _graph = linkedNode._graph;

            // Reverse the nodes
            _inputNode = linkedNode._outputNode;
            _outputNode = linkedNode._inputNode;

            _graph.BindEndpoint(_outputNode.Uuid, new EventDataAdapter(this));

            LinkedNode = true;

            // We don't bind logging and editing from the same graph, we assume the master did that
        }
Пример #9
0
        /// <summary>
        /// Overridden form of ToString
        /// </summary>
        /// <returns>The name of the node</returns>
        public override string ToString()
        {
            StringBuilder builder = new StringBuilder(Name);

            if (Graph != null)
            {
                NetGraph graph = Graph;
                while (graph.Parent != null)
                {
                    builder.Insert(0, String.Format("{0}/", graph.Name));
                    graph = graph.Parent;
                }
            }

            return(builder.ToString());
        }
Пример #10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="disposing"></param>
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (!_isDisposed)
            {
                _isDisposed = true;

                if (!LinkedNode)
                {
                    if (_graph != null)
                    {
                        ((IDisposable)_graph).Dispose();
                        _graph = null;
                    }
                }
            }
        }
Пример #11
0
        private void AddGraphToList(List<ListViewItem> items, NetGraph graph)
        {
            foreach (var pair in graph.Nodes)
            {
                BasePipelineNode node = pair.Value;

                if (_showHidden || !node.Hidden)
                {
                    NetGraphContainerNode container = node as NetGraphContainerNode;

                    if (node is NetGraphContainerNode)
                    {
                        AddGraphToList(items, ((NetGraphContainerNode)node).ContainedGraph);
                    }
                    else if (node is LayerSectionNode)
                    {
                        LayerSectionNode layerNode = (LayerSectionNode)node;

                        if (layerNode.IsMaster)
                        {
                            foreach (NetGraph subGraph in layerNode.Graphs)
                            {
                                AddGraphToList(items, subGraph);
                            }
                        }
                    }
                    else
                    {
                        ListViewItem item = new ListViewItem(node.ToString());
                        item.SubItems.Add(node.Enabled.ToString());
                        item.SubItems.Add(node.IsShutdown.ToString());
                        item.SubItems.Add(node.InputPacketCount.ToString());
                        item.SubItems.Add(node.OutputPacketCount.ToString());
                        item.SubItems.Add(node.ByteCount.ToString());
                        item.Tag = node;
                        items.Add(item);
                    }

                }
            }
        }
Пример #12
0
        /// <summary>
        /// Default constructor
        /// </summary>
        /// <param name="globalMeta">Global meta data</param>
        /// <param name="logger">Logger</param>
        /// <param name="meta">Local meta data</param>
        /// <param name="parent">Parent graph if available</param>
        /// <param name="properties">A property bag associated with this connection</param>
        public NetGraph(Logger logger, NetGraph parent, MetaDictionary globalMeta, MetaDictionary meta, PropertyBag properties)
        {
            Nodes = new Dictionary<Guid, BasePipelineNode>();
            if (meta == null)
            {
                Meta = new MetaDictionary();
            }
            else
            {
                Meta = meta;
            }

            Properties = new ConcurrentDictionary<string, string>();
            ConnectionProperties = properties;
            GlobalMeta = globalMeta;
            Uuid = Guid.NewGuid();
            if (logger != null)
            {
                Logger = logger;
            }
            else
            {
                Logger = Logger.GetSystemLogger();
            }
            NetworkDescription = "Unknown";
            Name = String.Empty;
            Parent = parent;
            Created = DateTime.Now;
            CreatedTicks = new TimeSpan(DateTime.UtcNow.Ticks);

            if (parent == null)
            {
                ServiceProvider = new CANAPEServiceProvider();
            }
            else
            {
                ServiceProvider = parent.ServiceProvider;
            }
        }
Пример #13
0
        /// <summary>
        /// Default constructor
        /// </summary>
        /// <param name="globalMeta">Global meta data</param>
        /// <param name="logger">Logger</param>
        /// <param name="meta">Local meta data</param>
        /// <param name="parent">Parent graph if available</param>
        /// <param name="properties">A property bag associated with this connection</param>
        public NetGraph(Logger logger, NetGraph parent, MetaDictionary globalMeta, MetaDictionary meta, PropertyBag properties)
        {
            Nodes = new Dictionary <Guid, BasePipelineNode>();
            if (meta == null)
            {
                Meta = new MetaDictionary();
            }
            else
            {
                Meta = meta;
            }

            Properties           = new ConcurrentDictionary <string, string>();
            ConnectionProperties = properties;
            GlobalMeta           = globalMeta;
            Uuid = Guid.NewGuid();
            if (logger != null)
            {
                Logger = logger;
            }
            else
            {
                Logger = Logger.GetSystemLogger();
            }
            NetworkDescription = "Unknown";
            Name         = String.Empty;
            Parent       = parent;
            Created      = DateTime.Now;
            CreatedTicks = new TimeSpan(DateTime.UtcNow.Ticks);

            if (parent == null)
            {
                ServiceProvider = new CANAPEServiceProvider();
            }
            else
            {
                ServiceProvider = parent.ServiceProvider;
            }
        }
Пример #14
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="name">Name of the factory</param>
        /// <param name="factory">Factory</param>
        /// <param name="direction">Direction of graph</param>
        /// <param name="containerGraph">The parent graph</param>
        /// <param name="logger">The logger to use</param>
        /// <param name="stateDictionary">Forwarded state dictionary</param>
        /// <param name="linked">If true then we are creating a linked master node</param>
        public NetGraphContainerNode(string name, NetGraphFactory factory,
                                     GraphDirection direction, NetGraph containerGraph, Logger logger,
                                     Dictionary <string, object> stateDictionary, bool linked)
        {
            var clients = factory.GetNodes <ClientEndpointFactory>();
            var servers = factory.GetNodes <ServerEndpointFactory>();

            if ((clients.Length > 0) && (servers.Length > 0))
            {
                Guid outputNode = direction == GraphDirection.ClientToServer
                    ? servers[0].Id : clients[0].Id;
                Guid inputNode = direction == GraphDirection.ClientToServer
                    ? clients[0].Id : servers[0].Id;

                if (linked)
                {
                    _graph = factory.Create(name, logger, containerGraph, containerGraph.GlobalMeta,
                                            containerGraph.Meta, containerGraph.ConnectionProperties);
                }
                else
                {
                    _graph = factory.CreateFiltered(name, logger, containerGraph, containerGraph.GlobalMeta,
                                                    containerGraph.Meta, inputNode, containerGraph.ConnectionProperties, stateDictionary);
                }

                _graph.BindEndpoint(outputNode, new EventDataAdapter(this));

                _inputNode        = (PipelineEndpoint)_graph.Nodes[inputNode];
                _inputNode.Hidden = true;

                _outputNode        = (PipelineEndpoint)_graph.Nodes[outputNode];
                _outputNode.Hidden = true;
            }
            else
            {
                throw new ArgumentException(CANAPE.Properties.Resources.NetGraphContainerNode_InvalidGraph);
            }
        }
Пример #15
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="name">Name of the factory</param>
        /// <param name="factory">Factory</param>
        /// <param name="direction">Direction of graph</param>        
        /// <param name="containerGraph">The parent graph</param>
        /// <param name="logger">The logger to use</param>
        /// <param name="stateDictionary">Forwarded state dictionary</param>
        /// <param name="linked">If true then we are creating a linked master node</param>
        public NetGraphContainerNode(string name, NetGraphFactory factory,  
            GraphDirection direction, NetGraph containerGraph, Logger logger, 
            Dictionary<string, object> stateDictionary, bool linked)
        {
            var clients = factory.GetNodes<ClientEndpointFactory>();
            var servers = factory.GetNodes<ServerEndpointFactory>();

            if ((clients.Length > 0) && (servers.Length > 0))
            {
                Guid outputNode = direction == GraphDirection.ClientToServer
                    ? servers[0].Id : clients[0].Id;
                Guid inputNode = direction == GraphDirection.ClientToServer
                    ? clients[0].Id : servers[0].Id;

                if (linked)
                {
                    _graph = factory.Create(name, logger, containerGraph, containerGraph.GlobalMeta,
                        containerGraph.Meta, containerGraph.ConnectionProperties);
                }
                else
                {
                    _graph = factory.CreateFiltered(name, logger, containerGraph, containerGraph.GlobalMeta,
                        containerGraph.Meta, inputNode, containerGraph.ConnectionProperties, stateDictionary);
                }

                _graph.BindEndpoint(outputNode, new EventDataAdapter(this));

                _inputNode = (PipelineEndpoint)_graph.Nodes[inputNode];
                _inputNode.Hidden = true;

                _outputNode = (PipelineEndpoint)_graph.Nodes[outputNode];
                _outputNode.Hidden = true;
            }
            else
            {
                throw new ArgumentException(CANAPE.Properties.Resources.NetGraphContainerNode_InvalidGraph);
            }
        }
Пример #16
0
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        protected override BasePipelineNode OnCreate(Logger logger, NetGraph graph, Dictionary<string, object> stateDictionary)
        {
            BasePipelineNode node = null;

            if (Container != null)
            {
                try
                {
                    if (String.IsNullOrWhiteSpace(ClassName))
                    {
                        throw new ArgumentException(String.Format(CANAPE.Scripting.Properties.Resources.DynamicNodeFactory_MustSpecifyClassName, Label));
                    }

                    // Determine what type of object we create, if it is an BasePipelineNode then return as is,
                    // if it is a parser then create the parsing pipeline node to contain it
                    object o = ScriptUtils.GetInstance(Container, ClassName);
                    if (o is BasePipelineNode)
                    {
                        node = o as BasePipelineNode;
                        if (State != null)
                        {
                            IPersistNode persist = node as IPersistNode;
                            if (persist != null)
                            {
                                persist.SetState(State, logger);
                            }
                        }
                    }
                    else if (o is IDataStreamParser)
                    {
                        // If we are selecting the whole packet, then we convert a binary stream
                        if (SelectionPath == "/")
                        {
                            DynamicBinaryStreamPipelineNode stmNode = new DynamicBinaryStreamPipelineNode();
                            stmNode.Container = DynamicScriptContainer.Create(Container, ClassName);
                            stmNode.State = State;

                            node = stmNode;
                        }
                        else
                        {
                            DynamicStreamPipelineNode dynNode = new DynamicStreamPipelineNode();

                            dynNode.Container = DynamicScriptContainer.Create(Container, ClassName);
                            dynNode.State = State;

                            node = dynNode;
                        }
                    }
                    else if (o is IDataArrayParser)
                    {
                        DynamicArrayPipelineNode dynNode = new DynamicArrayPipelineNode();

                        dynNode.Container = DynamicScriptContainer.Create(Container, ClassName);
                        dynNode.State = State;

                        node = dynNode;
                    }
                    else if (o is IDataStringParser)
                    {
                        DynamicStringPipelineNode dynNode = new DynamicStringPipelineNode();

                        dynNode.Container = DynamicScriptContainer.Create(Container, ClassName);
                        dynNode.State = State;

                        node = dynNode;
                    }
                    else if (o == null)
                    {
                        throw new InvalidOperationException(String.Format(CANAPE.Scripting.Properties.Resources.DynamicNodeFactory_CannotCreateType, ClassName, Label));
                    }
                    else
                    {
                        throw new InvalidOperationException(String.Format(CANAPE.Scripting.Properties.Resources.DynamicNodeFactory_InvalidNodeType, o.GetType().Name, Label));
                    }

                    node.Enabled = Enabled;
                }
                catch (EndOfStreamException)
                {
                    // End of stream
                }
                catch (ThreadAbortException)
                {
                }
            }
            else
            {
                throw new ArgumentException(String.Format(CANAPE.Scripting.Properties.Resources.DynamicNodeFactory_NoScriptSpecified, Label));
            }

            return node;
        }
Пример #17
0
        private FilePacketLogger GetLogFile(NetGraph graph)
        {
            FilePacketLogger logger = null;

            lock (_fileLogs)
            {
                if (_fileLogs.ContainsKey(graph.Uuid))
                {
                    logger =_fileLogs[graph.Uuid].Logger;
                }
                else
                {
                    long currLogIndex = Interlocked.Increment(ref _currentLogIndex);
                    string fileName = Path.Combine(redirectLogControl.BaseDirectory,
                        String.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"),
                        GeneralUtils.SanitizeFilename(graph.NetworkDescription, '_')+currLogIndex.ToString()+".log"));

                    try
                    {
                        FileRedirectLogEntry redirect = new FileRedirectLogEntry(graph.NetworkDescription, fileName);
                        _fileLogs.Add(graph.Uuid, redirect);

                        logger = redirect.Logger;
                    }
                    catch (IOException ex)
                    {
                        eventLogControl.Logger.LogException(ex);
                    }
                }
            }

            return logger;
        }
Пример #18
0
        private void HandleFrame(LayerSectionFilter filter, DataFrame frame)
        {
            string     name       = GenerateName(filter, frame);
            GraphEntry startEntry = null;

            lock (_graphEntries)
            {
                if (!_shuttingDown)
                {
                    if (_graphEntries.ContainsKey(name))
                    {
                        _graphEntries[name].GetInputAdapter(_direction).Enqueue(frame);
                    }
                    else
                    {
                        LayerSectionDataAdapter clientAdapter = new LayerSectionDataAdapter(this);
                        LayerSectionDataAdapter serverAdapter = new LayerSectionDataAdapter(_linkedNode);

                        if (_direction == LayerSectionGraphDirection.ClientToServer)
                        {
                            LayerSectionDataAdapter temp = clientAdapter;
                            clientAdapter = serverAdapter;
                            serverAdapter = temp;
                        }

                        var clients = filter.Factory.GetNodes <ClientEndpointFactory>();
                        var servers = filter.Factory.GetNodes <ServerEndpointFactory>();

                        if ((clients.Length > 0) && (servers.Length > 0))
                        {
                            MetaDictionary meta = filter.IsolatedGraph ? new MetaDictionary() : Graph.Meta;

                            NetGraph graph = filter.Factory.Create(Graph.Logger, Graph, Graph.GlobalMeta, meta, Graph.ConnectionProperties.AddBag(name));
                            graph.Name = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", Name, name);
                            startEntry = new GraphEntry(filter, clientAdapter, serverAdapter,
                                                        graph, clients[0].Id, servers[0].Id, ProxyNetworkService.GetLayerBinding(Graph));
                            startEntry.GetInputAdapter(_direction).Enqueue(frame);

                            _graphEntries[name] = startEntry;
                        }
                        else
                        {
                            throw new ArgumentException(CANAPE.Net.Properties.Resources.LayerSectionNode_InvalidGraph);
                        }
                    }
                }
            }

            // Ensure this is done outside the lock
            if (startEntry != null)
            {
                startEntry.NegotiationThread = new Thread(() =>
                {
                    try
                    {
                        startEntry.Start();
                    }
                    catch (Exception ex)
                    {
                        Graph.Logger.LogException(ex);
                        lock (_graphEntries)
                        {
                            _graphEntries.Remove(name);
                            startEntry.Dispose();
                        }
                    }
                }
                                                          );
                startEntry.NegotiationThread.CurrentUICulture = Thread.CurrentThread.CurrentUICulture;
                startEntry.NegotiationThread.IsBackground     = true;
                startEntry.NegotiationThread.Start();
            }
        }
Пример #19
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="graph">The current netgraph</param>
 /// <param name="input">The input pipeline node</param>
 /// <param name="output">The output pipeline node</param>
 internal TestGraphContainer(NetGraph graph, BasePipelineNode input, BasePipelineNode output)
 {
     Graph = graph;
     Input = input;
     Output = output;
 }
Пример #20
0
        // TODO: Should merge with implementation for the general connection so that it is 100% compatible
        /// <summary>
        /// 
        /// </summary>
        /// <param name="graph"></param>
        /// <param name="token"></param>        
        public void ReconnectClient(NetGraph graph, ProxyToken token)
        {
            IDataAdapter client = null;
            bool connected = false;
            PropertyBag networkService = graph.ConnectionProperties.GetRelativeBag("NetworkService");
            PropertyBag clientProperties = graph.ConnectionProperties.GetRelativeBag("Client");
            PropertyBag tokenProperties = graph.ConnectionProperties.GetRelativeBag("Token");

            try
            {
                while(graph.Parent != null)
                {
                    graph = graph.Parent;
                }

                if (token != null)
                {
                    // If passed in a token we need to apply filters to it
                    token = FilterToken(token);
                }
                else
                {
                    // Use original post-filtered
                    token = (ProxyToken)networkService.GetRelativeValue("Token");
                }

                if (token.Status == NetStatusCodes.Success)
                {
                    clientProperties.Clear();

                    if (token.Client == null)
                    {
                        client = _proxyClient.Connect(token, _logger, graph.Meta, _globalMeta, clientProperties, _credentialManager);
                    }
                    else
                    {
                        client = token.Client.Connect(token, _logger, graph.Meta, _globalMeta, clientProperties, _credentialManager);
                    }

                    tokenProperties.Clear();
                    token.PopulateBag(tokenProperties);

                    // Negotiate SSL or other bespoke encryption mechanisms
                    if (token.Layers != null)
                    {
                        // Bind but disabling server layer
                        NetworkLayerBinding binding = DefaultBinding & ~NetworkLayerBinding.Server;

                        foreach (INetworkLayer layer in token.Layers)
                        {
                            IDataAdapter server = null;

                            layer.Negotiate(ref server, ref client, token, _logger, graph.Meta, _globalMeta, graph.ConnectionProperties, binding);
                        }
                    }

                    graph.BindEndpoint((Guid)networkService.GetRelativeValue("ClientId"), client);

                    IDataAdapter serverAdapter = networkService.GetRelativeValue("ServerAdapter");

                    if (token.NetworkDescription != null)
                    {
                        graph.NetworkDescription = token.NetworkDescription;
                    }
                    else
                    {
                        graph.NetworkDescription = String.Format("{0} <=> {1}",
                            serverAdapter.Description, client.Description);
                    }

                    IDataAdapter oldClient = networkService.GetRelativeValue("ClientAdapter");

                    networkService.AddValue("ClientAdapter", client);
                    networkService.AddValue("Token", token);

                    oldClient.Close();

                    connected = true;
                }
                else
                {
                    _logger.LogVerbose(CANAPE.Net.Properties.Resources.ProxyNetworkService_ConnectionFiltered);
                }
            }
            catch (Exception ex)
            {
                _logger.LogException(ex);
            }
            finally
            {
                if (!connected)
                {
                    try
                    {
                        if (client != null)
                        {
                            client.Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.GetSystemLogger().LogException(ex);
                    }
                }
            }
        }
Пример #21
0
        /// <summary>
        /// Close a connection
        /// </summary>
        /// <param name="graph">The graph to close</param>
        public void CloseConnection(NetGraph graph)
        {
            ConnectionEntry entry = GetConnection(graph);

            if (entry != null)
            {
                CloseConnection(entry);
            }
        }
Пример #22
0
        /// <summary>
        /// Helper method to get the layer binding from the graph
        /// </summary>
        /// <param name="graph">The graph</param>
        /// <returns>The network layer binding, if no service returns default</returns>
        public static NetworkLayerBinding GetLayerBinding(NetGraph graph)
        {
            ProxyNetworkService service = graph.ServiceProvider.GetService<ProxyNetworkService>();

            if (service != null)
            {
                return service.DefaultBinding;
            }
            else
            {
                return NetworkLayerBinding.Default;
            }
        }
Пример #23
0
            public ConnectionEntry(ProxyNetworkService service, NetGraph graph, int timeout, bool afterData)
            {
                _service = service;
                Graph = graph;

                if (timeout > 0)
                {
                    SetTimeout(timeout, afterData);
                }

                foreach (KeyValuePair<Guid, BasePipelineNode> node in graph.Nodes)
                {
                    IPipelineEndpoint ep = node.Value as IPipelineEndpoint;

                    if (ep != null)
                    {
                        ep.DataRecieved += ep_DataRecieved;
                    }
                }
            }
Пример #24
0
        /// <summary>
        /// Method called when being created
        /// </summary>
        /// <returns>The new node</returns>
        protected override BasePipelineNode OnCreate(Logger logger, NetGraph graph, Dictionary<string, object> stateDictionary)
        {
            LogPacketPipelineNode node = new LogPacketPipelineNode();

            node.Tag = Tag;
            node.Color = Color;
            node.ConvertToBytes = ConvertToBytes;

            return node;
        }
Пример #25
0
        private void AddGraphToComboBox(NetGraph graph)
        {
            foreach (KeyValuePair<Guid, BasePipelineNode> pair in graph.Nodes)
            {
                if (!pair.Value.Hidden)
                {
                    if (pair.Value is NetGraphContainerNode)
                    {
                        AddGraphToComboBox(((NetGraphContainerNode)pair.Value).ContainedGraph);
                    }
                    else if (pair.Value is LayerSectionNode)
                    {
                        LayerSectionNode node = pair.Value as LayerSectionNode;

                        if (node.IsMaster)
                        {
                            foreach (NetGraph subGraph in node.Graphs)
                            {
                                AddGraphToComboBox(subGraph);
                            }
                        }
                    }
                    else
                    {
                        comboBoxNodes.Items.Add(pair.Value);
                    }
                }
            }
        }
Пример #26
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="graph"></param>
 public ConnectionEventArgs(NetGraph graph)
     : base()
 {
     Graph = graph;
 }
Пример #27
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="packet">The packet being logged</param>
 /// <param name="graph">The graph associated with this packet</param>
 public FilterPacketLogEventArgs(LogPacket packet, NetGraph graph)
 {
     Packet = packet;
     Graph = graph;
 }
Пример #28
0
        /// <summary>
        /// Create a node instance
        /// </summary>
        /// <returns></returns>
        protected override BasePipelineNode OnCreate(Logger logger, NetGraph graph, Dictionary<string, object> stateDictionary)
        {
            BasePipelineNode node = new EditPacketPipelineNode(_color, _tag);

            return node;
        }
Пример #29
0
 private void RemoveFileLog(NetGraph g)
 {
     if (g != null)
     {
         lock (_fileLogs)
         {
             if (_fileLogs.ContainsKey(g.Uuid))
             {
                 _fileLogs[g.Uuid].Logger.Dispose();
                 _fileLogs.Remove(g.Uuid);
             }
         }
     }
 }
Пример #30
0
        /// <summary>
        /// Set a timeout on a connection
        /// </summary>
        /// <param name="graph">The graph to set the timeout on</param>
        /// <param name="timeout">The timeout value in milliseconds</param>
        /// <param name="afterdata">True to timeout after last data received, otherwise absolute</param>
        public void SetTimeout(NetGraph graph, int timeout, bool afterdata)
        {
            ConnectionEntry entry = GetConnection(graph);

            if (entry != null)
            {
                lock (entry)
                {
                    entry.SetTimeout(timeout, afterdata);
                }
            }
        }
Пример #31
0
 void RemoveConnection(NetGraph graph)
 {
     if (InvokeRequired)
     {
         BeginInvoke(new Action<NetGraph>(RemoveConnection), graph);
     }
     else
     {
         foreach (ListViewItem item in listViewConns.Items)
         {
             if (item.Tag == graph)
             {
                 listViewConns.Items.Remove(item);
                 break;
             }
         }
     }
 }
Пример #32
0
        private ConnectionEntry GetConnection(NetGraph graph)
        {
            // Ensure at parent graph
            while (graph.Parent != null)
            {
                graph = graph.Parent;
            }

            lock (_connections)
            {
                for (int i = 0; i < _connections.Count; ++i)
                {
                    if (_connections[i].Graph == graph)
                    {
                        return _connections[i];
                    }
                }
            }

            return null;
        }
Пример #33
0
        /// <summary>
        /// Method to dispatch edit packet event
        /// </summary>
        /// <param name="graph">The graph which originated the edit</param>
        /// <param name="e">The event arguments</param>
        /// <returns></returns>
        private void OnEditPacket(NetGraph graph, EditPacketEventArgs e)
        {
            EventHandler<EditPacketEventArgs> editPacketEvent = EditPacketEvent;

            if (editPacketEvent != null)
            {
                editPacketEvent(graph, e);
            }
        }
Пример #34
0
        /// <summary>
        /// Method called for a new connection
        /// </summary>
        /// <param name="graph">The new connection graph</param>
        private void OnNewConnection(NetGraph graph)
        {
            bool connAdded = false;

            lock (_connections)
            {
                if (_state == (int)ServiceState.Running)
                {
                    _connections.Add(new ConnectionEntry(this, graph, _defaultTimeout, _afterData));
                    connAdded = true;
                }
            }

            if (connAdded)
            {
                if (NewConnectionEvent != null)
                {
                    NewConnectionEvent(this, new ConnectionEventArgs(graph));
                }

                if (_logger != null)
                {
                    _logger.LogVerbose(CANAPE.Net.Properties.Resources.NetworkServiceBase_ConnectionEstablished,
                        graph.NetworkDescription);
                }
            }
            else
            {
                // We are not running don't add it, just kill
                try
                {
                    ((IDisposable)graph).Dispose();
                }
                catch
                {
                }
            }
        }
Пример #35
0
 private string GetDescriptionString(NetGraph graph)
 {
     if (graph.Meta.ContainsKey("src") && graph.Meta.ContainsKey("dest"))
     {
         return String.Format("{0} -> {1}", graph.Meta["src"].ToString(), graph.Meta["dest"].ToString());
     }
     else
     {
         return "Unknown";
     }
 }
Пример #36
0
        private void btnInject_Click(object sender, EventArgs e)
        {
            if (_injectGraph != null)
            {
                CancelInject();
            }
            else
            {
                try
                {
                    NetGraph selectedGraph = comboBoxConnection.SelectedItem as NetGraph;

                    while ((selectedGraph == null) || (selectedGraph.CheckShutdown()))
                    {
                        PopulateConnections();

                        if (comboBoxConnection.Items.Count == 0)
                        {
                            selectedGraph = null;
                            break;
                        }

                        comboBoxConnection.SelectedItem = comboBoxConnection.Items[0];

                        selectedGraph = comboBoxConnection.SelectedItem as NetGraph;
                    }

                    if (selectedGraph != null)
                    {
                        if (logPacketControl.Packets.Length > 0)
                        {
                            if (comboBoxNodes.SelectedItem != null)
                            {
                                int repeatCount = (int)numericRepeatCount.Value;
                                BasePipelineNode node = (BasePipelineNode)comboBoxNodes.SelectedItem;

                                LogPacket[] basePackets = checkBoxInjectSelected.Checked ? logPacketControl.SelectedPackets : logPacketControl.Packets;

                                List<LogPacket> packets = new List<LogPacket>();

                                for (int i = 0; i < repeatCount; ++i)
                                {
                                    packets.AddRange((LogPacket[])GeneralUtils.CloneObject(basePackets));
                                }

                                NetGraphBuilder builder = new NetGraphBuilder();

                                ClientEndpointFactory client = builder.AddClient("client", Guid.NewGuid());
                                ServerEndpointFactory server = builder.AddServer("server", Guid.NewGuid());
                                DynamicNodeFactory dyn = null;

                                BaseNodeFactory startNode = client;

                                if (_config.EnablePacketDelay && (_config.PacketDelayMs > 0))
                                {
                                    DelayNodeFactory delay = builder.AddNode(new DelayNodeFactory("delay", Guid.NewGuid()) { PacketDelayMs = (int)_config.PacketDelayMs });
                                    builder.AddLine(startNode, delay, null);
                                    startNode = delay;
                                }

                                if (_config.EnableScripting && _config.ScriptDocumentId != Guid.Empty && !String.IsNullOrWhiteSpace(_config.ScriptDocumentClass))
                                {
                                    ScriptDocument doc = CANAPEProject.CurrentProject.GetDocumentByUuid(_config.ScriptDocumentId) as ScriptDocument;

                                    if (doc != null)
                                    {
                                        dyn = new DynamicNodeFactory("dyn", Guid.NewGuid(), doc.Container, _config.ScriptDocumentClass, null);

                                        builder.AddNode(dyn);
                                        builder.AddLine(startNode, dyn, null);
                                        startNode = dyn;
                                    }
                                }

                                builder.AddLine(startNode, server, null);

                                _injectGraph = builder.Factory.Create(selectedGraph.Logger, selectedGraph, selectedGraph.GlobalMeta,
                                    new MetaDictionary(), new PropertyBag("root"));

                                QueuedDataAdapter inputAdapter = new QueuedDataAdapter();
                                foreach (LogPacket p in packets)
                                {
                                    inputAdapter.Enqueue(p.Frame);
                                }
                                inputAdapter.StopEnqueue();

                                _injectGraph.BindEndpoint(client.Id, inputAdapter);

                                _injectGraph.BindEndpoint(server.Id, new DelegateDataAdapter(
                                    () => this.CancelInject(),
                                    frame => node.Input(frame),
                                    null
                                    ));

                                // Start injection
                                (_injectGraph.Nodes[client.Id] as IPipelineEndpoint).Start();

                                // Check if the dynamic node was an endpoint (so a generator), start as well
                                if ((dyn != null) && (_injectGraph.Nodes[dyn.Id] is PipelineEndpoint))
                                {
                                    (_injectGraph.Nodes[dyn.Id] as IPipelineEndpoint).Start();
                                }

                                // Start cancel timer
                                timerCancel.Start();

                                btnInject.Text = CANAPE.Properties.Resources.InjectPacketControl_CancelButtonText;
                            }
                            else
                            {
                                MessageBox.Show(this, CANAPE.Properties.Resources.InjectPacketForm_SelectNode,
                                    CANAPE.Properties.Resources.MessageBox_ErrorString, MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show(this, CANAPE.Properties.Resources.InjectPacketForm_SelectGraph,
                            CANAPE.Properties.Resources.MessageBox_ErrorString, MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
                    }
                }
                catch (NotSupportedException)
                {
                    MessageBox.Show(this, CANAPE.Properties.Resources.InjectPacketForm_NotSupported,
                        CANAPE.Properties.Resources.MessageBox_ErrorString, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (InvalidOperationException ex)
                {
                    MessageBox.Show(this, ex.Message,
                        CANAPE.Properties.Resources.MessageBox_ErrorString, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (NodeFactoryException ex)
                {
                    MessageBox.Show(this, ex.Message,
                        CANAPE.Properties.Resources.MessageBox_ErrorString, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Пример #37
0
 void AddGraph(NetGraph graph)
 {
     ListViewItem item = listViewConns.Items.Add(_connId.ToString());
     _connId++;
     TimeSpan currentSpan = new TimeSpan(DateTime.UtcNow.Ticks);
     item.SubItems.Add(graph.NetworkDescription);
     item.SubItems.Add(String.Format("{0}s", (long)currentSpan.Subtract(graph.CreatedTicks).TotalSeconds));
     item.Tag = graph;
 }
Пример #38
0
        private void CancelInject()
        {
            if (InvokeRequired)
            {
                Invoke(new Action(CancelInject));
            }
            else
            {
                timerCancel.Stop();

                if (_injectGraph != null)
                {
                    ((IDisposable)_injectGraph).Dispose();
                    _injectGraph = null;
                }

                btnInject.Text = CANAPE.Properties.Resources.InjectPacketControl_InjectButtonText;
            }
        }
Пример #39
0
 /// <summary>
 /// Reconnect a client using UDP
 /// </summary>
 /// <param name="graph">The network graph to reconnect</param>
 /// <param name="hostname">The hostname</param>
 /// <param name="port">The UDP port</param>
 public void ReconnectClientUdp(NetGraph graph, string hostname, int port)
 {
     ReconnectClient(graph, new IpProxyToken(null, hostname, port, IpProxyToken.IpClientType.Udp, false));
 }
Пример #40
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="disposing"></param>
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (!_isDisposed)
            {
                _isDisposed = true;

                if (!LinkedNode)
                {
                    if (_graph != null)
                    {
                        ((IDisposable)_graph).Dispose();
                        _graph = null;
                    }
                }
            }
        }