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.
35 using Mono.Security.Protocol.Tls;
36 using MSX = Mono.Security.X509;
37 using Mono.Security.X509.Extensions;
39 extern alias MonoSecurity;
40 using MonoSecurity::Mono.Security.X509.Extensions;
41 using MonoSecurity::Mono.Security.Protocol.Tls;
42 using MSX = MonoSecurity::Mono.Security.X509;
45 using System.Text.RegularExpressions;
49 using System.Collections;
50 using System.Collections.Specialized;
51 using System.Configuration;
52 using System.Net.Configuration;
53 using System.Security.Cryptography.X509Certificates;
55 using System.Globalization;
56 using System.Net.Security;
60 // A service point manager manages service points (duh!).
61 // A service point maintains a list of connections (per scheme + authority).
62 // According to HttpWebRequest.ConnectionGroupName each connection group
63 // creates additional connections. therefor, a service point has a hashtable
64 // of connection groups where each value is a list of connections.
66 // when we need to make an HttpWebRequest, we need to do the following:
67 // 1. find service point, given Uri and Proxy
68 // 2. find connection group, given service point and group name
69 // 3. find free connection in connection group, or create one (if ok due to limits)
70 // 4. lease connection
72 // 6. when finished, return connection
78 public class ServicePointManager {
80 Uri uri; // schema/host/port
84 public SPKey (Uri uri, Uri proxy, bool use_connect) {
87 this.use_connect = use_connect;
94 public bool UseConnect {
95 get { return use_connect; }
98 public bool UsesProxy {
99 get { return proxy != null; }
102 public override int GetHashCode () {
104 hash = hash * 31 + ((use_connect) ? 1 : 0);
105 hash = hash * 31 + uri.GetHashCode ();
106 hash = hash * 31 + (proxy != null ? proxy.GetHashCode () : 0);
110 public override bool Equals (object obj) {
111 SPKey other = obj as SPKey;
116 if (!uri.Equals (other.uri))
118 if (use_connect != other.use_connect || UsesProxy != other.UsesProxy)
120 if (UsesProxy && !proxy.Equals (other.proxy))
126 private static HybridDictionary servicePoints = new HybridDictionary ();
130 private static ICertificatePolicy policy = new DefaultCertificatePolicy ();
131 private static int defaultConnectionLimit = DefaultPersistentConnectionLimit;
132 private static int maxServicePointIdleTime = 900000; // 15 minutes
133 private static int maxServicePoints = 0;
134 private static bool _checkCRL = false;
135 private static SecurityProtocolType _securityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
138 static bool expectContinue = false;
140 static bool expectContinue = true;
142 static bool useNagle;
143 static RemoteCertificateValidationCallback server_cert_cb;
144 static bool tcp_keepalive;
145 static int tcp_keepalive_time;
146 static int tcp_keepalive_interval;
150 public const int DefaultNonPersistentConnectionLimit = 4;
152 public const int DefaultPersistentConnectionLimit = 10;
154 public const int DefaultPersistentConnectionLimit = 2;
158 const string configKey = "system.net/connectionManagement";
159 static ConnectionManagementData manager;
162 static ServicePointManager ()
165 #if CONFIGURATION_DEP
166 object cfg = ConfigurationManager.GetSection (configKey);
167 ConnectionManagementSection s = cfg as ConnectionManagementSection;
169 manager = new ConnectionManagementData (null);
170 foreach (ConnectionManagementElement e in s.ConnectionManagement)
171 manager.Add (e.Address, e.MaxConnection);
173 defaultConnectionLimit = (int) manager.GetMaxConnections ("*");
177 manager = (ConnectionManagementData) ConfigurationSettings.GetConfig (configKey);
178 if (manager != null) {
179 defaultConnectionLimit = (int) manager.GetMaxConnections ("*");
185 private ServicePointManager ()
191 [Obsolete ("Use ServerCertificateValidationCallback instead", false)]
192 public static ICertificatePolicy CertificatePolicy {
193 get { return policy; }
194 set { policy = value; }
197 [MonoTODO("CRL checks not implemented")]
198 public static bool CheckCertificateRevocationList {
199 get { return _checkCRL; }
200 set { _checkCRL = false; } // TODO - don't yet accept true
203 public static int DefaultConnectionLimit {
204 get { return defaultConnectionLimit; }
207 throw new ArgumentOutOfRangeException ("value");
209 defaultConnectionLimit = value;
212 manager.Add ("*", defaultConnectionLimit);
217 static Exception GetMustImplement ()
219 return new NotImplementedException ();
223 public static int DnsRefreshTimeout
226 throw GetMustImplement ();
229 throw GetMustImplement ();
234 public static bool EnableDnsRoundRobin
237 throw GetMustImplement ();
240 throw GetMustImplement ();
244 public static int MaxServicePointIdleTime {
246 return maxServicePointIdleTime;
249 if (value < -2 || value > Int32.MaxValue)
250 throw new ArgumentOutOfRangeException ("value");
251 maxServicePointIdleTime = value;
255 public static int MaxServicePoints {
257 return maxServicePoints;
261 throw new ArgumentException ("value");
263 maxServicePoints = value;
264 RecycleServicePoints ();
269 // we need it for SslClientStream
274 static SecurityProtocolType SecurityProtocol {
275 get { return _securityProtocol; }
276 set { _securityProtocol = value; }
279 public static RemoteCertificateValidationCallback ServerCertificateValidationCallback
282 return server_cert_cb;
285 server_cert_cb = value;
289 public static bool Expect100Continue {
290 get { return expectContinue; }
291 set { expectContinue = value; }
294 public static bool UseNagleAlgorithm {
295 get { return useNagle; }
296 set { useNagle = value; }
300 public static void SetTcpKeepAlive (bool enabled, int keepAliveTime, int keepAliveInterval)
303 if (keepAliveTime <= 0)
304 throw new ArgumentOutOfRangeException ("keepAliveTime", "Must be greater than 0");
305 if (keepAliveInterval <= 0)
306 throw new ArgumentOutOfRangeException ("keepAliveInterval", "Must be greater than 0");
309 tcp_keepalive = enabled;
310 tcp_keepalive_time = keepAliveTime;
311 tcp_keepalive_interval = keepAliveInterval;
314 public static ServicePoint FindServicePoint (Uri address)
316 return FindServicePoint (address, GlobalProxySelection.Select);
319 public static ServicePoint FindServicePoint (string uriString, IWebProxy proxy)
321 return FindServicePoint (new Uri(uriString), proxy);
324 public static ServicePoint FindServicePoint (Uri address, IWebProxy proxy)
327 throw new ArgumentNullException ("address");
329 RecycleServicePoints ();
331 var origAddress = new Uri (address.Scheme + "://" + address.Authority);
333 bool usesProxy = false;
334 bool useConnect = false;
335 if (proxy != null && !proxy.IsBypassed(address)) {
337 bool isSecure = address.Scheme == "https";
338 address = proxy.GetProxy (address);
339 if (address.Scheme != "http" && !isSecure)
340 throw new NotSupportedException ("Proxy scheme not supported.");
342 if (isSecure && address.Scheme == "http")
346 address = new Uri (address.Scheme + "://" + address.Authority);
348 ServicePoint sp = null;
349 lock (servicePoints) {
350 SPKey key = new SPKey (origAddress, usesProxy ? address : null, useConnect);
351 sp = servicePoints [key] as ServicePoint;
355 if (maxServicePoints > 0 && servicePoints.Count >= maxServicePoints)
356 throw new InvalidOperationException ("maximum number of service points reached");
360 limit = defaultConnectionLimit;
362 string addr = address.ToString ();
363 limit = (int) manager.GetMaxConnections (addr);
365 sp = new ServicePoint (address, limit, maxServicePointIdleTime);
366 sp.Expect100Continue = expectContinue;
367 sp.UseNagleAlgorithm = useNagle;
368 sp.UsesProxy = usesProxy;
369 sp.UseConnect = useConnect;
370 sp.SetTcpKeepAlive (tcp_keepalive, tcp_keepalive_time, tcp_keepalive_interval);
371 servicePoints.Add (key, sp);
379 internal static void RecycleServicePoints ()
381 ArrayList toRemove = new ArrayList ();
382 lock (servicePoints) {
383 IDictionaryEnumerator e = servicePoints.GetEnumerator ();
384 while (e.MoveNext ()) {
385 ServicePoint sp = (ServicePoint) e.Value;
386 if (sp.AvailableForRecycling) {
387 toRemove.Add (e.Key);
391 for (int i = 0; i < toRemove.Count; i++)
392 servicePoints.Remove (toRemove [i]);
394 if (maxServicePoints == 0 || servicePoints.Count <= maxServicePoints)
397 // get rid of the ones with the longest idle time
398 SortedList list = new SortedList (servicePoints.Count);
399 e = servicePoints.GetEnumerator ();
400 while (e.MoveNext ()) {
401 ServicePoint sp = (ServicePoint) e.Value;
402 if (sp.CurrentConnections == 0) {
403 while (list.ContainsKey (sp.IdleSince))
404 sp.IdleSince = sp.IdleSince.AddMilliseconds (1);
405 list.Add (sp.IdleSince, sp.Address);
409 for (int i = 0; i < list.Count && servicePoints.Count > maxServicePoints; i++)
410 servicePoints.Remove (list.GetByIndex (i));
414 internal class ChainValidationHelper {
417 RemoteCertificateValidationCallback cb;
420 static bool is_macosx = System.IO.File.Exists (OSX509Certificates.SecurityLibrary);
421 static X509RevocationMode revocation_mode;
423 static ChainValidationHelper ()
425 revocation_mode = X509RevocationMode.NoCheck;
427 string str = Environment.GetEnvironmentVariable ("MONO_X509_REVOCATION_MODE");
428 if (String.IsNullOrEmpty (str))
430 revocation_mode = (X509RevocationMode) Enum.Parse (typeof (X509RevocationMode), str, true);
436 public ChainValidationHelper (object sender, string hostName)
438 this.sender = sender;
442 public RemoteCertificateValidationCallback ServerCertificateValidationCallback {
445 cb = ServicePointManager.ServerCertificateValidationCallback;
451 // Used when the obsolete ICertificatePolicy is set to DefaultCertificatePolicy
452 // and the new ServerCertificateValidationCallback is not null
453 internal ValidationResult ValidateChain (MSX.X509CertificateCollection certs)
455 // user_denied is true if the user callback is called and returns false
456 bool user_denied = false;
457 if (certs == null || certs.Count == 0)
460 ICertificatePolicy policy = ServicePointManager.CertificatePolicy;
462 X509Certificate2 leaf = new X509Certificate2 (certs [0].RawData);
463 int status11 = 0; // Error code passed to the obsolete ICertificatePolicy callback
464 SslPolicyErrors errors = 0;
465 X509Chain chain = null;
468 // The X509Chain is not really usable with MonoTouch (since the decision is not based on this data)
469 // However if someone wants to override the results (good or bad) from iOS then they will want all
470 // the certificates that the server provided (which generally does not include the root) so, only
471 // if there's a user callback, we'll create the X509Chain but won't build it
472 // ref: https://bugzilla.xamarin.com/show_bug.cgi?id=7245
473 if (ServerCertificateValidationCallback != null) {
475 chain = new X509Chain ();
476 chain.ChainPolicy = new X509ChainPolicy ();
478 chain.ChainPolicy.RevocationMode = revocation_mode;
480 for (int i = 1; i < certs.Count; i++) {
481 X509Certificate2 c2 = new X509Certificate2 (certs [i].RawData);
482 chain.ChainPolicy.ExtraStore.Add (c2);
488 if (!chain.Build (leaf))
489 errors |= GetErrorsFromChain (chain);
490 } catch (Exception e) {
491 Console.Error.WriteLine ("ERROR building certificate chain: {0}", e);
492 Console.Error.WriteLine ("Please, report this problem to the Mono team");
493 errors |= SslPolicyErrors.RemoteCertificateChainErrors;
496 // for OSX and iOS we're using the native API to check for the SSL server policy and host names
498 if (!CheckCertificateUsage (leaf)) {
499 errors |= SslPolicyErrors.RemoteCertificateChainErrors;
500 status11 = -2146762490; //CERT_E_PURPOSE 0x800B0106
503 if (!CheckServerIdentity (certs [0], host)) {
504 errors |= SslPolicyErrors.RemoteCertificateNameMismatch;
505 status11 = -2146762481; // CERT_E_CN_NO_MATCH 0x800B010F
509 // Attempt to use OSX certificates
510 // Ideally we should return the SecTrustResult
511 OSX509Certificates.SecTrustResult trustResult = OSX509Certificates.SecTrustResult.Deny;
513 trustResult = OSX509Certificates.TrustEvaluateSsl (certs, host);
514 // We could use the other values of trustResult to pass this extra information
515 // to the .NET 2 callback for values like SecTrustResult.Confirm
516 result = (trustResult == OSX509Certificates.SecTrustResult.Proceed ||
517 trustResult == OSX509Certificates.SecTrustResult.Unspecified);
523 // TrustEvaluateSsl was successful so there's no trust error
524 // IOW we discard our own chain (since we trust OSX one instead)
527 // callback and DefaultCertificatePolicy needs this since 'result' is not specified
528 status11 = (int) trustResult;
529 errors |= SslPolicyErrors.RemoteCertificateChainErrors;
535 #if MONODROID && SECURITY_DEP
536 result = AndroidPlatform.TrustEvaluateSsl (certs, sender, leaf, chain, errors);
538 // chain.Build() + GetErrorsFromChain() (above) will ALWAYS fail on
539 // Android (there are no mozroots or preinstalled root certificates),
540 // thus `errors` will ALWAYS have RemoteCertificateChainErrors.
541 // Android just verified the chain; clear RemoteCertificateChainErrors.
542 errors &= ~SslPolicyErrors.RemoteCertificateChainErrors;
546 if (policy != null && (!(policy is DefaultCertificatePolicy) || cb == null)) {
547 ServicePoint sp = null;
548 HttpWebRequest req = sender as HttpWebRequest;
550 sp = req.ServicePointNoLock;
551 if (status11 == 0 && errors != 0)
552 status11 = GetStatusFromChain (chain);
555 result = policy.CheckValidationResult (sp, leaf, req, status11);
556 user_denied = !result && !(policy is DefaultCertificatePolicy);
558 // If there's a 2.0 callback, it takes precedence
559 if (ServerCertificateValidationCallback != null) {
560 result = ServerCertificateValidationCallback (sender, leaf, chain, errors);
561 user_denied = !result;
563 return new ValidationResult (result, user_denied, status11);
566 static int GetStatusFromChain (X509Chain chain)
569 foreach (var status in chain.ChainStatus) {
570 X509ChainStatusFlags flags = status.Status;
571 if (flags == X509ChainStatusFlags.NoError)
575 if ((flags & X509ChainStatusFlags.NotTimeValid) != 0) result = 0x800B0101;
576 // CERT_E_VALIDITYPERIODNESTING
577 else if ((flags & X509ChainStatusFlags.NotTimeNested) != 0) result = 0x800B0102;
579 else if ((flags & X509ChainStatusFlags.Revoked) != 0) result = 0x800B010C;
580 // TRUST_E_CERT_SIGNATURE
581 else if ((flags & X509ChainStatusFlags.NotSignatureValid) != 0) result = 0x80096004;
582 // CERT_E_WRONG_USAGE
583 else if ((flags & X509ChainStatusFlags.NotValidForUsage) != 0) result = 0x800B0110;
584 // CERT_E_UNTRUSTEDROOT
585 else if ((flags & X509ChainStatusFlags.UntrustedRoot) != 0) result = 0x800B0109;
586 // CRYPT_E_NO_REVOCATION_CHECK
587 else if ((flags & X509ChainStatusFlags.RevocationStatusUnknown) != 0) result = 0x80092012;
589 else if ((flags & X509ChainStatusFlags.Cyclic) != 0) result = 0x800B010A;
590 // TRUST_E_FAIL - generic
591 else if ((flags & X509ChainStatusFlags.InvalidExtension) != 0) result = 0x800B010B;
592 // CERT_E_UNTRUSTEDROOT
593 else if ((flags & X509ChainStatusFlags.InvalidPolicyConstraints) != 0) result = 0x800B010D;
594 // TRUST_E_BASIC_CONSTRAINTS
595 else if ((flags & X509ChainStatusFlags.InvalidBasicConstraints) != 0) result = 0x80096019;
596 // CERT_E_INVALID_NAME
597 else if ((flags & X509ChainStatusFlags.InvalidNameConstraints) != 0) result = 0x800B0114;
598 // CERT_E_INVALID_NAME
599 else if ((flags & X509ChainStatusFlags.HasNotSupportedNameConstraint) != 0) result = 0x800B0114;
600 // CERT_E_INVALID_NAME
601 else if ((flags & X509ChainStatusFlags.HasNotDefinedNameConstraint) != 0) result = 0x800B0114;
602 // CERT_E_INVALID_NAME
603 else if ((flags & X509ChainStatusFlags.HasNotPermittedNameConstraint) != 0) result = 0x800B0114;
604 // CERT_E_INVALID_NAME
605 else if ((flags & X509ChainStatusFlags.HasExcludedNameConstraint) != 0) result = 0x800B0114;
607 else if ((flags & X509ChainStatusFlags.PartialChain) != 0) result = 0x800B010A;
609 else if ((flags & X509ChainStatusFlags.CtlNotTimeValid) != 0) result = 0x800B0101;
610 // TRUST_E_CERT_SIGNATURE
611 else if ((flags & X509ChainStatusFlags.CtlNotSignatureValid) != 0) result = 0x80096004;
612 // CERT_E_WRONG_USAGE
613 else if ((flags & X509ChainStatusFlags.CtlNotValidForUsage) != 0) result = 0x800B0110;
614 // CRYPT_E_NO_REVOCATION_CHECK
615 else if ((flags & X509ChainStatusFlags.OfflineRevocation) != 0) result = 0x80092012;
616 // CERT_E_ISSUERCHAINING
617 else if ((flags & X509ChainStatusFlags.NoIssuanceChainPolicy) != 0) result = 0x800B0107;
618 else result = 0x800B010B; // TRUST_E_FAIL - generic
620 break; // Exit the loop on the first error
625 static SslPolicyErrors GetErrorsFromChain (X509Chain chain)
627 SslPolicyErrors errors = SslPolicyErrors.None;
628 foreach (var status in chain.ChainStatus) {
629 if (status.Status == X509ChainStatusFlags.NoError)
631 errors |= SslPolicyErrors.RemoteCertificateChainErrors;
637 static X509KeyUsageFlags s_flags = X509KeyUsageFlags.DigitalSignature |
638 X509KeyUsageFlags.KeyAgreement |
639 X509KeyUsageFlags.KeyEncipherment;
640 // Adapted to System 2.0+ from TlsServerCertificate.cs
641 //------------------------------
642 // Note: this method only works for RSA certificates
643 // DH certificates requires some changes - does anyone use one ?
644 static bool CheckCertificateUsage (X509Certificate2 cert)
647 // certificate extensions are required for this
648 // we "must" accept older certificates without proofs
649 if (cert.Version < 3)
652 X509KeyUsageExtension kux = (cert.Extensions ["2.5.29.15"] as X509KeyUsageExtension);
653 X509EnhancedKeyUsageExtension eku = (cert.Extensions ["2.5.29.37"] as X509EnhancedKeyUsageExtension);
654 if (kux != null && eku != null) {
655 // RFC3280 states that when both KeyUsageExtension and
656 // ExtendedKeyUsageExtension are present then BOTH should
658 if ((kux.KeyUsages & s_flags) == 0)
660 return eku.EnhancedKeyUsages ["1.3.6.1.5.5.7.3.1"] != null ||
661 eku.EnhancedKeyUsages ["2.16.840.1.113730.4.1"] != null;
662 } else if (kux != null) {
663 return ((kux.KeyUsages & s_flags) != 0);
664 } else if (eku != null) {
665 // Server Authentication (1.3.6.1.5.5.7.3.1) or
666 // Netscape Server Gated Crypto (2.16.840.1.113730.4)
667 return eku.EnhancedKeyUsages ["1.3.6.1.5.5.7.3.1"] != null ||
668 eku.EnhancedKeyUsages ["2.16.840.1.113730.4.1"] != null;
671 // last chance - try with older (deprecated) Netscape extensions
672 X509Extension ext = cert.Extensions ["2.16.840.1.113730.1.1"];
674 string text = ext.NetscapeCertType (false);
675 return text.IndexOf ("SSL Server Authentication", StringComparison.Ordinal) != -1;
678 } catch (Exception e) {
679 Console.Error.WriteLine ("ERROR processing certificate: {0}", e);
680 Console.Error.WriteLine ("Please, report this problem to the Mono team");
685 // RFC2818 - HTTP Over TLS, Section 3.1
686 // http://www.ietf.org/rfc/rfc2818.txt
688 // 1. if present MUST use subjectAltName dNSName as identity
689 // 1.1. if multiples entries a match of any one is acceptable
690 // 1.2. wildcard * is acceptable
691 // 2. URI may be an IP address -> subjectAltName.iPAddress
692 // 2.1. exact match is required
693 // 3. Use of the most specific Common Name (CN=) in the Subject
694 // 3.1 Existing practice but DEPRECATED
695 static bool CheckServerIdentity (MSX.X509Certificate cert, string targetHost)
698 MSX.X509Extension ext = cert.Extensions ["2.5.29.17"];
701 SubjectAltNameExtension subjectAltName = new SubjectAltNameExtension (ext);
702 // 1.1 - multiple dNSName
703 foreach (string dns in subjectAltName.DNSNames) {
704 // 1.2 TODO - wildcard support
705 if (Match (targetHost, dns))
709 foreach (string ip in subjectAltName.IPAddresses) {
710 // 2.1. Exact match required
711 if (ip == targetHost)
715 // 3. Common Name (CN=)
716 return CheckDomainName (cert.SubjectName, targetHost);
717 } catch (Exception e) {
718 Console.Error.WriteLine ("ERROR processing certificate: {0}", e);
719 Console.Error.WriteLine ("Please, report this problem to the Mono team");
724 static bool CheckDomainName (string subjectName, string targetHost)
726 string domainName = String.Empty;
727 Regex search = new Regex(@"CN\s*=\s*([^,]*)");
728 MatchCollection elements = search.Matches(subjectName);
729 if (elements.Count == 1) {
730 if (elements[0].Success)
731 domainName = elements[0].Groups[1].Value.ToString();
734 return Match (targetHost, domainName);
737 // ensure the pattern is valid wrt to RFC2595 and RFC2818
738 // http://www.ietf.org/rfc/rfc2595.txt
739 // http://www.ietf.org/rfc/rfc2818.txt
740 static bool Match (string hostname, string pattern)
742 // check if this is a pattern
743 int index = pattern.IndexOf ('*');
745 // not a pattern, do a direct case-insensitive comparison
746 return (String.Compare (hostname, pattern, true, CultureInfo.InvariantCulture) == 0);
749 // check pattern validity
750 // A "*" wildcard character MAY be used as the left-most name component in the certificate.
752 // unless this is the last char (valid)
753 if (index != pattern.Length - 1) {
754 // then the next char must be a dot .'.
755 if (pattern [index + 1] != '.')
759 // only one (A) wildcard is supported
760 int i2 = pattern.IndexOf ('*', index + 1);
764 // match the end of the pattern
765 string end = pattern.Substring (index + 1);
766 int length = hostname.Length - end.Length;
767 // no point to check a pattern that is longer than the hostname
771 if (String.Compare (hostname, length, end, 0, end.Length, true, CultureInfo.InvariantCulture) != 0)
774 // special case, we start with the wildcard
776 // ensure we hostname non-matched part (start) doesn't contain a dot
777 int i3 = hostname.IndexOf ('.');
778 return ((i3 == -1) || (i3 >= (hostname.Length - end.Length)));
781 // match the start of the pattern
782 string start = pattern.Substring (0, index);
783 return (String.Compare (hostname, 0, start, 0, start.Length, true, CultureInfo.InvariantCulture) == 0);