public UnixListener (UnixEndPoint localEndPoint)
		{
			if (localEndPoint == null)
				throw new ArgumentNullException ("localendPoint");

			Init (localEndPoint);
		}
Exemple #2
0
		public UnixClient (UnixEndPoint ep) : this ()
		{
			if (ep == null)
				throw new ArgumentNullException ("ep");

			Connect (ep);
		}
Exemple #3
0
        protected UnixSocket(UnixEndPoint localEndPoint)
            : base(System.Net.Sockets.AddressFamily.Unix,
			        System.Net.Sockets.SocketType.Stream,
			        System.Net.Sockets.ProtocolType.IP,
			        localEndPoint)
        {
        }
Exemple #4
0
		protected static UnixEndPoint CreateEndPoint (string path)
		{
			if (path == null)
				throw new ArgumentNullException ("path");
			
			var ep = new UnixEndPoint (path);
			
			if (System.IO.File.Exists (path)) {
				var conn = new System.Net.Sockets.Socket (
					System.Net.Sockets.AddressFamily.Unix,
					System.Net.Sockets.SocketType.Stream,
					System.Net.Sockets.ProtocolType.IP);
				
				try {
					conn.Connect (ep);
					conn.Close ();
					throw new InvalidOperationException (
						String.Format (CultureInfo.CurrentCulture,
							Strings.UnixSocket_AlreadyExists,
							path));
				} catch (System.Net.Sockets.SocketException) {
				}
				
				System.IO.File.Delete (path);
			}
			
			return ep;
		}
Exemple #5
0
		public override EndPoint Create (SocketAddress socketAddress)
		{
			/*
			 * Should also check this
			 *
			int addr = (int) AddressFamily.Unix;
			if (socketAddress [0] != (addr & 0xFF))
				throw new ArgumentException ("socketAddress is not a unix socket address.");

			if (socketAddress [1] != ((addr & 0xFF00) >> 8))
				throw new ArgumentException ("socketAddress is not a unix socket address.");
			 */

			if (socketAddress.Size == 2) {
				// Empty filename.
				// Probably from RemoteEndPoint which on linux does not return the file name.
				UnixEndPoint uep = new UnixEndPoint ("a");
				uep.filename = "";
				return uep;
			}
			byte [] bytes = new byte [socketAddress.Size - 2 - 1];
			for (int i = 0; i < bytes.Length; i++) {
				bytes [i] = socketAddress [i + 2];
			}

			string name = Encoding.Default.GetString (bytes);
			return new UnixEndPoint (name);
		}
Exemple #6
0
		public void InitUnix ()
		{
			//TODO: /tmp/.X1-lock
			//string lockFile = "/tmp/.X" + 1 + "-lock";

			string path = "/tmp/.X11-unix/X" + 1;

			UnixFileInfo ufi = new UnixFileInfo (path);

			UnixEndPoint ep = new UnixEndPoint (path);

			listener = new Socket (AddressFamily.Unix, SocketType.Stream, 0);
			
			//Bind creates the socket file right now
			listener.Bind (ep);
			//savedEP = listener.LocalEndPoint;
			
			//listen backlog 1 for now
			listener.Listen (1);

			Socket client = listener.Accept ();

			listener.Shutdown (SocketShutdown.Both);
			listener.Close ();
			ufi.Delete ();
		}
Exemple #7
0
        protected static Mono.Unix.UnixEndPoint CreateEndPoint(string path)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            Mono.Unix.UnixEndPoint ep = new Mono.Unix.UnixEndPoint(
                path);

            if (System.IO.File.Exists(path))
            {
                System.Net.Sockets.Socket conn =
                    new System.Net.Sockets.Socket(
                        System.Net.Sockets.AddressFamily.Unix,
                        System.Net.Sockets.SocketType.Stream,
                        System.Net.Sockets.ProtocolType.IP);

                try {
                    conn.Connect(ep);
                    conn.Close();
                    throw new InvalidOperationException(
                              string.Format(CultureInfo.CurrentCulture,
                                            Strings.UnixSocket_AlreadyExists,
                                            path));
                } catch (System.Net.Sockets.SocketException) {
                }

                System.IO.File.Delete(path);
            }

            return(ep);
        }
