ServicePath.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Text;
  8. using System.Text.Json.Serialization;
  9. namespace Emby.Server.Implementations.Services
  10. {
  11. public class RestPath
  12. {
  13. private const string WildCard = "*";
  14. private const char WildCardChar = '*';
  15. private const string PathSeperator = "/";
  16. private const char PathSeperatorChar = '/';
  17. private const char ComponentSeperator = '.';
  18. private const string VariablePrefix = "{";
  19. private readonly bool[] componentsWithSeparators;
  20. private readonly string restPath;
  21. public bool IsWildCardPath { get; private set; }
  22. private readonly string[] literalsToMatch;
  23. private readonly string[] variablesNames;
  24. private readonly bool[] isWildcard;
  25. private readonly int wildcardCount = 0;
  26. internal static string[] IgnoreAttributesNamed = new[]
  27. {
  28. nameof(JsonIgnoreAttribute)
  29. };
  30. private static Type _excludeType = typeof(Stream);
  31. public int VariableArgsCount { get; set; }
  32. /// <summary>
  33. /// The number of segments separated by '/' determinable by path.Split('/').Length
  34. /// e.g. /path/to/here.ext == 3
  35. /// </summary>
  36. public int PathComponentsCount { get; set; }
  37. /// <summary>
  38. /// Gets or sets the total number of segments after subparts have been exploded ('.')
  39. /// e.g. /path/to/here.ext == 4.
  40. /// </summary>
  41. public int TotalComponentsCount { get; set; }
  42. public string[] Verbs { get; private set; }
  43. public Type RequestType { get; private set; }
  44. public Type ServiceType { get; private set; }
  45. public string Path => this.restPath;
  46. public string Summary { get; private set; }
  47. public string Description { get; private set; }
  48. public bool IsHidden { get; private set; }
  49. public static string[] GetPathPartsForMatching(string pathInfo)
  50. {
  51. return pathInfo.ToLowerInvariant().Split(new[] { PathSeperatorChar }, StringSplitOptions.RemoveEmptyEntries);
  52. }
  53. public static List<string> GetFirstMatchHashKeys(string[] pathPartsForMatching)
  54. {
  55. var hashPrefix = pathPartsForMatching.Length + PathSeperator;
  56. return GetPotentialMatchesWithPrefix(hashPrefix, pathPartsForMatching);
  57. }
  58. public static List<string> GetFirstMatchWildCardHashKeys(string[] pathPartsForMatching)
  59. {
  60. const string hashPrefix = WildCard + PathSeperator;
  61. return GetPotentialMatchesWithPrefix(hashPrefix, pathPartsForMatching);
  62. }
  63. private static List<string> GetPotentialMatchesWithPrefix(string hashPrefix, string[] pathPartsForMatching)
  64. {
  65. var list = new List<string>();
  66. foreach (var part in pathPartsForMatching)
  67. {
  68. list.Add(hashPrefix + part);
  69. if (part.IndexOf(ComponentSeperator) == -1)
  70. {
  71. continue;
  72. }
  73. var subParts = part.Split(ComponentSeperator);
  74. foreach (var subPart in subParts)
  75. {
  76. list.Add(hashPrefix + subPart);
  77. }
  78. }
  79. return list;
  80. }
  81. public RestPath(Func<Type, object> createInstanceFn, Func<Type, Func<string, object>> getParseFn, Type requestType, Type serviceType, string path, string verbs, bool isHidden = false, string summary = null, string description = null)
  82. {
  83. this.RequestType = requestType;
  84. this.ServiceType = serviceType;
  85. this.Summary = summary;
  86. this.IsHidden = isHidden;
  87. this.Description = description;
  88. this.restPath = path;
  89. this.Verbs = string.IsNullOrWhiteSpace(verbs) ? ServiceExecExtensions.AllVerbs : verbs.ToUpperInvariant().Split(new[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
  90. var componentsList = new List<string>();
  91. //We only split on '.' if the restPath has them. Allows for /{action}.{type}
  92. var hasSeparators = new List<bool>();
  93. foreach (var component in this.restPath.Split(PathSeperatorChar))
  94. {
  95. if (string.IsNullOrEmpty(component)) continue;
  96. if (component.IndexOf(VariablePrefix, StringComparison.OrdinalIgnoreCase) != -1
  97. && component.IndexOf(ComponentSeperator) != -1)
  98. {
  99. hasSeparators.Add(true);
  100. componentsList.AddRange(component.Split(ComponentSeperator));
  101. }
  102. else
  103. {
  104. hasSeparators.Add(false);
  105. componentsList.Add(component);
  106. }
  107. }
  108. var components = componentsList.ToArray();
  109. this.TotalComponentsCount = components.Length;
  110. this.literalsToMatch = new string[this.TotalComponentsCount];
  111. this.variablesNames = new string[this.TotalComponentsCount];
  112. this.isWildcard = new bool[this.TotalComponentsCount];
  113. this.componentsWithSeparators = hasSeparators.ToArray();
  114. this.PathComponentsCount = this.componentsWithSeparators.Length;
  115. string firstLiteralMatch = null;
  116. for (var i = 0; i < components.Length; i++)
  117. {
  118. var component = components[i];
  119. if (component.StartsWith(VariablePrefix))
  120. {
  121. var variableName = component.Substring(1, component.Length - 2);
  122. if (variableName[variableName.Length - 1] == WildCardChar)
  123. {
  124. this.isWildcard[i] = true;
  125. variableName = variableName.Substring(0, variableName.Length - 1);
  126. }
  127. this.variablesNames[i] = variableName;
  128. this.VariableArgsCount++;
  129. }
  130. else
  131. {
  132. this.literalsToMatch[i] = component.ToLowerInvariant();
  133. if (firstLiteralMatch == null)
  134. {
  135. firstLiteralMatch = this.literalsToMatch[i];
  136. }
  137. }
  138. }
  139. for (var i = 0; i < components.Length - 1; i++)
  140. {
  141. if (!this.isWildcard[i])
  142. {
  143. continue;
  144. }
  145. if (this.literalsToMatch[i + 1] == null)
  146. {
  147. throw new ArgumentException(
  148. "A wildcard path component must be at the end of the path or followed by a literal path component.");
  149. }
  150. }
  151. this.wildcardCount = this.isWildcard.Length;
  152. this.IsWildCardPath = this.wildcardCount > 0;
  153. this.FirstMatchHashKey = !this.IsWildCardPath
  154. ? this.PathComponentsCount + PathSeperator + firstLiteralMatch
  155. : WildCardChar + PathSeperator + firstLiteralMatch;
  156. this.typeDeserializer = new StringMapTypeDeserializer(createInstanceFn, getParseFn, this.RequestType);
  157. _propertyNamesMap = new HashSet<string>(
  158. GetSerializableProperties(RequestType).Select(x => x.Name),
  159. StringComparer.OrdinalIgnoreCase);
  160. }
  161. internal static IEnumerable<PropertyInfo> GetSerializableProperties(Type type)
  162. {
  163. foreach (var prop in GetPublicProperties(type))
  164. {
  165. if (prop.GetMethod == null
  166. || _excludeType == prop.PropertyType)
  167. {
  168. continue;
  169. }
  170. var ignored = false;
  171. foreach (var attr in prop.GetCustomAttributes(true))
  172. {
  173. if (IgnoreAttributesNamed.Contains(attr.GetType().Name))
  174. {
  175. ignored = true;
  176. break;
  177. }
  178. }
  179. if (!ignored)
  180. {
  181. yield return prop;
  182. }
  183. }
  184. }
  185. private static IEnumerable<PropertyInfo> GetPublicProperties(Type type)
  186. {
  187. if (type.IsInterface)
  188. {
  189. var propertyInfos = new List<PropertyInfo>();
  190. var considered = new List<Type>()
  191. {
  192. type
  193. };
  194. var queue = new Queue<Type>();
  195. queue.Enqueue(type);
  196. while (queue.Count > 0)
  197. {
  198. var subType = queue.Dequeue();
  199. foreach (var subInterface in subType.GetTypeInfo().ImplementedInterfaces)
  200. {
  201. if (considered.Contains(subInterface))
  202. {
  203. continue;
  204. }
  205. considered.Add(subInterface);
  206. queue.Enqueue(subInterface);
  207. }
  208. var newPropertyInfos = GetTypesPublicProperties(subType)
  209. .Where(x => !propertyInfos.Contains(x));
  210. propertyInfos.InsertRange(0, newPropertyInfos);
  211. }
  212. return propertyInfos;
  213. }
  214. return GetTypesPublicProperties(type)
  215. .Where(x => x.GetIndexParameters().Length == 0);
  216. }
  217. private static IEnumerable<PropertyInfo> GetTypesPublicProperties(Type subType)
  218. {
  219. foreach (var pi in subType.GetRuntimeProperties())
  220. {
  221. var mi = pi.GetMethod ?? pi.SetMethod;
  222. if (mi != null && mi.IsStatic)
  223. {
  224. continue;
  225. }
  226. yield return pi;
  227. }
  228. }
  229. /// <summary>
  230. /// Provide for quick lookups based on hashes that can be determined from a request url.
  231. /// </summary>
  232. public string FirstMatchHashKey { get; private set; }
  233. private readonly StringMapTypeDeserializer typeDeserializer;
  234. private readonly HashSet<string> _propertyNamesMap;
  235. public int MatchScore(string httpMethod, string[] withPathInfoParts)
  236. {
  237. var isMatch = IsMatch(httpMethod, withPathInfoParts, out var wildcardMatchCount);
  238. if (!isMatch)
  239. {
  240. return -1;
  241. }
  242. //Routes with least wildcard matches get the highest score
  243. var score = Math.Max((100 - wildcardMatchCount), 1) * 1000
  244. //Routes with less variable (and more literal) matches
  245. + Math.Max((10 - VariableArgsCount), 1) * 100;
  246. //Exact verb match is better than ANY
  247. if (Verbs.Length == 1 && string.Equals(httpMethod, Verbs[0], StringComparison.OrdinalIgnoreCase))
  248. {
  249. score += 10;
  250. }
  251. else
  252. {
  253. score += 1;
  254. }
  255. return score;
  256. }
  257. /// <summary>
  258. /// For performance withPathInfoParts should already be a lower case string
  259. /// to minimize redundant matching operations.
  260. /// </summary>
  261. public bool IsMatch(string httpMethod, string[] withPathInfoParts, out int wildcardMatchCount)
  262. {
  263. wildcardMatchCount = 0;
  264. if (withPathInfoParts.Length != this.PathComponentsCount && !this.IsWildCardPath)
  265. {
  266. return false;
  267. }
  268. if (!Verbs.Contains(httpMethod, StringComparer.OrdinalIgnoreCase))
  269. {
  270. return false;
  271. }
  272. if (!ExplodeComponents(ref withPathInfoParts))
  273. {
  274. return false;
  275. }
  276. if (this.TotalComponentsCount != withPathInfoParts.Length && !this.IsWildCardPath)
  277. {
  278. return false;
  279. }
  280. int pathIx = 0;
  281. for (var i = 0; i < this.TotalComponentsCount; i++)
  282. {
  283. if (this.isWildcard[i])
  284. {
  285. if (i < this.TotalComponentsCount - 1)
  286. {
  287. // Continue to consume up until a match with the next literal
  288. while (pathIx < withPathInfoParts.Length
  289. && !string.Equals(withPathInfoParts[pathIx], this.literalsToMatch[i + 1], StringComparison.InvariantCultureIgnoreCase))
  290. {
  291. pathIx++;
  292. wildcardMatchCount++;
  293. }
  294. // Ensure there are still enough parts left to match the remainder
  295. if ((withPathInfoParts.Length - pathIx) < (this.TotalComponentsCount - i - 1))
  296. {
  297. return false;
  298. }
  299. }
  300. else
  301. {
  302. // A wildcard at the end matches the remainder of path
  303. wildcardMatchCount += withPathInfoParts.Length - pathIx;
  304. pathIx = withPathInfoParts.Length;
  305. }
  306. }
  307. else
  308. {
  309. var literalToMatch = this.literalsToMatch[i];
  310. if (literalToMatch == null)
  311. {
  312. // Matching an ordinary (non-wildcard) variable consumes a single part
  313. pathIx++;
  314. continue;
  315. }
  316. if (withPathInfoParts.Length <= pathIx
  317. || !string.Equals(withPathInfoParts[pathIx], literalToMatch, StringComparison.InvariantCultureIgnoreCase))
  318. {
  319. return false;
  320. }
  321. pathIx++;
  322. }
  323. }
  324. return pathIx == withPathInfoParts.Length;
  325. }
  326. private bool ExplodeComponents(ref string[] withPathInfoParts)
  327. {
  328. var totalComponents = new List<string>();
  329. for (var i = 0; i < withPathInfoParts.Length; i++)
  330. {
  331. var component = withPathInfoParts[i];
  332. if (string.IsNullOrEmpty(component))
  333. {
  334. continue;
  335. }
  336. if (this.PathComponentsCount != this.TotalComponentsCount
  337. && this.componentsWithSeparators[i])
  338. {
  339. var subComponents = component.Split(ComponentSeperator);
  340. if (subComponents.Length < 2)
  341. {
  342. return false;
  343. }
  344. totalComponents.AddRange(subComponents);
  345. }
  346. else
  347. {
  348. totalComponents.Add(component);
  349. }
  350. }
  351. withPathInfoParts = totalComponents.ToArray();
  352. return true;
  353. }
  354. public object CreateRequest(string pathInfo, Dictionary<string, string> queryStringAndFormData, object fromInstance)
  355. {
  356. var requestComponents = pathInfo.Split(new[] { PathSeperatorChar }, StringSplitOptions.RemoveEmptyEntries);
  357. ExplodeComponents(ref requestComponents);
  358. if (requestComponents.Length != this.TotalComponentsCount)
  359. {
  360. var isValidWildCardPath = this.IsWildCardPath
  361. && requestComponents.Length >= this.TotalComponentsCount - this.wildcardCount;
  362. if (!isValidWildCardPath)
  363. throw new ArgumentException(
  364. string.Format(
  365. CultureInfo.InvariantCulture,
  366. "Path Mismatch: Request Path '{0}' has invalid number of components compared to: '{1}'",
  367. pathInfo,
  368. this.restPath));
  369. }
  370. var requestKeyValuesMap = new Dictionary<string, string>();
  371. var pathIx = 0;
  372. for (var i = 0; i < this.TotalComponentsCount; i++)
  373. {
  374. var variableName = this.variablesNames[i];
  375. if (variableName == null)
  376. {
  377. pathIx++;
  378. continue;
  379. }
  380. if (!this._propertyNamesMap.Contains(variableName))
  381. {
  382. if (string.Equals("ignore", variableName, StringComparison.OrdinalIgnoreCase))
  383. {
  384. pathIx++;
  385. continue;
  386. }
  387. throw new ArgumentException("Could not find property "
  388. + variableName + " on " + RequestType.GetMethodName());
  389. }
  390. var value = requestComponents.Length > pathIx ? requestComponents[pathIx] : null; //wildcard has arg mismatch
  391. if (value != null && this.isWildcard[i])
  392. {
  393. if (i == this.TotalComponentsCount - 1)
  394. {
  395. // Wildcard at end of path definition consumes all the rest
  396. var sb = new StringBuilder();
  397. sb.Append(value);
  398. for (var j = pathIx + 1; j < requestComponents.Length; j++)
  399. {
  400. sb.Append(PathSeperatorChar + requestComponents[j]);
  401. }
  402. value = sb.ToString();
  403. }
  404. else
  405. {
  406. // Wildcard in middle of path definition consumes up until it
  407. // hits a match for the next element in the definition (which must be a literal)
  408. // It may consume 0 or more path parts
  409. var stopLiteral = i == this.TotalComponentsCount - 1 ? null : this.literalsToMatch[i + 1];
  410. if (!string.Equals(requestComponents[pathIx], stopLiteral, StringComparison.OrdinalIgnoreCase))
  411. {
  412. var sb = new StringBuilder(value);
  413. pathIx++;
  414. while (!string.Equals(requestComponents[pathIx], stopLiteral, StringComparison.OrdinalIgnoreCase))
  415. {
  416. sb.Append(PathSeperatorChar + requestComponents[pathIx++]);
  417. }
  418. value = sb.ToString();
  419. }
  420. else
  421. {
  422. value = null;
  423. }
  424. }
  425. }
  426. else
  427. {
  428. // Variable consumes single path item
  429. pathIx++;
  430. }
  431. requestKeyValuesMap[variableName] = value;
  432. }
  433. if (queryStringAndFormData != null)
  434. {
  435. //Query String and form data can override variable path matches
  436. //path variables < query string < form data
  437. foreach (var name in queryStringAndFormData)
  438. {
  439. requestKeyValuesMap[name.Key] = name.Value;
  440. }
  441. }
  442. return this.typeDeserializer.PopulateFromMap(fromInstance, requestKeyValuesMap);
  443. }
  444. public class RestPathMap : SortedDictionary<string, List<RestPath>>
  445. {
  446. public RestPathMap() : base(StringComparer.OrdinalIgnoreCase)
  447. {
  448. }
  449. }
  450. }
  451. }