示例#1
0
 public void GET(string key, RequestInfo info)
 {
     var fromUpdate = info.Request.QueryString["from-update"].Value;
     if (!Library.Utility.Utility.ParseBool(fromUpdate, false))
     {
         var path = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "changelog.txt");
         info.OutputOK(new GetResponse() {
             Status = "OK",
             Version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(),
             Changelog = System.IO.File.ReadAllText(path)
         });
     }
     else
     {
         var updateInfo = Program.DataConnection.ApplicationSettings.UpdatedVersion;
         if (updateInfo == null)
         {
             info.ReportClientError("No update found");
         }
         else
         {
             info.OutputOK(new GetResponse() {
                 Status = "OK",
                 Version = updateInfo.Version,
                 Changelog = updateInfo.ChangeInfo
             });
         }
     }
 }
示例#2
0
        public void PUT(string key, RequestInfo info)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                info.OutputError(null, System.Net.HttpStatusCode.BadRequest, "Key is missing");
                return;
            }

            if (key.Equals("server-ssl-certificate", StringComparison.OrdinalIgnoreCase) || key.Equals("ServerSSLCertificate", StringComparison.OrdinalIgnoreCase))
            {
                info.OutputError(null, System.Net.HttpStatusCode.BadRequest, "Can only update SSL certificate from commandline");
                return;
            }

            if (key.StartsWith("--", StringComparison.Ordinal))
            {
                var settings = Program.DataConnection.Settings.ToList();

                var prop = settings.Where(x => string.Equals(key, x.Name, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                if (prop == null)
                {
                    settings.Add(prop = new Database.Setting()
                    {
                        Name = key, Value = info.Request.Form["data"].Value
                    });
                }
                else
                {
                    prop.Value = info.Request.Form["data"].Value;
                }

                Program.DataConnection.Settings = settings.ToArray();

                info.OutputOK(prop == null ? null : prop.Value);
            }
            else
            {
                var prop = typeof(Database.ServerSettings).GetProperty(key);
                if (prop == null)
                {
                    info.OutputError(null, System.Net.HttpStatusCode.NotFound, "Not found");
                }
                else
                {
                    var dict = new Dictionary <string, string>();
                    dict[key] = info.Request.Form["data"].Value;
                    Program.DataConnection.ApplicationSettings.UpdateSettings(dict, false);
                    info.OutputOK();
                }
            }
        }
示例#3
0
        public void GET(string key, RequestInfo info)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                info.OutputOK(
                    Duplicati.CommandLine.Program.SupportedCommands
                    );
            }
            else
            {
                ActiveRun t;
                if (!m_activeItems.TryGetValue(key, out t))
                {
                    info.OutputError(code: System.Net.HttpStatusCode.NotFound);
                    return;
                }

                int pagesize;
                int offset;

                int.TryParse(info.Request.QueryString["pagesize"].Value, out pagesize);
                int.TryParse(info.Request.QueryString["offset"].Value, out offset);
                pagesize = Math.Max(10, Math.Min(500, pagesize));
                offset   = Math.Max(0, offset);
                var  items = new List <string>();
                long count;
                bool started;
                bool finished;

                lock (t.Lock)
                {
                    t.LastAccess = DateTime.Now;
                    count        = t.Log.Count;
                    offset       = Math.Min((int)count, offset);
                    items.AddRange(t.Log.Skip(offset).Take(pagesize));
                    finished = t.Finished;
                    started  = t.Started;
                }

                info.OutputOK(new
                {
                    Pagesize = pagesize,
                    Offset   = offset,
                    Count    = count,
                    Items    = items,
                    Finished = finished,
                    Started  = started
                });
            }
        }
示例#4
0
        public void GET(string key, RequestInfo info)
        {
            var adv_props = from n in Program.DataConnection.GetSettings(Database.Connection.APP_SETTINGS_ID)
                            select new KeyValuePair <string, string>(n.Name, n.Value);

            info.OutputOK(adv_props.ToDictionary(x => x.Key, x => x.Value));
        }
示例#5
0
        public void GET(string key, RequestInfo info)
        {
            var adv_props = from n in Program.DataConnection.GetSettings(Database.Connection.APP_SETTINGS_ID)
                select new KeyValuePair<string, string>(n.Name, n.Value);

            info.OutputOK(adv_props.ToDictionary(x => x.Key, x => x.Value));
        }
示例#6
0
        public void PATCH(string key, RequestInfo info)
        {
            string str = info.Request.Form["data"].Value;

            if (string.IsNullOrWhiteSpace(str))
                str = new StreamReader(info.Request.Body, System.Text.Encoding.UTF8).ReadToEnd();

            if (string.IsNullOrWhiteSpace(str))
            {
                info.ReportClientError("Missing data object");
                return;
            }

            Dictionary<string, string> data = null;
            try
            {
                data = Serializer.Deserialize<Dictionary<string, string>>(new StringReader(str));
                if (data == null)
                {
                    info.ReportClientError("Data object had no entry");
                    return;
                }

                Program.DataConnection.ApplicationSettings.UpdateSettings(data, false);

                info.OutputOK();
            }
            catch (Exception ex)
            {
                if (data == null)
                    info.ReportClientError(string.Format("Unable to parse data object: {0}", ex.Message));
                else
                    info.ReportClientError(string.Format("Unable to save settings: {0}", ex.Message));
            }            
        }
