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 if ((servicePoints.Count % 4) == 0)
330 RecycleServicePoints ();
332 var origAddress = new Uri (address.Scheme + "://" + address.Authority);
334 bool usesProxy = false;
335 bool useConnect = false;
336 if (proxy != null && !proxy.IsBypassed(address)) {
338 bool isSecure = address.Scheme == "https";
339 address = proxy.GetProxy (address);
340 if (address.Scheme != "http" && !isSecure)
341 throw new NotSupportedException ("Proxy scheme not supported.");
343 if (isSecure && address.Scheme == "http")
347 address = new Uri (address.Scheme + "://" + address.Authority);
349 ServicePoint sp = null;
350 SPKey key = new SPKey (origAddress, usesProxy ? address : null, useConnect);
351 lock (servicePoints) {
352 sp = servicePoints [key] as ServicePoint;
356 if (maxServicePoints > 0 && servicePoints.Count >= maxServicePoints)
357 throw new InvalidOperationException ("maximum number of service points reached");
361 limit = defaultConnectionLimit;
363 string addr = address.ToString ();
364 limit = (int) manager.GetMaxConnections (addr);
366 sp = new ServicePoint (address, limit, maxServicePointIdleTime);
367 sp.Expect100Continue = expectContinue;
368 sp.UseNagleAlgorithm = useNagle;
369 sp.UsesProxy = usesProxy;
370 sp.UseConnect = useConnect;
371 sp.SetTcpKeepAlive (tcp_keepalive, tcp_keepalive_time, tcp_keepalive_interval);
372 servicePoints.Add (key, sp);
380 internal static void RecycleServicePoints ()
382 ArrayList toRemove = new ArrayList ();
383 lock (servicePoints) {
384 IDictionaryEnumerator e = servicePoints.GetEnumerator ();
385 while (e.MoveNext ()) {
386 ServicePoint sp = (ServicePoint) e.Value;
387 if (sp.AvailableForRecycling) {
388 toRemove.Add (e.Key);
392 for (int i = 0; i < toRemove.Count; i++)
393 servicePoints.Remove (toRemove [i]);
395 if (maxServicePoints == 0 || servicePoints.Count <= maxServicePoints)
398 // get rid of the ones with the longest idle time
399 SortedList list = new SortedList (servicePoints.Count);
400 e = servicePoints.GetEnumerator ();
401 while (e.MoveNext ()) {
402 ServicePoint sp = (ServicePoint) e.Value;
403 if (sp.CurrentConnections == 0) {
404 while (list.ContainsKey (sp.IdleSince))
405 sp.IdleSince = sp.IdleSince.AddMilliseconds (1);
406 list.Add (sp.IdleSince, sp.Address);
410 for (int i = 0; i < list.Count && servicePoints.Count > maxServicePoints; i++)
411 servicePoints.Remove (list.GetByIndex (i));
415 internal class ChainValidationHelper {
418 RemoteCertificateValidationCallback cb;
421 static bool is_macosx = System.IO.File.Exists (OSX509Certificates.SecurityLibrary);
422 static X509RevocationMode revocation_mode;
424 static ChainValidationHelper ()
426 revocation_mode = X509RevocationMode.NoCheck;
428 string str = Environment.GetEnvironmentVariable ("MONO_X509_REVOCATION_MODE");
429 if (String.IsNullOrEmpty (str))
431 revocation_mode = (X509RevocationMode) Enum.Parse (typeof (X509RevocationMode), str, true);
437 public ChainValidationHelper (object sender, string hostName)
439 this.sender = sender;
443 public RemoteCertificateValidationCallback ServerCertificateValidationCallback {
446 cb = ServicePointManager.ServerCertificateValidationCallback;
452 // Used when the obsolete ICertificatePolicy is set to DefaultCertificatePolicy
453 // and the new ServerCertificateValidationCallback is not null
454 internal ValidationResult ValidateChain (MSX.X509CertificateCollection certs)
456 // user_denied is true if the user callback is called and returns false
457 bool user_denied = false;
458 if (certs == null || certs.Count == 0)
461 ICertificatePolicy policy = ServicePointManager.CertificatePolicy;
463 X509Certificate2 leaf = new X509Certificate2 (certs [0].RawData);
464 int status11 = 0; // Error code passed to the obsolete ICertificatePolicy callback
465 SslPolicyErrors errors = 0;
466 X509Chain chain = null;
469 // The X509Chain is not really usable with MonoTouch (since the decision is not based on this data)
470 // However if someone wants to override the results (good or bad) from iOS then they will want all
471 // the certificates that the server provided (which generally does not include the root) so, only
472 // if there's a user callback, we'll create the X509Chain but won't build it
473 // ref: https://bugzilla.xamarin.com/show_bug.cgi?id=7245
474 if (ServerCertificateValidationCallback != null) {
476 chain = new X509Chain ();
477 chain.ChainPolicy = new X509ChainPolicy ();
479 chain.ChainPolicy.RevocationMode = revocation_mode;
481 for (int i = 1; i < certs.Count; i++) {
482 X509Certificate2 c2 = new X509Certificate2 (certs [i].RawData);
483 chain.ChainPolicy.ExtraStore.Add (c2);
489 if (!chain.Build (leaf))
490 errors |= GetErrorsFromChain (chain);
491 } catch (Exception e) {
492 Console.Error.WriteLine ("ERROR building certificate chain: {0}", e);
493 Console.Error.WriteLine ("Please, report this problem to the Mono team");
494 errors |= SslPolicyErrors.RemoteCertificateChainErrors;
497 // for OSX and iOS we're using the native API to check for the SSL server policy and host names
499 if (!CheckCertificateUsage (leaf)) {
500 errors |= SslPolicyErrors.RemoteCertificateChainErrors;
501 status11 = -2146762490; //CERT_E_PURPOSE 0x800B0106
504 if (!CheckServerIdentity (certs [0], host)) {
505 errors |= SslPolicyErrors.RemoteCertificateNameMismatch;
506 status11 = -2146762481; // CERT_E_CN_NO_MATCH 0x800B010F
510 // Attempt to use OSX certificates
511 // Ideally we should return the SecTrustResult
512 OSX509Certificates.SecTrustResult trustResult = OSX509Certificates.SecTrustResult.Deny;
514 trustResult = OSX509Certificates.TrustEvaluateSsl (certs, host);
515 // We could use the other values of trustResult to pass this extra information
516 // to the .NET 2 callback for values like SecTrustResult.Confirm
517 result = (trustResult == OSX509Certificates.SecTrustResult.Proceed ||
518 trustResult == OSX509Certificates.SecTrustResult.Unspecified);
524 // TrustEvaluateSsl was successful so there's no trust error
525 // IOW we discard our own chain (since we trust OSX one instead)
528 // callback and DefaultCertificatePolicy needs this since 'result' is not specified
529 status11 = (int) trustResult;
530 errors |= SslPolicyErrors.RemoteCertificateChainErrors;
536 #if MONODROID && SECURITY_DEP
537 result = AndroidPlatform.TrustEvaluateSsl (certs, sender, leaf, chain, errors);
539 // chain.Build() + GetErrorsFromChain() (above) will ALWAYS fail on
540 // Android (there are no mozroots or preinstalled root certificates),
541 // thus `errors` will ALWAYS have RemoteCertificateChainErrors.
542 // Android just verified the chain; clear RemoteCertificateChainErrors.
543 errors &= ~SslPolicyErrors.RemoteCertificateChainErrors;
547 if (policy != null && (!(policy is DefaultCertificatePolicy) || cb == null)) {
548 ServicePoint sp = null;
549 HttpWebRequest req = sender as HttpWebRequest;
551 sp = req.ServicePointNoLock;
552 if (status11 == 0 && errors != 0)
553 status11 = GetStatusFromChain (chain);
556 result = policy.CheckValidationResult (sp, leaf, req, status11);
557 user_denied = !result && !(policy is DefaultCertificatePolicy);
559 // If there's a 2.0 callback, it takes precedence
560 if (ServerCertificateValidationCallback != null) {
561 result = ServerCertificateValidationCallback (sender, leaf, chain, errors);
562 user_denied = !result;
564 return new ValidationResult (result, user_denied, status11);
567 static int GetStatusFromChain (X509Chain chain)
570 foreach (var status in chain.ChainStatus) {
571 X509ChainStatusFlags flags = status.Status;
572 if (flags == X509ChainStatusFlags.NoError)
576 if ((flags & X509ChainStatusFlags.NotTimeValid) != 0) result = 0x800B0101;
577 // CERT_E_VALIDITYPERIODNESTING
578 else if ((flags & X509ChainStatusFlags.NotTimeNested) != 0) result = 0x800B0102;
580 else if ((flags & X509ChainStatusFlags.Revoked) != 0) result = 0x800B010C;
581 // TRUST_E_CERT_SIGNATURE
582 else if ((flags & X509ChainStatusFlags.NotSignatureValid) != 0) result = 0x80096004;
583 // CERT_E_WRONG_USAGE
584 else if ((flags & X509ChainStatusFlags.NotValidForUsage) != 0) result = 0x800B0110;
585 // CERT_E_UNTRUSTEDROOT
586 else if ((flags & X509ChainStatusFlags.UntrustedRoot) != 0) result = 0x800B0109;
587 // CRYPT_E_NO_REVOCATION_CHECK
588 else if ((flags & X509ChainStatusFlags.RevocationStatusUnknown) != 0) result = 0x80092012;
590 else if ((flags & X509ChainStatusFlags.Cyclic) != 0) result = 0x800B010A;
591 // TRUST_E_FAIL - generic
592 else if ((flags & X509ChainStatusFlags.InvalidExtension) != 0) result = 0x800B010B;
593 // CERT_E_UNTRUSTEDROOT
594 else if ((flags & X509ChainStatusFlags.InvalidPolicyConstraints) != 0) result = 0x800B010D;
595 // TRUST_E_BASIC_CONSTRAINTS
596 else if ((flags & X509ChainStatusFlags.InvalidBasicConstraints) != 0) result = 0x80096019;
597 // CERT_E_INVALID_NAME
598 else if ((flags & X509ChainStatusFlags.InvalidNameConstraints) != 0) result = 0x800B0114;
599 // CERT_E_INVALID_NAME
600 else if ((flags & X509ChainStatusFlags.HasNotSupportedNameConstraint) != 0) result = 0x800B0114;
601 // CERT_E_INVALID_NAME
602 else if ((flags & X509ChainStatusFlags.HasNotDefinedNameConstraint) != 0) result = 0x800B0114;
603 // CERT_E_INVALID_NAME
604 else if ((flags & X509ChainStatusFlags.HasNotPermittedNameConstraint) != 0) result = 0x800B0114;
605 // CERT_E_INVALID_NAME
606 else if ((flags & X509ChainStatusFlags.HasExcludedNameConstraint) != 0) result = 0x800B0114;
608 else if ((flags & X509ChainStatusFlags.PartialChain) != 0) result = 0x800B010A;
610 else if ((flags & X509ChainStatusFlags.CtlNotTimeValid) != 0) result = 0x800B0101;
611 // TRUST_E_CERT_SIGNATURE
612 else if ((flags & X509ChainStatusFlags.CtlNotSignatureValid) != 0) result = 0x80096004;
613 // CERT_E_WRONG_USAGE
614 else if ((flags & X509ChainStatusFlags.CtlNotValidForUsage) != 0) result = 0x800B0110;
615 // CRYPT_E_NO_REVOCATION_CHECK
616 else if ((flags & X509ChainStatusFlags.OfflineRevocation) != 0) result = 0x80092012;
617 // CERT_E_ISSUERCHAINING
618 else if ((flags & X509ChainStatusFlags.NoIssuanceChainPolicy) != 0) result = 0x800B0107;
619 else result = 0x800B010B; // TRUST_E_FAIL - generic
621 break; // Exit the loop on the first error
626 static SslPolicyErrors GetErrorsFromChain (X509Chain chain)
628 SslPolicyErrors errors = SslPolicyErrors.None;
629 foreach (var status in chain.ChainStatus) {
630 if (status.Status == X509ChainStatusFlags.NoError)
632 errors |= SslPolicyErrors.RemoteCertificateChainErrors;
638 static X509KeyUsageFlags s_flags = X509KeyUsageFlags.DigitalSignature |
639 X509KeyUsageFlags.KeyAgreement |
640 X509KeyUsageFlags.KeyEncipherment;
641 // Adapted to System 2.0+ from TlsServerCertificate.cs
642 //------------------------------
643 // Note: this method only works for RSA certificates
644 // DH certificates requires some changes - does anyone use one ?
645 static bool CheckCertificateUsage (X509Certificate2 cert)
648 // certificate extensions are required for this
649 // we "must" accept older certificates without proofs
650 if (cert.Version < 3)
653 X509KeyUsageExtension kux = (cert.Extensions ["2.5.29.15"] as X509KeyUsageExtension);
654 X509EnhancedKeyUsageExtension eku = (cert.Extensions ["2.5.29.37"] as X509EnhancedKeyUsageExtension);
655 if (kux != null && eku != null) {
656 // RFC3280 states that when both KeyUsageExtension and
657 // ExtendedKeyUsageExtension are present then BOTH should
659 if ((kux.KeyUsages & s_flags) == 0)
661 return eku.EnhancedKeyUsages ["1.3.6.1.5.5.7.3.1"] != null ||
662 eku.EnhancedKeyUsages ["2.16.840.1.113730.4.1"] != null;
663 } else if (kux != null) {
664 return ((kux.KeyUsages & s_flags) != 0);
665 } else if (eku != null) {
666 // Server Authentication (1.3.6.1.5.5.7.3.1) or
667 // Netscape Server Gated Crypto (2.16.840.1.113730.4)
668 return eku.EnhancedKeyUsages ["1.3.6.1.5.5.7.3.1"] != null ||
669 eku.EnhancedKeyUsages ["2.16.840.1.113730.4.1"] != null;
672 // last chance - try with older (deprecated) Netscape extensions
673 X509Extension ext = cert.Extensions ["2.16.840.1.113730.1.1"];
675 string text = ext.NetscapeCertType (false);
676 return text.IndexOf ("SSL Server Authentication", StringComparison.Ordinal) != -1;
679 } catch (Exception e) {
680 Console.Error.WriteLine ("ERROR processing certificate: {0}", e);
681 Console.Error.WriteLine ("Please, report this problem to the Mono team");
686 // RFC2818 - HTTP Over TLS, Section 3.1
687 // http://www.ietf.org/rfc/rfc2818.txt
689 // 1. if present MUST use subjectAltName dNSName as identity
690 // 1.1. if multiples entries a match of any one is acceptable
691 // 1.2. wildcard * is acceptable
692 // 2. URI may be an IP address -> subjectAltName.iPAddress
693 // 2.1. exact match is required
694 // 3. Use of the most specific Common Name (CN=) in the Subject
695 // 3.1 Existing practice but DEPRECATED
696 static bool CheckServerIdentity (MSX.X509Certificate cert, string targetHost)
699 MSX.X509Extension ext = cert.Extensions ["2.5.29.17"];
702 SubjectAltNameExtension subjectAltName = new SubjectAltNameExtension (ext);
703 // 1.1 - multiple dNSName
704 foreach (string dns in subjectAltName.DNSNames) {
705 // 1.2 TODO - wildcard support
706 if (Match (targetHost, dns))
710 foreach (string ip in subjectAltName.IPAddresses) {
711 // 2.1. Exact match required
712 if (ip == targetHost)
716 // 3. Common Name (CN=)
717 return CheckDomainName (cert.SubjectName, targetHost);
718 } catch (Exception e) {
719 Console.Error.WriteLine ("ERROR processing certificate: {0}", e);
720 Console.Error.WriteLine ("Please, report this problem to the Mono team");
725 static bool CheckDomainName (string subjectName, string targetHost)
727 string domainName = String.Empty;
728 Regex search = new Regex(@"CN\s*=\s*([^,]*)");
729 MatchCollection elements = search.Matches(subjectName);
730 if (elements.Count == 1) {
731 if (elements[0].Success)
732 domainName = elements[0].Groups[1].Value.ToString();
735 return Match (targetHost, domainName);
738 // ensure the pattern is valid wrt to RFC2595 and RFC2818
739 // http://www.ietf.org/rfc/rfc2595.txt
740 // http://www.ietf.org/rfc/rfc2818.txt
741 static bool Match (string hostname, string pattern)
743 // check if this is a pattern
744 int index = pattern.IndexOf ('*');
746 // not a pattern, do a direct case-insensitive comparison
747 return (String.Compare (hostname, pattern, true, CultureInfo.InvariantCulture) == 0);
750 // check pattern validity
751 // A "*" wildcard character MAY be used as the left-most name component in the certificate.
753 // unless this is the last char (valid)
754 if (index != pattern.Length - 1) {
755 // then the next char must be a dot .'.
756 if (pattern [index + 1] != '.')
760 // only one (A) wildcard is supported
761 int i2 = pattern.IndexOf ('*', index + 1);
765 // match the end of the pattern
766 string end = pattern.Substring (index + 1);
767 int length = hostname.Length - end.Length;
768 // no point to check a pattern that is longer than the hostname
772 if (String.Compare (hostname, length, end, 0, end.Length, true, CultureInfo.InvariantCulture) != 0)
775 // special case, we start with the wildcard
777 // ensure we hostname non-matched part (start) doesn't contain a dot
778 int i3 = hostname.IndexOf ('.');
779 return ((i3 == -1) || (i3 >= (hostname.Length - end.Length)));
782 // match the start of the pattern
783 string start = pattern.Substring (0, index);
784 return (String.Compare (hostname, 0, start, 0, start.Length, true, CultureInfo.InvariantCulture) == 0);