ServicePath.cs 20 KB

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