From 037d907028ef9baa87b3c0d8a06bf800ef7bfc48 Mon Sep 17 00:00:00 2001 From: kaso17 Date: Thu, 10 Nov 2016 09:06:35 +0100 Subject: [PATCH] Make the config saving process more robust (#670) --- src/Jackett/Services/IndexerManagerService.cs | 52 ++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/src/Jackett/Services/IndexerManagerService.cs b/src/Jackett/Services/IndexerManagerService.cs index 6bd490b8d..0645a416d 100644 --- a/src/Jackett/Services/IndexerManagerService.cs +++ b/src/Jackett/Services/IndexerManagerService.cs @@ -148,10 +148,60 @@ namespace Jackett.Services public void SaveConfig(IIndexer indexer, JToken obj) { + var uID = Guid.NewGuid().ToString("N"); var configFilePath = GetIndexerConfigFilePath(indexer); + var configFilePathBak = configFilePath + ".bak"; + var configFilePathTmp = configFilePath + "." + uID + ".tmp"; + var content = obj.ToString(); + + logger.Debug(string.Format("Saving new config file: {0}", configFilePathTmp)); + + if (string.IsNullOrWhiteSpace(content)) + { + throw new Exception(string.Format("New config content for {0} is empty, please report this bug.", indexer.ID)); + } + + if (content.Contains("NULL")) + { + throw new Exception(string.Format("New config content for {0} contains NULL, please report this bug. Content: {1}", indexer.ID, content)); + } + + // make sure the config directory exists if (!Directory.Exists(configService.GetIndexerConfigDir())) Directory.CreateDirectory(configService.GetIndexerConfigDir()); - File.WriteAllText(configFilePath, obj.ToString()); + + // create new temporary config file + File.WriteAllText(configFilePathTmp, content); + var fileInfo = new FileInfo(configFilePathTmp); + if (fileInfo.Length == 0) + { + throw new Exception(string.Format("New config file {0} is empty, please report this bug.", configFilePathTmp)); + } + + // create backup file + File.Delete(configFilePathBak); + if (File.Exists(configFilePath)) + { + try + { + File.Move(configFilePath, configFilePathBak); + } + catch (IOException ex) + { + logger.Error(string.Format("Error while moving {0} to {1}: {2}", configFilePath, configFilePathBak, ex.ToString())); + } + } + + // replace the actual config file + File.Delete(configFilePath); + try + { + File.Move(configFilePathTmp, configFilePath); + } + catch (IOException ex) + { + logger.Error(string.Format("Error while moving {0} to {1}: {2}", configFilePath, configFilePathBak, ex.ToString())); + } } } }