AccessReaderSystem.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. using System.Diagnostics.CodeAnalysis;
  2. using System.Linq;
  3. using Content.Shared.Access.Components;
  4. using Content.Shared.DeviceLinking.Events;
  5. using Content.Shared.Emag.Systems;
  6. using Content.Shared.Hands.EntitySystems;
  7. using Content.Shared.Inventory;
  8. using Content.Shared.NameIdentifier;
  9. using Content.Shared.PDA;
  10. using Content.Shared.StationRecords;
  11. using Robust.Shared.Containers;
  12. using Robust.Shared.GameStates;
  13. using Content.Shared.GameTicking;
  14. using Content.Shared.IdentityManagement;
  15. using Robust.Shared.Collections;
  16. using Robust.Shared.Prototypes;
  17. using Robust.Shared.Timing;
  18. namespace Content.Shared.Access.Systems;
  19. public sealed class AccessReaderSystem : EntitySystem
  20. {
  21. [Dependency] private readonly IPrototypeManager _prototype = default!;
  22. [Dependency] private readonly InventorySystem _inventorySystem = default!;
  23. [Dependency] private readonly IGameTiming _gameTiming = default!;
  24. [Dependency] private readonly EmagSystem _emag = default!;
  25. [Dependency] private readonly SharedGameTicker _gameTicker = default!;
  26. [Dependency] private readonly SharedHandsSystem _handsSystem = default!;
  27. [Dependency] private readonly SharedContainerSystem _containerSystem = default!;
  28. [Dependency] private readonly SharedStationRecordsSystem _recordsSystem = default!;
  29. public override void Initialize()
  30. {
  31. base.Initialize();
  32. SubscribeLocalEvent<AccessReaderComponent, GotEmaggedEvent>(OnEmagged);
  33. SubscribeLocalEvent<AccessReaderComponent, LinkAttemptEvent>(OnLinkAttempt);
  34. SubscribeLocalEvent<AccessReaderComponent, ComponentGetState>(OnGetState);
  35. SubscribeLocalEvent<AccessReaderComponent, ComponentHandleState>(OnHandleState);
  36. }
  37. private void OnGetState(EntityUid uid, AccessReaderComponent component, ref ComponentGetState args)
  38. {
  39. args.State = new AccessReaderComponentState(component.Enabled, component.DenyTags, component.AccessLists,
  40. _recordsSystem.Convert(component.AccessKeys), component.AccessLog, component.AccessLogLimit);
  41. }
  42. private void OnHandleState(EntityUid uid, AccessReaderComponent component, ref ComponentHandleState args)
  43. {
  44. if (args.Current is not AccessReaderComponentState state)
  45. return;
  46. component.Enabled = state.Enabled;
  47. component.AccessKeys.Clear();
  48. foreach (var key in state.AccessKeys)
  49. {
  50. var id = EnsureEntity<AccessReaderComponent>(key.Item1, uid);
  51. if (!id.IsValid())
  52. continue;
  53. component.AccessKeys.Add(new StationRecordKey(key.Item2, id));
  54. }
  55. component.AccessLists = new(state.AccessLists);
  56. component.DenyTags = new(state.DenyTags);
  57. component.AccessLog = new(state.AccessLog);
  58. component.AccessLogLimit = state.AccessLogLimit;
  59. }
  60. private void OnLinkAttempt(EntityUid uid, AccessReaderComponent component, LinkAttemptEvent args)
  61. {
  62. if (args.User == null) // AutoLink (and presumably future external linkers) have no user.
  63. return;
  64. if (!IsAllowed(args.User.Value, uid, component))
  65. args.Cancel();
  66. }
  67. private void OnEmagged(EntityUid uid, AccessReaderComponent reader, ref GotEmaggedEvent args)
  68. {
  69. if (!_emag.CompareFlag(args.Type, EmagType.Access))
  70. return;
  71. if (!reader.BreakOnAccessBreaker)
  72. return;
  73. if (!GetMainAccessReader(uid, out var accessReader))
  74. return;
  75. if (accessReader.Value.Comp.AccessLists.Count < 1)
  76. return;
  77. args.Repeatable = true;
  78. args.Handled = true;
  79. accessReader.Value.Comp.AccessLists.Clear();
  80. accessReader.Value.Comp.AccessLog.Clear();
  81. Dirty(uid, reader);
  82. }
  83. /// <summary>
  84. /// Searches the source for access tags
  85. /// then compares it with the all targets accesses to see if it is allowed.
  86. /// </summary>
  87. /// <param name="user">The entity that wants access.</param>
  88. /// <param name="target">The entity to search for an access reader</param>
  89. /// <param name="reader">Optional reader from the target entity</param>
  90. public bool IsAllowed(EntityUid user, EntityUid target, AccessReaderComponent? reader = null)
  91. {
  92. if (!Resolve(target, ref reader, false))
  93. return true;
  94. if (!reader.Enabled)
  95. return true;
  96. var accessSources = FindPotentialAccessItems(user);
  97. var access = FindAccessTags(user, accessSources);
  98. FindStationRecordKeys(user, out var stationKeys, accessSources);
  99. if (IsAllowed(access, stationKeys, target, reader))
  100. {
  101. LogAccess((target, reader), user);
  102. return true;
  103. }
  104. return false;
  105. }
  106. public bool GetMainAccessReader(EntityUid uid, [NotNullWhen(true)] out Entity<AccessReaderComponent>? ent)
  107. {
  108. ent = null;
  109. if (!TryComp<AccessReaderComponent>(uid, out var accessReader))
  110. return false;
  111. ent = (uid, accessReader);
  112. if (ent.Value.Comp.ContainerAccessProvider == null)
  113. return true;
  114. if (!_containerSystem.TryGetContainer(uid, ent.Value.Comp.ContainerAccessProvider, out var container))
  115. return true;
  116. foreach (var entity in container.ContainedEntities)
  117. {
  118. if (TryComp<AccessReaderComponent>(entity, out var containedReader))
  119. {
  120. ent = (entity, containedReader);
  121. return true;
  122. }
  123. }
  124. return true;
  125. }
  126. /// <summary>
  127. /// Check whether the given access permissions satisfy an access reader's requirements.
  128. /// </summary>
  129. public bool IsAllowed(
  130. ICollection<ProtoId<AccessLevelPrototype>> access,
  131. ICollection<StationRecordKey> stationKeys,
  132. EntityUid target,
  133. AccessReaderComponent reader)
  134. {
  135. if (!reader.Enabled)
  136. return true;
  137. if (reader.ContainerAccessProvider == null)
  138. return IsAllowedInternal(access, stationKeys, reader);
  139. if (!_containerSystem.TryGetContainer(target, reader.ContainerAccessProvider, out var container))
  140. return false;
  141. // If entity is paused then always allow it at this point.
  142. // Door electronics is kind of a mess but yeah, it should only be an unpaused ent interacting with it
  143. if (Paused(target))
  144. return true;
  145. foreach (var entity in container.ContainedEntities)
  146. {
  147. if (!TryComp(entity, out AccessReaderComponent? containedReader))
  148. continue;
  149. if (IsAllowed(access, stationKeys, entity, containedReader))
  150. return true;
  151. }
  152. return false;
  153. }
  154. private bool IsAllowedInternal(ICollection<ProtoId<AccessLevelPrototype>> access, ICollection<StationRecordKey> stationKeys, AccessReaderComponent reader)
  155. {
  156. return !reader.Enabled
  157. || AreAccessTagsAllowed(access, reader)
  158. || AreStationRecordKeysAllowed(stationKeys, reader);
  159. }
  160. /// <summary>
  161. /// Compares the given tags with the readers access list to see if it is allowed.
  162. /// </summary>
  163. /// <param name="accessTags">A list of access tags</param>
  164. /// <param name="reader">An access reader to check against</param>
  165. public bool AreAccessTagsAllowed(ICollection<ProtoId<AccessLevelPrototype>> accessTags, AccessReaderComponent reader)
  166. {
  167. if (reader.DenyTags.Overlaps(accessTags))
  168. {
  169. // Sec owned by cargo.
  170. // Note that in resolving the issue with only one specific item "counting" for access, this became a bit more strict.
  171. // As having an ID card in any slot that "counts" with a denied access group will cause denial of access.
  172. // DenyTags doesn't seem to be used right now anyway, though, so it'll be dependent on whoever uses it to figure out if this matters.
  173. return false;
  174. }
  175. if (reader.AccessLists.Count == 0)
  176. return true;
  177. foreach (var set in reader.AccessLists)
  178. {
  179. if (set.IsSubsetOf(accessTags))
  180. return true;
  181. }
  182. return false;
  183. }
  184. /// <summary>
  185. /// Compares the given stationrecordkeys with the accessreader to see if it is allowed.
  186. /// </summary>
  187. public bool AreStationRecordKeysAllowed(ICollection<StationRecordKey> keys, AccessReaderComponent reader)
  188. {
  189. foreach (var key in reader.AccessKeys)
  190. {
  191. if (keys.Contains(key))
  192. return true;
  193. }
  194. return false;
  195. }
  196. /// <summary>
  197. /// Finds all the items that could potentially give access to a given entity
  198. /// </summary>
  199. public HashSet<EntityUid> FindPotentialAccessItems(EntityUid uid)
  200. {
  201. FindAccessItemsInventory(uid, out var items);
  202. var ev = new GetAdditionalAccessEvent
  203. {
  204. Entities = items
  205. };
  206. RaiseLocalEvent(uid, ref ev);
  207. foreach (var item in new ValueList<EntityUid>(items))
  208. {
  209. items.UnionWith(FindPotentialAccessItems(item));
  210. }
  211. items.Add(uid);
  212. return items;
  213. }
  214. /// <summary>
  215. /// Finds the access tags on the given entity
  216. /// </summary>
  217. /// <param name="uid">The entity that is being searched.</param>
  218. /// <param name="items">All of the items to search for access. If none are passed in, <see cref="FindPotentialAccessItems"/> will be used.</param>
  219. public ICollection<ProtoId<AccessLevelPrototype>> FindAccessTags(EntityUid uid, HashSet<EntityUid>? items = null)
  220. {
  221. HashSet<ProtoId<AccessLevelPrototype>>? tags = null;
  222. var owned = false;
  223. items ??= FindPotentialAccessItems(uid);
  224. foreach (var ent in items)
  225. {
  226. FindAccessTagsItem(ent, ref tags, ref owned);
  227. }
  228. return (ICollection<ProtoId<AccessLevelPrototype>>?) tags ?? Array.Empty<ProtoId<AccessLevelPrototype>>();
  229. }
  230. /// <summary>
  231. /// Finds the access tags on the given entity
  232. /// </summary>
  233. /// <param name="uid">The entity that is being searched.</param>
  234. /// <param name="recordKeys"></param>
  235. /// <param name="items">All of the items to search for access. If none are passed in, <see cref="FindPotentialAccessItems"/> will be used.</param>
  236. public bool FindStationRecordKeys(EntityUid uid, out ICollection<StationRecordKey> recordKeys, HashSet<EntityUid>? items = null)
  237. {
  238. recordKeys = new HashSet<StationRecordKey>();
  239. items ??= FindPotentialAccessItems(uid);
  240. foreach (var ent in items)
  241. {
  242. if (FindStationRecordKeyItem(ent, out var key))
  243. recordKeys.Add(key.Value);
  244. }
  245. return recordKeys.Any();
  246. }
  247. /// <summary>
  248. /// Try to find <see cref="AccessComponent"/> on this item
  249. /// or inside this item (if it's pda)
  250. /// This version merges into a set or replaces the set.
  251. /// If owned is false, the existing tag-set "isn't ours" and can't be merged with (is read-only).
  252. /// </summary>
  253. private void FindAccessTagsItem(EntityUid uid, ref HashSet<ProtoId<AccessLevelPrototype>>? tags, ref bool owned)
  254. {
  255. if (!FindAccessTagsItem(uid, out var targetTags))
  256. {
  257. // no tags, no problem
  258. return;
  259. }
  260. if (tags != null)
  261. {
  262. // existing tags, so copy to make sure we own them
  263. if (!owned)
  264. {
  265. tags = new(tags);
  266. owned = true;
  267. }
  268. // then merge
  269. tags.UnionWith(targetTags);
  270. }
  271. else
  272. {
  273. // no existing tags, so now they're ours
  274. tags = targetTags;
  275. owned = false;
  276. }
  277. }
  278. public void SetAccesses(EntityUid uid, AccessReaderComponent component, List<ProtoId<AccessLevelPrototype>> accesses)
  279. {
  280. component.AccessLists.Clear();
  281. foreach (var access in accesses)
  282. {
  283. component.AccessLists.Add(new HashSet<ProtoId<AccessLevelPrototype>>(){access});
  284. }
  285. Dirty(uid, component);
  286. RaiseLocalEvent(uid, new AccessReaderConfigurationChangedEvent());
  287. }
  288. public bool FindAccessItemsInventory(EntityUid uid, out HashSet<EntityUid> items)
  289. {
  290. items = new();
  291. foreach (var item in _handsSystem.EnumerateHeld(uid))
  292. {
  293. items.Add(item);
  294. }
  295. // maybe its inside an inventory slot?
  296. if (_inventorySystem.TryGetSlotEntity(uid, "id", out var idUid))
  297. {
  298. items.Add(idUid.Value);
  299. }
  300. return items.Any();
  301. }
  302. /// <summary>
  303. /// Try to find <see cref="AccessComponent"/> on this item
  304. /// or inside this item (if it's pda)
  305. /// </summary>
  306. private bool FindAccessTagsItem(EntityUid uid, out HashSet<ProtoId<AccessLevelPrototype>> tags)
  307. {
  308. tags = new();
  309. var ev = new GetAccessTagsEvent(tags, _prototype);
  310. RaiseLocalEvent(uid, ref ev);
  311. return tags.Count != 0;
  312. }
  313. /// <summary>
  314. /// Try to find <see cref="StationRecordKeyStorageComponent"/> on this item
  315. /// or inside this item (if it's pda)
  316. /// </summary>
  317. private bool FindStationRecordKeyItem(EntityUid uid, [NotNullWhen(true)] out StationRecordKey? key)
  318. {
  319. if (TryComp(uid, out StationRecordKeyStorageComponent? storage) && storage.Key != null)
  320. {
  321. key = storage.Key;
  322. return true;
  323. }
  324. if (TryComp<PdaComponent>(uid, out var pda) &&
  325. pda.ContainedId is { Valid: true } id)
  326. {
  327. if (TryComp<StationRecordKeyStorageComponent>(id, out var pdastorage) && pdastorage.Key != null)
  328. {
  329. key = pdastorage.Key;
  330. return true;
  331. }
  332. }
  333. key = null;
  334. return false;
  335. }
  336. /// <summary>
  337. /// Logs an access for a specific entity.
  338. /// </summary>
  339. /// <param name="ent">The reader to log the access on</param>
  340. /// <param name="accessor">The accessor to log</param>
  341. public void LogAccess(Entity<AccessReaderComponent> ent, EntityUid accessor)
  342. {
  343. if (IsPaused(ent) || ent.Comp.LoggingDisabled)
  344. return;
  345. string? name = null;
  346. if (TryComp<NameIdentifierComponent>(accessor, out var nameIdentifier))
  347. name = nameIdentifier.FullIdentifier;
  348. // TODO pass the ID card on IsAllowed() instead of using this expensive method
  349. // Set name if the accessor has a card and that card has a name and allows itself to be recorded
  350. var getIdentityShortInfoEvent = new TryGetIdentityShortInfoEvent(ent, accessor, true);
  351. RaiseLocalEvent(getIdentityShortInfoEvent);
  352. if (getIdentityShortInfoEvent.Title != null)
  353. {
  354. name = getIdentityShortInfoEvent.Title;
  355. }
  356. LogAccess(ent, name ?? Loc.GetString("access-reader-unknown-id"));
  357. }
  358. /// <summary>
  359. /// Logs an access with a predetermined name
  360. /// </summary>
  361. /// <param name="ent">The reader to log the access on</param>
  362. /// <param name="name">The name to log as</param>
  363. public void LogAccess(Entity<AccessReaderComponent> ent, string name)
  364. {
  365. if (IsPaused(ent) || ent.Comp.LoggingDisabled)
  366. return;
  367. if (ent.Comp.AccessLog.Count >= ent.Comp.AccessLogLimit)
  368. ent.Comp.AccessLog.Dequeue();
  369. var stationTime = _gameTiming.CurTime.Subtract(_gameTicker.RoundStartTimeSpan);
  370. ent.Comp.AccessLog.Enqueue(new AccessRecord(stationTime, name));
  371. }
  372. }