File: AppConfigSerializer.cs

package info (click to toggle)
keepass2 2.41%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 13,892 kB
  • sloc: cs: 103,600; xml: 5,869; cpp: 308; sh: 48; makefile: 46
file content (446 lines) | stat: -rw-r--r-- 12,824 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
/*
  KeePass Password Safe - The Open-Source Password Manager
  Copyright (C) 2003-2019 Dominik Reichl <dominik.reichl@t-online.de>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml;

using KeePass.Resources;
using KeePass.Util;
using KeePass.Util.XmlSerialization;

using KeePassLib;
using KeePassLib.Serialization;
using KeePassLib.Utility;

namespace KeePass.App.Configuration
{
	public static class AppConfigSerializer
	{
		private static string m_strBaseName = null; // Null prop allowed

		private static string m_strCreateDir = null;
		private static string m_strCreateDirLocal = null;
		private static string m_strEnforcedConfigFile = null;
		private static string m_strGlobalConfigFile = null;
		private static string m_strUserConfigFile = null;

		public static string AppDataDirectory
		{
			get
			{
				AppConfigSerializer.GetConfigPaths();
				return m_strCreateDir;
			}
		}

		public static string LocalAppDataDirectory
		{
			get
			{
				AppConfigSerializer.GetConfigPaths();
				return m_strCreateDirLocal;
			}
		}

		/// <summary>
		/// Get/set the base name for the configuration. If this property is
		/// <c>null</c>, the class constructs names based on the current
		/// assembly and the product name.
		/// </summary>
		public static string BaseName
		{
			get { return m_strBaseName; }

			set
			{
				m_strBaseName = value;

				m_strCreateDir = null; // Invalidate paths
				m_strCreateDirLocal = null;
				m_strEnforcedConfigFile = null;
				m_strGlobalConfigFile = null;
				m_strUserConfigFile = null;
			}
		}

		private static XmlDocument m_xdEnforced = null;
		public static XmlDocument EnforcedConfigXml
		{
			get { return m_xdEnforced; }
		}

		private static void GetConfigPaths()
		{
			if(m_strGlobalConfigFile == null)
			{
				Assembly asm = Assembly.GetExecutingAssembly();
				Debug.Assert(asm != null); if(asm == null) return;

#if !KeePassLibSD
				string strFile = null;

				try { strFile = asm.Location; }
				catch(Exception) { }

				if(string.IsNullOrEmpty(strFile))
					strFile = UrlUtil.FileUrlToPath(asm.GetName().CodeBase);
#else
				string strFile = UrlUtil.FileUrlToPath(asm.GetName().CodeBase);
#endif
				Debug.Assert(strFile != null); if(strFile == null) return;

				if(string.IsNullOrEmpty(m_strBaseName))
				{
					// Remove assembly extension
					if(strFile.EndsWith(".exe", StrUtil.CaseIgnoreCmp))
						strFile = strFile.Substring(0, strFile.Length - 4);
					else if(strFile.EndsWith(".dll", StrUtil.CaseIgnoreCmp))
						strFile = strFile.Substring(0, strFile.Length - 4);
				}
				else // Base name != null
					strFile = UrlUtil.GetFileDirectory(strFile, true, false) + m_strBaseName;

				m_strGlobalConfigFile = strFile + ".config.xml";
				m_strEnforcedConfigFile = strFile + ".config.enforced.xml";
			}

			if(m_strUserConfigFile == null)
			{
				string strBaseDirName = PwDefs.ShortProductName;
				if((m_strBaseName != null) && (m_strBaseName.Length > 0))
					strBaseDirName = m_strBaseName;

				string strUserDir;
				try
				{
					strUserDir = Environment.GetFolderPath(
						Environment.SpecialFolder.ApplicationData);
				}
				catch(Exception)
				{
					strUserDir = UrlUtil.GetFileDirectory(UrlUtil.FileUrlToPath(
						Assembly.GetExecutingAssembly().GetName().CodeBase), true, false);
				}
				strUserDir = UrlUtil.EnsureTerminatingSeparator(strUserDir, false);

				string strUserDirLocal;
				try
				{
					strUserDirLocal = Environment.GetFolderPath(
						Environment.SpecialFolder.LocalApplicationData);
				}
				catch(Exception) { strUserDirLocal = strUserDir; }
				strUserDirLocal = UrlUtil.EnsureTerminatingSeparator(strUserDirLocal, false);

				m_strCreateDir = strUserDir + strBaseDirName;
				m_strCreateDirLocal = strUserDirLocal + strBaseDirName;
				m_strUserConfigFile = UrlUtil.EnsureTerminatingSeparator(
					m_strCreateDir, false) + strBaseDirName + ".config.xml";
			}

			string strLocalOvr = Program.CommandLineArgs[
				AppDefs.CommandLineOptions.ConfigPathLocal];
			if(!string.IsNullOrEmpty(strLocalOvr))
			{
				string strWD = UrlUtil.EnsureTerminatingSeparator(
					WinUtil.GetWorkingDirectory(), false);
				m_strUserConfigFile = UrlUtil.MakeAbsolutePath(strWD +
					"Sentinel.txt", strLocalOvr);
				// Do not change m_strCreateDir, as it's returned from
				// the AppDataDirectory property
			}

			Debug.Assert(!string.IsNullOrEmpty(m_strCreateDir));
		}

		private static void EnsureAppDataDirAvailable(string strForFile)
		{
			if(string.IsNullOrEmpty(strForFile)) { Debug.Assert(false); return; }
			if(string.IsNullOrEmpty(m_strCreateDir)) { Debug.Assert(false); return; }

			string strPre = UrlUtil.EnsureTerminatingSeparator(m_strCreateDir, false);
			if(!strForFile.StartsWith(strPre, StrUtil.CaseIgnoreCmp)) return;

			try
			{
				if(!Directory.Exists(m_strCreateDir))
					Directory.CreateDirectory(m_strCreateDir);
			}
			catch(Exception) { Debug.Assert(false); }
		}

		private static XmlDocument LoadEnforcedConfigFile()
		{
#if DEBUG
			Stopwatch sw = Stopwatch.StartNew();
#endif

			m_xdEnforced = null;
			try
			{
				// Performance optimization
				if(!File.Exists(m_strEnforcedConfigFile)) return null;

				XmlDocument xmlDoc = XmlUtilEx.CreateXmlDocument();
				xmlDoc.Load(m_strEnforcedConfigFile);

				m_xdEnforced = xmlDoc;
				return xmlDoc;
			}
			catch(Exception) { Debug.Assert(false); }
#if DEBUG
			finally
			{
				sw.Stop();
			}
#endif

			return null;
		}

		private static AppConfigEx LoadConfigFileEx(string strFilePath,
			XmlDocument xdEnforced)
		{
			if(string.IsNullOrEmpty(strFilePath)) return null;

			AppConfigEx tConfig = null;
			XmlSerializerEx xmlSerial = new XmlSerializerEx(typeof(AppConfigEx));

			if(xdEnforced == null)
			{
				try
				{
					using(FileStream fs = new FileStream(strFilePath,
						FileMode.Open, FileAccess.Read, FileShare.Read))
					{
						tConfig = (AppConfigEx)xmlSerial.Deserialize(fs);
					}
				}
				catch(Exception) { } // Do not assert
			}
			else // Enforced configuration
			{
				try
				{
					XmlDocument xd = XmlUtilEx.CreateXmlDocument();
					xd.Load(strFilePath);

					XmlUtil.MergeNodes(xd, xd.DocumentElement, xdEnforced.DocumentElement);

					using(MemoryStream msAsm = new MemoryStream())
					{
						xd.Save(msAsm);

						using(MemoryStream msRead = new MemoryStream(
							msAsm.ToArray(), false))
						{
							tConfig = (AppConfigEx)xmlSerial.Deserialize(msRead);
						}
					}
				}
				catch(FileNotFoundException) { }
				catch(Exception) { Debug.Assert(false); }
			}

			if(tConfig != null) tConfig.OnLoad();

			return tConfig;
		}

		public static AppConfigEx Load()
		{
			AppConfigSerializer.GetConfigPaths();

			// AppConfigEx cfgEnf = LoadConfigFileEx(m_strEnforcedConfigFile);
			// if(cfgEnf != null)
			// {
			//	cfgEnf.Meta.IsEnforcedConfiguration = true;
			//	return cfgEnf;
			// }
			XmlDocument xdEnforced = LoadEnforcedConfigFile();

			AppConfigEx cfgGlobal = LoadConfigFileEx(m_strGlobalConfigFile, xdEnforced);
			AppConfigEx cfgUser = LoadConfigFileEx(m_strUserConfigFile, xdEnforced);

			if((cfgGlobal == null) && (cfgUser == null))
			{
				if(xdEnforced != null)
				{
					XmlSerializerEx xmlSerial = new XmlSerializerEx(typeof(AppConfigEx));
					try
					{
						using(MemoryStream msEnf = new MemoryStream())
						{
							xdEnforced.Save(msEnf);

							using(MemoryStream msRead = new MemoryStream(
								msEnf.ToArray(), false))
							{
								AppConfigEx cfgEnf = (AppConfigEx)xmlSerial.Deserialize(msRead);
								cfgEnf.OnLoad();

								return cfgEnf;
							}
						}
					}
					catch(Exception) { Debug.Assert(false); }
				}

				AppConfigEx cfgNew = new AppConfigEx();
				cfgNew.OnLoad(); // Create defaults
				return cfgNew;
			}
			else if((cfgGlobal != null) && (cfgUser == null))
				return cfgGlobal;
			else if((cfgGlobal == null) && (cfgUser != null))
				return cfgUser;

			cfgUser.Meta.PreferUserConfiguration = cfgGlobal.Meta.PreferUserConfiguration;
			return (cfgGlobal.Meta.PreferUserConfiguration ? cfgUser : cfgGlobal);
		}

		private static bool SaveConfigFileEx(AppConfigEx tConfig,
			string strFilePath, bool bRemoveConfigPref)
		{
			tConfig.OnSavePre();

			// Temporarily remove user file preference (restore after saving)
			bool bConfigPref = tConfig.Meta.PreferUserConfiguration;
			if(bRemoveConfigPref) tConfig.Meta.PreferUserConfiguration = false;

			bool bResult = true;
			try
			{
				Debug.Assert(!string.IsNullOrEmpty(strFilePath));
				IOConnectionInfo iocPath = IOConnectionInfo.FromPath(strFilePath);

				using(FileTransactionEx ft = new FileTransactionEx(iocPath, true))
				{
					using(Stream s = ft.OpenWrite())
					{
						using(XmlWriter xw = XmlUtilEx.CreateXmlWriter(s))
						{
							XmlSerializerEx xs = new XmlSerializerEx(typeof(AppConfigEx));
							xs.Serialize(xw, tConfig);
						}
					}

					ft.CommitWrite();
				}
			}
			catch(Exception) { Debug.Assert(false); bResult = false; }

			if(bRemoveConfigPref) tConfig.Meta.PreferUserConfiguration = bConfigPref;

			AssertConfigPref(tConfig);

			tConfig.OnSavePost();
			return bResult;
		}

		public static bool Save(AppConfigEx tConfig)
		{
			Debug.Assert(tConfig != null);
			if(tConfig == null) throw new ArgumentNullException("tConfig");

			AppConfigSerializer.GetConfigPaths();

			XmlDocument xdEnforced = LoadEnforcedConfigFile();
			AppConfigEx cfgGlobal = LoadConfigFileEx(m_strGlobalConfigFile, xdEnforced);

			bool bPreferUser = (xdEnforced != null);
			if(cfgGlobal != null)
				bPreferUser = cfgGlobal.Meta.PreferUserConfiguration;
			else if(xdEnforced != null)
				GetConfigPref(xdEnforced, ref bPreferUser, null);

			if(bPreferUser)
			{
				EnsureAppDataDirAvailable(m_strUserConfigFile);
				if(SaveConfigFileEx(tConfig, m_strUserConfigFile, true)) return true;

				if(SaveConfigFileEx(tConfig, m_strGlobalConfigFile, false)) return true;
			}
			else // Don't prefer user -- use global first
			{
				if(SaveConfigFileEx(tConfig, m_strGlobalConfigFile, false)) return true;

				EnsureAppDataDirAvailable(m_strUserConfigFile);
				if(SaveConfigFileEx(tConfig, m_strUserConfigFile, true)) return true;
			}

#if !KeePassLibSD
			if(Program.MainForm != null)
				Program.MainForm.SetStatusEx(KPRes.ConfigSaveFailed);
#endif

			return false;
		}

		private static void GetConfigPref(XmlDocument d, ref bool bPrefUser,
			bool? obExpectedPref)
		{
			if(d == null) { Debug.Assert(false); return; }

			try
			{
				XmlElement eRoot = d.DocumentElement;
				if(eRoot == null) { Debug.Assert(false); return; }

				// obExpectedPref is for debugging only; an assertion
				// will be displayed if the XPath is incorrect

				XmlNode n = eRoot.SelectSingleNode("Meta/PreferUserConfiguration");
				if(n == null) { Debug.Assert(!obExpectedPref.HasValue); return; }

				bPrefUser = XmlConvert.ToBoolean(XmlUtil.SafeInnerText(n));
				if(obExpectedPref.HasValue) { Debug.Assert(bPrefUser == obExpectedPref.Value); }
			}
			catch(Exception) { Debug.Assert(false); }
		}

		[Conditional("DEBUG")]
		private static void AssertConfigPref(AppConfigEx t)
		{
#if DEBUG
			if(t == null) { Debug.Assert(false); return; }

			using(MemoryStream ms = new MemoryStream())
			{
				XmlUtilEx.Serialize<AppConfigEx>(ms, t);

				using(MemoryStream msRead = new MemoryStream(ms.ToArray(), false))
				{
					XmlDocument d = XmlUtilEx.CreateXmlDocument();
					d.Load(msRead);

					// Assert that the meta node XPath is correct
					bool bDummy = false;
					GetConfigPref(d, ref bDummy, t.Meta.PreferUserConfiguration);
				}
			}
#endif
		}
	}
}