Esempio n. 1
0
        static AdbServer()
        {
            switch (Environment.OSVersion.Platform)
            {
            case PlatformID.Win32NT:
                EndPoint = new IPEndPoint(IPAddress.Loopback, AdbServerPort);
                break;

            case PlatformID.MacOSX:
            case PlatformID.Unix:
                EndPoint = new UnixEndPoint($"/tmp/{AdbServerPort}");
                break;

            default:
                throw new InvalidOperationException("Only Windows, Linux and Mac OS X are supported");
            }
        }
Esempio n. 2
0
        private async Task <Socket> Connect()
        {
            Socket   socket   = null;
            EndPoint endpoint = null;

            if (Address.Scheme == "tcp" || Address.Scheme == "tcp")
            {
                var domain = Address.DnsSafeHost;
                if (!IPAddress.TryParse(domain, out IPAddress address))
                {
                    address = (await Dns.GetHostAddressesAsync(domain)).FirstOrDefault();
                    if (address == null)
                    {
                        throw new Exception("Host not found");
                    }
                }
                socket   = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                endpoint = new IPEndPoint(address, Address.Port);
            }
            else if (Address.Scheme == "unix")
            {
                var path = Address.AbsoluteUri.Remove(0, "unix:".Length);
                if (!path.StartsWith('/'))
                {
                    path = "/" + path;
                }
                while (path.Length >= 2 && (path[0] != '/' || path[1] == '/'))
                {
                    path = path.Remove(0, 1);
                }
                if (path.Length < 2)
                {
                    throw new FormatException("Invalid unix url");
                }
                socket   = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
                endpoint = new UnixEndPoint(path);
            }
            else
            {
                throw new NotSupportedException($"Protocol {Address.Scheme} for clightning not supported");
            }

            await socket.ConnectAsync(endpoint);

            return(socket);
        }
Esempio n. 3
0
        private async Task <bool> OpenUnixSocketAsync(ConnectionSettings cs, IOBehavior ioBehavior, CancellationToken cancellationToken)
        {
            var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
            var unixEp = new UnixEndPoint(cs.UnixSocket);

            try
            {
                using (cancellationToken.Register(() => socket.Dispose()))
                {
                    try
                    {
                        if (ioBehavior == IOBehavior.Asynchronous)
                        {
#if NETSTANDARD1_6
                            await socket.ConnectAsync(unixEp).ConfigureAwait(false);
#else
                            await Task.Factory.FromAsync(socket.BeginConnect, socket.EndConnect, unixEp, null).ConfigureAwait(false);
#endif
                        }
                        else
                        {
                            socket.Connect(unixEp);
                        }
                    }
                    catch (ObjectDisposedException ex) when(cancellationToken.IsCancellationRequested)
                    {
                        throw new MyCatException("Connect Timeout expired.", ex);
                    }
                }
            }
            catch (SocketException)
            {
                socket.Dispose();
            }

            if (socket.Connected)
            {
                m_socket        = socket;
                m_networkStream = new NetworkStream(socket);

                m_state = State.Connected;
                return(true);
            }

            return(false);
        }
Esempio n. 4
0
        /**
         * Constructor with given socket path
         * @param socketPath
         * @throws IOException
         */
        public ClientManager(string socketPath)
        {
            this.socketPath = socketPath;
            //lines below taken from https://stackoverflow.com/a/40203940/87088
            var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);

            var unixEp = new UnixEndPoint(socketPath);

            socket.Connect(unixEp);
            NetworkStream oss = new NetworkStream(socket);
            NetworkStream iss = new NetworkStream(socket);

            //below lines translated from:
            //AFUNIXSocket socket = AFUNIXSocket.connectTo(new AFUNIXSocketAddress(new File(socketPath)));
            //this.transport = new TIOStreamTransport(socket.getInputStream(), socket.getOutputStream());
            this.transport = new TStreamTransport(iss, oss);
            this.protocol  = new TBinaryProtocol(transport);
        }
Esempio n. 5
0
        private void SendRequestOverSocket()
        {
            var unixSocket = Constants.SOCKET_NAME;

            using (var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP))
            {
                var unixEp = new UnixEndPoint(unixSocket);
                //socket.NoDelay = true;
                socket.Connect(unixEp);

                var header  = "POST /index HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n";
                var body    = "hello=workd&aid=SomeID\r\n";
                var cl      = "Content-Length: " + (Encoding.UTF8.GetByteCount(body)) + "\r\n\r\n";
                var payload = Encoding.UTF8.GetBytes(header + cl + body);
                socket.Send(payload, payload.Length, 0);
                socket.Close();
            }
        }
Esempio n. 6
0
        static Socket Connect(string filename)
        {
            if (filename == null || filename == "")
            {
                return(null);
            }

            EndPoint ep   = new UnixEndPoint(filename);
            Socket   sock = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);

            try {
                sock.Connect(ep);
            } catch (Exception) {
                sock.Close();
                return(null);
            }
            return(sock);
        }
Esempio n. 7
0
        private Stream CreateUnixSocketStream()
        {
#if __MonoCS__ && !WINDOWS
            Socket socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);

            try
            {
                UnixEndPoint endPoint = new UnixEndPoint(hostList);
                socket.Connect(endPoint);
                return(new NetworkStream(socket, true));
            }
            catch (Exception ex)
            {
                return(null);
            }
#else
            throw new PlatformNotSupportedException("Unix sockets are only supported on this platform");
#endif
        }
Esempio n. 8
0
        public Logger(string logFile, string webHook)
        {
            file   = new StreamWriter(logFile, true);
            counts = new int[Enum.GetValues(typeof(Logging)).Length];
            if (File.Exists(ENDPOINT))
            {
                File.Delete(ENDPOINT);
            }
            socket   = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
            endpoint = new UnixEndPoint(ENDPOINT);
            socket.Bind(endpoint);
            socket.Listen(1);
            socket.BeginAccept(new AsyncCallback(AcceptCallback), null);
            var fileInfo = new Mono.Unix.UnixFileInfo(ENDPOINT);

            Syscall.chown(ENDPOINT, Syscall.getuid(), Syscall.getgrnam("netdata").gr_gid);
            Syscall.chmod(ENDPOINT, FilePermissions.S_IWGRP | FilePermissions.S_IWUSR | FilePermissions.S_IRGRP | FilePermissions.S_IRUSR);
            this.webHook = webHook;
        }
