Esempio n. 1
0
        public XSPWorker(Socket client, EndPoint localEP, ApplicationServer server,
			bool secureConnection,
			Mono.Security.Protocol.Tls.SecurityProtocolType SecurityProtocol,
			X509Certificate cert,
			PrivateKeySelectionCallback keyCB,
			bool allowClientCert,
			bool requireClientCert)
        {
            if (secureConnection) {
                ssl = new SslInformation ();
                ssl.AllowClientCertificate = allowClientCert;
                ssl.RequireClientCertificate = requireClientCert;
                ssl.RawServerCertificate = cert.GetRawCertData ();

                netStream = new LingeringNetworkStream (client, true);
                SslServerStream s = new SslServerStream (netStream, cert, requireClientCert, false);
                s.PrivateKeyCertSelectionDelegate += keyCB;
                s.ClientCertValidationDelegate += new CertificateValidationCallback (ClientCertificateValidation);
                stream = s;
            } else {
                netStream = new LingeringNetworkStream (client, false);
                stream = netStream;
            }

            sock = client;
            this.server = server;
            this.remoteEP = (IPEndPoint) client.RemoteEndPoint;
            this.localEP = (IPEndPoint) localEP;
        }
Esempio n. 2
0
        public XSPWorker(Socket client, EndPoint localEP, ApplicationServer server,
                         bool secureConnection,
                         Mono.Security.Protocol.Tls.SecurityProtocolType SecurityProtocol,
                         X509Certificate cert,
                         PrivateKeySelectionCallback keyCB,
                         bool allowClientCert,
                         bool requireClientCert)
        {
            if (secureConnection)
            {
                ssl = new SslInformations();
                ssl.AllowClientCertificate   = allowClientCert;
                ssl.RequireClientCertificate = requireClientCert;
                ssl.RawServerCertificate     = cert.GetRawCertData();

                netStream = new LingeringNetworkStream(client, true);
                SslServerStream s = new SslServerStream(netStream, cert, requireClientCert, false);
                s.PrivateKeyCertSelectionDelegate += keyCB;
                s.ClientCertValidationDelegate    += new CertificateValidationCallback(ClientCertificateValidation);
                stream = s;
            }
            else
            {
                netStream = new LingeringNetworkStream(client, false);
                stream    = netStream;
            }

            sock          = client;
            this.server   = server;
            this.remoteEP = (IPEndPoint)client.RemoteEndPoint;
            this.localEP  = (IPEndPoint)localEP;
        }
Esempio n. 3
0
File: test.cs Progetto: mono/gert
	static void Main ()
	{
		XSPWebSource websource = new XSPWebSource (IPAddress.Any, 12344);
		ApplicationServer AppServer = new ApplicationServer (websource);
		AppServer.Start (true);
		Thread.Sleep (1000);
		AppServer.Stop ();
	}
Esempio n. 4
0
        public override Worker CreateWorker(Socket client, ApplicationServer server)
        {
#if MONO
            return(new XSPWorker(client, client.LocalEndPoint, server,
                                 secureConnection, SecurityProtocol, cert, keyCB, allowClientCert, requireClientCert));
#else
            return(new XSPWorker(client, client.LocalEndPoint, server));
#endif
        }
Esempio n. 5
0
 public void Start()
 {
     Environment.CurrentDirectory = this.RootDirectory;
     this.websource = new XSPWebSource(IPAddress.Any, this.Port);
     this.WebAppServer = new ApplicationServer(this.websource);
     this.WebAppServer.AddApplication(this.App, this.Port, this.Path, Directory.GetCurrentDirectory());
     this.WebAppServer.Verbose = this.Verbose;
     this.WebAppServer.Start(false);
 }
Esempio n. 6
0
 public XSPWorker(Socket client, EndPoint localEP, ApplicationServer server)
 {
     netStream     = new LingeringNetworkStream(client, false);
     stream        = netStream;
     sock          = client;
     this.server   = server;
     this.remoteEP = (IPEndPoint)client.RemoteEndPoint;
     this.localEP  = (IPEndPoint)localEP;
 }
Esempio n. 7
0
        public static void Start()
        {
            string agentBaseDir = AppDomain.CurrentDomain.BaseDirectory;

            string fullPath = PrepareWebRootPath(agentBaseDir);

            //"[[hostname:]port:]VPath:realpath"
            string cmdLine = Port + ":/:" + fullPath;

            WebSource websource = new XSPWebSource(IPAddress.Any, Port);
            webserver = new ApplicationServer(websource);

            webserver.AddApplicationsFromCommandLine(cmdLine);
            webserver.Start(true);
        }
