Example #1
0
 //--- Constructors ---
 internal ActivityState(IDreamEnvironment env, string verb, string uri)
 {
     _env      = env;
     _activity = env.CreateActivityDescription();
     _verb     = verb;
     _uri      = uri;
 }
Example #2
0
 //--- Constructors ---
 internal ActivityState(IDreamEnvironment env, string verb, string uri, string hostname)
 {
     _env      = env;
     _verb     = verb;
     _uri      = uri;
     _hostname = hostname;
 }
Example #3
0
 //--- Constructors ---
 private DreamApplication(DreamApplicationConfiguration appConfig)
 {
     _appConfig = appConfig;
     _env       = new DreamHostService();
     Initialize();
     RegisterDefaultRoute();
     _self = Plug.New(_env.Self.Uri.AtAbsolutePath("/"));
 }
Example #4
0
 //--- Constructors ---
 private DreamApplication(DreamApplicationConfiguration appConfig)
 {
     _appConfig = appConfig;
     _env = new DreamHostService();
     Initialize();
     RegisterDefaultRoute();
     _self = Plug.New(_env.Self.Uri.AtAbsolutePath("/"));
 }
Example #5
0
        //--- Methods ---

        /// <summary>
        /// Initialize a service instance.
        /// </summary>
        /// <param name="env">Host environment.</param>
        /// <param name="blueprint">Service blueprint.</param>
        public virtual void Initialize(IDreamEnvironment env, XDoc blueprint)
        {
            if (env == null)
            {
                throw new ArgumentNullException("env");
            }
            if (blueprint == null)
            {
                throw new ArgumentNullException("blueprint");
            }
            _env       = env;
            _blueprint = blueprint;
        }
Example #6
0
        //--- Constructors ---

        /// <summary>
        /// Create instance.
        /// </summary>
        /// <param name="env">Dream Environment.</param>
        /// <param name="verb">Http request verb.</param>
        /// <param name="uri">Request Uri.</param>
        /// <param name="feature">Request handling feature.</param>
        /// <param name="publicUri">Public Uri for incoming request.</param>
        /// <param name="serverUri">Server Uri for Dream Host.</param>
        /// <param name="request">Request message.</param>
        /// <param name="culture">Request Culture.</param>
        /// <param name="requestContainerFactory">Factory delegate to create a request container on demand.</param>
        public DreamContext(IDreamEnvironment env, string verb, XUri uri, DreamFeature feature, XUri publicUri, XUri serverUri, DreamMessage request, CultureInfo culture, Func <Action <ContainerBuilder>, ILifetimeScope> requestContainerFactory)
        {
            if (env == null)
            {
                throw new ArgumentNullException("env");
            }
            if (verb == null)
            {
                throw new ArgumentNullException("verb");
            }
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }
            if (feature == null)
            {
                throw new ArgumentNullException("feature");
            }
            if (publicUri == null)
            {
                throw new ArgumentNullException("publicUri");
            }
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            if (culture == null)
            {
                throw new ArgumentNullException("culture");
            }
            if (requestContainerFactory == null)
            {
                throw new ArgumentNullException("requestContainerFactory");
            }
            this.ID      = System.Threading.Interlocked.Increment(ref _contextIdCounter);
            this.Env     = env;
            this.Verb    = verb;
            this.Uri     = uri;
            this.Feature = feature;
            this.Feature.ExtractArguments(this.Uri, out _suffixes, out _pathParams);
            this.ServerUri           = serverUri;
            this.Request             = request;
            this.StartTime           = GlobalClock.UtcNow;
            _publicUri               = publicUri;
            _culture                 = culture;
            _requestContainerFactory = requestContainerFactory;

            // get service license
            _license = CheckServiceLicense();
        }