Esempio n. 9
0
        public override bool AttemptConnection(string a_pipe)
        {
            m_socket          = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
            m_socket.Blocking = false;

            UnixEndPoint endPoint = new UnixEndPoint(string.Format("{0}/{1}", m_envPath, a_pipe));

            try
            {
                m_socket.Connect(endPoint);
            }
            catch (Exception e)
            {
                InternalConsole.Error(string.Format("Failed to connect to {0}: {1}", a_pipe, e.Message));

                return(false);
            }

            return(true);
        }
        private StatsSenderData CreateStatsSender(StatsdConfig config, string statsdServerName)
        {
            var statsSenderData = new StatsSenderData();

            if (statsdServerName.StartsWith(UnixDomainSocketPrefix))
            {
                statsdServerName = statsdServerName.Substring(UnixDomainSocketPrefix.Length);
                var endPoint = new UnixEndPoint(statsdServerName);
                statsSenderData.Sender = _factory.CreateUnixDomainSocketStatsSender(
                    endPoint,
                    config.Advanced.UDSBufferFullBlockDuration);
                statsSenderData.BufferCapacity = config.StatsdMaxUnixDomainSocketPacketSize;
            }
            else
            {
                statsSenderData.Sender         = CreateUDPStatsSender(config, statsdServerName);
                statsSenderData.BufferCapacity = config.StatsdMaxUDPPacketSize;
            }

            return(statsSenderData);
        }
Esempio n. 11
0
        public static SocketConfig ParseSocketConfig(XmlNode Node)
        {
            string type = Node.Attributes["type"].Value.Trim().ToLower();

            switch (type)
            {
            case "unix":
            {
                var          socket         = new Socket(AddressFamily.Unix, SocketType.Stream, 0);
                var          endPoint       = new UnixEndPoint(Node.InnerText);
                XmlAttribute permsAttribute = Node.Attributes["perms"];
                SocketConfig sockConf       = new SocketConfig(socket, endPoint)
                {
                    UnixSocketPath = Node.InnerText
                };
                if (permsAttribute != null)
                {
                    sockConf.UnixSocketPerms = ParseUnixSocketPerms(permsAttribute.Value.Trim());
                }
                else
                {
                    sockConf.UnixSocketPerms = (FilePermissions)(0xC000 | 0x100 | 0x80 | 0x20 | 0x10);
                }
                return(sockConf);
            }

            case "tcp":
            {
                var    socket   = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                var    endPoint = Helper.GetIPEndPointFromString(Node.InnerText);
                string strTls   = Node.Attributes["tls"].Value.Trim();
                return(new SocketConfig(socket, endPoint)
                    {
                        UseTLS = Convert.ToBoolean(strTls)
                    });
            }

            default: throw new Exception("Unknown node '" + Node.Name + "'");
            }
        }
Esempio n. 12
0
        public void TestCreate()
        {
            const string socketFile = "test";
            // mangledSocketFile simulates the socket file name with a null
            // terminator and junk after the null terminator. This can be present
            // in a SocketAddress when marshaled from native code.
            const string mangledSocketFile = socketFile + "\0junk";

            var bytes         = Encoding.Default.GetBytes(mangledSocketFile);
            var socketAddress = new SocketAddress(AddressFamily.Unix, bytes.Length + 2);

            for (int i = 0; i < bytes.Length; i++)
            {
                socketAddress [i + 2] = bytes [i];
            }
            var dummyEndPoint = new UnixEndPoint(socketFile);

            // testing that the Create() method strips off the null terminator and the junk
            var endPoint = (UnixEndPoint)dummyEndPoint.Create(socketAddress);

            Assert.AreEqual(socketFile, endPoint.Filename, "#A01");
        }
Esempio n. 13
0
        public async Task <CrossSocket> Connect()
        {
            if (IsUnix)
            {
                var home = Environment.GetEnvironmentVariable("HOME");
                if (!((new DirectoryInfo(home)).Exists))
                {
                    home = "/Users/" + Environment.GetEnvironmentVariable("USER");
                }
                var kawi    = home + "/.kawi";
                var kawidir = new DirectoryInfo(kawi);
                if (!kawidir.Exists)
                {
                    kawidir.Create();
                }
                kawi    = kawi + "/rpa";
                kawidir = new DirectoryInfo(kawi);
                if (!kawidir.Exists)
                {
                    kawidir.Create();
                }

                var file         = kawi + "/" + GetSha1Id();
                var socket       = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
                var unixEndPoint = new UnixEndPoint(file);
                await socket.ConnectAsync(unixEndPoint);

                CrossSocket csocket = new CrossSocket();
                csocket.socket = socket;
                return(csocket);
            }
            else
            {
                var         pipe    = new NamedPipeClientStream(GetSha1Id());
                CrossSocket csocket = new CrossSocket();
                csocket.pipec = pipe;
                return(csocket);
            }
        }
Esempio n. 14
0
        public SocketClient(SocketSettings socketSettings)
        {
            SocketSettings.Validate(socketSettings.ProtocolType, socketSettings.Address, socketSettings.Port);

            if (socketSettings.ProtocolType == ProtocolType.Tcp)
            {
                _tcpClient = new TcpClient();
            }

            if (socketSettings.ProtocolType == ProtocolType.Udp)
            {
                _udpClient = new UdpClient();
            }

            if (socketSettings.ProtocolType == ProtocolType.IP)
            {
                _unixClient   = new System.Net.Sockets.Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
                _unixEndpoint = new UnixEndPoint(socketSettings.Address);
            }

            _socketSettings = socketSettings;
        }
Esempio n. 15
0
        private bool CreateUnixSocketStream(string socketName)
        {
#if __MonoCS__ && !WINDOWS
            Socket socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);

            try
            {
                UnixEndPoint endPoint = new UnixEndPoint(socketName);
                socket.Connect(endPoint);
                stream = new NetworkStream(socket, true);
                return(true);
            }
            catch (Exception ex)
            {
                baseException = ex;
                return(false);
            }
#else
            baseException = new PlatformNotSupportedException("This is not a Unix");
            return(false);
