2 // System.Net.ServicePointManager
5 // Lawrence Pit (loz@cable.a2000.nl)
6 // Gonzalo Paniagua Javier (gonzalo@novell.com)
8 // Copyright (c) 2003-2010 Novell, Inc (http://www.novell.com)
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 using System.Collections;
34 using System.Collections.Specialized;
35 using System.Configuration;
36 using System.Net.Configuration;
37 using System.Security.Cryptography.X509Certificates;
39 using System.Globalization;
40 using System.Net.Security;
42 using System.Text.RegularExpressions;
44 using Mono.Security.Cryptography;
45 using Mono.Security.X509.Extensions;
46 using Mono.Security.Protocol.Tls;
47 using MSX = Mono.Security.X509;
52 // A service point manager manages service points (duh!).
53 // A service point maintains a list of connections (per scheme + authority).
54 // According to HttpWebRequest.ConnectionGroupName each connection group
55 // creates additional connections. therefor, a service point has a hashtable
56 // of connection groups where each value is a list of connections.
58 // when we need to make an HttpWebRequest, we need to do the following:
59 // 1. find service point, given Uri and Proxy
60 // 2. find connection group, given service point and group name
61 // 3. find free connection in connection group, or create one (if ok due to limits)
62 // 4. lease connection
64 // 6. when finished, return connection
71 internal class ServicePointManager {
73 public class ServicePointManager {
76 Uri uri; // schema/host/port
79 public SPKey (Uri uri, bool use_connect) {
81 this.use_connect = use_connect;
88 public bool UseConnect {
89 get { return use_connect; }
92 public override int GetHashCode () {
93 return uri.GetHashCode () + ((use_connect) ? 1 : 0);
96 public override bool Equals (object obj) {
97 SPKey other = obj as SPKey;
102 return (uri.Equals (other.uri) && other.use_connect == use_connect);
106 private static HybridDictionary servicePoints = new HybridDictionary ();
110 private static ICertificatePolicy policy = new DefaultCertificatePolicy ();
111 private static int defaultConnectionLimit = DefaultPersistentConnectionLimit;
112 private static int maxServicePointIdleTime = 900000; // 15 minutes
113 private static int maxServicePoints = 0;
114 private static bool _checkCRL = false;
115 private static SecurityProtocolType _securityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
118 static bool expectContinue = false;
120 static bool expectContinue = true;
122 static bool useNagle;
123 static RemoteCertificateValidationCallback server_cert_cb;
124 static bool tcp_keepalive;
125 static int tcp_keepalive_time;
126 static int tcp_keepalive_interval;
130 public const int DefaultNonPersistentConnectionLimit = 4;
132 public const int DefaultPersistentConnectionLimit = 10;
134 public const int DefaultPersistentConnectionLimit = 2;
138 const string configKey = "system.net/connectionManagement";
139 static ConnectionManagementData manager;
142 static ServicePointManager ()
145 #if CONFIGURATION_DEP
146 object cfg = ConfigurationManager.GetSection (configKey);
147 ConnectionManagementSection s = cfg as ConnectionManagementSection;
149 manager = new ConnectionManagementData (null);
150 foreach (ConnectionManagementElement e in s.ConnectionManagement)
151 manager.Add (e.Address, e.MaxConnection);
153 defaultConnectionLimit = (int) manager.GetMaxConnections ("*");
157 manager = (ConnectionManagementData) ConfigurationSettings.GetConfig (configKey);
158 if (manager != null) {
159 defaultConnectionLimit = (int) manager.GetMaxConnections ("*");
165 private ServicePointManager ()
171 [Obsolete ("Use ServerCertificateValidationCallback instead", false)]
172 public static ICertificatePolicy CertificatePolicy {
173 get { return policy; }
174 set { policy = value; }
177 [MonoTODO("CRL checks not implemented")]
178 public static bool CheckCertificateRevocationList {
179 get { return _checkCRL; }
180 set { _checkCRL = false; } // TODO - don't yet accept true
183 public static int DefaultConnectionLimit {
184 get { return defaultConnectionLimit; }
187 throw new ArgumentOutOfRangeException ("value");
189 defaultConnectionLimit = value;
191 manager.Add ("*", defaultConnectionLimit);
195 static Exception GetMustImplement ()
197 return new NotImplementedException ();
201 public static int DnsRefreshTimeout
204 throw GetMustImplement ();
207 throw GetMustImplement ();
212 public static bool EnableDnsRoundRobin
215 throw GetMustImplement ();
218 throw GetMustImplement ();
222 public static int MaxServicePointIdleTime {
224 return maxServicePointIdleTime;
227 if (value < -2 || value > Int32.MaxValue)
228 throw new ArgumentOutOfRangeException ("value");
229 maxServicePointIdleTime = value;
233 public static int MaxServicePoints {
235 return maxServicePoints;
239 throw new ArgumentException ("value");
241 maxServicePoints = value;
242 RecycleServicePoints ();
247 // we need it for SslClientStream
252 static SecurityProtocolType SecurityProtocol {
253 get { return _securityProtocol; }
254 set { _securityProtocol = value; }
257 public static RemoteCertificateValidationCallback ServerCertificateValidationCallback
260 return server_cert_cb;
263 server_cert_cb = value;
267 public static bool Expect100Continue {
268 get { return expectContinue; }
269 set { expectContinue = value; }
272 public static bool UseNagleAlgorithm {
273 get { return useNagle; }
274 set { useNagle = value; }
278 public static void SetTcpKeepAlive (bool enabled, int keepAliveTime, int keepAliveInterval)
281 if (keepAliveTime <= 0)
282 throw new ArgumentOutOfRangeException ("keepAliveTime", "Must be greater than 0");
283 if (keepAliveInterval <= 0)
284 throw new ArgumentOutOfRangeException ("keepAliveInterval", "Must be greater than 0");
287 tcp_keepalive = enabled;
288 tcp_keepalive_time = keepAliveTime;
289 tcp_keepalive_interval = keepAliveInterval;
292 public static ServicePoint FindServicePoint (Uri address)
294 return FindServicePoint (address, GlobalProxySelection.Select);
297 public static ServicePoint FindServicePoint (string uriString, IWebProxy proxy)
299 return FindServicePoint (new Uri(uriString), proxy);
302 public static ServicePoint FindServicePoint (Uri address, IWebProxy proxy)
305 throw new ArgumentNullException ("address");
307 RecycleServicePoints ();
309 var origAddress = new Uri (address.Scheme + "://" + address.Authority);
311 bool usesProxy = false;
312 bool useConnect = false;
313 if (proxy != null && !proxy.IsBypassed(address)) {
315 bool isSecure = address.Scheme == "https";
316 address = proxy.GetProxy (address);
317 if (address.Scheme != "http" && !isSecure)
318 throw new NotSupportedException ("Proxy scheme not supported.");
320 if (isSecure && address.Scheme == "http")
324 address = new Uri (address.Scheme + "://" + address.Authority);
326 ServicePoint sp = null;
327 lock (servicePoints) {
328 SPKey key = new SPKey (origAddress, useConnect);
329 sp = servicePoints [key] as ServicePoint;
333 if (maxServicePoints > 0 && servicePoints.Count >= maxServicePoints)
334 throw new InvalidOperationException ("maximum number of service points reached");
336 string addr = address.ToString ();
338 int limit = defaultConnectionLimit;
340 int limit = (int) manager.GetMaxConnections (addr);
342 sp = new ServicePoint (address, limit, maxServicePointIdleTime);
343 sp.Expect100Continue = expectContinue;
344 sp.UseNagleAlgorithm = useNagle;
345 sp.UsesProxy = usesProxy;
346 sp.UseConnect = useConnect;
347 sp.SetTcpKeepAlive (tcp_keepalive, tcp_keepalive_time, tcp_keepalive_interval);
348 servicePoints.Add (key, sp);
356 internal static void RecycleServicePoints ()
358 ArrayList toRemove = new ArrayList ();
359 lock (servicePoints) {
360 IDictionaryEnumerator e = servicePoints.GetEnumerator ();
361 while (e.MoveNext ()) {
362 ServicePoint sp = (ServicePoint) e.Value;
363 if (sp.AvailableForRecycling) {
364 toRemove.Add (e.Key);
368 for (int i = 0; i < toRemove.Count; i++)
369 servicePoints.Remove (toRemove [i]);
371 if (maxServicePoints == 0 || servicePoints.Count <= maxServicePoints)
374 // get rid of the ones with the longest idle time
375 SortedList list = new SortedList (servicePoints.Count);
376 e = servicePoints.GetEnumerator ();
377 while (e.MoveNext ()) {
378 ServicePoint sp = (ServicePoint) e.Value;
379 if (sp.CurrentConnections == 0) {
380 while (list.ContainsKey (sp.IdleSince))
381 sp.IdleSince = sp.IdleSince.AddMilliseconds (1);
382 list.Add (sp.IdleSince, sp.Address);
386 for (int i = 0; i < list.Count && servicePoints.Count > maxServicePoints; i++)
387 servicePoints.Remove (list.GetByIndex (i));
390 #if MOONLIGHT && SECURITY_DEP
391 internal class ChainValidationHelper {
394 public ChainValidationHelper (object sender)
396 this.sender = sender;
399 // no need to check certificates since we are either
400 // (a) loading from the site of origin (and we accepted its certificate to load from it)
401 // (b) loading from a cross-domain site and we downloaded the policy file using the browser stack
402 // i.e. the certificate was accepted (or the policy would not be valid)
403 internal ValidationResult ValidateChain (Mono.Security.X509.X509CertificateCollection certs)
405 return new ValidationResult (true, false, 0);
409 internal class ChainValidationHelper {
412 static bool is_macosx = System.IO.File.Exists (MSX.OSX509Certificates.SecurityLibrary);
413 static X509RevocationMode revocation_mode;
415 static ChainValidationHelper ()
418 revocation_mode = X509RevocationMode.NoCheck;
420 string str = Environment.GetEnvironmentVariable ("MONO_X509_REVOCATION_MODE");
421 if (String.IsNullOrEmpty (str))
423 revocation_mode = (X509RevocationMode) Enum.Parse (typeof (X509RevocationMode), str, true);
429 public ChainValidationHelper (object sender)
431 this.sender = sender;
436 if (host == null && sender is HttpWebRequest)
437 host = ((HttpWebRequest) sender).Address.Host;
441 set { host = value; }
444 // Used when the obsolete ICertificatePolicy is set to DefaultCertificatePolicy
445 // and the new ServerCertificateValidationCallback is not null
446 internal ValidationResult ValidateChain (Mono.Security.X509.X509CertificateCollection certs)
448 // user_denied is true if the user callback is called and returns false
449 bool user_denied = false;
450 if (certs == null || certs.Count == 0)
453 ICertificatePolicy policy = ServicePointManager.CertificatePolicy;
454 RemoteCertificateValidationCallback cb = ServicePointManager.ServerCertificateValidationCallback;
456 X509Certificate2 leaf = new X509Certificate2 (certs [0].RawData);
457 int status11 = 0; // Error code passed to the obsolete ICertificatePolicy callback
458 SslPolicyErrors errors = 0;
459 X509Chain chain = null;
462 // The X509Chain is not really usable with MonoTouch (since the decision is not based on this data)
463 // However if someone wants to override the results (good or bad) from iOS then they will want all
464 // the certificates that the server provided (which generally does not include the root) so, only
465 // if there's a user callback, we'll create the X509Chain but won't build it
466 // ref: https://bugzilla.xamarin.com/show_bug.cgi?id=7245
469 chain = new X509Chain ();
470 chain.ChainPolicy = new X509ChainPolicy ();
471 chain.ChainPolicy.RevocationMode = revocation_mode;
472 for (int i = 1; i < certs.Count; i++) {
473 X509Certificate2 c2 = new X509Certificate2 (certs [i].RawData);
474 chain.ChainPolicy.ExtraStore.Add (c2);
480 if (!chain.Build (leaf))
481 errors |= GetErrorsFromChain (chain);
482 } catch (Exception e) {
483 Console.Error.WriteLine ("ERROR building certificate chain: {0}", e);
484 Console.Error.WriteLine ("Please, report this problem to the Mono team");
485 errors |= SslPolicyErrors.RemoteCertificateChainErrors;
488 // for OSX and iOS we're using the native API to check for the SSL server policy and host names
490 if (!CheckCertificateUsage (leaf)) {
491 errors |= SslPolicyErrors.RemoteCertificateChainErrors;
492 status11 = -2146762490; //CERT_E_PURPOSE 0x800B0106
495 if (!CheckServerIdentity (certs [0], Host)) {
496 errors |= SslPolicyErrors.RemoteCertificateNameMismatch;
497 status11 = -2146762481; // CERT_E_CN_NO_MATCH 0x800B010F
501 // Attempt to use OSX certificates
502 // Ideally we should return the SecTrustResult
503 MSX.OSX509Certificates.SecTrustResult trustResult = MSX.OSX509Certificates.SecTrustResult.Deny;
505 trustResult = MSX.OSX509Certificates.TrustEvaluateSsl (certs, Host);
506 // We could use the other values of trustResult to pass this extra information
507 // to the .NET 2 callback for values like SecTrustResult.Confirm
508 result = (trustResult == MSX.OSX509Certificates.SecTrustResult.Proceed ||
509 trustResult == MSX.OSX509Certificates.SecTrustResult.Unspecified);
515 // TrustEvaluateSsl was successful so there's no trust error
516 // IOW we discard our own chain (since we trust OSX one instead)
519 // callback and DefaultCertificatePolicy needs this since 'result' is not specified
520 status11 = (int) trustResult;
521 errors |= SslPolicyErrors.RemoteCertificateChainErrors;
528 result = AndroidPlatform.TrustEvaluateSsl (certs, sender, leaf, chain, errors);
530 // chain.Build() + GetErrorsFromChain() (above) will ALWAYS fail on
531 // Android (there are no mozroots or preinstalled root certificates),
532 // thus `errors` will ALWAYS have RemoteCertificateChainErrors.
533 // Android just verified the chain; clear RemoteCertificateChainErrors.
534 errors &= ~SslPolicyErrors.RemoteCertificateChainErrors;
538 if (policy != null && (!(policy is DefaultCertificatePolicy) || cb == null)) {
539 ServicePoint sp = null;
540 HttpWebRequest req = sender as HttpWebRequest;
542 sp = req.ServicePointNoLock;
543 if (status11 == 0 && errors != 0)
544 status11 = GetStatusFromChain (chain);
547 result = policy.CheckValidationResult (sp, leaf, req, status11);
548 user_denied = !result && !(policy is DefaultCertificatePolicy);
550 // If there's a 2.0 callback, it takes precedence
552 result = cb (sender, leaf, chain, errors);
553 user_denied = !result;
555 return new ValidationResult (result, user_denied, status11);
558 static int GetStatusFromChain (X509Chain chain)
561 foreach (var status in chain.ChainStatus) {
562 X509ChainStatusFlags flags = status.Status;
563 if (flags == X509ChainStatusFlags.NoError)
567 if ((flags & X509ChainStatusFlags.NotTimeValid) != 0) result = 0x800B0101;
568 // CERT_E_VALIDITYPERIODNESTING
569 else if ((flags & X509ChainStatusFlags.NotTimeNested) != 0) result = 0x800B0102;
571 else if ((flags & X509ChainStatusFlags.Revoked) != 0) result = 0x800B010C;
572 // TRUST_E_CERT_SIGNATURE
573 else if ((flags & X509ChainStatusFlags.NotSignatureValid) != 0) result = 0x80096004;
574 // CERT_E_WRONG_USAGE
575 else if ((flags & X509ChainStatusFlags.NotValidForUsage) != 0) result = 0x800B0110;
576 // CERT_E_UNTRUSTEDROOT
577 else if ((flags & X509ChainStatusFlags.UntrustedRoot) != 0) result = 0x800B0109;
578 // CRYPT_E_NO_REVOCATION_CHECK
579 else if ((flags & X509ChainStatusFlags.RevocationStatusUnknown) != 0) result = 0x80092012;
581 else if ((flags & X509ChainStatusFlags.Cyclic) != 0) result = 0x800B010A;
582 // TRUST_E_FAIL - generic
583 else if ((flags & X509ChainStatusFlags.InvalidExtension) != 0) result = 0x800B010B;
584 // CERT_E_UNTRUSTEDROOT
585 else if ((flags & X509ChainStatusFlags.InvalidPolicyConstraints) != 0) result = 0x800B010D;
586 // TRUST_E_BASIC_CONSTRAINTS
587 else if ((flags & X509ChainStatusFlags.InvalidBasicConstraints) != 0) result = 0x80096019;
588 // CERT_E_INVALID_NAME
589 else if ((flags & X509ChainStatusFlags.InvalidNameConstraints) != 0) result = 0x800B0114;
590 // CERT_E_INVALID_NAME
591 else if ((flags & X509ChainStatusFlags.HasNotSupportedNameConstraint) != 0) result = 0x800B0114;
592 // CERT_E_INVALID_NAME
593 else if ((flags & X509ChainStatusFlags.HasNotDefinedNameConstraint) != 0) result = 0x800B0114;
594 // CERT_E_INVALID_NAME
595 else if ((flags & X509ChainStatusFlags.HasNotPermittedNameConstraint) != 0) result = 0x800B0114;
596 // CERT_E_INVALID_NAME
597 else if ((flags & X509ChainStatusFlags.HasExcludedNameConstraint) != 0) result = 0x800B0114;
599 else if ((flags & X509ChainStatusFlags.PartialChain) != 0) result = 0x800B010A;
601 else if ((flags & X509ChainStatusFlags.CtlNotTimeValid) != 0) result = 0x800B0101;
602 // TRUST_E_CERT_SIGNATURE
603 else if ((flags & X509ChainStatusFlags.CtlNotSignatureValid) != 0) result = 0x80096004;
604 // CERT_E_WRONG_USAGE
605 else if ((flags & X509ChainStatusFlags.CtlNotValidForUsage) != 0) result = 0x800B0110;
606 // CRYPT_E_NO_REVOCATION_CHECK
607 else if ((flags & X509ChainStatusFlags.OfflineRevocation) != 0) result = 0x80092012;
608 // CERT_E_ISSUERCHAINING
609 else if ((flags & X509ChainStatusFlags.NoIssuanceChainPolicy) != 0) result = 0x800B0107;
610 else result = 0x800B010B; // TRUST_E_FAIL - generic
612 break; // Exit the loop on the first error
617 static SslPolicyErrors GetErrorsFromChain (X509Chain chain)
619 SslPolicyErrors errors = SslPolicyErrors.None;
620 foreach (var status in chain.ChainStatus) {
621 if (status.Status == X509ChainStatusFlags.NoError)
623 errors |= SslPolicyErrors.RemoteCertificateChainErrors;
629 static X509KeyUsageFlags s_flags = X509KeyUsageFlags.DigitalSignature |
630 X509KeyUsageFlags.KeyAgreement |
631 X509KeyUsageFlags.KeyEncipherment;
632 // Adapted to System 2.0+ from TlsServerCertificate.cs
633 //------------------------------
634 // Note: this method only works for RSA certificates
635 // DH certificates requires some changes - does anyone use one ?
636 static bool CheckCertificateUsage (X509Certificate2 cert)
639 // certificate extensions are required for this
640 // we "must" accept older certificates without proofs
641 if (cert.Version < 3)
644 X509KeyUsageExtension kux = (cert.Extensions ["2.5.29.15"] as X509KeyUsageExtension);
645 X509EnhancedKeyUsageExtension eku = (cert.Extensions ["2.5.29.37"] as X509EnhancedKeyUsageExtension);
646 if (kux != null && eku != null) {
647 // RFC3280 states that when both KeyUsageExtension and
648 // ExtendedKeyUsageExtension are present then BOTH should
650 if ((kux.KeyUsages & s_flags) == 0)
652 return eku.EnhancedKeyUsages ["1.3.6.1.5.5.7.3.1"] != null ||
653 eku.EnhancedKeyUsages ["2.16.840.1.113730.4.1"] != null;
654 } else if (kux != null) {
655 return ((kux.KeyUsages & s_flags) != 0);
656 } else if (eku != null) {
657 // Server Authentication (1.3.6.1.5.5.7.3.1) or
658 // Netscape Server Gated Crypto (2.16.840.1.113730.4)
659 return eku.EnhancedKeyUsages ["1.3.6.1.5.5.7.3.1"] != null ||
660 eku.EnhancedKeyUsages ["2.16.840.1.113730.4.1"] != null;
663 // last chance - try with older (deprecated) Netscape extensions
664 X509Extension ext = cert.Extensions ["2.16.840.1.113730.1.1"];
666 string text = ext.NetscapeCertType (false);
667 return text.IndexOf ("SSL Server Authentication", StringComparison.Ordinal) != -1;
670 } catch (Exception e) {
671 Console.Error.WriteLine ("ERROR processing certificate: {0}", e);
672 Console.Error.WriteLine ("Please, report this problem to the Mono team");
677 // RFC2818 - HTTP Over TLS, Section 3.1
678 // http://www.ietf.org/rfc/rfc2818.txt
680 // 1. if present MUST use subjectAltName dNSName as identity
681 // 1.1. if multiples entries a match of any one is acceptable
682 // 1.2. wildcard * is acceptable
683 // 2. URI may be an IP address -> subjectAltName.iPAddress
684 // 2.1. exact match is required
685 // 3. Use of the most specific Common Name (CN=) in the Subject
686 // 3.1 Existing practice but DEPRECATED
687 static bool CheckServerIdentity (Mono.Security.X509.X509Certificate cert, string targetHost)
690 Mono.Security.X509.X509Extension ext = cert.Extensions ["2.5.29.17"];
693 SubjectAltNameExtension subjectAltName = new SubjectAltNameExtension (ext);
694 // 1.1 - multiple dNSName
695 foreach (string dns in subjectAltName.DNSNames) {
696 // 1.2 TODO - wildcard support
697 if (Match (targetHost, dns))
701 foreach (string ip in subjectAltName.IPAddresses) {
702 // 2.1. Exact match required
703 if (ip == targetHost)
707 // 3. Common Name (CN=)
708 return CheckDomainName (cert.SubjectName, targetHost);
709 } catch (Exception e) {
710 Console.Error.WriteLine ("ERROR processing certificate: {0}", e);
711 Console.Error.WriteLine ("Please, report this problem to the Mono team");
716 static bool CheckDomainName (string subjectName, string targetHost)
718 string domainName = String.Empty;
719 Regex search = new Regex(@"CN\s*=\s*([^,]*)");
720 MatchCollection elements = search.Matches(subjectName);
721 if (elements.Count == 1) {
722 if (elements[0].Success)
723 domainName = elements[0].Groups[1].Value.ToString();
726 return Match (targetHost, domainName);
729 // ensure the pattern is valid wrt to RFC2595 and RFC2818
730 // http://www.ietf.org/rfc/rfc2595.txt
731 // http://www.ietf.org/rfc/rfc2818.txt
732 static bool Match (string hostname, string pattern)
734 // check if this is a pattern
735 int index = pattern.IndexOf ('*');
737 // not a pattern, do a direct case-insensitive comparison
738 return (String.Compare (hostname, pattern, true, CultureInfo.InvariantCulture) == 0);
741 // check pattern validity
742 // A "*" wildcard character MAY be used as the left-most name component in the certificate.
744 // unless this is the last char (valid)
745 if (index != pattern.Length - 1) {
746 // then the next char must be a dot .'.
747 if (pattern [index + 1] != '.')
751 // only one (A) wildcard is supported
752 int i2 = pattern.IndexOf ('*', index + 1);
756 // match the end of the pattern
757 string end = pattern.Substring (index + 1);
758 int length = hostname.Length - end.Length;
759 // no point to check a pattern that is longer than the hostname
763 if (String.Compare (hostname, length, end, 0, end.Length, true, CultureInfo.InvariantCulture) != 0)
766 // special case, we start with the wildcard
768 // ensure we hostname non-matched part (start) doesn't contain a dot
769 int i3 = hostname.IndexOf ('.');
770 return ((i3 == -1) || (i3 >= (hostname.Length - end.Length)));
773 // match the start of the pattern
774 string start = pattern.Substring (0, index);
775 return (String.Compare (hostname, 0, start, 0, start.Length, true, CultureInfo.InvariantCulture) == 0);