private void SetupListener(bool secure)
        {
            var opts = CouchbaseLiteTcpOptions.Default;

            if (_authScheme == AuthenticationSchemes.Basic)
            {
                opts |= CouchbaseLiteTcpOptions.AllowBasicAuth;
            }

            if (secure)
            {
                var cert = X509Manager.GetPersistentCertificate("127.0.0.1", "123abc", System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "unit_test.pfx"));
                _listenerDBUri = new Uri(String.Format("https://localhost:{0}/{1}/", _port, LISTENER_DB_NAME));
                _listener      = new CouchbaseLiteTcpListener(manager, _port, opts | CouchbaseLiteTcpOptions.UseTLS, cert);
            }
            else
            {
                _listenerDBUri = new Uri(String.Format("http://localhost:{0}/{1}/", _port, LISTENER_DB_NAME));
                _listener      = new CouchbaseLiteTcpListener(manager, _port, opts);
            }

            if (_authScheme != AuthenticationSchemes.None)
            {
                _listener.SetPasswords(new Dictionary <string, string> {
                    { "bob", "slack" }
                });
            }

            _listener.Start();
        }
示例#2
0
        public static void Main(string[] args)
        {
            CouchbaseLiteServiceListener listener = new CouchbaseLiteTcpListener(Manager.SharedInstance, port);

            listener.SetPasswords(new Dictionary <string, string> {
                { "jim", "borden" }
            });
            listener.Start();

            Console.ReadKey(true);
            listener.Stop();
        }
        protected override void SetUp()
        {
            base.SetUp();

            _listenerDB = EnsureEmptyDatabase(LISTENER_DB_NAME);
            _listener   = new CouchbaseLiteTcpListener(manager, _port);
            #if USE_AUTH
            _listener.SetPasswords(new Dictionary <string, string> {
                { "bob", "slack" }
            });
            #endif

            _listenerDBUri = new Uri("http://localhost:" + _port + "/" + LISTENER_DB_NAME);
            _listener.Start();
        }
示例#4
0
        private static void Main()
        {
            SetupLogger();

            manager = new Manager(
                Directory.CreateDirectory("D:\\CouchbaseLite"),
                ManagerOptions.Default);

            db = manager.GetDatabase(DbName);

            var listener = new CouchbaseLiteTcpListener(manager, DbPort);

            listener.Start();

            Console.WriteLine("Press ESC to stop");

            var shutdownTokenSource = new CancellationTokenSource();

            HandleCommands(shutdownTokenSource);
        }
示例#5
0
        public static void StartListener()
        {
            var listener = new CouchbaseLiteTcpListener(Manager.SharedInstance, Port);

            listener.Start();

            //var broadcaster = new CouchbaseLiteServiceBroadcaster(null, port)
            //{
            //    Name = "LiddupSession"
            //};
            //broadcaster.Start();

            //var browser = new CouchbaseLiteServiceBrowser(null);
            //browser.ServiceResolved += (sender, e) => {

            //};

            //browser.ServiceRemoved += (sender, e) => {

            //};
            //browser.Start();
        }
        public void TestSsl()
        {
            var cert        = X509Manager.GetPersistentCertificate("127.0.0.1", "123abc", System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "unit_test.pfx"));
            var sslListener = new CouchbaseLiteTcpListener(manager, 59841, CouchbaseLiteTcpOptions.UseTLS, cert);

            sslListener.Start();

            ServicePointManager.ServerCertificateValidationCallback =
                (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) =>
            {
                // If the certificate is a valid, signed certificate, return true.
                if (sslPolicyErrors == SslPolicyErrors.None || sslPolicyErrors == SslPolicyErrors.RemoteCertificateNameMismatch)
                {
                    return(true);
                }

                // If there are errors in the certificate chain, look at each error to determine the cause.
                if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0)
                {
                    if (chain != null && chain.ChainStatus != null)
                    {
                        foreach (X509ChainStatus status in chain.ChainStatus)
                        {
                            if ((certificate.Subject == certificate.Issuer) &&
                                (status.Status == X509ChainStatusFlags.UntrustedRoot))
                            {
                                // Self-signed certificates with an untrusted root are valid.
                                continue;
                            }
                            else
                            {
                                if (status.Status != X509ChainStatusFlags.NoError)
                                {
                                    // If there are any other errors in the certificate chain, the certificate is invalid,
                                    // so the method returns false.
                                    return(false);
                                }
                            }
                        }
                    }

                    // When processing reaches this line, the only errors in the certificate chain are
                    // untrusted root errors for self-signed certificates. These certificates are valid
                    // for default Exchange server installations, so return true.
                    return(true);
                }
                else
                {
                    // In all other cases, return false.
                    return(false);
                }
            };

            try {
                var request  = (HttpWebRequest)WebRequest.Create("https://127.0.0.1:59841/");
                var response = (HttpWebResponse)request.GetResponse();
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

                request = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:59841/");
                Assert.Throws <WebException>(() => response = (HttpWebResponse)request.GetResponse());
            } finally {
                sslListener.Stop();
            }
        }