#endif
        }
        public UnixDomainSocketTransport(
            UnixEndPoint endPoint,
            TimeSpan?bufferFullBlockDuration)
        {
            if (bufferFullBlockDuration.HasValue)
            {
                _noBufferSpaceAvailableRetryCount = (int)(bufferFullBlockDuration.Value.TotalMilliseconds
                                                          / NoBufferSpaceAvailableWait.TotalMilliseconds);
            }

            try
            {
                _socket = new Socket(AddressFamily.Unix, SocketType.Dgram, ProtocolType.Unspecified);
            }
            catch (SocketException e)
            {
                throw new NotSupportedException($"Unix domain socket is not supported on your operating system.", e);
            }

            // When closing, wait 2 seconds to send data.
            _socket.LingerState = new LingerOption(true, 2);
            _endPoint           = endPoint;
        }
        public StatsdUnixDomainSocket(string unixSocket, int maxPacketSize)
        {
            if (unixSocket == null || !unixSocket.StartsWith(StatsdUnixDomainSocket.UnixDomainSocketPrefix))
            {
                throw new ArgumentException($"{nameof(unixSocket)} must start with {StatsdUnixDomainSocket.UnixDomainSocketPrefix}");
            }
            unixSocket = unixSocket.Substring(StatsdUnixDomainSocket.UnixDomainSocketPrefix.Length);

            try
            {
                _socket = new Socket(AddressFamily.Unix, SocketType.Dgram, ProtocolType.IP);
            }
            catch (SocketException e)
            {
                throw new NotSupportedException("Unix domain socket is not supported on your operating system.", e);
            }
            _endPoint        = new UnixEndPoint(unixSocket);
            _maxPacketSize   = maxPacketSize;
            _socket.Blocking = false;

            // When closing, wait 2 seconds to send data.
            _socket.LingerState = new LingerOption(true, 2);
            _socketLock         = new object();
        }
