File: MonoTlsProviderFactory.cs

package info (click to toggle)
mono 6.14.1%2Bds2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,282,732 kB
  • sloc: cs: 11,182,461; xml: 2,850,281; ansic: 699,123; cpp: 122,919; perl: 58,604; javascript: 30,841; asm: 21,845; makefile: 19,602; sh: 10,973; python: 4,772; pascal: 925; sql: 859; sed: 16; php: 1
file content (383 lines) | stat: -rw-r--r-- 10,310 bytes parent folder | download | duplicates (5)
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
//
// MonoTlsProviderFactory.cs
//
// Author:
//       Martin Baulig <martin.baulig@xamarin.com>
//
// Copyright (c) 2015 Xamarin, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#if SECURITY_DEP

#if MONO_SECURITY_ALIAS
extern alias MonoSecurity;
using MSI = MonoSecurity::Mono.Security.Interface;
using MX = MonoSecurity::Mono.Security.X509;
#else
using MSI = Mono.Security.Interface;
using MX = Mono.Security.X509;
#endif
using System.Security.Cryptography.X509Certificates;

using System;
using System.Net;
using System.Diagnostics;
using System.Collections.Generic;
using System.Runtime.CompilerServices;

#if MONO_FEATURE_BTLS
using Mono.Btls;
#endif

#if MONO_FEATURE_APPLETLS
using Mono.AppleTls;
#endif

#if !MOBILE
using System.Reflection;
#endif

namespace Mono.Net.Security
{
	/*
	 * Keep in sync with Mono.Security/Mono.Security.Interface/MonoTlsProvider.cs.
	 *
	 */
	static partial class MonoTlsProviderFactory
	{
#region Internal API

		/*
		 * APIs in this section are for consumption within System.dll only - do not access via
		 * reflection or from friend assemblies.
		 * 
		 */

		internal static MobileTlsProvider GetProviderInternal ()
		{
			lock (locker) {
				InitializeInternal ();
				return defaultProvider;
			}
		}

		internal static void InitializeInternal ()
		{
			lock (locker) {
				if (initialized)
					return;

				SystemDependencyProvider.Initialize ();

				InitializeProviderRegistration ();

				MobileTlsProvider provider;
				try {
					provider = CreateDefaultProviderImpl ();
				} catch (Exception ex) {
					throw new NotSupportedException ("TLS Support not available.", ex);
				}

				if (provider == null)
					throw new NotSupportedException ("TLS Support not available.");

				if (!providerCache.ContainsKey (provider.ID))
					providerCache.Add (provider.ID, provider);

				defaultProvider = provider;
				initialized = true;
			}
		}

		internal static void InitializeInternal (string provider) 
		{
			lock (locker) {
				if (initialized)
					throw new NotSupportedException ("TLS Subsystem already initialized.");

				SystemDependencyProvider.Initialize ();

				defaultProvider = LookupProvider (provider, true);

				initialized = true;
			}
		}

		static object locker = new object ();
		static bool initialized;

		static MobileTlsProvider defaultProvider;

		/*
		 * @providerRegistration maps provider names to a tuple containing its ID and full type name.
		 * On non-reflection enabled systems (such as XI and XM), we can use the Guid to uniquely
		 * identify the provider.
		 *
		 * @providerCache maps the provider's Guid to the MobileTlsProvider instance.
		 *
		 */
		static Dictionary<string,Tuple<Guid,string>> providerRegistration;
		static Dictionary<Guid,MobileTlsProvider> providerCache;

#if !ONLY_APPLETLS && !MONOTOUCH && !XAMMAC
		static Type LookupProviderType (string name, bool throwOnError)
		{
			lock (locker) {
				InitializeProviderRegistration ();
				Tuple<Guid,string> entry;
				if (!providerRegistration.TryGetValue (name, out entry)) {
					if (throwOnError)
						throw new NotSupportedException (string.Format ("No such TLS Provider: `{0}'.", name));
					return null;
				}
				var type = Type.GetType (entry.Item2, false);
				if (type == null && throwOnError)
					throw new NotSupportedException (string.Format ("Could not find TLS Provider: `{0}'.", entry.Item2));
				return type;
			}
		}
#endif

		static MobileTlsProvider LookupProvider (string name, bool throwOnError)
		{
			lock (locker) {
				InitializeProviderRegistration ();
				Tuple<Guid,string> entry;
				if (!providerRegistration.TryGetValue (name, out entry)) {
					if (throwOnError)
						throw new NotSupportedException (string.Format ("No such TLS Provider: `{0}'.", name));
					return null;
				}

				// Check cache before doing the reflection lookup.
				MobileTlsProvider provider;
				if (providerCache.TryGetValue (entry.Item1, out provider))
					return provider;

#if !ONLY_APPLETLS && !MONOTOUCH && !XAMMAC
				var type = Type.GetType (entry.Item2, false);
				if (type == null && throwOnError)
					throw new NotSupportedException (string.Format ("Could not find TLS Provider: `{0}'.", entry.Item2));

				try {
					provider = (MobileTlsProvider)Activator.CreateInstance (type, true);
				} catch (Exception ex) {
					throw new NotSupportedException (string.Format ("Unable to instantiate TLS Provider `{0}'.", type), ex);
				}
#endif

				if (provider == null) {
					if (throwOnError)
						throw new NotSupportedException (string.Format ("No such TLS Provider: `{0}'.", name));
					return null;
				}

				providerCache.Add (entry.Item1, provider);
				return provider;
			}
		}