Example #7
0
 //--- Constructors ---
 public HttpTransport(IDreamEnvironment env, XUri uri, AuthenticationSchemes authenticationSheme)
 {
     if(env == null) {
         throw new ArgumentNullException("env");
     }
     if(uri == null) {
         throw new ArgumentNullException("uri");
     }
     _env = env;
     _uri = uri.WithoutCredentialsPathQueryFragment();
     _minSimilarity = _uri.MaxSimilarity;
     _sourceInternal = _uri + " (internal)";
     _sourceExternal = _uri.ToString();
     _authenticationSheme = authenticationSheme;
 }
Example #8
0
 private DreamContext(IDreamEnvironment env, string verb, XUri uri, DreamFeature feature, XUri publicUri, XUri serverUri, DreamMessage request, CultureInfo culture, Func <IContainer> requestContainerFactory, Dictionary <string, string> license)
 {
     if (env == null)
     {
         throw new ArgumentNullException("env");
     }
     if (verb == null)
     {
         throw new ArgumentNullException("verb");
     }
     if (uri == null)
     {
         throw new ArgumentNullException("uri");
     }
     if (feature == null)
     {
         throw new ArgumentNullException("feature");
     }
     if (publicUri == null)
     {
         throw new ArgumentNullException("publicUri");
     }
     if (request == null)
     {
         throw new ArgumentNullException("request");
     }
     if (culture == null)
     {
         throw new ArgumentNullException("culture");
     }
     if (requestContainerFactory == null)
     {
         throw new ArgumentNullException("requestContainerFactory");
     }
     this.ID      = System.Threading.Interlocked.Increment(ref _contextIdCounter);
     this.Env     = env;
     this.Verb    = verb;
     this.Uri     = uri;
     this.Feature = feature;
     this.Feature.ExtractArguments(this.Uri, out _suffixes, out _pathParams);
     this.ServerUri           = serverUri;
     this.Request             = request;
     this.StartTime           = DateTime.UtcNow;
     _publicUri               = publicUri;
     _culture                 = culture;
     _requestContainerFactory = requestContainerFactory;
     _license                 = license;
 }
Example #9
0
 //--- Constructors ---
 public HttpTransport(IDreamEnvironment env, XUri uri, AuthenticationSchemes authenticationSheme)
 {
     if (env == null)
     {
         throw new ArgumentNullException("env");
     }
     if (uri == null)
     {
         throw new ArgumentNullException("uri");
     }
     _env                 = env;
     _uri                 = uri.WithoutCredentialsPathQueryFragment();
     _minSimilarity       = _uri.MaxSimilarity;
     _sourceInternal      = _uri + " (internal)";
     _sourceExternal      = _uri.ToString();
     _authenticationSheme = authenticationSheme;
 }
Example #10
0
 //--- Constructors ---
 public HttpTransport(IDreamEnvironment env, XUri uri, AuthenticationSchemes authenticationSheme, string dreamInParamAuthtoken)
 {
     if(env == null) {
         throw new ArgumentNullException("env");
     }
     if(uri == null) {
         throw new ArgumentNullException("uri");
     }
     _env = env;
     _uri = uri.WithoutCredentialsPathQueryFragment();
     _minSimilarity = _uri.MaxSimilarity;
     _sourceInternal = _uri + " (internal)";
     _sourceExternal = _uri.ToString();
     _authenticationSheme = authenticationSheme;
     _dreamInParamAuthtoken = dreamInParamAuthtoken;
     this.ServerSignature = "Dream-HTTPAPI/" + DreamUtil.DreamVersion;
 }
Example #11
0
 //--- Constructors ---
 public HttpTransport(IDreamEnvironment env, XUri uri, AuthenticationSchemes authenticationSheme, string dreamInParamAuthtoken)
 {
     if (env == null)
     {
         throw new ArgumentNullException("env");
     }
     if (uri == null)
     {
         throw new ArgumentNullException("uri");
     }
     _env                   = env;
     _uri                   = uri.WithoutCredentialsPathQueryFragment();
     _minSimilarity         = _uri.MaxSimilarity;
     _sourceInternal        = _uri + " (internal)";
     _sourceExternal        = _uri.ToString();
     _authenticationSheme   = authenticationSheme;
     _dreamInParamAuthtoken = dreamInParamAuthtoken;
     this.ServerSignature   = "Dream-HTTPAPI/" + DreamUtil.DreamVersion;
 }