Esempio n. 8
0
        public int Run()
        {
            port = Int32.Parse(System.Environment.GetEnvironmentVariable("PORT"));
              ipcport= Int32.Parse(System.Environment.GetEnvironmentVariable("IPCPORT"));
              dir = System.Environment.GetEnvironmentVariable("ROOT");
              CopyBinariesToBin();
              var webSource = new XSPWebSource(IPAddress.Parse("0.0.0.0"), port, false);

              var server = new ApplicationServer(webSource, dir);
              server.SingleApplication = true;
              server.AddApplicationsFromCommandLine("/:.");
              var vh = server.GetSingleApp();
              vh.CreateHost(server, webSource);
              server.AppHost = vh.AppHost;
              if (server.Start(true, null, 500) == false)
              return 2;

              var listener = (TestListener) vh.AppHost.Domain.CreateInstanceFromAndUnwrap(
              GetType().Assembly.Location, typeof (TestListener).FullName);
              listener.Start(ipcport);

              bool doSleep;
              while (true)
              {
              doSleep = false;
              try
              {
                  Console.ReadLine();
                  break;
              }
              catch (IOException)
              {
                  // This might happen on appdomain unload
                  // until the previous threads are terminated.
                  doSleep = true;
              }
              catch (ThreadAbortException)
              {
                  doSleep = true;
              }
              if (doSleep)
              {
                  Thread.Sleep(500);
              }
              }
              server.Stop();
              return 1337;
        }
Esempio n. 9
0
        public void CreateHost(ApplicationServer server, WebSource webSource)
        {
            string v = vpath;

            if (v != "/" && v.EndsWith("/"))
            {
                v = v.Substring(0, v.Length - 1);
            }

            AppHost        = ApplicationHost.CreateApplicationHost(webSource.GetApplicationHostType(), v, realPath) as IApplicationHost;
            AppHost.Server = server;

            // Link the host in the application domain with a request broker in the main domain
            RequestBroker         = webSource.CreateRequestBroker();
            AppHost.RequestBroker = RequestBroker;
        }
Esempio n. 10
0
        public void CreateHost(ApplicationServer server, WebSource webSource)
        {
            string v = vpath;
            if (v != "/" && v.EndsWith ("/")) {
                v = v.Substring (0, v.Length - 1);
            }

            AppHost = ApplicationHost.CreateApplicationHost (webSource.GetApplicationHostType(), v, realPath) as IApplicationHost;
            AppHost.Server = server;

            if (!server.SingleApplication) {
                // Link the host in the application domain with a request broker in the main domain
                RequestBroker = webSource.CreateRequestBroker ();
                AppHost.RequestBroker = RequestBroker;
            }
        }
Esempio n. 11
0
		public Webserver (int port = 80)
		{
			// I know, i know... bad style but I couldn't find a successor of the class.
			// This post in the mono mailing list stated that the class would be removed in 2010, now its 2014.
			// http://permalink.gmane.org/gmane.comp.gnome.mono.patches/172698
			// There's life in the old dog yet.
			#pragma warning disable 0618
			webSource = new XSPWebSource (IPAddress.Any, port);
			WebAppServer = new ApplicationServer (webSource);
			#pragma warning restore 0618

			string commandLine = string.Format ("{0}:/:{1}"
			                                   , port
			                                   , Path.GetDirectoryName (Assembly.GetExecutingAssembly ().Location));

			WebAppServer.AddApplicationsFromCommandLine (commandLine);
		}
Esempio n. 12
0
        public void CreateHost(ApplicationServer server, WebSource webSource)
        {
            string v = vpath;

            if (v != "/" && v.EndsWith("/"))
            {
                v = v.Substring(0, v.Length - 1);
            }

            var domain      = AppDomain.CurrentDomain;
            var debugDomain = domain.GetData("DebugDomain") as DebugDomain;
            var listAsm     = domain.GetAssemblies();
            // { Mono.WebServer, Version = 4.4.0.0, Culture = neutral, PublicKeyToken = 0738eb9f132ed756}
            // { Mono.WebServer.XSP, Version = 4.9.0.0, Culture = neutral, PublicKeyToken = 0738eb9f132ed756}

            Exception error = null;

            try
            {
                var hostType = webSource.GetApplicationHostType();
                AppHost =
                    Mono.Web.Hosting.
                    ApplicationHost.CreateApplicationHost(hostType, v, realPath) as IApplicationHost;
                AppHost.Server = server;
            } catch (Exception err) { error = err.InnerException ?? err; }

            if (AppHost == null && error != null)
            {
                Console.WriteLine(error.Message);
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                Console.ReadKey();
                // throw error;
            }

            if (!server.SingleApplication)
            {
                // Link the host in the application domain with a request broker in the main domain
                RequestBroker         = webSource.CreateRequestBroker();
                AppHost.RequestBroker = RequestBroker;
            }
        }
