IPCServer.cs 12 KB

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