Example #12
0
        private void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }
            _disposed = true;
            if (disposing)
            {
                // shutdown the environment
                if (_env != null)
                {
                    try {
                        _env.Deinitialize();
                    } catch (Exception e) {
                        _log.ErrorExceptionMethodCall(e, "Destroy");
                    }
                }

                // stop transports
                if (_transports != null)
                {
                    foreach (Http.HttpTransport transport in _transports)
                    {
                        if (transport != null)
                        {
                            try {
                                transport.Shutdown();
                            } catch (Exception e) {
                                _log.ErrorExceptionMethodCall(e, "Destroy");
                            }
                        }
                    }
                    _transports.Clear();
                }
            }
            _host       = null;
            _env        = null;
            _transports = null;
        }
Example #13
0
        //--- Constructors ---
        /// <summary>
        /// Create new handler instance
        /// </summary>
        public HttpHandler()
        {
            if(_env == null) {
                lock(SyncRoot) {
                    if(_env == null) {
                        _log.InfoMethodCall("Startup");
                        try {
                            _log.InfoMethodCall("ctor: initializing HttpHandler");
                            NameValueCollection settings = System.Configuration.ConfigurationManager.AppSettings;

                            // determine storage locations
                            string basePath = HttpContext.Current.ApplicationInstance.Server.MapPath("~");
                            string storagePath = settings["storage-dir"] ?? settings["service-dir"];
                            if(string.IsNullOrEmpty(storagePath)) {
                                storagePath = Path.Combine(basePath, "storage");
                            } else if(!Path.IsPathRooted(storagePath)) {
                                storagePath = Path.Combine(basePath, storagePath);
                            }

                            // read configuration
                            string apikey = settings["apikey"];
                            _uri = new XUri(settings["public-uri"] ?? settings["root-uri"] ?? "http://localhost/@api");
                            _minSimilarity = _uri.MaxSimilarity;

                            // start dreamhost
                            XDoc config = new XDoc("config")
                                .Elem("guid", settings["guid"])
                                .Elem("uri.public", _uri.ToString())
                                .Elem("storage-dir", storagePath)
                                .Elem("host-path", settings["host-path"])
                                .Elem("connect-limit", settings["connect-limit"])
                                .Elem("apikey", apikey);
                            IDreamEnvironment env = new DreamHostService();
                            env.Initialize(config);

                            // load assemblies in 'services' folder
                            string servicesFolder = settings["service-dir"] ?? Path.Combine("bin", "services");
                            if(!Path.IsPathRooted(servicesFolder)) {
                                servicesFolder = Path.Combine(basePath, servicesFolder);
                            }
                            _log.DebugFormat("examining services directory '{0}'", servicesFolder);
                            if(Directory.Exists(servicesFolder)) {
                                Plug host = env.Self.With("apikey", apikey);
                                foreach(string file in Directory.GetFiles(servicesFolder, "*.dll")) {
                                    string assembly = Path.GetFileNameWithoutExtension(file);
                                    _log.DebugFormat("attempting to load '{0}'", assembly);

                                    // register assembly blueprints
                                    DreamMessage response = host.At("load").With("name", assembly).Post(new Result<DreamMessage>(TimeSpan.MaxValue)).Wait();
                                    if(!response.IsSuccessful) {
                                        _log.WarnFormat("DreamHost: ERROR: assembly '{0}' failed to load", file);
                                    }
                                }
                            } else {
                                _log.WarnFormat("DreamHost: WARN: no services directory '{0}'", servicesFolder);
                            }

                            // execute script
                            string scriptFilename = settings["script"];
                            if(!string.IsNullOrEmpty(scriptFilename)) {
                                string filename = scriptFilename;
                                if(!Path.IsPathRooted(filename)) {
                                    filename = Path.Combine(basePath, filename);
                                }

                                // execute xml script file
                                XDoc script = XDocFactory.LoadFrom(filename, MimeType.XML);
                                Plug host = env.Self.With("apikey", apikey);
                                host.At("execute").Post(script);
                            }

                            // register plug factory for this uri
                            Plug.AddEndpoint(this);

                            // set _env variable so other constructors don't initialize it anymore
                            _env = env;
                        } catch(Exception e) {
                            _log.ErrorExceptionMethodCall(e, "ctor");
                            throw;
                        }
                    }
                }
            }
        }