Exemple #8
0
		public override EndPoint Create (SocketAddress socketAddress)
		{
			/*
			 * Should also check this
			 *
			int addr = (int) AddressFamily.Unix;
			if (socketAddress [0] != (addr & 0xFF))
				throw new ArgumentException ("socketAddress is not a unix socket address.");

			if (socketAddress [1] != ((addr & 0xFF00) >> 8))
				throw new ArgumentException ("socketAddress is not a unix socket address.");
			 */

			if (socketAddress.Size == 2) {
				// Empty filename.
				// Probably from RemoteEndPoint which on linux does not return the file name.
				UnixEndPoint uep = new UnixEndPoint ("a");
				uep.filename = "";
				return uep;
			}
			int size = socketAddress.Size - 2;
			byte [] bytes = new byte [size];
			for (int i = 0; i < bytes.Length; i++) {
				bytes [i] = socketAddress [i + 2];
				// There may be junk after the null terminator, so ignore it all.
				if (bytes [i] == 0) {
					size = i;
					break;
				}
			}

			string name = Encoding.Default.GetString (bytes, 0, size);
			return new UnixEndPoint (name);
		}
Exemple #9
0
 protected UnixSocket(Mono.Unix.UnixEndPoint localEndPoint)
     : base(System.Net.Sockets.AddressFamily.Unix,
            System.Net.Sockets.SocketType.Stream,
            System.Net.Sockets.ProtocolType.IP,
            localEndPoint)
 {
     //base.Bind (localEndPoint);
 }
        public Socket OpenUnix(string path)
        {
            UnixEndPoint remoteEndPoint = new UnixEndPoint (path);

            Socket client = new Socket (AddressFamily.Unix, SocketType.Stream, 0);
            client.Connect (remoteEndPoint);

            return client;
        }
		public virtual bool GracefulShutdown ()
		{
			EndPoint ep = new UnixEndPoint (filename);
			Socket sock = new Socket (AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
			try {
				sock.Connect (ep);
			} catch (Exception e) {
				Console.Error.WriteLine ("Cannot connect to {0}: {1}", filename, e.Message);
				return false;
			}

			return SendShutdownCommandAndClose (sock);
		}
Exemple #12
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");
            }
        }
Exemple #13
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");
        }
		void Init (UnixEndPoint ep)
		{
			listening = false;
			string filename = ep.Filename;
			if (File.Exists (filename)) {
				Socket conn = new Socket (AddressFamily.Unix, SocketType.Stream, 0);
				try {
					conn.Connect (ep);
					conn.Close ();
					throw new InvalidOperationException ("There's already a server listening on " + filename);
				} catch (SocketException se) {
				}
				File.Delete (filename);
			}

			server = new Socket (AddressFamily.Unix, SocketType.Stream, 0);
			server.Bind (ep);
			savedEP = server.LocalEndPoint;
		}
        void Init(UnixEndPoint ep)
        {
            listening = false;
            string filename = ep.Filename;

            if (File.Exists(filename))
            {
                Socket conn = new Socket(AddressFamily.Unix, SocketType.Stream, 0);
                try {
                    conn.Connect(ep);
                    conn.Close();
                    throw new InvalidOperationException("There's already a server listening on " + filename);
                } catch (SocketException) {
                }
                File.Delete(filename);
            }

            server = new Socket(AddressFamily.Unix, SocketType.Stream, 0);
            server.Bind(ep);
            savedEP = server.LocalEndPoint;
        }
        public override EndPoint Create(SocketAddress socketAddress)
        {
            /*
             * Should also check this
             *
             * int addr = (int) AddressFamily.Unix;
             * if (socketAddress [0] != (addr & 0xFF))
             *  throw new ArgumentException ("socketAddress is not a unix socket address.");
             *
             * if (socketAddress [1] != ((addr & 0xFF00) >> 8))
             *  throw new ArgumentException ("socketAddress is not a unix socket address.");
             */

            if (socketAddress.Size == 2)
            {
                // Empty filename.
                // Probably from RemoteEndPoint which on linux does not return the file name.
                UnixEndPoint uep = new UnixEndPoint("a");
                uep.filename = string.Empty;
                return(uep);
            }

            int size = socketAddress.Size - 2;

            byte[] bytes = new byte[size];
            for (int i = 0; i < bytes.Length; i++)
            {
                bytes[i] = socketAddress[i + 2];
                // There may be junk after the null terminator, so ignore it all.
                if (bytes[i] == 0)
                {
                    size = i;
                    break;
                }
            }

            string name = Encoding.UTF8.GetString(bytes, 0, size);

            return(new UnixEndPoint(name));
        }