示例#7
0
        private void ListFileSets(IBackup backup, RequestInfo info)
        {
            var input = info.Request.QueryString;
            var extra = new Dictionary <string, string>();

            extra["list-sets-only"] = "true";
            if (input["include-metadata"].Value != null)
            {
                extra["list-sets-only"] = (!Library.Utility.Utility.ParseBool(input["include-metadata"].Value, false)).ToString();
            }
            if (input["from-remote-only"].Value != null)
            {
                extra["no-local-db"] = Library.Utility.Utility.ParseBool(input["from-remote-only"].Value, false).ToString();
            }

            var r = Runner.Run(Runner.CreateTask(DuplicatiOperation.List, backup, extra), false) as Duplicati.Library.Interface.IListResults;

            if (r.EncryptedFiles && backup.Settings.Any(x => string.Equals("--no-encryption", x.Name, StringComparison.InvariantCultureIgnoreCase)))
            {
                info.ReportServerError("encrypted-storage");
            }
            else
            {
                info.OutputOK(r.Filesets);
            }
        }
示例#8
0
        private void SearchFiles(IBackup backup, string filterstring, RequestInfo info)
        {
            var filter     = filterstring.Split(new string[] { System.IO.Path.PathSeparator.ToString() }, StringSplitOptions.RemoveEmptyEntries);
            var timestring = info.Request.QueryString["time"].Value;
            var allversion = Duplicati.Library.Utility.Utility.ParseBool(info.Request.QueryString["all-versions"].Value, false);

            if (string.IsNullOrWhiteSpace(timestring) && !allversion)
            {
                info.ReportClientError("Invalid or missing time");
                return;
            }

            var prefixonly     = Duplicati.Library.Utility.Utility.ParseBool(info.Request.QueryString["prefix-only"].Value, false);
            var foldercontents = Duplicati.Library.Utility.Utility.ParseBool(info.Request.QueryString["folder-contents"].Value, false);
            var time           = new DateTime();

            if (!allversion)
            {
                time = Duplicati.Library.Utility.Timeparser.ParseTimeInterval(timestring, DateTime.Now);
            }

            var r = Runner.Run(Runner.CreateListTask(backup, filter, prefixonly, allversion, foldercontents, time), false) as Duplicati.Library.Interface.IListResults;

            var result = new Dictionary <string, object>();

            foreach (HttpServer.HttpInputItem n in info.Request.QueryString)
            {
                result[n.Name] = n.Value;
            }

            result["Filesets"] = r.Filesets;
            result["Files"]    = r.Files;

            info.OutputOK(result);
        }
示例#9
0
        public void GET(string key, RequestInfo info)
        {
            // Join server settings and global settings
            var adv_props =
                Program.DataConnection.GetSettings(Database.Connection.SERVER_SETTINGS_ID)
                .Where(x => !string.IsNullOrWhiteSpace(x.Name))
                .Union(
                    Program.DataConnection.Settings
                    .Where(x => !string.IsNullOrWhiteSpace(x.Name) && x.Name.StartsWith("--", StringComparison.Ordinal))
                    );

            var dict = new Dictionary <string, string>();

            foreach (var n in adv_props)
            {
                dict[n.Name] = n.Value;
            }

            string sslcert;

            dict.TryGetValue("server-ssl-certificate", out sslcert);
            dict["server-ssl-certificate"] = (!string.IsNullOrWhiteSpace(sslcert)).ToString();

            info.OutputOK(dict);
        }
示例#10
0
        private void RestoreFiles(IBackup backup, RequestInfo info)
        {
            var input = info.Request.Form;

            string[] filters;
            var      rawpaths = (input["paths"].Value ?? string.Empty).Trim();

            // We send the file list as a JSON array to avoid encoding issues with the path seperator
            // as it is an allowed character in file and path names.
            // We also accept the old way, for compatibility with the greeno theme
            if (!string.IsNullOrWhiteSpace(rawpaths) && rawpaths.StartsWith("[", StringComparison.Ordinal) && rawpaths.EndsWith("]", StringComparison.Ordinal))
            {
                filters = Newtonsoft.Json.JsonConvert.DeserializeObject <string[]>(rawpaths);
            }
            else
            {
                filters = input["paths"].Value.Split(new string[] { System.IO.Path.PathSeparator.ToString() }, StringSplitOptions.RemoveEmptyEntries);
            }

            var time          = Duplicati.Library.Utility.Timeparser.ParseTimeInterval(input["time"].Value, DateTime.Now);
            var restoreTarget = input["restore-path"].Value;
            var overwrite     = Duplicati.Library.Utility.Utility.ParseBool(input["overwrite"].Value, false);

            var permissions   = Duplicati.Library.Utility.Utility.ParseBool(input["permissions"].Value, false);
            var skip_metadata = Duplicati.Library.Utility.Utility.ParseBool(input["skip-metadata"].Value, false);

            var task = Runner.CreateRestoreTask(backup, filters, time, restoreTarget, overwrite, permissions, skip_metadata);

            Program.WorkThread.AddTask(task);

            info.OutputOK(new { TaskID = task.TaskID });
        }
示例#11
0
        private void CreateFolder(string uri, RequestInfo info)
        {
            using (var b = Duplicati.Library.DynamicLoader.BackendLoader.GetBackend(uri, new Dictionary <string, string>()))
                b.CreateFolder();

            info.OutputOK();
        }
示例#12
0
        public void POST(string key, RequestInfo info)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                info.ReportClientError("Scheme is missing");
                return;
            }

            IDictionary <string, string> data;

            try
            {
                data = Serializer.Deserialize <Dictionary <string, string> >(new StreamReader(info.Request.Body));
            }
            catch (Exception ex)
            {
                info.ReportClientError(string.Format("Unable to parse settings object: {0}", ex.Message));
                return;
            }

            if (data == null)
            {
                info.ReportClientError(string.Format("Unable to parse settings object"));
                return;
            }

            Program.DataConnection.SetUISettings(key, data);
            info.OutputOK();
        }
