File: BaseUriWithWildcard.cs

package info (click to toggle)
mono 4.6.2.7%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (342 lines) | stat: -rw-r--r-- 13,241 bytes parent folder | download | duplicates (9)
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
//----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//----------------------------------------------------------------------------

namespace System.ServiceModel.Channels
{
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Globalization;
    using System.Runtime;
    using System.Runtime.Serialization;
    using System.ServiceModel;

    [DataContract]
    sealed class BaseUriWithWildcard
    {
        [DataMember]
        Uri baseAddress;

        const char segmentDelimiter = '/';

        [DataMember]
        HostNameComparisonMode hostNameComparisonMode;
        const string plus = "+";
        const string star = "*";
        const int HttpUriDefaultPort = 80;
        const int HttpsUriDefaultPort = 443;

        // Derived from [DataMember] fields
        Comparand comparand;
        int hashCode;

        public BaseUriWithWildcard(Uri baseAddress, HostNameComparisonMode hostNameComparisonMode)
        {
            this.baseAddress = baseAddress;
            this.hostNameComparisonMode = hostNameComparisonMode;
            this.SetComparisonAddressAndHashCode();

            // Note the Uri may contain query string for WSDL purpose.
            // So do not check IsValid().
        }

        BaseUriWithWildcard(string protocol, int defaultPort, string binding, int segmentCount, string path, string sampleBinding)
        {
            string[] urlParameters = SplitBinding(binding);

            if (urlParameters.Length != segmentCount)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new UriFormatException(SR.GetString(SR.Hosting_MisformattedBinding, binding, protocol, sampleBinding)));
            }

            int currentIndex = segmentCount - 1;
            string host = ParseHostAndHostNameComparisonMode(urlParameters[currentIndex]);

            int port = -1;

