You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

726 lines
26 KiB

3 years ago
1 year ago
3 years ago
2 years ago
1 year ago
2 years ago
1 year ago
3 years ago
1 year ago
3 years ago
1 year ago
3 years ago
2 years ago
1 year ago
3 years ago
2 years ago
1 year ago
2 years ago
3 years ago
1 year ago
3 years ago
1 year ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
1 year ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
1 year ago
3 years ago
1 year ago
1 year ago
1 year ago
1 year ago
3 years ago
1 year ago
3 years ago
1 year ago
3 years ago
1 year ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
1 year ago
3 years ago
1 year ago
3 years ago
1 year ago
3 years ago
3 years ago
1 year ago
3 years ago
1 year ago
3 years ago
1 year ago
3 years ago
1 year ago
3 years ago
1 year ago
3 years ago
1 year ago
3 years ago
2 years ago
3 years ago
1 year ago
2 years ago
3 years ago
1 year ago
3 years ago
1 year ago
3 years ago
1 year ago
3 years ago
1 year ago
3 years ago
1 year ago
3 years ago
1 year ago
3 years ago
1 year ago
3 years ago
1 year ago
3 years ago
1 year ago
3 years ago
1 year ago
3 years ago
1 year ago
3 years ago
3 years ago
3 years ago
1 year ago
3 years ago
2 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
1 year ago
3 years ago
1 year ago
3 years ago
1 year ago
3 years ago
2 years ago
3 years ago
  1. using Apewer.Network;
  2. using Apewer.Source;
  3. using System;
  4. using System.Net;
  5. using System.Reflection;
  6. using static Apewer.Web.ApiUtility;
  7. namespace Apewer.Web
  8. {
  9. internal class ApiProcessor
  10. {
  11. private ApiContext _context = null;
  12. internal ApiProcessor(ApiContext context) => _context = context ?? throw new ArgumentNullException(nameof(context));
  13. #region prepare
  14. /// <summary>执行处理程序,返回错误信息。</summary>
  15. public void Run()
  16. {
  17. var url = null as Uri;
  18. var method = HttpMethod.NULL;
  19. var response = null as ApiResponse;
  20. try
  21. {
  22. // 检查执行的前提条件,获取 Method 和 URL。
  23. var check = Check(ref method, ref url);
  24. if (!string.IsNullOrEmpty(check))
  25. {
  26. Logger.Internals.Error(typeof(ApiInvoker), check);
  27. return;
  28. }
  29. // 准备请求模型。
  30. var request = GetRequest(_context.Provider, _context.Options, method, url);
  31. _context.Request = request;
  32. // 准备响应模型。
  33. response = new ApiResponse();
  34. response.Random = request.Random;
  35. response.Application = request.Application;
  36. response.Function = request.Function;
  37. _context.Response = response;
  38. // 调用 API。
  39. Invoke();
  40. }
  41. catch (Exception ex)
  42. {
  43. var message = ex.Message();
  44. Logger.Internals.Error(typeof(ApiInvoker), message);
  45. }
  46. finally
  47. {
  48. // 输出。
  49. if (response != null)
  50. {
  51. try
  52. {
  53. response.Duration = Duration(_context.Beginning);
  54. Output(_context.Provider, _context.Options, response, null, method);
  55. }
  56. catch { }
  57. finally
  58. {
  59. RuntimeUtility.Dispose(response.Model);
  60. }
  61. }
  62. }
  63. }
  64. static string Duration(DateTime beginning)
  65. {
  66. var span = DateTime.Now - beginning;
  67. var ms = span.TotalMilliseconds;
  68. if (ms < 1000) return Math.Round(ms, 0).ToString() + "ms";
  69. if (ms < 10000) return Math.Round(ms / 1000, 2).ToString() + "s";
  70. if (ms < 60000) return Math.Round(ms / 1000, 1).ToString() + "s";
  71. return Math.Round(ms / 1000, 0).ToString() + "s";
  72. }
  73. string Check(ref HttpMethod method, ref Uri url)
  74. {
  75. // 服务程序检查。
  76. var check = _context.Provider.PreInvoke();
  77. if (!string.IsNullOrEmpty(check)) return check;
  78. // URL
  79. url = _context.Provider.GetUrl();
  80. if (url == null) return "URL 无效。";
  81. method = _context.Provider.GetMethod();
  82. if (method == HttpMethod.NULL) return "HTTP 方法无效。";
  83. if (method == HttpMethod.OPTIONS) return null;
  84. // favicon.ico
  85. var lowerPath = TextUtility.AssureStarts(TextUtility.Lower(url.AbsolutePath), "/");
  86. if (!_context.Options.AllowFavIcon)
  87. {
  88. if (lowerPath.StartsWith("/favicon.ico"))
  89. {
  90. Output(_context.Provider, _context.Options, null, null, null);
  91. return "已取消对 favicon.ico 的请求。";
  92. }
  93. }
  94. // robots.txt
  95. if (!_context.Options.AllowRobots)
  96. {
  97. if (lowerPath.StartsWith("/robots.txt"))
  98. {
  99. const string text = "User-agent: *\nDisallow: / \n";
  100. Output(_context.Provider, _context.Options, null, "text/plain", TextUtility.Bytes(text));
  101. return "已取消对 robots.txt 的请求。";
  102. }
  103. }
  104. return null;
  105. }
  106. // 寻找入口。
  107. void Invoke()
  108. {
  109. // 路由
  110. if (_context.Options.UseRoute)
  111. {
  112. var path = _context?.Request?.Url?.AbsolutePath;
  113. path = path.TrimEnd('/');
  114. var action = _context.Entries.GetAction(path);
  115. if (action != null)
  116. {
  117. _context.ApiAction = action;
  118. Invoke(action);
  119. _context.Response.Duration = Duration(_context.Beginning);
  120. return;
  121. }
  122. }
  123. // 反射
  124. if (_context.Options.UseReflection)
  125. {
  126. var appName = _context.Request.Application;
  127. var application = _context.Entries.GetApplication(appName);
  128. Invoke(application);
  129. _context.Response.Duration = Duration(_context.Beginning);
  130. return;
  131. }
  132. // 未匹配到
  133. _context.Response.Duration = Duration(_context.Beginning);
  134. _context.Response.Model = new ApiStatusModel(404);
  135. }
  136. #endregion
  137. #region common
  138. // 创建控制器实例
  139. static ApiController CreateController(Type type, ApiRequest request, ApiResponse response, ApiOptions options)
  140. {
  141. var controller = (ApiController)Activator.CreateInstance(type);
  142. ApiUtility.SetProperties(controller, request, response, options);
  143. return controller;
  144. }
  145. static void Invoke(ApiContext context, MethodInfo method, ApiParameter[] parameters)
  146. {
  147. context.MethodInfo = method;
  148. // 调用。
  149. var parametersValue = ReadParameters(context.Request, parameters);
  150. var controller = context.Controller;
  151. var returnValue = method.Invoke(controller, parametersValue);
  152. // 程序要求停止输出。
  153. var response = context.Response;
  154. if (response.StopReturn) return;
  155. // 已经有了返回模型。
  156. if (response.Model != null) return;
  157. // 没有返回类型。
  158. var returnType = method.ReturnType;
  159. if (returnType == null) return;
  160. // 已明确字符串类型。
  161. if (returnType.Equals(typeof(string)))
  162. {
  163. var textValue = returnValue as string;
  164. var textRenderer = context.Options.TextRenderer;
  165. if (textRenderer != null)
  166. {
  167. textRenderer.Invoke(context, textValue);
  168. return;
  169. }
  170. // 默认视为提示错误
  171. if (!string.IsNullOrEmpty(textValue)) response.Error(textValue);
  172. return;
  173. }
  174. // 已明确 Exception 类型,视为提示错误。
  175. if (returnValue is Exception)
  176. {
  177. ApiUtility.Exception(response, returnValue as Exception);
  178. return;
  179. }
  180. // 已明确 Json 类型。
  181. if (returnValue is Json json)
  182. {
  183. response.Data = json;
  184. return;
  185. }
  186. // 已明确 Model 类型。
  187. if (returnValue is IApiModel model)
  188. {
  189. response.Model = model;
  190. return;
  191. }
  192. // 已明确 Result 类型。
  193. if (returnValue is IActionResult result)
  194. {
  195. response.Model = result;
  196. return;
  197. }
  198. // 类型未知,尝试 ToJson 方法。
  199. if (returnValue is IToJson toJson)
  200. {
  201. response.Data = toJson.ToJson();
  202. return;
  203. }
  204. // 未知返回类型,尝试使用默认渲染器。
  205. var defaultRenderer = context.Options.DefaultRenderer;
  206. if (defaultRenderer != null) defaultRenderer.Invoke(context, returnValue);
  207. }
  208. #endregion
  209. #region route
  210. // 执行 Action。
  211. void Invoke(ApiAction action)
  212. {
  213. var controller = null as ApiController;
  214. try
  215. {
  216. // 准备控制器。
  217. controller = CreateController(action.Type, _context.Request, _context.Response, _context.Options);
  218. // 准备参数。
  219. var parameters = action.Parameters;
  220. var values = ReadParameters(_context.Request, parameters);
  221. // 调用。
  222. _context.Controller = controller;
  223. Invoke(_context, action.MethodInfo, action.Parameters);
  224. }
  225. catch (Exception ex)
  226. {
  227. if (ex.InnerException != null) ex = ex.InnerException;
  228. ApiUtility.Exception(_context.Response, ex, _context.Options.WithException);
  229. var catcher = _context.Invoker.Catcher;
  230. if (catcher != null)
  231. {
  232. try
  233. {
  234. var apiCatch = new ApiCatch(_context, ex);
  235. catcher.Invoke(apiCatch);
  236. }
  237. catch { }
  238. }
  239. }
  240. finally
  241. {
  242. RuntimeUtility.Dispose(controller);
  243. }
  244. }
  245. #endregion
  246. #region reflection
  247. // 创建控制器。
  248. void Invoke(ApiApplication application)
  249. {
  250. var options = _context.Options;
  251. var entries = _context.Entries;
  252. var request = _context.Request;
  253. var response = _context.Response;
  254. // Application 无效,尝试默认控制器和枚举。
  255. if (application == null)
  256. {
  257. var @default = options.Default;
  258. if (@default == null)
  259. {
  260. // 没有指定默认控制器,尝试枚举。
  261. response.Status = "notfound";
  262. response.Message = "Not Found";
  263. if (options.AllowEnumerate) response.Data = Enumerate(entries.Applications, options);
  264. return;
  265. }
  266. else
  267. {
  268. // 创建默认控制器。
  269. var controller = null as ApiController;
  270. try
  271. {
  272. controller = CreateController(@default, request, response, options);
  273. Invoke(controller, application, null, options, request, response);
  274. }
  275. catch (Exception ex)
  276. {
  277. ApiUtility.Exception(response, ex.InnerException ?? ex);
  278. }
  279. finally
  280. {
  281. RuntimeUtility.Dispose(controller);
  282. }
  283. }
  284. }
  285. else
  286. {
  287. // 创建控制器时候会填充 Controller.Request 属性,可能导致 Request.Function 被篡改,所以在创建之前获取 Function。
  288. var function = application.GetFunction(request.Function);
  289. var controller = null as ApiController;
  290. try
  291. {
  292. controller = CreateController(application.Type, request, response, options);
  293. Invoke(controller, application, function, options, request, response);
  294. }
  295. catch (Exception ex)
  296. {
  297. ApiUtility.Exception(response, ex.InnerException ?? ex);
  298. }
  299. finally
  300. {
  301. RuntimeUtility.Dispose(controller);
  302. }
  303. }
  304. }
  305. // 调用 Function。
  306. void Invoke(ApiController controller, ApiApplication application, ApiFunction function, ApiOptions options, ApiRequest request, ApiResponse response)
  307. {
  308. try
  309. {
  310. // 控制器初始化。
  311. var initializer = ApiUtility.GetInitialier(controller);
  312. var match = initializer == null ? true : initializer.Invoke(controller);
  313. if (!match) return;
  314. if (application.Independent) return;
  315. if (function != null)
  316. {
  317. // 调用 API,获取返回值。
  318. _context.Controller = controller;
  319. Invoke(_context, function.Method, function.Parameters);
  320. }
  321. else
  322. {
  323. // 未匹配到 Function,尝试 Default。
  324. var @default = ApiUtility.GetDefault(controller);
  325. if (@default != null)
  326. {
  327. @default.Invoke(controller);
  328. return;
  329. }
  330. // 没有执行任何 Function,尝试枚举。
  331. response.Status = "notfound";
  332. if (application.Hidden)
  333. {
  334. response.Message = "Not Found";
  335. }
  336. else
  337. {
  338. response.Message = "Not Found";
  339. if (options.AllowEnumerate) response.Data = Enumerate(application.Functions, options);
  340. }
  341. }
  342. }
  343. catch (Exception ex)
  344. {
  345. if (ex.InnerException != null) ex = ex.InnerException;
  346. ApiUtility.Exception(_context.Response, ex, _context.Options.WithException);
  347. var catcher = _context.Invoker.Catcher;
  348. if (catcher != null)
  349. {
  350. try
  351. {
  352. var apiCatch = new ApiCatch(_context, ex);
  353. catcher.Invoke(apiCatch);
  354. }
  355. catch { }
  356. }
  357. }
  358. }
  359. #endregion
  360. #region static
  361. internal static ApiRequest GetRequest(ApiProvider provider, ApiOptions options, HttpMethod method, Uri url)
  362. {
  363. // 创建数据对象。
  364. var request = new ApiRequest();
  365. // Http Method。
  366. request.Method = method;
  367. // 基本信息。
  368. var ip = provider.GetClientIP();
  369. var headers = provider.GetHeaders() ?? new HttpHeaders();
  370. request.Headers = headers;
  371. request.IP = ip;
  372. request.Url = url;
  373. request.Referrer = provider.GetReferrer();
  374. request.Parameters = ApiUtility.Parameters(url.Query);
  375. // Headers。
  376. request.UserAgent = ApiUtility.UserAgent(headers);
  377. request.Cookies = ParseCookies(headers) ?? new CookieCollection();
  378. // 匹配 API。
  379. var application = null as string;
  380. var function = null as string;
  381. var random = null as string;
  382. var ticket = null as string;
  383. var session = null as string;
  384. var page = null as string;
  385. // 解析 POST 请求。
  386. switch (request.Method)
  387. {
  388. case HttpMethod.PATCH:
  389. case HttpMethod.POST:
  390. case HttpMethod.PUT:
  391. var preRead = provider.PreRead();
  392. if (string.IsNullOrEmpty(preRead))
  393. {
  394. var post = null as byte[];
  395. var length = 0L;
  396. var max = options.MaxRequestBody;
  397. if (max == 0) post = new byte[0];
  398. else if (max < 0) post = provider.RequestBody().Read();
  399. else
  400. {
  401. length = provider.GetContentLength();
  402. if (length <= max) post = provider.RequestBody().Read();
  403. }
  404. length = post == null ? 0 : post.Length;
  405. if (length > 1)
  406. {
  407. request.PostData = post;
  408. if (length < 104857600)
  409. {
  410. var text = TextUtility.FromBytes(post);
  411. request.PostText = text;
  412. // 尝试解析 Json,首尾必须是“{}”或“[]”。
  413. var first = post[0];
  414. var last = post[length - 1];
  415. if ((first == 123 && last == 125) || (first == 91 && last == 93))
  416. {
  417. var json = Json.From(text);
  418. if (json != null && json.IsObject)
  419. {
  420. application = json["application"];
  421. function = json["function"];
  422. random = json["random"];
  423. ticket = json["ticket"];
  424. session = json["session"];
  425. page = json["page"];
  426. var data = json.GetProperty("data");
  427. request.PostJson = json;
  428. request.Data = data ?? Json.NewObject();
  429. }
  430. }
  431. // 尝试解析 Form,需要 application/x-www-form-urlencoded
  432. var contentType = headers.GetValue("Content-Type") ?? "";
  433. if (contentType.Contains("urlencoded")) request.Form = ApiUtility.Parameters(text);
  434. }
  435. }
  436. }
  437. break;
  438. }
  439. // 解析 URL 参数。
  440. // URL 参数的优先级应高于 URL 路径,以避免反向代理产生的路径问题。
  441. var urlParameters = ApiUtility.Parameters(request.Url.Query);
  442. if (string.IsNullOrEmpty(application)) application = urlParameters.GetValue("application");
  443. if (string.IsNullOrEmpty(function)) function = urlParameters.GetValue("function");
  444. if (string.IsNullOrEmpty(random)) random = urlParameters.GetValue("random");
  445. if (string.IsNullOrEmpty(ticket)) ticket = urlParameters.GetValue("ticket");
  446. if (string.IsNullOrEmpty(session)) session = urlParameters.GetValue("session");
  447. if (string.IsNullOrEmpty(page)) page = urlParameters.GetValue("page");
  448. // 从 Cookie 中获取 Ticket。
  449. var cookies = request.Cookies;
  450. if (string.IsNullOrEmpty(ticket)) ticket = cookies.GetValue("ticket");
  451. // 最后检查 URL 路径。
  452. var paths = (request.Url.AbsolutePath ?? "").Split('/');
  453. if (string.IsNullOrEmpty(application) && paths.Length >= 2) application = TextUtility.DecodeUrl(paths[1]);
  454. if (string.IsNullOrEmpty(function) && paths.Length >= 3) function = TextUtility.DecodeUrl(paths[2]);
  455. // 修正内容。
  456. application = TextUtility.Trim(application);
  457. function = TextUtility.Trim(function);
  458. random = TextUtility.Trim(random);
  459. ticket = TextUtility.Trim(ticket);
  460. session = TextUtility.Trim(session);
  461. page = TextUtility.Trim(page);
  462. // 设置请求:回传。
  463. request.Application = application;
  464. request.Function = function;
  465. request.Random = random;
  466. // 设置请求:不回传。
  467. request.Ticket = ticket;
  468. request.Session = session;
  469. request.Page = page;
  470. return request;
  471. }
  472. static StringPairs PrepareHeaders(ApiOptions options, ApiResponse response, ApiRequest request = null)
  473. {
  474. var merged = new StringPairs();
  475. if (options != null)
  476. {
  477. // 跨域访问。
  478. if (options.WithAccessControl)
  479. {
  480. merged.Add("Access-Control-Allow-Headers", "Content-Type");
  481. merged.Add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
  482. merged.Add("Access-Control-Allow-Origin", "*");
  483. var maxage = options.AccessControlMaxAge;
  484. if (maxage > 0) merged.Add("Access-Control-Max-Age", maxage.ToString());
  485. if (request != null && request.Headers != null)
  486. {
  487. var @private = request.Headers.GetValue("Access-Control-Request-Private-Network");
  488. if (NumberUtility.Boolean(@private)) merged.Add("Access-Control-Allow-Private-Network", "true");
  489. }
  490. }
  491. // Content-Type 检查。
  492. if (options.WithContentTypeOptions || options.Default != null)
  493. {
  494. merged.Add("X-Content-Type-Options", "nosniff");
  495. }
  496. // 用于客户端,当前页面使用 HTTPS 时,将资源升级为 HTTPS。
  497. if (options.UpgradeHttps)
  498. {
  499. merged.Add("Content-Security-Policy", "upgrade-insecure-requests");
  500. }
  501. // 包含 API 的处理时间。
  502. if (options.WithDuration && response != null)
  503. {
  504. if (response.Duration.NotEmpty()) merged.Add("Duration", response.Duration);
  505. }
  506. }
  507. if (response != null)
  508. {
  509. // Cookies。
  510. var setCookies = SetCookie(response.Cookies);
  511. if (setCookies != null)
  512. {
  513. foreach (var value in setCookies) merged.Add("Set-Cookie", value);
  514. }
  515. // 自定义头。
  516. var headers = response.Headers;
  517. if (headers != null)
  518. {
  519. foreach (var header in headers)
  520. {
  521. var key = TextUtility.Trim(header.Name);
  522. if (string.IsNullOrEmpty(key)) continue;
  523. var value = header.Value;
  524. if (string.IsNullOrEmpty(value)) continue;
  525. merged.Add(key, value);
  526. }
  527. }
  528. }
  529. return merged;
  530. }
  531. internal void Output(ApiProvider provider, ApiOptions options, ApiResponse response, string type, byte[] bytes)
  532. {
  533. var preWrite = provider.PreWrite();
  534. if (!string.IsNullOrEmpty(preWrite)) return;
  535. if (response != null)
  536. {
  537. var responsePreOutput = response.PreOutput;
  538. if (responsePreOutput != null)
  539. {
  540. var @continue = responsePreOutput.Invoke(_context);
  541. if (!@continue) return;
  542. }
  543. }
  544. var invokerPreOutput = _context.Invoker.PreOutput;
  545. if (invokerPreOutput != null)
  546. {
  547. var @continue = invokerPreOutput.Invoke(_context);
  548. if (!@continue) return;
  549. }
  550. var optionsPreOutput = _context.Options.PreOutput;
  551. if (optionsPreOutput != null)
  552. {
  553. var @continue = optionsPreOutput.Invoke(_context);
  554. if (!@continue) return;
  555. }
  556. var headers = PrepareHeaders(options, response);
  557. foreach (var header in headers) provider.SetHeader(header.Key, header.Value);
  558. provider.SetCache(0);
  559. provider.SetContentType(string.IsNullOrEmpty(type) ? "application/octet-stream" : type);
  560. var length = bytes == null ? 0 : bytes.Length;
  561. provider.SetContentLength(length);
  562. if (length > 0) provider.ResponseBody().Write(bytes, 0, bytes.Length);
  563. provider.Sent();
  564. }
  565. internal void Output(ApiProvider provider, ApiOptions options, ApiResponse response, ApiRequest request, HttpMethod method)
  566. {
  567. var preWrite = provider.PreWrite();
  568. if (!string.IsNullOrEmpty(preWrite)) return;
  569. if (response != null)
  570. {
  571. var responsePreOutput = response.PreOutput;
  572. if (responsePreOutput != null)
  573. {
  574. var @continue = responsePreOutput.Invoke(_context);
  575. if (!@continue) return;
  576. }
  577. }
  578. var invokerPreOutput = _context.Invoker.PreOutput;
  579. if (invokerPreOutput != null)
  580. {
  581. var @continue = invokerPreOutput.Invoke(_context);
  582. if (!@continue) return;
  583. }
  584. var optionsPreOutput = _context.Options.PreOutput;
  585. if (optionsPreOutput != null)
  586. {
  587. var @continue = optionsPreOutput.Invoke(_context);
  588. if (!@continue) return;
  589. }
  590. // 设置头。
  591. var headers = PrepareHeaders(options, response, request);
  592. foreach (var header in headers) provider.SetHeader(header.Key, header.Value);
  593. // 自定义模型
  594. var model = response.Model as IApiModel;
  595. var result = response.Model as IActionResult;
  596. if (model != null)
  597. {
  598. try
  599. {
  600. model.Output(_context);
  601. }
  602. catch (Exception ex)
  603. {
  604. Logger.Internals.Exception(model, ex);
  605. }
  606. RuntimeUtility.Dispose(model);
  607. return;
  608. }
  609. else if (result != null)
  610. {
  611. try
  612. {
  613. result.ExecuteResult(_context);
  614. }
  615. catch (Exception ex)
  616. {
  617. Logger.Internals.Exception(result, ex);
  618. }
  619. RuntimeUtility.Dispose(result);
  620. return;
  621. }
  622. var text = ApiUtility.ToJson(response, options);
  623. var bytes = TextUtility.Bytes(text);
  624. provider.SetCache(0);
  625. provider.SetContentType("text/json; charset=utf-8");
  626. provider.SetContentLength(bytes.Length);
  627. var stream = provider.ResponseBody();
  628. if (stream != null && stream.CanWrite) stream.Write(bytes, 0, bytes.Length);
  629. provider.Sent();
  630. }
  631. #endregion
  632. }
  633. }