示例#13
0
        private void SearchFiles(IBackup backup, string filterstring, RequestInfo info)
        {
            var filter = Library.Utility.Uri.UrlDecode(filterstring ?? "").Split(new string[] { System.IO.Path.PathSeparator.ToString() }, StringSplitOptions.RemoveEmptyEntries);
            var timestring = info.Request.QueryString["time"].Value;
            var allversion = Duplicati.Library.Utility.Utility.ParseBool(info.Request.QueryString["all-versions"].Value, false);

            if (string.IsNullOrWhiteSpace(timestring) && !allversion)
            {
                info.ReportClientError("Invalid or missing time");
                return;
            }

            var prefixonly = Duplicati.Library.Utility.Utility.ParseBool(info.Request.QueryString["prefix-only"].Value, false);
            var foldercontents = Duplicati.Library.Utility.Utility.ParseBool(info.Request.QueryString["folder-contents"].Value, false);
            var time = new DateTime();
            if (!allversion)
                time = Duplicati.Library.Utility.Timeparser.ParseTimeInterval(timestring, DateTime.Now);

            var r = Runner.Run(Runner.CreateListTask(backup, filter, prefixonly, allversion, foldercontents, time), false) as Duplicati.Library.Interface.IListResults;

            var result = new Dictionary<string, object>();

            foreach(HttpServer.HttpInputItem n in info.Request.QueryString)
                result[n.Name] = n.Value;

            result["Filesets"] = r.Filesets;
            result["Files"] = r.Files;

            info.OutputOK(result);

        }
示例#14
0
        private void CreateFolder(string uri, RequestInfo info)
        {
            using(var b = Duplicati.Library.DynamicLoader.BackendLoader.GetBackend(uri, new Dictionary<string, string>()))
                b.CreateFolder();

            info.OutputOK();
        }
示例#15
0
        private void DoRepair(IBackup backup, RequestInfo info, bool repairUpdate)
        {
            var input = info.Request.Form;

            string[] filters = null;
            var      extra   = new Dictionary <string, string>();

            if (input["only-paths"].Value != null)
            {
                extra["repair-only-paths"] = (Library.Utility.Utility.ParseBool(input["only-paths"].Value, false)).ToString();
            }
            if (input["time"].Value != null)
            {
                extra["time"] = input["time"].Value;
            }
            if (input["version"].Value != null)
            {
                extra["version"] = input["version"].Value;
            }
            if (input["paths"].Value != null)
            {
                filters = parsePaths(input["paths"].Value);
            }

            var task = Runner.CreateTask(repairUpdate ? DuplicatiOperation.RepairUpdate : DuplicatiOperation.Repair, backup, extra, filters);

            Program.WorkThread.AddTask(task);
            Program.StatusEventNotifyer.SignalNewEvent();

            info.OutputOK(new { Status = "OK", ID = task.TaskID });
        }
示例#16
0
        public void GET(string key, RequestInfo info)
        {
            var  parts = (key ?? "").Split(new char[] { '/' }, 2);
            long taskid;

            if (long.TryParse(parts.FirstOrDefault(), out taskid))
            {
                var task  = Program.WorkThread.CurrentTask;
                var tasks = Program.WorkThread.CurrentTasks;

                if (task != null && task.TaskID == taskid)
                {
                    info.OutputOK(new { Status = "Running" });
                    return;
                }

                task = tasks.Where(x => x.TaskID == taskid).FirstOrDefault();
                if (tasks.Where(x => x.TaskID == taskid).FirstOrDefault() == null)
                {
                    KeyValuePair <long, Exception>[] matches;
                    lock (Program.MainLock)
                        matches = Program.TaskResultCache.Where(x => x.Key == taskid).ToArray();

                    if (matches.Length == 0)
                    {
                        info.ReportClientError("No such task found", System.Net.HttpStatusCode.NotFound);
                    }
                    else
                    {
                        info.OutputOK(new {
                            Status       = matches[0].Value == null ? "Completed" : "Failed",
                            ErrorMessage = matches[0].Value == null ? null : matches[0].Value.Message,
                            Exception    = matches[0].Value == null ? null : matches[0].Value.ToString()
                        });
                    }
                }
                else
                {
                    info.OutputOK(new { Status = "Waiting" });
                }
            }
            else
            {
                info.ReportClientError("Invalid request");
            }
        }
示例#17
0
 public void GET(string key, RequestInfo info)
 {
     var prop = typeof(Database.ApplicationSettings).GetProperty(key);
     if (prop == null)
         info.OutputError(null, System.Net.HttpStatusCode.NotFound, "Not found");
     else
         info.OutputOK(prop.GetValue(Program.DataConnection.ApplicationSettings));
 }
示例#18
0
 private void LocateDbUri(string uri, RequestInfo info)
 {
     var path = Library.Main.DatabaseLocator.GetDatabasePath(uri, null, false, false);
     info.OutputOK(new {
         Exists = !string.IsNullOrWhiteSpace(path),
         Path = path
     });
 }
示例#19
0
        private void Export(IBackup backup, RequestInfo info)
        {
            var cmdline         = Library.Utility.Utility.ParseBool(info.Request.QueryString["cmdline"].Value, false);
            var argsonly        = Library.Utility.Utility.ParseBool(info.Request.QueryString["argsonly"].Value, false);
            var exportPasswords = Library.Utility.Utility.ParseBool(info.Request.QueryString["export-passwords"].Value, false);

            if (!exportPasswords)
            {
                backup.SanitizeSettings();
                backup.SanitizeTargetUrl();
            }

            if (cmdline)
            {
                info.OutputOK(new { Command = Runner.GetCommandLine(Runner.CreateTask(DuplicatiOperation.Backup, backup)) });
            }
            else if (argsonly)
            {
                var parts = Runner.GetCommandLineParts(Runner.CreateTask(DuplicatiOperation.Backup, backup));

                info.OutputOK(new {
                    Backend   = parts.First(),
                    Arguments = parts.Skip(1).Where(x => !x.StartsWith("--", StringComparison.Ordinal)),
                    Options   = parts.Skip(1).Where(x => x.StartsWith("--", StringComparison.Ordinal))
                });
            }
            else
            {
                var    passphrase = info.Request.QueryString["passphrase"].Value;
                byte[] data       = Backup.ExportToJSON(backup, passphrase);

                string filename = Library.Utility.Uri.UrlEncode(backup.Name) + "-duplicati-config.json";
                if (!string.IsNullOrWhiteSpace(passphrase))
                {
                    filename += ".aes";
                }

                info.Response.ContentLength = data.Length;
                info.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", filename));
                info.Response.ContentType = "application/octet-stream";

                info.BodyWriter.SetOK();
                info.Response.SendHeaders();
                info.Response.SendBody(data);
            }
        }
