File: XmlUtilEx.cs

package info (click to toggle)
keepass2 2.47%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye
  • size: 13,992 kB
  • sloc: cs: 111,053; xml: 5,956; cpp: 308; makefile: 48; sh: 48
file content (290 lines) | stat: -rw-r--r-- 8,726 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
/*
  KeePass Password Safe - The Open-Source Password Manager
  Copyright (C) 2003-2021 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.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.XPath;

using KeePassLib.Delegates;
using KeePassLib.Interfaces;
using KeePassLib.Serialization;

namespace KeePassLib.Utility
{
	public static class XmlUtilEx
	{
		public static XmlDocument CreateXmlDocument()
		{
			XmlDocument d = new XmlDocument();

			// .NET 4.5.2 and newer do not resolve external XML resources
			// by default; for older .NET versions, we explicitly
			// prevent resolving
			d.XmlResolver = null; // Default in old .NET: XmlUrlResolver object

			return d;
		}

		public static XmlReaderSettings CreateXmlReaderSettings()
		{
			XmlReaderSettings xrs = new XmlReaderSettings();

			xrs.CloseInput = false;
			xrs.IgnoreComments = true;
			xrs.IgnoreProcessingInstructions = true;
			xrs.IgnoreWhitespace = true;

#if KeePassUAP
			xrs.DtdProcessing = DtdProcessing.Prohibit;
#else
			// Also see PrepMonoDev.sh script
			xrs.ProhibitDtd = true; // Obsolete in .NET 4, but still there
			// xrs.DtdProcessing = DtdProcessing.Prohibit; // .NET 4 only
#endif

			xrs.ValidationType = ValidationType.None;
			xrs.XmlResolver = null;

			return xrs;
		}

		public static XmlReader CreateXmlReader(Stream s)
		{
			if(s == null) { Debug.Assert(false); throw new ArgumentNullException("s"); }

			return XmlReader.Create(s, CreateXmlReaderSettings());
		}

		public static XmlWriterSettings CreateXmlWriterSettings()
		{
			XmlWriterSettings xws = new XmlWriterSettings();

			xws.CloseOutput = false;
			xws.Encoding = StrUtil.Utf8;
			xws.Indent = true;
			xws.IndentChars = "\t";
			xws.NewLineOnAttributes = false;

			return xws;
		}

		public static XmlWriter CreateXmlWriter(Stream s)
		{
			if(s == null) { Debug.Assert(false); throw new ArgumentNullException("s"); }

			return XmlWriter.Create(s, CreateXmlWriterSettings());
		}

		public static T Deserialize<T>(Stream s)
		{
			if(s == null) { Debug.Assert(false); throw new ArgumentNullException("s"); }

			XmlSerializer xs = new XmlSerializer(typeof(T));

			T t = default(T);
			using(XmlReader xr = CreateXmlReader(s))
			{
				t = (T)xs.Deserialize(xr);
			}

			return t;
		}

		public static void Serialize<T>(Stream s, T t)
		{
			if(s == null) { Debug.Assert(false); throw new ArgumentNullException("s"); }

			XmlSerializer xs = new XmlSerializer(typeof(T));
			using(XmlWriter xw = CreateXmlWriter(s))
			{
				xs.Serialize(xw, t);
			}
		}

		internal static void Serialize<T>(Stream s, T t, bool bRemoveXsdXsi)
		{
			// One way to remove the "xsd" and "xsi" namespace declarations
			// is to use an XmlSerializerNamespaces object containing only
			// a ""/"" pair; this seems to work, but Microsoft's
			// documentation explicitly states that it isn't supported:
			// https://docs.microsoft.com/en-us/dotnet/api/system.xml.serialization.xmlserializernamespaces
			// There are other, more complex ways, but these either rely on
			// undocumented details or require the type T to be modified.

			string str;
			using(MemoryStream ms = new MemoryStream())
			{
				Serialize<T>(ms, t);

				str = StrUtil.Utf8.GetString(ms.ToArray());
			}

			GFunc<string, string, bool> fFindPfx = delegate(string strText, string strSub)
			{
				int i = strText.IndexOf(strSub, StringComparison.Ordinal);
				if(i < 0) return false;
				if(i == 0) return true;
				return char.IsWhiteSpace(strText[i - 1]);
			};

			if(bRemoveXsdXsi)
			{
				if(!fFindPfx(str, "xsd:") && !fFindPfx(str, "xsi:"))
				{
					Debug.Assert(str.IndexOf("xmlns:xsd") > 0);
					str = str.Replace(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"", string.Empty);
					Debug.Assert(str.IndexOf("xmlns:xsd") < 0);

					Debug.Assert(str.IndexOf("xmlns:xsi") > 0);
					str = str.Replace(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"", string.Empty);
					Debug.Assert(str.IndexOf("xmlns:xsi") < 0);
				}
				else { Debug.Assert(false); } // "xsd"/"xsi" decl. may be required
			}

			MemUtil.Write(s, StrUtil.Utf8.GetBytes(str));
		}

#if DEBUG
		internal static void ValidateXml(string strXml, bool bReplaceStdEntities)
		{
			if(strXml == null) throw new ArgumentNullException("strXml");
			if(strXml.Length == 0) { Debug.Assert(false); return; }

			string str = strXml;

			if(bReplaceStdEntities)
				str = str.Replace("&nbsp;", "&#160;");

			XmlDocument d = new XmlDocument();
			d.LoadXml(str);
		}
#endif

		internal static XPathNodeIterator FindNodes(PwDatabase pd, string strXPath,
			IStatusLogger sl, out XmlDocument xd)
		{
			if(pd == null) throw new ArgumentNullException("pd");
			if(strXPath == null) { Debug.Assert(false); strXPath = string.Empty; }

			KdbxFile kdbx = new KdbxFile(pd);

			byte[] pbXml;
			using(MemoryStream ms = new MemoryStream())
			{
				kdbx.Save(ms, null, KdbxFormat.PlainXml, sl);
				pbXml = ms.ToArray();
			}
			string strXml = StrUtil.Utf8.GetString(pbXml);

			xd = CreateXmlDocument();
			xd.LoadXml(strXml);

			XPathNavigator xpNav = xd.CreateNavigator();
			return xpNav.Select(strXPath);
			// XPathExpression xpExpr = xpNav.Compile(strXPath);
			// xpExpr.SetContext(new XuXsltContext());
			// return xpNav.Select(xpExpr);
		}

		/* private sealed class XuFnMatches : IXsltContextFunction
		{
			private readonly XPathResultType[] m_vArgTypes = new XPathResultType[] {
				XPathResultType.String, XPathResultType.String, XPathResultType.String
			};
			public XPathResultType[] ArgTypes { get { return m_vArgTypes; } }

			public int Maxargs { get { return 3; } }
			public int Minargs { get { return 2; } }

			public XPathResultType ReturnType { get { return XPathResultType.Boolean; } }

			private static string GetArgString(object[] args, int i, string strDefault)
			{
				if(args == null) { Debug.Assert(false); return strDefault; }
				if(i >= args.Length) return strDefault;

				object o = args[i];
				if(o == null) return strDefault;

				XPathNodeIterator it = (o as XPathNodeIterator);
				if(it != null) o = it.Current.Value;

				return (o.ToString() ?? strDefault);
			}

			public object Invoke(XsltContext xsltContext, object[] args,
				XPathNavigator docContext)
			{
				string strInput = GetArgString(args, 0, string.Empty);
				string strPattern = GetArgString(args, 1, string.Empty);
				string strFlags = GetArgString(args, 2, null);

				RegexOptions ro = RegexOptions.None;
				if(!string.IsNullOrEmpty(strFlags))
				{
					if(strFlags.IndexOf('s') >= 0) ro |= RegexOptions.Singleline;
					if(strFlags.IndexOf('m') >= 0) ro |= RegexOptions.Multiline;
					if(strFlags.IndexOf('i') >= 0) ro |= RegexOptions.IgnoreCase;
					if(strFlags.IndexOf('x') >= 0) ro |= RegexOptions.IgnorePatternWhitespace;
				}

				return Regex.IsMatch(strInput, strPattern, ro);
			}
		}

		private sealed class XuXsltContext : XsltContext
		{
			public override bool Whitespace { get { return false; } }

			public override int CompareDocument(string baseUri, string nextbaseUri)
			{
				return string.CompareOrdinal(baseUri, nextbaseUri);
			}

			public override bool PreserveWhitespace(XPathNavigator node)
			{
				return false;
			}

			public override IXsltContextFunction ResolveFunction(string prefix,
				string name, XPathResultType[] ArgTypes)
			{
				if(prefix != "kp") { Debug.Assert(false); return null; }

				if(name == "matches") return new XuFnMatches();

				Debug.Assert(false);
				return null;
			}

			public override IXsltContextVariable ResolveVariable(string prefix,
				string name)
			{
				Debug.Assert(false);
				return null;
			}
		} */
	}
}