예제 #1
0
        private async void StartAsync()
        {
            try
            {
                await Task.Run(
                    () =>
                {
                    SetConfig();
                    Config config   = ServerConfig.GetConfig();
                    _networkManager = new NetworkManager(
                        config.WebAddress,
                        config.TcpAddress,
                        Convert.ToInt32(config.Timeout),
                        new DataBaseManager(_dbSourceTextBox.Text, _dbCatalogTextBox.Text));
                    _networkManager.Start();
                });

                _stopButton.Enabled = true;
            }
            catch (Exception exception)
            {
                MessageBox.Show($"{exception.TargetSite.DeclaringType.Name}: {exception.Message}");
                SwitchButton(false);
                _networkManager?.Stop();
            }
        }
예제 #2
0
        /// <summary>
        /// Create the data endpoint
        /// </summary>
        /// <param name="logger">The logger to use</param>
        /// <param name="globalMeta">Global meta dictionary</param>
        /// <param name="meta">Meta dictionary</param>
        /// <returns></returns>
        public override IDataEndpoint Create(Logger logger, MetaDictionary meta, MetaDictionary globalMeta)
        {
            IDataEndpoint ret = Script.Container.GetInstance(ClassName) as IDataEndpoint;

            if (ret == null)
            {
                throw new NetServiceException(CANAPE.Documents.Properties.Resources.ScriptDataEndpointFactory_InvalidType);
            }

            ServerConfig config = (ServerConfig)Config;

            foreach (KeyValuePair <string, string> pair in config.Properties)
            {
                meta[pair.Key] = pair.Value;
            }

            ret.Meta = meta;

            ret.GlobalMeta = globalMeta;

            if (ret is IPersistNode)
            {
                IPersistNode persist = ret as IPersistNode;

                persist.SetState(config.GetConfig(), logger);
            }

            return(ret);
        }
예제 #3
0
        public static bool IsVirtualDirectory(string urlDirectory)
        {
            if (System.String.IsNullOrEmpty(urlDirectory))
            {
                return(false);
            }

            if (ServerConfig.GetConfig().VirtualDirectories == null)
            {
                return(false);
            }

            urlDirectory = urlDirectory.Trim(trims);

            if (urlDirectory.IndexOf('/') > 0)
            {
                string[] directories = urlDirectory.Split('/');

                foreach (string directory in directories)
                {
                    if (IsVirtualDirectory(directory))
                    {
                        return(true);
                    }
                }
                return(false);
            }

            return(ServerConfig.GetConfig().VirtualDirectories[urlDirectory] != null);
        }
예제 #4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnEndRequest(object sender, EventArgs e)
        {
            HttpContext context = (HttpContext)sender;

            if (!AuthenticationRequired)
            {
                return;
            }

            string realm = ServerConfig.GetConfig().Authentication.Realm;
            string nonce = GetCurrentNonce();

            StringBuilder challenge = new StringBuilder("Digest realm=\"");

            challenge.Append(realm);
            challenge.Append("\"");
            challenge.Append(", nonce=\"");
            challenge.Append(nonce);
            challenge.Append("\"");
            challenge.Append(", opaque=\"0000000000000000\"");
            challenge.Append(", stale=");
            challenge.Append("false");
            challenge.Append(", algorithm=MD5");
            challenge.Append(", qop=\"auth\"");

            context.Response.AppendHeader("WWW-Authenticate", challenge.ToString());
        }