示例#20
0
        public void POST(string key, RequestInfo info)
        {
            var input = info.Request.Form;

            switch ((key ?? "").ToLowerInvariant())
            {
            case "pause":
                if (input.Contains("duration") && !string.IsNullOrWhiteSpace(input["duration"].Value))
                {
                    TimeSpan ts;
                    try
                    {
                        ts = Library.Utility.Timeparser.ParseTimeSpan(input["duration"].Value);
                    }
                    catch (Exception ex)
                    {
                        info.ReportClientError(ex.Message, System.Net.HttpStatusCode.BadRequest);
                        return;
                    }
                    if (ts.TotalMilliseconds > 0)
                    {
                        Program.LiveControl.Pause(ts);
                    }
                    else
                    {
                        Program.LiveControl.Pause();
                    }
                }
                else
                {
                    Program.LiveControl.Pause();
                }

                info.OutputOK();
                return;

            case "resume":
                Program.LiveControl.Resume();
                info.OutputOK();
                return;

            default:
                info.ReportClientError("No such action", System.Net.HttpStatusCode.NotFound);
                return;
            }
        }
示例#21
0
 public void GET(string key, RequestInfo info)
 {
     var path = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "acknowledgements.txt");
     info.OutputOK(new GetResponse() {
         Status = "OK",
         Acknowledgements = System.IO.File.ReadAllText(path)
     });            
 }
示例#22
0
        private void Compact(IBackup backup, RequestInfo info)
        {
            var task = Runner.CreateTask(DuplicatiOperation.Compact, backup);

            Program.WorkThread.AddTask(task);
            Program.StatusEventNotifyer.SignalNewEvent();

            info.OutputOK(new { Status = "OK", ID = task.TaskID });
        }
示例#23
0
        private void LocateDbUri(string uri, RequestInfo info)
        {
            var path = Library.Main.DatabaseLocator.GetDatabasePath(uri, null, false, false);

            info.OutputOK(new {
                Exists = !string.IsNullOrWhiteSpace(path),
                Path   = path
            });
        }
示例#24
0
        public void GET(string key, RequestInfo info)
        {
            bool isError;
            long id = 0;
            long.TryParse(key, out id);

            if (info.LongPollCheck(Program.StatusEventNotifyer, ref id, out isError))
            {
                //Make sure we do not report a higher number than the eventnotifyer says
                var st = new Serializable.ServerStatus();
                st.LastEventID = id;
                info.OutputOK(st);
            }
            else if (!isError)
            {
                info.OutputOK(new Serializable.ServerStatus());
            }
        }
        public void POST(string key, RequestInfo info)
        {
            switch ((key ?? "").ToLowerInvariant())
            {
            case "suppressdonationmessages":
                Library.Main.Utility.SuppressDonationMessages = true;
                info.OutputOK();
                return;

            case "showdonationmessages":
                Library.Main.Utility.SuppressDonationMessages = false;
                info.OutputOK();
                return;

            default:
                info.ReportClientError("No such action", System.Net.HttpStatusCode.NotFound);
                return;
            }
        }
示例#26
0
        public void POST(string key, RequestInfo info)
        {
            var  parts = (key ?? "").Split(new char[] { '/' }, 2);
            long taskid;

            if (parts.Length == 2 && long.TryParse(parts.First(), out taskid))
            {
                var task  = Program.WorkThread.CurrentTask;
                var tasks = Program.WorkThread.CurrentTasks;

                if (task != null)
                {
                    tasks.Insert(0, task);
                }

                task = tasks.FirstOrDefault(x => x.TaskID == taskid);
                if (task == null)
                {
                    info.ReportClientError("No such task", System.Net.HttpStatusCode.NotFound);
                    return;
                }

                switch (parts.Last().ToLowerInvariant())
                {
                case "stopaftercurrentfile":
                    task.Stop(allowCurrentFileToFinish: true);
                    info.OutputOK();
                    return;

                case "stopnow":
                    task.Stop(allowCurrentFileToFinish: false);
                    info.OutputOK();
                    return;

                case "abort":
                    task.Abort();
                    info.OutputOK();
                    return;
                }
            }

            info.ReportClientError("Invalid or missing task id", System.Net.HttpStatusCode.NotFound);
        }
示例#27
0
        public void GET(string key, RequestInfo info)
        {
            var path = SystemIO.IO_OS.PathCombine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "acknowledgements.txt");

            info.OutputOK(new GetResponse()
            {
                Status           = "OK",
                Acknowledgements = System.IO.File.ReadAllText(path)
            });
        }
示例#28
0
        public void GET(string key, RequestInfo info)
        {
            bool isError;
            long id = 0;

            long.TryParse(key, out id);

            if (info.LongPollCheck(Program.StatusEventNotifyer, ref id, out isError))
            {
                //Make sure we do not report a higher number than the eventnotifyer says
                var st = new Serializable.ServerStatus();
                st.LastEventID = id;
                info.OutputOK(st);
            }
            else if (!isError)
            {
                info.OutputOK(new Serializable.ServerStatus());
            }
        }