示例#7
0
        public static void Main(string[] args)
        {
            // INTERNAL API
            CouchbaseLiteRouter.InsecureMode = true;
            // INTERNAL API

            Couchbase.Lite.Util.Log.SetLogger(Logger);
            Couchbase.Lite.Util.Log.ScrubSensitivity = Couchbase.Lite.Util.LogScrubSensitivity.AllOK;

            var alternateDir = default(string);
            var pullUrl      = default(Uri);
            var pushUrl      = default(Uri);
            var portToUse    = DefaultPort;
            var readOnly     = false;
            var requiresAuth = false;
            var createTarget = false;
            var continuous   = false;
            var userName     = default(string);
            var password     = default(string);
            var useSSL       = false;
            var sslCertPath  = default(string);
            var sslCertPass  = default(string);
            var storageType  = "SQLite";
            var passwordMap  = new Dictionary <string, string>();
            var showHelp     = false;
            var revsLimit    = 0;

            View.Compiler           = new JSViewCompiler();
            Database.FilterCompiler = new JSFilterCompiler();

            var options = new OptionSet {
                { "dir=", "Specifies an alternate directory to store databases in", v => alternateDir = v },
                { "port=", "Specifies the port to listen on (default 59840)", v => portToUse = Int32.Parse(v) },
                { "readonly", "Enables readonly mode", v => readOnly = v != null },
                { "auth", "Set listener to require HTTP auth", v => requiresAuth = v != null },
                { "pull=", "Specifies a remote database to pull from", v => pullUrl = new Uri(v) },
                { "push=", "Specifies a remote database to push to", v => pushUrl = new Uri(v) },
                { "create-target", "Creates the replication target database, if pull", v => createTarget = v != null },
                { "continuous", "Specifies continuous replication", v => continuous = v != null },
                { "user="******"Specifies a username for connecting to a remote database", v => userName = v },
                { "password="******"Specifies a password for connection to a remote database", v => password = v },
                { "revs_limit=", "Sets default max rev-tree depth for databases", v => revsLimit = Int32.Parse(v) },
                { "ssl", "Serve over SSL", v => useSSL = v != null },
                { "sslcert=", "Path to the SSL certificate to use", v => sslCertPath = v },
                { "sslpass="******"Password for the SSL certificate", v => sslCertPass = v },
                { "storage=", "Set default storage engine ('SQLite' (default) or 'ForestDB')", v => storageType = v },
                { "dbpassword="******"Register password to open a database (name=password)", v => RegisterPassword(passwordMap, v) },
                { "help|h|?", "Show this help message", v => showHelp = v != null }
            };

            try {
                var remaining = options.Parse(args);
                foreach (var arg in remaining)
                {
                    Logger.W("Listener", "Unrecognized argument {0}, ignoring...", arg);
                }
            } catch (Exception e) {
                Logger.E("Listener", "Error parsing arguments", e);
                ShowHelp(options);
                Exit();
                return;
            }

            if (showHelp)
            {
                ShowHelp(options);
                Exit();
                return;
            }

            Couchbase.Lite.Storage.ForestDB.Plugin.Register();
            Couchbase.Lite.Storage.SQLCipher.Plugin.Register();

            var manager = alternateDir != null ? new Manager(new DirectoryInfo(alternateDir), ManagerOptions.Default)
                : Manager.SharedInstance;

            manager.StorageType = storageType;
            if (revsLimit > 0)
            {
                // Note: Internal API (used for testing)
                manager.DefaultMaxRevTreeDepth = revsLimit;
            }

            if (passwordMap.Count > 0)
            {
                foreach (var entry in passwordMap)
                {
#pragma warning disable 618
                    manager.RegisterEncryptionKey(entry.Key, new SymmetricKey(entry.Value));
#pragma warning restore 618
                }
            }

            var tcpOptions = CouchbaseLiteTcpOptions.Default | CouchbaseLiteTcpOptions.AllowBasicAuth;
            var sslCert    = default(X509Certificate2);
            if (useSSL)
            {
                tcpOptions |= CouchbaseLiteTcpOptions.UseTLS;
                if (sslCertPath != null)
                {
                    if (!File.Exists(sslCertPath))
                    {
                        Logger.E("Listener", "No file exists at given path for SSL cert ({0})", sslCertPath);
                        Exit();
                        return;
                    }

                    try {
                        sslCert = new X509Certificate2(sslCertPath, sslCertPass);
                    } catch (Exception e) {
                        Logger.E("Listener", "Error reading SSL cert ({0}), {1}", sslCertPath, e);
                        Exit();
                        return;
                    }
                }
            }

            var replicator = default(Replication);
            if (pushUrl != null || pullUrl != null)
            {
                replicator = SetupReplication(manager, continuous, createTarget,
                                              pushUrl ?? pullUrl, pullUrl != null, userName, password);
                if (replicator == null)
                {
                    Exit();
                    return;
                }
            }

            CouchbaseLiteServiceListener listener = new CouchbaseLiteTcpListener(manager, (ushort)portToUse, tcpOptions, sslCert);
            listener.ReadOnly = readOnly;
            if (requiresAuth)
            {
                var random            = new Random();
                var generatedPassword = random.Next().ToString();
                listener.SetPasswords(new Dictionary <string, string> {
                    { "cbl", generatedPassword }
                });
                Logger.I("Listener", "Auth required: user='******', password='******'", generatedPassword);
            }

            listener.Start();
            Logger.I("Listener", "LISTENING...");
            var wait = new ManualResetEventSlim();
            Console.WriteLine("Press Ctrl+C to end the process");
            Console.CancelKeyPress += (sender, e) => wait.Set();
            wait.Wait();
            Console.WriteLine("Shutting down now");
            wait.Dispose();

            foreach (var db in manager.AllOpenDatabases())
            {
                db.Close();
            }

            if (replicator != null)
            {
                replicator.Stop();
                Thread.Sleep(5000);
            }
        }
