예제 #1
0
        public static void Main(string[] args)
        {
            CouchbaseLiteServiceListener listener = new CouchbaseLiteTcpListener(Manager.SharedInstance, port);
            listener.Start();

            Console.ReadKey(true);
            listener.Stop();

        }
        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();

        }
        static void Main(string[] args)
        {
            CouchbaseLiteServiceListener listener = new CouchbaseLiteTcpListener(Manager.SharedInstance, listenerPort);
            listener.Start();

            Console.WriteLine("LISTENING...");

            // sync workaround
            var syncManager = new SyncManager("sync-config.json");
            syncManager.StartReplications();

            Console.ReadKey(true);
            listener.Stop();
        }
예제 #4
0
        static void Main()
        {
            Manager manager = Manager.SharedInstance;
            var database = manager.GetDatabase("kis-database");

            var cert = X509Manager.GetPersistentCertificate("127.0.0.1", "123abc", System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "unit_test.pfx"));
            Uri uri = new Uri(String.Format("http://localhost:{0}/{1}/", 3689, "database"));
            CouchbaseLiteTcpOptions options = new CouchbaseLiteTcpOptions();

            CouchbaseLiteTcpListener listener = new CouchbaseLiteTcpListener(manager, 3689, CouchbaseLiteTcpOptions.UseTLS, cert);
            listener.SetPasswords(new Dictionary<string, string>() { { "user", "pass" } });

            listener.Start();

             Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
        public void TestSsl()
        {
            var cert = SSLGenerator.GetExistingCertificate("127.0.0.1", 59841);
            if (cert == null) {
                cert = SSLGenerator.GenerateCert("127.0.0.1", new RSACryptoServiceProvider(2048));
                SSLGenerator.InstallCertificateForListener(cert, 59841);
            }

            var sslListener = new CouchbaseLiteTcpListener(manager, 59841, CouchbaseLiteTcpOptions.UseTLS);
            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)
                {
                    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;
                }
            };

            var request = (HttpWebRequest)WebRequest.Create("https://127.0.0.1:59841");
            request.ClientCertificates.Add(SSLGenerator.GetOrCreateClientCert());
            var response = (HttpWebResponse)request.GetResponse();
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
        }
        protected override void SetUp()
        {
            base.SetUp();

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

            _listenerDBUri = new Uri("http://localhost:" + _port + "/" + LISTENER_DB_NAME);
            _listener.Start();
        }
        public void TestReplicateWithListener()
        {
            var listener = new CouchbaseLiteTcpListener(manager, 59840);
            listener.Start();

            var dbCopy = EnsureEmptyDatabase("replicate_end");
  
            var push = database.CreatePushReplication(new Uri("http://localhost:59840/replicate_end"));
            CreateDocuments(database, 20);
            var attachDoc = CreateDocWithAttachment(database, "attachment.png", "image/png");
            var attachDocId = attachDoc.Id;
            RunReplication(push);

            Assert.IsNull(push.LastError);
            Assert.AreEqual(21, dbCopy.DocumentCount);

            attachDoc = dbCopy.GetExistingDocument(attachDocId);
            Assert.IsNotNull(attachDoc, "Failed to store doc with attachment");
            Assert.IsNotNull(attachDoc.CurrentRevision.Attachments, "Failed to store attachments on attachment doc");

            var name = database.Name;
            database.Close();
            database = EnsureEmptyDatabase(name);

            var pull = database.CreatePullReplication(new Uri("http://localhost:59840/replicate_end"));
            RunReplication(pull);
            Assert.IsNull(pull.LastError);
            Assert.AreEqual(21, database.DocumentCount);

            attachDoc = database.GetExistingDocument(attachDocId);
            Assert.IsNotNull(attachDoc, "Failed to retrieve doc with attachment");
            Assert.IsNotNull(attachDoc.CurrentRevision.Attachments, "Failed to retrieve attachments on attachment doc");

            // Now with auth
            // Digest
            listener.SetPasswords(new Dictionary<string, string> { { "jim", "borden" } });
            dbCopy = EnsureEmptyDatabase("replicate_end");
            push = database.CreatePushReplication(new Uri("http://localhost:59840/replicate_end"));
            push.Authenticator = new DigestAuthenticator("jim", "borden");
            RunReplication(push);

            Assert.IsNull(push.LastError);
            Assert.AreEqual(21, dbCopy.DocumentCount);

            attachDoc = dbCopy.GetExistingDocument(attachDocId);
            Assert.IsNotNull(attachDoc, "Failed to store doc with attachment");
            Assert.IsNotNull(attachDoc.CurrentRevision.Attachments, "Failed to store attachments on attachment doc");

            name = database.Name;
            database.Close();
            database = EnsureEmptyDatabase(name);

            pull = database.CreatePullReplication(new Uri("http://localhost:59840/replicate_end"));
            pull.Authenticator = push.Authenticator;
            RunReplication(pull);
            Assert.IsNull(pull.LastError);
            Assert.AreEqual(21, database.DocumentCount);

            attachDoc = database.GetExistingDocument(attachDocId);
            Assert.IsNotNull(attachDoc, "Failed to retrieve doc with attachment");
            Assert.IsNotNull(attachDoc.CurrentRevision.Attachments, "Failed to retrieve attachments on attachment doc");

            // and now Basic
            listener.Stop();
            listener = new CouchbaseLiteTcpListener(manager, 59840, CouchbaseLiteTcpOptions.AllowBasicAuth);
            listener.SetPasswords(new Dictionary<string, string> { { "jim", "borden" } });
            listener.Start();

            dbCopy = EnsureEmptyDatabase("replicate_end");
            push = database.CreatePushReplication(new Uri("http://localhost:59840/replicate_end"));
            push.Authenticator = new BasicAuthenticator("jim", "borden");
            RunReplication(push);

            Assert.IsNull(push.LastError);
            Assert.AreEqual(21, dbCopy.DocumentCount);

            attachDoc = dbCopy.GetExistingDocument(attachDocId);
            Assert.IsNotNull(attachDoc, "Failed to store doc with attachment");
            Assert.IsNotNull(attachDoc.CurrentRevision.Attachments, "Failed to store attachments on attachment doc");

            name = database.Name;
            database.Close();
            database = EnsureEmptyDatabase(name);

            pull = database.CreatePullReplication(new Uri("http://localhost:59840/replicate_end"));
            pull.Authenticator = push.Authenticator;
            RunReplication(pull);
            Assert.IsNull(pull.LastError);
            Assert.AreEqual(21, database.DocumentCount);

            attachDoc = database.GetExistingDocument(attachDocId);
            Assert.IsNotNull(attachDoc, "Failed to retrieve doc with attachment");
            Assert.IsNotNull(attachDoc.CurrentRevision.Attachments, "Failed to retrieve attachments on attachment doc");
        }
        public void TestReplicateWithListener()
        {
            var listener = new CouchbaseLiteTcpListener(manager, 59840);
            listener.Start();

            var dbCopy = EnsureEmptyDatabase("replicate_end");
  
            var push = database.CreatePushReplication(new Uri("http://localhost:59840/replicate_end"));
            CreateDocuments(database, 20);
            var attachDoc = CreateDocWithAttachment(database, "attachment.png", "image/png");
            var attachDocId = attachDoc.Id;
            RunReplication(push);

            Assert.IsNull(push.LastError);
            Assert.AreEqual(21, dbCopy.DocumentCount);

            attachDoc = dbCopy.GetExistingDocument(attachDocId);
            Assert.IsNotNull(attachDoc, "Failed to store doc with attachment");
            Assert.IsNotNull(attachDoc.CurrentRevision.Attachments, "Failed to store attachments on attachment doc");

            var name = database.Name;
            database.Close();
            database = EnsureEmptyDatabase(name);

            var pull = database.CreatePullReplication(new Uri("http://localhost:59840/replicate_end"));
            RunReplication(pull);
            Assert.IsNull(pull.LastError);
            Assert.AreEqual(21, database.DocumentCount);

            attachDoc = database.GetExistingDocument(attachDocId);
            Assert.IsNotNull(attachDoc, "Failed to retrieve doc with attachment");
            Assert.IsNotNull(attachDoc.CurrentRevision.Attachments, "Failed to retrieve attachments on attachment doc");

            listener.Stop();

            // TODO: Auth
        }
예제 #9
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 revsLimit = 0;

            View.Compiler = new JSViewCompiler();

            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);
            }
        }
        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();
        }
        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.SecurityProtocol = SecurityProtocolType.Tls;
            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();
            }
        }