Inheritance: MonoBehaviour
Exemplo n.º 1
0
        /// <summary>
        /// Discovers and returns all NAT devices for the specified type. If no NAT device is found it returns an empty enumerable
        /// </summary>
        /// <param name="portMapper">Port mapper protocol; Upnp, Pmp or both</param>
        /// <param name="cancellationTokenSource">Cancellation token source for cancelling the discovery process</param>
        /// <returns>All found NAT devices</returns>
        public async Task<IEnumerable<NatDevice>> DiscoverDevicesAsync(PortMapper portMapper, CancellationTokenSource cancellationTokenSource)
        {
            Guard.IsTrue(portMapper == PortMapper.Upnp || portMapper == PortMapper.Pmp, "poertMapper");
            Guard.IsNotNull(cancellationTokenSource, "cancellationTokenSource");

            var devices = await DiscoverAsync(portMapper, false, cancellationTokenSource);
            return devices.ToArray();
        }
Exemplo n.º 2
0
        /// <summary>
        ///     Discovers and returns all NAT devices for the specified type. If no NAT device is found it returns an empty
        ///     enumerable
        /// </summary>
        /// <param name="portMapper">Port mapper protocol; Upnp, Pmp or both</param>
        /// <param name="cancellationTokenSource">Cancellation token source for cancelling the discovery process</param>
        /// <returns>All found NAT devices</returns>
        public async Task <IEnumerable <NatDevice> > DiscoverDevicesAsync(PortMapper portMapper,
                                                                          CancellationTokenSource cancellationTokenSource)
        {
            Guard.IsTrue(portMapper.HasFlag(PortMapper.Upnp) || portMapper.HasFlag(PortMapper.Pmp), "portMapper");
            Guard.IsNotNull(cancellationTokenSource, "cancellationTokenSource");

            var devices = await DiscoverAsync(portMapper, false, cancellationTokenSource).ConfigureAwait(false);

            return(devices.ToArray());
        }
Exemplo n.º 3
0
        /// <summary>
        /// Discovers and returns a NAT device for the specified type; otherwise a <see cref="NatDeviceNotFoundException">NatDeviceNotFoundException</see> 
        /// exception is thrown when it is cancelled. 
        /// </summary>
        /// <remarks>
        /// It allows to specify the NAT type to discover as well as the cancellation token in order.
        /// </remarks>
        /// <param name="portMapper">Port mapper protocol; Upnp, Pmp or both</param>
        /// <param name="cancellationTokenSource">Cancellation token source for cancelling the discovery process</param>
        /// <returns>A NAT device</returns>
        /// <exception cref="NatDeviceNotFoundException">when no NAT found before cancellation</exception>
        public async Task<NatDevice> DiscoverDeviceAsync(PortMapper portMapper, CancellationTokenSource cancellationTokenSource)
        {
            Guard.IsTrue(portMapper == PortMapper.Upnp || portMapper == PortMapper.Pmp, "poertMapper");
            Guard.IsNotNull(cancellationTokenSource, "cancellationTokenSource");

            var devices = await DiscoverAsync(portMapper, true, cancellationTokenSource);
            var device = devices.FirstOrDefault();
            if(device==null)
            {
                throw new NatDeviceNotFoundException();
            }
            return device;
        }
Exemplo n.º 4
0
        internal RpcTcpTransport GetTransport(int program, int version)
        {
            RpcTcpTransport transport;
            if (!_transports.TryGetValue(program, out transport))
            {
                PortMapper pm = new PortMapper(this);
                int port = pm.GetPort(program, version, PortMapperProtocol.Tcp);
                transport = new RpcTcpTransport(_serverAddress, port);
                _transports[program] = transport;
            }

            return transport;
        }
Exemplo n.º 5
0
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            PortMapper pm = PortMapper.SharedInstance;

            pm.DidStartWork               -= new PortMapper.PMDidStartWork(PortMapper_DidStartWork);
            pm.DidFinishWork              -= new PortMapper.PMDidFinishWork(PortMapper_DidFinishWork);
            pm.WillStartSearchForRouter   -= new PortMapper.PMWillStartSearchForRouter(PortMapper_WillStartSearchForRouter);
            pm.DidFinishSearchForRouter   -= new PortMapper.PMDidFinishSearchForRouter(PortMapper_DidFinishSearchForRouter);
            pm.DidChangeMappingStatus     -= new PortMapper.PMDidChangeMappingStatus(PortMapper_DidChangeMappingStatus);
            pm.ExternalIPAddressDidChange -= new PortMapper.PMExternalIPAddressDidChange(PortMapper_ExternalIPAddressDidChange);

            pm.StopBlocking();
        }
