Esempio n. 1
0
        public static void TrackDevices(Router router)
        {
            // Find AppDeployCmd.exe
            var programFilesX86 = Environment.GetEnvironmentVariable(Environment.Is64BitOperatingSystem ? "COMMONPROGRAMFILES(X86)" : "COMMONPROGRAMFILES");
            var ipOverUsbEnum = Path.Combine(programFilesX86, @"Microsoft Shared\Phone Tools\CoreCon\11.0\Bin\IpOverUsbEnum.exe");
            if (!File.Exists(ipOverUsbEnum))
            {
                return;
            }

            var portRegex = new Regex(string.Format(@"{0} (\d+) ->", IpOverUsbXenkoName));
            var currentWinPhoneDevices = new Dictionary<int, ConnectedDevice>();

            bool checkIfPortMappingIsSetup = false;

            while (true)
            {
                ProcessOutputs devicesOutputs;
                try
                {
                    devicesOutputs = ShellHelper.RunProcessAndGetOutput(ipOverUsbEnum, "");
                }
                catch (Exception)
                {
                    continue;
                }

                if (devicesOutputs.ExitCode != 0)
                    continue;

                var newWinPhoneDevices = new Dictionary<int, string>();

                // First time a device is detected, we check port mapping is properly setup in registry
                var isThereAnyDevices = devicesOutputs.OutputLines.Any(x => x == "Partner:");
                if (isThereAnyDevices && !checkIfPortMappingIsSetup)
                {

                    using (var ipOverUsb = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\IpOverUsb") ?? Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\IpOverUsbSdk"))
                    {
                        if (ipOverUsb != null)
                        {
                            using (var ipOverUsbXenko = ipOverUsb.OpenSubKey(IpOverUsbXenkoName))
                            {
                                if (ipOverUsbXenko == null)
                                {
                                    RegisterWindowsPhonePortMapping();
                                }
                            }
                        }
                    }

                    checkIfPortMappingIsSetup = true;
                }

                // Match forwarded ports
                foreach (var outputLine in devicesOutputs.OutputLines)
                {
                    int port;
                    var match = portRegex.Match(outputLine);
                    if (match.Success && Int32.TryParse(match.Groups[1].Value, out port))
                    {
                        newWinPhoneDevices.Add(port, "Device");
                    }
                }

                DeviceHelper.UpdateDevices(Log, newWinPhoneDevices, currentWinPhoneDevices, (connectedDevice) =>
                {
                    // Launch a client thread that will automatically tries to connect to this port
                    var localPort = (int)connectedDevice.Key;

                    Log.Info("Device connected: {0}; mapped port {1}", connectedDevice.Name, localPort);

                    Task.Run(() => DeviceHelper.LaunchPersistentClient(connectedDevice, router, "localhost", localPort));
                });

                Thread.Sleep(1000); // Detect new devices every 1000 msec
            }
        }
Esempio n. 2
0
 public IosTracker(Router router)
 {
     this.router = router;
 }