示例#29
0
 public void GET(string key, RequestInfo info)
 {
     if (Program.GenerateProgressState == null)
     {
         info.ReportClientError("No active backup", System.Net.HttpStatusCode.NotFound);
     }
     else
     {
         info.OutputOK(Program.GenerateProgressState());
     }
 }
示例#30
0
 public void GET(string key, RequestInfo info)
 {
     if (Program.GenerateProgressState == null)
     {
         info.ReportClientError("No active backup");
     }
     else
     {
         info.OutputOK(Program.GenerateProgressState());
     }
 }
示例#31
0
        public void POST(string key, RequestInfo info)
        {
            var input = info.Request.Form;
            switch ((key ?? "").ToLowerInvariant())
            {
                case "suppressdonationmessages":
                    Library.Main.Utility.SuppressDonationMessages = true;
                    info.OutputOK();
                    return;

                case "showdonationmessages":
                    Library.Main.Utility.SuppressDonationMessages = false;
                    info.OutputOK();
                    return;

                default:
                    info.ReportClientError("No such action", System.Net.HttpStatusCode.NotFound);
                    return;
            }
        }
示例#32
0
 public void GET(string key, RequestInfo info)
 {
     try
     {
         info.OutputOK(new HyperVUtility().GetHyperVGuests().Select(x => new { id = x.ID, name = x.Name }).ToList());
     }
     catch (Exception ex)
     {
         info.ReportClientError("Failed to enumerate Hyper-V virtual machines: " + ex.Message);
     }
 }
示例#33
0
        private void FetchLogData(IBackup backup, RequestInfo info)
        {
            using (var con = (System.Data.IDbConnection)Activator.CreateInstance(Duplicati.Library.SQLiteHelper.SQLiteLoader.SQLiteConnectionType))
            {
                con.ConnectionString = "Data Source=" + backup.DBPath;
                con.Open();

                using (var cmd = con.CreateCommand())
                    info.OutputOK(LogData.DumpTable(cmd, "LogData", "ID", info.Request.QueryString["offset"].Value, info.Request.QueryString["pagesize"].Value));
            }
        }
示例#34
0
        public void GET(string key, RequestInfo info)
        {
            var parts = (key ?? "").Split(new char[] { '/' }, 2);
            long taskid;
            if (parts.Length == 2 && long.TryParse(parts.First(), out taskid))
            {
                var task = Program.WorkThread.CurrentTask;
                var tasks = Program.WorkThread.CurrentTasks;

                if (task != null && task.TaskID == taskid)
                {
                    info.OutputOK(new { Status = "Running" });
                    return;
                }

                task = tasks.Where(x => x.TaskID == taskid).FirstOrDefault();
                if (tasks.Where(x => x.TaskID == taskid).FirstOrDefault() == null)
                {
                    KeyValuePair<long, Exception>[] matches;
                    lock(Program.MainLock)
                        matches = Program.TaskResultCache.Where(x => x.Key == taskid).ToArray();

                    if (matches.Length == 0)
                        info.ReportClientError("No such task found", System.Net.HttpStatusCode.NotFound);
                    else
                        info.OutputOK(new {
                            Status = matches[0].Value == null ? "Completed" : "Failed",
                            ErrorMessage = matches[0].Value == null ? null : matches[0].Value.Message,
                            Exception = matches[0].Value == null ? null : matches[0].Value.ToString()
                        });
                }
                else
                {
                    info.OutputOK(new { Status = "Waiting" });
                }
            }
            else
            {
                info.ReportClientError("Invalid request");
            }
        }
示例#35
0
        public void POST(string key, RequestInfo info)
        {
            var input = info.Request.Form;
            switch ((key ?? "").ToLowerInvariant())
            {
                case "pause":
                    if (input.Contains("duration") && !string.IsNullOrWhiteSpace(input["duration"].Value))
                    {
                        TimeSpan ts;
                        try
                        {
                            ts = Library.Utility.Timeparser.ParseTimeSpan(input["duration"].Value);
                        }
                        catch (Exception ex)
                        {
                            info.ReportClientError(ex.Message);
                            return;
                        }
                        if (ts.TotalMilliseconds > 0)
                            Program.LiveControl.Pause(ts);
                        else
                            Program.LiveControl.Pause();
                    }
                    else
                    {
                        Program.LiveControl.Pause();
                    }

                    info.OutputOK();
                    return;

                case "resume":
                    Program.LiveControl.Resume();
                    info.OutputOK();
                    return;
                    
                default:
                    info.ReportClientError("No such action", System.Net.HttpStatusCode.NotFound);
                    return;
            }
        }
示例#36
0
        private void TestConnection(string url, RequestInfo info)
        {
            var modules = (from n in Library.DynamicLoader.GenericLoader.Modules
                           where n is Library.Interface.IConnectionModule
                           select n).ToArray();

            try
            {
                var uri = new Library.Utility.Uri(url);
                var qp  = uri.QueryParameters;

                var opts = new Dictionary <string, string>();
                foreach (var k in qp.Keys.Cast <string>())
                {
                    opts[k] = qp[k];
                }

                foreach (var n in modules)
                {
                    n.Configure(opts);
                }

                using (var b = Duplicati.Library.DynamicLoader.BackendLoader.GetBackend(url, new Dictionary <string, string>()))
                    b.Test();

                info.OutputOK();
            }
            catch (Duplicati.Library.Interface.FolderMissingException)
            {
                info.ReportServerError("missing-folder");
            }
            catch (Duplicati.Library.Utility.SslCertificateValidator.InvalidCertificateException icex)
            {
                if (string.IsNullOrWhiteSpace(icex.Certificate))
                {
                    info.ReportServerError(icex.Message);
                }
                else
                {
                    info.ReportServerError("incorrect-cert:" + icex.Certificate);
                }
            }
            finally
            {
                foreach (var n in modules)
                {
                    if (n is IDisposable)
                    {
                        ((IDisposable)n).Dispose();
                    }
                }
            }
        }