Exemplo n.º 6
0
        private void PortMapper_DidChangeMappingStatus(PortMapper sender, PortMapping pm)
        {
            DebugLog.WriteLine("Form1: PortMapper_DidChangeMappingStatus");

            foreach (ListViewItem lvi in mappings)
            {
                PortMapping lvi_pm = (PortMapping)lvi.Tag;
                if (lvi_pm == pm)
                {
                    mappingsListView.RedrawItems(lvi.Index, lvi.Index, false);
                }
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Discovers and returns a NAT device for the specified type; otherwise a <see cref="NatDeviceNotFoundException">NatDeviceNotFoundException</see>
        /// exception is thrown when it is cancelled.
        /// </summary>
        /// <remarks>
        /// It allows to specify the NAT type to discover as well as the cancellation token in order.
        /// </remarks>
        /// <param name="portMapper">Port mapper protocol; Upnp, Pmp or both</param>
        /// <param name="cancellationTokenSource">Cancellation token source for cancelling the discovery process</param>
        /// <returns>A NAT device</returns>
        /// <exception cref="NatDeviceNotFoundException">when no NAT found before cancellation</exception>
        public async Task <NatDevice> DiscoverDeviceAsync(PortMapper portMapper, CancellationTokenSource cancellationTokenSource)
        {
            Guard.IsTrue(portMapper.HasFlag(PortMapper.Upnp) || portMapper.HasFlag(PortMapper.Pmp), "portMapper");
            Guard.IsNotNull(cancellationTokenSource, "cancellationTokenSource");

            var devices = await DiscoverAsync(portMapper, true, cancellationTokenSource);

            var device = devices.FirstOrDefault();

            if (device == null)
            {
                throw new NatDeviceNotFoundException();
            }
            return(device);
        }
Exemplo n.º 8
0
        private Task <IEnumerable <NatDevice> > DiscoverAsync(PortMapper portMapper, bool onlyOne, CancellationTokenSource cts)
        {
            TraceSource.LogInfo("Start Discovery");
            var searcherTasks = new List <Task <IEnumerable <NatDevice> > >();

            if (portMapper.HasFlag(PortMapper.Upnp))
            {
                var upnpSearcher = new UpnpSearcher(new IPAddressesProvider());
                upnpSearcher.DeviceFound += (sender, args) => { if (onlyOne)
                                                                {
                                                                    cts.Cancel();
                                                                }
                };
                searcherTasks.Add(upnpSearcher.Search(cts.Token));
            }
            if (portMapper.HasFlag(PortMapper.Pmp))
            {
                var pmpSearcher = new PmpSearcher(new IPAddressesProvider());
                pmpSearcher.DeviceFound += (sender, args) => { if (onlyOne)
                                                               {
                                                                   cts.Cancel();
                                                               }
                };
                searcherTasks.Add(pmpSearcher.Search(cts.Token));
            }

            return(TaskExtension.WhenAll(searcherTasks.ToArray())
                   .ContinueWith(t =>
            {
                TraceSource.LogInfo("Stop Discovery");

                var devices = searcherTasks.SelectMany(x => x.Result);
                foreach (var device in devices)
                {
                    var key = device.ToString();
                    NatDevice nat;
                    if (Devices.TryGetValue(key, out nat))
                    {
                        nat.Touch();
                    }
                    else
                    {
                        Devices.Add(key, device);
                    }
                }
                return devices;
            }));
        }
Exemplo n.º 9
0
        /// <summary>
        /// DEPRECATED!
        /// Invoke PortMapper.GetNetStatPorts() to get occupied ports list
        /// Then filter with process name and get port number
        /// </summary>
        /// <param name="process">Target process</param>
        /// <returns>Port number of target process</returns>
        private string getTargetPort(string process)
        {
            string result = null;

            List <PortMapper.Port> portList = PortMapper.GetNetStatPorts();

            foreach (var listItem in portList)
            {
                if (listItem.process_name == process)
                {
                    result = listItem.port_number;
                }
            }

            return(result);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Discovers and returns a NAT device for the specified type; otherwise a <see cref="NatDeviceNotFoundException">NatDeviceNotFoundException</see> 
        /// exception is thrown when it is cancelled. 
        /// </summary>
        /// <remarks>
        /// It allows to specify the NAT type to discover as well as the cancellation token in order.
        /// </remarks>
        /// <param name="portMapper">Port mapper protocol; Upnp, Pmp or both</param>
        /// <param name="cancellationTokenSource">Cancellation token source for cancelling the discovery process</param>
        /// <returns>A NAT device</returns>
        /// <exception cref="NatDeviceNotFoundException">when no NAT found before cancellation</exception>
        public async Task<NatDevice> DiscoverDeviceAsync(PortMapper portMapper, CancellationTokenSource cancellationTokenSource)
        {
            Guard.IsTrue(portMapper.HasFlag(PortMapper.Upnp) || portMapper.HasFlag(PortMapper.Pmp), "portMapper");
            Guard.IsNotNull(cancellationTokenSource, "cancellationTokenSource");

            var devices = await DiscoverAsync(portMapper, true, cancellationTokenSource);
            var device = devices.FirstOrDefault();
            if(device==null)
            {
                TraceSource.LogInfo("Device not found. Common reasons:");
                TraceSource.LogInfo("\t* No device is present or,");
                TraceSource.LogInfo("\t* Upnp is disabled in the router or");
                TraceSource.LogInfo("\t* Antivirus software is filtering SSDP (discovery protocol).");
                throw new NatDeviceNotFoundException();
            }
            return device;
        }
Exemplo n.º 11
0
        private void PortMapper_DidFinishSearchForRouter(PortMapper sender)
        {
            DebugLog.WriteLine("Form1: PortMapper_DidFinishSearchForRouter");

            progressPictureBox.Visible = false;

            if (PortMapper.SharedInstance.MappingProtocolName == "UPnP")
            {
                allUpnpButton.Enabled = true;
            }
            else
            {
                allUpnpButton.Enabled = false;
            }

            UpdateTagLine();
        }
Exemplo n.º 12
0
        protected override void DoCommandAction()
        {
            int slicePortIndex = 0;

            foreach (LibElemInst inst in LibraryElementInstanceManager.Instance.GetAllInstantiations())
            {
                PortMapper portMapper = inst.PortMapper;
                Slice      s          = FPGA.FPGA.Instance.GetSlice(inst.SliceName);
                Tile       clb        = s.ContainingTile;

                Tuple <string, string, PortMapper.MappingKind> mapping = portMapper.GetMappings().Where(m => Regex.IsMatch(m.Item2, SignalName)).FirstOrDefault();

                string             signalName = portMapper.GetSignalName(mapping.Item1);
                int                index      = portMapper.GetIndex(mapping.Item1);
                string             netName    = Prefix + signalName + "[" + index + "]";
                Tuple <Port, Port> arc        = clb.SwitchMatrix.GetAllArcs().FirstOrDefault(a => Regex.IsMatch(a.Item1.Name, SliceOutPorts[slicePortIndex]));
                slicePortIndex++;
                slicePortIndex %= SliceOutPorts.Count;
                if (arc == null)
                {
                    throw new ArgumentException("Cannot start pre route from tile " + clb.Location);
                }
                Location current             = Navigator.GetDestinations(clb.Location, arc.Item2.Name).First();
                bool     startIsUserSelected = TileSelectionManager.Instance.IsUserSelected(current.Tile.TileKey, UserSelectionType);
                bool     continuePath        = true;
                string   routingConstraint   = @"set_property ROUTE { " + arc.Item1 + " " + arc.Item2 + " ";
                do
                {
                    Port port = current.Tile.SwitchMatrix.GetDrivenPorts(current.Pip).Where(p => Regex.IsMatch(p.Name, RoutingResources)).FirstOrDefault();
                    if (port == null)
                    {
                        throw new ArgumentException("Cannot continue pre route from " + current + ". Is the tile at the border of the device?");
                    }
                    routingConstraint += port.Name + " ";
                    current            = Navigator.GetDestinations(current.Tile.Location, port.Name).FirstOrDefault();

                    continuePath =
                        (startIsUserSelected && TileSelectionManager.Instance.IsUserSelected(current.Tile.TileKey, UserSelectionType)) ||
                        (!startIsUserSelected && !TileSelectionManager.Instance.IsUserSelected(current.Tile.TileKey, UserSelectionType));
                }while (continuePath);

                routingConstraint += "} [get_nets " + netName + "]" + Environment.NewLine;;
                routingConstraint += "set_property IS_ROUTE_FIXED TRUE [get_nets " + netName + "]";
                OutputManager.WriteOutput(routingConstraint);
            }
        }
Exemplo n.º 13
0
        private async Task <IEnumerable <NatDevice> > DiscoverAsync(PortMapper portMapper, bool onlyOne, CancellationTokenSource cts)
        {
            TraceSource.LogInfo("Start Discovery");
            List <Task <IEnumerable <NatDevice> > > searcherTasks = new List <Task <IEnumerable <NatDevice> > >();

            if (portMapper.HasFlag(PortMapper.Upnp))
            {
                UpnpSearcher upnpSearcher = new UpnpSearcher(new IPAddressesProvider());
                upnpSearcher.DeviceFound += (sender, args) => { if (onlyOne)
                                                                {
                                                                    cts.Cancel();
                                                                }
                };
                searcherTasks.Add(upnpSearcher.Search(cts.Token));
            }
            if (portMapper.HasFlag(PortMapper.Pmp))
            {
                PmpSearcher pmpSearcher = new PmpSearcher(new IPAddressesProvider());
                pmpSearcher.DeviceFound += (sender, args) => { if (onlyOne)
                                                               {
                                                                   cts.Cancel();
                                                               }
                };
                searcherTasks.Add(pmpSearcher.Search(cts.Token));
            }

            await Task.WhenAll(searcherTasks);

            TraceSource.LogInfo("Stop Discovery");

            IEnumerable <NatDevice> devices = searcherTasks.SelectMany(x => x.Result);

            foreach (NatDevice device in devices)
            {
                string key = device.ToString();
                if (Devices.TryGetValue(key, out NatDevice nat))
                {
                    nat.Touch();
                }
                else
                {
                    Devices.Add(key, device);
                }
            }
            return(devices);
        }
Exemplo n.º 14
0
        private void ExternalIPChanged(PortMapper sender, IPAddress externalIP)
        {
            lock (lockObj)
            {
                if (externalIP == null)
                {
                    return;
                }

                this.externalIP = externalIP;
                logger.Info("Public IP detected: " + externalIP.ToString());

                if (IsReadyToNotifyCloud())
                {
                    TaskQueue.EnqueueMedium(this.NotifyCloudOfExternalPort);
                }
            }
        }
Exemplo n.º 15
0
        private async Task <IEnumerable <NatDevice> > DiscoverAsync(PortMapper portMapper, bool onlyOne,
                                                                    CancellationTokenSource cts)
        {
            TraceSource.LogInfo("Start Discovery");
            var searcherTasks = new List <Task <IEnumerable <NatDevice> > >();

            if (portMapper.HasFlag(PortMapper.Upnp))
            {
                var upnpSearcher = new UpnpSearcher(new IPAddressesProvider());
                upnpSearcher.DeviceFound += (sender, args) => { if (onlyOne)
                                                                {
                                                                    cts.Cancel();
                                                                }
                };
                searcherTasks.Add(upnpSearcher.Search(cts.Token));
            }
            if (portMapper.HasFlag(PortMapper.Pmp))
            {
                throw new NotImplementedException();

                /*var pmpSearcher = new PmpSearcher(new IPAddressesProvider());
                 * pmpSearcher.DeviceFound += (sender, args) => { if (onlyOne) cts.Cancel(); };
                 * searcherTasks.Add(pmpSearcher.Search(cts.Token));*/
            }

            var devices = (await Task.WhenAll(searcherTasks).ConfigureAwait(false)).SelectMany(enumerable => enumerable.ToList()).ToList();

            TraceSource.LogInfo("Stop Discovery");

            foreach (var device in devices)
            {
                var       key = device.ToString();
                NatDevice nat;
                if (Devices.TryGetValue(key, out nat))
                {
                    nat.Touch();
                }
                else
                {
                    Devices.Add(key, device);
                }
            }
            return(devices);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Discovers and returns a NAT device for the specified type; otherwise a <see cref="NatDeviceNotFoundException">NatDeviceNotFoundException</see>
        /// exception is thrown when it is cancelled.
        /// </summary>
        /// <remarks>
        /// It allows to specify the NAT type to discover as well as the cancellation token in order.
        /// </remarks>
        /// <param name="portMapper">Port mapper protocol; Upnp, Pmp or both</param>
        /// <param name="cancellationTokenSource">Cancellation token source for cancelling the discovery process</param>
        /// <returns>A NAT device</returns>
        /// <exception cref="NatDeviceNotFoundException">when no NAT found before cancellation</exception>
        public async Task <NatDevice> DiscoverDeviceAsync(PortMapper portMapper, CancellationTokenSource cancellationTokenSource)
        {
            Guard.IsTrue(portMapper.HasFlag(PortMapper.Upnp) || portMapper.HasFlag(PortMapper.Pmp), "portMapper");
            Guard.IsNotNull(cancellationTokenSource, "cancellationTokenSource");

            var devices = await DiscoverAsync(portMapper, true, cancellationTokenSource);

            var device = devices.FirstOrDefault();

            if (device == null)
            {
                TraceSource.LogInfo("Device not found. Common reasons:");
                TraceSource.LogInfo("\t* No device is present or,");
                TraceSource.LogInfo("\t* Upnp is disabled in the router or");
                TraceSource.LogInfo("\t* Antivirus software is filtering SSDP (discovery protocol).");
                throw new NatDeviceNotFoundException();
            }
            return(device);
        }
Exemplo n.º 17
0
        public Mini8086Emulator()
        {
            var components = new List <BaseComponent>();

            _memMapper  = new MemoryMapper(512);
            _portMapper = new PortMapper();

            _cpu          = new Cpu8086(_memMapper, _portMapper);
            _disassembler = new Disassembler(_cpu, _memMapper);

            components.Add(_bios = new Rom(Config.BiosMemAddress));
            _memMapper.Register(Config.BiosMemAddress, Config.BiosMemAddress + Config.BiosMemSize - 1, _bios);

            components.Add(_pic = new InterruptController(Config.PicBasePort));
            _portMapper.Register(Config.PicBasePort, Config.PicBasePort + 0x07, _pic);

            components.Add(_timer = new Timer(Config.TimerBasePort, _pic));
            _portMapper.Register(Config.TimerBasePort, Config.TimerBasePort + 0x07, _timer);

            components.Add(_graphicsAdapter = new GraphicsAdapter(Config.VgaBasePort, Config.VgaMemAddress, _pic, @"..\..\..\ROMs\charrom.bin"));
            _portMapper.Register(Config.VgaBasePort, Config.VgaBasePort + 0x07, _graphicsAdapter);
            _memMapper.Register(Config.VgaMemAddress, Config.VgaMemAddress + Config.VgaMemSize - 1, _graphicsAdapter);

            components.Add(_lcd = new Lcd44780(Config.LcdBasePort));
            _portMapper.Register(Config.LcdBasePort, Config.LcdBasePort + 0x07, _lcd);

            //components.Add(_ppi = new Ppi(Config.PpiBasePort));
            //_portMapper.Register(Config.PpiBasePort, Config.PpiBasePort + 0x07, _ppi);

            components.Add(_keybController = new KeybController(Config.KeybControllerBasePort, _pic));
            _portMapper.Register(Config.KeybControllerBasePort, Config.KeybControllerBasePort + 0x07, _keybController);

            components.Add(_sdController = new SdController(Config.SdControllerBasePort, Config.SdImagePath));
            _portMapper.Register(Config.SdControllerBasePort, Config.SdControllerBasePort + 0x07, _sdController);

            _memMapper.FinishRegistration();

            components.ForEach(_ =>
            {
                _.EventTimer     = _cpu;
                _.DoCpuInterrupt = _cpu.DoInterrupt;
            });
        }
Exemplo n.º 18
0
        public async Task <int> ListDevicesAsync(bool includePMP)
        {
            var nat = new NatDiscoverer();
            var cts = new CancellationTokenSource(TIMEOUT);

            PortMapper param = PortMapper.Upnp;

            if (includePMP)
            {
                param |= PortMapper.Pmp;
            }

            logMessageContext.Create("Getting devices");

            return(await nat.DiscoverDevicesAsync(param, cts).ContinueWith(t =>
            {
                int result = 0;

                if (t.Status != TaskStatus.Faulted)
                {
                    using (IEnumerator <NatDevice> enumerator = t.Result.GetEnumerator())
                    {
                        while (enumerator.MoveNext())
                        {
                            logMessageContext.Create("Found device: " + enumerator.Current.ToString());
                            result++;
                        }
                    }
                }
                else
                {
                    if (!(t.Exception.InnerException is NatDeviceNotFoundException))
                    {
                        result = -1;
                        logMessageContext.Create("error listing devices");
                    }
                }

                return result;
            }));
        }
Exemplo n.º 19
0
    public void Awake()
    {
        DontDestroyOnLoad(this);
        NetworkPlayers = new List <uLink.NetworkPlayer>();

        ServerNotifier = new ExternalServerNotifier();

        Leaderboard      = new Leaderboard();
        Leaderboard.Skin = Relay.Instance.BaseSkin;

        StatusMessage = "?";

        BannerMessages = new List <BannerMessage>();

        if (networkView.isMine)
        {
            _CurrentMapName = Application.loadedLevelName;
            IsGameActive    = false;
            // Set up hooks for UPnP
            PortMapper = new PortMapper(Relay.Port);
        }
    }
Exemplo n.º 20
0
        public MainEmulator()
        {
            _memoryMapper = new MemoryMapper();
            _portMapper = new PortMapper();
            _cpu = new Z80 { MemProvider = _memoryMapper, PortProvider = _portMapper };

            _graphics = new Graphics();
            _memoryMapper.Register(0x1000, 0x1fff, _graphics, true, false);
            _portMapper.Register(5, 7, _graphics);

            _ram = new Ram();
            _memoryMapper.Register(0, 0xffff, _ram, true, true);
            _portMapper.Register(0, 0, _ram);

            _tickCounter = new TickCounter(_cancellationTokenSource.Token);
            _portMapper.Register(130, 133, _tickCounter);

            _diskController = new DiskController(_memoryMapper, () => _cpu.Reset());
            _portMapper.Register(160, 169, _diskController);

            _serial = new Serial(_memoryMapper);
            _portMapper.Register(170, 179, _serial);

            _led = new Led();
            _portMapper.Register(3, 3, _led);

            _speaker = new Speaker();
            _portMapper.Register(4, 4, _speaker);

            _keyboard = new Keyboard();
            _portMapper.Register(128, 129, _keyboard);

            //FBootLoader = new BootLoader(FMemoryMapper);

            _memoryMapper.FinishRegistration();

            OriginalSpeed = true;
        }
Exemplo n.º 21
0
        private void PortMappingChanged(PortMapper sender, PortMapping pm)
        {
            lock (lockObj)
            {
                if (pm != myMapping)
                {
                    return;
                }

                if (pm.MappingStatus != PortMappingStatus.Mapped)
                {
                    return;
                }

                externalPort = pm.ExternalPort;
                logger.Info("External port is registered: " + externalPort);

                if (IsReadyToNotifyCloud())
                {
                    TaskQueue.EnqueueMedium(this.NotifyCloudOfExternalPort);
                }
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Discovers and returns all NAT devices for the specified type. If no NAT device is found it returns an empty enumerable
        /// </summary>
        /// <param name="portMapper">Port mapper protocol; Upnp, Pmp or both</param>
        /// <param name="cancellationTokenSource">Cancellation token source for cancelling the discovery process</param>
        /// <returns>All found NAT devices</returns>
#if NET35
        public Task<IEnumerable<NatDevice>> DiscoverDevicesAsync(PortMapper portMapper, CancellationTokenSource cancellationTokenSource)
        {
            Guard.IsTrue(portMapper.HasFlag(PortMapper.Upnp) || portMapper.HasFlag(PortMapper.Pmp), "portMapper");
            Guard.IsNotNull(cancellationTokenSource, "cancellationTokenSource");

            return DiscoverAsync(portMapper, false, cancellationTokenSource)
                .ContinueWith(t => (IEnumerable<NatDevice>)t.Result.ToArray());
        }
        public void OnDefineNode(
            Func <string, TypeHandle, PortModel.PortModelOptions, PortModel>
            addDataInputPort, Func <string, TypeHandle, PortModel> addDataOutputPort,
            Func <string, PortModel> addExecutionInputPort,
            Func <string, PortModel> addExecutionOutputPort)
        {
            if (m_PortToOffsetMapping == null)
            {
                m_PortToOffsetMapping = new PortMapper();
            }
            else
            {
                m_PortToOffsetMapping.Clear();
            }
            m_Node = new GraphReference();

            m_Node.Inputs.SetCount(0);
            m_Node.DataInputs.SetCount(0);
            m_Node.Outputs.SetCount(0);
            m_Node.DataOutputs.SetCount(0);
            if (!m_GraphReference)
            {
                return;
            }

            m_LastHashCode = GetGraphReferenceHashCode();

            uint i = 1;

            m_Node.Target.Port.Index = i++;

            var vsGraphModel = (VSGraphModel)m_GraphReference.GraphModel;

            // TODO: ugly. GraphBuilder.AddNodeInternal is processing ports in field declaration order, hence the need here to process variables in a very specific order.
            ProcessVariablesOfGivenTypeAndDirection(vsGraphModel, ModifierFlags.ReadOnly, false, m_PortToOffsetMapping);
            ProcessVariablesOfGivenTypeAndDirection(vsGraphModel, ModifierFlags.WriteOnly, false, m_PortToOffsetMapping);
            ProcessVariablesOfGivenTypeAndDirection(vsGraphModel, ModifierFlags.ReadOnly, true, m_PortToOffsetMapping);
            ProcessVariablesOfGivenTypeAndDirection(vsGraphModel, ModifierFlags.WriteOnly, true, m_PortToOffsetMapping);

            m_Node.Inputs.Port.Index      = 2;
            m_Node.Outputs.Port.Index     = (uint)(m_Node.Inputs.Port.Index + m_Node.Inputs.DataCount);
            m_Node.DataInputs.Port.Index  = (uint)(m_Node.Outputs.Port.Index + m_Node.Outputs.DataCount);
            m_Node.DataOutputs.Port.Index = (uint)(m_Node.DataInputs.Port.Index + m_Node.DataInputs.DataCount);

            void ProcessVariablesOfGivenTypeAndDirection(VSGraphModel graphModel, ModifierFlags expectedFlags,
                                                         bool expectedData, PortMapper mPortToOffsetMapping)
            {
                foreach (var variableModel in graphModel.GraphVariableModels.Where(
                             v => v.IsInputOrOutput()))
                {
                    var isData = !variableModel.IsInputOrOutputTrigger();
                    if (variableModel.Modifiers != expectedFlags || isData != expectedData)
                    {
                        continue;
                    }
                    PortModel p;
                    if (variableModel.Modifiers == ModifierFlags.ReadOnly)
                    {
                        if (isData)
                        {
                            p = addDataInputPort(variableModel.Name, variableModel.DataType, PortModel.PortModelOptions.NoEmbeddedConstant);
                            m_Node.DataInputs.DataCount++;
                        }
                        else
                        {
                            p = addExecutionInputPort(variableModel.Name);
                            m_Node.Inputs.DataCount++;
                        }
                    }
                    else
                    {
                        if (isData)
                        {
                            p = addDataOutputPort(variableModel.Name, variableModel.DataType);
                            m_Node.DataOutputs.DataCount++;
                        }
                        else
                        {
                            p = addExecutionOutputPort(variableModel.Name);
                            m_Node.Outputs.DataCount++;
                        }
                    }

                    mPortToOffsetMapping.Add(p.UniqueId, p.Direction, i++);
                }
            }
        }
Exemplo n.º 24
0
 private void DidStartWork(PortMapper sender)
 {
 }
Exemplo n.º 25
0
        public static void ForwardPorts(PortMapper type = PortMapper.Upnp, bool retry = false)
        {
            var config          = Config.Load();
            var webServerPort   = config.WebServer.WebServerPort;
            var apiPort         = config.TaskServer.TaskServerPort;
            var webCamPort      = config.Webcams.WebcamPort;
            var terminalPort    = config.Terminal.TerminalPort;
            var screenSharePort = config.ScreenShareService.ScreenSharePort;
            var nat             = new NatDiscoverer();
            var cts             = new CancellationTokenSource();

            cts.CancelAfter(5000);
            NatDevice device;
            var       t = nat.DiscoverDeviceAsync(type, cts);

            t.ContinueWith(tt =>
            {
                device = tt.Result;
                device.GetExternalIPAsync()
                .ContinueWith(task =>
                {
                    ;
                    return(device.DeletePortMapAsync(
                               new Mapping(Protocol.Tcp, webServerPort, webServerPort, 0, "Ulterius Web Server")));
                })
                .Unwrap()
                .ContinueWith(task =>
                {
                    return(device.DeletePortMapAsync(
                               new Mapping(Protocol.Tcp, screenSharePort, screenSharePort, 0, "Ulterius Screen Share")));
                })
                .Unwrap()
                .ContinueWith(task =>
                {
                    return(device.DeletePortMapAsync(
                               new Mapping(Protocol.Tcp, apiPort, apiPort, 0, "Ulterius Api")));
                })
                .Unwrap()
                .ContinueWith(task =>
                {
                    return(device.DeletePortMapAsync(
                               new Mapping(Protocol.Tcp, webCamPort, webCamPort, 0, "Ulterius Webcams")));
                })
                .Unwrap()
                .ContinueWith(task =>
                {
                    return(device.DeletePortMapAsync(
                               new Mapping(Protocol.Tcp, terminalPort, terminalPort, 0, "Ulterius Terminal")));
                })
                .Unwrap()
                .ContinueWith(task =>
                {
                    ;
                    return(device.CreatePortMapAsync(
                               new Mapping(Protocol.Tcp, webServerPort, webServerPort, 0, "Ulterius Web Server")));
                })
                .Unwrap()
                .ContinueWith(task =>
                {
                    return(device.CreatePortMapAsync(
                               new Mapping(Protocol.Tcp, screenSharePort, screenSharePort, 0, "Ulterius Screen Share")));
                })
                .Unwrap()
                .ContinueWith(task =>
                {
                    return(device.CreatePortMapAsync(
                               new Mapping(Protocol.Tcp, apiPort, apiPort, 0, "Ulterius Api")));
                })
                .Unwrap()
                .ContinueWith(task =>
                {
                    return(device.CreatePortMapAsync(
                               new Mapping(Protocol.Tcp, webCamPort, webCamPort, 0, "Ulterius Webcams")));
                })
                .Unwrap()
                .ContinueWith(task =>
                {
                    return(device.CreatePortMapAsync(
                               new Mapping(Protocol.Tcp, terminalPort, terminalPort, 0, "Ulterius Terminal")));
                })
                .Unwrap()
                .ContinueWith(task => { Console.WriteLine("Ports forwarded!"); });
            }, TaskContinuationOptions.OnlyOnRanToCompletion);

            try
            {
                t.Wait();
            }
            catch (AggregateException e)
            {
                if (e.InnerException is NatDeviceNotFoundException)
                {
                    if (retry)
                    {
                        return;
                    }
                    ForwardPorts(PortMapper.Pmp, true);
                    Console.WriteLine("No NAT Device Found");
                }
            }
        }
Exemplo n.º 26
0
    public void Awake()
    {
        DontDestroyOnLoad(this);
        NetworkPlayers = new List<uLink.NetworkPlayer>();

        ServerNotifier = new ExternalServerNotifier();

        Leaderboard = new Leaderboard();
        Leaderboard.Skin = Relay.Instance.BaseSkin;

        StatusMessage = "?";

        BannerMessages = new List<BannerMessage>();

        if (networkView.isMine)
        {
            _CurrentMapName = Application.loadedLevelName;
            IsGameActive = false;
            // Set up hooks for UPnP
            PortMapper = new PortMapper(Relay.Port);
        }
    }
Exemplo n.º 27
0
        private async Task<IEnumerable<NatDevice>> DiscoverAsync(PortMapper portMapper, bool onlyOne, CancellationTokenSource cts)
        {
            TraceSource.LogInfo("Start Discovery");
            var searcherTasks = new List<Task<IEnumerable<NatDevice>>>();
            if(portMapper.HasFlag(PortMapper.Upnp))
            {
                var upnpSearcher = new UpnpSearcher(new IPAddressesProvider());
                upnpSearcher.DeviceFound += (sender, args) => { if (onlyOne) cts.Cancel(); };
                searcherTasks.Add(upnpSearcher.Search(cts.Token));
            }
            if(portMapper.HasFlag(PortMapper.Pmp))
            {
                var pmpSearcher = new PmpSearcher(new IPAddressesProvider());
                pmpSearcher.DeviceFound += (sender, args) => { if (onlyOne) cts.Cancel(); };
                searcherTasks.Add(pmpSearcher.Search(cts.Token));
            }

            await Task.WhenAll(searcherTasks);
            TraceSource.LogInfo("Stop Discovery");
            
            var devices = searcherTasks.SelectMany(x => x.Result);
            foreach (var device in devices)
            {
                var key = device.ToString();
                NatDevice nat;
                if(Devices.TryGetValue(key, out nat))
                {
                    nat.Touch();
                }
                else
                {
                    Devices.Add(key, device);
                }
            }
            return devices;
        }
Exemplo n.º 28
0
 private void PortMapper_DidFinishWork(PortMapper sender)
 {
     DebugLog.WriteLine("Form1: PortMapper_DidFinishWork");
 }
Exemplo n.º 29
0
        private void PortMapper_ExternalIPAddressDidChange(PortMapper sender, System.Net.IPAddress ip)
        {
            DebugLog.WriteLine("Form1: PortMapper_ExternalIPAddressDidChange");

            UpdateTagLine();
        }
        private void IntergrateIntoContainer(Command callee)
        {
            m_instanceCode.AppendLine("-- instantiation of " + m_instantation.InstanceName);
            m_instanceCode.AppendLine(m_instantation.InstanceName + " : " + m_instantation.GetLibraryElement().PrimitiveName);
            if (!string.IsNullOrEmpty(m_libraryElement.VHDLGenericMap))
            {
                m_instanceCode.AppendLine(m_libraryElement.VHDLGenericMap);
            }
            m_instanceCode.AppendLine("port map (");

            List <string> mappings = new List <string>();

            foreach (XDLPort port in ((XDLContainer)m_libraryElement.Containter).Ports)
            {
                if (!m_instantation.PortMapper.HasKindMapping(port.ExternalName))
                {
                    callee.OutputManager.WriteOutput("Warning: Could not find a signal mapping for port " + port.ExternalName + ". Misspelled mapping? Note that the mapping is case sensitive.");
                    continue;
                }

                PortMapper             mapper      = m_instantation.PortMapper;
                PortMapper.MappingKind mappingKind = mapper.GetMapping(port.ExternalName);
                string rightHandSide = mapper.GetSignalName(port.ExternalName);

                // do not vectorize already indeced ports
                //bool vector = Regex.IsMatch(port.ExternalName, @"\d+$") && !Regex.IsMatch(rightHandSide, @"\(\d+\)$");

                if (rightHandSide.Equals("0") || rightHandSide.Equals("1"))
                {
                    mappings.Add("\t" + port.ExternalName + " => " + "'" + rightHandSide + "',");
                }
                else if (rightHandSide.Equals("open"))
                {
                    mappings.Add("\t" + port.ExternalName + " => open,");
                }
                else if (!rightHandSide.Equals("open"))
                {
                    VHDLSignalList signalList = null;
                    switch (mappingKind)
                    {
                    case PortMapper.MappingKind.NoVector:
                    case PortMapper.MappingKind.External:
                    {
                        // in case of entity signals add direction
                        signalList = m_container.Entity;
                        m_container.Entity.SetDirection(rightHandSide, port.Direction);
                        break;
                    }

                    case PortMapper.MappingKind.Internal:
                    {
                        signalList = m_container.SignalDeclaration;
                        break;
                    }

                    default:
                        throw new ArgumentException("Found port mapped to " + mappingKind + ". This mapping is not supported. Use either public or external, see command AddPortMapping");
                    }

                    if (!signalList.HasSignal(rightHandSide))
                    {
                        if (m_instantation.PortMapper.HasKindMapping(port.ExternalName))
                        {
                            signalList.Add(rightHandSide, 1, m_instantation.PortMapper.GetMapping(port.ExternalName));
                        }
                        else
                        {
                            signalList.Add(rightHandSide, 1);
                        }
                    }

                    switch (mappingKind)
                    {
                    case PortMapper.MappingKind.Internal:
                    case PortMapper.MappingKind.External:
                    {
                        //int index = signalList.GetSignalWidth(rightHandSide) - 1;
                        int index = mapper.GetIndex(port.ExternalName);
                        mappings.Add("\t" + port.ExternalName + " => " + rightHandSide + "(" + index + "),");

                        if (!signalList.HasSignal(rightHandSide))
                        {
                            signalList.Add(rightHandSide, -1);
                        }
                        if (signalList.GetSignalWidth(rightHandSide) <= index)
                        {
                            signalList.SetSignalWidth(rightHandSide, index + 1);
                        }

                        // store the index generated during VHDL generation for interface checks
                        //this.m_instantation.GetPortMapper().SetIndex(port.ExternalName, index);
                        break;
                    }

                    case PortMapper.MappingKind.NoVector:
                    {
                        mappings.Add("\t" + port.ExternalName + " => " + rightHandSide + ",");
                        break;
                    }

                    default:
                        throw new ArgumentException("Found port mapped to " + mappingKind + ". This mapping is not supported. Use either public or external, see command AddPortMapping");
                    }
                }
            }

            if (mappings.Count > 0)
            {
                mappings[mappings.Count - 1] = Regex.Replace(mappings[mappings.Count - 1], ",$", "");
            }

            // update tool info
            //Tile t = FPGA.FPGA.Instance.GetTile(m_instantation.AnchorLocation);
            //Blackboard.Instance.ClearToolTipInfo(t);

            foreach (string str in mappings)
            {
                m_instanceCode.AppendLine(str);

                // update tool info
                if (!str.EndsWith(" => ,"))
                {
                    string toolTip = str;
                    toolTip  = Regex.Replace(toolTip, @"^\s+", "");
                    toolTip  = Regex.Replace(toolTip, ",", "");
                    toolTip += Environment.NewLine;
                    //Blackboard.Instance.AddToolTipInfo(t, toolTip);
                }
            }

            m_instanceCode.AppendLine(");");
        }
Exemplo n.º 31
0
 private void WillStartSearchForRouter(PortMapper sender)
 {
 }