ServicePath.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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)) continue;
  97. if (component.IndexOf(VariablePrefix, StringComparison.OrdinalIgnoreCase) != -1
  98. && component.IndexOf(ComponentSeperator) != -1)
  99. {
  100. hasSeparators.Add(true);
  101. componentsList.AddRange(component.Split(ComponentSeperator));
  102. }
  103. else
  104. {
  105. hasSeparators.Add(false);
  106. componentsList.Add(component);
  107. }
  108. }
  109. var components = componentsList.ToArray();
  110. this.TotalComponentsCount = components.Length;
  111. this.literalsToMatch = new string[this.TotalComponentsCount];
  112. this.variablesNames = new string[this.TotalComponentsCount];
  113. this.isWildcard = new bool[this.TotalComponentsCount];
  114. this.componentsWithSeparators = hasSeparators.ToArray();
  115. this.PathComponentsCount = this.componentsWithSeparators.Length;
  116. string firstLiteralMatch = null;
  117. for (var i = 0; i < components.Length; i++)
  118. {
  119. var component = components[i];
  120. if (component.StartsWith(VariablePrefix))
  121. {
  122. var variableName = component.Substring(1, component.Length - 2);
  123. if (variableName[variableName.Length - 1] == WildCardChar)
  124. {
  125. this.isWildcard[i] = true;
  126. variableName = variableName.Substring(0, variableName.Length - 1);
  127. }
  128. this.variablesNames[i] = variableName;
  129. this.VariableArgsCount++;
  130. }
  131. else
  132. {
  133. this.literalsToMatch[i] = component.ToLowerInvariant();
  134. if (firstLiteralMatch == null)
  135. {
  136. firstLiteralMatch = this.literalsToMatch[i];
  137. }
  138. }
  139. }
  140. for (var i = 0; i < components.Length - 1; i++)
  141. {
  142. if (!this.isWildcard[i])
  143. {
  144. continue;
  145. }
  146. if (this.literalsToMatch[i + 1] == null)
  147. {
  148. throw new ArgumentException(
  149. "A wildcard path component must be at the end of the path or followed by a literal path component.");
  150. }
  151. }
  152. this.wildcardCount = this.isWildcard.Length;
  153. this.IsWildCardPath = this.wildcardCount > 0;
  154. this.FirstMatchHashKey = !this.IsWildCardPath
  155. ? this.PathComponentsCount + PathSeperator + firstLiteralMatch
  156. : WildCardChar + PathSeperator + firstLiteralMatch;
  157. this.typeDeserializer = new StringMapTypeDeserializer(createInstanceFn, getParseFn, this.RequestType);
  158. _propertyNamesMap = new HashSet<string>(
  159. GetSerializableProperties(RequestType).Select(x => x.Name),
  160. StringComparer.OrdinalIgnoreCase);
  161. }
  162. internal static IEnumerable<PropertyInfo> GetSerializableProperties(Type type)
  163. {
  164. foreach (var prop in GetPublicProperties(type))
  165. {
  166. if (prop.GetMethod == null
  167. || _excludeType == prop.PropertyType)
  168. {
  169. continue;
  170. }
  171. var ignored = false;
  172. foreach (var attr in prop.GetCustomAttributes(true))
  173. {
  174. if (IgnoreAttributesNamed.Contains(attr.GetType().Name))
  175. {
  176. ignored = true;
  177. break;
  178. }
  179. }
  180. if (!ignored)
  181. {
  182. yield return prop;
  183. }
  184. }
  185. }
  186. private static IEnumerable<PropertyInfo> GetPublicProperties(Type type)
  187. {
  188. if (type.IsInterface)
  189. {
  190. var propertyInfos = new List<PropertyInfo>();
  191. var considered = new List<Type>()
  192. {
  193. type
  194. };
  195. var queue = new Queue<Type>();
  196. queue.Enqueue(type);
  197. while (queue.Count > 0)
  198. {
  199. var subType = queue.Dequeue();
  200. foreach (var subInterface in subType.GetTypeInfo().ImplementedInterfaces)
  201. {
  202. if (considered.Contains(subInterface))
  203. {
  204. continue;
  205. }
  206. considered.Add(subInterface);
  207. queue.Enqueue(subInterface);
  208. }
  209. var newPropertyInfos = GetTypesPublicProperties(subType)
  210. .Where(x => !propertyInfos.Contains(x));
  211. propertyInfos.InsertRange(0, newPropertyInfos);
  212. }
  213. return propertyInfos;
  214. }
  215. return GetTypesPublicProperties(type)
  216. .Where(x => x.GetIndexParameters().Length == 0);
  217. }
  218. private static IEnumerable<PropertyInfo> GetTypesPublicProperties(Type subType)
  219. {
  220. foreach (var pi in subType.GetRuntimeProperties())
  221. {
  222. var mi = pi.GetMethod ?? pi.SetMethod;
  223. if (mi != null && mi.IsStatic)
  224. {
  225. continue;
  226. }
  227. yield return pi;
  228. }
  229. }
  230. /// <summary>
  231. /// Provide for quick lookups based on hashes that can be determined from a request url.
  232. /// </summary>
  233. public string FirstMatchHashKey { get; private set; }
  234. private readonly StringMapTypeDeserializer typeDeserializer;
  235. private readonly HashSet<string> _propertyNamesMap;
  236. public int MatchScore(string httpMethod, string[] withPathInfoParts)
  237. {
  238. var isMatch = IsMatch(httpMethod, withPathInfoParts, out var wildcardMatchCount);
  239. if (!isMatch)
  240. {
  241. return -1;
  242. }
  243. //Routes with least wildcard matches get the highest score
  244. var score = Math.Max((100 - wildcardMatchCount), 1) * 1000
  245. //Routes with less variable (and more literal) matches
  246. + Math.Max((10 - VariableArgsCount), 1) * 100;
  247. //Exact verb match is better than ANY
  248. if (Verbs.Length == 1 && string.Equals(httpMethod, Verbs[0], StringComparison.OrdinalIgnoreCase))
  249. {
  250. score += 10;
  251. }
  252. else
  253. {
  254. score += 1;
  255. }
  256. return score;
  257. }
  258. /// <summary>
  259. /// For performance withPathInfoParts should already be a lower case string
  260. /// to minimize redundant matching operations.
  261. /// </summary>
  262. public bool IsMatch(string httpMethod, string[] withPathInfoParts, out int wildcardMatchCount)
  263. {
  264. wildcardMatchCount = 0;
  265. if (withPathInfoParts.Length != this.PathComponentsCount && !this.IsWildCardPath)
  266. {
  267. return false;
  268. }
  269. if (!Verbs.Contains(httpMethod, StringComparer.OrdinalIgnoreCase))
  270. {
  271. return false;
  272. }
  273. if (!ExplodeComponents(ref withPathInfoParts))
  274. {
  275. return false;
  276. }
  277. if (this.TotalComponentsCount != withPathInfoParts.Length && !this.IsWildCardPath)
  278. {
  279. return false;
  280. }
  281. int pathIx = 0;
  282. for (var i = 0; i < this.TotalComponentsCount; i++)
  283. {
  284. if (this.isWildcard[i])
  285. {
  286. if (i < this.TotalComponentsCount - 1)
  287. {
  288. // Continue to consume up until a match with the next literal
  289. while (pathIx < withPathInfoParts.Length
  290. && !string.Equals(withPathInfoParts[pathIx], this.literalsToMatch[i + 1], StringComparison.InvariantCultureIgnoreCase))
  291. {
  292. pathIx++;
  293. wildcardMatchCount++;
  294. }
  295. // Ensure there are still enough parts left to match the remainder
  296. if ((withPathInfoParts.Length - pathIx) < (this.TotalComponentsCount - i - 1))
  297. {
  298. return false;
  299. }
  300. }
  301. else
  302. {
  303. // A wildcard at the end matches the remainder of path
  304. wildcardMatchCount += withPathInfoParts.Length - pathIx;
  305. pathIx = withPathInfoParts.Length;
  306. }
  307. }
  308. else
  309. {
  310. var literalToMatch = this.literalsToMatch[i];
  311. if (literalToMatch == null)
  312. {
  313. // Matching an ordinary (non-wildcard) variable consumes a single part
  314. pathIx++;
  315. continue;
  316. }
  317. if (withPathInfoParts.Length <= pathIx
  318. || !string.Equals(withPathInfoParts[pathIx], literalToMatch, StringComparison.InvariantCultureIgnoreCase))
  319. {
  320. return false;
  321. }
  322. pathIx++;
  323. }
  324. }
  325. return pathIx == withPathInfoParts.Length;
  326. }
  327. private bool ExplodeComponents(ref string[] withPathInfoParts)
  328. {
  329. var totalComponents = new List<string>();
  330. for (var i = 0; i < withPathInfoParts.Length; i++)
  331. {
  332. var component = withPathInfoParts[i];
  333. if (string.IsNullOrEmpty(component))
  334. {
  335. continue;
  336. }
  337. if (this.PathComponentsCount != this.TotalComponentsCount
  338. && this.componentsWithSeparators[i])
  339. {
  340. var subComponents = component.Split(ComponentSeperator);
  341. if (subComponents.Length < 2)
  342. {
  343. return false;
  344. }
  345. totalComponents.AddRange(subComponents);
  346. }
  347. else
  348. {
  349. totalComponents.Add(component);
  350. }
  351. }
  352. withPathInfoParts = totalComponents.ToArray();
  353. return true;
  354. }
  355. public object CreateRequest(string pathInfo, Dictionary<string, string> queryStringAndFormData, object fromInstance)
  356. {
  357. var requestComponents = pathInfo.Split(new[] { PathSeperatorChar }, StringSplitOptions.RemoveEmptyEntries);
  358. ExplodeComponents(ref requestComponents);
  359. if (requestComponents.Length != this.TotalComponentsCount)
  360. {
  361. var isValidWildCardPath = this.IsWildCardPath
  362. && requestComponents.Length >= this.TotalComponentsCount - this.wildcardCount;
  363. if (!isValidWildCardPath)
  364. throw new ArgumentException(
  365. string.Format(
  366. CultureInfo.InvariantCulture,
  367. "Path Mismatch: Request Path '{0}' has invalid number of components compared to: '{1}'",
  368. pathInfo,
  369. this.restPath));
  370. }
  371. var requestKeyValuesMap = new Dictionary<string, string>();
  372. var pathIx = 0;
  373. for (var i = 0; i < this.TotalComponentsCount; i++)
  374. {
  375. var variableName = this.variablesNames[i];
  376. if (variableName == null)
  377. {
  378. pathIx++;
  379. continue;
  380. }
  381. if (!this._propertyNamesMap.Contains(variableName))
  382. {
  383. if (string.Equals("ignore", variableName, StringComparison.OrdinalIgnoreCase))
  384. {
  385. pathIx++;
  386. continue;
  387. }
  388. throw new ArgumentException("Could not find property "
  389. + variableName + " on " + RequestType.GetMethodName());
  390. }
  391. var value = requestComponents.Length > pathIx ? requestComponents[pathIx] : null; //wildcard has arg mismatch
  392. if (value != null && this.isWildcard[i])
  393. {
  394. if (i == this.TotalComponentsCount - 1)
  395. {
  396. // Wildcard at end of path definition consumes all the rest
  397. var sb = new StringBuilder();
  398. sb.Append(value);
  399. for (var j = pathIx + 1; j < requestComponents.Length; j++)
  400. {
  401. sb.Append(PathSeperatorChar + requestComponents[j]);
  402. }
  403. value = sb.ToString();
  404. }
  405. else
  406. {
  407. // Wildcard in middle of path definition consumes up until it
  408. // hits a match for the next element in the definition (which must be a literal)
  409. // It may consume 0 or more path parts
  410. var stopLiteral = i == this.TotalComponentsCount - 1 ? null : this.literalsToMatch[i + 1];
  411. if (!string.Equals(requestComponents[pathIx], stopLiteral, StringComparison.OrdinalIgnoreCase))
  412. {
  413. var sb = new StringBuilder(value);
  414. pathIx++;
  415. while (!string.Equals(requestComponents[pathIx], stopLiteral, StringComparison.OrdinalIgnoreCase))
  416. {
  417. sb.Append(PathSeperatorChar + requestComponents[pathIx++]);
  418. }
  419. value = sb.ToString();
  420. }
  421. else
  422. {
  423. value = null;
  424. }
  425. }
  426. }
  427. else
  428. {
  429. // Variable consumes single path item
  430. pathIx++;
  431. }
  432. requestKeyValuesMap[variableName] = value;
  433. }
  434. if (queryStringAndFormData != null)
  435. {
  436. //Query String and form data can override variable path matches
  437. //path variables < query string < form data
  438. foreach (var name in queryStringAndFormData)
  439. {
  440. requestKeyValuesMap[name.Key] = name.Value;
  441. }
  442. }
  443. return this.typeDeserializer.PopulateFromMap(fromInstance, requestKeyValuesMap);
  444. }
  445. public class RestPathMap : SortedDictionary<string, List<RestPath>>
  446. {
  447. public RestPathMap() : base(StringComparer.OrdinalIgnoreCase)
  448. {
  449. }
  450. }
  451. }
  452. }