binder/
state.rs

1/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17use crate::sys;
18
19use libc::{pid_t, uid_t};
20
21/// Static utility functions to manage Binder process state.
22pub struct ProcessState;
23
24impl ProcessState {
25    /// Starts the Binder IPC thread pool.
26    ///
27    /// Starts 1 thread, plus allows the kernel to lazily start up to
28    /// `num_threads` additional threads as specified by
29    /// [`set_thread_pool_max_thread_count`](Self::set_thread_pool_max_thread_count).
30    ///
31    /// If this is called, it must be done before creating any Binder client or server.
32    ///
33    /// If neither this nor [`join_thread_pool`](Self::join_thread_pool) are
34    /// called, then some things (such as callbacks and
35    /// [`IBinder::link_to_death`](crate::IBinder::link_to_death)) will silently
36    /// not work: the callbacks will be queued but never called as there is no
37    /// thread to call them on.
38    pub fn start_thread_pool() {
39        // Safety: Safe FFI
40        unsafe {
41            sys::ABinderProcess_startThreadPool();
42        }
43    }
44
45    /// Sets the maximum number of threads that can be started in the
46    /// threadpool.
47    ///
48    /// By default, after [`start_thread_pool`](Self::start_thread_pool) is
49    /// called, this is 15. If it is called additional times, the thread pool
50    /// size can only be increased.
51    pub fn set_thread_pool_max_thread_count(num_threads: u32) {
52        // Safety: Safe FFI
53        unsafe {
54            sys::ABinderProcess_setThreadPoolMaxThreadCount(num_threads);
55        }
56    }
57
58    /// Blocks on the Binder IPC thread pool by adding the current thread to the
59    /// pool.
60    ///
61    /// Note that this adds the current thread in addition to those that are
62    /// created by
63    /// [`set_thread_pool_max_thread_count`](Self::set_thread_pool_max_thread_count)
64    /// and [`start_thread_pool`](Self::start_thread_pool).
65    pub fn join_thread_pool() {
66        // Safety: Safe FFI
67        unsafe {
68            sys::ABinderProcess_joinThreadPool();
69        }
70    }
71}
72
73/// Static utility functions to manage Binder thread state.
74pub struct ThreadState;
75
76impl ThreadState {
77    /// This returns the calling UID assuming that this thread is called from a
78    /// thread that is processing a binder transaction (for instance, in the
79    /// implementation of
80    /// [`Remotable::on_transact`](crate::Remotable::on_transact)).
81    ///
82    /// This can be used with higher-level system services to determine the
83    /// caller's identity and check permissions.
84    ///
85    /// Available since API level 29.
86    ///
87    /// \return calling uid or the current process's UID if this thread isn't
88    /// processing a transaction.
89    pub fn get_calling_uid() -> uid_t {
90        // Safety: Safe FFI
91        unsafe { sys::AIBinder_getCallingUid() }
92    }
93
94    /// This returns the calling PID assuming that this thread is called from a
95    /// thread that is processing a binder transaction (for instance, in the
96    /// implementation of
97    /// [`Remotable::on_transact`](crate::Remotable::on_transact)).
98    ///
99    /// This can be used with higher-level system services to determine the
100    /// caller's identity and check permissions. However, when doing this, one
101    /// should be aware of possible TOCTOU problems when the calling process
102    /// dies and is replaced with another process with elevated permissions and
103    /// the same PID.
104    ///
105    /// Warning: oneway transactions do not receive PID. Even if you expect
106    /// a transaction to be synchronous, a misbehaving client could send it
107    /// as a synchronous call and result in a 0 PID here. Additionally, if
108    /// there is a race and the calling process dies, the PID may still be
109    /// 0 for a synchronous call.
110    ///
111    /// Available since API level 29.
112    ///
113    /// \return calling pid or the current process's PID if this thread isn't
114    /// processing a transaction.
115    pub fn get_calling_pid() -> pid_t {
116        // Safety: Safe FFI
117        unsafe { sys::AIBinder_getCallingPid() }
118    }
119
120    /// Determine whether the current thread is currently executing an incoming transaction.
121    ///
122    /// \return true if the current thread is currently executing an incoming transaction, and false
123    /// otherwise.
124    pub fn is_handling_transaction() -> bool {
125        // Safety: Safe FFI
126        unsafe { sys::AIBinder_isHandlingTransaction() }
127    }
128
129    /// This function makes the client's security context available to the
130    /// service calling this function. This can be used for access control.
131    /// It does not suffer from the TOCTOU issues of get_calling_pid.
132    ///
133    /// Implementations of `check_permission` should use the given CStr
134    /// argument as context for selinux permission checks. If `None` is
135    /// given, the implementation should fall back to using the PID
136    /// instead.
137    ///
138    /// Note: `None` may be passed to the callback if the caller did not
139    /// `set_requesting_sid` on the serviced binder, or if the underlying
140    /// kernel is too old to support this feature.
141    pub fn with_calling_sid<T, F>(check_permission: F) -> T
142    where
143        for<'a> F: FnOnce(Option<&'a std::ffi::CStr>) -> T,
144    {
145        // Safety: AIBinder_getCallingSid returns a c-string pointer
146        // that is valid for a transaction. Also, the string returned
147        // is thread local. By restricting the lifetime of the CStr
148        // reference to the scope of the callback, we prevent it being
149        // used beyond the guaranteed lifetime.
150        check_permission(unsafe {
151            let sid = sys::AIBinder_getCallingSid();
152            // AIBinder_getCallingSid() returns a '\0' terminated string
153            // or NULL.
154            if sid.is_null() {
155                None
156            } else {
157                Some(std::ffi::CStr::from_ptr(sid))
158            }
159        })
160    }
161}