示例#37
0
        public void GET(string key, RequestInfo info)
        {
            var cur = Program.WorkThread.CurrentTask;
            var n   = Program.WorkThread.CurrentTasks;

            if (cur != null)
            {
                n.Insert(0, cur);
            }

            info.OutputOK(n);
        }
示例#38
0
文件: MSSQL.cs 项目: kevinv12/test
 public void GET(string key, RequestInfo info)
 {
     // Early exit in case we are non-windows to prevent attempting to load Windows-only components
     if (Platform.IsClientWindows)
     {
         RealGET(key, info);
     }
     else
     {
         info.OutputOK(new string[0]);
     }
 }
示例#39
0
        public void GET(string key, RequestInfo info)
        {
            var prop = typeof(Database.ApplicationSettings).GetProperty(key);

            if (prop == null)
            {
                info.OutputError(null, System.Net.HttpStatusCode.NotFound, "Not found");
            }
            else
            {
                info.OutputOK(prop.GetValue(Program.DataConnection.ApplicationSettings));
            }
        }
示例#40
0
 public void PUT(string key, RequestInfo info)
 {
     var prop = typeof(Database.ApplicationSettings).GetProperty(key);
     if (prop == null)
         info.OutputError(null, System.Net.HttpStatusCode.NotFound, "Not found");
     else
     {
         var dict = new Dictionary<string, string>();
         dict[key] = info.Request.Form["data"].Value;
         Program.DataConnection.ApplicationSettings.UpdateSettings(dict, false);
         info.OutputOK();
     }
 }
示例#41
0
        private void ListFileSets(IBackup backup, RequestInfo info)
        {
            var input = info.Request.QueryString;
            var extra = new Dictionary<string, string>();
            extra["list-sets-only"] = "true";
            if (input["include-metadata"].Value != null)
                extra["list-sets-only"] = (!Library.Utility.Utility.ParseBool(input["include-metadata"].Value, false)).ToString();
            if (input["from-remote-only"].Value != null)
                extra["no-local-db"] = Library.Utility.Utility.ParseBool(input["from-remote-only"].Value, false).ToString();

            var r = Runner.Run(Runner.CreateTask(DuplicatiOperation.List, backup, extra), false) as Duplicati.Library.Interface.IListResults;

            info.OutputOK(r.Filesets);
        }
示例#42
0
        private void Export(IBackup backup, RequestInfo info)
        {
            var cmdline = Library.Utility.Utility.ParseBool(info.Request.QueryString["cmdline"].Value, false);

            if (cmdline)
            {
                info.OutputOK(new { Command = Runner.GetCommandLine(Runner.CreateTask(DuplicatiOperation.Backup, backup)) });
            }
            else
            {
                var passphrase = info.Request.QueryString["passphrase"].Value;
                var ipx        = Program.DataConnection.PrepareBackupForExport(backup);

                byte[] data;
                using (var ms = new System.IO.MemoryStream())
                    using (var sw = new System.IO.StreamWriter(ms))
                    {
                        Serializer.SerializeJson(sw, ipx, true);

                        if (!string.IsNullOrWhiteSpace(passphrase))
                        {
                            ms.Position = 0;
                            using (var ms2 = new System.IO.MemoryStream())
                                using (var m = new Duplicati.Library.Encryption.AESEncryption(passphrase, new Dictionary <string, string>()))
                                {
                                    m.Encrypt(ms, ms2);
                                    data = ms2.ToArray();
                                }
                        }
                        else
                        {
                            data = ms.ToArray();
                        }
                    }

                var filename = Library.Utility.Uri.UrlEncode(backup.Name) + "-duplicati-config.json";
                if (!string.IsNullOrWhiteSpace(passphrase))
                {
                    filename += ".aes";
                }

                info.Response.ContentLength = data.Length;
                info.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", filename));
                info.Response.ContentType = "application/octet-stream";

                info.BodyWriter.SetOK();
                info.Response.SendHeaders();
                info.Response.SendBody(data);
            }
        }
示例#43
0
文件: Tags.cs 项目: kevinv12/test
        public void GET(string key, RequestInfo info)
        {
            var r =
                from n in
                Serializable.ServerSettings.CompressionModules
                .Union(Serializable.ServerSettings.EncryptionModules)
                .Union(Serializable.ServerSettings.BackendModules)
                .Union(Serializable.ServerSettings.GenericModules)
                select n.Key.ToLower(CultureInfo.InvariantCulture);

            // Append all known tags
            r = r.Union(from n in Program.DataConnection.Backups select n.Tags into p from x in p select x.ToLower(CultureInfo.InvariantCulture));
            info.OutputOK(r);
        }
示例#44
0
文件: MSSQL.cs 项目: kevinv12/test
        private void RealGET(string key, RequestInfo info)
        {
            var mssqlUtility = new MSSQLUtility();

            if (!mssqlUtility.IsMSSQLInstalled || !new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator))
            {
                info.OutputOK(new string[0]);
                return;
            }

            try
            {
                mssqlUtility.QueryDBsInfo();

                if (string.IsNullOrEmpty(key))
                {
                    info.OutputOK(mssqlUtility.DBs.Select(x => new { id = x.ID, name = x.Name }).ToList());
                }
                else
                {
                    var foundDBs = mssqlUtility.DBs.FindAll(x => x.ID.Equals(key, StringComparison.OrdinalIgnoreCase));

                    if (foundDBs.Count == 1)
                    {
                        info.OutputOK(foundDBs[0].DataPaths.Select(x => new { text = x, id = x, cls = "folder", iconCls = "x-tree-icon-leaf", check = "false", leaf = "true" }).ToList());
                    }
                    else
                    {
                        info.ReportClientError(string.Format("Cannot find DB with ID {0}.", key), System.Net.HttpStatusCode.NotFound);
                    }
                }
            }
            catch (Exception ex)
            {
                info.ReportServerError("Failed to enumerate Microsoft SQL Server databases: " + ex.Message);
            }
        }