Example #14
0
        //--- Constructors ---

        /// <summary>
        /// Create new handler instance
        /// </summary>
        public RoutedHttpHandler(DreamApplication handler, IDreamEnvironment env)
        {
            _handler = handler;
            _env     = env;
        }
Example #15
0
 //--- Constructors ---
 internal ActivityState(IDreamEnvironment env, string verb, string uri, string hostname)
 {
     _env = env;
     _verb = verb;
     _uri = uri;
     _hostname = hostname;
 }
Example #16
0
        //--- Constructors ---

        /// <summary>
        /// Create new handler instance
        /// </summary>
        public HttpHandler()
        {
            if (_env == null)
            {
                lock (SyncRoot) {
                    if (_env == null)
                    {
                        _log.InfoMethodCall("Startup");
                        try {
                            _log.InfoMethodCall("ctor: initializing HttpHandler");
                            NameValueCollection settings = System.Configuration.ConfigurationManager.AppSettings;

                            // determine storage locations
                            string basePath    = HttpContext.Current.ApplicationInstance.Server.MapPath("~");
                            string storagePath = settings["storage-dir"] ?? settings["service-dir"];
                            if (string.IsNullOrEmpty(storagePath))
                            {
                                storagePath = Path.Combine(basePath, "storage");
                            }
                            else if (!Path.IsPathRooted(storagePath))
                            {
                                storagePath = Path.Combine(basePath, storagePath);
                            }

                            // read configuration
                            string apikey = settings["apikey"];
                            _uri                   = new XUri(settings["public-uri"] ?? settings["root-uri"] ?? "http://localhost/@api");
                            _minSimilarity         = _uri.MaxSimilarity;
                            _dreamInParamAuthtoken = settings["dream.in.authtoken"];

                            // start dreamhost
                            XDoc config = new XDoc("config")
                                          .Elem("guid", settings["guid"])
                                          .Elem("uri.public", _uri.ToString())
                                          .Elem("storage-dir", storagePath)
                                          .Elem("host-path", settings["host-path"])
                                          .Elem("connect-limit", settings["connect-limit"])
                                          .Elem("apikey", apikey);
                            IDreamEnvironment env = new DreamHostService();
                            env.Initialize(config);

                            // load assemblies in 'services' folder
                            string servicesFolder = settings["service-dir"] ?? Path.Combine("bin", "services");
                            if (!Path.IsPathRooted(servicesFolder))
                            {
                                servicesFolder = Path.Combine(basePath, servicesFolder);
                            }
                            _log.DebugFormat("examining services directory '{0}'", servicesFolder);
                            if (Directory.Exists(servicesFolder))
                            {
                                Plug host = env.Self.With("apikey", apikey);
                                foreach (string file in Directory.GetFiles(servicesFolder, "*.dll"))
                                {
                                    string assembly = Path.GetFileNameWithoutExtension(file);
                                    _log.DebugFormat("attempting to load '{0}'", assembly);

                                    // register assembly blueprints
                                    DreamMessage response = host.At("load").With("name", assembly).Post(new Result <DreamMessage>(TimeSpan.MaxValue)).Wait();
                                    if (!response.IsSuccessful)
                                    {
                                        _log.WarnFormat("DreamHost: ERROR: assembly '{0}' failed to load", file);
                                    }
                                }
                            }
                            else
                            {
                                _log.WarnFormat("DreamHost: WARN: no services directory '{0}'", servicesFolder);
                            }


                            // execute script
                            string scriptFilename = settings["script"];
                            if (!string.IsNullOrEmpty(scriptFilename))
                            {
                                string filename = scriptFilename;
                                if (!Path.IsPathRooted(filename))
                                {
                                    filename = Path.Combine(basePath, filename);
                                }

                                // execute xml script file
                                XDoc script = XDocFactory.LoadFrom(filename, MimeType.XML);
                                Plug host   = env.Self.With("apikey", apikey);
                                host.At("execute").Post(script);
                            }

                            // register plug factory for this uri
                            Plug.AddEndpoint(this);

                            // set _env variable so other constructors don't initialize it anymore
                            _env = env;
                        } catch (Exception e) {
                            _log.ErrorExceptionMethodCall(e, "ctor");
                            throw;
                        }
                    }
                }
            }
        }
