user_namespace.rs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. use alloc::sync::{Arc, Weak};
  2. use core::cmp::Ordering;
  3. use core::fmt::Debug;
  4. use crate::libs::spinlock::SpinLock;
  5. use crate::process::ProcessManager;
  6. use super::nsproxy::NsCommon;
  7. use super::{NamespaceOps, NamespaceType};
  8. use alloc::vec::Vec;
  9. lazy_static! {
  10. pub static ref INIT_USER_NAMESPACE: Arc<UserNamespace> = UserNamespace::new_root();
  11. }
  12. pub struct UserNamespace {
  13. parent: Option<Weak<UserNamespace>>,
  14. nscommon: NsCommon,
  15. self_ref: Weak<UserNamespace>,
  16. _inner: SpinLock<InnerUserNamespace>,
  17. }
  18. pub struct InnerUserNamespace {
  19. _children: Vec<Arc<UserNamespace>>,
  20. }
  21. impl NamespaceOps for UserNamespace {
  22. fn ns_common(&self) -> &NsCommon {
  23. &self.nscommon
  24. }
  25. }
  26. impl UserNamespace {
  27. /// 创建root user namespace
  28. fn new_root() -> Arc<Self> {
  29. Arc::new_cyclic(|self_ref| Self {
  30. self_ref: self_ref.clone(),
  31. nscommon: NsCommon::new(0, NamespaceType::User),
  32. parent: None,
  33. _inner: SpinLock::new(InnerUserNamespace {
  34. _children: Vec::new(),
  35. }),
  36. })
  37. }
  38. /// 获取层级
  39. pub fn level(&self) -> u32 {
  40. self.nscommon.level
  41. }
  42. /// 检查当前用户命名空间是否是另一个用户命名空间的祖先
  43. ///
  44. /// # 参数
  45. /// * `other` - 要检查的目标用户命名空间
  46. ///
  47. /// # 返回值
  48. /// * `true` - 如果当前命名空间是 `other` 的祖先
  49. /// * `false` - 如果当前命名空间不是 `other` 的祖先
  50. ///
  51. /// # 说明
  52. /// 该方法通过遍历 `other` 的父命名空间链来判断当前命名空间是否为其祖先。
  53. /// 如果两个命名空间处于同一层级且指向同一个对象,则认为是祖先关系。
  54. /// 如果当前命名空间的层级大于目标命名空间,则不可能是祖先关系。
  55. pub fn is_ancestor_of(&self, other: &Arc<Self>) -> bool {
  56. let mut current = other.clone();
  57. let self_level = self.level();
  58. loop {
  59. let current_level = current.level();
  60. match current_level.cmp(&self_level) {
  61. Ordering::Greater => {
  62. if let Some(parent) = current.parent.as_ref().and_then(|p| p.upgrade()) {
  63. current = parent;
  64. continue;
  65. } else {
  66. return false;
  67. }
  68. }
  69. Ordering::Equal => return Arc::ptr_eq(&self.self_ref.upgrade().unwrap(), &current),
  70. Ordering::Less => return false,
  71. }
  72. }
  73. }
  74. }
  75. impl Debug for UserNamespace {
  76. fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
  77. f.debug_struct("UserNamespace").finish()
  78. }
  79. }
  80. impl ProcessManager {
  81. /// 获取当前进程的 user_ns
  82. pub fn current_user_ns() -> Arc<UserNamespace> {
  83. if Self::initialized() {
  84. ProcessManager::current_pcb().cred().user_ns.clone()
  85. } else {
  86. INIT_USER_NAMESPACE.clone()
  87. }
  88. }
  89. }