Esempio n. 13
0
        protected override void OnStart()
        {
            this.bus = Bus.Open("tcp:host=localhost,port=12345");
            //var bus = Bus.Open("win:path=dbus-session");
            var path = new ObjectPath("/org/mathias/xspservice");

            IXspService service;

            if (bus.RequestName(BusName) == RequestNameReply.PrimaryOwner)
            {
                this.port = 1254;
                this.websource = new XSPWebSource(IPAddress.Any, this.port);
                this.webAppServer = new ApplicationServer(this.websource);
                //this.webAppServer.AddApplicationsFromCommandLine(string.Format("localhost:{0}:{1}:{2}", port, "/", "Bundles/WebAspBundle"));
                this.webAppServer.Start(true);
                //create a new instance of the object to be exported
                bus.Register(path, this);

                //this.webAppServer.Start(true);
                this.listen = true;
                ThreadPool.QueueUserWorkItem((o) =>
                {
                    //run the main loop
                    while (true)
                    {
                        mutex.WaitOne();
                        try
                        {
                            if (!this.listen)
                                break;
                            bus.Iterate();
                        }
                        finally
                        {
                            mutex.ReleaseMutex();
                        }
                    }
                }, null);
            }
        }
Esempio n. 14
0
        public static void Start()
        {
            XSPWebSource websource=new XSPWebSource(IPAddress.Loopback,0);
            WebAppServer=new ApplicationServer(websource);

            string basePath = Directory.GetParent(Assembly.GetExecutingAssembly().Location).ToString();
            string serverPath = basePath;
            if(serverPath[serverPath.Length - 1] != System.IO.Path.DirectorySeparatorChar)
                serverPath += System.IO.Path.DirectorySeparatorChar;
            serverPath += "WebUI";
            string serverBinPath = serverPath + System.IO.Path.DirectorySeparatorChar + "bin" + System.IO.Path.DirectorySeparatorChar;
            WebAppServer.AddApplication("",-1,"/", serverPath);

            bool started = false;

            DateTime curr = DateTime.Now;
            while(!started && curr.AddMinutes(1) > DateTime.Now)
            {
                try
                {
                    WebAppServer.Start(true);
                    started = true;
                }
                catch (System.Net.Sockets.SocketException e)
                {
                    if(e.ErrorCode == 10049 || e.ErrorCode == 10022)
                    {
                        //strange error on bind, probably network still not started
                        //try to rerun server
                        System.Threading.Thread.Sleep(10000);
                        //WebAppServer.Start(true);
                    }
                    else
                        throw;
                }
            }

            if(!started)
                WebAppServer.Start(true);

            //copy Mono.WebServer2.dll
            /*try
            {
                if (!Directory.Exists(serverBinPath))
                    Directory.CreateDirectory(serverBinPath);

                File.Copy(basePath + System.IO.Path.DirectorySeparatorChar+"Mono.WebServer2.dll", serverBinPath + "Mono.WebServer2.dll", true);
            }

            catch { ;}
            */

            AppDomain ap = WebAppServer.GetApplicationForPath("", WebAppServer.Port, "/", false).AppHost.Domain;
            ap.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
            ap.UnhandledException += OnUnhandledExceptionEvent;

            ap.SetData("WebUIGate", webServerGate);

            port = WebAppServer.Port;
            //uri = new Uri("http://127.0.0.1:" + port.ToString() + "/");
            uri = new Uri("http://localhost:" + port.ToString() + "/");
            Console.WriteLine("Webserver started at " + uri.ToString());
        }
Esempio n. 15
0
 public override Worker CreateWorker(Socket client, ApplicationServer server)
 {
     return new XSPWorker (client, client.LocalEndPoint, server,
         secureConnection, SecurityProtocol, cert, keyCB, allowClientCert, requireClientCert);
 }
Esempio n. 16
0
 public override Worker CreateWorker(Socket client, ApplicationServer server)
 {
     return new ModMonoWorker (client, server);
 }
