Roll src/third_party/WebKit f298044:aa8346d (svn 202628:202629)
[chromium-blink-merge.git] / ipc / ipc_channel_posix.cc
blobb3aee8e06bb06de8be578098541037406be4937b
1 // Copyright (c) 2012 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 "ipc/ipc_channel_posix.h"
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <stddef.h>
10 #include <stdint.h>
11 #include <sys/socket.h>
12 #include <sys/stat.h>
13 #include <sys/types.h>
14 #include <unistd.h>
16 #if defined(OS_OPENBSD)
17 #include <sys/uio.h>
18 #endif
20 #if !defined(OS_NACL_NONSFI)
21 #include <sys/un.h>
22 #endif
24 #include <map>
25 #include <string>
27 #include "base/command_line.h"
28 #include "base/files/file_path.h"
29 #include "base/files/file_util.h"
30 #include "base/location.h"
31 #include "base/logging.h"
32 #include "base/memory/scoped_ptr.h"
33 #include "base/memory/singleton.h"
34 #include "base/posix/eintr_wrapper.h"
35 #include "base/posix/global_descriptors.h"
36 #include "base/process/process_handle.h"
37 #include "base/rand_util.h"
38 #include "base/stl_util.h"
39 #include "base/strings/string_util.h"
40 #include "base/synchronization/lock.h"
41 #include "ipc/attachment_broker.h"
42 #include "ipc/ipc_descriptors.h"
43 #include "ipc/ipc_listener.h"
44 #include "ipc/ipc_logging.h"
45 #include "ipc/ipc_message_attachment_set.h"
46 #include "ipc/ipc_message_utils.h"
47 #include "ipc/ipc_platform_file_attachment_posix.h"
48 #include "ipc/ipc_switches.h"
49 #include "ipc/unix_domain_socket_util.h"
51 namespace IPC {
53 // IPC channels on Windows use named pipes (CreateNamedPipe()) with
54 // channel ids as the pipe names. Channels on POSIX use sockets as
55 // pipes These don't quite line up.
57 // When creating a child subprocess we use a socket pair and the parent side of
58 // the fork arranges it such that the initial control channel ends up on the
59 // magic file descriptor kPrimaryIPCChannel in the child. Future
60 // connections (file descriptors) can then be passed via that
61 // connection via sendmsg().
63 // A POSIX IPC channel can also be set up as a server for a bound UNIX domain
64 // socket, and will handle multiple connect and disconnect sequences. Currently
65 // it is limited to one connection at a time.
67 //------------------------------------------------------------------------------
68 namespace {
70 // The PipeMap class works around this quirk related to unit tests:
72 // When running as a server, we install the client socket in a
73 // specific file descriptor number (@kPrimaryIPCChannel). However, we
74 // also have to support the case where we are running unittests in the
75 // same process. (We do not support forking without execing.)
77 // Case 1: normal running
78 // The IPC server object will install a mapping in PipeMap from the
79 // name which it was given to the client pipe. When forking the client, the
80 // GetClientFileDescriptorMapping will ensure that the socket is installed in
81 // the magic slot (@kPrimaryIPCChannel). The client will search for the
82 // mapping, but it won't find any since we are in a new process. Thus the
83 // magic fd number is returned. Once the client connects, the server will
84 // close its copy of the client socket and remove the mapping.
86 // Case 2: unittests - client and server in the same process
87 // The IPC server will install a mapping as before. The client will search
88 // for a mapping and find out. It duplicates the file descriptor and
89 // connects. Once the client connects, the server will close the original
90 // copy of the client socket and remove the mapping. Thus, when the client
91 // object closes, it will close the only remaining copy of the client socket
92 // in the fd table and the server will see EOF on its side.
94 // TODO(port): a client process cannot connect to multiple IPC channels with
95 // this scheme.
97 class PipeMap {
98 public:
99 static PipeMap* GetInstance() { return base::Singleton<PipeMap>::get(); }
101 ~PipeMap() {
102 // Shouldn't have left over pipes.
103 DCHECK(map_.empty());
106 // Lookup a given channel id. Return -1 if not found.
107 int Lookup(const std::string& channel_id) {
108 base::AutoLock locked(lock_);
110 ChannelToFDMap::const_iterator i = map_.find(channel_id);
111 if (i == map_.end())
112 return -1;
113 return i->second;
116 // Remove the mapping for the given channel id. No error is signaled if the
117 // channel_id doesn't exist
118 void Remove(const std::string& channel_id) {
119 base::AutoLock locked(lock_);
120 map_.erase(channel_id);
123 // Insert a mapping from @channel_id to @fd. It's a fatal error to insert a
124 // mapping if one already exists for the given channel_id
125 void Insert(const std::string& channel_id, int fd) {
126 base::AutoLock locked(lock_);
127 DCHECK_NE(-1, fd);
129 ChannelToFDMap::const_iterator i = map_.find(channel_id);
130 CHECK(i == map_.end()) << "Creating second IPC server (fd " << fd << ") "
131 << "for '" << channel_id << "' while first "
132 << "(fd " << i->second << ") still exists";
133 map_[channel_id] = fd;
136 private:
137 base::Lock lock_;
138 typedef std::map<std::string, int> ChannelToFDMap;
139 ChannelToFDMap map_;
141 friend struct base::DefaultSingletonTraits<PipeMap>;
142 #if defined(OS_ANDROID)
143 friend void ::IPC::Channel::NotifyProcessForkedForTesting();
144 #endif
147 //------------------------------------------------------------------------------
149 bool SocketWriteErrorIsRecoverable() {
150 #if defined(OS_MACOSX)
151 // On OS X if sendmsg() is trying to send fds between processes and there
152 // isn't enough room in the output buffer to send the fd structure over
153 // atomically then EMSGSIZE is returned.
155 // EMSGSIZE presents a problem since the system APIs can only call us when
156 // there's room in the socket buffer and not when there is "enough" room.
158 // The current behavior is to return to the event loop when EMSGSIZE is
159 // received and hopefull service another FD. This is however still
160 // technically a busy wait since the event loop will call us right back until
161 // the receiver has read enough data to allow passing the FD over atomically.
162 return errno == EAGAIN || errno == EMSGSIZE;
163 #else
164 return errno == EAGAIN;
165 #endif // OS_MACOSX
168 } // namespace
170 #if defined(OS_ANDROID)
171 // When we fork for simple tests on Android, we can't 'exec', so we need to
172 // reset these entries manually to get the expected testing behavior.
173 void Channel::NotifyProcessForkedForTesting() {
174 PipeMap::GetInstance()->map_.clear();
176 #endif
178 //------------------------------------------------------------------------------
180 #if defined(OS_LINUX)
181 int ChannelPosix::global_pid_ = 0;
182 #endif // OS_LINUX
184 ChannelPosix::ChannelPosix(const IPC::ChannelHandle& channel_handle,
185 Mode mode,
186 Listener* listener)
187 : ChannelReader(listener),
188 mode_(mode),
189 peer_pid_(base::kNullProcessId),
190 is_blocked_on_write_(false),
191 waiting_connect_(true),
192 message_send_bytes_written_(0),
193 pipe_name_(channel_handle.name),
194 in_dtor_(false),
195 must_unlink_(false) {
196 if (!CreatePipe(channel_handle)) {
197 // The pipe may have been closed already.
198 const char *modestr = (mode_ & MODE_SERVER_FLAG) ? "server" : "client";
199 LOG(WARNING) << "Unable to create pipe named \"" << channel_handle.name
200 << "\" in " << modestr << " mode";
204 ChannelPosix::~ChannelPosix() {
205 in_dtor_ = true;
206 CleanUp();
207 Close();
210 bool SocketPair(int* fd1, int* fd2) {
211 int pipe_fds[2];
212 if (socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds) != 0) {
213 PLOG(ERROR) << "socketpair()";
214 return false;
217 // Set both ends to be non-blocking.
218 if (fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK) == -1 ||
219 fcntl(pipe_fds[1], F_SETFL, O_NONBLOCK) == -1) {
220 PLOG(ERROR) << "fcntl(O_NONBLOCK)";
221 if (IGNORE_EINTR(close(pipe_fds[0])) < 0)
222 PLOG(ERROR) << "close";
223 if (IGNORE_EINTR(close(pipe_fds[1])) < 0)
224 PLOG(ERROR) << "close";
225 return false;
228 *fd1 = pipe_fds[0];
229 *fd2 = pipe_fds[1];
231 return true;
234 bool ChannelPosix::CreatePipe(
235 const IPC::ChannelHandle& channel_handle) {
236 DCHECK(!server_listen_pipe_.is_valid() && !pipe_.is_valid());
238 // Four possible cases:
239 // 1) It's a channel wrapping a pipe that is given to us.
240 // 2) It's for a named channel, so we create it.
241 // 3) It's for a client that we implement ourself. This is used
242 // in single-process unittesting.
243 // 4) It's the initial IPC channel:
244 // 4a) Client side: Pull the pipe out of the GlobalDescriptors set.
245 // 4b) Server side: create the pipe.
247 base::ScopedFD local_pipe;
248 if (channel_handle.socket.fd != -1) {
249 // Case 1 from comment above.
250 local_pipe.reset(channel_handle.socket.fd);
251 } else if (mode_ & MODE_NAMED_FLAG) {
252 #if defined(OS_NACL_NONSFI)
253 LOG(FATAL)
254 << "IPC channels in nacl_helper_nonsfi should not be in NAMED mode.";
255 #else
256 // Case 2 from comment above.
257 int local_pipe_fd = -1;
259 if (mode_ & MODE_SERVER_FLAG) {
260 if (!CreateServerUnixDomainSocket(base::FilePath(pipe_name_),
261 &local_pipe_fd)) {
262 return false;
265 must_unlink_ = true;
266 } else if (mode_ & MODE_CLIENT_FLAG) {
267 if (!CreateClientUnixDomainSocket(base::FilePath(pipe_name_),
268 &local_pipe_fd)) {
269 return false;
271 } else {
272 LOG(ERROR) << "Bad mode: " << mode_;
273 return false;
276 local_pipe.reset(local_pipe_fd);
277 #endif // !defined(OS_NACL_NONSFI)
278 } else {
279 local_pipe.reset(PipeMap::GetInstance()->Lookup(pipe_name_));
280 if (mode_ & MODE_CLIENT_FLAG) {
281 if (local_pipe.is_valid()) {
282 // Case 3 from comment above.
283 // We only allow one connection.
284 local_pipe.reset(HANDLE_EINTR(dup(local_pipe.release())));
285 PipeMap::GetInstance()->Remove(pipe_name_);
286 } else {
287 // Case 4a from comment above.
288 // Guard against inappropriate reuse of the initial IPC channel. If
289 // an IPC channel closes and someone attempts to reuse it by name, the
290 // initial channel must not be recycled here. http://crbug.com/26754.
291 static bool used_initial_channel = false;
292 if (used_initial_channel) {
293 LOG(FATAL) << "Denying attempt to reuse initial IPC channel for "
294 << pipe_name_;
295 return false;
297 used_initial_channel = true;
299 local_pipe.reset(
300 base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel));
302 } else if (mode_ & MODE_SERVER_FLAG) {
303 // Case 4b from comment above.
304 if (local_pipe.is_valid()) {
305 LOG(ERROR) << "Server already exists for " << pipe_name_;
306 // This is a client side pipe registered by other server and
307 // shouldn't be closed.
308 ignore_result(local_pipe.release());
309 return false;
311 base::AutoLock lock(client_pipe_lock_);
312 int local_pipe_fd = -1, client_pipe_fd = -1;
313 if (!SocketPair(&local_pipe_fd, &client_pipe_fd))
314 return false;
315 local_pipe.reset(local_pipe_fd);
316 client_pipe_.reset(client_pipe_fd);
317 PipeMap::GetInstance()->Insert(pipe_name_, client_pipe_fd);
318 } else {
319 LOG(ERROR) << "Bad mode: " << mode_;
320 return false;
324 if ((mode_ & MODE_SERVER_FLAG) && (mode_ & MODE_NAMED_FLAG)) {
325 #if defined(OS_NACL_NONSFI)
326 LOG(FATAL) << "IPC channels in nacl_helper_nonsfi "
327 << "should not be in NAMED or SERVER mode.";
328 #else
329 server_listen_pipe_.reset(local_pipe.release());
330 #endif
331 } else {
332 pipe_.reset(local_pipe.release());
334 return true;
337 bool ChannelPosix::Connect() {
338 if (!server_listen_pipe_.is_valid() && !pipe_.is_valid()) {
339 DLOG(WARNING) << "Channel creation failed: " << pipe_name_;
340 return false;
343 bool did_connect = true;
344 if (server_listen_pipe_.is_valid()) {
345 #if defined(OS_NACL_NONSFI)
346 LOG(FATAL) << "IPC channels in nacl_helper_nonsfi "
347 << "should always be in client mode.";
348 #else
349 // Watch the pipe for connections, and turn any connections into
350 // active sockets.
351 base::MessageLoopForIO::current()->WatchFileDescriptor(
352 server_listen_pipe_.get(),
353 true,
354 base::MessageLoopForIO::WATCH_READ,
355 &server_listen_connection_watcher_,
356 this);
357 #endif
358 } else {
359 did_connect = AcceptConnection();
361 return did_connect;
364 void ChannelPosix::CloseFileDescriptors(Message* msg) {
365 #if defined(OS_MACOSX)
366 // There is a bug on OSX which makes it dangerous to close
367 // a file descriptor while it is in transit. So instead we
368 // store the file descriptor in a set and send a message to
369 // the recipient, which is queued AFTER the message that
370 // sent the FD. The recipient will reply to the message,
371 // letting us know that it is now safe to close the file
372 // descriptor. For more information, see:
373 // http://crbug.com/298276
374 std::vector<int> to_close;
375 msg->attachment_set()->ReleaseFDsToClose(&to_close);
376 for (size_t i = 0; i < to_close.size(); i++) {
377 fds_to_close_.insert(to_close[i]);
378 QueueCloseFDMessage(to_close[i], 2);
380 #else
381 msg->attachment_set()->CommitAll();
382 #endif
385 bool ChannelPosix::ProcessOutgoingMessages() {
386 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
387 // no connection?
388 if (output_queue_.empty())
389 return true;
391 if (!pipe_.is_valid())
392 return false;
394 // Write out all the messages we can till the write blocks or there are no
395 // more outgoing messages.
396 while (!output_queue_.empty()) {
397 Message* msg = output_queue_.front();
399 size_t amt_to_write = msg->size() - message_send_bytes_written_;
400 DCHECK_NE(0U, amt_to_write);
401 const char* out_bytes = reinterpret_cast<const char*>(msg->data()) +
402 message_send_bytes_written_;
404 struct msghdr msgh = {0};
405 struct iovec iov = {const_cast<char*>(out_bytes), amt_to_write};
406 msgh.msg_iov = &iov;
407 msgh.msg_iovlen = 1;
408 char buf[CMSG_SPACE(sizeof(int) *
409 MessageAttachmentSet::kMaxDescriptorsPerMessage)];
411 ssize_t bytes_written = 1;
412 int fd_written = -1;
414 if (message_send_bytes_written_ == 0 && !msg->attachment_set()->empty()) {
415 // This is the first chunk of a message which has descriptors to send
416 struct cmsghdr *cmsg;
417 const unsigned num_fds = msg->attachment_set()->size();
419 DCHECK(num_fds <= MessageAttachmentSet::kMaxDescriptorsPerMessage);
420 if (msg->attachment_set()->ContainsDirectoryDescriptor()) {
421 LOG(FATAL) << "Panic: attempting to transport directory descriptor over"
422 " IPC. Aborting to maintain sandbox isolation.";
423 // If you have hit this then something tried to send a file descriptor
424 // to a directory over an IPC channel. Since IPC channels span
425 // sandboxes this is very bad: the receiving process can use openat
426 // with ".." elements in the path in order to reach the real
427 // filesystem.
430 msgh.msg_control = buf;
431 msgh.msg_controllen = CMSG_SPACE(sizeof(int) * num_fds);
432 cmsg = CMSG_FIRSTHDR(&msgh);
433 cmsg->cmsg_level = SOL_SOCKET;
434 cmsg->cmsg_type = SCM_RIGHTS;
435 cmsg->cmsg_len = CMSG_LEN(sizeof(int) * num_fds);
436 msg->attachment_set()->PeekDescriptors(
437 reinterpret_cast<int*>(CMSG_DATA(cmsg)));
438 msgh.msg_controllen = cmsg->cmsg_len;
440 // DCHECK_LE above already checks that
441 // num_fds < kMaxDescriptorsPerMessage so no danger of overflow.
442 msg->header()->num_fds = static_cast<uint16_t>(num_fds);
445 if (bytes_written == 1) {
446 fd_written = pipe_.get();
447 bytes_written = HANDLE_EINTR(sendmsg(pipe_.get(), &msgh, MSG_DONTWAIT));
449 if (bytes_written > 0)
450 CloseFileDescriptors(msg);
452 if (bytes_written < 0 && !SocketWriteErrorIsRecoverable()) {
453 // We can't close the pipe here, because calling OnChannelError
454 // may destroy this object, and that would be bad if we are
455 // called from Send(). Instead, we return false and hope the
456 // caller will close the pipe. If they do not, the pipe will
457 // still be closed next time OnFileCanReadWithoutBlocking is
458 // called.
459 #if defined(OS_MACOSX)
460 // On OSX writing to a pipe with no listener returns EPERM.
461 if (errno == EPERM) {
462 return false;
464 #endif // OS_MACOSX
465 if (errno == EPIPE) {
466 return false;
468 PLOG(ERROR) << "pipe error on "
469 << fd_written
470 << " Currently writing message of size: "
471 << msg->size();
472 return false;
475 if (static_cast<size_t>(bytes_written) != amt_to_write) {
476 if (bytes_written > 0) {
477 // If write() fails with EAGAIN then bytes_written will be -1.
478 message_send_bytes_written_ += bytes_written;
481 // Tell libevent to call us back once things are unblocked.
482 is_blocked_on_write_ = true;
483 base::MessageLoopForIO::current()->WatchFileDescriptor(
484 pipe_.get(),
485 false, // One shot
486 base::MessageLoopForIO::WATCH_WRITE,
487 &write_watcher_,
488 this);
489 return true;
490 } else {
491 message_send_bytes_written_ = 0;
493 // Message sent OK!
494 DVLOG(2) << "sent message @" << msg << " on channel @" << this
495 << " with type " << msg->type() << " on fd " << pipe_.get();
496 delete output_queue_.front();
497 output_queue_.pop();
500 return true;
503 bool ChannelPosix::Send(Message* message) {
504 DCHECK(!message->HasMojoHandles());
505 DVLOG(2) << "sending message @" << message << " on channel @" << this
506 << " with type " << message->type()
507 << " (" << output_queue_.size() << " in queue)";
509 #ifdef IPC_MESSAGE_LOG_ENABLED
510 Logging::GetInstance()->OnSendMessage(message, "");
511 #endif // IPC_MESSAGE_LOG_ENABLED
513 TRACE_EVENT_WITH_FLOW0(TRACE_DISABLED_BY_DEFAULT("ipc.flow"),
514 "ChannelPosix::Send",
515 message->flags(),
516 TRACE_EVENT_FLAG_FLOW_OUT);
517 output_queue_.push(message);
518 if (!is_blocked_on_write_ && !waiting_connect_) {
519 return ProcessOutgoingMessages();
522 return true;
525 AttachmentBroker* ChannelPosix::GetAttachmentBroker() {
526 return AttachmentBroker::GetGlobal();
529 int ChannelPosix::GetClientFileDescriptor() const {
530 base::AutoLock lock(client_pipe_lock_);
531 return client_pipe_.get();
534 base::ScopedFD ChannelPosix::TakeClientFileDescriptor() {
535 base::AutoLock lock(client_pipe_lock_);
536 if (!client_pipe_.is_valid())
537 return base::ScopedFD();
538 PipeMap::GetInstance()->Remove(pipe_name_);
539 return client_pipe_.Pass();
542 void ChannelPosix::CloseClientFileDescriptor() {
543 base::AutoLock lock(client_pipe_lock_);
544 if (!client_pipe_.is_valid())
545 return;
546 PipeMap::GetInstance()->Remove(pipe_name_);
547 client_pipe_.reset();
550 bool ChannelPosix::AcceptsConnections() const {
551 return server_listen_pipe_.is_valid();
554 bool ChannelPosix::HasAcceptedConnection() const {
555 return AcceptsConnections() && pipe_.is_valid();
558 #if !defined(OS_NACL_NONSFI)
559 // GetPeerEuid is not supported in nacl_helper_nonsfi.
560 bool ChannelPosix::GetPeerEuid(uid_t* peer_euid) const {
561 DCHECK(!(mode_ & MODE_SERVER) || HasAcceptedConnection());
562 return IPC::GetPeerEuid(pipe_.get(), peer_euid);
564 #endif
566 void ChannelPosix::ResetToAcceptingConnectionState() {
567 // Unregister libevent for the unix domain socket and close it.
568 read_watcher_.StopWatchingFileDescriptor();
569 write_watcher_.StopWatchingFileDescriptor();
570 ResetSafely(&pipe_);
572 while (!output_queue_.empty()) {
573 Message* m = output_queue_.front();
574 output_queue_.pop();
575 CloseFileDescriptors(m);
576 delete m;
579 // Close any outstanding, received file descriptors.
580 ClearInputFDs();
582 #if defined(OS_MACOSX)
583 // Clear any outstanding, sent file descriptors.
584 for (std::set<int>::iterator i = fds_to_close_.begin();
585 i != fds_to_close_.end();
586 ++i) {
587 if (IGNORE_EINTR(close(*i)) < 0)
588 PLOG(ERROR) << "close";
590 fds_to_close_.clear();
591 #endif
594 // static
595 bool ChannelPosix::IsNamedServerInitialized(
596 const std::string& channel_id) {
597 return base::PathExists(base::FilePath(channel_id));
600 #if defined(OS_LINUX)
601 // static
602 void ChannelPosix::SetGlobalPid(int pid) {
603 global_pid_ = pid;
605 #endif // OS_LINUX
607 // Called by libevent when we can read from the pipe without blocking.
608 void ChannelPosix::OnFileCanReadWithoutBlocking(int fd) {
609 if (fd == server_listen_pipe_.get()) {
610 #if defined(OS_NACL_NONSFI)
611 LOG(FATAL)
612 << "IPC channels in nacl_helper_nonsfi should not be SERVER mode.";
613 #else
614 int new_pipe = 0;
615 if (!ServerAcceptConnection(server_listen_pipe_.get(), &new_pipe) ||
616 new_pipe < 0) {
617 Close();
618 listener()->OnChannelListenError();
621 if (pipe_.is_valid()) {
622 // We already have a connection. We only handle one at a time.
623 // close our new descriptor.
624 if (HANDLE_EINTR(shutdown(new_pipe, SHUT_RDWR)) < 0)
625 DPLOG(ERROR) << "shutdown " << pipe_name_;
626 if (IGNORE_EINTR(close(new_pipe)) < 0)
627 DPLOG(ERROR) << "close " << pipe_name_;
628 listener()->OnChannelDenied();
629 return;
631 pipe_.reset(new_pipe);
633 if ((mode_ & MODE_OPEN_ACCESS_FLAG) == 0) {
634 // Verify that the IPC channel peer is running as the same user.
635 uid_t client_euid;
636 if (!GetPeerEuid(&client_euid)) {
637 DLOG(ERROR) << "Unable to query client euid";
638 ResetToAcceptingConnectionState();
639 return;
641 if (client_euid != geteuid()) {
642 DLOG(WARNING) << "Client euid is not authorised";
643 ResetToAcceptingConnectionState();
644 return;
648 if (!AcceptConnection()) {
649 NOTREACHED() << "AcceptConnection should not fail on server";
651 waiting_connect_ = false;
652 #endif
653 } else if (fd == pipe_) {
654 if (waiting_connect_ && (mode_ & MODE_SERVER_FLAG)) {
655 waiting_connect_ = false;
657 if (ProcessIncomingMessages() == DISPATCH_ERROR) {
658 // ClosePipeOnError may delete this object, so we mustn't call
659 // ProcessOutgoingMessages.
660 ClosePipeOnError();
661 return;
663 } else {
664 NOTREACHED() << "Unknown pipe " << fd;
667 // If we're a server and handshaking, then we want to make sure that we
668 // only send our handshake message after we've processed the client's.
669 // This gives us a chance to kill the client if the incoming handshake
670 // is invalid. This also flushes any closefd messages.
671 if (!is_blocked_on_write_) {
672 if (!ProcessOutgoingMessages()) {
673 ClosePipeOnError();
678 // Called by libevent when we can write to the pipe without blocking.
679 void ChannelPosix::OnFileCanWriteWithoutBlocking(int fd) {
680 DCHECK_EQ(pipe_.get(), fd);
681 is_blocked_on_write_ = false;
682 if (!ProcessOutgoingMessages()) {
683 ClosePipeOnError();
687 bool ChannelPosix::AcceptConnection() {
688 base::MessageLoopForIO::current()->WatchFileDescriptor(
689 pipe_.get(),
690 true,
691 base::MessageLoopForIO::WATCH_READ,
692 &read_watcher_,
693 this);
694 QueueHelloMessage();
696 if (mode_ & MODE_CLIENT_FLAG) {
697 // If we are a client we want to send a hello message out immediately.
698 // In server mode we will send a hello message when we receive one from a
699 // client.
700 waiting_connect_ = false;
701 return ProcessOutgoingMessages();
702 } else if (mode_ & MODE_SERVER_FLAG) {
703 waiting_connect_ = true;
704 return true;
705 } else {
706 NOTREACHED();
707 return false;
711 void ChannelPosix::ClosePipeOnError() {
712 if (HasAcceptedConnection()) {
713 ResetToAcceptingConnectionState();
714 listener()->OnChannelError();
715 } else {
716 Close();
717 if (AcceptsConnections()) {
718 listener()->OnChannelListenError();
719 } else {
720 listener()->OnChannelError();
725 int ChannelPosix::GetHelloMessageProcId() const {
726 #if defined(OS_NACL_NONSFI)
727 // In nacl_helper_nonsfi, getpid() invoked by GetCurrentProcId() is not
728 // allowed and would cause a SIGSYS crash because of the seccomp sandbox.
729 return -1;
730 #else
731 int pid = base::GetCurrentProcId();
732 #if defined(OS_LINUX)
733 // Our process may be in a sandbox with a separate PID namespace.
734 if (global_pid_) {
735 pid = global_pid_;
737 #endif // defined(OS_LINUX)
738 return pid;
739 #endif // defined(OS_NACL_NONSFI)
742 void ChannelPosix::QueueHelloMessage() {
743 // Create the Hello message
744 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
745 HELLO_MESSAGE_TYPE,
746 IPC::Message::PRIORITY_NORMAL));
747 if (!msg->WriteInt(GetHelloMessageProcId())) {
748 NOTREACHED() << "Unable to pickle hello message proc id";
750 output_queue_.push(msg.release());
753 ChannelPosix::ReadState ChannelPosix::ReadData(
754 char* buffer,
755 int buffer_len,
756 int* bytes_read) {
757 if (!pipe_.is_valid())
758 return READ_FAILED;
760 struct msghdr msg = {0};
762 struct iovec iov = {buffer, static_cast<size_t>(buffer_len)};
763 msg.msg_iov = &iov;
764 msg.msg_iovlen = 1;
766 char input_cmsg_buf[kMaxReadFDBuffer];
767 msg.msg_control = input_cmsg_buf;
769 // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
770 // is waiting on the pipe.
771 msg.msg_controllen = sizeof(input_cmsg_buf);
772 *bytes_read = HANDLE_EINTR(recvmsg(pipe_.get(), &msg, MSG_DONTWAIT));
774 if (*bytes_read < 0) {
775 if (errno == EAGAIN) {
776 return READ_PENDING;
777 #if defined(OS_MACOSX)
778 } else if (errno == EPERM) {
779 // On OSX, reading from a pipe with no listener returns EPERM
780 // treat this as a special case to prevent spurious error messages
781 // to the console.
782 return READ_FAILED;
783 #endif // OS_MACOSX
784 } else if (errno == ECONNRESET || errno == EPIPE) {
785 return READ_FAILED;
786 } else {
787 PLOG(ERROR) << "pipe error (" << pipe_.get() << ")";
788 return READ_FAILED;
790 } else if (*bytes_read == 0) {
791 // The pipe has closed...
792 return READ_FAILED;
794 DCHECK(*bytes_read);
796 CloseClientFileDescriptor();
798 // Read any file descriptors from the message.
799 if (!ExtractFileDescriptorsFromMsghdr(&msg))
800 return READ_FAILED;
801 return READ_SUCCEEDED;
804 bool ChannelPosix::ShouldDispatchInputMessage(Message* msg) {
805 return true;
808 // On Posix, we need to fix up the file descriptors before the input message
809 // is dispatched.
811 // This will read from the input_fds_ (READWRITE mode only) and read more
812 // handles from the FD pipe if necessary.
813 bool ChannelPosix::GetNonBrokeredAttachments(Message* msg) {
814 uint16_t header_fds = msg->header()->num_fds;
815 if (!header_fds)
816 return true; // Nothing to do.
818 // The message has file descriptors.
819 const char* error = NULL;
820 if (header_fds > input_fds_.size()) {
821 // The message has been completely received, but we didn't get
822 // enough file descriptors.
823 error = "Message needs unreceived descriptors";
826 if (header_fds > MessageAttachmentSet::kMaxDescriptorsPerMessage)
827 error = "Message requires an excessive number of descriptors";
829 if (error) {
830 LOG(WARNING) << error
831 << " channel:" << this
832 << " message-type:" << msg->type()
833 << " header()->num_fds:" << header_fds;
834 // Abort the connection.
835 ClearInputFDs();
836 return false;
839 // The shenaniganery below with &foo.front() requires input_fds_ to have
840 // contiguous underlying storage (such as a simple array or a std::vector).
841 // This is why the header warns not to make input_fds_ a deque<>.
842 msg->attachment_set()->AddDescriptorsToOwn(&input_fds_.front(), header_fds);
843 input_fds_.erase(input_fds_.begin(), input_fds_.begin() + header_fds);
844 return true;
847 bool ChannelPosix::DidEmptyInputBuffers() {
848 // When the input data buffer is empty, the fds should be too. If this is
849 // not the case, we probably have a rogue renderer which is trying to fill
850 // our descriptor table.
851 return input_fds_.empty();
854 bool ChannelPosix::ExtractFileDescriptorsFromMsghdr(msghdr* msg) {
855 // Check that there are any control messages. On OSX, CMSG_FIRSTHDR will
856 // return an invalid non-NULL pointer in the case that controllen == 0.
857 if (msg->msg_controllen == 0)
858 return true;
860 for (cmsghdr* cmsg = CMSG_FIRSTHDR(msg);
861 cmsg;
862 cmsg = CMSG_NXTHDR(msg, cmsg)) {
863 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
864 unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
865 DCHECK_EQ(0U, payload_len % sizeof(int));
866 const int* file_descriptors = reinterpret_cast<int*>(CMSG_DATA(cmsg));
867 unsigned num_file_descriptors = payload_len / 4;
868 input_fds_.insert(input_fds_.end(),
869 file_descriptors,
870 file_descriptors + num_file_descriptors);
872 // Check this after adding the FDs so we don't leak them.
873 if (msg->msg_flags & MSG_CTRUNC) {
874 ClearInputFDs();
875 return false;
878 return true;
882 // No file descriptors found, but that's OK.
883 return true;
886 void ChannelPosix::ClearInputFDs() {
887 for (size_t i = 0; i < input_fds_.size(); ++i) {
888 if (IGNORE_EINTR(close(input_fds_[i])) < 0)
889 PLOG(ERROR) << "close ";
891 input_fds_.clear();
894 void ChannelPosix::QueueCloseFDMessage(int fd, int hops) {
895 switch (hops) {
896 case 1:
897 case 2: {
898 // Create the message
899 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
900 CLOSE_FD_MESSAGE_TYPE,
901 IPC::Message::PRIORITY_NORMAL));
902 if (!msg->WriteInt(hops - 1) || !msg->WriteInt(fd)) {
903 NOTREACHED() << "Unable to pickle close fd.";
905 // Send(msg.release());
906 output_queue_.push(msg.release());
907 break;
910 default:
911 NOTREACHED();
912 break;
916 void ChannelPosix::HandleInternalMessage(const Message& msg) {
917 // The Hello message contains only the process id.
918 base::PickleIterator iter(msg);
920 switch (msg.type()) {
921 default:
922 NOTREACHED();
923 break;
925 case Channel::HELLO_MESSAGE_TYPE:
926 int pid;
927 if (!iter.ReadInt(&pid))
928 NOTREACHED();
930 peer_pid_ = pid;
931 listener()->OnChannelConnected(pid);
932 break;
934 #if defined(OS_MACOSX)
935 case Channel::CLOSE_FD_MESSAGE_TYPE:
936 int fd, hops;
937 if (!iter.ReadInt(&hops))
938 NOTREACHED();
939 if (!iter.ReadInt(&fd))
940 NOTREACHED();
941 if (hops == 0) {
942 if (fds_to_close_.erase(fd) > 0) {
943 if (IGNORE_EINTR(close(fd)) < 0)
944 PLOG(ERROR) << "close";
945 } else {
946 NOTREACHED();
948 } else {
949 QueueCloseFDMessage(fd, hops);
951 break;
952 #endif
956 base::ProcessId ChannelPosix::GetSenderPID() {
957 return GetPeerPID();
960 bool ChannelPosix::IsAttachmentBrokerEndpoint() {
961 return is_attachment_broker_endpoint();
964 void ChannelPosix::Close() {
965 // Close can be called multiple time, so we need to make sure we're
966 // idempotent.
968 ResetToAcceptingConnectionState();
970 if (must_unlink_) {
971 unlink(pipe_name_.c_str());
972 must_unlink_ = false;
975 if (server_listen_pipe_.is_valid()) {
976 #if defined(OS_NACL_NONSFI)
977 LOG(FATAL)
978 << "IPC channels in nacl_helper_nonsfi should not be SERVER mode.";
979 #else
980 server_listen_pipe_.reset();
981 // Unregister libevent for the listening socket and close it.
982 server_listen_connection_watcher_.StopWatchingFileDescriptor();
983 #endif
986 CloseClientFileDescriptor();
989 base::ProcessId ChannelPosix::GetPeerPID() const {
990 return peer_pid_;
993 base::ProcessId ChannelPosix::GetSelfPID() const {
994 return GetHelloMessageProcId();
997 void ChannelPosix::ResetSafely(base::ScopedFD* fd) {
998 if (!in_dtor_) {
999 fd->reset();
1000 return;
1003 // crbug.com/449233
1004 // The CL [1] tightened the error check for closing FDs, but it turned
1005 // out that there are existing cases that hit the newly added check.
1006 // ResetSafely() is the workaround for that crash, turning it from
1007 // from PCHECK() to DPCHECK() so that it doesn't crash in production.
1008 // [1] https://crrev.com/ce44fef5fd60dd2be5c587d4b084bdcd36adcee4
1009 int fd_to_close = fd->release();
1010 if (-1 != fd_to_close) {
1011 int rv = IGNORE_EINTR(close(fd_to_close));
1012 DPCHECK(0 == rv);
1016 //------------------------------------------------------------------------------
1017 // Channel's methods
1019 // static
1020 scoped_ptr<Channel> Channel::Create(const IPC::ChannelHandle& channel_handle,
1021 Mode mode,
1022 Listener* listener,
1023 AttachmentBroker* broker) {
1024 return make_scoped_ptr(
1025 new ChannelPosix(channel_handle, mode, listener));
1028 // static
1029 std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) {
1030 // A random name is sufficient validation on posix systems, so we don't need
1031 // an additional shared secret.
1033 std::string id = prefix;
1034 if (!id.empty())
1035 id.append(".");
1037 return id.append(GenerateUniqueRandomChannelID());
1040 bool Channel::IsNamedServerInitialized(
1041 const std::string& channel_id) {
1042 return ChannelPosix::IsNamedServerInitialized(channel_id);
1045 #if defined(OS_LINUX)
1046 // static
1047 void Channel::SetGlobalPid(int pid) {
1048 ChannelPosix::SetGlobalPid(pid);
1050 #endif // OS_LINUX
1052 } // namespace IPC