IPCServer.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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 System.Collections.Concurrent;
  8. using System.IO.Pipes;
  9. using System.Reflection;
  10. using System.Security.Principal;
  11. namespace InABox.IPC
  12. {
  13. delegate void IPCPollEvent(IPCNotifyState.Session session);
  14. class IPCNotifyState
  15. {
  16. public class Session
  17. {
  18. public PipeConnection<IPCMessage?> Connection { get; }
  19. public Guid SessionID { get; }
  20. public Platform Platform { get; }
  21. public Session(PipeConnection<IPCMessage?> connection, Guid sessionID, Platform platform)
  22. {
  23. Connection = connection;
  24. SessionID = sessionID;
  25. Platform = platform;
  26. }
  27. }
  28. public ConcurrentDictionary<Guid, Session> SessionMap = new();
  29. public event IPCPollEvent? OnPoll;
  30. public void Poll(Session session)
  31. {
  32. OnPoll?.Invoke(session);
  33. }
  34. }
  35. class IPCNotifier : Notifier
  36. {
  37. IPCNotifyState NotifyState { get; set; }
  38. public IPCNotifier(IPCNotifyState notifyState)
  39. {
  40. NotifyState = notifyState;
  41. NotifyState.OnPoll += NotifyState_OnPoll;
  42. }
  43. private void NotifyState_OnPoll(IPCNotifyState.Session session)
  44. {
  45. Notify.Poll(session.SessionID);
  46. }
  47. protected override IEnumerable<Guid> GetSessions(Platform platform)
  48. {
  49. return NotifyState.SessionMap.Where(x => x.Value.Platform == platform).Select(x => x.Key);
  50. }
  51. protected override IEnumerable<Guid> GetUserSessions(Guid userID)
  52. {
  53. return CredentialsCache.GetUserSessions(userID);
  54. }
  55. protected override void NotifyAll<TNotification>(TNotification notification)
  56. {
  57. foreach(var session in NotifyState.SessionMap.Values)
  58. {
  59. session.Connection.WriteAsync(IPCMessage.Notification(notification)).ContinueWith(task =>
  60. {
  61. if(task.Exception != null)
  62. {
  63. Logger.Send(LogType.Error, "", $"Error in notification: {CoreUtils.FormatException(task.Exception)}");
  64. }
  65. });
  66. }
  67. }
  68. protected override void NotifySession<TNotification>(Guid sessionID, TNotification notification)
  69. {
  70. if(NotifyState.SessionMap.TryGetValue(sessionID, out var session))
  71. {
  72. session.Connection.WriteAsync(IPCMessage.Notification(notification)).ContinueWith(task =>
  73. {
  74. if(task.Exception != null)
  75. {
  76. Logger.Send(LogType.Error, "", $"Error in notification: {CoreUtils.FormatException(task.Exception)}");
  77. }
  78. });
  79. }
  80. }
  81. protected override void NotifySession(Guid sessionID, Type TNotification, BaseObject notification)
  82. {
  83. if(NotifyState.SessionMap.TryGetValue(sessionID, out var session))
  84. {
  85. session.Connection.WriteAsync(IPCMessage.Notification(TNotification, notification)).ContinueWith(task =>
  86. {
  87. if(task.Exception != null)
  88. {
  89. Logger.Send(LogType.Error, "", $"Error in notification: {CoreUtils.FormatException(task.Exception)}");
  90. }
  91. });
  92. }
  93. }
  94. }
  95. public class IPCServer : IDisposable
  96. {
  97. PipeServer<IPCMessage> Server;
  98. IPCNotifyState NotifyState = new();
  99. public IPCServer(string name)
  100. {
  101. Server = new PipeServer<IPCMessage>(name);
  102. #if WINDOWS
  103. SetPipeSecurity();
  104. #endif
  105. Server.ClientConnected += Server_ClientConnected;
  106. Server.ClientDisconnected += Server_ClientDisconnected;
  107. Server.MessageReceived += Server_MessageReceived;
  108. Server.ExceptionOccurred += Server_ExceptionOccurred;
  109. }
  110. private void SetPipeSecurity()
  111. {
  112. #pragma warning disable CA1416
  113. var pipeSecurity = new PipeSecurity();
  114. pipeSecurity.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.LocalSid, null), PipeAccessRights.ReadWrite,
  115. System.Security.AccessControl.AccessControlType.Allow));
  116. pipeSecurity.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.LocalServiceSid, null), PipeAccessRights.ReadWrite,
  117. System.Security.AccessControl.AccessControlType.Allow));
  118. pipeSecurity.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), PipeAccessRights.ReadWrite,
  119. System.Security.AccessControl.AccessControlType.Allow));
  120. Server.SetPipeSecurity(pipeSecurity);
  121. #pragma warning restore CA1416
  122. }
  123. private void Server_ExceptionOccurred(object? sender, H.Pipes.Args.ExceptionEventArgs e)
  124. {
  125. Logger.Send(LogType.Error, "", $"Exception Occurred: {e.Exception.Message}");
  126. }
  127. public void Start()
  128. {
  129. Server.StartAsync().Wait();
  130. }
  131. private static List<Type>? _persistentRemotable;
  132. private static Type? GetEntity(string entityName)
  133. {
  134. _persistentRemotable ??= CoreUtils.TypeList(
  135. e => e.IsSubclassOf(typeof(Entity)) &&
  136. e.GetInterfaces().Contains(typeof(IRemotable)) &&
  137. e.GetInterfaces().Contains(typeof(IPersistent))).ToList();
  138. return _persistentRemotable.FirstOrDefault(x => x.Name == entityName);
  139. }
  140. private static Type? GetResponseType(Method method, string? entityName)
  141. {
  142. if(entityName != null)
  143. {
  144. var entityType = GetEntity(entityName);
  145. if(entityType != null)
  146. {
  147. var response = method switch
  148. {
  149. Method.Query => typeof(QueryResponse<>).MakeGenericType(entityType),
  150. Method.Delete => typeof(DeleteResponse<>).MakeGenericType(entityType),
  151. Method.MultiDelete => typeof(MultiDeleteResponse<>).MakeGenericType(entityType),
  152. Method.Save => typeof(SaveResponse<>).MakeGenericType(entityType),
  153. Method.MultiSave => typeof(MultiSaveResponse<>).MakeGenericType(entityType),
  154. _ => null
  155. };
  156. if (response != null) return response;
  157. }
  158. }
  159. return method switch
  160. {
  161. Method.QueryMultiple => typeof(MultiQueryResponse),
  162. Method.Validate => typeof(ValidateResponse),
  163. Method.Check2FA => typeof(Check2FAResponse),
  164. _ => null
  165. };
  166. }
  167. private class RequestData
  168. {
  169. public ConnectionMessageEventArgs<IPCMessage?> e { get; }
  170. public RequestData(ConnectionMessageEventArgs<IPCMessage?> e)
  171. {
  172. this.e = e;
  173. }
  174. }
  175. private IPCMessage QueryMultiple(IPCMessage request, RequestData data)
  176. {
  177. var response = RestService.QueryMultiple(request.GetRequest<MultiQueryRequest>(), true);
  178. return request.Respond(response);
  179. }
  180. private IPCMessage Validate(IPCMessage request, RequestData data)
  181. {
  182. var response = RestService.Validate(request.GetRequest<ValidateRequest>());
  183. return request.Respond(response);
  184. }
  185. private IPCMessage Ping(IPCMessage request, RequestData data) => request.Respond(new PingResponse().Status(StatusCode.OK));
  186. private IPCMessage Info(IPCMessage request, RequestData data)
  187. {
  188. var response = RestService.Info(request.GetRequest<InfoRequest>());
  189. return request.Respond(response);
  190. }
  191. private IPCMessage Check2FA(IPCMessage request, RequestData data)
  192. {
  193. var response = RestService.Check2FA(request.GetRequest<Check2FARequest>());
  194. return request.Respond(response);
  195. }
  196. private IPCMessage Query<T>(IPCMessage request, RequestData data) where T : Entity, new()
  197. {
  198. var response = RestService<T>.List(request.GetRequest<QueryRequest<T>>());
  199. return request.Respond(response);
  200. }
  201. private IPCMessage Save<T>(IPCMessage request, RequestData data) where T : Entity, new()
  202. {
  203. var response = RestService<T>.Save(request.GetRequest<SaveRequest<T>>());
  204. return request.Respond(response);
  205. }
  206. private IPCMessage MultiSave<T>(IPCMessage request, RequestData data) where T : Entity, new()
  207. {
  208. var response = RestService<T>.MultiSave(request.GetRequest<MultiSaveRequest<T>>());
  209. return request.Respond(response);
  210. }
  211. private IPCMessage Delete<T>(IPCMessage request, RequestData data) where T : Entity, new()
  212. {
  213. var response = RestService<T>.Delete(request.GetRequest<DeleteRequest<T>>());
  214. return request.Respond(response);
  215. }
  216. private IPCMessage MultiDelete<T>(IPCMessage request, RequestData data) where T : Entity, new()
  217. {
  218. var response = RestService<T>.MultiDelete(request.GetRequest<MultiDeleteRequest<T>>());
  219. return request.Respond(response);
  220. }
  221. private static readonly MethodInfo QueryMethod = GetMethod(nameof(Query));
  222. private static readonly MethodInfo SaveMethod = GetMethod(nameof(Save));
  223. private static readonly MethodInfo MultiSaveMethod = GetMethod(nameof(MultiSave));
  224. private static readonly MethodInfo DeleteMethod = GetMethod(nameof(Delete));
  225. private static readonly MethodInfo MultiDeleteMethod = GetMethod(nameof(MultiDelete));
  226. private static readonly MethodInfo QueryMultipleMethod = GetMethod(nameof(QueryMultiple));
  227. private static readonly MethodInfo ValidateMethod = GetMethod(nameof(Validate));
  228. private static readonly MethodInfo Check2FAMethod = GetMethod(nameof(Check2FA));
  229. private static readonly MethodInfo PingMethod = GetMethod(nameof(Ping));
  230. private static readonly MethodInfo InfoMethod = GetMethod(nameof(Info));
  231. private static MethodInfo GetMethod(string name) =>
  232. typeof(IPCServer).GetMethod(name, BindingFlags.NonPublic | BindingFlags.Instance)
  233. ?? throw new Exception($"Invalid method '{name}'");
  234. private void Server_MessageReceived(object? sender, H.Pipes.Args.ConnectionMessageEventArgs<IPCMessage?> e)
  235. {
  236. Task.Run(() =>
  237. {
  238. var start = DateTime.Now;
  239. try
  240. {
  241. if (e.Message == null) throw new Exception($"Invalid message");
  242. var method = e.Message.Method switch
  243. {
  244. Method.Query => QueryMethod,
  245. Method.QueryMultiple => QueryMultipleMethod,
  246. Method.Delete => DeleteMethod,
  247. Method.MultiDelete => MultiDeleteMethod,
  248. Method.Save => SaveMethod,
  249. Method.MultiSave => MultiSaveMethod,
  250. Method.Check2FA => Check2FAMethod,
  251. Method.Validate => ValidateMethod,
  252. Method.Ping => PingMethod,
  253. Method.Info => InfoMethod,
  254. Method.None or _ => throw new Exception($"Invalid method '{e.Message.Method}'")
  255. };
  256. if (e.Message.Type != null)
  257. {
  258. var entityType = GetEntity(e.Message.Type) ?? throw new Exception($"No entity '{e.Message.Type}'");
  259. method = method.MakeGenericMethod(entityType);
  260. }
  261. var response = method.Invoke(this, new object[] { e.Message, new RequestData(e) }) as IPCMessage;
  262. e.Connection.WriteAsync(response).ContinueWith(task =>
  263. {
  264. if (task.Exception != null)
  265. {
  266. Logger.Send(LogType.Error, "", $"Error in response: {CoreUtils.FormatException(task.Exception)}");
  267. }
  268. });
  269. }
  270. catch (Exception err)
  271. {
  272. Logger.Send(LogType.Error, "", err.Message);
  273. if (e.Message != null)
  274. {
  275. var responseType = GetResponseType(e.Message.Method, e.Message.Type);
  276. if (responseType != null)
  277. {
  278. var response = (Activator.CreateInstance(responseType) as Response)!;
  279. response.Status = StatusCode.Error;
  280. response.Messages.Add(err.Message);
  281. e.Connection.WriteAsync(e.Message.Respond(response)).ContinueWith(task =>
  282. {
  283. if (task.Exception != null)
  284. {
  285. Logger.Send(LogType.Error, "", $"Error in response: {CoreUtils.FormatException(task.Exception)}");
  286. }
  287. });
  288. }
  289. }
  290. }
  291. });
  292. }
  293. private void Server_ClientDisconnected(object? sender, H.Pipes.Args.ConnectionEventArgs<IPCMessage> e)
  294. {
  295. Logger.Send(LogType.Information, "", "Client Disconnected");
  296. var sessionID = NotifyState.SessionMap.Where(x => x.Value.Connection == e.Connection).FirstOrDefault().Key;
  297. NotifyState.SessionMap.TryRemove(sessionID, out var session);
  298. e.Connection.DisposeAsync();
  299. }
  300. private void Server_ClientConnected(object? sender, H.Pipes.Args.ConnectionEventArgs<IPCMessage> e)
  301. {
  302. Logger.Send(LogType.Information, "", "Client Connected");
  303. }
  304. public void Dispose()
  305. {
  306. Server.DisposeAsync().AsTask().Wait();
  307. }
  308. ~IPCServer()
  309. {
  310. Dispose();
  311. }
  312. }
  313. }