Esempio n. 17
0
		public static int Main (string [] args)
		{
			SecurityConfiguration security = new SecurityConfiguration ();
			bool nonstop = false;
			bool verbose = false;
			Trace.Listeners.Add (new TextWriterTraceListener (Console.Out));
			string apps = AppSettings ["MonoApplications"];
			string appConfigDir = AppSettings ["MonoApplicationsConfigDir"];
			string appConfigFile = AppSettings ["MonoApplicationsConfigFile"];
			string rootDir = AppSettings ["MonoServerRootDir"];
			object oport;
			string ip = AppSettings ["MonoServerAddress"];
			bool master = false;
#if MODMONO_SERVER
			string filename = AppSettings ["MonoUnixSocket"];
#endif
			if (ip == "" || ip == null)
				ip = "0.0.0.0";

			oport = AppSettings ["MonoServerPort"];
			if (oport == null)
				oport = 8080;

			Options options = 0;
			int hash = 0;
			for (int i = 0; i < args.Length; i++){
				string a = args [i];
				int idx = (i + 1 < args.Length) ? i + 1 : i;
				hash ^= args [idx].GetHashCode () + i;
				
				switch (a){
#if MODMONO_SERVER
				case "--filename":
					CheckAndSetOptions (a, Options.FileName, ref options);
					filename = args [++i];
					break;
				case "--terminate":
					CheckAndSetOptions (a, Options.Terminate, ref options);
					break;
				case "--master":
					CheckAndSetOptions (a, Options.Master, ref options);
					master = true;
					break;
#else
				case "--https":
					CheckAndSetOptions (a, Options.Https, ref options);
					security.Enabled = true;
					break;
				case "--https-client-accept":
					CheckAndSetOptions (a, Options.Https, ref options);
					security.Enabled = true;
					security.AcceptClientCertificates = true;
					security.RequireClientCertificates = false;
					break;
				case "--https-client-require":
					CheckAndSetOptions (a, Options.Https, ref options);
					security.Enabled = true;
					security.AcceptClientCertificates = true;
					security.RequireClientCertificates = true;
					break;
				case "--p12file":
					security.Pkcs12File = args [++i];
					break;
				case "--cert":
					security.CertificateFile = args [++i];
					break;
				case "--pkfile":
					security.PvkFile = args [++i];
					break;
				case "--pkpwd":
					security.Password = args [++i];
					break;
				case "--protocols":
					security.SetProtocol (args [++i]);
					break;
#endif
				case "--port":
					CheckAndSetOptions (a, Options.Port, ref options);
					oport = args [++i];
					break;
				case "--address":
					CheckAndSetOptions (a, Options.Address, ref options);
					ip = args [++i];
					break;
				case "--root":
					CheckAndSetOptions (a, Options.Root, ref options);
					rootDir = args [++i];
					break;
				case "--applications":
					CheckAndSetOptions (a, Options.Applications, ref options);
					apps = args [++i];
					break;
				case "--appconfigfile":
					CheckAndSetOptions (a, Options.AppConfigFile, ref options);
					appConfigFile = args [++i];
					break;
				case "--appconfigdir":
					CheckAndSetOptions (a, Options.AppConfigDir, ref options);
					appConfigDir = args [++i];
					break;
				case "--nonstop":
					nonstop = true;
					break;
				case "--help":
					ShowHelp ();
					return 0;
				case "--version":
					ShowVersion ();
					return 0;
				case "--verbose":
					verbose = true;
					break;
				default:
					Console.WriteLine ("Unknown argument: {0}", a);
					ShowHelp ();
					return 1;
				}
			}

#if MODMONO_SERVER
			if (hash < 0)
				hash = -hash;

			string lockfile;
			bool useTCP = ((options & Options.Port) != 0);
			if (!useTCP) {
				if (filename == null || filename == "")
					filename = "/tmp/mod_mono_server";

				if ((options & Options.Address) != 0) {
					ShowHelp ();
					Console.WriteLine ();
					Console.WriteLine ("ERROR: --address without --port");
					Environment.Exit (1);
				} lockfile = Path.Combine (Path.GetTempPath (), Path.GetFileName (filename));
				lockfile = String.Format ("{0}_{1}", lockfile, hash);
			} else {
				lockfile = Path.Combine (Path.GetTempPath (), "mod_mono_TCP_");
				lockfile = String.Format ("{0}_{1}", lockfile, hash);
			}
#endif
			IPAddress ipaddr = null;
			ushort port;
			try {
				port = Convert.ToUInt16 (oport);
			} catch (Exception) {
				Console.WriteLine ("The value given for the listen port is not valid: " + oport);
				return 1;
			}

			try {
				ipaddr = IPAddress.Parse (ip);
			} catch (Exception) {
				Console.WriteLine ("The value given for the address is not valid: " + ip);
				return 1;
			}

			if (rootDir != null && rootDir != "") {
				try {
					Environment.CurrentDirectory = rootDir;
				} catch (Exception e) {
					Console.WriteLine ("Error: {0}", e.Message);
					return 1;
				}
			}

			rootDir = Directory.GetCurrentDirectory ();
			
			WebSource webSource;
#if MODMONO_SERVER
			if (useTCP) {
				webSource = new ModMonoTCPWebSource (ipaddr, port, lockfile);
			} else {
				webSource = new ModMonoWebSource (filename, lockfile);
			}

			if ((options & Options.Terminate) != 0) {
				if (verbose)
					Console.WriteLine ("Shutting down running mod-mono-server...");
				
				bool res = ((ModMonoWebSource) webSource).GracefulShutdown ();
				if (verbose)
					Console.WriteLine (res ? "Done." : "Failed");

				return (res) ? 0 : 1;
			}

			ApplicationServer server = new ApplicationServer (webSource);
#else
			if (security.Enabled) {
				try {
					key = security.KeyPair;
					webSource = new XSPWebSource (ipaddr, port, security.Protocol, security.ServerCertificate, 
						new PrivateKeySelectionCallback (GetPrivateKey), 
						security.AcceptClientCertificates, security.RequireClientCertificates);
				}
				catch (CryptographicException ce) {
					Console.WriteLine (ce.Message);
					return 1;
				}
			} else {
				webSource = new XSPWebSource (ipaddr, port);
			}

			ApplicationServer server = new ApplicationServer (webSource);
#endif
			server.Verbose = verbose;

			Console.WriteLine (Assembly.GetExecutingAssembly ().GetName ().Name);
			if (apps != null)
				server.AddApplicationsFromCommandLine (apps);

			if (appConfigFile != null)
				server.AddApplicationsFromConfigFile (appConfigFile);

			if (appConfigDir != null)
				server.AddApplicationsFromConfigDirectory (appConfigDir);

			if (!master && apps == null && appConfigDir == null && appConfigFile == null)
				server.AddApplicationsFromCommandLine ("/:.");
#if MODMONO_SERVER
			if (!useTCP) {
				Console.WriteLine ("Listening on: {0}", filename);
			} else
#endif
			{
				Console.WriteLine ("Listening on port: {0} {1}", port, security);
				Console.WriteLine ("Listening on address: {0}", ip);
			}
			
			Console.WriteLine ("Root directory: {0}", rootDir);

			try {
				if (server.Start (!nonstop) == false)
					return 2;

				if (!nonstop) {
					Console.WriteLine ("Hit Return to stop the server.");
					Console.ReadLine ();
					server.Stop ();
				}
			} catch (Exception e) {
				Console.WriteLine ("Error: {0}", e.Message);
				return 1;
			}

			return 0;
		}