示例#45
0
        private void UploadFile(string uri, RequestInfo info)
        {
            var data = info.Request.QueryString["data"].Value;
            var remotename = info.Request.QueryString["filename"].Value;

            using(var ms = new System.IO.MemoryStream())   
            using(var b = Duplicati.Library.DynamicLoader.BackendLoader.GetBackend(uri, new Dictionary<string, string>()))
            {
                using(var tf = new Duplicati.Library.Utility.TempFile())
                {
                    System.IO.File.WriteAllText(tf, data);
                    b.Put(remotename, tf);
                }
            }

            info.OutputOK();
        }
示例#46
0
        public void GET(string key, RequestInfo info)
        {
            // Start with a scratch object
            var o = new Newtonsoft.Json.Linq.JObject();

            // Add application wide settings
            o.Add("ApplicationOptions", new Newtonsoft.Json.Linq.JArray(
                from n in Program.DataConnection.Settings
                select Newtonsoft.Json.Linq.JObject.FromObject(n)
            ));

            try
            {
                // Add built-in defaults
                Newtonsoft.Json.Linq.JObject n;
                using(var s = new System.IO.StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + ".newbackup.json")))
                    n = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(s.ReadToEnd());

                MergeJsonObjects(o, n);
            }
            catch
            {
            }

            try
            {
                // Add install defaults/overrides, if present
                var path = System.IO.Path.Combine(Duplicati.Library.AutoUpdater.UpdaterManager.InstalledBaseDir, "newbackup.json");
                if (System.IO.File.Exists(path))
                {
                    Newtonsoft.Json.Linq.JObject n;
                    n = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(System.IO.File.ReadAllText(path));

                    MergeJsonObjects(o, n);
                }
            }
            catch
            {
            }

            info.OutputOK(new
            {
                success = true,
                data = o
            });
        }
示例#47
0
        private void TestConnection(string url, RequestInfo info)
        {
            
            var modules = (from n in Library.DynamicLoader.GenericLoader.Modules
                where n is Library.Interface.IConnectionModule
                select n).ToArray();

            try
            {
                var uri = new Library.Utility.Uri(url);
                var qp = uri.QueryParameters;

                var opts = new Dictionary<string, string>();
                foreach(var k in qp.Keys.Cast<string>())
                    opts[k] = qp[k];

                foreach(var n in modules)
                    n.Configure(opts);
                    
                using(var b = Duplicati.Library.DynamicLoader.BackendLoader.GetBackend(url, new Dictionary<string, string>()))
                    b.Test();
                
                info.OutputOK();
            }
            catch (Duplicati.Library.Interface.FolderMissingException)
            {
                info.ReportServerError("missing-folder");
            }
            catch (Duplicati.Library.Utility.SslCertificateValidator.InvalidCertificateException icex)
            {
                if (string.IsNullOrWhiteSpace(icex.Certificate))
                    info.ReportServerError(icex.Message);
                else
                    info.ReportServerError("incorrect-cert:" + icex.Certificate);
            }
            finally
            {
                foreach(var n in modules)
                    if (n is IDisposable)
                        ((IDisposable)n).Dispose();
            }
        }
示例#48
0
        public void POST(string key, RequestInfo info)
        {
            if ("import".Equals(key, StringComparison.InvariantCultureIgnoreCase))
            {
                ImportBackup(info);
                return;
            }

            AddOrUpdateBackupData data = null;
            try
            {
                data = Serializer.Deserialize<AddOrUpdateBackupData>(new StringReader(info.Request.Form["data"].Value));
                if (data.Backup == null)
                {
                    info.ReportClientError("Data object had no backup entry");
                    return;
                }

                data.Backup.ID = null;

                if (Duplicati.Library.Utility.Utility.ParseBool(info.Request.Form["temporary"].Value, false))
                {
                    using(var tf = new Duplicati.Library.Utility.TempFile())
                        data.Backup.DBPath = tf;

                    Program.DataConnection.RegisterTemporaryBackup(data.Backup);

                    info.OutputOK(new { status = "OK", ID = data.Backup.ID });
                }
                else
                {
                    if (Library.Utility.Utility.ParseBool(info.Request.Form["existing_db"].Value, false))
                    {
                        data.Backup.DBPath = Library.Main.DatabaseLocator.GetDatabasePath(data.Backup.TargetURL, null, false, false);
                        if (string.IsNullOrWhiteSpace(data.Backup.DBPath))
                            throw new Exception("Unable to find remote db path?");
                    }

                    lock(Program.DataConnection.m_lock)
                    {
                        if (Program.DataConnection.Backups.Where(x => x.Name.Equals(data.Backup.Name, StringComparison.InvariantCultureIgnoreCase)).Any())
                        {
                            info.ReportClientError("There already exists a backup with the name: " + data.Backup.Name);
                            return;
                        }

                        Program.DataConnection.AddOrUpdateBackupAndSchedule(data.Backup, data.Schedule);
                    }

                    info.OutputOK(new { status = "OK", ID = data.Backup.ID });
                }
            }
            catch (Exception ex)
            {
                if (data == null)
                    info.ReportClientError(string.Format("Unable to parse backup or schedule object: {0}", ex.Message));
                else
                    info.ReportClientError(string.Format("Unable to save schedule or backup object: {0}", ex.Message));
            }
        }