Esempio n. 18
0
        public static void Start()
        {
            // Connect to a remote device.
            try
            {
                var unixSocket = "/tmp/dolittle.sock";
                var client     = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
                var unixEp     = new UnixEndPoint(unixSocket);
                //client.Bind(unixEp);


                // Connect to the remote endpoint.
                client.BeginConnect(unixEp,
                                    new AsyncCallback(ConnectCallback), client);
                connectDone.WaitOne();

                // Send test data to the remote device.
                Send(client, "This is a test<EOF>");
                sendDone.WaitOne();

                // Receive the response from the remote device.
                Receive(client);
                receiveDone.WaitOne();

                // Write the response to the console.
                Console.WriteLine("Response received : {0}", response);

                // Release the socket.
                client.Shutdown(SocketShutdown.Both);
                client.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
Esempio n. 19
0
        private static HttpResponse RunDockerCommand(string endpoint, HttpMethod method, string body = null)
        {
            var unixSocket = "/var/run/docker.sock";
            var socket     = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
            var unixEp     = new UnixEndPoint(unixSocket);

            socket.Connect(unixEp);

            var rawHttpString = $"{method.ToString()} /v1.37/{endpoint} HTTP/1.1\nHost: .\n";

            if (body != null)
            {
                rawHttpString += $"Content-Length: {body.Length}\n";
                rawHttpString += $"Content-Type: application/json\n";
                rawHttpString += "\n";
                rawHttpString += body;
            }
            rawHttpString += "\n";
            socket.Send(Encoding.UTF8.GetBytes(rawHttpString), 0, Encoding.UTF8.GetByteCount(rawHttpString), SocketFlags.None);

            var httpResult = ReadAndParseResponse(socket);

            return(httpResult);
        }
Esempio n. 20
0
        int Run(MonoDevelopOptions options)
        {
            Counters.Initialization.BeginTiming();

            if (options.LogCounters)
            {
                string logFile = Path.Combine(Environment.CurrentDirectory, "monodevelop.clog");
                LoggingService.LogInfo("Logging instrumentation service data to file: " + logFile);
                InstrumentationService.StartAutoSave(logFile, 1000);
            }

            Counters.Initialization.Trace("Initializing GTK");
            SetupExceptionManager();

            try {
                MonoDevelop.Ide.Gui.GLibLogging.Enabled = true;
            } catch (Exception ex) {
                LoggingService.LogError("Error initialising GLib logging.", ex);
            }

            //OSXFIXME
            var args = options.RemainingArgs.ToArray();

            Gtk.Application.Init("monodevelop", ref args);

            //default to Windows IME on Windows
            if (Platform.IsWindows && Mono.TextEditor.GtkWorkarounds.GtkMinorVersion >= 16)
            {
                var settings = Gtk.Settings.Default;
                var val      = Mono.TextEditor.GtkWorkarounds.GetProperty(settings, "gtk-im-module");
                if (string.IsNullOrEmpty(val.Val as string))
                {
                    Mono.TextEditor.GtkWorkarounds.SetProperty(settings, "gtk-im-module", new GLib.Value("ime"));
                }
            }

            InternalLog.Initialize();
            string   socket_filename = null;
            EndPoint ep = null;

            DispatchService.Initialize();

            // Set a synchronization context for the main gtk thread
            SynchronizationContext.SetSynchronizationContext(new GtkSynchronizationContext());

            AddinManager.AddinLoadError += OnAddinError;

            var startupInfo = new StartupInfo(args);

            // If a combine was specified, force --newwindow.

            if (!options.NewWindow && startupInfo.HasFiles)
            {
                Counters.Initialization.Trace("Pre-Initializing Runtime to load files in existing window");
                Runtime.Initialize(true);
                foreach (var file in startupInfo.RequestedFileList)
                {
                    if (MonoDevelop.Projects.Services.ProjectService.IsWorkspaceItemFile(file.FileName))
                    {
                        options.NewWindow = true;
                        break;
                    }
                }
            }

            DefaultTheme = Gtk.Settings.Default.ThemeName;
            if (!string.IsNullOrEmpty(IdeApp.Preferences.UserInterfaceTheme))
            {
                Gtk.Settings.Default.ThemeName = IdeApp.Preferences.UserInterfaceTheme;
            }

            //don't show the splash screen on the Mac, so instead we get the expected "Dock bounce" effect
            //this also enables the Mac platform service to subscribe to open document events before the GUI loop starts.
            if (Platform.IsMac)
            {
                options.NoLogo = true;
            }

            IProgressMonitor monitor;

            if (options.NoLogo)
            {
                monitor = new MonoDevelop.Core.ProgressMonitoring.ConsoleProgressMonitor();
            }
            else
            {
                monitor = SplashScreenForm.SplashScreen;
                SplashScreenForm.SplashScreen.ShowAll();
            }

            Counters.Initialization.Trace("Initializing Runtime");
            monitor.BeginTask(GettextCatalog.GetString("Starting {0}", BrandingService.ApplicationName), 3);
            monitor.Step(1);
            Runtime.Initialize(true);

            //make sure that the platform service is initialised so that the Mac platform can subscribe to open-document events
            Counters.Initialization.Trace("Initializing Platform Service");
            DesktopService.Initialize();

            monitor.Step(1);

            if (options.IpcTcp)
            {
                listen_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                ep            = new IPEndPoint(IPAddress.Loopback, ipcBasePort + HashSdbmBounded(Environment.UserName));
            }
            else
            {
                socket_filename = "/tmp/md-" + Environment.GetEnvironmentVariable("USER") + "-socket";
                listen_socket   = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
                ep = new UnixEndPoint(socket_filename);
            }

            // If not opening a combine, connect to existing monodevelop and pass filename(s) and exit
            if (!options.NewWindow && startupInfo.HasFiles)
            {
                try {
                    StringBuilder builder = new StringBuilder();
                    foreach (var file in startupInfo.RequestedFileList)
                    {
                        builder.AppendFormat("{0};{1};{2}\n", file.FileName, file.Line, file.Column);
                    }
                    listen_socket.Connect(ep);
                    listen_socket.Send(Encoding.UTF8.GetBytes(builder.ToString()));
                    return(0);
                } catch {
                    // Reset the socket
                    if (null != socket_filename && File.Exists(socket_filename))
                    {
                        File.Delete(socket_filename);
                    }
                }
            }

            Counters.Initialization.Trace("Checking System");
            string version = Assembly.GetEntryAssembly().GetName().Version.Major + "." + Assembly.GetEntryAssembly().GetName().Version.Minor;

            if (Assembly.GetEntryAssembly().GetName().Version.Build != 0)
            {
                version += "." + Assembly.GetEntryAssembly().GetName().Version.Build;
            }
            if (Assembly.GetEntryAssembly().GetName().Version.Revision != 0)
            {
                version += "." + Assembly.GetEntryAssembly().GetName().Version.Revision;
            }

            // System checks
            if (!CheckBug77135())
            {
                return(1);
            }

            if (!CheckQtCurve())
            {
                return(1);
            }

            CheckFileWatcher();

            Exception error            = null;
            int       reportedFailures = 0;

            try {
                Counters.Initialization.Trace("Loading Icons");
                //force initialisation before the workbench so that it can register stock icons for GTK before they get requested
                ImageService.Initialize();

                if (errorsList.Count > 0)
                {
                    if (monitor is SplashScreenForm)
                    {
                        SplashScreenForm.SplashScreen.Hide();
                    }
                    AddinLoadErrorDialog dlg = new AddinLoadErrorDialog((AddinError[])errorsList.ToArray(typeof(AddinError)), false);
                    if (!dlg.Run())
                    {
                        return(1);
                    }
                    if (monitor is SplashScreenForm)
                    {
                        SplashScreenForm.SplashScreen.Show();
                    }
                    reportedFailures = errorsList.Count;
                }

                // no alternative for Application.ThreadException?
                // Application.ThreadException += new ThreadExceptionEventHandler(ShowErrorBox);

                Counters.Initialization.Trace("Initializing IdeApp");
                IdeApp.Initialize(monitor);

                // Load requested files
                Counters.Initialization.Trace("Opening Files");
                IdeApp.OpenFiles(startupInfo.RequestedFileList);

                monitor.Step(1);
            } catch (Exception e) {
                error = e;
            } finally {
                monitor.Dispose();
            }

            if (error != null)
            {
                LoggingService.LogFatalError(null, error);
                MessageService.ShowException(error,
                                             GettextCatalog.GetString("MonoDevelop failed to start. The following error has been reported: ") + error.Message);
                return(1);
            }

            if (errorsList.Count > reportedFailures)
            {
                AddinLoadErrorDialog dlg = new AddinLoadErrorDialog((AddinError[])errorsList.ToArray(typeof(AddinError)), true);
                dlg.Run();
            }

            errorsList = null;

            // FIXME: we should probably track the last 'selected' one
            // and do this more cleanly
            try {
                listen_socket.Bind(ep);
                listen_socket.Listen(5);
                listen_socket.BeginAccept(new AsyncCallback(ListenCallback), listen_socket);
            } catch {
                // Socket already in use
            }

            initialized = true;
            MessageService.RootWindow = IdeApp.Workbench.RootWindow;
            Thread.CurrentThread.Name = "GUI Thread";
            Counters.Initialization.Trace("Running IdeApp");
            Counters.Initialization.EndTiming();

            AddinManager.AddExtensionNodeHandler("/MonoDevelop/Ide/InitCompleteHandlers", OnExtensionChanged);

            IdeApp.Run();

            // unloading services
            if (null != socket_filename)
            {
                File.Delete(socket_filename);
            }

            Runtime.Shutdown();
            InstrumentationService.Stop();

            return(0);
        }
Esempio n. 21
0
        int Run(MonoDevelopOptions options)
        {
            LoggingService.LogInfo("Starting {0} {1}", BrandingService.ApplicationLongName, IdeVersionInfo.MonoDevelopVersion);
            LoggingService.LogInfo("Build Information{0}{1}", Environment.NewLine, SystemInformation.GetBuildInformation());
            LoggingService.LogInfo("Running on {0}", IdeVersionInfo.GetRuntimeInfo());

            //ensure native libs initialized before we hit anything that p/invokes
            Platform.Initialize();
            GettextCatalog.Initialize();

            LoggingService.LogInfo("Operating System: {0}", SystemInformation.GetOperatingSystemDescription());

            if (!Platform.IsWindows)
            {
                // The assembly resolver for MSBuild 15 assemblies needs to be defined early on.
                // Whilst Runtime.Initialize loads the MSBuild 15 assemblies from Mono this seems
                // to be too late to prevent the MEF composition and the static registrar from
                // failing to load the MonoDevelop.Ide assembly which now uses MSBuild 15 assemblies.
                ResolveMSBuildAssemblies();
            }

            Counters.Initialization.BeginTiming();

            if (options.PerfLog)
            {
                string logFile = Path.Combine(Environment.CurrentDirectory, "monodevelop.perf-log");
                LoggingService.LogInfo("Logging instrumentation service data to file: " + logFile);
                InstrumentationService.StartAutoSave(logFile, 1000);
            }

            Counters.Initialization.Trace("Initializing GTK");
            if (Platform.IsWindows && !CheckWindowsGtk())
            {
                return(1);
            }
            SetupExceptionManager();

            // explicit GLib type system initialization for GLib < 2.36 before any other type system access
            GLib.GType.Init();

            IdeApp.Customizer = options.IdeCustomizer ?? new IdeCustomizer();
            try {
                IdeApp.Customizer.Initialize();
            } catch (UnauthorizedAccessException ua) {
                LoggingService.LogError("Unauthorized access: " + ua.Message);
                return(1);
            }

            try {
                GLibLogging.Enabled = true;
            } catch (Exception ex) {
                LoggingService.LogError("Error initialising GLib logging.", ex);
            }

            var args = options.RemainingArgs.ToArray();

            IdeTheme.InitializeGtk(BrandingService.ApplicationName, ref args);

            LoggingService.LogInfo("Using GTK+ {0}", IdeVersionInfo.GetGtkVersion());

            // XWT initialization
            FilePath p = typeof(IdeStartup).Assembly.Location;

            Runtime.LoadAssemblyFrom(p.ParentDirectory.Combine("Xwt.Gtk.dll"));
            Xwt.Application.InitializeAsGuest(Xwt.ToolkitType.Gtk);
            Xwt.Toolkit.CurrentEngine.RegisterBackend <IExtendedTitleBarWindowBackend, GtkExtendedTitleBarWindowBackend> ();
            Xwt.Toolkit.CurrentEngine.RegisterBackend <IExtendedTitleBarDialogBackend, GtkExtendedTitleBarDialogBackend> ();
            IdeTheme.SetupXwtTheme();

            //default to Windows IME on Windows
            if (Platform.IsWindows && GtkWorkarounds.GtkMinorVersion >= 16)
            {
                var settings = Gtk.Settings.Default;
                var val      = GtkWorkarounds.GetProperty(settings, "gtk-im-module");
                if (string.IsNullOrEmpty(val.Val as string))
                {
                    GtkWorkarounds.SetProperty(settings, "gtk-im-module", new GLib.Value("ime"));
                }
            }

            string   socket_filename = null;
            EndPoint ep = null;

            DispatchService.Initialize();

            // Set a synchronization context for the main gtk thread
            SynchronizationContext.SetSynchronizationContext(DispatchService.SynchronizationContext);
            Runtime.MainSynchronizationContext = SynchronizationContext.Current;

            // Initialize Roslyn's synchronization context
            RoslynServices.RoslynService.Initialize();

            AddinManager.AddinLoadError += OnAddinError;

            var startupInfo = new StartupInfo(args);

            // If a combine was specified, force --newwindow.

            if (!options.NewWindow && startupInfo.HasFiles)
            {
                Counters.Initialization.Trace("Pre-Initializing Runtime to load files in existing window");
                Runtime.Initialize(true);
                foreach (var file in startupInfo.RequestedFileList)
                {
                    if (MonoDevelop.Projects.Services.ProjectService.IsWorkspaceItemFile(file.FileName))
                    {
                        options.NewWindow = true;
                        break;
                    }
                }
            }

            Counters.Initialization.Trace("Initializing Runtime");
            Runtime.Initialize(true);

            IdeApp.Customizer.OnCoreInitialized();

            Counters.Initialization.Trace("Initializing theme");

            IdeTheme.SetupGtkTheme();

            ProgressMonitor monitor = new MonoDevelop.Core.ProgressMonitoring.ConsoleProgressMonitor();

            monitor.BeginTask(GettextCatalog.GetString("Starting {0}", BrandingService.ApplicationName), 2);

            //make sure that the platform service is initialised so that the Mac platform can subscribe to open-document events
            Counters.Initialization.Trace("Initializing Platform Service");
            DesktopService.Initialize();

            monitor.Step(1);

            if (options.IpcTcp)
            {
                listen_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                ep            = new IPEndPoint(IPAddress.Loopback, ipcBasePort + HashSdbmBounded(Environment.UserName));
            }
            else
            {
                socket_filename = "/tmp/md-" + Environment.GetEnvironmentVariable("USER") + "-socket";
                listen_socket   = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
                ep = new UnixEndPoint(socket_filename);
            }

            // If not opening a combine, connect to existing monodevelop and pass filename(s) and exit
            if (!options.NewWindow && startupInfo.HasFiles)
            {
                try {
                    StringBuilder builder = new StringBuilder();
                    foreach (var file in startupInfo.RequestedFileList)
                    {
                        builder.AppendFormat("{0};{1};{2}\n", file.FileName, file.Line, file.Column);
                    }
                    listen_socket.Connect(ep);
                    listen_socket.Send(Encoding.UTF8.GetBytes(builder.ToString()));
                    return(0);
                } catch {
                    // Reset the socket
                    if (null != socket_filename && File.Exists(socket_filename))
                    {
                        File.Delete(socket_filename);
                    }
                }
            }

            Counters.Initialization.Trace("Checking System");

            CheckFileWatcher();

            Exception error            = null;
            int       reportedFailures = 0;

            try {
                Counters.Initialization.Trace("Loading Icons");
                //force initialisation before the workbench so that it can register stock icons for GTK before they get requested
                ImageService.Initialize();
                LocalizationService.Initialize();

                // If we display an error dialog before the main workbench window on OS X then a second application menu is created
                // which is then replaced with a second empty Apple menu.
                // XBC #33699
                Counters.Initialization.Trace("Initializing IdeApp");
                IdeApp.Initialize(monitor);

                if (errorsList.Count > 0)
                {
                    using (AddinLoadErrorDialog dlg = new AddinLoadErrorDialog((AddinError[])errorsList.ToArray(typeof(AddinError)), false)) {
                        if (!dlg.Run())
                        {
                            return(1);
                        }
                    }
                    reportedFailures = errorsList.Count;
                }

                if (!CheckSCPlugin())
                {
                    return(1);
                }

                // Load requested files
                Counters.Initialization.Trace("Opening Files");

                // load previous combine
                RecentFile openedProject = null;
                if (IdeApp.Preferences.LoadPrevSolutionOnStartup && !startupInfo.HasSolutionFile && !IdeApp.Workspace.WorkspaceItemIsOpening && !IdeApp.Workspace.IsOpen)
                {
                    openedProject = DesktopService.RecentFiles.MostRecentlyUsedProject;
                    if (openedProject != null)
                    {
                        var metadata = GetOpenWorkspaceOnStartupMetadata();
                        IdeApp.Workspace.OpenWorkspaceItem(openedProject.FileName, true, true, metadata).ContinueWith(t => IdeApp.OpenFiles(startupInfo.RequestedFileList, metadata), TaskScheduler.FromCurrentSynchronizationContext());
                        startupInfo.OpenedRecentProject = true;
                    }
                }
                if (openedProject == null)
                {
                    IdeApp.OpenFiles(startupInfo.RequestedFileList, GetOpenWorkspaceOnStartupMetadata());
                    startupInfo.OpenedFiles = startupInfo.HasFiles;
                }

                monitor.Step(1);
            } catch (Exception e) {
                error = e;
            } finally {
                monitor.Dispose();
            }

            if (error != null)
            {
                string message = BrandingService.BrandApplicationName(GettextCatalog.GetString("MonoDevelop failed to start"));
                MessageService.ShowFatalError(message, null, error);
                return(1);
            }

            if (errorsList.Count > reportedFailures)
            {
                using (AddinLoadErrorDialog dlg = new AddinLoadErrorDialog((AddinError[])errorsList.ToArray(typeof(AddinError)), true))
                    dlg.Run();
            }

            errorsList = null;
            AddinManager.AddinLoadError -= OnAddinError;

            // FIXME: we should probably track the last 'selected' one
            // and do this more cleanly
            try {
                listen_socket.Bind(ep);
                listen_socket.Listen(5);
                listen_socket.BeginAccept(new AsyncCallback(ListenCallback), listen_socket);
            } catch {
                // Socket already in use
            }

            initialized = true;
            MessageService.RootWindow    = IdeApp.Workbench.RootWindow;
            Xwt.MessageDialog.RootWindow = Xwt.Toolkit.CurrentEngine.WrapWindow(IdeApp.Workbench.RootWindow);
            Thread.CurrentThread.Name    = "GUI Thread";
            Counters.Initialization.Trace("Running IdeApp");
            Counters.Initialization.EndTiming();

            AddinManager.AddExtensionNodeHandler("/MonoDevelop/Ide/InitCompleteHandlers", OnExtensionChanged);
            StartLockupTracker();

            startupTimer.Stop();

            CreateStartupMetadata(startupInfo);

            GLib.Idle.Add(OnIdle);
            IdeApp.Run();

            IdeApp.Customizer.OnIdeShutdown();

            // unloading services
            if (null != socket_filename)
            {
                File.Delete(socket_filename);
            }
            lockupCheckRunning = false;
            Runtime.Shutdown();

            IdeApp.Customizer.OnCoreShutdown();

            InstrumentationService.Stop();

            MonoDevelop.Components.GtkWorkarounds.Terminate();

            return(0);
        }
Esempio n. 22
0
 public void Dispose()
 {
     _socketFile.Dispose();
     _socketFile   = null;
     _unixEndpoint = null;
 }
        int Run(MonoDevelopOptions options)
        {
            LoggingService.LogInfo("Starting {0} {1}", BrandingService.ApplicationName, IdeVersionInfo.MonoDevelopVersion);
            LoggingService.LogInfo("Running on {0}", IdeVersionInfo.GetRuntimeInfo());

            //ensure native libs initialized before we hit anything that p/invokes
            Platform.Initialize();

            IdeApp.Customizer = options.IdeCustomizer ?? new IdeCustomizer();
            IdeApp.Customizer.Initialize();

            Counters.Initialization.BeginTiming();

            if (options.PerfLog)
            {
                string logFile = Path.Combine(Environment.CurrentDirectory, "monodevelop.perf-log");
                LoggingService.LogInfo("Logging instrumentation service data to file: " + logFile);
                InstrumentationService.StartAutoSave(logFile, 1000);
            }

            Counters.Initialization.Trace("Initializing GTK");
            if (Platform.IsWindows && !CheckWindowsGtk())
            {
                return(1);
            }
            SetupExceptionManager();

            try {
                GLibLogging.Enabled = true;
            } catch (Exception ex) {
                LoggingService.LogError("Error initialising GLib logging.", ex);
            }

            SetupTheme();

            var args = options.RemainingArgs.ToArray();

            Gtk.Application.Init(BrandingService.ApplicationName, ref args);

            LoggingService.LogInfo("Using GTK+ {0}", IdeVersionInfo.GetGtkVersion());

            // XWT initialization
            FilePath p = typeof(IdeStartup).Assembly.Location;

            Assembly.LoadFrom(p.ParentDirectory.Combine("Xwt.Gtk.dll"));
            Xwt.Application.InitializeAsGuest(Xwt.ToolkitType.Gtk);
            Xwt.Toolkit.CurrentEngine.RegisterBackend <IExtendedTitleBarWindowBackend, GtkExtendedTitleBarWindowBackend> ();
            Xwt.Toolkit.CurrentEngine.RegisterBackend <IExtendedTitleBarDialogBackend, GtkExtendedTitleBarDialogBackend> ();

            //default to Windows IME on Windows
            if (Platform.IsWindows && Mono.TextEditor.GtkWorkarounds.GtkMinorVersion >= 16)
            {
                var settings = Gtk.Settings.Default;
                var val      = Mono.TextEditor.GtkWorkarounds.GetProperty(settings, "gtk-im-module");
                if (string.IsNullOrEmpty(val.Val as string))
                {
                    Mono.TextEditor.GtkWorkarounds.SetProperty(settings, "gtk-im-module", new GLib.Value("ime"));
                }
            }

            InternalLog.Initialize();
            string   socket_filename = null;
            EndPoint ep = null;

            DispatchService.Initialize();

            // Set a synchronization context for the main gtk thread
            SynchronizationContext.SetSynchronizationContext(new GtkSynchronizationContext());
            Runtime.MainSynchronizationContext = SynchronizationContext.Current;

            AddinManager.AddinLoadError += OnAddinError;

            var startupInfo = new StartupInfo(args);

            // If a combine was specified, force --newwindow.

            if (!options.NewWindow && startupInfo.HasFiles)
            {
                Counters.Initialization.Trace("Pre-Initializing Runtime to load files in existing window");
                Runtime.Initialize(true);
                foreach (var file in startupInfo.RequestedFileList)
                {
                    if (MonoDevelop.Projects.Services.ProjectService.IsWorkspaceItemFile(file.FileName))
                    {
                        options.NewWindow = true;
                        break;
                    }
                }
            }

            Counters.Initialization.Trace("Initializing Runtime");
            Runtime.Initialize(true);

            IdeApp.Customizer.OnCoreInitialized();

            Counters.Initialization.Trace("Initializing theme");

            DefaultTheme = Gtk.Settings.Default.ThemeName;
            string theme = IdeApp.Preferences.UserInterfaceTheme;

            if (string.IsNullOrEmpty(theme))
            {
                theme = DefaultTheme;
            }
            ValidateGtkTheme(ref theme);
            if (theme != DefaultTheme)
            {
                Gtk.Settings.Default.ThemeName = theme;
            }

            IProgressMonitor monitor = new MonoDevelop.Core.ProgressMonitoring.ConsoleProgressMonitor();

            monitor.BeginTask(GettextCatalog.GetString("Starting {0}", BrandingService.ApplicationName), 2);

            //make sure that the platform service is initialised so that the Mac platform can subscribe to open-document events
            Counters.Initialization.Trace("Initializing Platform Service");
            DesktopService.Initialize();

            monitor.Step(1);

            if (options.IpcTcp)
            {
                listen_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                ep            = new IPEndPoint(IPAddress.Loopback, ipcBasePort + HashSdbmBounded(Environment.UserName));
            }
            else
            {
                socket_filename = "/tmp/md-" + Environment.GetEnvironmentVariable("USER") + "-socket";
                listen_socket   = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
                ep = new UnixEndPoint(socket_filename);
            }

            // If not opening a combine, connect to existing monodevelop and pass filename(s) and exit
            if (!options.NewWindow && startupInfo.HasFiles)
            {
                try {
                    StringBuilder builder = new StringBuilder();
                    foreach (var file in startupInfo.RequestedFileList)
                    {
                        builder.AppendFormat("{0};{1};{2}\n", file.FileName, file.Line, file.Column);
                    }
                    listen_socket.Connect(ep);
                    listen_socket.Send(Encoding.UTF8.GetBytes(builder.ToString()));
                    return(0);
                } catch {
                    // Reset the socket
                    if (null != socket_filename && File.Exists(socket_filename))
                    {
                        File.Delete(socket_filename);
                    }
                }
            }

            Counters.Initialization.Trace("Checking System");
            string version = Assembly.GetEntryAssembly().GetName().Version.Major + "." + Assembly.GetEntryAssembly().GetName().Version.Minor;

            if (Assembly.GetEntryAssembly().GetName().Version.Build != 0)
            {
                version += "." + Assembly.GetEntryAssembly().GetName().Version.Build;
            }
            if (Assembly.GetEntryAssembly().GetName().Version.Revision != 0)
            {
                version += "." + Assembly.GetEntryAssembly().GetName().Version.Revision;
            }

            CheckFileWatcher();

            Exception error            = null;
            int       reportedFailures = 0;

            try {
                Counters.Initialization.Trace("Loading Icons");
                //force initialisation before the workbench so that it can register stock icons for GTK before they get requested
                ImageService.Initialize();

                if (errorsList.Count > 0)
                {
                    AddinLoadErrorDialog dlg = new AddinLoadErrorDialog((AddinError[])errorsList.ToArray(typeof(AddinError)), false);
                    if (!dlg.Run())
                    {
                        return(1);
                    }
                    reportedFailures = errorsList.Count;
                }

                if (!CheckSCPlugin())
                {
                    return(1);
                }

                // no alternative for Application.ThreadException?
                // Application.ThreadException += new ThreadExceptionEventHandler(ShowErrorBox);

                Counters.Initialization.Trace("Initializing IdeApp");
                IdeApp.Initialize(monitor);

                // Load requested files
                Counters.Initialization.Trace("Opening Files");

                // load previous combine
                if (IdeApp.Preferences.LoadPrevSolutionOnStartup && !startupInfo.HasSolutionFile && !IdeApp.Workspace.WorkspaceItemIsOpening && !IdeApp.Workspace.IsOpen)
                {
                    var proj = DesktopService.RecentFiles.GetProjects().FirstOrDefault();
                    if (proj != null)
                    {
                        IdeApp.Workspace.OpenWorkspaceItem(proj.FileName).WaitForCompleted();
                    }
                }

                IdeApp.OpenFiles(startupInfo.RequestedFileList);

                monitor.Step(1);
            } catch (Exception e) {
                error = e;
            } finally {
                monitor.Dispose();
            }

            if (error != null)
            {
                string message = BrandingService.BrandApplicationName(GettextCatalog.GetString("MonoDevelop failed to start"));
                MessageService.ShowFatalError(message, null, error);
                return(1);
            }

            if (errorsList.Count > reportedFailures)
            {
                AddinLoadErrorDialog dlg = new AddinLoadErrorDialog((AddinError[])errorsList.ToArray(typeof(AddinError)), true);
                dlg.Run();
            }

            errorsList = null;

            // FIXME: we should probably track the last 'selected' one
            // and do this more cleanly
            try {
                listen_socket.Bind(ep);
                listen_socket.Listen(5);
                listen_socket.BeginAccept(new AsyncCallback(ListenCallback), listen_socket);
            } catch {
                // Socket already in use
            }

            initialized = true;
            MessageService.RootWindow = IdeApp.Workbench.RootWindow;
            Thread.CurrentThread.Name = "GUI Thread";
            Counters.Initialization.Trace("Running IdeApp");
            Counters.Initialization.EndTiming();

            AddinManager.AddExtensionNodeHandler("/MonoDevelop/Ide/InitCompleteHandlers", OnExtensionChanged);
            StartLockupTracker();
            IdeApp.Run();

            IdeApp.Customizer.OnIdeShutdown();

            // unloading services
            if (null != socket_filename)
            {
                File.Delete(socket_filename);
            }
            lockupCheckRunning = false;
            Runtime.Shutdown();

            IdeApp.Customizer.OnCoreShutdown();

            InstrumentationService.Stop();
            AddinManager.AddinLoadError -= OnAddinError;

            return(0);
        }
Esempio n. 24
0
        private void StartVideoPlayer()
        {
            string player;
            string exepath;
            string mpvpath;

            if (!MainClass.IsOSX)
            {
                exepath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
                mpvpath = Path.Combine(exepath, "mpv");
                player  = Path.Combine(mpvpath, @"mpv.exe");
            }
            else
            {
                exepath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                mpvpath = Path.Combine(exepath, Path.Combine("..", "..", "mpv.mac", "MacOS"));
                player  = Path.Combine(mpvpath, "mpv");
            }

            var args = "--audio-channels=6 --quiet --ontop --input-ipc-server=/tmp/mpv-socket --script=\"" + Path.Combine(exepath, "mpvslave.lua") + "\"";

            if (MainClass.Configuration.Fullscreen)
            {
                args += " --fullscreen";
            }

            if (m_state == PlayerState.Idle)
            {
                args += " --loop=inf";
            }

            args += " \"" + m_currentItem.Path + "\"";

            Console.WriteLine(player + " " + args);

            var psi = new ProcessStartInfo()
            {
                FileName               = player,
                Arguments              = args,
                UseShellExecute        = false,
                RedirectStandardInput  = true,
                RedirectStandardOutput = true,
                WorkingDirectory       = mpvpath
            };

            m_currentPlayer = Process.Start(psi);

            if (MainClass.IsOSX)
            {
                var ep   = new UnixEndPoint("/tmp/mpv-socket");
                var sock = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);

                sock.Connect(ep);

                var ns = new NetworkStream(sock);

                m_commandWriter = new StreamWriter(ns);
                m_commandReader = new StreamReader(ns);
            }
            else
            {
                var client = new NamedPipeClientStream(@"tmp\mpv-socket");
                client.Connect();
                m_commandWriter = new StreamWriter(client);
                m_commandReader = new StreamReader(client);
            }

            Task.Run(new Action(HandlePlayerExit));

            Task.Run(new Action(HandleOutput));
        }
Esempio n. 25
0
        public Session(string path)
        {
            var endPoint = new UnixEndPoint(path);

            _transport = new Transport(endPoint);
        }
Esempio n. 26
0
        public static void Main(string[] args)
        {
            var socketPath = Path.GetTempPath() + "/parkitect_nexus.socket";
            var endPoint   = new UnixEndPoint(socketPath);
            var socket     = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);

            if (!File.Exists(Path.GetTempPath() + "/parkitect_nexus.socket"))
            {
                if (!CreateSocket(socket, endPoint))
                {
                    return;
                }
            }
            else
            {
                try
                {
                    socket.Connect(endPoint);
                    using (var sr = new NetworkStream(socket))
                    {
                        using (var writer = new StreamWriter(sr))
                        {
                            writer.WriteLine(args.Length);
                            foreach (var t in args)
                            {
                                writer.WriteLine(t);
                            }
                        }
                    }
                    return;
                }
                catch
                {
                    File.Delete(Path.GetTempPath() + "/parkitect_nexus.socket");
                    if (!CreateSocket(socket, endPoint))
                    {
                        return;
                    }
                }
            }


            try
            {
                // Initialize the structure map container.
                var registry = ObjectFactory.ConfigureStructureMap();
                registry.IncludeRegistry(new PresenterRegistry());
                registry.For <IApp>().Singleton().Use <App>();
                ObjectFactory.SetUpContainer(registry);


                // Create the form and run its message loop. If arguments were specified, process them within the
                // form.
                var presenterFactory = ObjectFactory.GetInstance <IPresenterFactory>();
                App = presenterFactory.InstantiatePresenter <App>();
                if (!App.Initialize(ToolkitType.Gtk))
                {
                    return;
                }


                if (args.Any())
                {
                    ProcessArgs(args);
                }

                App.Run();
            }
            catch (Exception e)
            {
                // Report crash to the server.
                var crashReporterFactory = ObjectFactory.GetInstance <ICrashReporterFactory>();
                crashReporterFactory.Report("global", e);

                // Write the error to the log file.
                var log = ObjectFactory.GetInstance <ILogger>();
                log?.WriteLine("Application crashed!", LogLevel.Fatal);
                log?.WriteException(e);
            }
            Closed = true;
            socket.Close();
        }
