Welcome to mirror list, hosted at ThFree Co, Russian Federation.

BindingAddress.cs « src « Http « Http « src - github.com/dotnet/aspnetcore.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 6e6e12b46ae09458337408dc856f79bd7c8dbed0 (plain)
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Globalization;

namespace Microsoft.AspNetCore.Http;

/// <summary>
/// An address that a HTTP server may bind to.
/// </summary>
public class BindingAddress
{
    private const string UnixPipeHostPrefix = "unix:/";
    private const string NamedPipeHostPrefix = "pipe:";

    private BindingAddress(string host, string pathBase, int port, string scheme)
    {
        Host = host;
        PathBase = pathBase;
        Port = port;
        Scheme = scheme;
    }

    /// <summary>
    /// Initializes a new instance of <see cref="BindingAddress"/>.
    /// </summary>
    [Obsolete("This constructor is obsolete and will be removed in a future version. Use BindingAddress.Parse(address) to create a BindingAddress instance.")]
    public BindingAddress()
    {
        throw new InvalidOperationException("This constructor is obsolete and will be removed in a future version. Use BindingAddress.Parse(address) to create a BindingAddress instance.");
    }

    /// <summary>
    /// Gets the host component.
    /// </summary>
    public string Host { get; }

    /// <summary>
    /// Gets the path component.
    /// </summary>
    public string PathBase { get; }

    /// <summary>
    /// Gets the port.
    /// </summary>
    public int Port { get; }

    /// <summary>
    /// Gets the scheme component.
    /// </summary>
    public string Scheme { get; }

    /// <summary>
    /// Gets a value that determines if this instance represents a Unix pipe.
    /// <para>
    /// Returns <see langword="true"/> if <see cref="Host"/> starts with <c>unix://</c> prefix.
    /// </para>
    /// </summary>
    public bool IsUnixPipe => Host.StartsWith(UnixPipeHostPrefix, StringComparison.Ordinal);

    /// <summary>
    /// Gets a value that determines if this instance represents a named pipe.
    /// <para>
    /// Returns <see langword="true"/> if <see cref="Host"/> starts with <c>pipe:</c> prefix.
    /// </para>
    /// </summary>
    public bool IsNamedPipe => Host.StartsWith(NamedPipeHostPrefix, StringComparison.Ordinal);

    /// <summary>
    /// Gets the unix pipe path if this instance represents a Unix pipe.
    /// </summary>
    public string UnixPipePath
    {
        get
        {
            if (!IsUnixPipe)
            {
                throw new InvalidOperationException("Binding address is not a unix pipe.");
            }

            return GetUnixPipePath(Host);
        }
    }

    /// <summary>
    /// Gets the named pipe path if this instance represents a named pipe.
    /// </summary>
    public string NamedPipePath
    {
        get
        {
            if (!IsNamedPipe)
            {
                throw new InvalidOperationException("Binding address is not a named pipe.");
            }

            return GetNamedPipePath(Host);
        }
    }

    private static string GetUnixPipePath(string host)
    {
        var unixPipeHostPrefixLength = UnixPipeHostPrefix.Length;
        if (!OperatingSystem.IsWindows())
        {
            // "/" character in unix refers to root. Windows has drive letters and volume separator (c:)
            unixPipeHostPrefixLength--;
        }
        return host.Substring(unixPipeHostPrefixLength);
    }

    private static string GetNamedPipePath(string host) => host.Substring(NamedPipeHostPrefix.Length);

    /// <inheritdoc />
    public override string ToString()
    {
        if (IsUnixPipe || IsNamedPipe)
        {
            return Scheme.ToLowerInvariant() + Uri.SchemeDelimiter + Host.ToLowerInvariant();
        }
        else
        {
            return Scheme.ToLowerInvariant() + Uri.SchemeDelimiter + Host.ToLowerInvariant() + ":" + Port.ToString(CultureInfo.InvariantCulture) + PathBase;
        }
    }

    /// <inheritdoc />
    public override int GetHashCode()
    {
        return ToString().GetHashCode();
    }

    /// <inheritdoc />
    public override bool Equals(object? obj)
    {
        var other = obj as BindingAddress;
        if (other == null)
        {
            return false;
        }
        return string.Equals(Scheme, other.Scheme, StringComparison.OrdinalIgnoreCase)
            && string.Equals(Host, other.Host, StringComparison.OrdinalIgnoreCase)
            && Port == other.Port
            && PathBase == other.PathBase;
    }

