1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/mach_broker_mac.h"
7 #include <bsm/libbsm.h>
8 #include <servers/bootstrap.h>
10 #include "base/bind.h"
11 #include "base/bind_helpers.h"
12 #include "base/command_line.h"
13 #include "base/logging.h"
14 #include "base/mac/foundation_util.h"
15 #include "base/mac/mach_logging.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/stringprintf.h"
18 #include "base/strings/sys_string_conversions.h"
19 #include "content/browser/renderer_host/render_process_host_impl.h"
20 #include "content/public/browser/browser_thread.h"
21 #include "content/public/browser/child_process_data.h"
22 #include "content/public/browser/notification_service.h"
23 #include "content/public/browser/notification_types.h"
24 #include "content/public/common/content_switches.h"
30 // Mach message structure used in the child as a sending message.
31 struct MachBroker_ChildSendMsg {
32 mach_msg_header_t header;
34 mach_msg_port_descriptor_t child_task_port;
37 // Complement to the ChildSendMsg, this is used in the parent for receiving
38 // a message. Contains a message trailer with audit information.
39 struct MachBroker_ParentRecvMsg : public MachBroker_ChildSendMsg {
40 mach_msg_audit_trailer_t trailer;
45 bool MachBroker::ChildSendTaskPortToParent() {
46 // Look up the named MachBroker port that's been registered with the
48 mach_port_t parent_port;
49 kern_return_t kr = bootstrap_look_up(bootstrap_port,
50 const_cast<char*>(GetMachPortName().c_str()), &parent_port);
51 if (kr != KERN_SUCCESS) {
52 BOOTSTRAP_LOG(ERROR, kr) << "bootstrap_look_up";
55 base::mac::ScopedMachSendRight scoped_right(parent_port);
57 // Create the check in message. This will copy a send right on this process'
58 // (the child's) task port and send it to the parent.
59 MachBroker_ChildSendMsg msg;
60 bzero(&msg, sizeof(msg));
61 msg.header.msgh_bits = MACH_MSGH_BITS_REMOTE(MACH_MSG_TYPE_COPY_SEND) |
62 MACH_MSGH_BITS_COMPLEX;
63 msg.header.msgh_remote_port = parent_port;
64 msg.header.msgh_size = sizeof(msg);
65 msg.body.msgh_descriptor_count = 1;
66 msg.child_task_port.name = mach_task_self();
67 msg.child_task_port.disposition = MACH_MSG_TYPE_PORT_SEND;
68 msg.child_task_port.type = MACH_MSG_PORT_DESCRIPTOR;
70 kr = mach_msg(&msg.header, MACH_SEND_MSG | MACH_SEND_TIMEOUT, sizeof(msg),
71 0, MACH_PORT_NULL, 100 /*milliseconds*/, MACH_PORT_NULL);
72 if (kr != KERN_SUCCESS) {
73 MACH_LOG(ERROR, kr) << "mach_msg";
80 MachBroker* MachBroker::GetInstance() {
81 return base::Singleton<MachBroker,
82 base::LeakySingletonTraits<MachBroker>>::get();
85 base::Lock& MachBroker::GetLock() {
89 void MachBroker::EnsureRunning() {
90 lock_.AssertAcquired();
95 // Do not attempt to reinitialize in the event of failure.
98 BrowserThread::PostTask(
99 BrowserThread::UI, FROM_HERE,
100 base::Bind(&MachBroker::RegisterNotifications, base::Unretained(this)));
103 LOG(ERROR) << "Failed to initialize the MachListenerThreadDelegate";
107 void MachBroker::AddPlaceholderForPid(base::ProcessHandle pid,
108 int child_process_id) {
109 lock_.AssertAcquired();
111 DCHECK_EQ(0u, mach_map_.count(pid));
112 mach_map_[pid] = MACH_PORT_NULL;
113 child_process_id_map_[child_process_id] = pid;
116 mach_port_t MachBroker::TaskForPid(base::ProcessHandle pid) const {
117 base::AutoLock lock(lock_);
118 MachBroker::MachMap::const_iterator it = mach_map_.find(pid);
119 if (it == mach_map_.end())
120 return MACH_PORT_NULL;
124 void MachBroker::BrowserChildProcessHostDisconnected(
125 const ChildProcessData& data) {
126 InvalidateChildProcessId(data.id);
129 void MachBroker::BrowserChildProcessCrashed(const ChildProcessData& data,
131 InvalidateChildProcessId(data.id);
134 void MachBroker::Observe(int type,
135 const NotificationSource& source,
136 const NotificationDetails& details) {
138 case NOTIFICATION_RENDERER_PROCESS_TERMINATED:
139 case NOTIFICATION_RENDERER_PROCESS_CLOSED: {
140 RenderProcessHost* host = Source<RenderProcessHost>(source).ptr();
141 InvalidateChildProcessId(host->GetID());
145 NOTREACHED() << "Unexpected notification";
151 std::string MachBroker::GetMachPortName() {
152 const base::CommandLine* command_line =
153 base::CommandLine::ForCurrentProcess();
154 const bool is_child = command_line->HasSwitch(switches::kProcessType);
156 // In non-browser (child) processes, use the parent's pid.
157 const pid_t pid = is_child ? getppid() : getpid();
158 return base::StringPrintf("%s.rohitfork.%d", base::mac::BaseBundleID(), pid);
161 MachBroker::MachBroker() : initialized_(false) {
164 MachBroker::~MachBroker() {}
166 bool MachBroker::Init() {
167 DCHECK(server_port_.get() == MACH_PORT_NULL);
169 // Check in with launchd and publish the service name.
172 bootstrap_check_in(bootstrap_port, GetMachPortName().c_str(), &port);
173 if (kr != KERN_SUCCESS) {
174 BOOTSTRAP_LOG(ERROR, kr) << "bootstrap_check_in";
177 server_port_.reset(port);
179 // Start the dispatch source.
180 std::string queue_name =
181 base::StringPrintf("%s.MachBroker", base::mac::BaseBundleID());
182 dispatch_source_.reset(new base::DispatchSourceMach(
183 queue_name.c_str(), server_port_.get(), ^{ HandleRequest(); }));
184 dispatch_source_->Resume();
189 void MachBroker::HandleRequest() {
190 MachBroker_ParentRecvMsg msg;
191 bzero(&msg, sizeof(msg));
192 msg.header.msgh_size = sizeof(msg);
193 msg.header.msgh_local_port = server_port_.get();
195 const mach_msg_option_t options = MACH_RCV_MSG |
196 MACH_RCV_TRAILER_TYPE(MACH_RCV_TRAILER_AUDIT) |
197 MACH_RCV_TRAILER_ELEMENTS(MACH_RCV_TRAILER_AUDIT);
199 kern_return_t kr = mach_msg(&msg.header,
204 MACH_MSG_TIMEOUT_NONE,
206 if (kr != KERN_SUCCESS) {
207 MACH_LOG(ERROR, kr) << "mach_msg";
211 // Use the kernel audit information to make sure this message is from
212 // a task that this process spawned. The kernel audit token contains the
213 // unspoofable pid of the task that sent the message.
215 // TODO(rsesek): In the 10.7 SDK, there's audit_token_to_pid().
217 audit_token_to_au32(msg.trailer.msgh_audit,
218 NULL, NULL, NULL, NULL, NULL, &child_pid, NULL, NULL);
220 mach_port_t child_task_port = msg.child_task_port.name;
222 // Take the lock and update the broker information.
223 base::AutoLock lock(GetLock());
224 FinalizePid(child_pid, child_task_port);
227 void MachBroker::FinalizePid(base::ProcessHandle pid,
228 mach_port_t task_port) {
229 lock_.AssertAcquired();
231 MachMap::iterator it = mach_map_.find(pid);
232 if (it == mach_map_.end()) {
233 // Do nothing for unknown pids.
234 LOG(ERROR) << "Unknown process " << pid << " is sending Mach IPC messages!";
238 DCHECK(it->second == MACH_PORT_NULL);
239 if (it->second == MACH_PORT_NULL)
240 it->second = task_port;
243 void MachBroker::InvalidateChildProcessId(int child_process_id) {
244 base::AutoLock lock(lock_);
245 MachBroker::ChildProcessIdMap::iterator it =
246 child_process_id_map_.find(child_process_id);
247 if (it == child_process_id_map_.end())
250 MachMap::iterator mach_it = mach_map_.find(it->second);
251 if (mach_it != mach_map_.end()) {
252 kern_return_t kr = mach_port_deallocate(mach_task_self(),
254 MACH_LOG_IF(WARNING, kr != KERN_SUCCESS, kr) << "mach_port_deallocate";
255 mach_map_.erase(mach_it);
257 child_process_id_map_.erase(it);
260 void MachBroker::RegisterNotifications() {
261 registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_CLOSED,
262 NotificationService::AllBrowserContextsAndSources());
263 registrar_.Add(this, NOTIFICATION_RENDERER_PROCESS_TERMINATED,
264 NotificationService::AllBrowserContextsAndSources());
266 // No corresponding StopObservingBrowserChildProcesses,
267 // we leak this singleton.
268 BrowserChildProcessObserver::Add(this);
271 } // namespace content