Esempio n. 27
0
        /// <param name="useTCP">`true` to check a TCP port, `false` for UNIX domain socket</param>
        /// <param name="socketFile">the file name for the UNIX domain socket</param>
        /// <param name="port">the TCP port</param>
        /// <returns>true if a server instance is running</returns>
        public static bool ServerIsRunning(bool useTCP, string socketFile, ushort port)
        {
            AutocompleteRequest request = new AutocompleteRequest()
            {
                Kind = RequestKind.query
            };

            Socket socket = null;

            if (!RuntimePlatform.IsUnix)
            {
                useTCP = true;
            }

            EndPoint endpoint;

            if (useTCP)
            {
                socket   = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                endpoint = new IPEndPoint(IPAddress.Loopback, port);
            }
            else
            {
                socket   = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
                endpoint = new UnixEndPoint(socketFile);
            }

            try
            {
                socket.Connect(endpoint);

                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 5000);
                socket.Blocking = true;

                if (SendRequest(socket, request))
                {
                    AutocompleteResponse r = GetResponse(socket);
                    return(r.CompletionType == "ack");
                }
                else
                {
                    return(false);
                }
            }
            catch (SocketException ex)
            {
                if (ex.SocketErrorCode == SocketError.ConnectionRefused)
                {
                    return(false);
                }
                else
                {
                    throw ex;
                }
            }
            finally
            {
                if (socket.Connected)
                {
                    socket.Shutdown(SocketShutdown.Both);
                }

                socket.Close();
            }
        }
Esempio n. 28
0
 public StatsSender CreateUnixDomainSocketStatsSender(
     UnixEndPoint endPoint,
     TimeSpan?udsBufferFullBlockDuration)
 {
     return(StatsSender.CreateUnixDomainSocketStatsSender(endPoint, udsBufferFullBlockDuration));
 }
Esempio n. 29
0
 public UnixSocketListener(string socketFile)
 {
     _logger.Debug(string.Format("Creating UnixSocketListener with socketFile={0}", socketFile));
     _socketFile = socketFile;
     _endpoint   = new UnixEndPoint(socketFile);
 }
Esempio n. 30
0
 public ITransport CreateUnixDomainSocketTransport(
     UnixEndPoint endPoint,
     TimeSpan?udsBufferFullBlockDuration)
 {
     return(new UnixDomainSocketTransport(endPoint, udsBufferFullBlockDuration));
 }