Example #17
0
        /// <summary>
        /// Create a new host with provided configuration and an Inversion of Control container.
        /// </summary>
        /// <remarks>
        /// The IoC container is also injected into default activator, so that <see cref="IDreamService"/> instances
        /// can be resolved from the container. The host configuration is provided to the container as a typed parameter.
        /// </remarks>
        /// <param name="config">Host configuration.</param>
        /// <param name="container">IoC Container.</param>
        public DreamHost(XDoc config, IContainer container) {
            if(config == null) {
                throw new ArgumentNullException("config");
            }

            // read host settings
            string appDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName);
            int limit = config["connect-limit"].AsInt ?? 0;
            int httpPort = config["http-port"].AsInt ?? DEFAULT_PORT;
            AuthenticationSchemes authenticationScheme = AuthenticationSchemes.Anonymous;
            string authShemes = config["authentication-shemes"].AsText;
            if(!String.IsNullOrEmpty(authShemes)) {
                try {
                    authenticationScheme = (AuthenticationSchemes)Enum.Parse(typeof(AuthenticationSchemes), authShemes, true);
                } catch(Exception e) {
                    _log.Warn(String.Format("invalid authetication scheme specified :{0}", authShemes), e);
                }
            }

            // get the authtoken for whitelisting dream.in.* query args
            _dreamInParamAuthtoken = config["dream.in.authtoken"].AsText;
            if(!string.IsNullOrEmpty(_dreamInParamAuthtoken)) {
                _log.Debug("Host is configured in dream.in param authorizing mode");
            }

            // read ip-addresses
            var addresses = new List<string>();
            foreach(XDoc ip in config["host|ip"]) {
                addresses.Add(ip.AsText);
            }
            if(addresses.Count == 0) {

                // if no addresses were supplied listen to all
                addresses.Add("*:" + httpPort);
            }

            // use default servername
            XUri publicUri = config["uri.public"].AsUri;
            if(publicUri == null) {

                // backwards compatibility
                publicUri = config["server-name"].AsUri;
                if(publicUri == null) {
                    foreach(IPAddress addr in Dns.GetHostAddresses(Dns.GetHostName())) {
                        if(addr.AddressFamily == AddressFamily.InterNetwork) {
                            XUri.TryParse("http://" + addr, out publicUri);
                        }
                    }
                    if(publicUri == null) {
                        // failed to get an address out of dns, fall back to localhost
                        XUri.TryParse("http://localhost", out publicUri);
                    }
                }
                publicUri = publicUri.AtPath(config["server-path"].AsText ?? config["path-prefix"].AsText ?? string.Empty);
            }

            // create environment and initialize it
            _env = new DreamHostService(container);
            try {

                // initialize environment
                string apikey = config["apikey"].AsText ?? StringUtil.CreateAlphaNumericKey(32);
                XDoc serviceConfig = new XDoc("config");
                var storageType = config["storage/@type"].AsText ?? "local";
                if("s3".EqualsInvariant(storageType)) {
                    serviceConfig.Add(config["storage"]);
                } else {
                    serviceConfig.Elem("storage-dir", config["storage-dir"].AsText ?? config["service-dir"].AsText ?? appDirectory);
                }
                serviceConfig.Elem("apikey", apikey);
                serviceConfig.Elem("uri.public", publicUri);
                serviceConfig.Elem("connect-limit", limit);
                serviceConfig.Elem("guid", config["guid"].AsText);
                serviceConfig.AddAll(config["components"]);
                var memorize = config["memorize-aliases"];
                if(!memorize.IsEmpty) {
                    serviceConfig.Elem("memorize-aliases", memorize.AsBool);
                }
                _env.Initialize(serviceConfig);

                // initialize host plug
                _host = _env.Self.With("apikey", apikey);

                // load assemblies in 'services' folder
                string servicesFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "services");
                if(Directory.Exists(servicesFolder)) {

                    // Note (arnec): Deprecated, but the suggested alternative really doesn't apply since we don't want to
                    // load services into a separate appdomain.
#pragma warning disable 618,612
                    AppDomain.CurrentDomain.AppendPrivatePath("services");
#pragma warning restore 618,612
                    foreach(string file in Directory.GetFiles(servicesFolder, "*.dll")) {

                        // register assembly blueprints
                        DreamMessage response = _host.At("load").With("name", Path.GetFileNameWithoutExtension(file)).Post(new Result<DreamMessage>(TimeSpan.MaxValue)).Wait();
                        if(!response.IsSuccessful) {
                            _log.WarnFormat("DreamHost: ERROR: assembly '{0}' failed to load", file);
                        }
                    }
                }

                // add acccess-points
                AddListener(new XUri(String.Format("http://{0}:{1}/", "localhost", httpPort)), authenticationScheme);

                // check if user prescribed a set of IP addresses to use
                if(addresses != null) {

                    // listen to custom addresses (don't use the supplied port info, we expect that to be part of the address)
                    foreach(string address in addresses) {
                        if(!StringUtil.EqualsInvariantIgnoreCase(address, "localhost")) {
                            AddListener(new XUri(String.Format("http://{0}/", address)), authenticationScheme);
                        }
                    }
                } else {

                    // add listeners for all known IP addresses
                    foreach(IPAddress address in Dns.GetHostAddresses(Dns.GetHostName())) {
                        XUri uri = MakeUri(address, httpPort);
                        if(uri != null) {
                            AddListener(uri, authenticationScheme);
                            try {
                                foreach(string alias in Dns.GetHostEntry(address).Aliases) {
                                    AddListener(new XUri(String.Format("http://{0}:{1}/", alias, httpPort)), authenticationScheme);
                                }
                            } catch { }
                        }
                    }
                }
            } catch(Exception e) {
                if((e is HttpListenerException) && e.Message.EqualsInvariant("Access is denied")) {
                    _log.ErrorExceptionMethodCall(e, "ctor", "insufficient privileges to create HttpListener, make sure the application runs with Administrator rights");
                } else {
                    _log.ErrorExceptionMethodCall(e, "ctor");
                }
                try {
                    _env.Deinitialize();
                } catch { }
                throw;
            }
        }
