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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
|
// Copyright (C) 2015, The Duplicati Team
// http://www.duplicati.com, info@duplicati.com
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
namespace Duplicati.Library.Utility
{
/// <summary>
/// Represents a relaxed parsing of a URL.
/// The goal is to cover as many types of url's as possible,
/// without being ambiguous.
/// The major limitations is that an embedded username may not contain a :,
/// and the password may not contain a @.
/// </summary>
public struct Uri
{
/// <summary>
/// A very lax version of a URL parser
/// </summary>
private static readonly System.Text.RegularExpressions.Regex URL_PARSER = new System.Text.RegularExpressions.Regex(@"(?<scheme>[^:]+)://(((?<username>[^\:\?/]+)(\:(?<password>[^@\:\?/]*))?\@))?((?<hostname>[^/\?\:]+)(\:(?<port>\d+))?)?((?<path>[^\?]*))?(\?(?<query>.+))?");
/// <summary>
/// The URL scheme, e.g. http
/// </summary>
public readonly string Scheme;
/// <summary>
/// The server name, e.g. www.example.com
/// </summary>
public readonly string Host;
/// <summary>
/// The server path, e.g. index.html
/// </summary>
public readonly string Path;
/// <summary>
/// The server port, e.g. 80, is -1 if using the default port
/// </summary>
public readonly int Port;
/// <summary>
/// The querystring, e.g. ?id=1
/// </summary>
public readonly string Query;
/// <summary>
/// The username, if any
/// </summary>
public readonly string Username;
/// <summary>
/// The password, if any
/// </summary>
public readonly string Password;
/// <summary>
/// The original URI.
/// </summary>
public readonly string OriginalUri;
/// <summary>
/// Cache for the query parameters.
/// </summary>
private NameValueCollection m_queryParams;
/// <summary>
/// Gets the parameters in the query string
/// </summary>
/// <value>The query parameters.</value>
public NameValueCollection QueryParameters
{
get
{
if (m_queryParams == null)
{
if (Query == null)
m_queryParams = new NameValueCollection();
else
m_queryParams = ParseQueryString(Query);
}
return m_queryParams;
}
}
/// <summary>
/// Gets the host and path.
/// </summary>
/// <value>The host and path.</value>
public string HostAndPath
{
get
{
if (string.IsNullOrEmpty(Path))
return Host;
else if (string.IsNullOrEmpty(Host))
return Path;
else
return Host + (Path == null ? "" : "/" + Path);
}
}
/// <summary>
/// Gets the path and query.
/// </summary>
/// <value>The path and query.</value>
public string PathAndQuery
{
get
{
return (Path ?? "") + (Query == null ? "" : "?" + Query);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="Duplicati.Library.Utility.Uri"/> struct.
/// </summary>
/// <param name="url">The URL to parse</param>
public Uri(string url)
{
if (string.IsNullOrEmpty(url))
throw new ArgumentNullException(nameof(url));
m_queryParams = null;
this.OriginalUri = url;
var m = URL_PARSER.Match(url);
if (!m.Success || m.Length != url.Length)
{
var path = url;
if (path.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
path = path.Substring("file://".Length);
if (path.IndexOfAny(System.IO.Path.GetInvalidPathChars()) < 0)
try
{
var fp = System.IO.Path.GetFullPath(path);
this.Scheme = "file";
this.Host = null;
this.Path = fp;
this.Port = -1;
this.Query = null;
this.Username = null;
this.Password = null;
return;
}
catch
{
}
throw new ArgumentException(Strings.Uri.UriParseError(url), nameof(url));
}
this.Scheme = m.Groups["scheme"].Value;
var h = m.Groups["hostname"].Success ? m.Groups["hostname"].Value : "";
var p = m.Groups["path"].Success ? m.Groups["path"].Value : "";
if (m.Groups["hostname"].Success && p.StartsWith("/", StringComparison.Ordinal))
p = p.Substring(1);
// file://c:\test support
if (h.Length == 1 && p.StartsWith(":", StringComparison.Ordinal))
{
h = h + p;
p = "";
}
this.Host = h;
this.Path = p;
this.Query = m.Groups["query"].Success ? m.Groups["query"].Value : null;
this.Username = m.Groups["username"].Success ? UrlDecode(m.Groups["username"].Value) : null;
this.Password = m.Groups["password"].Success ? UrlDecode(m.Groups["password"].Value) : null;
if (m.Groups["port"].Success)
this.Port = int.Parse(m.Groups["port"].Value);
else
this.Port = -1;
}
/// <summary>
/// Constructs a free-form URI from components
/// </summary>
/// <param name="scheme">The url scheme, e.g. http</param>
/// <param name="host">The hostname, e.g. www.example.com</param>
/// <param name="path">The path, e.g. index.html</param>
/// <param name="query">The query string, e.g. id=1</param>
/// <param name="username">The username</param>
/// <param name="password">The password</param>
/// <param name="port">The port</param>
public Uri(string scheme, string host, string path = null, string query = null, string username = null, string password = null, int port = -1)
{
m_queryParams = null;
Scheme = scheme;
Host = host;
Path = path;
Query = query;
Username = username;
Password = password;
Port = port;
OriginalUri = AsString(scheme, host, path, query, username, password, port);
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents the current <see cref="Duplicati.Library.Utility.Uri"/>.
/// </summary>
/// <returns>A <see cref="System.String"/> that represents the current <see cref="Duplicati.Library.Utility.Uri"/>.</returns>
public override string ToString()
{
return AsString(Scheme, Host, Path, Query, Username, Password, Port);
}
/// <summary>
/// Throws an exception if the host name is missing.
/// </summary>
public void RequireHost()
{
if (string.IsNullOrEmpty(Host))
throw new ArgumentException(Strings.Uri.NoHostname(OriginalUri));
}
/// <summary>
/// Constructs an url-like string from components.
/// </summary>
/// <returns>An url-like string</returns>
/// <param name="scheme">The url scheme, e.g. http</param>
/// <param name="host">The hostname, e.g. www.example.com</param>
/// <param name="path">The path, e.g. index.html</param>
/// <param name="query">The query string, e.g. id=1</param>
/// <param name="username">The username</param>
/// <param name="password">The password</param>
/// <param name="port">The port</param>
private static string AsString(string scheme, string host, string path, string query, string username, string password, int port)
{
var s = scheme + "://";
if (!string.IsNullOrEmpty(username) || !string.IsNullOrEmpty(password))
{
s += UrlEncode(username ?? "");
s += ":";
s += UrlEncode(password ?? "");
s += "@";
}
if (!string.IsNullOrEmpty(host))
{
s += host;
if (port != -1)
s += ":" + port.ToString();
}
if (!string.IsNullOrEmpty(path))
{
if (!string.IsNullOrEmpty(host) && !path.StartsWith("/", StringComparison.Ordinal))
s += "/";
s += path;
}
if (!string.IsNullOrEmpty(query))
s += "?" + query;
return s;
}
/// <summary>
/// Creates a new instance with another scheme
/// </summary>
/// <returns>A new instance</returns>
/// <param name="scheme">The new scheme to use</param>
public Uri SetScheme(string scheme)
{
return new Uri(scheme, Host, Path, Query, Username, Password, Port);
}
/// <summary>
/// Creates a new instance with another host
/// </summary>
/// <returns>A new instance</returns>
/// <param name="host">The new hostname to use</param>
public Uri SetHost(string host)
{
return new Uri(Scheme, host, Path, Query, Username, Password, Port);
}
/// <summary>
/// Creates a new instance with another path
/// </summary>
/// <returns>A new instance</returns>
/// <param name="path">The new path to use</param>
public Uri SetPath(string path)
{
return new Uri(Scheme, Host, path, Query, Username, Password, Port);
}
/// <summary>
/// Creates a new instance with another query
/// </summary>
/// <returns>A new instance</returns>
/// <param name="query">The new query to use</param>
public Uri SetQuery(string query)
{
return new Uri(Scheme, Host, Path, query, Username, Password, Port);
}
/// <summary>
/// Creates a new instance with other credentials
/// </summary>
/// <returns>A new instance</returns>
/// <param name="username">The new username to use</param>
/// <param name="password">The new password to use</param>
public Uri SetCredentials(string username, string password)
{
return new Uri(Scheme, Host, Path, Query, username, password, Port);
}
/// <summary>
/// Creates a new instance with another port
/// </summary>
/// <returns>A new instance</returns>
/// <param name="port">The new port to use</param>
public Uri SetPort(int port)
{
return new Uri(Scheme, Host, Path, Query, Username, Password, port);
}
/// <summary>
/// The regular expression that matches %20 type values in a querystring
/// </summary>
private static readonly System.Text.RegularExpressions.Regex RE_ESCAPECHAR = new System.Text.RegularExpressions.Regex(@"[^0-9a-zA-Z\-_]", System.Text.RegularExpressions.RegexOptions.Compiled);
/// <summary>
/// Encodes a URL, like System.Web.HttpUtility.UrlEncode
/// </summary>
/// <returns>The encoded URL</returns>
/// <param name="value">The URL fragment to encode</param>
/// <param name="encoding">The encoding to use</param>
public static string UrlPathEncode(string value, System.Text.Encoding encoding = null)
{
return UrlEncode(value, encoding, "%20");
}
/// <summary>
/// Encodes a URL, like System.Web.HttpUtility.UrlEncode
/// </summary>
/// <returns>The encoded URL</returns>
/// <param name="value">The URL fragment to encode</param>
/// <param name="encoding">The encoding to use</param>
public static string UrlEncode(string value, System.Text.Encoding encoding = null, string spacevalue = "+")
{
if (value == null)
throw new ArgumentNullException(nameof(value));
encoding = encoding ?? System.Text.Encoding.UTF8;
var encoder = encoding.GetEncoder();
var inbuf = new char[1];
var outbuf = new byte[4];
return RE_ESCAPECHAR.Replace(value, (m) =>
{
if (m.Value == " ")
return spacevalue;
inbuf[0] = m.Value[0];
try
{
var len = encoder.GetBytes(inbuf, 0, 1, outbuf, 0, true);
return "%" + BitConverter.ToString(outbuf, 0, len).Replace("-", "%");
}
catch
{
}
//Fallback
return m.Value;
});
}
/// <summary>
/// The regular expression that matches %20 type values in a querystring
/// </summary>
private static readonly System.Text.RegularExpressions.Regex RE_NUMBER = new System.Text.RegularExpressions.Regex(@"(\%(?<number>([0-9]|[a-f]|[A-F]){2}))|(\+)|(\%u(?<number>([0-9]|[a-f]|[A-F]){4}))", System.Text.RegularExpressions.RegexOptions.Compiled);
/// <summary>
/// Decodes a URL, like System.Web.HttpUtility.UrlDecode
/// </summary>
/// <returns>The decoded URL</returns>
/// <param name="value">The URL fragment to decode</param>
/// <param name="encoding">The encoding to use</param>
public static string UrlDecode(string value, System.Text.Encoding encoding = null)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
encoding = encoding ?? System.Text.Encoding.UTF8;
var decoder = encoding.GetDecoder();
var inbuf = new byte[8];
var outbuf = new char[8];
return RE_NUMBER.Replace(value, (m) =>
{
if (m.Value == "+")
return " ";
try
{
var hex = m.Groups["number"].Value;
var bytelen = hex.Length / 2;
Utility.HexStringAsByteArray(hex, inbuf);
var c = decoder.GetChars(inbuf, 0, bytelen, outbuf, 0);
return new string(outbuf, 0, c);
}
catch
{
}
//Fallback
return m.Value;
});
}
/// <summary>
/// The regular expression that matches a=b type values in a querystring
/// </summary>
private static readonly System.Text.RegularExpressions.Regex RE_URLPARAM = new System.Text.RegularExpressions.Regex(@"(?<key>[^\=\&]+)(\=(?<value>[^\&]*))?", System.Text.RegularExpressions.RegexOptions.Compiled);
/// <summary>
/// Parses the query string.
/// This is a duplicate of the System.Web.HttpUtility.ParseQueryString that does not work well on Mono
/// </summary>
/// <returns>The parsed query string</returns>
/// <param name="query">The query to parse</param>
public static NameValueCollection ParseQueryString(string query)
{
return Library.Utility.Uri.ParseQueryString(query, true);
}
/// <summary>
/// Parses the query string.
/// This is a duplicate of the System.Web.HttpUtility.ParseQueryString that does not work well on Mono
/// </summary>
/// <returns>The parsed query string</returns>
/// <param name="query">The query to parse</param>
/// <param name="decodeValues">Whether to the parameter values should be decoded or not.</param>
public static NameValueCollection ParseQueryString(string query, bool decodeValues)
{
if (query == null)
throw new ArgumentNullException(nameof(query));
if (query.StartsWith("?", StringComparison.Ordinal))
query = query.Substring(1);
if (string.IsNullOrEmpty(query))
return new NameValueCollection(StringComparer.OrdinalIgnoreCase);
var result = new NameValueCollection(StringComparer.OrdinalIgnoreCase);
foreach (System.Text.RegularExpressions.Match m in RE_URLPARAM.Matches(query))
{
string value = m.Groups["value"].Success ? m.Groups["value"].Value : "";
if (decodeValues)
{
value = UrlDecode(value);
}
result.Add(UrlDecode(m.Groups["key"].Value), value);
}
return result;
}
/// <summary>
/// Build the querystring to be used in a URL
/// </summary>
/// <returns>The generated querystring</returns>
/// <param name="query">A collection of name value pairs to be translated into a query string</param>
/// <param name="delimiter">The delimiter to separate key value pairs in the query string</param>
public static string BuildUriQuery(NameValueCollection query, string delimiter)
{
if (query == null)
throw new ArgumentNullException(nameof(query));
StringBuilder builder = new StringBuilder();
foreach (var key in query.Cast<string>().Where(key => !string.IsNullOrEmpty(query[key])))
{
builder.Append(builder.Length == 0 ? string.Empty : delimiter)
.Append(key)
.Append("=")
.Append(query[key]);
}
return builder.ToString();
}
/// <summary>
/// Build the querystring to be used in a URL
/// </summary>
/// <returns>The generated querystring</returns>
/// <param name="query">A collection of name value pairs to be translated into a query string that is
/// ampersand delimited.</param>
public static string BuildUriQuery(NameValueCollection query)
{
return BuildUriQuery(query, "&");
}
/// <summary>
/// Builds a URL together using a base URL, a path and a query.
/// </summary>
/// <returns>The built together URL.</returns>
/// <param name="url">Base URL, containing schema, host, port.</param>
/// <param name="path">Base path.</param>
/// <param name="query">A collection of name value pairs to be translated into a query string.</param>
public static string UriBuilder(string url, string path, NameValueCollection query)
{
var builder = new UriBuilder(url)
{
Path = (new UrlPath(ExtractPath(url)).Append(path)).ToString(),
Query = query != null ? BuildUriQuery(query) : null
};
return builder.Uri.AbsoluteUri;
}
/// <summary>
/// Grab path part of a URI.
/// At the moment, simple implementation does not remove fragments.
/// </summary>
/// <returns>The path.</returns>
/// <param name="url">URL.</param>
public static string ExtractPath(string url)
{
return (new Uri(url)).Path;
}
/// <summary>
/// Builds a URL together using a base URL and path.
/// </summary>
/// <returns>The built together URL.</returns>
/// <param name="url">Base URL, containing schema, host, port.</param>
/// <param name="path">Base path.</param>
public static string UriBuilder(string url, string path)
{
return UriBuilder(url, path, null);
}
}
}
|