Esempio n. 18
0
 public override Worker CreateWorker(Socket client, ApplicationServer server)
 {
     return(new XSPWorker(client, client.LocalEndPoint, server,
                          cert, allowClientCert, requireClientCert));
 }
Esempio n. 19
0
		public abstract Worker CreateWorker (Socket client, ApplicationServer server);
Esempio n. 20
0
        //
        // Parameters:
        //
        //   args - original args passed to the program
        //   root - true means caller is in the root domain
        //   ext_apphost - used when single app mode is used, in a recursive call to
        //        RealMain from the single app domain
        //   quiet - don't show messages. Used to avoid double printing of the banner
        //
        public int RealMain(string [] args, bool root, IApplicationHost ext_apphost, bool quiet)
        {
            SecurityConfiguration security = new SecurityConfiguration ();
            ApplicationSettings settings = new ApplicationSettings ();

            if (settings.IP == null || settings.IP.Length == 0)
                settings.IP = "0.0.0.0";

            if (settings.Oport == null)
                settings.Oport = 8080;

            Options options = 0;
            int hash = 0;
            for (int i = 0; i < args.Length; i++){
                string a = args [i];
                int idx = (i + 1 < args.Length) ? i + 1 : i;
                hash ^= args [idx].GetHashCode () + i;

                switch (a){
                case "--https":
                    CheckAndSetOptions (a, Options.Https, ref options);
                    security.Enabled = true;
                    break;
                case "--https-client-accept":
                    CheckAndSetOptions (a, Options.Https, ref options);
                    security.Enabled = true;
                    security.AcceptClientCertificates = true;
                    security.RequireClientCertificates = false;
                    break;
                case "--https-client-require":
                    CheckAndSetOptions (a, Options.Https, ref options);
                    security.Enabled = true;
                    security.AcceptClientCertificates = true;
                    security.RequireClientCertificates = true;
                    break;
                case "--p12file":
                    security.Pkcs12File = args [++i];
                    break;
                case "--cert":
                    security.CertificateFile = args [++i];
                    break;
                case "--pkfile":
                    security.PvkFile = args [++i];
                    break;
                case "--pkpwd":
                    security.Password = args [++i];
                    break;
                case "--protocols":
                    security.SetProtocol (args [++i]);
                    break;
                case "--port":
                    CheckAndSetOptions (a, Options.Port, ref options);
                    settings.Oport = args [++i];
                    break;
                case "--random-port":
                    CheckAndSetOptions (a, Options.RandomPort, ref options);
                    settings.Oport = 0;
                    break;
                case "--address":
                    CheckAndSetOptions (a, Options.Address, ref options);
                    settings.IP = args [++i];
                    break;
                case "--root":
                    CheckAndSetOptions (a, Options.Root, ref options);
                    settings.RootDir = args [++i];
                    break;
                case "--applications":
                    CheckAndSetOptions (a, Options.Applications, ref options);
                    settings.Apps = args [++i];
                    break;
                case "--appconfigfile":
                    CheckAndSetOptions (a, Options.AppConfigFile, ref options);
                    settings.AppConfigFile = args [++i];
                    break;
                case "--appconfigdir":
                    CheckAndSetOptions (a, Options.AppConfigDir, ref options);
                    settings.AppConfigDir = args [++i];
                    break;
                case "--nonstop":
                    settings.NonStop = true;
                    break;
                case "--help":
                    ShowHelp ();
                    return 0;
                case "--quiet":
                    quiet = true;
                    break;
                case "--version":
                    ShowVersion ();
                    return 0;
                case "--verbose":
                    settings.Verbose = true;
                    break;
                case "--pidfile": {
                    string pidfile = args[++i];
                    if (pidfile != null && pidfile.Length > 0) {
                        try {
                            using (StreamWriter sw = File.CreateText (pidfile))
                                sw.Write (Process.GetCurrentProcess ().Id);
                        } catch (Exception ex) {
                            Console.Error.WriteLine ("Failed to write pidfile {0}: {1}", pidfile, ex.Message);
                        }
                    }
                    break;
                }
                case "--no-hidden":
                    MonoWorkerRequest.CheckFileAccess = false;
                    break;

                default:
                    ShowHelp ();
                    return 1;
                }
            }

            IPAddress ipaddr = null;
            ushort port;
            try {

                port = Convert.ToUInt16 (settings.Oport);
            } catch (Exception) {
                Console.WriteLine ("The value given for the listen port is not valid: " + settings.Oport);
                return 1;
            }

            try {
                ipaddr = IPAddress.Parse (settings.IP);
            } catch (Exception) {
                Console.WriteLine ("The value given for the address is not valid: " + settings.IP);
                return 1;
            }

            if (settings.RootDir != null && settings.RootDir.Length != 0) {
                try {
                    Environment.CurrentDirectory = settings.RootDir;
                } catch (Exception e) {
                    Console.WriteLine ("Error: {0}", e.Message);
                    return 1;
                }
            }

            settings.RootDir = Directory.GetCurrentDirectory ();

            WebSource webSource;
            if (security.Enabled) {
                try {
                    key = security.KeyPair;
                    webSource = new XSPWebSource (ipaddr, port, security.Protocol, security.ServerCertificate,
                        new PrivateKeySelectionCallback (GetPrivateKey),
                        security.AcceptClientCertificates, security.RequireClientCertificates, !root);
                }
                catch (CryptographicException ce) {
                    Console.WriteLine (ce.Message);
                    return 1;
                }
            } else {
                webSource = new XSPWebSource (ipaddr, port, !root);
            }

            ApplicationServer server = new ApplicationServer (webSource, settings.RootDir);
            server.Verbose = settings.Verbose;
            server.SingleApplication = !root;

            if (settings.Apps != null)
                server.AddApplicationsFromCommandLine (settings.Apps);

            if (settings.AppConfigFile != null)
                server.AddApplicationsFromConfigFile (settings.AppConfigFile);

            if (settings.AppConfigDir != null)
                server.AddApplicationsFromConfigDirectory (settings.AppConfigDir);

            if (settings.Apps == null && settings.AppConfigDir == null && settings.AppConfigFile == null)
                server.AddApplicationsFromCommandLine ("/:.");

            VPathToHost vh = server.GetSingleApp ();
            if (root && vh != null) {
                // Redo in new domain
                vh.CreateHost (server, webSource);
                Server svr = (Server) vh.AppHost.Domain.CreateInstanceAndUnwrap (GetType ().Assembly.GetName ().ToString (), GetType ().FullName);
                webSource.Dispose ();
                return svr.RealMain (args, false, vh.AppHost, quiet);
            }
            server.AppHost = ext_apphost;

            if (!quiet) {
                Console.WriteLine (Assembly.GetExecutingAssembly ().GetName ().Name);
                Console.WriteLine ("Listening on address: {0}", settings.IP);
                Console.WriteLine ("Root directory: {0}", settings.RootDir);
            }

            try {
                if (server.Start (!settings.NonStop, settings.Exception) == false)
                    return 2;

                if (!quiet) {
                    // MonoDevelop depends on this string. If you change it, let them know.
                    Console.WriteLine ("Listening on port: {0} {1}", server.Port, security);
                }
                if (port == 0 && !quiet)
                    Console.Error.WriteLine ("Random port: {0}", server.Port);

                if (!settings.NonStop) {
                    if (!quiet)
                        Console.WriteLine ("Hit Return to stop the server.");

                    bool doSleep;
                    while (true) {
                        doSleep = false;
                        try {
                            Console.ReadLine ();
                            break;
                        } catch (IOException) {
                            // This might happen on appdomain unload
                            // until the previous threads are terminated.
                            doSleep = true;
                        } catch (ThreadAbortException) {
                            doSleep = true;
                        }

                        if (doSleep)
                            Thread.Sleep (500);
                    }
                    server.Stop ();
                }
            } catch (Exception e) {
                if (!(e is ThreadAbortException))
                    Console.WriteLine ("Error: {0}", e);
                else
                    server.ShutdownSockets ();
                return 1;
            }

            return 0;
        }