示例#49
0
        public void DELETE(string key, RequestInfo info)
        {
            var backup = Program.DataConnection.GetBackup(key);
            if (backup == null)
            {
                info.ReportClientError("Invalid or missing backup id");
                return;
            }

            if (Program.WorkThread.Active)
            {
                try
                {
                    //TODO: It's not safe to access the values like this,
                    //because the runner thread might interfere
                    var nt = Program.WorkThread.CurrentTask;
                    if (backup.Equals(nt == null ? null : nt.Backup))
                    {
                        bool force;
                        if (!bool.TryParse(info.Request.QueryString["force"].Value, out force))
                            force = false;

                        if (!force)
                        {
                            info.OutputError(new { status = "failed", reason = "backup-in-progress" });
                            return;
                        }

                        bool hasPaused = Program.LiveControl.State == LiveControls.LiveControlState.Paused;
                        Program.LiveControl.Pause();

                        try
                        {
                            for(int i = 0; i < 10; i++)
                                if (Program.WorkThread.Active)
                                {
                                    var t = Program.WorkThread.CurrentTask;
                                    if (backup.Equals(t == null ? null : t.Backup))
                                        System.Threading.Thread.Sleep(1000);
                                    else
                                        break;
                                }
                                else
                                    break;
                        }
                        finally
                        {
                        }

                        if (Program.WorkThread.Active)
                        {
                            var t = Program.WorkThread.CurrentTask;
                            if (backup.Equals(t == null ? null : t.Backup))
                            {
                                if (hasPaused)
                                    Program.LiveControl.Resume();
                                info.OutputError(new { status = "failed", reason = "backup-unstoppable" });
                                return;
                            }
                        }

                        if (hasPaused)
                            Program.LiveControl.Resume();
                    }
                }
                catch (Exception ex)
                {
                    info.OutputError(new { status = "error", message = ex.Message });
                    return;
                }
            }

            //var dbpath = backup.DBPath;
            Program.DataConnection.DeleteBackup(backup);

            // TODO: Before we activate this,
            // we need some strategy to figure out
            // if the db is shared with something else
            // like the commandline or another backup
            /*try
            {
                if (System.IO.File.Exists(dbpath))
                    System.IO.File.Delete(dbpath);
            }
            catch (Exception ex)
            {
                Program.DataConnection.LogError(null, string.Format("Failed to delete database: {0}", dbpath), ex);
            }*/

            //We have fiddled with the schedules
            Program.Scheduler.Reschedule();

            info.OutputOK();
        }
示例#50
0
     info.ReportClientError("Invalid ID");
     return;
 }
 var el = Program.DataConnection.GetNotifications().Where(x => x.ID == id).FirstOrDefault();
示例#51
0
 public class ServerState : IRESTMethodGET, IRESTMethodPOST, IRESTMethodDocumented
示例#52
0
        private void Verify(IBackup backup, RequestInfo info)
        {
            var task = Runner.CreateTask(DuplicatiOperation.Verify, backup);
            Program.WorkThread.AddTask(task);
            Program.StatusEventNotifyer.SignalNewEvent();

            info.OutputOK(new {Status = "OK", ID = task.TaskID});
        }
示例#53
0
 public void GET(string key, RequestInfo info)
 {
     if (string.IsNullOrWhiteSpace(key))
     {
示例#54
0
 {
     public void POST(string key, RequestInfo info)
     {
示例#55
0
{
示例#56
0
        private void RunBackup(IBackup backup, RequestInfo info)
        {
            var t = Program.WorkThread.CurrentTask;
            var bt = t == null ? null : t.Backup;
            if (bt != null && backup.ID == bt.ID)
            {
                // Already running
            }
            else if (Program.WorkThread.CurrentTasks.Where(x => {
                var bn = x == null ? null : x.Backup;
                return bn == null || bn.ID == backup.ID;
            }).Any())
            {
                // Already in queue
            }
            else
            {
                Program.WorkThread.AddTask(Runner.CreateTask(DuplicatiOperation.Backup, backup));
                Program.StatusEventNotifyer.SignalNewEvent();
            }

            info.OutputOK();
        }
示例#57
0
 }
 else
 {
     info.OutputOK(Program.DataConnection.GetUISettings(key));
示例#58
0
 private void IsActive(IBackup backup, RequestInfo info)
 {
     var t = Program.WorkThread.CurrentTask;
     var bt = t == null ? null : t.Backup;
     if (bt != null && backup.ID == bt.ID)
     {
         info.OutputOK(new { Status = "OK", Active = true });
         return;
     }
     else if (Program.WorkThread.CurrentTasks.Where(x =>
     {
         var bn = x == null ? null : x.Backup;
         return bn == null || bn.ID == backup.ID;
     }).Any())
     {
         info.OutputOK(new { Status = "OK", Active = true });
         return;
     }
     else
     {
         info.OutputOK(new { Status = "OK", Active = false });
         return;
     }
 }
示例#59
0
        private void RestoreFiles(IBackup backup, RequestInfo info)
        {
            var input = info.Request.Form;

            var filters = input["paths"].Value.Split(new string[] { System.IO.Path.PathSeparator.ToString() }, StringSplitOptions.RemoveEmptyEntries);
            var time = Duplicati.Library.Utility.Timeparser.ParseTimeInterval(input["time"].Value, DateTime.Now);
            var restoreTarget = input["restore-path"].Value;
            var overwrite = Duplicati.Library.Utility.Utility.ParseBool(input["overwrite"].Value, false);

            var permissions = Duplicati.Library.Utility.Utility.ParseBool(input["permissions"].Value, false);
            var skip_metadata = Duplicati.Library.Utility.Utility.ParseBool(input["skip-metadata"].Value, false);

            var task = Runner.CreateRestoreTask(backup, filters, time, restoreTarget, overwrite, permissions, skip_metadata);

            Program.WorkThread.AddTask(task);

            info.OutputOK(new { TaskID = task.TaskID });
        }
示例#60
0
 public void GET(string key, RequestInfo info)
 {
     var cur = Program.WorkThread.CurrentTask;
     var n = Program.WorkThread.CurrentTasks;