IPCServer.cs 11 KB

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