    /// <summary>
    /// Parses the specified <paramref name="address"/> as a <see cref="BindingAddress"/>.
    /// </summary>
    /// <param name="address">The address to parse.</param>
    /// <returns>The parsed address.</returns>
    public static BindingAddress Parse(string address)
    {
        // A null/empty address will throw FormatException
        address = address ?? string.Empty;

        var schemeDelimiterStart = address.IndexOf(Uri.SchemeDelimiter, StringComparison.Ordinal);
        if (schemeDelimiterStart < 0)
        {
            throw new FormatException($"Invalid url: '{address}'");
        }
        var schemeDelimiterEnd = schemeDelimiterStart + Uri.SchemeDelimiter.Length;

        var isUnixPipe = address.IndexOf(UnixPipeHostPrefix, schemeDelimiterEnd, StringComparison.Ordinal) == schemeDelimiterEnd;
        var isNamedPipe = address.IndexOf(NamedPipeHostPrefix, schemeDelimiterEnd, StringComparison.Ordinal) == schemeDelimiterEnd;

        int pathDelimiterStart;
        int pathDelimiterEnd;
        if (isUnixPipe)
        {
            var unixPipeHostPrefixLength = UnixPipeHostPrefix.Length;
            if (OperatingSystem.IsWindows())
            {
                // Windows has drive letters and volume separator (c:)
                unixPipeHostPrefixLength += 2;
                if (schemeDelimiterEnd + unixPipeHostPrefixLength > address.Length)
                {
                    throw new FormatException($"Invalid url: '{address}'");
                }
            }

            pathDelimiterStart = address.IndexOf(":", schemeDelimiterEnd + unixPipeHostPrefixLength, StringComparison.Ordinal);
            pathDelimiterEnd = pathDelimiterStart + ":".Length;
        }
        else if (isNamedPipe)
        {
            pathDelimiterStart = address.IndexOf(":", schemeDelimiterEnd + NamedPipeHostPrefix.Length, StringComparison.Ordinal);
            pathDelimiterEnd = pathDelimiterStart + ":".Length;
        }
        else
        {
            pathDelimiterStart = address.IndexOf("/", schemeDelimiterEnd, StringComparison.Ordinal);
            pathDelimiterEnd = pathDelimiterStart;
        }

        if (pathDelimiterStart < 0)
        {
            pathDelimiterStart = pathDelimiterEnd = address.Length;
        }

        var scheme = address.Substring(0, schemeDelimiterStart);
        string? host = null;
        var port = 0;

        var hasSpecifiedPort = false;
        if (!isUnixPipe)
        {
            var portDelimiterStart = address.LastIndexOf(":", pathDelimiterStart - 1, pathDelimiterStart - schemeDelimiterEnd, StringComparison.Ordinal);
            if (portDelimiterStart >= 0)
            {
                var portDelimiterEnd = portDelimiterStart + ":".Length;

                var portString = address.Substring(portDelimiterEnd, pathDelimiterStart - portDelimiterEnd);
                int portNumber;
                if (int.TryParse(portString, NumberStyles.Integer, CultureInfo.InvariantCulture, out portNumber))
                {
                    hasSpecifiedPort = true;
                    host = address.Substring(schemeDelimiterEnd, portDelimiterStart - schemeDelimiterEnd);
                    port = portNumber;
                }
            }

            if (!hasSpecifiedPort)
            {
                if (string.Equals(scheme, "http", StringComparison.OrdinalIgnoreCase))
                {
                    port = 80;
                }
                else if (string.Equals(scheme, "https", StringComparison.OrdinalIgnoreCase))
                {
                    port = 443;
                }
            }
        }

        if (!hasSpecifiedPort)
        {
            host = address.Substring(schemeDelimiterEnd, pathDelimiterStart - schemeDelimiterEnd);
        }

        if (string.IsNullOrEmpty(host))
        {
            throw new FormatException($"Invalid url: '{address}'");
        }

        if (isUnixPipe && !Path.IsPathRooted(GetUnixPipePath(host)))
        {
            throw new FormatException($"Invalid url, unix socket path must be absolute: '{address}'");
        }

        if (isNamedPipe && GetNamedPipePath(host).Contains('\\'))
        {
            throw new FormatException($"Invalid url, pipe name must not contain backslashes: '{address}'");
        }

        string pathBase;
        if (address[address.Length - 1] == '/')
        {
            pathBase = address.Substring(pathDelimiterEnd, address.Length - pathDelimiterEnd - 1);
        }
        else
        {
            pathBase = address.Substring(pathDelimiterEnd);
        }

        return new BindingAddress(host: host, pathBase: pathBase, port: port, scheme: scheme);
    }
}