ServicePath.cs 19 KB

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