Esempio n. 3
0
        static int Main(string[] args)
        {
            var exeName = Path.GetFileName(Assembly.GetExecutingAssembly().Location);
            var showHelp = false;
            var windowsPhonePortMapping = false;
            int exitCode = 0;
            string logFileName = "routerlog.txt";

            var p = new OptionSet
                {
                    "Copyright (C) 2011-2015 Silicon Studio Corporation. All Rights Reserved",
                    "Xenko Router Server - Version: "
                    +
                    String.Format(
                        "{0}.{1}.{2}",
                        typeof(Program).Assembly.GetName().Version.Major,
                        typeof(Program).Assembly.GetName().Version.Minor,
                        typeof(Program).Assembly.GetName().Version.Build) + string.Empty,
                    string.Format("Usage: {0} command [options]*", exeName),
                    string.Empty,
                    "=== Options ===",
                    string.Empty,
                    { "h|help", "Show this message and exit", v => showHelp = v != null },
                    { "log-file=", "Log build in a custom file (default: routerlog.txt).", v => logFileName = v },
                    { "register-windowsphone-portmapping", "Register Windows Phone IpOverUsb port mapping", v => windowsPhonePortMapping = true },
                };

            try
            {
                var commandArgs = p.Parse(args);
                if (showHelp)
                {
                    p.WriteOptionDescriptions(Console.Out);
                    return 0;
                }

                // Make sure path exists
                if (commandArgs.Count > 0)
                    throw new OptionException("This command expect no additional arguments", "");

                if (windowsPhonePortMapping)
                {
                    WindowsPhoneTracker.RegisterWindowsPhonePortMapping();
                    return 0;
                }

                SetupTrayIcon(logFileName);

                // Enable file logging
                if (!string.IsNullOrEmpty(logFileName))
                {
                    var fileLogListener = new TextWriterLogListener(File.Open(logFileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite));
                    GlobalLogger.GlobalMessageLogged += fileLogListener;
                }

                // TODO: Lock will be only for this folder but it should be shared across OS (should we resolve SiliconStudioXenkoDir?)
                using (var mutex = FileLock.TryLock("connectionrouter.lock"))
                {
                    if (mutex == null)
                    {
                        Console.WriteLine("Another instance of Xenko Router is already running");
                        return -1;
                    }

                    var router = new Router();

                    // Start router (in listen server mode)
                    router.Listen(RouterClient.DefaultPort).Wait();

                    // Start Android management thread
                    new Thread(() => AndroidTracker.TrackDevices(router)) { IsBackground = true }.Start();

                    // Start Windows Phone management thread
                    new Thread(() => WindowsPhoneTracker.TrackDevices(router)) { IsBackground = true }.Start();

                    //Start iOS device discovery and proxy launcher
                    //Currently this is used only internally for QA testing... as we cannot attach the debugger from windows for normal usages..
                    if (IosTracker.CanProxy())
                    {
                        new Thread(async () =>
                        {
                            var iosTracker = new IosTracker(router);
                            await iosTracker.TrackDevices();
                        }) { IsBackground = true }.Start();
                    }

                    // Start WinForms loop
                    System.Windows.Forms.Application.Run();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("{0}: {1}", exeName, e);
                if (e is OptionException)
                    p.WriteOptionDescriptions(Console.Out);
                exitCode = 1;
            }

            return exitCode;
        }
        public static void TrackDevices(Router router)
        {
            var currentAndroidDevices = new Dictionary<string, ConnectedDevice>();

            // Start new devices
            int startLocalPort = 51153; // Use ports in the dynamic port range

            // Check if ADB is on the path
            var adbPath = AndroidDeviceEnumerator.GetAdbPath();
            if (adbPath == null)
                return;

            // Wait and process android device changes events
            while (true)
            {
                // Fill list of android devices
                var newAndroidDevices = new Dictionary<string, string>();
                foreach (var device in AndroidDeviceEnumerator.ListAndroidDevices())
                {
                    newAndroidDevices.Add(device.Serial, string.Format("{0} ({1})", device.Name, device.Serial));
                }

                DeviceHelper.UpdateDevices(Log, newAndroidDevices, currentAndroidDevices, (connectedDevice) =>
                {
                    // First, try adb reverse port mapping (supported on newest adb+device)
                    // This is the best solution, as nothing specific needs to be done.
                    // NOTE: disabled for now, as it's difficult to know what to try first from the device itself.
                    //var output = ShellHelper.RunProcessAndGetOutput(AndroidDeviceEnumerator.GetAdbPath(), string.Format(@"-s {0} reverse tcp:{1} tcp:{2}", newAndroidDevice, LocalPort, LocalPort));
                    //if (output.ExitCode == 0)
                    //    continue;

                    // Setup adb port forward (tries up to 5 times for open ports)
                    int localPort = 0;
                    int firstTestedLocalPort = startLocalPort;
                    for (int i = 0; i < 4; ++i)
                    {
                        int testedLocalPort = startLocalPort++;
                        if (startLocalPort >= 65536) // Make sure we stay in the range of dynamic ports: 49152-65535
                            startLocalPort = 49152;

                        var output = ShellHelper.RunProcessAndGetOutput(adbPath, string.Format(@"-s {0} forward tcp:{1} tcp:{2}", connectedDevice.Key, testedLocalPort, RouterClient.DefaultListenPort));

                        if (output.ExitCode == 0)
                        {
                            localPort = testedLocalPort;
                            Log.Info("Android Device connected: {0}; successfully mapped port {1}:{2}", connectedDevice.Name, testedLocalPort, RouterClient.DefaultListenPort);
                            break;
                        }
                    }

                    if (localPort == 0)
                    {
                        int lastTestedLocalPort = startLocalPort;
                        Log.Info("Android Device connected: {0}; error when mapping port [{1}-{2}]:{3}", connectedDevice.Name, firstTestedLocalPort, lastTestedLocalPort - 1, RouterClient.DefaultListenPort);
                        return;
                    }

                    // Launch a client thread that will automatically tries to connect to this port
                    Task.Run(() => DeviceHelper.LaunchPersistentClient(connectedDevice, router, "localhost", localPort));
                });

                Thread.Sleep(1000); // Detect new devices every 1000 msec
            }
        }
Esempio n. 5
0
        public static void TrackDevices(Router router)
        {
            // Find AppDeployCmd.exe
            var programFilesX86 = Environment.GetEnvironmentVariable(Environment.Is64BitOperatingSystem ? "COMMONPROGRAMFILES(X86)" : "COMMONPROGRAMFILES");
            var ipOverUsbEnum   = Path.Combine(programFilesX86, @"Microsoft Shared\Phone Tools\CoreCon\11.0\Bin\IpOverUsbEnum.exe");

            if (!File.Exists(ipOverUsbEnum))
            {
                return;
            }

            var portRegex = new Regex(string.Format(@"{0} (\d+) ->", IpOverUsbXenkoName));
            var currentWinPhoneDevices = new Dictionary <int, ConnectedDevice>();

            bool checkIfPortMappingIsSetup = false;

            while (true)
            {
                ProcessOutputs devicesOutputs;
                try
                {
                    devicesOutputs = ShellHelper.RunProcessAndGetOutput(ipOverUsbEnum, "");
                }
                catch (Exception)
                {
                    continue;
                }

                if (devicesOutputs.ExitCode != 0)
                {
                    continue;
                }

                var newWinPhoneDevices = new Dictionary <int, string>();

                // First time a device is detected, we check port mapping is properly setup in registry
                var isThereAnyDevices = devicesOutputs.OutputLines.Any(x => x == "Partner:");
                if (isThereAnyDevices && !checkIfPortMappingIsSetup)
                {
                    using (var ipOverUsb = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\IpOverUsb") ?? Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\IpOverUsbSdk"))
                    {
                        if (ipOverUsb != null)
                        {
                            using (var ipOverUsbXenko = ipOverUsb.OpenSubKey(IpOverUsbXenkoName))
                            {
                                if (ipOverUsbXenko == null)
                                {
                                    RegisterWindowsPhonePortMapping();
                                }
                            }
                        }
                    }

                    checkIfPortMappingIsSetup = true;
                }

                // Match forwarded ports
                foreach (var outputLine in devicesOutputs.OutputLines)
                {
                    int port;
                    var match = portRegex.Match(outputLine);
                    if (match.Success && Int32.TryParse(match.Groups[1].Value, out port))
                    {
                        newWinPhoneDevices.Add(port, "Device");
                    }
                }

                DeviceHelper.UpdateDevices(Log, newWinPhoneDevices, currentWinPhoneDevices, (connectedDevice) =>
                {
                    // Launch a client thread that will automatically tries to connect to this port
                    var localPort = (int)connectedDevice.Key;

                    Log.Info($"Device connected: {connectedDevice.Name}; mapped port {localPort}");

                    Task.Run(() => DeviceHelper.LaunchPersistentClient(connectedDevice, router, "localhost", localPort));
                });

                Thread.Sleep(1000); // Detect new devices every 1000 msec
            }
        }
Esempio n. 6
0
 public IosTracker(Router router)
 {
     this.router = router;
 }