예제 #5
0
        private void LoadLogProvider()
        {
            Exception e            = null;
            string    providerPath = string.Empty;

            try
            {
                // see if a LogProvider is set in the config
                providerPath = ServerConfig.GetConfig(false).LogProvider;

                if (providerPath == null)
                {
                    return;
                }
                if (!File.Exists(providerPath))
                {
                    // look locally
                    providerPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase), providerPath);
                    if (!File.Exists(providerPath))
                    {
                        return;
                    }
                }

                Assembly providerAssembly = Assembly.LoadFrom(providerPath);

                foreach (Module m in providerAssembly.GetModules())
                {
                    foreach (Type t in m.GetTypes())
                    {
                        if (t.Implements <ILogProvider>())
                        {
                            m_logProvider = (ILogProvider)Activator.CreateInstance(t);
                            return;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // swallow any errors - pass them to the default provider
                e = ex;
            }
            finally
            {
                if (m_logProvider == null)
                {
                    m_logProvider = new DefaultLogProvider();
                }

                // log any error loading the log
                if (e != null)
                {
                    m_logProvider.LogPadarnError(string.Format("Error loading custom log provider '{0}' : {1}", providerPath, e.Message), null);
                }

                m_logProvider.ServerConfiguration = ServerConfig.GetConfig(m_logProvider, true);
            }
        }
예제 #6
0
 private bool CheckUserWithServerCallback(DigestAuthInfo digest)
 {
     try
     {
         return(ServerConfig.GetConfig().Authentication.AuthenticationCallback(digest));
     }
     catch
     {
         return(false);
     }
 }
예제 #7
0
        /// <summary>
        /// Maps a virtual path to a physical path on the server.
        /// </summary>
        /// <param name="virtualPath">The virtual path (absolute or relative). </param>
        /// <returns>The physical path on the server specified by virtualPath.</returns>
        public static string MapPath(string virtualPath)
        {
            var separator = new string(System.IO.Path.DirectorySeparatorChar, 1);

            // Normalize the path
            string path = System.Text.RegularExpressions.Regex.Replace(virtualPath, @"(/+)", "/");

            // Get the index of the end of the last directory name
            string resourcePath;
            string resourceIdentifier;

            int endIndex = path.LastIndexOf("/");

            if (endIndex < 0)
            {
                resourcePath       = "/";
                resourceIdentifier = path;
            }
            else
            {
                resourcePath       = (endIndex == 0) ? string.Empty : path.Substring(virtualPath.StartsWith("/") ? 1 : 0, endIndex - 1);
                resourceIdentifier = path.Substring(endIndex + 1);
            }

            ServerConfig webServerConfig = ServerConfig.GetConfig();

            // make sure all slashes on all OSes use the proper directory separator
            string rootPath = webServerConfig.DocumentRoot.Replace('/', System.IO.Path.DirectorySeparatorChar).Replace('\\', System.IO.Path.DirectorySeparatorChar);

            rootPath = (rootPath.EndsWith(separator) ? rootPath : String.Format("{0}{1}", rootPath, separator));
            StringBuilder physicalPath = new StringBuilder(rootPath);

            string[] directories = resourcePath.Split('/');
            foreach (string directory in directories)
            {
                if (String.IsNullOrEmpty(directory))
                {
                    break;
                }

                if (UrlPath.IsVirtualDirectory(directory))
                {
                    physicalPath = new StringBuilder(String.Format("{0}{1}", ServerConfig.GetConfig().VirtualDirectories.GetVirtualDirectory(directory).PhysicalDirectory, System.IO.Path.DirectorySeparatorChar));
                }
                else
                {
                    physicalPath.AppendFormat(CultureInfo.InvariantCulture, "{0}{1}", directory, System.IO.Path.DirectorySeparatorChar);
                }
            }

            physicalPath.Append(resourceIdentifier);

            return(physicalPath.ToString().Replace('/', System.IO.Path.DirectorySeparatorChar).Replace('\\', System.IO.Path.DirectorySeparatorChar));
        }
예제 #8
0
 private bool CheckUserWithServerCallback(BasicAuthInfo info)
 {
     try
     {
         return(ServerConfig.GetConfig().Authentication.AuthenticationCallback(info));
     }
     catch
     {
         return(false);
     }
 }
예제 #9
0
        public override void OnEndRequest(object sender, EventArgs e)
        {
            HttpContext context = (HttpContext)sender;

            if (!AuthenticationRequired)
            {
                return;
            }

            string realm     = ServerConfig.GetConfig().Authentication.Realm;
            string challenge = String.Format("{0} realm=\"{1}\"", AuthenticationMethod, realm);

            context.Response.AppendHeader("WWW-Authenticate", challenge);
        }
예제 #10
0
        private void SetDefaultsFromConfig()
        {
            CookiesConfiguration cookiesConfig = ServerConfig.GetConfig().Cookies;

            if (cookiesConfig != null)
            {
                this.secure   = cookiesConfig.RequireSSL;
                this.httpOnly = cookiesConfig.HttpOnlyCookies;

                if (!string.IsNullOrEmpty(cookiesConfig.Domain))
                {
                    this.domain = cookiesConfig.Domain;
                }
            }
        }
예제 #11
0
 private void MainForm_Load(object sender, EventArgs e)
 {
     try
     {
         Config config = ServerConfig.GetConfig();
         StayParameters(config);
     }
     catch (NullReferenceException exception)
     {
         MessageBox.Show(exception.Message);
         Config config = ServerConfig.GetDefaultConfig();
         StayParameters(config);
         throw;
     }
 }
예제 #12
0
        private bool CheckConfigUserList(string userName, string password)
        {
            User user;

            if ((user = ServerConfig.GetConfig().Authentication.Users.Find(userName)) == null)
            {
                return(false);
            }

            if (!user.Password.Equals(password))
            {
                return(false);
            }

            return(true);
        }
예제 #13
0
        /// <summary>
        /// Create an instance of the listener on the specified port.
        /// </summary>
        /// <param name="port">The port to listen on for incoming requests.</param>
        /// <param name="maxConnections">The maximum number of clients that can concurrently connect to listener.</param>
        /// <param name="localIP"></param>
        public HttpRequestListener(IPAddress localIP, int port, int maxConnections, ILogProvider logProvider)
        {
            m_logProvider = logProvider;

            if (port <= 0)
            {
                throw new ArgumentException("port");
            }
            if (maxConnections <= 0)
            {
                throw new ArgumentException("maxConnections");
            }

            m_logProvider.LogRuntimeInfo(ZoneFlags.RequestListener | ZoneFlags.Startup, string.Format("Creating HttpRequestListener at {0}:{1} Max connections = {2}", localIP, port, maxConnections));

            m_maxConnections = maxConnections;
            m_port           = port;

            IPEndPoint localEndpoint = new IPEndPoint(localIP, m_port);

            if (ServerConfig.GetConfig().UseSsl == true)
            {
                m_logProvider.LogRuntimeInfo(ZoneFlags.RequestListener | ZoneFlags.Startup, "SSL Enabled");
                m_serverSocket = new HttpsSocket(m_logProvider);
            }
            else
            {
                m_logProvider.LogRuntimeInfo(ZoneFlags.RequestListener | ZoneFlags.Startup, "SSL Disabled");
                m_serverSocket = new HttpSocket();
            }
            m_serverSocket.Create(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                m_logProvider.LogRuntimeInfo(ZoneFlags.RequestListener | ZoneFlags.Startup, string.Format("Binding to {0}:{1}", localEndpoint.Address, localEndpoint.Port));
                m_serverSocket.Bind(localEndpoint);
            }
            catch (Exception ex)
            {
                m_logProvider.LogRuntimeInfo(ZoneFlags.RequestListener | ZoneFlags.Startup, string.Format("Failed to binding to {0}:{1}: {2}", localEndpoint.Address, localEndpoint.Port, ex.Message));
                throw;
            }

            OnReceiveRequest += ProcessRequest;
        }
예제 #14
0
        public override bool AcceptCredentials(HttpContext context, string authentication)
        {
            bool auth = true;

            byte[]   userpass = Convert.FromBase64String(authentication);
            string[] up       = Encoding.UTF8.GetString(userpass, 0, userpass.Length).Split(separator);
            m_user = up[0];
            string password = up[1];

            if (String.IsNullOrEmpty(this.User))
            {
                return(false);
            }

            var config = ServerConfig.GetConfig();

            if (config.Authentication.AuthenticationCallback == null)
            {
                auth = CheckConfigUserList(this.User, password);
            }
            else
            {
                var info = new BasicAuthInfo
                {
                    UserName = this.User,
                    Password = password,
                    Realm    = config.Authentication.Realm,
                    Uri      = context.Request.Path,
                    Method   = context.Request.HttpMethod
                };

                auth = CheckUserWithServerCallback(info);
            }

            // set the user info
            var id = new GenericIdentity(User, this.AuthenticationMethod.ToLower());

            id.IsAuthenticated = auth;
            var principal = new GenericPrincipal(id);

            context.User = principal;

            return(auth);
        }
예제 #15
0
            // Methods
            internal TempFile()
            {
                string path = ServerConfig.GetConfig().TempRoot;

                if (!Directory.Exists(path))
                {
                    try
                    {
                        Directory.CreateDirectory(path);
                    }
                    catch
                    {
                        // TODO: don't swallow this!! - log it
                        // Logging
                    }
                }
                this.m_filename   = System.IO.Path.Combine(path, Guid.NewGuid().ToString() + ".post");
                this.m_filestream = new FileStream(this.m_filename, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
            }
예제 #16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <param name="authentication"></param>
        /// <returns></returns>
        public override bool AcceptCredentials(HttpContext context, string authentication)
        {
            bool auth = false;

            var            config = ServerConfig.GetConfig();
            DigestAuthInfo digest = new DigestAuthInfo(context.Request.HttpMethod);

            string[] elements = authentication.Split(',');

            foreach (string element in elements)
            {
                int    splitIndex = element.IndexOf('=');
                string K          = element.Substring(0, splitIndex).Trim(new char[] { ' ', '\"' });
                string V          = element.Substring(splitIndex + 1).Trim(new char[] { ' ', '\"' });
                digest.AddElement(K, V);
            }

            m_user = digest["username"];

            if (config.Authentication.AuthenticationCallback == null)
            {
                auth = CheckConfigUserList(digest);
            }
            else
            {
                auth = CheckUserWithServerCallback(digest);
            }

            // set the user info
            var id = new GenericIdentity(User, this.AuthenticationMethod.ToLower());

            id.IsAuthenticated = auth;
            var principal = new GenericPrincipal(id);

            context.User = principal;

            return(auth);
        }
예제 #17
0
        static void InitializeTypes()
        {
            foreach (var a in ServerConfig.GetConfig().Rest)
            {
                foreach (var t in a.GetTypes())
                {
                    object[] restAttributes = t.GetCustomAttributes(typeof(ServiceContractAttribute), true);

                    if (restAttributes.Length > 0)
                    {
                        foreach (var m in t.GetMethods(BindingFlags.Public | BindingFlags.Instance))
                        {
                            object[] webGet = m.GetCustomAttributes(typeof(WebGetAttribute), true);
                            foreach (WebGetAttribute g in webGet)
                            {
                                _restTypes.Add(new RestMethodKey {
                                    UriTemplate = g.UriTemplate
                                }, m);
                            }
                        }
                    }
                }
            }
        }
예제 #18
0
        private bool CheckConfigUserList(DigestAuthInfo digest)
        {
            AuthenticationConfiguration authConfig = ServerConfig.GetConfig().Authentication;
            var user = authConfig.Users.Find(digest.UserName);

            if (user == null)
            {
                return(false);
            }

            var password = user.Password;
            var hash     = digest.GetHashCode(password);

            return(digest["response"].Equals(hash));

            //if (authConfig.Users.Find(User) == null)
            //{
            //    // Username does not exist configuration
            //    return false;
            //}

            //string realm = authConfig.Realm;

            //// Calculate the digest hashes (taken from RFC2617)

            //// A1 = unq(username-value) ":" unq(realm-value) ":" passwd
            //string A1 = String.Format("{0}:{1}:{2}", User, realm, password);
            //// H(A1) = MD5(A1)
            //string HA1 = MD5Hash(A1);

            //// A2 = method ":" digest-uri
            //string A2 = String.Format("{0}:{1}", method, digest["uri"]);
            //// H(A2) = MD5(A2)
            //string HA2 = MD5Hash(A2);

            //// KD(secret, data) = H(concat(secret, ":", data))
            //// if qop == auth:
            //// request-digest  = <"> < KD ( H(A1),     unq(nonce-value)
            ////                              ":" nc-value
            ////                              ":" unq(cnonce-value)
            ////                              ":" unq(qop-value)
            ////                              ":" H(A2)
            ////                            ) <">
            //// if qop is not present,
            //// request-digest  =
            ////           <"> < KD ( H(A1), unq(nonce-value) ":" H(A2) ) > <">
            //string unhashedDigest;
            //if (digest["qop"].Equals("auth"))
            //{
            //    unhashedDigest = String.Format("{0}:{1}:{2}:{3}:{4}:{5}",
            //        HA1,
            //        digest["nonce"],
            //        digest["nc"],
            //        digest["cnonce"],
            //        digest["qop"],
            //        HA2);
            //}
            //else
            //{
            //    unhashedDigest = String.Format("{0}:{1}:{2}",
            //        HA1, digest["nonce"], HA2);
            //}

            //string hashedDigest = MD5Hash(unhashedDigest);
        }