Make chrome compile with the win8 sdk
[chromium-blink-merge.git] / ipc / ipc_channel_posix.cc
blob3e39534659e6630a07a19be09d86ce780b225b5c
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 <sys/types.h>
11 #include <sys/socket.h>
12 #include <sys/stat.h>
13 #include <sys/un.h>
14 #include <unistd.h>
16 #if defined(OS_OPENBSD)
17 #include <sys/uio.h>
18 #endif
20 #include <string>
21 #include <map>
23 #include "base/command_line.h"
24 #include "base/eintr_wrapper.h"
25 #include "base/file_path.h"
26 #include "base/file_util.h"
27 #include "base/global_descriptors_posix.h"
28 #include "base/location.h"
29 #include "base/logging.h"
30 #include "base/memory/scoped_ptr.h"
31 #include "base/memory/singleton.h"
32 #include "base/process_util.h"
33 #include "base/rand_util.h"
34 #include "base/stl_util.h"
35 #include "base/string_util.h"
36 #include "base/synchronization/lock.h"
37 #include "ipc/ipc_descriptors.h"
38 #include "ipc/ipc_switches.h"
39 #include "ipc/file_descriptor_set_posix.h"
40 #include "ipc/ipc_logging.h"
41 #include "ipc/ipc_message_utils.h"
43 namespace IPC {
45 // IPC channels on Windows use named pipes (CreateNamedPipe()) with
46 // channel ids as the pipe names. Channels on POSIX use sockets as
47 // pipes These don't quite line up.
49 // When creating a child subprocess we use a socket pair and the parent side of
50 // the fork arranges it such that the initial control channel ends up on the
51 // magic file descriptor kPrimaryIPCChannel in the child. Future
52 // connections (file descriptors) can then be passed via that
53 // connection via sendmsg().
55 // A POSIX IPC channel can also be set up as a server for a bound UNIX domain
56 // socket, and will handle multiple connect and disconnect sequences. Currently
57 // it is limited to one connection at a time.
59 //------------------------------------------------------------------------------
60 namespace {
62 // The PipeMap class works around this quirk related to unit tests:
64 // When running as a server, we install the client socket in a
65 // specific file descriptor number (@kPrimaryIPCChannel). However, we
66 // also have to support the case where we are running unittests in the
67 // same process. (We do not support forking without execing.)
69 // Case 1: normal running
70 // The IPC server object will install a mapping in PipeMap from the
71 // name which it was given to the client pipe. When forking the client, the
72 // GetClientFileDescriptorMapping will ensure that the socket is installed in
73 // the magic slot (@kPrimaryIPCChannel). The client will search for the
74 // mapping, but it won't find any since we are in a new process. Thus the
75 // magic fd number is returned. Once the client connects, the server will
76 // close its copy of the client socket and remove the mapping.
78 // Case 2: unittests - client and server in the same process
79 // The IPC server will install a mapping as before. The client will search
80 // for a mapping and find out. It duplicates the file descriptor and
81 // connects. Once the client connects, the server will close the original
82 // copy of the client socket and remove the mapping. Thus, when the client
83 // object closes, it will close the only remaining copy of the client socket
84 // in the fd table and the server will see EOF on its side.
86 // TODO(port): a client process cannot connect to multiple IPC channels with
87 // this scheme.
89 class PipeMap {
90 public:
91 static PipeMap* GetInstance() {
92 return Singleton<PipeMap>::get();
95 ~PipeMap() {
96 // Shouldn't have left over pipes.
97 DCHECK(map_.empty());
100 // Lookup a given channel id. Return -1 if not found.
101 int Lookup(const std::string& channel_id) {
102 base::AutoLock locked(lock_);
104 ChannelToFDMap::const_iterator i = map_.find(channel_id);
105 if (i == map_.end())
106 return -1;
107 return i->second;
110 // Remove the mapping for the given channel id. No error is signaled if the
111 // channel_id doesn't exist
112 void Remove(const std::string& channel_id) {
113 base::AutoLock locked(lock_);
114 map_.erase(channel_id);
117 // Insert a mapping from @channel_id to @fd. It's a fatal error to insert a
118 // mapping if one already exists for the given channel_id
119 void Insert(const std::string& channel_id, int fd) {
120 base::AutoLock locked(lock_);
121 DCHECK_NE(-1, fd);
123 ChannelToFDMap::const_iterator i = map_.find(channel_id);
124 CHECK(i == map_.end()) << "Creating second IPC server (fd " << fd << ") "
125 << "for '" << channel_id << "' while first "
126 << "(fd " << i->second << ") still exists";
127 map_[channel_id] = fd;
130 private:
131 base::Lock lock_;
132 typedef std::map<std::string, int> ChannelToFDMap;
133 ChannelToFDMap map_;
135 friend struct DefaultSingletonTraits<PipeMap>;
138 //------------------------------------------------------------------------------
139 // Verify that kMaxPipeNameLength is a decent size.
140 COMPILE_ASSERT(sizeof(((sockaddr_un*)0)->sun_path) >= kMaxPipeNameLength,
141 BAD_SUN_PATH_LENGTH);
143 // Creates a unix domain socket bound to the specified name that is listening
144 // for connections.
145 bool CreateServerUnixDomainSocket(const std::string& pipe_name,
146 int* server_listen_fd) {
147 DCHECK(server_listen_fd);
149 if (pipe_name.length() == 0 || pipe_name.length() >= kMaxPipeNameLength) {
150 DLOG(ERROR) << "pipe_name.length() == " << pipe_name.length();
151 return false;
154 // Create socket.
155 int fd = socket(AF_UNIX, SOCK_STREAM, 0);
156 if (fd < 0) {
157 return false;
160 // Make socket non-blocking
161 if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
162 PLOG(ERROR) << "fcntl(O_NONBLOCK) " << pipe_name;
163 if (HANDLE_EINTR(close(fd)) < 0)
164 PLOG(ERROR) << "close " << pipe_name;
165 return false;
168 // Delete any old FS instances.
169 unlink(pipe_name.c_str());
171 // Make sure the path we need exists.
172 FilePath path(pipe_name);
173 FilePath dir_path = path.DirName();
174 if (!file_util::CreateDirectory(dir_path)) {
175 if (HANDLE_EINTR(close(fd)) < 0)
176 PLOG(ERROR) << "close " << pipe_name;
177 return false;
180 // Create unix_addr structure.
181 struct sockaddr_un unix_addr;
182 memset(&unix_addr, 0, sizeof(unix_addr));
183 unix_addr.sun_family = AF_UNIX;
184 int path_len = snprintf(unix_addr.sun_path, IPC::kMaxPipeNameLength,
185 "%s", pipe_name.c_str());
186 DCHECK_EQ(static_cast<int>(pipe_name.length()), path_len);
187 size_t unix_addr_len = offsetof(struct sockaddr_un,
188 sun_path) + path_len + 1;
190 // Bind the socket.
191 if (bind(fd, reinterpret_cast<const sockaddr*>(&unix_addr),
192 unix_addr_len) != 0) {
193 PLOG(ERROR) << "bind " << pipe_name;
194 if (HANDLE_EINTR(close(fd)) < 0)
195 PLOG(ERROR) << "close " << pipe_name;
196 return false;
199 // Start listening on the socket.
200 const int listen_queue_length = 1;
201 if (listen(fd, listen_queue_length) != 0) {
202 PLOG(ERROR) << "listen " << pipe_name;
203 if (HANDLE_EINTR(close(fd)) < 0)
204 PLOG(ERROR) << "close " << pipe_name;
205 return false;
208 *server_listen_fd = fd;
209 return true;
212 // Accept a connection on a socket we are listening to.
213 bool ServerAcceptConnection(int server_listen_fd, int* server_socket) {
214 DCHECK(server_socket);
216 int accept_fd = HANDLE_EINTR(accept(server_listen_fd, NULL, 0));
217 if (accept_fd < 0)
218 return false;
219 if (fcntl(accept_fd, F_SETFL, O_NONBLOCK) == -1) {
220 PLOG(ERROR) << "fcntl(O_NONBLOCK) " << accept_fd;
221 if (HANDLE_EINTR(close(accept_fd)) < 0)
222 PLOG(ERROR) << "close " << accept_fd;
223 return false;
226 *server_socket = accept_fd;
227 return true;
230 bool CreateClientUnixDomainSocket(const std::string& pipe_name,
231 int* client_socket) {
232 DCHECK(client_socket);
233 DCHECK_GT(pipe_name.length(), 0u);
234 DCHECK_LT(pipe_name.length(), kMaxPipeNameLength);
236 if (pipe_name.length() == 0 || pipe_name.length() >= kMaxPipeNameLength) {
237 return false;
240 // Create socket.
241 int fd = socket(AF_UNIX, SOCK_STREAM, 0);
242 if (fd < 0) {
243 PLOG(ERROR) << "socket " << pipe_name;
244 return false;
247 // Make socket non-blocking
248 if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
249 PLOG(ERROR) << "fcntl(O_NONBLOCK) " << pipe_name;
250 if (HANDLE_EINTR(close(fd)) < 0)
251 PLOG(ERROR) << "close " << pipe_name;
252 return false;
255 // Create server side of socket.
256 struct sockaddr_un server_unix_addr;
257 memset(&server_unix_addr, 0, sizeof(server_unix_addr));
258 server_unix_addr.sun_family = AF_UNIX;
259 int path_len = snprintf(server_unix_addr.sun_path, IPC::kMaxPipeNameLength,
260 "%s", pipe_name.c_str());
261 DCHECK_EQ(static_cast<int>(pipe_name.length()), path_len);
262 size_t server_unix_addr_len = offsetof(struct sockaddr_un,
263 sun_path) + path_len + 1;
265 if (HANDLE_EINTR(connect(fd, reinterpret_cast<sockaddr*>(&server_unix_addr),
266 server_unix_addr_len)) != 0) {
267 PLOG(ERROR) << "connect " << pipe_name;
268 if (HANDLE_EINTR(close(fd)) < 0)
269 PLOG(ERROR) << "close " << pipe_name;
270 return false;
273 *client_socket = fd;
274 return true;
277 bool SocketWriteErrorIsRecoverable() {
278 #if defined(OS_MACOSX)
279 // On OS X if sendmsg() is trying to send fds between processes and there
280 // isn't enough room in the output buffer to send the fd structure over
281 // atomically then EMSGSIZE is returned.
283 // EMSGSIZE presents a problem since the system APIs can only call us when
284 // there's room in the socket buffer and not when there is "enough" room.
286 // The current behavior is to return to the event loop when EMSGSIZE is
287 // received and hopefull service another FD. This is however still
288 // technically a busy wait since the event loop will call us right back until
289 // the receiver has read enough data to allow passing the FD over atomically.
290 return errno == EAGAIN || errno == EMSGSIZE;
291 #else
292 return errno == EAGAIN;
293 #endif // OS_MACOSX
296 } // namespace
297 //------------------------------------------------------------------------------
299 #if defined(OS_LINUX)
300 int Channel::ChannelImpl::global_pid_ = 0;
301 #endif // OS_LINUX
303 Channel::ChannelImpl::ChannelImpl(const IPC::ChannelHandle& channel_handle,
304 Mode mode, Listener* listener)
305 : ChannelReader(listener),
306 mode_(mode),
307 peer_pid_(base::kNullProcessId),
308 is_blocked_on_write_(false),
309 waiting_connect_(true),
310 message_send_bytes_written_(0),
311 server_listen_pipe_(-1),
312 pipe_(-1),
313 client_pipe_(-1),
314 #if defined(IPC_USES_READWRITE)
315 fd_pipe_(-1),
316 remote_fd_pipe_(-1),
317 #endif // IPC_USES_READWRITE
318 pipe_name_(channel_handle.name),
319 must_unlink_(false) {
320 memset(input_cmsg_buf_, 0, sizeof(input_cmsg_buf_));
321 if (!CreatePipe(channel_handle)) {
322 // The pipe may have been closed already.
323 const char *modestr = (mode_ & MODE_SERVER_FLAG) ? "server" : "client";
324 LOG(WARNING) << "Unable to create pipe named \"" << channel_handle.name
325 << "\" in " << modestr << " mode";
329 Channel::ChannelImpl::~ChannelImpl() {
330 Close();
333 bool SocketPair(int* fd1, int* fd2) {
334 int pipe_fds[2];
335 if (socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds) != 0) {
336 PLOG(ERROR) << "socketpair()";
337 return false;
340 // Set both ends to be non-blocking.
341 if (fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK) == -1 ||
342 fcntl(pipe_fds[1], F_SETFL, O_NONBLOCK) == -1) {
343 PLOG(ERROR) << "fcntl(O_NONBLOCK)";
344 if (HANDLE_EINTR(close(pipe_fds[0])) < 0)
345 PLOG(ERROR) << "close";
346 if (HANDLE_EINTR(close(pipe_fds[1])) < 0)
347 PLOG(ERROR) << "close";
348 return false;
351 *fd1 = pipe_fds[0];
352 *fd2 = pipe_fds[1];
354 return true;
357 bool Channel::ChannelImpl::CreatePipe(
358 const IPC::ChannelHandle& channel_handle) {
359 DCHECK(server_listen_pipe_ == -1 && pipe_ == -1);
361 // Four possible cases:
362 // 1) It's a channel wrapping a pipe that is given to us.
363 // 2) It's for a named channel, so we create it.
364 // 3) It's for a client that we implement ourself. This is used
365 // in unittesting.
366 // 4) It's the initial IPC channel:
367 // 4a) Client side: Pull the pipe out of the GlobalDescriptors set.
368 // 4b) Server side: create the pipe.
370 int local_pipe = -1;
371 if (channel_handle.socket.fd != -1) {
372 // Case 1 from comment above.
373 local_pipe = channel_handle.socket.fd;
374 #if defined(IPC_USES_READWRITE)
375 // Test the socket passed into us to make sure it is nonblocking.
376 // We don't want to call read/write on a blocking socket.
377 int value = fcntl(local_pipe, F_GETFL);
378 if (value == -1) {
379 PLOG(ERROR) << "fcntl(F_GETFL) " << pipe_name_;
380 return false;
382 if (!(value & O_NONBLOCK)) {
383 LOG(ERROR) << "Socket " << pipe_name_ << " must be O_NONBLOCK";
384 return false;
386 #endif // IPC_USES_READWRITE
387 } else if (mode_ & MODE_NAMED_FLAG) {
388 // Case 2 from comment above.
389 if (mode_ & MODE_SERVER_FLAG) {
390 if (!CreateServerUnixDomainSocket(pipe_name_, &local_pipe)) {
391 return false;
393 must_unlink_ = true;
394 } else if (mode_ & MODE_CLIENT_FLAG) {
395 if (!CreateClientUnixDomainSocket(pipe_name_, &local_pipe)) {
396 return false;
398 } else {
399 LOG(ERROR) << "Bad mode: " << mode_;
400 return false;
402 } else {
403 local_pipe = PipeMap::GetInstance()->Lookup(pipe_name_);
404 if (mode_ & MODE_CLIENT_FLAG) {
405 if (local_pipe != -1) {
406 // Case 3 from comment above.
407 // We only allow one connection.
408 local_pipe = HANDLE_EINTR(dup(local_pipe));
409 PipeMap::GetInstance()->Remove(pipe_name_);
410 } else {
411 // Case 4a from comment above.
412 // Guard against inappropriate reuse of the initial IPC channel. If
413 // an IPC channel closes and someone attempts to reuse it by name, the
414 // initial channel must not be recycled here. http://crbug.com/26754.
415 static bool used_initial_channel = false;
416 if (used_initial_channel) {
417 LOG(FATAL) << "Denying attempt to reuse initial IPC channel for "
418 << pipe_name_;
419 return false;
421 used_initial_channel = true;
423 local_pipe =
424 base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel);
426 } else if (mode_ & MODE_SERVER_FLAG) {
427 // Case 4b from comment above.
428 if (local_pipe != -1) {
429 LOG(ERROR) << "Server already exists for " << pipe_name_;
430 return false;
432 base::AutoLock lock(client_pipe_lock_);
433 if (!SocketPair(&local_pipe, &client_pipe_))
434 return false;
435 PipeMap::GetInstance()->Insert(pipe_name_, client_pipe_);
436 } else {
437 LOG(ERROR) << "Bad mode: " << mode_;
438 return false;
442 #if defined(IPC_USES_READWRITE)
443 // Create a dedicated socketpair() for exchanging file descriptors.
444 // See comments for IPC_USES_READWRITE for details.
445 if (mode_ & MODE_CLIENT_FLAG) {
446 if (!SocketPair(&fd_pipe_, &remote_fd_pipe_)) {
447 return false;
450 #endif // IPC_USES_READWRITE
452 if ((mode_ & MODE_SERVER_FLAG) && (mode_ & MODE_NAMED_FLAG)) {
453 server_listen_pipe_ = local_pipe;
454 local_pipe = -1;
457 pipe_ = local_pipe;
458 return true;
461 bool Channel::ChannelImpl::Connect() {
462 if (server_listen_pipe_ == -1 && pipe_ == -1) {
463 DLOG(INFO) << "Channel creation failed: " << pipe_name_;
464 return false;
467 bool did_connect = true;
468 if (server_listen_pipe_ != -1) {
469 // Watch the pipe for connections, and turn any connections into
470 // active sockets.
471 MessageLoopForIO::current()->WatchFileDescriptor(
472 server_listen_pipe_,
473 true,
474 MessageLoopForIO::WATCH_READ,
475 &server_listen_connection_watcher_,
476 this);
477 } else {
478 did_connect = AcceptConnection();
480 return did_connect;
483 bool Channel::ChannelImpl::ProcessOutgoingMessages() {
484 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
485 // no connection?
486 if (output_queue_.empty())
487 return true;
489 if (pipe_ == -1)
490 return false;
492 // Write out all the messages we can till the write blocks or there are no
493 // more outgoing messages.
494 while (!output_queue_.empty()) {
495 Message* msg = output_queue_.front();
497 size_t amt_to_write = msg->size() - message_send_bytes_written_;
498 DCHECK_NE(0U, amt_to_write);
499 const char* out_bytes = reinterpret_cast<const char*>(msg->data()) +
500 message_send_bytes_written_;
502 struct msghdr msgh = {0};
503 struct iovec iov = {const_cast<char*>(out_bytes), amt_to_write};
504 msgh.msg_iov = &iov;
505 msgh.msg_iovlen = 1;
506 char buf[CMSG_SPACE(
507 sizeof(int) * FileDescriptorSet::kMaxDescriptorsPerMessage)];
509 ssize_t bytes_written = 1;
510 int fd_written = -1;
512 if (message_send_bytes_written_ == 0 &&
513 !msg->file_descriptor_set()->empty()) {
514 // This is the first chunk of a message which has descriptors to send
515 struct cmsghdr *cmsg;
516 const unsigned num_fds = msg->file_descriptor_set()->size();
518 DCHECK(num_fds <= FileDescriptorSet::kMaxDescriptorsPerMessage);
519 if (msg->file_descriptor_set()->ContainsDirectoryDescriptor()) {
520 LOG(FATAL) << "Panic: attempting to transport directory descriptor over"
521 " IPC. Aborting to maintain sandbox isolation.";
522 // If you have hit this then something tried to send a file descriptor
523 // to a directory over an IPC channel. Since IPC channels span
524 // sandboxes this is very bad: the receiving process can use openat
525 // with ".." elements in the path in order to reach the real
526 // filesystem.
529 msgh.msg_control = buf;
530 msgh.msg_controllen = CMSG_SPACE(sizeof(int) * num_fds);
531 cmsg = CMSG_FIRSTHDR(&msgh);
532 cmsg->cmsg_level = SOL_SOCKET;
533 cmsg->cmsg_type = SCM_RIGHTS;
534 cmsg->cmsg_len = CMSG_LEN(sizeof(int) * num_fds);
535 msg->file_descriptor_set()->GetDescriptors(
536 reinterpret_cast<int*>(CMSG_DATA(cmsg)));
537 msgh.msg_controllen = cmsg->cmsg_len;
539 // DCHECK_LE above already checks that
540 // num_fds < kMaxDescriptorsPerMessage so no danger of overflow.
541 msg->header()->num_fds = static_cast<uint16>(num_fds);
543 #if defined(IPC_USES_READWRITE)
544 if (!IsHelloMessage(*msg)) {
545 // Only the Hello message sends the file descriptor with the message.
546 // Subsequently, we can send file descriptors on the dedicated
547 // fd_pipe_ which makes Seccomp sandbox operation more efficient.
548 struct iovec fd_pipe_iov = { const_cast<char *>(""), 1 };
549 msgh.msg_iov = &fd_pipe_iov;
550 fd_written = fd_pipe_;
551 bytes_written = HANDLE_EINTR(sendmsg(fd_pipe_, &msgh, MSG_DONTWAIT));
552 msgh.msg_iov = &iov;
553 msgh.msg_controllen = 0;
554 if (bytes_written > 0) {
555 msg->file_descriptor_set()->CommitAll();
558 #endif // IPC_USES_READWRITE
561 if (bytes_written == 1) {
562 fd_written = pipe_;
563 #if defined(IPC_USES_READWRITE)
564 if ((mode_ & MODE_CLIENT_FLAG) && IsHelloMessage(*msg)) {
565 DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
567 if (!msgh.msg_controllen) {
568 bytes_written = HANDLE_EINTR(write(pipe_, out_bytes, amt_to_write));
569 } else
570 #endif // IPC_USES_READWRITE
572 bytes_written = HANDLE_EINTR(sendmsg(pipe_, &msgh, MSG_DONTWAIT));
575 if (bytes_written > 0)
576 msg->file_descriptor_set()->CommitAll();
578 if (bytes_written < 0 && !SocketWriteErrorIsRecoverable()) {
579 #if defined(OS_MACOSX)
580 // On OSX writing to a pipe with no listener returns EPERM.
581 if (errno == EPERM) {
582 Close();
583 return false;
585 #endif // OS_MACOSX
586 if (errno == EPIPE) {
587 Close();
588 return false;
590 PLOG(ERROR) << "pipe error on "
591 << fd_written
592 << " Currently writing message of size: "
593 << msg->size();
594 return false;
597 if (static_cast<size_t>(bytes_written) != amt_to_write) {
598 if (bytes_written > 0) {
599 // If write() fails with EAGAIN then bytes_written will be -1.
600 message_send_bytes_written_ += bytes_written;
603 // Tell libevent to call us back once things are unblocked.
604 is_blocked_on_write_ = true;
605 MessageLoopForIO::current()->WatchFileDescriptor(
606 pipe_,
607 false, // One shot
608 MessageLoopForIO::WATCH_WRITE,
609 &write_watcher_,
610 this);
611 return true;
612 } else {
613 message_send_bytes_written_ = 0;
615 // Message sent OK!
616 DVLOG(2) << "sent message @" << msg << " on channel @" << this
617 << " with type " << msg->type() << " on fd " << pipe_;
618 delete output_queue_.front();
619 output_queue_.pop();
622 return true;
625 bool Channel::ChannelImpl::Send(Message* message) {
626 DVLOG(2) << "sending message @" << message << " on channel @" << this
627 << " with type " << message->type()
628 << " (" << output_queue_.size() << " in queue)";
630 #ifdef IPC_MESSAGE_LOG_ENABLED
631 Logging::GetInstance()->OnSendMessage(message, "");
632 #endif // IPC_MESSAGE_LOG_ENABLED
634 output_queue_.push(message);
635 if (!is_blocked_on_write_ && !waiting_connect_) {
636 return ProcessOutgoingMessages();
639 return true;
642 int Channel::ChannelImpl::GetClientFileDescriptor() {
643 base::AutoLock lock(client_pipe_lock_);
644 return client_pipe_;
647 int Channel::ChannelImpl::TakeClientFileDescriptor() {
648 base::AutoLock lock(client_pipe_lock_);
649 int fd = client_pipe_;
650 if (client_pipe_ != -1) {
651 PipeMap::GetInstance()->Remove(pipe_name_);
652 client_pipe_ = -1;
654 return fd;
657 void Channel::ChannelImpl::CloseClientFileDescriptor() {
658 base::AutoLock lock(client_pipe_lock_);
659 if (client_pipe_ != -1) {
660 PipeMap::GetInstance()->Remove(pipe_name_);
661 if (HANDLE_EINTR(close(client_pipe_)) < 0)
662 PLOG(ERROR) << "close " << pipe_name_;
663 client_pipe_ = -1;
667 bool Channel::ChannelImpl::AcceptsConnections() const {
668 return server_listen_pipe_ != -1;
671 bool Channel::ChannelImpl::HasAcceptedConnection() const {
672 return AcceptsConnections() && pipe_ != -1;
675 bool Channel::ChannelImpl::GetClientEuid(uid_t* client_euid) const {
676 DCHECK(HasAcceptedConnection());
677 #if defined(OS_MACOSX) || defined(OS_OPENBSD)
678 uid_t peer_euid;
679 gid_t peer_gid;
680 if (getpeereid(pipe_, &peer_euid, &peer_gid) != 0) {
681 PLOG(ERROR) << "getpeereid " << pipe_;
682 return false;
684 *client_euid = peer_euid;
685 return true;
686 #elif defined(OS_SOLARIS)
687 return false;
688 #else
689 struct ucred cred;
690 socklen_t cred_len = sizeof(cred);
691 if (getsockopt(pipe_, SOL_SOCKET, SO_PEERCRED, &cred, &cred_len) != 0) {
692 PLOG(ERROR) << "getsockopt " << pipe_;
693 return false;
695 if (static_cast<unsigned>(cred_len) < sizeof(cred)) {
696 NOTREACHED() << "Truncated ucred from SO_PEERCRED?";
697 return false;
699 *client_euid = cred.uid;
700 return true;
701 #endif
704 void Channel::ChannelImpl::ResetToAcceptingConnectionState() {
705 // Unregister libevent for the unix domain socket and close it.
706 read_watcher_.StopWatchingFileDescriptor();
707 write_watcher_.StopWatchingFileDescriptor();
708 if (pipe_ != -1) {
709 if (HANDLE_EINTR(close(pipe_)) < 0)
710 PLOG(ERROR) << "close pipe_ " << pipe_name_;
711 pipe_ = -1;
713 #if defined(IPC_USES_READWRITE)
714 if (fd_pipe_ != -1) {
715 if (HANDLE_EINTR(close(fd_pipe_)) < 0)
716 PLOG(ERROR) << "close fd_pipe_ " << pipe_name_;
717 fd_pipe_ = -1;
719 if (remote_fd_pipe_ != -1) {
720 if (HANDLE_EINTR(close(remote_fd_pipe_)) < 0)
721 PLOG(ERROR) << "close remote_fd_pipe_ " << pipe_name_;
722 remote_fd_pipe_ = -1;
724 #endif // IPC_USES_READWRITE
726 while (!output_queue_.empty()) {
727 Message* m = output_queue_.front();
728 output_queue_.pop();
729 delete m;
732 // Close any outstanding, received file descriptors.
733 ClearInputFDs();
736 // static
737 bool Channel::ChannelImpl::IsNamedServerInitialized(
738 const std::string& channel_id) {
739 return file_util::PathExists(FilePath(channel_id));
742 #if defined(OS_LINUX)
743 // static
744 void Channel::ChannelImpl::SetGlobalPid(int pid) {
745 global_pid_ = pid;
747 #endif // OS_LINUX
749 // Called by libevent when we can read from the pipe without blocking.
750 void Channel::ChannelImpl::OnFileCanReadWithoutBlocking(int fd) {
751 bool send_server_hello_msg = false;
752 if (fd == server_listen_pipe_) {
753 int new_pipe = 0;
754 if (!ServerAcceptConnection(server_listen_pipe_, &new_pipe)) {
755 Close();
756 listener()->OnChannelListenError();
759 if (pipe_ != -1) {
760 // We already have a connection. We only handle one at a time.
761 // close our new descriptor.
762 if (HANDLE_EINTR(shutdown(new_pipe, SHUT_RDWR)) < 0)
763 DPLOG(ERROR) << "shutdown " << pipe_name_;
764 if (HANDLE_EINTR(close(new_pipe)) < 0)
765 DPLOG(ERROR) << "close " << pipe_name_;
766 listener()->OnChannelDenied();
767 return;
769 pipe_ = new_pipe;
771 if ((mode_ & MODE_OPEN_ACCESS_FLAG) == 0) {
772 // Verify that the IPC channel peer is running as the same user.
773 uid_t client_euid;
774 if (!GetClientEuid(&client_euid)) {
775 DLOG(ERROR) << "Unable to query client euid";
776 ResetToAcceptingConnectionState();
777 return;
779 if (client_euid != geteuid()) {
780 DLOG(WARNING) << "Client euid is not authorised";
781 ResetToAcceptingConnectionState();
782 return;
786 if (!AcceptConnection()) {
787 NOTREACHED() << "AcceptConnection should not fail on server";
789 send_server_hello_msg = true;
790 waiting_connect_ = false;
791 } else if (fd == pipe_) {
792 if (waiting_connect_ && (mode_ & MODE_SERVER_FLAG)) {
793 send_server_hello_msg = true;
794 waiting_connect_ = false;
796 if (!ProcessIncomingMessages()) {
797 // ClosePipeOnError may delete this object, so we mustn't call
798 // ProcessOutgoingMessages.
799 send_server_hello_msg = false;
800 ClosePipeOnError();
802 } else {
803 NOTREACHED() << "Unknown pipe " << fd;
806 // If we're a server and handshaking, then we want to make sure that we
807 // only send our handshake message after we've processed the client's.
808 // This gives us a chance to kill the client if the incoming handshake
809 // is invalid.
810 if (send_server_hello_msg) {
811 ProcessOutgoingMessages();
815 // Called by libevent when we can write to the pipe without blocking.
816 void Channel::ChannelImpl::OnFileCanWriteWithoutBlocking(int fd) {
817 DCHECK_EQ(pipe_, fd);
818 is_blocked_on_write_ = false;
819 if (!ProcessOutgoingMessages()) {
820 ClosePipeOnError();
824 bool Channel::ChannelImpl::AcceptConnection() {
825 MessageLoopForIO::current()->WatchFileDescriptor(pipe_,
826 true,
827 MessageLoopForIO::WATCH_READ,
828 &read_watcher_,
829 this);
830 QueueHelloMessage();
832 if (mode_ & MODE_CLIENT_FLAG) {
833 // If we are a client we want to send a hello message out immediately.
834 // In server mode we will send a hello message when we receive one from a
835 // client.
836 waiting_connect_ = false;
837 return ProcessOutgoingMessages();
838 } else if (mode_ & MODE_SERVER_FLAG) {
839 waiting_connect_ = true;
840 return true;
841 } else {
842 NOTREACHED();
843 return false;
847 void Channel::ChannelImpl::ClosePipeOnError() {
848 if (HasAcceptedConnection()) {
849 ResetToAcceptingConnectionState();
850 listener()->OnChannelError();
851 } else {
852 Close();
853 if (AcceptsConnections()) {
854 listener()->OnChannelListenError();
855 } else {
856 listener()->OnChannelError();
861 int Channel::ChannelImpl::GetHelloMessageProcId() {
862 int pid = base::GetCurrentProcId();
863 #if defined(OS_LINUX)
864 // Our process may be in a sandbox with a separate PID namespace.
865 if (global_pid_) {
866 pid = global_pid_;
868 #endif
869 return pid;
872 void Channel::ChannelImpl::QueueHelloMessage() {
873 // Create the Hello message
874 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
875 HELLO_MESSAGE_TYPE,
876 IPC::Message::PRIORITY_NORMAL));
877 if (!msg->WriteInt(GetHelloMessageProcId())) {
878 NOTREACHED() << "Unable to pickle hello message proc id";
880 #if defined(IPC_USES_READWRITE)
881 scoped_ptr<Message> hello;
882 if (remote_fd_pipe_ != -1) {
883 if (!msg->WriteFileDescriptor(base::FileDescriptor(remote_fd_pipe_,
884 false))) {
885 NOTREACHED() << "Unable to pickle hello message file descriptors";
887 DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
889 #endif // IPC_USES_READWRITE
890 output_queue_.push(msg.release());
893 Channel::ChannelImpl::ReadState Channel::ChannelImpl::ReadData(
894 char* buffer,
895 int buffer_len,
896 int* bytes_read) {
897 if (pipe_ == -1)
898 return READ_FAILED;
900 struct msghdr msg = {0};
902 struct iovec iov = {buffer, static_cast<size_t>(buffer_len)};
903 msg.msg_iov = &iov;
904 msg.msg_iovlen = 1;
906 msg.msg_control = input_cmsg_buf_;
908 // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
909 // is waiting on the pipe.
910 #if defined(IPC_USES_READWRITE)
911 if (fd_pipe_ >= 0) {
912 *bytes_read = HANDLE_EINTR(read(pipe_, buffer, buffer_len));
913 msg.msg_controllen = 0;
914 } else
915 #endif // IPC_USES_READWRITE
917 msg.msg_controllen = sizeof(input_cmsg_buf_);
918 *bytes_read = HANDLE_EINTR(recvmsg(pipe_, &msg, MSG_DONTWAIT));
920 if (*bytes_read < 0) {
921 if (errno == EAGAIN) {
922 return READ_PENDING;
923 #if defined(OS_MACOSX)
924 } else if (errno == EPERM) {
925 // On OSX, reading from a pipe with no listener returns EPERM
926 // treat this as a special case to prevent spurious error messages
927 // to the console.
928 return READ_FAILED;
929 #endif // OS_MACOSX
930 } else if (errno == ECONNRESET || errno == EPIPE) {
931 return READ_FAILED;
932 } else {
933 PLOG(ERROR) << "pipe error (" << pipe_ << ")";
934 return READ_FAILED;
936 } else if (*bytes_read == 0) {
937 // The pipe has closed...
938 return READ_FAILED;
940 DCHECK(*bytes_read);
942 CloseClientFileDescriptor();
944 // Read any file descriptors from the message.
945 if (!ExtractFileDescriptorsFromMsghdr(&msg))
946 return READ_FAILED;
947 return READ_SUCCEEDED;
950 #if defined(IPC_USES_READWRITE)
951 bool Channel::ChannelImpl::ReadFileDescriptorsFromFDPipe() {
952 char dummy;
953 struct iovec fd_pipe_iov = { &dummy, 1 };
955 struct msghdr msg = { 0 };
956 msg.msg_iov = &fd_pipe_iov;
957 msg.msg_iovlen = 1;
958 msg.msg_control = input_cmsg_buf_;
959 msg.msg_controllen = sizeof(input_cmsg_buf_);
960 ssize_t bytes_received = HANDLE_EINTR(recvmsg(fd_pipe_, &msg, MSG_DONTWAIT));
962 if (bytes_received != 1)
963 return true; // No message waiting.
965 if (!ExtractFileDescriptorsFromMsghdr(&msg))
966 return false;
967 return true;
969 #endif
971 // On Posix, we need to fix up the file descriptors before the input message
972 // is dispatched.
974 // This will read from the input_fds_ (READWRITE mode only) and read more
975 // handles from the FD pipe if necessary.
976 bool Channel::ChannelImpl::WillDispatchInputMessage(Message* msg) {
977 uint16 header_fds = msg->header()->num_fds;
978 if (!header_fds)
979 return true; // Nothing to do.
981 // The message has file descriptors.
982 const char* error = NULL;
983 if (header_fds > input_fds_.size()) {
984 // The message has been completely received, but we didn't get
985 // enough file descriptors.
986 #if defined(IPC_USES_READWRITE)
987 if (!ReadFileDescriptorsFromFDPipe())
988 return false;
989 if (header_fds > input_fds_.size())
990 #endif // IPC_USES_READWRITE
991 error = "Message needs unreceived descriptors";
994 if (header_fds > FileDescriptorSet::kMaxDescriptorsPerMessage)
995 error = "Message requires an excessive number of descriptors";
997 if (error) {
998 LOG(WARNING) << error
999 << " channel:" << this
1000 << " message-type:" << msg->type()
1001 << " header()->num_fds:" << header_fds;
1002 #if defined(CHROMIUM_SELINUX)
1003 LOG(WARNING) << "In the case of SELinux this can be caused when "
1004 "using a --user-data-dir to which the default "
1005 "policy doesn't give the renderer access to. ";
1006 #endif // CHROMIUM_SELINUX
1007 // Abort the connection.
1008 ClearInputFDs();
1009 return false;
1012 // The shenaniganery below with &foo.front() requires input_fds_ to have
1013 // contiguous underlying storage (such as a simple array or a std::vector).
1014 // This is why the header warns not to make input_fds_ a deque<>.
1015 msg->file_descriptor_set()->SetDescriptors(&input_fds_.front(),
1016 header_fds);
1017 input_fds_.erase(input_fds_.begin(), input_fds_.begin() + header_fds);
1018 return true;
1021 bool Channel::ChannelImpl::DidEmptyInputBuffers() {
1022 // When the input data buffer is empty, the fds should be too. If this is
1023 // not the case, we probably have a rogue renderer which is trying to fill
1024 // our descriptor table.
1025 return input_fds_.empty();
1028 bool Channel::ChannelImpl::ExtractFileDescriptorsFromMsghdr(msghdr* msg) {
1029 // Check that there are any control messages. On OSX, CMSG_FIRSTHDR will
1030 // return an invalid non-NULL pointer in the case that controllen == 0.
1031 if (msg->msg_controllen == 0)
1032 return true;
1034 for (cmsghdr* cmsg = CMSG_FIRSTHDR(msg);
1035 cmsg;
1036 cmsg = CMSG_NXTHDR(msg, cmsg)) {
1037 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
1038 unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
1039 DCHECK_EQ(0U, payload_len % sizeof(int));
1040 const int* file_descriptors = reinterpret_cast<int*>(CMSG_DATA(cmsg));
1041 unsigned num_file_descriptors = payload_len / 4;
1042 input_fds_.insert(input_fds_.end(),
1043 file_descriptors,
1044 file_descriptors + num_file_descriptors);
1046 // Check this after adding the FDs so we don't leak them.
1047 if (msg->msg_flags & MSG_CTRUNC) {
1048 ClearInputFDs();
1049 return false;
1052 return true;
1056 // No file descriptors found, but that's OK.
1057 return true;
1060 void Channel::ChannelImpl::ClearInputFDs() {
1061 for (size_t i = 0; i < input_fds_.size(); ++i) {
1062 if (HANDLE_EINTR(close(input_fds_[i])) < 0)
1063 PLOG(ERROR) << "close ";
1065 input_fds_.clear();
1068 void Channel::ChannelImpl::HandleHelloMessage(const Message& msg) {
1069 // The Hello message contains only the process id.
1070 PickleIterator iter(msg);
1071 int pid;
1072 if (!msg.ReadInt(&iter, &pid))
1073 NOTREACHED();
1075 #if defined(IPC_USES_READWRITE)
1076 if (mode_ & MODE_SERVER_FLAG) {
1077 // With IPC_USES_READWRITE, the Hello message from the client to the
1078 // server also contains the fd_pipe_, which will be used for all
1079 // subsequent file descriptor passing.
1080 DCHECK_EQ(msg.file_descriptor_set()->size(), 1U);
1081 base::FileDescriptor descriptor;
1082 if (!msg.ReadFileDescriptor(&iter, &descriptor)) {
1083 NOTREACHED();
1085 fd_pipe_ = descriptor.fd;
1086 CHECK(descriptor.auto_close);
1088 #endif // IPC_USES_READWRITE
1089 peer_pid_ = pid;
1090 listener()->OnChannelConnected(pid);
1093 void Channel::ChannelImpl::Close() {
1094 // Close can be called multiple time, so we need to make sure we're
1095 // idempotent.
1097 ResetToAcceptingConnectionState();
1099 if (must_unlink_) {
1100 unlink(pipe_name_.c_str());
1101 must_unlink_ = false;
1103 if (server_listen_pipe_ != -1) {
1104 if (HANDLE_EINTR(close(server_listen_pipe_)) < 0)
1105 DPLOG(ERROR) << "close " << server_listen_pipe_;
1106 server_listen_pipe_ = -1;
1107 // Unregister libevent for the listening socket and close it.
1108 server_listen_connection_watcher_.StopWatchingFileDescriptor();
1111 CloseClientFileDescriptor();
1114 //------------------------------------------------------------------------------
1115 // Channel's methods simply call through to ChannelImpl.
1116 Channel::Channel(const IPC::ChannelHandle& channel_handle, Mode mode,
1117 Listener* listener)
1118 : channel_impl_(new ChannelImpl(channel_handle, mode, listener)) {
1121 Channel::~Channel() {
1122 delete channel_impl_;
1125 bool Channel::Connect() {
1126 return channel_impl_->Connect();
1129 void Channel::Close() {
1130 if (channel_impl_)
1131 channel_impl_->Close();
1134 void Channel::set_listener(Listener* listener) {
1135 channel_impl_->set_listener(listener);
1138 base::ProcessId Channel::peer_pid() const {
1139 return channel_impl_->peer_pid();
1142 bool Channel::Send(Message* message) {
1143 return channel_impl_->Send(message);
1146 int Channel::GetClientFileDescriptor() const {
1147 return channel_impl_->GetClientFileDescriptor();
1150 int Channel::TakeClientFileDescriptor() {
1151 return channel_impl_->TakeClientFileDescriptor();
1154 bool Channel::AcceptsConnections() const {
1155 return channel_impl_->AcceptsConnections();
1158 bool Channel::HasAcceptedConnection() const {
1159 return channel_impl_->HasAcceptedConnection();
1162 bool Channel::GetClientEuid(uid_t* client_euid) const {
1163 return channel_impl_->GetClientEuid(client_euid);
1166 void Channel::ResetToAcceptingConnectionState() {
1167 channel_impl_->ResetToAcceptingConnectionState();
1170 // static
1171 bool Channel::IsNamedServerInitialized(const std::string& channel_id) {
1172 return ChannelImpl::IsNamedServerInitialized(channel_id);
1175 // static
1176 std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) {
1177 // A random name is sufficient validation on posix systems, so we don't need
1178 // an additional shared secret.
1180 std::string id = prefix;
1181 if (!id.empty())
1182 id.append(".");
1184 return id.append(GenerateUniqueRandomChannelID());
1188 #if defined(OS_LINUX)
1189 // static
1190 void Channel::SetGlobalPid(int pid) {
1191 ChannelImpl::SetGlobalPid(pid);
1193 #endif // OS_LINUX
1195 } // namespace IPC