Exemple #17
0
        public static void Main(string[] args)
        {
            if (args.Length != 2) {
                Console.WriteLine("Please provide a name for this daemon and a path to dll files to load. Aborting.");
                return;
            }

            string tName = args[0];
            string tDllPath = args[1];

            Console.WriteLine("Starting up MonoDaemon...");

            foreach (string tPath in Directory.GetFiles(tDllPath, "*.dll")) {
                Assembly.LoadFile(tPath);
                Console.WriteLine("Loaded assembly " + tPath);
            }

            Mono.Unix.Native.Syscall.unlink(tName);

            UnixEndPoint tEndpoint = new UnixEndPoint(tName);

            Socket tSocket = new Socket(tEndpoint.AddressFamily, SocketType.Stream, 0);

            Console.CancelKeyPress += (sender, e) => {
                if (tSocket.Connected) {
                    tSocket.Close();
                }
            };

            tSocket.Bind(tEndpoint);
            tSocket.Listen(255);
            while (true) {
                Socket tConnection = tSocket.Accept();
                Console.WriteLine("Got request.");
                Thread tThread = new Thread(handleRequest);
                tThread.Start(tConnection);
            }
        }
        private void Init(UnixEndPoint ep)
        {
            this.listening = false;
            string filename = ep.Filename;

            if (File.Exists(filename))
            {
                Socket socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
                try
                {
                    socket.Connect(ep);
                    socket.Close();
                    throw new InvalidOperationException(string.Concat("There's already a server listening on ", filename));
                }
                catch (SocketException socketException)
                {
                }
                File.Delete(filename);
            }
            this.server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
            this.server.Bind(ep);
            this.savedEP = this.server.LocalEndPoint;
        }
        public override void Open(AddressEntry entry)
        {
            string path;
            bool isAbstract;

            if (entry.Properties.TryGetValue("path", out path))
                isAbstract = false;
            else if (entry.Properties.TryGetValue("abstract", out path))
                isAbstract = true;
            else
                throw new ArgumentException("No path specified for UNIX transport");

            EndPoint ep;

            if (isAbstract)
                ep = new AbstractUnixEndPoint(path);
            else
                ep = new UnixEndPoint(path);

            var client = new Socket(AddressFamily.Unix, SocketType.Stream, 0);
            client.Connect(ep);
            Stream = new NetworkStream(client);
        }
        public static bool CreateSocket(Socket s, UnixEndPoint end)
        {
            //listen for a connection and then rebind the accept
            var listeningThread = new Thread(delegate()
            {
                s.Bind(end);
                s.Listen(10);

                while (s.IsBound)
                {
                    AllDone.Reset();
                    if (Closed)
                        break;
                    //bind accept and listen for arguments
                    s.BeginAccept(OnAccept, s);
                    //end the thread when nothing is connected

                    AllDone.WaitOne();
                }
            });
            listeningThread.Start();

            return true;
        }
Exemple #21
0
 public UnixClient(UnixEndPoint ep) : this()
 {
     Connect(ep);
 }
