PipeIPCServer.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. using H.Formatters;
  2. using H.Pipes;
  3. using H.Pipes.AccessControl;
  4. using InABox.API;
  5. using InABox.Clients;
  6. using InABox.Core;
  7. using InABox.IPC.Shared;
  8. using Microsoft.CodeAnalysis.CSharp.Syntax;
  9. using Microsoft.CodeAnalysis.Operations;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Diagnostics;
  13. using System.IO.Pipes;
  14. using System.Linq;
  15. using System.Reflection;
  16. using System.Security.Principal;
  17. using System.Text;
  18. using System.Threading.Tasks;
  19. namespace Piping
  20. {
  21. using PipeResponse = PipeRequest;
  22. public class PipeIPCServer : IDisposable
  23. {
  24. PipeServer<PipeRequest> Server;
  25. public PipeIPCServer(string name)
  26. {
  27. Server = new PipeServer<PipeRequest>(name);
  28. var pipeSecurity = new PipeSecurity();
  29. pipeSecurity.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.LocalSid, null), PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow));
  30. pipeSecurity.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.LocalServiceSid, null), PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow));
  31. pipeSecurity.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow));
  32. Server.SetPipeSecurity(pipeSecurity);
  33. Server.ClientConnected += Server_ClientConnected;
  34. Server.ClientDisconnected += Server_ClientDisconnected;
  35. Server.MessageReceived += Server_MessageReceived;
  36. Server.ExceptionOccurred += Server_ExceptionOccurred;
  37. }
  38. private void Server_ExceptionOccurred(object? sender, H.Pipes.Args.ExceptionEventArgs e)
  39. {
  40. Logger.Send(LogType.Error, "", $"Exception Occurred: {e.Exception.Message}");
  41. }
  42. public void Start()
  43. {
  44. Server.StartAsync().Wait();
  45. }
  46. private static List<Type>? _persistentRemotable;
  47. private static Type? GetEntity(string entityName)
  48. {
  49. _persistentRemotable ??= CoreUtils.TypeList(
  50. e => e.IsSubclassOf(typeof(Entity)) &&
  51. e.GetInterfaces().Contains(typeof(IRemotable)) &&
  52. e.GetInterfaces().Contains(typeof(IPersistent))).ToList();
  53. return _persistentRemotable.FirstOrDefault(x => x.Name == entityName);
  54. }
  55. private static Type? GetResponseType(Method method, string? entityName)
  56. {
  57. if(entityName != null)
  58. {
  59. var entityType = GetEntity(entityName);
  60. if(entityType != null)
  61. {
  62. var response = method switch
  63. {
  64. Method.Query => typeof(QueryResponse<>).MakeGenericType(entityType),
  65. Method.Delete => typeof(DeleteResponse<>).MakeGenericType(entityType),
  66. Method.MultiDelete => typeof(MultiDeleteResponse<>).MakeGenericType(entityType),
  67. Method.Save => typeof(SaveResponse<>).MakeGenericType(entityType),
  68. Method.MultiSave => typeof(MultiSaveResponse<>).MakeGenericType(entityType),
  69. _ => null
  70. };
  71. if (response != null) return response;
  72. }
  73. }
  74. return method switch
  75. {
  76. Method.QueryMultiple => typeof(MultiQueryResponse),
  77. Method.Validate => typeof(ValidateResponse),
  78. Method.Check2FA => typeof(Check2FAResponse),
  79. _ => null
  80. };
  81. }
  82. private static PipeResponse QueryMultiple(PipeRequest request)
  83. {
  84. var response = RestService.QueryMultiple(request.GetRequest<MultiQueryRequest>(), true);
  85. return request.Respond(response);
  86. }
  87. private static PipeResponse Validate(PipeRequest request)
  88. {
  89. var response = RestService.Validate(request.GetRequest<ValidateRequest>());
  90. return request.Respond(response);
  91. }
  92. private static PipeResponse Ping(PipeRequest request) => request.Respond(new PingResponse().Status(StatusCode.OK));
  93. private static PipeResponse Info(PipeRequest request)
  94. {
  95. var response = RestService.Info(request.GetRequest<InfoRequest>());
  96. return request.Respond(response);
  97. }
  98. private static PipeResponse Check2FA(PipeRequest request)
  99. {
  100. var response = RestService.Check2FA(request.GetRequest<Check2FARequest>());
  101. return request.Respond(response);
  102. }
  103. private static PipeResponse Query<T>(PipeRequest request) where T : Entity, new()
  104. {
  105. var response = RestService<T>.List(request.GetRequest<QueryRequest<T>>());
  106. return request.Respond(response);
  107. }
  108. private static PipeResponse Save<T>(PipeRequest request) where T : Entity, new()
  109. {
  110. var response = RestService<T>.Save(request.GetRequest<SaveRequest<T>>());
  111. return request.Respond(response);
  112. }
  113. private static PipeResponse MultiSave<T>(PipeRequest request) where T : Entity, new()
  114. {
  115. var response = RestService<T>.MultiSave(request.GetRequest<MultiSaveRequest<T>>());
  116. return request.Respond(response);
  117. }
  118. private static PipeResponse Delete<T>(PipeRequest request) where T : Entity, new()
  119. {
  120. var response = RestService<T>.Delete(request.GetRequest<DeleteRequest<T>>());
  121. return request.Respond(response);
  122. }
  123. private static PipeResponse MultiDelete<T>(PipeRequest request) where T : Entity, new()
  124. {
  125. var response = RestService<T>.MultiDelete(request.GetRequest<MultiDeleteRequest<T>>());
  126. return request.Respond(response);
  127. }
  128. private static MethodInfo QueryMethod = GetMethod(nameof(Query));
  129. private static MethodInfo SaveMethod = GetMethod(nameof(Save));
  130. private static MethodInfo MultiSaveMethod = GetMethod(nameof(MultiSave));
  131. private static MethodInfo DeleteMethod = GetMethod(nameof(Delete));
  132. private static MethodInfo MultiDeleteMethod = GetMethod(nameof(MultiDelete));
  133. private static MethodInfo QueryMultipleMethod = GetMethod(nameof(QueryMultiple));
  134. private static MethodInfo ValidateMethod = GetMethod(nameof(Validate));
  135. private static MethodInfo Check2FAMethod = GetMethod(nameof(Check2FA));
  136. private static MethodInfo PingMethod = GetMethod(nameof(Ping));
  137. private static MethodInfo InfoMethod = GetMethod(nameof(Info));
  138. private static MethodInfo GetMethod(string name) =>
  139. typeof(PipeIPCServer).GetMethod(name, BindingFlags.NonPublic | BindingFlags.Static)
  140. ?? throw new Exception($"Invalid method '{name}'");
  141. private void Server_MessageReceived(object? sender, H.Pipes.Args.ConnectionMessageEventArgs<PipeRequest?> e)
  142. {
  143. Task.Run(() =>
  144. {
  145. var start = DateTime.Now;
  146. try
  147. {
  148. if (e.Message == null) throw new Exception($"Invalid message");
  149. var method = e.Message.Method switch
  150. {
  151. Method.Query => QueryMethod,
  152. Method.QueryMultiple => QueryMultipleMethod,
  153. Method.Delete => DeleteMethod,
  154. Method.MultiDelete => MultiDeleteMethod,
  155. Method.Save => SaveMethod,
  156. Method.MultiSave => MultiSaveMethod,
  157. Method.Check2FA => Check2FAMethod,
  158. Method.Validate => ValidateMethod,
  159. Method.Ping => PingMethod,
  160. Method.Info => InfoMethod,
  161. Method.None or _ => throw new Exception($"Invalid method '{e.Message.Method}'")
  162. };
  163. if (e.Message.Type != null)
  164. {
  165. var entityType = GetEntity(e.Message.Type) ?? throw new Exception($"No entity '{e.Message.Type}'");
  166. method = method.MakeGenericMethod(entityType);
  167. }
  168. var response = method.Invoke(null, new object[] { e.Message }) as PipeResponse;
  169. e.Connection.WriteAsync(response);
  170. }
  171. catch (Exception err)
  172. {
  173. Logger.Send(LogType.Error, "", err.Message);
  174. if (e.Message != null)
  175. {
  176. var responseType = GetResponseType(e.Message.Method, e.Message.Type);
  177. if (responseType != null)
  178. {
  179. var response = (Activator.CreateInstance(responseType) as Response)!;
  180. response.Status = StatusCode.Error;
  181. response.Messages.Add(err.Message);
  182. e.Connection.WriteAsync(e.Message.Respond(response));
  183. }
  184. }
  185. }
  186. });
  187. }
  188. private void Server_ClientDisconnected(object? sender, H.Pipes.Args.ConnectionEventArgs<PipeRequest> e)
  189. {
  190. Logger.Send(LogType.Information, "", "Client Disconnected");
  191. e.Connection.DisposeAsync();
  192. }
  193. private void Server_ClientConnected(object? sender, H.Pipes.Args.ConnectionEventArgs<PipeRequest> e)
  194. {
  195. Logger.Send(LogType.Information, "", "Client Connected");
  196. }
  197. public void Dispose()
  198. {
  199. Server.DisposeAsync().AsTask().Wait();
  200. }
  201. ~PipeIPCServer()
  202. {
  203. Dispose();
  204. }
  205. }
  206. }