IPCServer.cs 12 KB

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