Exemple #22
0
		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 ();

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

			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) {
					using (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) {
				using (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;
		}
Exemple #23
0
		public void Connect (UnixEndPoint remoteEndPoint)
		{
			CheckDisposed ();
			client.Connect (remoteEndPoint);
			stream = new NetworkStream (client, true);
		}
Exemple #24
0
        public override Socket CreateSocket()
        {
            if (filename == null)
                throw new InvalidOperationException ("filename not set");

            EndPoint ep = new UnixEndPoint (filename);
            if (File.Exists (filename)) {
                Socket conn = new Socket (AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
                try {
                    conn.Connect (ep);
                    conn.Close ();
                    throw new InvalidOperationException ("There's already a server listening on " + filename);
                } catch (SocketException) {
                }
                File.Delete (filename);
            }

            Socket listen_socket = new Socket (AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
            listen_socket.Bind (ep);
            file_bound = true;
            return listen_socket;
        }
		public int Run (string[] args)
		{
			Counters.Initialization.BeginTiming ();
			
			var options = new MonoDevelopOptions ();
			var optionsSet = new Mono.Options.OptionSet () {
				{ "nologo", "Do not display splash screen.", s => options.NoLogo = true },
				{ "ipc-tcp", "Use the Tcp channel for inter-process comunication.", s => options.IpcTcp = true },
				{ "newwindow", "Do not open in an existing instance of MonoDevelop", s => options.NewWindow = true },
				{ "h|?|help", "Show help", s => options.ShowHelp = true },
				{ "clog", "Log internal counter data", s => options.LogCounters = true },
				{ "clog-interval=", "Interval between counter logs (in miliseconds)", s => options.LogCountersInterval = int.Parse (s) },
			};
			var remainingArgs = optionsSet.Parse (args);
			if (options.ShowHelp) {
				Console.WriteLine ("MonoDevelop IDE " + MonoDevelop.Ide.BuildVariables.PackageVersionLabel);
				Console.WriteLine ("Options:");
				optionsSet.WriteOptionDescriptions (Console.Out);
				return 0;
			}
			
			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
			Gtk.Application.Init ("monodevelop", ref args);
			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 (remainingArgs);
			
			// 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 (PropertyService.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 MonoDevelop"), 2);
			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);
			monitor.EndTask ();
			
			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) {
				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 ();
			
			System.Environment.Exit (0);
			return 0;
		}
Exemple #26
0
        public WvUnix(string path) : base(null)
	{
	    EndPoint ep;
	    
	    if (path.StartsWith("@"))
		ep = new AbstractUnixEndPoint(path.Substring(1));
	    else
		ep = new UnixEndPoint(path);
	    
	    Socket sock = new Socket(AddressFamily.Unix,
				     SocketType.Stream, 0);
	    sock.Connect(ep);
	    this.sock = sock;
	}
Exemple #27
0
 public UnixListener(UnixEndPoint localEndPoint)
 {
     Init(localEndPoint, out server, out savedEP);
 }
Exemple #28
0
		int Run (MonoDevelopOptions options)
		{
			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");
			SetupExceptionManager ();
			
			try {
				MonoDevelop.Ide.Gui.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);

			FilePath p = typeof(IdeStartup).Assembly.Location;
			Assembly.LoadFrom (p.ParentDirectory.Combine ("Xwt.Gtk.dll"));
			Xwt.Application.Initialize (Xwt.ToolkitType.Gtk);
			Xwt.Engine.Toolkit.ExitUserCode (null);

			//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;
					}
				}
			}
			
			Counters.Initialization.Trace ("Initializing Runtime");
			Runtime.Initialize (true);

			Counters.Initialization.Trace ("Initializing theme and splash window");

			DefaultTheme = Gtk.Settings.Default.ThemeName;
			if (!string.IsNullOrEmpty (IdeApp.Preferences.UserInterfaceTheme)) {
				string theme;
				if (!ValidateGtkTheme (IdeApp.Preferences.UserInterfaceTheme, out theme))
					return 1;
				Gtk.Settings.Default.ThemeName = theme;
			}
			
			//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.NoSplash = true;
			
			IProgressMonitor monitor;
			
			if (options.NoSplash) {
				monitor = new MonoDevelop.Core.ProgressMonitoring.ConsoleProgressMonitor ();
			} else {
				monitor = SplashScreenForm.SplashScreen;
				SplashScreenForm.SplashScreen.ShowAll ();
			}
			
			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;
			
			// System checks
			if (!CheckBug77135 ())
				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,
				                              BrandingService.BrandApplicationName (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;
		}
Exemple #29
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;
		}
Exemple #30
0
 public void Connect(UnixEndPoint remoteEndPoint)
 {
     CheckDisposed();
     client.Connect(remoteEndPoint);
     stream = new NetworkStream(client, true);
 }
Exemple #31
0
 public UnixSocketListener(string socketFile)
 {
     _logger.Debug(string.Format("Creating UnixSocketListener with socketFile={0}", socketFile));
     _socketFile = socketFile;
     _endpoint = new UnixEndPoint(socketFile);
 }
        public UnixSocketConnection(string socketFile)
        {
            if(socketFile == null)
                throw new ArgumentException("No socket file specified");

            _logger.Debug(string.Format("Creating UnixSocketConnection with socketFile={0}", socketFile));
            _socketFile = socketFile;
            _endpoint = new UnixEndPoint(socketFile);
        }
        protected override void Transfer()
        {
            try {
                Socket = new Socket (AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
                EndPoint ep = new UnixEndPoint (Address);
                Socket.Connect (ep);

                Console.WriteLine ("Sending file");
                SendFile ();
            }
            catch (Exception e) {
                Console.WriteLine (e.ToString ());
                Close ();
            }
        }
        public void Initialize()
        {
            try
            {
            #if UNIX
                EndPoint endPoint = new UnixEndPoint(this._fileName);

                if (File.Exists(this._fileName))
                {
                    File.Delete(this._fileName);
                }

                Debug.WriteLine(this + " listen on " + this._fileName);
                Socket socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
                socket.Bind(endPoint);
                socket.Listen(5);

                // add "socket" to this._listeners to manage it by SocketManager
                this._listeners.Add(socket);
                this._socketManager.UpdateListener(this); // important to register the new socket in SocketManager
            #endif
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
        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();
        }
 public void Connect(UnixEndPoint remoteEndPoint)
 {
     this.CheckDisposed();
     this.client.Connect(remoteEndPoint);
     this.stream = new NetworkStream(this.client, true);
 }