[refactor] More post-NSS WebCrypto cleanups (utility functions).
[chromium-blink-merge.git] / content / browser / mach_broker_mac.mm
blobd42bbeedbf4b02b9561cf1a43838996462fc8442
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"
26 namespace content {
28 namespace {
30 // Mach message structure used in the child as a sending message.
31 struct MachBroker_ChildSendMsg {
32   mach_msg_header_t header;
33   mach_msg_body_t body;
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;
43 }  // namespace
45 bool MachBroker::ChildSendTaskPortToParent() {
46   // Look up the named MachBroker port that's been registered with the
47   // bootstrap server.
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";
53     return false;
54   }
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";
74     return false;
75   }
77   return true;
80 MachBroker* MachBroker::GetInstance() {
81   return base::Singleton<MachBroker,
82                          base::LeakySingletonTraits<MachBroker>>::get();
85 base::Lock& MachBroker::GetLock() {
86   return lock_;
89 void MachBroker::EnsureRunning() {
90   lock_.AssertAcquired();
92   if (initialized_)
93     return;
95   // Do not attempt to reinitialize in the event of failure.
96   initialized_ = true;
98   BrowserThread::PostTask(
99       BrowserThread::UI, FROM_HERE,
100       base::Bind(&MachBroker::RegisterNotifications, base::Unretained(this)));
102   if (!Init()) {
103     LOG(ERROR) << "Failed to initialize the MachListenerThreadDelegate";
104   }
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;
121   return it->second;
124 void MachBroker::BrowserChildProcessHostDisconnected(
125     const ChildProcessData& data) {
126   InvalidateChildProcessId(data.id);
129 void MachBroker::BrowserChildProcessCrashed(const ChildProcessData& data,
130     int exit_code) {
131   InvalidateChildProcessId(data.id);
134 void MachBroker::Observe(int type,
135                          const NotificationSource& source,
136                          const NotificationDetails& details) {
137   switch (type) {
138     case NOTIFICATION_RENDERER_PROCESS_TERMINATED:
139     case NOTIFICATION_RENDERER_PROCESS_CLOSED: {
140       RenderProcessHost* host = Source<RenderProcessHost>(source).ptr();
141       InvalidateChildProcessId(host->GetID());
142       break;
143     }
144     default:
145       NOTREACHED() << "Unexpected notification";
146       break;
147   }
150 // static
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.
170   mach_port_t port;
171   kern_return_t kr =
172       bootstrap_check_in(bootstrap_port, GetMachPortName().c_str(), &port);
173   if (kr != KERN_SUCCESS) {
174     BOOTSTRAP_LOG(ERROR, kr) << "bootstrap_check_in";
175     return false;
176   }
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();
186   return true;
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,
200                               options,
201                               0,
202                               sizeof(msg),
203                               server_port_,
204                               MACH_MSG_TIMEOUT_NONE,
205                               MACH_PORT_NULL);
206   if (kr != KERN_SUCCESS) {
207     MACH_LOG(ERROR, kr) << "mach_msg";
208     return;
209   }
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.
214   //
215   // TODO(rsesek): In the 10.7 SDK, there's audit_token_to_pid().
216   pid_t child_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!";
235     return;
236   }
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())
248     return;
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(),
253                                             mach_it->second);
254     MACH_LOG_IF(WARNING, kr != KERN_SUCCESS, kr) << "mach_port_deallocate";
255     mach_map_.erase(mach_it);
256   }
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