Esempio n. 21
0
        //
        // Parameters:
        //
        //   args - original args passed to the program
        //   root - true means caller is in the root domain
        //   ext_apphost - used when single app mode is used, in a recursive call to
        //        RealMain from the single app domain
        //   quiet - don't show messages. Used to avoid double printing of the banner
        //
        public int RealMain(string [] args, bool root, IApplicationHost ext_apphost, bool quiet)
        {
            ApplicationSettings settings = new ApplicationSettings ();
            if (ext_apphost != null)
                settings.RootDir = ext_apphost.Path;

            Options options = 0;
            int backlog = 500;
            int hash = 0;
            for (int i = 0; i < args.Length; i++){
                string a = args [i];
                int idx = (i + 1 < args.Length) ? i + 1 : i;
                hash ^= args [idx].GetHashCode () + i;

                switch (a){
                case "--filename":
                    CheckAndSetOptions (a, Options.FileName, ref options);
                    settings.FileName = args [++i];
                    break;
                case "--terminate":
                    CheckAndSetOptions (a, Options.Terminate, ref options);
                    break;
                case "--master":
                    CheckAndSetOptions (a, Options.Master, ref options);
                    settings.Master = true;
                    break;
                case "--port":
                    CheckAndSetOptions (a, Options.Port, ref options);
                    settings.Oport = args [++i];
                    break;
                case "--address":
                    CheckAndSetOptions (a, Options.Address, ref options);
                    settings.IP = args [++i];
                    break;
                case "--backlog":
                    string backlogstr = args [++i];
                    try {
                        backlog = Convert.ToInt32 (backlogstr);
                    } catch (Exception) {
                        Console.WriteLine ("The value given for backlog is not valid {0}", backlogstr);
                        return 1;
                    }
                    break;
                case "--root":
                    CheckAndSetOptions (a, Options.Root, ref options);
                    settings.RootDir = args [++i];
                    break;
                case "--applications":
                    CheckAndSetOptions (a, Options.Applications, ref options);
                    settings.Apps = args [++i];
                    break;
                case "--appconfigfile":
                    CheckAndSetOptions (a, Options.AppConfigFile, ref options);
                    settings.AppConfigFile = args [++i];
                    break;
                case "--appconfigdir":
                    CheckAndSetOptions (a, Options.AppConfigDir, ref options);
                    settings.AppConfigDir = args [++i];
                    break;
                case "--minThreads":
                    string mtstr = args [++i];
                    int minThreads = 0;
                    try {
                        minThreads = Convert.ToInt32 (mtstr);
                    } catch (Exception) {
                        Console.WriteLine ("The value given for minThreads is not valid {0}", mtstr);
                        return 1;
                    }

                    if (minThreads > 0)
                        ThreadPool.SetMinThreads(minThreads, minThreads);

                    break;
                case "--nonstop":
                    settings.NonStop = true;
                    break;
                case "--help":
                    ShowHelp ();
                    return 0;
                case "--version":
                    ShowVersion ();
                    return 0;
                case "--verbose":
                    settings.Verbose = true;
                    break;
                case "--pidfile": {
                    string pidfile = args[++i];
                    if (pidfile != null && pidfile.Length > 0) {
                        try {
                            using (StreamWriter sw = File.CreateText (pidfile))
                                sw.Write (Process.GetCurrentProcess ().Id);
                        } catch (Exception ex) {
                            Console.Error.WriteLine ("Failed to write pidfile {0}: {1}", pidfile, ex.Message);
                        }
                    }
                    break;
                }
                case "--no-hidden":
                    MonoWorkerRequest.CheckFileAccess = false;
                    break;
                default:
                    Console.Error.WriteLine ("Unknown argument: {0}", a);
                    ShowHelp ();
                    return 1;
                }
            }

            if (hash < 0)
                hash = -hash;

            string lockfile;
            bool useTCP = ((options & Options.Port) != 0);
            if (!useTCP) {
                if (settings.FileName == null || settings.FileName.Length == 0)
                    settings.FileName = "/tmp/mod_mono_server";

                if ((options & Options.Address) != 0) {
                    ShowHelp ();
                    Console.Error.WriteLine ();
                    Console.Error.WriteLine ("ERROR: --address without --port");
                    Environment.Exit (1);
                } lockfile = Path.Combine (Path.GetTempPath (), Path.GetFileName (settings.FileName));
                lockfile = String.Format ("{0}_{1}", lockfile, hash);
            } else {
                lockfile = Path.Combine (Path.GetTempPath (), "mod_mono_TCP_");
                lockfile = String.Format ("{0}_{1}", lockfile, hash);
            }

            IPAddress ipaddr = null;
            ushort port;
            try {
                port = Convert.ToUInt16 (settings.Oport);
            } catch (Exception) {
                Console.Error.WriteLine ("The value given for the listen port is not valid: " + settings.Oport);
                return 1;
            }

            try {
                ipaddr = IPAddress.Parse (settings.IP);
            } catch (Exception) {
                Console.Error.WriteLine ("The value given for the address is not valid: " + settings.IP);
                return 1;
            }

            if (settings.RootDir != null && settings.RootDir.Length > 0) {
                try {
                    Environment.CurrentDirectory = settings.RootDir;
                } catch (Exception e) {
                    Console.Error.WriteLine ("Error: {0}", e.Message);
                    return 1;
                }
            }

            settings.RootDir = Directory.GetCurrentDirectory ();

            WebSource webSource;
            if (useTCP) {
                webSource = new ModMonoTCPWebSource (ipaddr, port, lockfile);
            } else {
                webSource = new ModMonoWebSource (settings.FileName, lockfile);
            }

            if ((options & Options.Terminate) != 0) {
                if (settings.Verbose)
                    Console.Error.WriteLine ("Shutting down running mod-mono-server...");

                bool res = ((ModMonoWebSource) webSource).GracefulShutdown ();
                if (settings.Verbose)
                    Console.Error.WriteLine (res ? "Done." : "Failed");

                return (res) ? 0 : 1;
            }

            ApplicationServer server = new ApplicationServer (webSource, settings.RootDir);
            server.Verbose = settings.Verbose;
            server.SingleApplication = !root;

            Console.WriteLine (Assembly.GetExecutingAssembly ().GetName ().Name);
            if (settings.Apps != null)
                server.AddApplicationsFromCommandLine (settings.Apps);

            if (settings.AppConfigFile != null)
                server.AddApplicationsFromConfigFile (settings.AppConfigFile);

            if (settings.AppConfigDir != null)
                server.AddApplicationsFromConfigDirectory (settings.AppConfigDir);

            if (!settings.Master && settings.Apps == null && settings.AppConfigDir == null && settings.AppConfigFile == null)
                server.AddApplicationsFromCommandLine ("/:.");

            VPathToHost vh = server.GetSingleApp ();
            if (root && vh != null) {
                // Redo in new domain
                vh.CreateHost (server, webSource);
                Server svr = (Server) vh.AppHost.Domain.CreateInstanceAndUnwrap (GetType ().Assembly.GetName ().ToString (), GetType ().FullName);
                webSource.Dispose ();
                return svr.RealMain (args, false, vh.AppHost, quiet);
            }
            if (ext_apphost != null) {
                ext_apphost.Server = server;
                server.AppHost = ext_apphost;
            }
            if (!useTCP && !quiet) {
                Console.Error.WriteLine ("Listening on: {0}", settings.FileName);
            } else if (!quiet) {
                Console.Error.WriteLine ("Listening on port: {0}", port);
                Console.Error.WriteLine ("Listening on address: {0}", settings.IP);
            }

            if (!quiet)
                Console.Error.WriteLine ("Root directory: {0}", settings.RootDir);

            try {
                if (server.Start (!settings.NonStop, backlog) == false)
                    return 2;

                if (!settings.NonStop) {
                    Console.Error.WriteLine ("Hit Return to stop the server.");
                    while (true) {
                        try {
                            Console.ReadLine ();
                            break;
                        } catch (IOException) {
                            // This might happen on appdomain unload
                            // until the previous threads are terminated.
                            Thread.Sleep (500);
                        }
                    }
                    server.Stop ();
                }
            } catch (Exception e) {
                if (!(e is ThreadAbortException))
                    Console.Error.WriteLine ("Error: {0}", e.Message);
                else
                    server.ShutdownSockets ();
                return 1;
            }

            return 0;
        }
