Support named wildcard in UriTemplate matching. Fixed bug #693996.
[mono.git] / mcs / class / System.ServiceModel.Web / System / UriTemplate.cs
1 //
2 // UriTemplate.cs
3 //
4 // Author:
5 //      Atsushi Enomoto  <atsushi@ximian.com>
6 //
7 // Copyright (C) 2008 Novell, Inc (http://www.novell.com)
8 //
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
16 // 
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
19 // 
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 //
28 using System;
29 using System.Collections.Generic;
30 using System.Collections.ObjectModel;
31 using System.Collections.Specialized;
32 using System.Globalization;
33 using System.Text;
34
35 #if NET_2_1
36 using NameValueCollection = System.Object;
37 #endif
38
39 namespace System
40 {
41         public class UriTemplate
42         {
43                 static readonly ReadOnlyCollection<string> empty_strings = new ReadOnlyCollection<string> (new string [0]);
44
45                 string template;
46                 ReadOnlyCollection<string> path, query;
47                 string wild_path_name;
48                 Dictionary<string,string> query_params = new Dictionary<string,string> ();
49
50                 public UriTemplate (string template)
51                         : this (template, false)
52                 {
53                 }
54
55                 public UriTemplate (string template, IDictionary<string,string> additionalDefaults)
56                         : this (template, false, additionalDefaults)
57                 {
58                 }
59
60                 public UriTemplate (string template, bool ignoreTrailingSlash)
61                         : this (template, ignoreTrailingSlash, null)
62                 {
63                 }
64
65                 public UriTemplate (string template, bool ignoreTrailingSlash, IDictionary<string,string> additionalDefaults)
66                 {
67                         if (template == null)
68                                 throw new ArgumentNullException ("template");
69                         this.template = template;
70                         IgnoreTrailingSlash = ignoreTrailingSlash;
71                         Defaults = new Dictionary<string,string> (StringComparer.InvariantCultureIgnoreCase);
72                         if (additionalDefaults != null)
73                                 foreach (var pair in additionalDefaults)
74                                         Defaults.Add (pair.Key, pair.Value);
75
76                         string p = template;
77                         // Trim scheme, host name and port if exist.
78                         if (CultureInfo.InvariantCulture.CompareInfo.IsPrefix (template, "http")) {
79                                 int idx = template.IndexOf ('/', 8); // after "http://x" or "https://"
80                                 if (idx > 0)
81                                         p = template.Substring (idx);
82                         }
83                         int q = p.IndexOf ('?');
84                         path = ParsePathTemplate (p, 0, q >= 0 ? q : p.Length);
85                         if (q >= 0)
86                                 ParseQueryTemplate (p, q, p.Length);
87                         else
88                                 query = empty_strings;
89                 }
90
91                 public bool IgnoreTrailingSlash { get; private set; }
92
93                 public IDictionary<string,string> Defaults { get; private set; }
94
95                 public ReadOnlyCollection<string> PathSegmentVariableNames {
96                         get { return path; }
97                 }
98
99                 public ReadOnlyCollection<string> QueryValueVariableNames {
100                         get { return query; }
101                 }
102
103                 public override string ToString ()
104                 {
105                         return template;
106                 }
107
108                 // Bind
109
110 #if !MOONLIGHT
111                 public Uri BindByName (Uri baseAddress, NameValueCollection parameters)
112                 {
113                         return BindByName (baseAddress, parameters, false);
114                 }
115
116                 public Uri BindByName (Uri baseAddress, NameValueCollection parameters, bool omitDefaults)
117                 {
118                         return BindByNameCommon (baseAddress, parameters, null, omitDefaults);
119                 }
120 #endif
121
122                 public Uri BindByName (Uri baseAddress, IDictionary<string,string> parameters)
123                 {
124                         return BindByName (baseAddress, parameters, false);
125                 }
126
127                 public Uri BindByName (Uri baseAddress, IDictionary<string,string> parameters, bool omitDefaults)
128                 {
129                         return BindByNameCommon (baseAddress, null, parameters, omitDefaults);
130                 }
131
132                 string SuffixEndRenderedUri (string s)
133                 {
134                         return s.Length > 0 && s [s.Length - 1] == '/' ? s : s + '/';
135                 }
136
137                 string TrimStartRenderedUri (StringBuilder sb)
138                 {
139                         if (sb.Length == 0)
140                                 return String.Empty;
141                         
142                         if (sb [0] == '/')
143                                 return sb.ToString (1, sb.Length - 1);
144
145                         return sb.ToString ();
146                 }
147                 
148                 Uri BindByNameCommon (Uri baseAddress, NameValueCollection nvc, IDictionary<string,string> dic, bool omitDefaults)
149                 {
150                         CheckBaseAddress (baseAddress);
151
152                         // take care of case sensitivity.
153                         if (dic != null)
154                                 dic = new Dictionary<string,string> (dic, StringComparer.OrdinalIgnoreCase);
155
156                         int src = 0;
157                         StringBuilder sb = new StringBuilder (template.Length);
158                         BindByName (ref src, sb, path, nvc, dic, omitDefaults, false);
159                         BindByName (ref src, sb, query, nvc, dic, omitDefaults, true);
160                         sb.Append (template.Substring (src));
161                         return new Uri (SuffixEndRenderedUri (baseAddress.ToString ()) + TrimStartRenderedUri (sb));
162                 }
163
164                 void BindByName (ref int src, StringBuilder sb, ReadOnlyCollection<string> names, NameValueCollection nvc, IDictionary<string,string> dic, bool omitDefaults, bool query)
165                 {
166                         foreach (string name in names) {
167                                 int s = template.IndexOf ('{', src);
168                                 int e = template.IndexOf ('}', s + 1);
169 #if NET_2_1
170                                 string value = null;
171 #else
172                                 string value = nvc != null ? nvc [name] : null;
173 #endif
174                                 if (dic != null)
175                                         dic.TryGetValue (name, out value);
176                                 if (query) {
177                                         if (value != null || (!omitDefaults && Defaults.TryGetValue (name, out value))) {
178                                                 sb.Append (template.Substring (src, s - src));
179                                                 sb.Append (value);
180                                         }
181                                 } else
182                                         if (value == null && (omitDefaults || !Defaults.TryGetValue(name, out value)))
183                                                 throw new ArgumentException(string.Format("The argument name value collection does not contain non-nul vaalue for '{0}'", name), "parameters");
184                                         else {
185                                                 sb.Append (template.Substring (src, s - src));
186                                                 sb.Append (value);
187                                         }
188                                 src = e + 1;
189                         }
190                 }
191
192                 public Uri BindByPosition (Uri baseAddress, params string [] values)
193                 {
194                         CheckBaseAddress (baseAddress);
195
196                         if (values.Length != path.Count + query.Count)
197                                 throw new FormatException (String.Format ("Template '{0}' contains {1} parameters but the argument values to bind are {2}", template, path.Count + query.Count, values.Length));
198
199                         int src = 0, index = 0;
200                         StringBuilder sb = new StringBuilder (template.Length);
201                         BindByPosition (ref src, sb, path, values, ref index);
202                         BindByPosition (ref src, sb, query, values, ref index);
203                         sb.Append (template.Substring (src));
204                         return new Uri (SuffixEndRenderedUri (baseAddress.ToString ()) + TrimStartRenderedUri (sb));
205                 }
206
207                 void BindByPosition (ref int src, StringBuilder sb, ReadOnlyCollection<string> names, string [] values, ref int index)
208                 {
209                         for (int i = 0; i < names.Count; i++) {
210                                 int s = template.IndexOf ('{', src);
211                                 int e = template.IndexOf ('}', s + 1);
212                                 sb.Append (template.Substring (src, s - src));
213                                 string value = values [index++];
214                                 if (value == null)
215                                         throw new FormatException (String.Format ("The argument value collection contains null at {0}", index - 1));
216                                 sb.Append (value);
217                                 src = e + 1;
218                         }
219                 }
220
221                 // Compare
222
223                 public bool IsEquivalentTo (UriTemplate other)
224                 {
225                         if (other == null)
226                                 throw new ArgumentNullException ("other");
227                         return this.template == other.template;
228                 }
229
230                 // Match
231
232                 static readonly char [] slashSep = {'/'};
233
234                 public UriTemplateMatch Match (Uri baseAddress, Uri candidate)
235                 {
236                         CheckBaseAddress (baseAddress);
237                         if (candidate == null)
238                                 throw new ArgumentNullException ("candidate");
239
240                         var us = baseAddress.LocalPath;
241                         if (us [us.Length - 1] != '/')
242                                 baseAddress = new Uri (baseAddress.GetComponents (UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.Unescaped) + '/' + baseAddress.Query, baseAddress.IsAbsoluteUri ? UriKind.Absolute : UriKind.RelativeOrAbsolute);
243                         if (IgnoreTrailingSlash) {
244                                 us = candidate.LocalPath;
245                                 if (us.Length > 0 && us [us.Length - 1] != '/')
246                                         candidate = new Uri(candidate.GetComponents (UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.Unescaped) + '/' + candidate.Query, candidate.IsAbsoluteUri ? UriKind.Absolute : UriKind.RelativeOrAbsolute);
247                         }
248
249                         int i = 0, c = 0;
250                         UriTemplateMatch m = new UriTemplateMatch ();
251                         m.BaseUri = baseAddress;
252                         m.Template = this;
253                         m.RequestUri = candidate;
254                         var vc = m.BoundVariables;
255
256                         string cp = Uri.UnescapeDataString (baseAddress.MakeRelativeUri (new Uri (baseAddress, candidate.GetComponents (UriComponents.PathAndQuery, UriFormat.Unescaped))).ToString ());
257                         if (IgnoreTrailingSlash && cp [cp.Length - 1] == '/')
258                                 cp = cp.Substring (0, cp.Length - 1);
259
260                         int tEndCp = cp.IndexOf ('?');
261                         if (tEndCp >= 0)
262                                 cp = cp.Substring (0, tEndCp);
263
264                         if (template.Length > 0 && template [0] == '/')
265                                 i++;
266                         if (cp.Length > 0 && cp [0] == '/')
267                                 c++;
268
269                         foreach (string name in path) {
270                                 if (name == wild_path_name) {
271                                         vc [name] = cp.Substring (c); // all remaining paths.
272                                         continue;
273                                 }
274                                 int n = StringIndexOf (template, '{' + name + '}', i);
275                                 if (String.CompareOrdinal (cp, c, template, i, n - i) != 0)
276                                         return null; // doesn't match before current template part.
277                                 c += n - i;
278                                 i = n + 2 + name.Length;
279                                 int ce = cp.IndexOf ('/', c);
280                                 if (ce < 0)
281                                         ce = cp.Length;
282                                 string value = cp.Substring (c, ce - c);
283                                 if (value.Length == 0)
284                                         return null; // empty => mismatch
285                                 vc [name] = value;
286                                 m.RelativePathSegments.Add (value);
287                                 c += value.Length;
288                         }
289                         int tEnd = template.IndexOf ('?');
290                         int wildIdx = template.IndexOf ('*');
291                         bool wild = wildIdx >= 0;
292                         if (tEnd < 0)
293                                 tEnd = template.Length;
294                         if (wild)
295                                 tEnd = wildIdx - 1;
296                         if (!wild && (cp.Length - c) != (tEnd - i) ||
297                             String.CompareOrdinal (cp, c, template, i, tEnd - i) != 0)
298                                 return null; // suffix doesn't match
299                         if (wild) {
300                                 c += tEnd - i;
301                                 foreach (var pe in cp.Substring (c).Split (slashSep, StringSplitOptions.RemoveEmptyEntries))
302                                         m.WildcardPathSegments.Add (pe);
303                         }
304                         if (candidate.Query.Length == 0)
305                                 return m;
306
307
308                         string [] parameters = Uri.UnescapeDataString (candidate.Query.Substring (1)).Split ('&'); // chop first '?'
309                         foreach (string parameter in parameters) {
310                                 string [] pair = parameter.Split ('=');
311                                 m.QueryParameters.Add (pair [0], pair [1]);
312                                 if (!query_params.ContainsKey (pair [0]))
313                                         continue;
314                                 string templateName = query_params [pair [0]];
315                                 vc.Add (templateName, pair [1]);
316                         }
317
318                         return m;
319                 }
320
321                 int StringIndexOf (string s, string pattern, int idx)
322                 {
323                         return CultureInfo.InvariantCulture.CompareInfo.IndexOf (s, pattern, idx, CompareOptions.OrdinalIgnoreCase);
324                 }
325
326                 // Helpers
327
328                 void CheckBaseAddress (Uri baseAddress)
329                 {
330                         if (baseAddress == null)
331                                 throw new ArgumentNullException ("baseAddress");
332                         if (!baseAddress.IsAbsoluteUri)
333                                 throw new ArgumentException ("baseAddress must be an absolute URI.");
334                         if (baseAddress.Scheme == Uri.UriSchemeHttp ||
335                             baseAddress.Scheme == Uri.UriSchemeHttps)
336                                 return;
337                         throw new ArgumentException ("baseAddress scheme must be either http or https.");
338                 }
339
340                 ReadOnlyCollection<string> ParsePathTemplate (string template, int index, int end)
341                 {
342                         int widx = template.IndexOf ('*', index, end);
343                         if (widx >= 0)
344                                 if (widx != end - 1 && template.IndexOf ('}', widx) != end - 1)
345                                         throw new FormatException (String.Format ("Wildcard in UriTemplate is valid only if it is placed at the last part of the path: '{0}'", template));
346                         List<string> list = null;
347                         int prevEnd = -2;
348                         for (int i = index; i <= end; ) {
349                                 i = template.IndexOf ('{', i);
350                                 if (i < 0 || i > end)
351                                         break;
352                                 if (i == prevEnd + 1)
353                                         throw new ArgumentException (String.Format ("The UriTemplate '{0}' contains adjacent templated segments, which is invalid.", template));
354                                 int e = template.IndexOf ('}', i + 1);
355                                 if (e < 0 || i > end)
356                                         throw new FormatException (String.Format ("Missing '}' in URI template '{0}'", template));
357                                 prevEnd = e;
358                                 if (list == null)
359                                         list = new List<string> ();
360                                 i++;
361                                 string name = template.Substring (i, e - i);
362                                 string uname = name.ToUpper (CultureInfo.InvariantCulture);
363                                 if (uname [0] == '*')
364                                         uname = wild_path_name = uname.Substring (1);
365                                 if (list.Contains (uname) || (path != null && path.Contains (uname)))
366                                         throw new InvalidOperationException (String.Format ("The URI template string contains duplicate template item {{'{0}'}}", name));
367                                 list.Add (uname);
368                                 i = e + 1;
369                         }
370                         return list != null ? new ReadOnlyCollection<string> (list) : empty_strings;
371                 }
372
373                 void ParseQueryTemplate (string template, int index, int end)
374                 {
375                         // template starts with '?'
376                         string [] parameters = template.Substring (index + 1, end - index - 1).Split ('&');
377                         List<string> list = null;
378                         foreach (string parameter in parameters) {
379                                 string [] pair = parameter.Split ('=');
380                                 if (pair.Length != 2)
381                                         throw new FormatException ("Invalid URI query string format");
382                                 string pname = pair [0];
383                                 string pvalue = pair [1];
384                                 if (pvalue.Length >= 2 && pvalue [0] == '{' && pvalue [pvalue.Length - 1] == '}') {
385                                         string ptemplate = pvalue.Substring (1, pvalue.Length - 2).ToUpper (CultureInfo.InvariantCulture);
386                                         query_params.Add (pname, ptemplate);
387                                         if (list == null)
388                                                 list = new List<string> ();
389                                         if (list.Contains (ptemplate) || (path != null && path.Contains (ptemplate)))
390                                                 throw new InvalidOperationException (String.Format ("The URI template string contains duplicate template item {{'{0}'}}", pvalue));
391                                         list.Add (ptemplate);
392                                 }
393                         }
394                         query = list != null ? new ReadOnlyCollection<string> (list.ToArray ()) : empty_strings;
395                 }
396         }
397 }