示例#8
0
        public static void Main(string[] args)
        {
            Couchbase.Lite.Util.Log.SetLogger(Logger);
            var alternateDir = default(string);
            var pullUrl      = default(Uri);
            var pushUrl      = default(Uri);
            var portToUse    = DefaultPort;
            var readOnly     = false;
            var requiresAuth = false;
            var createTarget = false;
            var continuous   = false;
            var userName     = default(string);
            var password     = default(string);
            var useSSL       = false;
            var sslCertPath  = default(string);
            var sslCertPass  = default(string);
            var storageType  = "SQLite";
            //var passwordMap = new Dictionary<string, string>();
            var showHelp = false;

            var options = new OptionSet {
                { "dir=", "Specifies an alternate directory to store databases in", v => alternateDir = v },
                { "port=", "Specifies the port to listen on (default 59840)", v => portToUse = Int32.Parse(v) },
                { "readonly", "Enables readonly mode", v => readOnly = v != null },
                { "auth", "Set listener to require HTTP auth", v => requiresAuth = v != null },
                { "pull=", "Specifies a remote database to pull from", v => pullUrl = new Uri(v) },
                { "push=", "Specifies a remote database to push to", v => pushUrl = new Uri(v) },
                { "create-target", "Creates the replication target database, if pull", v => createTarget = v != null },
                { "continuous", "Specifies continuous replication", v => continuous = v != null },
                { "user="******"Specifies a username for connecting to a remote database", v => userName = v },
                { "password="******"Specifies a password for connection to a remote database", v => password = v },
                { "ssl", "Serve over SSL", v => useSSL = v != null },
                { "sslcert=", "Path to the SSL certificate to use", v => sslCertPath = v },
                { "sslpass="******"Password for the SSL certificate", v => sslCertPass = v },
                { "storage=", "Set default storage engine ('SQLite' (default) or 'ForestDB')", v => storageType = v },

                { "help|h|?", "Show this help message", v => showHelp = v != null }
            };

            try {
                var remaining = options.Parse(args);
                foreach (var arg in remaining)
                {
                    Logger.W("Listener", "Unrecognized argument {0}, ignoring...", arg);
                }
            } catch (Exception e) {
                Logger.E("Listener", "Error parsing arguments", e);
                ShowHelp(options);
                Exit();
                return;
            }

            if (showHelp)
            {
                ShowHelp(options);
                Exit();
                return;
            }

            var manager = alternateDir != null ? new Manager(new DirectoryInfo(alternateDir), ManagerOptions.Default)
                : Manager.SharedInstance;

            manager.StorageType = storageType;

            var tcpOptions = CouchbaseLiteTcpOptions.Default | CouchbaseLiteTcpOptions.AllowBasicAuth;
            var sslCert    = default(X509Certificate2);

            if (useSSL)
            {
                tcpOptions |= CouchbaseLiteTcpOptions.UseTLS;
                if (sslCertPath != null)
                {
                    if (!File.Exists(sslCertPath))
                    {
                        Logger.E("Listener", "No file exists at given path for SSL cert ({0})", sslCertPath);
                        Exit();
                        return;
                    }

                    try {
                        sslCert = new X509Certificate2(sslCertPath, sslCertPass);
                    } catch (Exception e) {
                        Logger.E("Listener", "Error reading SSL cert ({0}), {1}", sslCertPath, e);
                        Exit();
                        return;
                    }
                }
            }

            var replicator = default(Replication);

            if (pushUrl != null || pullUrl != null)
            {
                replicator = SetupReplication(manager, continuous, createTarget,
                                              pushUrl ?? pullUrl, pullUrl != null, userName, password);
                if (replicator == null)
                {
                    Exit();
                    return;
                }
            }

            CouchbaseLiteServiceListener listener = new CouchbaseLiteTcpListener(manager, (ushort)portToUse, tcpOptions, sslCert);

            listener.ReadOnly = readOnly;
            if (requiresAuth)
            {
                var random            = new Random();
                var generatedPassword = random.Next().ToString();
                listener.SetPasswords(new Dictionary <string, string> {
                    { "cbl", generatedPassword }
                });
                Logger.I("Listener", "Auth required: user='******', password='******'", generatedPassword);
            }

            listener.Start();
            Logger.I("Listener", "LISTENING...");
            Console.ReadKey(true);
            if (replicator != null)
            {
                replicator.Stop();
                Thread.Sleep(5000);
            }
        }
        public static void StartListener()
        {
            var alternateDir = default(string);
            var pullUrl      = default(Uri);
            var pushUrl      = default(Uri);
            var portToUse    = DefaultPort;
            var readOnly     = false;
            var requiresAuth = false;
            var createTarget = false;
            var continuous   = false;
            var userName     = default(string);
            var password     = default(string);
            var useSSL       = false;
            var sslCertPath  = default(string);
            var sslCertPass  = default(string);
            var storageType  = "SQLite";
            var passwordMap  = new Dictionary <string, string>();
            var revsLimit    = 0;

            string json;

            using (var httpListener = new HttpListener())
            {
                try {
                    httpListener.Prefixes.Add($"http://*:{DefaultPort}/test/");
                    httpListener.Start();
                } catch (HttpListenerException e) {
                    Console.Error.WriteLine("Error setting up parameter listener: {0}", e);
                    return;
                }

                var context = httpListener.GetContext();
                var reader  = new StreamReader(context.Request.InputStream);
                json = reader.ReadToEnd();
            }

            Dictionary <string, object> optionsDict = JsonConvert.DeserializeObject <Dictionary <string, object> >(json);

            foreach (var option in optionsDict)
            {
                switch (option.Key)
                {
                case "dir":           alternateDir = (string)option.Value; break;

                case "port":          portToUse = (int)option.Value; break;

                case "readonly":      readOnly = (bool)option.Value; break;

                case "auth":          requiresAuth = (bool)option.Value; break;

                case "push":          pushUrl = new Uri((string)option.Value); break;

                case "pull":          pullUrl = new Uri((string)option.Value); break;

                case "create-target": createTarget = (bool)option.Value; break;

                case "continuous":    continuous = (bool)option.Value; break;

                case "user":          userName = (string)option.Value; break;

                case "password":      password = (string)option.Value; break;

                case "revs_limit":    revsLimit = (int)option.Value; break;

                case "ssl":           useSSL = (bool)option.Value; break;

                case "sslcert":       sslCertPath = (string)option.Value; break;

                case "sslpass":       sslCertPass = (string)option.Value; break;

                case "storage":       storageType = (string)option.Value; break;

                case "dbpassword":
                    RegisterPassword(passwordMap, (string)option.Value);
                    break;

                default:
                    Console.Error.WriteLine("Unrecognized argument {0}, ignoring...", option.Key);
                    break;
                }
            }

            Couchbase.Lite.Storage.ForestDB.Plugin.Register();
            Couchbase.Lite.Storage.SQLCipher.Plugin.Register();

            var manager = alternateDir != null ? new Manager(new DirectoryInfo(alternateDir), ManagerOptions.Default) : Manager.SharedInstance;

            manager.StorageType = storageType;
            if (revsLimit > 0)
            {
                // Note: Internal API (used for testing)
                manager.DefaultMaxRevTreeDepth = revsLimit;
            }

            if (passwordMap.Count > 0)
            {
                foreach (var entry in passwordMap)
                {
#pragma warning disable 618
                    manager.RegisterEncryptionKey(entry.Key, new SymmetricKey(entry.Value));
#pragma warning restore 618
                }
            }

            var tcpOptions = CouchbaseLiteTcpOptions.Default | CouchbaseLiteTcpOptions.AllowBasicAuth;
            var sslCert    = default(X509Certificate2);
            if (useSSL)
            {
                tcpOptions |= CouchbaseLiteTcpOptions.UseTLS;
                if (sslCertPath != null)
                {
                    if (!File.Exists(sslCertPath))
                    {
                        Console.Error.WriteLine("No file exists at given path for SSL cert ({0})", sslCertPath);
                        return;
                    }

                    try {
                        sslCert = new X509Certificate2(sslCertPath, sslCertPass);
                    } catch (Exception e) {
                        Console.Error.WriteLine("Error reading SSL cert ({0}), {1}", sslCertPath, e);
                        return;
                    }
                }
            }

            var replicator = default(Replication);
            if (pushUrl != null || pullUrl != null)
            {
                replicator = SetupReplication(manager, continuous, createTarget, pushUrl ?? pullUrl, pullUrl != null, userName, password);
                if (replicator == null)
                {
                    return;
                }
            }

            CouchbaseLiteServiceListener listener = new CouchbaseLiteTcpListener(manager, (ushort)portToUse, tcpOptions, sslCert);
            listener.ReadOnly = readOnly;
            if (requiresAuth)
            {
                var random            = new Random();
                var generatedPassword = random.Next().ToString();
                listener.SetPasswords(new Dictionary <string, string> {
                    { "cbl", generatedPassword }
                });
                Console.WriteLine("Auth required: user='******', password='******'", generatedPassword);
            }

            listener.Start();
            Console.WriteLine("LISTENING...");
        }