Esempio n. 22
0
 public XSPWorker(Socket client, EndPoint localEP, ApplicationServer server)
 {
     netStream = new LingeringNetworkStream (client, false);
     stream = netStream;
     sock = client;
     this.server = server;
     this.remoteEP = (IPEndPoint) client.RemoteEndPoint;
     this.localEP = (IPEndPoint) localEP;
 }
Esempio n. 23
0
 public ModMonoWorker(Socket client, ApplicationServer server)
 {
     Stream      = new NetworkStream(client, true);
     this.client = client;
     this.server = server;
 }
Esempio n. 24
0
 public abstract Worker CreateWorker(Socket client, ApplicationServer server);
Esempio n. 25
0
 public override Worker CreateWorker(Socket client, ApplicationServer server)
 {
     return(new ModMonoWorker(client, server));
 }
Esempio n. 26
0
 public ModMonoWorker(Socket client, ApplicationServer server)
 {
     Stream = new NetworkStream (client, true);
     this.client = client;
     this.server = server;
 }
Esempio n. 27
0
		public ModMonoWorker (Socket client, ApplicationServer server)
		{
			Stream = new LingeringNetworkStream (client, true);
			Stream.EnableLingering = false;
			this.server = server;
		}
Esempio n. 28
0
        protected override void OnStop()
        {
            mutex.WaitOne();
            try
            {
                this.listen = false;
                this.bus.Close();
                this.bus = null;

                this.webAppServer.UnloadAll();
                this.webAppServer.Stop();
                this.webAppServer = null;

                this.websource.Dispose();
                this.websource = null;
            }
            finally
            {
                mutex.ReleaseMutex();
            }
        }