Example #18
0
        private void Dispose(bool disposing) {
            if(_disposed) {
                return;
            }
            _disposed = true;
            if(disposing) {

                // shutdown the environment
                if(_env != null) {
                    try {
                        _env.Deinitialize();
                    } catch(Exception e) {
                        _log.ErrorExceptionMethodCall(e, "Destroy");
                    }
                }

                // stop transports
                if(_transports != null) {
                    foreach(Http.HttpTransport transport in _transports) {
                        if(transport != null) {
                            try {
                                transport.Shutdown();
                            } catch(Exception e) {
                                _log.ErrorExceptionMethodCall(e, "Destroy");
                            }
                        }
                    }
                    _transports.Clear();
                }
            }
            _host = null;
            _env = null;
            _transports = null;
        }
Example #19
0
 //--- Constructors ---
 /// <summary>
 /// Create new handler instance
 /// </summary>
 public RoutedHttpHandler(DreamApplication handler, IDreamEnvironment env)
 {
     _handler = handler;
     _env = env;
 }
Example #20
0
 //--- Constructors ---
 public DreamRouteHandler(DreamApplication application, IDreamEnvironment env)
 {
     _application = application;
     _env         = env;
 }
Example #21
0
 //--- Constructors ---
 internal ActivityState(IDreamEnvironment env, string verb, string uri)
 {
     _env = env;
     _verb = verb;
     _uri = uri;
 }