		static bool enableDebug;

		[Conditional ("MONO_TLS_DEBUG")]
		static void InitializeDebug ()
		{
			if (Environment.GetEnvironmentVariable ("MONO_TLS_DEBUG") != null)
				enableDebug = true;
		}

		[Conditional ("MONO_TLS_DEBUG")]
		internal static void Debug (string message, params object[] args)
		{
			if (enableDebug)
				Console.Error.WriteLine (message, args);
		}

#endregion

		internal static readonly Guid AppleTlsId = new Guid ("981af8af-a3a3-419a-9f01-a518e3a17c1c");
		internal static readonly Guid BtlsId = new Guid ("432d18c9-9348-4b90-bfbf-9f2a10e1f15b");

		static void InitializeProviderRegistration ()
		{
			lock (locker) {
				if (providerRegistration != null)
					return;

				InitializeDebug ();

				providerRegistration = new Dictionary<string,Tuple<Guid,string>> ();
				providerCache = new Dictionary<Guid,MobileTlsProvider> ();

				PopulateProviders ();
			}
		}

#if ONLY_APPLETLS || MONOTOUCH || XAMMAC
		// TODO: Should be redundant
		static void PopulateProviders ()
		{
			var appleTlsEntry = new Tuple<Guid,String> (AppleTlsId, typeof (Mono.AppleTls.AppleTlsProvider).FullName);

			providerRegistration.Add ("default", appleTlsEntry);
			providerRegistration.Add ("legacy", appleTlsEntry);
			providerRegistration.Add ("apple", appleTlsEntry);
		}
#elif MONODROID
		// TODO: Should be redundant		
		static void PopulateProviders ()
		{
#if MONO_FEATURE_BTLS
			var btlsEntry = new Tuple<Guid,String> (BtlsId, typeof (Mono.Btls.MonoBtlsProvider).FullName);
			providerRegistration.Add ("default", btlsEntry);
			providerRegistration.Add ("legacy", btlsEntry);
			providerRegistration.Add ("btls", btlsEntry);
#endif
		}
#else
		static void PopulateProviders ()
		{
			Tuple<Guid,String> appleTlsEntry = null;
			Tuple<Guid,String> btlsEntry = null;

#if MONO_FEATURE_APPLETLS
			appleTlsEntry = new Tuple<Guid,String> (AppleTlsId, typeof (Mono.AppleTls.AppleTlsProvider).FullName);
			providerRegistration.Add ("apple", appleTlsEntry);
#endif

#if MONO_FEATURE_BTLS
			if (IsBtlsSupported ()) {
				btlsEntry = new Tuple<Guid,String> (BtlsId, typeof (Mono.Btls.MonoBtlsProvider).FullName);
				providerRegistration.Add ("btls", btlsEntry);
			}
#endif

			var defaultEntry = appleTlsEntry ?? btlsEntry;
			if (defaultEntry != null) {
				providerRegistration.Add ("default", defaultEntry);
				providerRegistration.Add ("legacy", defaultEntry);
			}
		}
#endif


#if MONO_FEATURE_BTLS
		[MethodImpl (MethodImplOptions.InternalCall)]
		internal extern static bool IsBtlsSupported ();
#endif

		static MobileTlsProvider CreateDefaultProviderImpl ()
		{
#if MONODROID
			var type = Environment.GetEnvironmentVariable ("XA_TLS_PROVIDER");
			switch (type) {
#if MONO_FEATURE_BTLS
			case null:
			case "default":
			case "legacy":
			case "btls":
				if (!IsBtlsSupported ())
					throw new NotSupportedException ("BTLS in not supported!");
				return new MonoBtlsProvider ();
#endif
			default:
				throw new NotSupportedException ($"Invalid TLS Provider: `{type}'.");
			}

#elif ONLY_APPLETLS || MONOTOUCH || XAMMAC
			return new AppleTlsProvider ();
#else
			var type = Environment.GetEnvironmentVariable ("MONO_TLS_PROVIDER");
			if (string.IsNullOrEmpty (type))
				type = "default";

			switch (type) {
			case "default":
			case "legacy":
#if MONO_FEATURE_APPLETLS
				if (Platform.IsMacOS)
					goto case "apple";
#endif
#if MONO_FEATURE_BTLS
				if (IsBtlsSupported ())
					goto case "btls";
#endif
				throw new NotSupportedException ("TLS Support not available.");
#if MONO_FEATURE_APPLETLS
			case "apple":
				return new AppleTlsProvider ();
#endif
#if MONO_FEATURE_BTLS
			case "btls":
				return new MonoBtlsProvider ();
#endif
			}

			return LookupProvider (type, true);
#endif
		}

#region Mono.Security visible API

		/*
		 * "Public" section, intended to be consumed via reflection.
		 * 
		 * Mono.Security.dll provides a public wrapper around these.
		 */

		internal static MobileTlsProvider GetProvider ()
		{
			return GetProviderInternal ();
		}

		internal static bool IsProviderSupported (string name)
		{
			lock (locker) {
				InitializeProviderRegistration ();
				return providerRegistration.ContainsKey (name);
			}
		}

		internal static MobileTlsProvider GetProvider (string name)
		{
			return LookupProvider (name, false);
		}

		internal static bool IsInitialized {
			get {
				lock (locker) {
					return initialized;
				}
			}
		}

		internal static void Initialize ()
		{
			InitializeInternal ();
		}

		internal static void Initialize (string provider)
		{
			InitializeInternal (provider);
		}
#endregion
	}
}
#endif