            if (--currentIndex >= 0)
            {
                string portString = urlParameters[currentIndex].Trim();

                if (!string.IsNullOrEmpty(portString) &&
                    !int.TryParse(portString, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out port))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new UriFormatException(SR.GetString(SR.Hosting_MisformattedPort, protocol, binding, portString)));
                }

                if (port == defaultPort)
                {
                    // Set to -1 so that Uri does not show it in the string.
                    port = -1;
                }
            }
            try
            {
                Fx.Assert(path != null, "path should never be null here");
                this.baseAddress = new UriBuilder(protocol, host, port, path).Uri;
            }
            catch (Exception exception)
            {
                if (Fx.IsFatal(exception))
                {
                    throw;
                }

                DiagnosticUtility.TraceHandledException(exception, TraceEventType.Error);

                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new UriFormatException(SR.GetString(SR.Hosting_MisformattedBindingData, binding,
                    protocol)));
            }
            SetComparisonAddressAndHashCode();
        }

        internal Uri BaseAddress
        {
            get { return this.baseAddress; }
        }

        internal HostNameComparisonMode HostNameComparisonMode
        {
            get { return this.hostNameComparisonMode; }
        }

        static string[] SplitBinding(string binding)
        {
            bool parsingIPv6Address = false;
            string[] tokens = null;
            const char splitChar = ':', startIPv6Address = '[', endIPv6Address = ']';

            List<int> splitLocations = null;

            for (int i = 0; i < binding.Length; i++)
            {
                if (parsingIPv6Address && binding[i] == endIPv6Address)
                {
                    parsingIPv6Address = false;
                }
                else if (binding[i] == startIPv6Address)
                {
                    parsingIPv6Address = true;
                }
                else if (!parsingIPv6Address && binding[i] == splitChar)
                {
                    if (splitLocations == null)
                    {
                        splitLocations = new List<int>();
                    }
                    splitLocations.Add(i);
                }
            }

            if (splitLocations == null)
            {
                tokens = new string[] { binding };
            }
            else
            {
                tokens = new string[splitLocations.Count + 1];
                int startIndex = 0;
                for (int i = 0; i < tokens.Length; i++)
                {
                    if (i < splitLocations.Count)
                    {
                        int nextSplitIndex = splitLocations[i];
                        tokens[i] = binding.Substring(startIndex, nextSplitIndex - startIndex);
                        startIndex = nextSplitIndex + 1;
                    }
                    else //splitting the last segment
                    {
                        if (startIndex < binding.Length)
                        {
                            tokens[i] = binding.Substring(startIndex, binding.Length - startIndex);
                        }
                        else
                        {
                            //splitChar was the last character in the string
                            tokens[i] = string.Empty;
                        }
                    }
                }
            }
            return tokens;
        }

        internal static BaseUriWithWildcard CreateHostedUri(string protocol, string binding, string path)
        {
            Fx.Assert(protocol != null, "caller must verify");

            if (binding == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("binding");
            }

            if (path == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("path");
            }

            if (protocol.Equals(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase))
            {
                // For http, binding format is: "<ipAddress>:<port>:<hostName>"
                // as specified in http://www.microsoft.com/resources/documentation/WindowsServ/2003/standard/proddocs/en-us/Default.asp?url=/resources/documentation/WindowsServ/2003/standard/proddocs/en-us/ref_mb_serverbindings.asp
                return new BaseUriWithWildcard(Uri.UriSchemeHttp, HttpUriDefaultPort, binding, 3, path, ":80:");
            }
            else if (protocol.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase))
            {
                // For https, binding format is the same as http
                return new BaseUriWithWildcard(Uri.UriSchemeHttps, HttpsUriDefaultPort, binding, 3, path, ":443:");
            }
            else if (protocol.Equals(Uri.UriSchemeNetTcp, StringComparison.OrdinalIgnoreCase))
            {
                // For net.tcp, binding format is: "<port>:<hostName>"
                return new BaseUriWithWildcard(Uri.UriSchemeNetTcp, TcpUri.DefaultPort, binding, 2, path, "808:*");
            }
            else if (protocol.Equals(Uri.UriSchemeNetPipe, StringComparison.OrdinalIgnoreCase))
            {
                return CreateHostedPipeUri(binding, path);
            }
            else if (protocol.Equals(MsmqUri.NetMsmqAddressTranslator.Scheme, StringComparison.OrdinalIgnoreCase))
            {
                return new BaseUriWithWildcard(MsmqUri.NetMsmqAddressTranslator.Scheme, -1, binding, 1, path, "*");
            }
            else if (protocol.Equals(MsmqUri.FormatNameAddressTranslator.Scheme, StringComparison.OrdinalIgnoreCase))
            {
                return new BaseUriWithWildcard(MsmqUri.FormatNameAddressTranslator.Scheme, -1, binding, 1, path, "*");
            }

            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new UriFormatException(SR.GetString(SR.Hosting_NotSupportedProtocol, binding)));
        }

        internal static BaseUriWithWildcard CreateHostedPipeUri(string binding, string path)
        {
            // For net.pipe, binding format is: "<hostName>"
            return new BaseUriWithWildcard(Uri.UriSchemeNetPipe, -1, binding, 1, path, "*");
        }

        public override bool Equals(object o)
        {
            BaseUriWithWildcard other = o as BaseUriWithWildcard;

            if (other == null || other.hashCode != this.hashCode || other.hostNameComparisonMode != this.hostNameComparisonMode ||
                other.comparand.Port != this.comparand.Port)
            {
                return false;
            }
            if (!object.ReferenceEquals(other.comparand.Scheme, this.comparand.Scheme))
            {
                return false;
            }
            return this.comparand.Address.Equals(other.comparand.Address);
        }

        public override int GetHashCode()
        {
            return this.hashCode;
        }

        internal bool IsBaseOf(Uri fullAddress)
        {
            if ((object)baseAddress.Scheme != (object)fullAddress.Scheme)
            {
                return false;
            }

            if (baseAddress.Port != fullAddress.Port)
            {
                return false;
            }

            if (this.HostNameComparisonMode == HostNameComparisonMode.Exact)
            {
                if (string.Compare(baseAddress.Host, fullAddress.Host, StringComparison.OrdinalIgnoreCase) != 0)
                {
                    return false;
                }
            }
            string s1 = baseAddress.GetComponents(UriComponents.Path | UriComponents.KeepDelimiter, UriFormat.Unescaped);
            string s2 = fullAddress.GetComponents(UriComponents.Path | UriComponents.KeepDelimiter, UriFormat.Unescaped);

            if (s1.Length > s2.Length)
            {
                return false;
            }

            if (s1.Length < s2.Length &&
                s1[s1.Length - 1] != segmentDelimiter &&
                s2[s1.Length] != segmentDelimiter)
            {
                // Matching over segments
                return false;
            }
            return string.Compare(s2, 0, s1, 0, s1.Length, StringComparison.OrdinalIgnoreCase) == 0;
        }

        [OnDeserialized]
        internal void OnDeserialized(StreamingContext context)
        {
            UriSchemeKeyedCollection.ValidateBaseAddress(baseAddress, "context");

            if (!HostNameComparisonModeHelper.IsDefined(this.HostNameComparisonMode))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("context", SR.GetString(SR.Hosting_BaseUriDeserializedNotValid));
            }
            this.SetComparisonAddressAndHashCode();
        }

        string ParseHostAndHostNameComparisonMode(string host)
        {
            if (string.IsNullOrEmpty(host) || host.Equals(star))
            {
                hostNameComparisonMode = HostNameComparisonMode.WeakWildcard;
                host = DnsCache.MachineName;
            }
            else if (host.Equals(plus))
            {
                hostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
                host = DnsCache.MachineName;
            }
            else
            {
                hostNameComparisonMode = HostNameComparisonMode.Exact;
            }
            return host;
        }

        void SetComparisonAddressAndHashCode()
        {
            if (this.HostNameComparisonMode == HostNameComparisonMode.Exact)
            {
                // Use canonical string representation of the full base address for comparison
                this.comparand.Address = this.baseAddress.ToString();
            }
            else
            {
                // Use canonical string representation of the absolute path for comparison
                this.comparand.Address = this.baseAddress.GetComponents(UriComponents.Path | UriComponents.KeepDelimiter, UriFormat.UriEscaped);
            }

            this.comparand.Port = this.baseAddress.Port;
            this.comparand.Scheme = this.baseAddress.Scheme;

            if ((this.comparand.Port == -1) && ((object)this.comparand.Scheme == (object)Uri.UriSchemeNetTcp))
            {
                // Compensate for the fact that the Uri type doesn't know about our default TCP port number
                this.comparand.Port = TcpUri.DefaultPort;
            }
            this.hashCode = this.comparand.Address.GetHashCode() ^ this.comparand.Port ^ (int)this.HostNameComparisonMode;
        }

        public override string ToString()
        {
            return string.Format(CultureInfo.InvariantCulture, "{0}:{1}", this.HostNameComparisonMode, this.BaseAddress);
        }

        struct Comparand
        {
            public string Address;
            public int Port;
            public string Scheme;
        }
    }
}