Example #22
0
 //--- Constructors ---
 public DreamRouteHandler(DreamApplication application, IDreamEnvironment env)
 {
     _application = application;
     _env = env;
 }
Example #23
0
 //--- Constructors ---
 internal ActivityState(IDreamEnvironment env, string verb, string uri, string hostname)
 {
     _env = env;
     _activity = env.CreateActivityDescription();
     _verb = verb;
     _uri = uri;
     _hostname = hostname;
 }
Example #24
0
        /// <summary>
        /// Create a new host with provided configuration and an Inversion of Control container.
        /// </summary>
        /// <remarks>
        /// The IoC container is also injected into default activator, so that <see cref="IDreamService"/> instances
        /// can be resolved from the container. The host configuration is provided to the container as a typed parameter.
        /// </remarks>
        /// <param name="config">Host configuration.</param>
        /// <param name="container">IoC Container.</param>
        public DreamHost(XDoc config, IContainer container)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            // read host settings
            string appDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName);
            int    limit        = config["connect-limit"].AsInt ?? 0;
            int    httpPort     = config["http-port"].AsInt ?? DEFAULT_PORT;
            AuthenticationSchemes authenticationScheme = AuthenticationSchemes.Anonymous;
            string authShemes = config["authentication-shemes"].AsText;

            if (!String.IsNullOrEmpty(authShemes))
            {
                try {
                    authenticationScheme = (AuthenticationSchemes)Enum.Parse(typeof(AuthenticationSchemes), authShemes, true);
                } catch (Exception e) {
                    _log.Warn(String.Format("invalid authetication scheme specified :{0}", authShemes), e);
                }
            }

            // get the authtoken for whitelisting dream.in.* query args
            _dreamInParamAuthtoken = config["dream.in.authtoken"].AsText;
            if (!string.IsNullOrEmpty(_dreamInParamAuthtoken))
            {
                _log.Debug("Host is configured in dream.in param authorizing mode");
            }

            // read ip-addresses
            var addresses = new List <string>();

            foreach (XDoc ip in config["host|ip"])
            {
                addresses.Add(ip.AsText);
            }
            if (addresses.Count == 0)
            {
                // if no addresses were supplied listen to all
                addresses.Add("*:" + httpPort);
            }

            // use default servername
            XUri publicUri = config["uri.public"].AsUri;

            if (publicUri == null)
            {
                // backwards compatibility
                publicUri = config["server-name"].AsUri;
                if (publicUri == null)
                {
                    foreach (IPAddress addr in Dns.GetHostAddresses(Dns.GetHostName()))
                    {
                        if (addr.AddressFamily == AddressFamily.InterNetwork)
                        {
                            XUri.TryParse("http://" + addr, out publicUri);
                        }
                    }
                    if (publicUri == null)
                    {
                        // failed to get an address out of dns, fall back to localhost
                        XUri.TryParse("http://localhost", out publicUri);
                    }
                }
                publicUri = publicUri.AtPath(config["server-path"].AsText ?? config["path-prefix"].AsText ?? string.Empty);
            }

            // create environment and initialize it
            _env = new DreamHostService(container);
            try {
                // initialize environment
                string apikey        = config["apikey"].AsText ?? StringUtil.CreateAlphaNumericKey(32);
                XDoc   serviceConfig = new XDoc("config");
                var    storageType   = config["storage/@type"].AsText ?? "local";
                if ("s3".EqualsInvariant(storageType))
                {
                    serviceConfig.Add(config["storage"]);
                }
                else
                {
                    serviceConfig.Elem("storage-dir", config["storage-dir"].AsText ?? config["service-dir"].AsText ?? appDirectory);
                }
                serviceConfig.Elem("apikey", apikey);
                serviceConfig.Elem("uri.public", publicUri);
                serviceConfig.Elem("connect-limit", limit);
                serviceConfig.Elem("guid", config["guid"].AsText);
                serviceConfig.AddAll(config["components"]);
                var memorize = config["memorize-aliases"];
                if (!memorize.IsEmpty)
                {
                    serviceConfig.Elem("memorize-aliases", memorize.AsBool);
                }
                _env.Initialize(serviceConfig);

                // initialize host plug
                _host = _env.Self.With("apikey", apikey);

                // load assemblies in 'services' folder
                string servicesFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "services");
                if (Directory.Exists(servicesFolder))
                {
                    // Note (arnec): Deprecated, but the suggested alternative really doesn't apply since we don't want to
                    // load services into a separate appdomain.
#pragma warning disable 618,612
                    AppDomain.CurrentDomain.AppendPrivatePath("services");
#pragma warning restore 618,612
                    foreach (string file in Directory.GetFiles(servicesFolder, "*.dll"))
                    {
                        // register assembly blueprints
                        DreamMessage response = _host.At("load").With("name", Path.GetFileNameWithoutExtension(file)).Post(new Result <DreamMessage>(TimeSpan.MaxValue)).Wait();
                        if (!response.IsSuccessful)
                        {
                            _log.WarnFormat("DreamHost: ERROR: assembly '{0}' failed to load", file);
                        }
                    }
                }

                // add acccess-points
                AddListener(new XUri(String.Format("http://{0}:{1}/", "localhost", httpPort)), authenticationScheme);

                // check if user prescribed a set of IP addresses to use
                if (addresses != null)
                {
                    // listen to custom addresses (don't use the supplied port info, we expect that to be part of the address)
                    foreach (string address in addresses)
                    {
                        if (!StringUtil.EqualsInvariantIgnoreCase(address, "localhost"))
                        {
                            AddListener(new XUri(String.Format("http://{0}/", address)), authenticationScheme);
                        }
                    }
                }
                else
                {
                    // add listeners for all known IP addresses
                    foreach (IPAddress address in Dns.GetHostAddresses(Dns.GetHostName()))
                    {
                        XUri uri = MakeUri(address, httpPort);
                        if (uri != null)
                        {
                            AddListener(uri, authenticationScheme);
                            try {
                                foreach (string alias in Dns.GetHostEntry(address).Aliases)
                                {
                                    AddListener(new XUri(String.Format("http://{0}:{1}/", alias, httpPort)), authenticationScheme);
                                }
                            } catch { }
                        }
                    }
                }
            } catch (Exception e) {
                if ((e is HttpListenerException) && e.Message.EqualsInvariant("Access is denied"))
                {
                    _log.ErrorExceptionMethodCall(e, "ctor", "insufficient privileges to create HttpListener, make sure the application runs with Administrator rights");
                }
                else
                {
                    _log.ErrorExceptionMethodCall(e, "ctor");
                }
                try {
                    _env.Deinitialize();
                } catch { }
                throw;
            }
        }
Example #25
0
 //--- Methods ---
 /// <summary>
 /// Initialize a service instance.
 /// </summary>
 /// <param name="env">Host environment.</param>
 /// <param name="blueprint">Service blueprint.</param>
 public virtual void Initialize(IDreamEnvironment env, XDoc blueprint)
 {
     if(env == null) {
         throw new ArgumentNullException("env");
     }
     if(blueprint == null) {
         throw new ArgumentNullException("blueprint");
     }
     _env = env;
     _blueprint = blueprint;
 }
Example #26
0
 //--- Constructors ---
 internal ActivityState(IDreamEnvironment env, string verb, string uri)
 {
     _env  = env;
     _verb = verb;
     _uri  = uri;
 }