Revert 187554 "Implement IPC::ChannelFactory, a class that accep..."
[chromium-blink-merge.git] / ipc / ipc_channel_posix.cc
blob17b3641f577d5605bd0aa1763ea6fa79fd12ada7
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/socket.h>
11 #include <sys/stat.h>
12 #include <sys/types.h>
13 #include <sys/un.h>
14 #include <unistd.h>
16 #if defined(OS_OPENBSD)
17 #include <sys/uio.h>
18 #endif
20 #include <map>
21 #include <string>
23 #include "base/command_line.h"
24 #include "base/file_util.h"
25 #include "base/files/file_path.h"
26 #include "base/location.h"
27 #include "base/logging.h"
28 #include "base/memory/scoped_ptr.h"
29 #include "base/memory/singleton.h"
30 #include "base/posix/eintr_wrapper.h"
31 #include "base/posix/global_descriptors.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/file_descriptor_set_posix.h"
38 #include "ipc/ipc_descriptors.h"
39 #include "ipc/ipc_listener.h"
40 #include "ipc/ipc_logging.h"
41 #include "ipc/ipc_message_utils.h"
42 #include "ipc/ipc_switches.h"
44 namespace IPC {
46 // IPC channels on Windows use named pipes (CreateNamedPipe()) with
47 // channel ids as the pipe names. Channels on POSIX use sockets as
48 // pipes These don't quite line up.
50 // When creating a child subprocess we use a socket pair and the parent side of
51 // the fork arranges it such that the initial control channel ends up on the
52 // magic file descriptor kPrimaryIPCChannel in the child. Future
53 // connections (file descriptors) can then be passed via that
54 // connection via sendmsg().
56 // A POSIX IPC channel can also be set up as a server for a bound UNIX domain
57 // socket, and will handle multiple connect and disconnect sequences. Currently
58 // it is limited to one connection at a time.
60 //------------------------------------------------------------------------------
61 namespace {
63 // The PipeMap class works around this quirk related to unit tests:
65 // When running as a server, we install the client socket in a
66 // specific file descriptor number (@kPrimaryIPCChannel). However, we
67 // also have to support the case where we are running unittests in the
68 // same process. (We do not support forking without execing.)
70 // Case 1: normal running
71 // The IPC server object will install a mapping in PipeMap from the
72 // name which it was given to the client pipe. When forking the client, the
73 // GetClientFileDescriptorMapping will ensure that the socket is installed in
74 // the magic slot (@kPrimaryIPCChannel). The client will search for the
75 // mapping, but it won't find any since we are in a new process. Thus the
76 // magic fd number is returned. Once the client connects, the server will
77 // close its copy of the client socket and remove the mapping.
79 // Case 2: unittests - client and server in the same process
80 // The IPC server will install a mapping as before. The client will search
81 // for a mapping and find out. It duplicates the file descriptor and
82 // connects. Once the client connects, the server will close the original
83 // copy of the client socket and remove the mapping. Thus, when the client
84 // object closes, it will close the only remaining copy of the client socket
85 // in the fd table and the server will see EOF on its side.
87 // TODO(port): a client process cannot connect to multiple IPC channels with
88 // this scheme.
90 class PipeMap {
91 public:
92 static PipeMap* GetInstance() {
93 return Singleton<PipeMap>::get();
96 ~PipeMap() {
97 // Shouldn't have left over pipes.
98 DCHECK(map_.empty());
101 // Lookup a given channel id. Return -1 if not found.
102 int Lookup(const std::string& channel_id) {
103 base::AutoLock locked(lock_);
105 ChannelToFDMap::const_iterator i = map_.find(channel_id);
106 if (i == map_.end())
107 return -1;
108 return i->second;
111 // Remove the mapping for the given channel id. No error is signaled if the
112 // channel_id doesn't exist
113 void Remove(const std::string& channel_id) {
114 base::AutoLock locked(lock_);
115 map_.erase(channel_id);
118 // Insert a mapping from @channel_id to @fd. It's a fatal error to insert a
119 // mapping if one already exists for the given channel_id
120 void Insert(const std::string& channel_id, int fd) {
121 base::AutoLock locked(lock_);
122 DCHECK_NE(-1, fd);
124 ChannelToFDMap::const_iterator i = map_.find(channel_id);
125 CHECK(i == map_.end()) << "Creating second IPC server (fd " << fd << ") "
126 << "for '" << channel_id << "' while first "
127 << "(fd " << i->second << ") still exists";
128 map_[channel_id] = fd;
131 private:
132 base::Lock lock_;
133 typedef std::map<std::string, int> ChannelToFDMap;
134 ChannelToFDMap map_;
136 friend struct DefaultSingletonTraits<PipeMap>;
139 //------------------------------------------------------------------------------
140 // Verify that kMaxPipeNameLength is a decent size.
141 COMPILE_ASSERT(sizeof(((sockaddr_un*)0)->sun_path) >= kMaxPipeNameLength,
142 BAD_SUN_PATH_LENGTH);
144 // Creates a unix domain socket bound to the specified name that is listening
145 // for connections.
146 bool CreateServerUnixDomainSocket(const std::string& pipe_name,
147 int* server_listen_fd) {
148 DCHECK(server_listen_fd);
150 if (pipe_name.length() == 0 || pipe_name.length() >= kMaxPipeNameLength) {
151 DLOG(ERROR) << "pipe_name.length() == " << pipe_name.length();
152 return false;
155 // Create socket.
156 int fd = socket(AF_UNIX, SOCK_STREAM, 0);
157 if (fd < 0) {
158 return false;
161 // Make socket non-blocking
162 if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
163 PLOG(ERROR) << "fcntl(O_NONBLOCK) " << pipe_name;
164 if (HANDLE_EINTR(close(fd)) < 0)
165 PLOG(ERROR) << "close " << pipe_name;
166 return false;
169 // Delete any old FS instances.
170 unlink(pipe_name.c_str());
172 // Make sure the path we need exists.
173 base::FilePath path(pipe_name);
174 base::FilePath dir_path = path.DirName();
175 if (!file_util::CreateDirectory(dir_path)) {
176 if (HANDLE_EINTR(close(fd)) < 0)
177 PLOG(ERROR) << "close " << pipe_name;
178 return false;
181 // Create unix_addr structure.
182 struct sockaddr_un unix_addr;
183 memset(&unix_addr, 0, sizeof(unix_addr));
184 unix_addr.sun_family = AF_UNIX;
185 int path_len = snprintf(unix_addr.sun_path, IPC::kMaxPipeNameLength,
186 "%s", pipe_name.c_str());
187 DCHECK_EQ(static_cast<int>(pipe_name.length()), path_len);
188 size_t unix_addr_len = offsetof(struct sockaddr_un,
189 sun_path) + path_len + 1;
191 // Bind the socket.
192 if (bind(fd, reinterpret_cast<const sockaddr*>(&unix_addr),
193 unix_addr_len) != 0) {
194 PLOG(ERROR) << "bind " << pipe_name;
195 if (HANDLE_EINTR(close(fd)) < 0)
196 PLOG(ERROR) << "close " << pipe_name;
197 return false;
200 // Start listening on the socket.
201 const int listen_queue_length = 1;
202 if (listen(fd, listen_queue_length) != 0) {
203 PLOG(ERROR) << "listen " << pipe_name;
204 if (HANDLE_EINTR(close(fd)) < 0)
205 PLOG(ERROR) << "close " << pipe_name;
206 return false;
209 *server_listen_fd = fd;
210 return true;
213 // Accept a connection on a socket we are listening to.
214 bool ServerAcceptConnection(int server_listen_fd, int* server_socket) {
215 DCHECK(server_socket);
217 int accept_fd = HANDLE_EINTR(accept(server_listen_fd, NULL, 0));
218 if (accept_fd < 0)
219 return false;
220 if (fcntl(accept_fd, F_SETFL, O_NONBLOCK) == -1) {
221 PLOG(ERROR) << "fcntl(O_NONBLOCK) " << accept_fd;
222 if (HANDLE_EINTR(close(accept_fd)) < 0)
223 PLOG(ERROR) << "close " << accept_fd;
224 return false;
227 *server_socket = accept_fd;
228 return true;
231 bool CreateClientUnixDomainSocket(const std::string& pipe_name,
232 int* client_socket) {
233 DCHECK(client_socket);
234 DCHECK_GT(pipe_name.length(), 0u);
235 DCHECK_LT(pipe_name.length(), kMaxPipeNameLength);
237 if (pipe_name.length() == 0 || pipe_name.length() >= kMaxPipeNameLength) {
238 return false;
241 // Create socket.
242 int fd = socket(AF_UNIX, SOCK_STREAM, 0);
243 if (fd < 0) {
244 PLOG(ERROR) << "socket " << pipe_name;
245 return false;
248 // Make socket non-blocking
249 if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
250 PLOG(ERROR) << "fcntl(O_NONBLOCK) " << pipe_name;
251 if (HANDLE_EINTR(close(fd)) < 0)
252 PLOG(ERROR) << "close " << pipe_name;
253 return false;
256 // Create server side of socket.
257 struct sockaddr_un server_unix_addr;
258 memset(&server_unix_addr, 0, sizeof(server_unix_addr));
259 server_unix_addr.sun_family = AF_UNIX;
260 int path_len = snprintf(server_unix_addr.sun_path, IPC::kMaxPipeNameLength,
261 "%s", pipe_name.c_str());
262 DCHECK_EQ(static_cast<int>(pipe_name.length()), path_len);
263 size_t server_unix_addr_len = offsetof(struct sockaddr_un,
264 sun_path) + path_len + 1;
266 if (HANDLE_EINTR(connect(fd, reinterpret_cast<sockaddr*>(&server_unix_addr),
267 server_unix_addr_len)) != 0) {
268 PLOG(ERROR) << "connect " << pipe_name;
269 if (HANDLE_EINTR(close(fd)) < 0)
270 PLOG(ERROR) << "close " << pipe_name;
271 return false;
274 *client_socket = fd;
275 return true;
278 bool SocketWriteErrorIsRecoverable() {
279 #if defined(OS_MACOSX)
280 // On OS X if sendmsg() is trying to send fds between processes and there
281 // isn't enough room in the output buffer to send the fd structure over
282 // atomically then EMSGSIZE is returned.
284 // EMSGSIZE presents a problem since the system APIs can only call us when
285 // there's room in the socket buffer and not when there is "enough" room.
287 // The current behavior is to return to the event loop when EMSGSIZE is
288 // received and hopefull service another FD. This is however still
289 // technically a busy wait since the event loop will call us right back until
290 // the receiver has read enough data to allow passing the FD over atomically.
291 return errno == EAGAIN || errno == EMSGSIZE;
292 #else
293 return errno == EAGAIN;
294 #endif // OS_MACOSX
297 } // namespace
298 //------------------------------------------------------------------------------
300 #if defined(OS_LINUX)
301 int Channel::ChannelImpl::global_pid_ = 0;
302 #endif // OS_LINUX
304 Channel::ChannelImpl::ChannelImpl(const IPC::ChannelHandle& channel_handle,
305 Mode mode, Listener* listener)
306 : ChannelReader(listener),
307 mode_(mode),
308 peer_pid_(base::kNullProcessId),
309 is_blocked_on_write_(false),
310 waiting_connect_(true),
311 message_send_bytes_written_(0),
312 server_listen_pipe_(-1),
313 pipe_(-1),
314 client_pipe_(-1),
315 #if defined(IPC_USES_READWRITE)
316 fd_pipe_(-1),
317 remote_fd_pipe_(-1),
318 #endif // IPC_USES_READWRITE
319 pipe_name_(channel_handle.name),
320 must_unlink_(false) {
321 memset(input_cmsg_buf_, 0, sizeof(input_cmsg_buf_));
322 if (!CreatePipe(channel_handle)) {
323 // The pipe may have been closed already.
324 const char *modestr = (mode_ & MODE_SERVER_FLAG) ? "server" : "client";
325 LOG(WARNING) << "Unable to create pipe named \"" << channel_handle.name
326 << "\" in " << modestr << " mode";
330 Channel::ChannelImpl::~ChannelImpl() {
331 Close();
334 bool SocketPair(int* fd1, int* fd2) {
335 int pipe_fds[2];
336 if (socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds) != 0) {
337 PLOG(ERROR) << "socketpair()";
338 return false;
341 // Set both ends to be non-blocking.
342 if (fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK) == -1 ||
343 fcntl(pipe_fds[1], F_SETFL, O_NONBLOCK) == -1) {
344 PLOG(ERROR) << "fcntl(O_NONBLOCK)";
345 if (HANDLE_EINTR(close(pipe_fds[0])) < 0)
346 PLOG(ERROR) << "close";
347 if (HANDLE_EINTR(close(pipe_fds[1])) < 0)
348 PLOG(ERROR) << "close";
349 return false;
352 *fd1 = pipe_fds[0];
353 *fd2 = pipe_fds[1];
355 return true;
358 bool Channel::ChannelImpl::CreatePipe(
359 const IPC::ChannelHandle& channel_handle) {
360 DCHECK(server_listen_pipe_ == -1 && pipe_ == -1);
362 // Four possible cases:
363 // 1) It's a channel wrapping a pipe that is given to us.
364 // 2) It's for a named channel, so we create it.
365 // 3) It's for a client that we implement ourself. This is used
366 // in unittesting.
367 // 4) It's the initial IPC channel:
368 // 4a) Client side: Pull the pipe out of the GlobalDescriptors set.
369 // 4b) Server side: create the pipe.
371 int local_pipe = -1;
372 if (channel_handle.socket.fd != -1) {
373 // Case 1 from comment above.
374 local_pipe = channel_handle.socket.fd;
375 #if defined(IPC_USES_READWRITE)
376 // Test the socket passed into us to make sure it is nonblocking.
377 // We don't want to call read/write on a blocking socket.
378 int value = fcntl(local_pipe, F_GETFL);
379 if (value == -1) {
380 PLOG(ERROR) << "fcntl(F_GETFL) " << pipe_name_;
381 return false;
383 if (!(value & O_NONBLOCK)) {
384 LOG(ERROR) << "Socket " << pipe_name_ << " must be O_NONBLOCK";
385 return false;
387 #endif // IPC_USES_READWRITE
388 } else if (mode_ & MODE_NAMED_FLAG) {
389 // Case 2 from comment above.
390 if (mode_ & MODE_SERVER_FLAG) {
391 if (!CreateServerUnixDomainSocket(pipe_name_, &local_pipe)) {
392 return false;
394 must_unlink_ = true;
395 } else if (mode_ & MODE_CLIENT_FLAG) {
396 if (!CreateClientUnixDomainSocket(pipe_name_, &local_pipe)) {
397 return false;
399 } else {
400 LOG(ERROR) << "Bad mode: " << mode_;
401 return false;
403 } else {
404 local_pipe = PipeMap::GetInstance()->Lookup(pipe_name_);
405 if (mode_ & MODE_CLIENT_FLAG) {
406 if (local_pipe != -1) {
407 // Case 3 from comment above.
408 // We only allow one connection.
409 local_pipe = HANDLE_EINTR(dup(local_pipe));
410 PipeMap::GetInstance()->Remove(pipe_name_);
411 } else {
412 // Case 4a from comment above.
413 // Guard against inappropriate reuse of the initial IPC channel. If
414 // an IPC channel closes and someone attempts to reuse it by name, the
415 // initial channel must not be recycled here. http://crbug.com/26754.
416 static bool used_initial_channel = false;
417 if (used_initial_channel) {
418 LOG(FATAL) << "Denying attempt to reuse initial IPC channel for "
419 << pipe_name_;
420 return false;
422 used_initial_channel = true;
424 local_pipe =
425 base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel);
427 } else if (mode_ & MODE_SERVER_FLAG) {
428 // Case 4b from comment above.
429 if (local_pipe != -1) {
430 LOG(ERROR) << "Server already exists for " << pipe_name_;
431 return false;
433 base::AutoLock lock(client_pipe_lock_);
434 if (!SocketPair(&local_pipe, &client_pipe_))
435 return false;
436 PipeMap::GetInstance()->Insert(pipe_name_, client_pipe_);
437 } else {
438 LOG(ERROR) << "Bad mode: " << mode_;
439 return false;
443 #if defined(IPC_USES_READWRITE)
444 // Create a dedicated socketpair() for exchanging file descriptors.
445 // See comments for IPC_USES_READWRITE for details.
446 if (mode_ & MODE_CLIENT_FLAG) {
447 if (!SocketPair(&fd_pipe_, &remote_fd_pipe_)) {
448 return false;
451 #endif // IPC_USES_READWRITE
453 if ((mode_ & MODE_SERVER_FLAG) && (mode_ & MODE_NAMED_FLAG)) {
454 server_listen_pipe_ = local_pipe;
455 local_pipe = -1;
458 pipe_ = local_pipe;
459 return true;
462 bool Channel::ChannelImpl::Connect() {
463 if (server_listen_pipe_ == -1 && pipe_ == -1) {
464 DLOG(INFO) << "Channel creation failed: " << pipe_name_;
465 return false;
468 bool did_connect = true;
469 if (server_listen_pipe_ != -1) {
470 // Watch the pipe for connections, and turn any connections into
471 // active sockets.
472 MessageLoopForIO::current()->WatchFileDescriptor(
473 server_listen_pipe_,
474 true,
475 MessageLoopForIO::WATCH_READ,
476 &server_listen_connection_watcher_,
477 this);
478 } else {
479 did_connect = AcceptConnection();
481 return did_connect;
484 bool Channel::ChannelImpl::ProcessOutgoingMessages() {
485 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
486 // no connection?
487 if (output_queue_.empty())
488 return true;
490 if (pipe_ == -1)
491 return false;
493 // Write out all the messages we can till the write blocks or there are no
494 // more outgoing messages.
495 while (!output_queue_.empty()) {
496 Message* msg = output_queue_.front();
498 size_t amt_to_write = msg->size() - message_send_bytes_written_;
499 DCHECK_NE(0U, amt_to_write);
500 const char* out_bytes = reinterpret_cast<const char*>(msg->data()) +
501 message_send_bytes_written_;
503 struct msghdr msgh = {0};
504 struct iovec iov = {const_cast<char*>(out_bytes), amt_to_write};
505 msgh.msg_iov = &iov;
506 msgh.msg_iovlen = 1;
507 char buf[CMSG_SPACE(
508 sizeof(int) * FileDescriptorSet::kMaxDescriptorsPerMessage)];
510 ssize_t bytes_written = 1;
511 int fd_written = -1;
513 if (message_send_bytes_written_ == 0 &&
514 !msg->file_descriptor_set()->empty()) {
515 // This is the first chunk of a message which has descriptors to send
516 struct cmsghdr *cmsg;
517 const unsigned num_fds = msg->file_descriptor_set()->size();
519 DCHECK(num_fds <= FileDescriptorSet::kMaxDescriptorsPerMessage);
520 if (msg->file_descriptor_set()->ContainsDirectoryDescriptor()) {
521 LOG(FATAL) << "Panic: attempting to transport directory descriptor over"
522 " IPC. Aborting to maintain sandbox isolation.";
523 // If you have hit this then something tried to send a file descriptor
524 // to a directory over an IPC channel. Since IPC channels span
525 // sandboxes this is very bad: the receiving process can use openat
526 // with ".." elements in the path in order to reach the real
527 // filesystem.
530 msgh.msg_control = buf;
531 msgh.msg_controllen = CMSG_SPACE(sizeof(int) * num_fds);
532 cmsg = CMSG_FIRSTHDR(&msgh);
533 cmsg->cmsg_level = SOL_SOCKET;
534 cmsg->cmsg_type = SCM_RIGHTS;
535 cmsg->cmsg_len = CMSG_LEN(sizeof(int) * num_fds);
536 msg->file_descriptor_set()->GetDescriptors(
537 reinterpret_cast<int*>(CMSG_DATA(cmsg)));
538 msgh.msg_controllen = cmsg->cmsg_len;
540 // DCHECK_LE above already checks that
541 // num_fds < kMaxDescriptorsPerMessage so no danger of overflow.
542 msg->header()->num_fds = static_cast<uint16>(num_fds);
544 #if defined(IPC_USES_READWRITE)
545 if (!IsHelloMessage(*msg)) {
546 // Only the Hello message sends the file descriptor with the message.
547 // Subsequently, we can send file descriptors on the dedicated
548 // fd_pipe_ which makes Seccomp sandbox operation more efficient.
549 struct iovec fd_pipe_iov = { const_cast<char *>(""), 1 };
550 msgh.msg_iov = &fd_pipe_iov;
551 fd_written = fd_pipe_;
552 bytes_written = HANDLE_EINTR(sendmsg(fd_pipe_, &msgh, MSG_DONTWAIT));
553 msgh.msg_iov = &iov;
554 msgh.msg_controllen = 0;
555 if (bytes_written > 0) {
556 msg->file_descriptor_set()->CommitAll();
559 #endif // IPC_USES_READWRITE
562 if (bytes_written == 1) {
563 fd_written = pipe_;
564 #if defined(IPC_USES_READWRITE)
565 if ((mode_ & MODE_CLIENT_FLAG) && IsHelloMessage(*msg)) {
566 DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
568 if (!msgh.msg_controllen) {
569 bytes_written = HANDLE_EINTR(write(pipe_, out_bytes, amt_to_write));
570 } else
571 #endif // IPC_USES_READWRITE
573 bytes_written = HANDLE_EINTR(sendmsg(pipe_, &msgh, MSG_DONTWAIT));
576 if (bytes_written > 0)
577 msg->file_descriptor_set()->CommitAll();
579 if (bytes_written < 0 && !SocketWriteErrorIsRecoverable()) {
580 #if defined(OS_MACOSX)
581 // On OSX writing to a pipe with no listener returns EPERM.
582 if (errno == EPERM) {
583 Close();
584 return false;
586 #endif // OS_MACOSX
587 if (errno == EPIPE) {
588 Close();
589 return false;
591 PLOG(ERROR) << "pipe error on "
592 << fd_written
593 << " Currently writing message of size: "
594 << msg->size();
595 return false;
598 if (static_cast<size_t>(bytes_written) != amt_to_write) {
599 if (bytes_written > 0) {
600 // If write() fails with EAGAIN then bytes_written will be -1.
601 message_send_bytes_written_ += bytes_written;
604 // Tell libevent to call us back once things are unblocked.
605 is_blocked_on_write_ = true;
606 MessageLoopForIO::current()->WatchFileDescriptor(
607 pipe_,
608 false, // One shot
609 MessageLoopForIO::WATCH_WRITE,
610 &write_watcher_,
611 this);
612 return true;
613 } else {
614 message_send_bytes_written_ = 0;
616 // Message sent OK!
617 DVLOG(2) << "sent message @" << msg << " on channel @" << this
618 << " with type " << msg->type() << " on fd " << pipe_;
619 delete output_queue_.front();
620 output_queue_.pop();
623 return true;
626 bool Channel::ChannelImpl::Send(Message* message) {
627 DVLOG(2) << "sending message @" << message << " on channel @" << this
628 << " with type " << message->type()
629 << " (" << output_queue_.size() << " in queue)";
631 #ifdef IPC_MESSAGE_LOG_ENABLED
632 Logging::GetInstance()->OnSendMessage(message, "");
633 #endif // IPC_MESSAGE_LOG_ENABLED
635 message->TraceMessageBegin();
636 output_queue_.push(message);
637 if (!is_blocked_on_write_ && !waiting_connect_) {
638 return ProcessOutgoingMessages();
641 return true;
644 int Channel::ChannelImpl::GetClientFileDescriptor() {
645 base::AutoLock lock(client_pipe_lock_);
646 return client_pipe_;
649 int Channel::ChannelImpl::TakeClientFileDescriptor() {
650 base::AutoLock lock(client_pipe_lock_);
651 int fd = client_pipe_;
652 if (client_pipe_ != -1) {
653 PipeMap::GetInstance()->Remove(pipe_name_);
654 client_pipe_ = -1;
656 return fd;
659 void Channel::ChannelImpl::CloseClientFileDescriptor() {
660 base::AutoLock lock(client_pipe_lock_);
661 if (client_pipe_ != -1) {
662 PipeMap::GetInstance()->Remove(pipe_name_);
663 if (HANDLE_EINTR(close(client_pipe_)) < 0)
664 PLOG(ERROR) << "close " << pipe_name_;
665 client_pipe_ = -1;
669 bool Channel::ChannelImpl::AcceptsConnections() const {
670 return server_listen_pipe_ != -1;
673 bool Channel::ChannelImpl::HasAcceptedConnection() const {
674 return AcceptsConnections() && pipe_ != -1;
677 bool Channel::ChannelImpl::GetClientEuid(uid_t* client_euid) const {
678 DCHECK(HasAcceptedConnection());
679 #if defined(OS_MACOSX) || defined(OS_OPENBSD)
680 uid_t peer_euid;
681 gid_t peer_gid;
682 if (getpeereid(pipe_, &peer_euid, &peer_gid) != 0) {
683 PLOG(ERROR) << "getpeereid " << pipe_;
684 return false;
686 *client_euid = peer_euid;
687 return true;
688 #elif defined(OS_SOLARIS)
689 return false;
690 #else
691 struct ucred cred;
692 socklen_t cred_len = sizeof(cred);
693 if (getsockopt(pipe_, SOL_SOCKET, SO_PEERCRED, &cred, &cred_len) != 0) {
694 PLOG(ERROR) << "getsockopt " << pipe_;
695 return false;
697 if (static_cast<unsigned>(cred_len) < sizeof(cred)) {
698 NOTREACHED() << "Truncated ucred from SO_PEERCRED?";
699 return false;
701 *client_euid = cred.uid;
702 return true;
703 #endif
706 void Channel::ChannelImpl::ResetToAcceptingConnectionState() {
707 // Unregister libevent for the unix domain socket and close it.
708 read_watcher_.StopWatchingFileDescriptor();
709 write_watcher_.StopWatchingFileDescriptor();
710 if (pipe_ != -1) {
711 if (HANDLE_EINTR(close(pipe_)) < 0)
712 PLOG(ERROR) << "close pipe_ " << pipe_name_;
713 pipe_ = -1;
715 #if defined(IPC_USES_READWRITE)
716 if (fd_pipe_ != -1) {
717 if (HANDLE_EINTR(close(fd_pipe_)) < 0)
718 PLOG(ERROR) << "close fd_pipe_ " << pipe_name_;
719 fd_pipe_ = -1;
721 if (remote_fd_pipe_ != -1) {
722 if (HANDLE_EINTR(close(remote_fd_pipe_)) < 0)
723 PLOG(ERROR) << "close remote_fd_pipe_ " << pipe_name_;
724 remote_fd_pipe_ = -1;
726 #endif // IPC_USES_READWRITE
728 while (!output_queue_.empty()) {
729 Message* m = output_queue_.front();
730 output_queue_.pop();
731 delete m;
734 // Close any outstanding, received file descriptors.
735 ClearInputFDs();
738 // static
739 bool Channel::ChannelImpl::IsNamedServerInitialized(
740 const std::string& channel_id) {
741 return file_util::PathExists(base::FilePath(channel_id));
744 #if defined(OS_LINUX)
745 // static
746 void Channel::ChannelImpl::SetGlobalPid(int pid) {
747 global_pid_ = pid;
749 #endif // OS_LINUX
751 // Called by libevent when we can read from the pipe without blocking.
752 void Channel::ChannelImpl::OnFileCanReadWithoutBlocking(int fd) {
753 bool send_server_hello_msg = false;
754 if (fd == server_listen_pipe_) {
755 int new_pipe = 0;
756 if (!ServerAcceptConnection(server_listen_pipe_, &new_pipe)) {
757 Close();
758 listener()->OnChannelListenError();
761 if (pipe_ != -1) {
762 // We already have a connection. We only handle one at a time.
763 // close our new descriptor.
764 if (HANDLE_EINTR(shutdown(new_pipe, SHUT_RDWR)) < 0)
765 DPLOG(ERROR) << "shutdown " << pipe_name_;
766 if (HANDLE_EINTR(close(new_pipe)) < 0)
767 DPLOG(ERROR) << "close " << pipe_name_;
768 listener()->OnChannelDenied();
769 return;
771 pipe_ = new_pipe;
773 if ((mode_ & MODE_OPEN_ACCESS_FLAG) == 0) {
774 // Verify that the IPC channel peer is running as the same user.
775 uid_t client_euid;
776 if (!GetClientEuid(&client_euid)) {
777 DLOG(ERROR) << "Unable to query client euid";
778 ResetToAcceptingConnectionState();
779 return;
781 if (client_euid != geteuid()) {
782 DLOG(WARNING) << "Client euid is not authorised";
783 ResetToAcceptingConnectionState();
784 return;
788 if (!AcceptConnection()) {
789 NOTREACHED() << "AcceptConnection should not fail on server";
791 send_server_hello_msg = true;
792 waiting_connect_ = false;
793 } else if (fd == pipe_) {
794 if (waiting_connect_ && (mode_ & MODE_SERVER_FLAG)) {
795 send_server_hello_msg = true;
796 waiting_connect_ = false;
798 if (!ProcessIncomingMessages()) {
799 // ClosePipeOnError may delete this object, so we mustn't call
800 // ProcessOutgoingMessages.
801 send_server_hello_msg = false;
802 ClosePipeOnError();
804 } else {
805 NOTREACHED() << "Unknown pipe " << fd;
808 // If we're a server and handshaking, then we want to make sure that we
809 // only send our handshake message after we've processed the client's.
810 // This gives us a chance to kill the client if the incoming handshake
811 // is invalid.
812 if (send_server_hello_msg) {
813 ProcessOutgoingMessages();
817 // Called by libevent when we can write to the pipe without blocking.
818 void Channel::ChannelImpl::OnFileCanWriteWithoutBlocking(int fd) {
819 DCHECK_EQ(pipe_, fd);
820 is_blocked_on_write_ = false;
821 if (!ProcessOutgoingMessages()) {
822 ClosePipeOnError();
826 bool Channel::ChannelImpl::AcceptConnection() {
827 MessageLoopForIO::current()->WatchFileDescriptor(pipe_,
828 true,
829 MessageLoopForIO::WATCH_READ,
830 &read_watcher_,
831 this);
832 QueueHelloMessage();
834 if (mode_ & MODE_CLIENT_FLAG) {
835 // If we are a client we want to send a hello message out immediately.
836 // In server mode we will send a hello message when we receive one from a
837 // client.
838 waiting_connect_ = false;
839 return ProcessOutgoingMessages();
840 } else if (mode_ & MODE_SERVER_FLAG) {
841 waiting_connect_ = true;
842 return true;
843 } else {
844 NOTREACHED();
845 return false;
849 void Channel::ChannelImpl::ClosePipeOnError() {
850 if (HasAcceptedConnection()) {
851 ResetToAcceptingConnectionState();
852 listener()->OnChannelError();
853 } else {
854 Close();
855 if (AcceptsConnections()) {
856 listener()->OnChannelListenError();
857 } else {
858 listener()->OnChannelError();
863 int Channel::ChannelImpl::GetHelloMessageProcId() {
864 int pid = base::GetCurrentProcId();
865 #if defined(OS_LINUX)
866 // Our process may be in a sandbox with a separate PID namespace.
867 if (global_pid_) {
868 pid = global_pid_;
870 #endif
871 return pid;
874 void Channel::ChannelImpl::QueueHelloMessage() {
875 // Create the Hello message
876 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
877 HELLO_MESSAGE_TYPE,
878 IPC::Message::PRIORITY_NORMAL));
879 if (!msg->WriteInt(GetHelloMessageProcId())) {
880 NOTREACHED() << "Unable to pickle hello message proc id";
882 #if defined(IPC_USES_READWRITE)
883 scoped_ptr<Message> hello;
884 if (remote_fd_pipe_ != -1) {
885 if (!msg->WriteFileDescriptor(base::FileDescriptor(remote_fd_pipe_,
886 false))) {
887 NOTREACHED() << "Unable to pickle hello message file descriptors";
889 DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
891 #endif // IPC_USES_READWRITE
892 output_queue_.push(msg.release());
895 Channel::ChannelImpl::ReadState Channel::ChannelImpl::ReadData(
896 char* buffer,
897 int buffer_len,
898 int* bytes_read) {
899 if (pipe_ == -1)
900 return READ_FAILED;
902 struct msghdr msg = {0};
904 struct iovec iov = {buffer, static_cast<size_t>(buffer_len)};
905 msg.msg_iov = &iov;
906 msg.msg_iovlen = 1;
908 msg.msg_control = input_cmsg_buf_;
910 // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
911 // is waiting on the pipe.
912 #if defined(IPC_USES_READWRITE)
913 if (fd_pipe_ >= 0) {
914 *bytes_read = HANDLE_EINTR(read(pipe_, buffer, buffer_len));
915 msg.msg_controllen = 0;
916 } else
917 #endif // IPC_USES_READWRITE
919 msg.msg_controllen = sizeof(input_cmsg_buf_);
920 *bytes_read = HANDLE_EINTR(recvmsg(pipe_, &msg, MSG_DONTWAIT));
922 if (*bytes_read < 0) {
923 if (errno == EAGAIN) {
924 return READ_PENDING;
925 #if defined(OS_MACOSX)
926 } else if (errno == EPERM) {
927 // On OSX, reading from a pipe with no listener returns EPERM
928 // treat this as a special case to prevent spurious error messages
929 // to the console.
930 return READ_FAILED;
931 #endif // OS_MACOSX
932 } else if (errno == ECONNRESET || errno == EPIPE) {
933 return READ_FAILED;
934 } else {
935 PLOG(ERROR) << "pipe error (" << pipe_ << ")";
936 return READ_FAILED;
938 } else if (*bytes_read == 0) {
939 // The pipe has closed...
940 return READ_FAILED;
942 DCHECK(*bytes_read);
944 CloseClientFileDescriptor();
946 // Read any file descriptors from the message.
947 if (!ExtractFileDescriptorsFromMsghdr(&msg))
948 return READ_FAILED;
949 return READ_SUCCEEDED;
952 #if defined(IPC_USES_READWRITE)
953 bool Channel::ChannelImpl::ReadFileDescriptorsFromFDPipe() {
954 char dummy;
955 struct iovec fd_pipe_iov = { &dummy, 1 };
957 struct msghdr msg = { 0 };
958 msg.msg_iov = &fd_pipe_iov;
959 msg.msg_iovlen = 1;
960 msg.msg_control = input_cmsg_buf_;
961 msg.msg_controllen = sizeof(input_cmsg_buf_);
962 ssize_t bytes_received = HANDLE_EINTR(recvmsg(fd_pipe_, &msg, MSG_DONTWAIT));
964 if (bytes_received != 1)
965 return true; // No message waiting.
967 if (!ExtractFileDescriptorsFromMsghdr(&msg))
968 return false;
969 return true;
971 #endif
973 // On Posix, we need to fix up the file descriptors before the input message
974 // is dispatched.
976 // This will read from the input_fds_ (READWRITE mode only) and read more
977 // handles from the FD pipe if necessary.
978 bool Channel::ChannelImpl::WillDispatchInputMessage(Message* msg) {
979 uint16 header_fds = msg->header()->num_fds;
980 if (!header_fds)
981 return true; // Nothing to do.
983 // The message has file descriptors.
984 const char* error = NULL;
985 if (header_fds > input_fds_.size()) {
986 // The message has been completely received, but we didn't get
987 // enough file descriptors.
988 #if defined(IPC_USES_READWRITE)
989 if (!ReadFileDescriptorsFromFDPipe())
990 return false;
991 if (header_fds > input_fds_.size())
992 #endif // IPC_USES_READWRITE
993 error = "Message needs unreceived descriptors";
996 if (header_fds > FileDescriptorSet::kMaxDescriptorsPerMessage)
997 error = "Message requires an excessive number of descriptors";
999 if (error) {
1000 LOG(WARNING) << error
1001 << " channel:" << this
1002 << " message-type:" << msg->type()
1003 << " header()->num_fds:" << header_fds;
1004 #if defined(CHROMIUM_SELINUX)
1005 LOG(WARNING) << "In the case of SELinux this can be caused when "
1006 "using a --user-data-dir to which the default "
1007 "policy doesn't give the renderer access to. ";
1008 #endif // CHROMIUM_SELINUX
1009 // Abort the connection.
1010 ClearInputFDs();
1011 return false;
1014 // The shenaniganery below with &foo.front() requires input_fds_ to have
1015 // contiguous underlying storage (such as a simple array or a std::vector).
1016 // This is why the header warns not to make input_fds_ a deque<>.
1017 msg->file_descriptor_set()->SetDescriptors(&input_fds_.front(),
1018 header_fds);
1019 input_fds_.erase(input_fds_.begin(), input_fds_.begin() + header_fds);
1020 return true;
1023 bool Channel::ChannelImpl::DidEmptyInputBuffers() {
1024 // When the input data buffer is empty, the fds should be too. If this is
1025 // not the case, we probably have a rogue renderer which is trying to fill
1026 // our descriptor table.
1027 return input_fds_.empty();
1030 bool Channel::ChannelImpl::ExtractFileDescriptorsFromMsghdr(msghdr* msg) {
1031 // Check that there are any control messages. On OSX, CMSG_FIRSTHDR will
1032 // return an invalid non-NULL pointer in the case that controllen == 0.
1033 if (msg->msg_controllen == 0)
1034 return true;
1036 for (cmsghdr* cmsg = CMSG_FIRSTHDR(msg);
1037 cmsg;
1038 cmsg = CMSG_NXTHDR(msg, cmsg)) {
1039 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
1040 unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
1041 DCHECK_EQ(0U, payload_len % sizeof(int));
1042 const int* file_descriptors = reinterpret_cast<int*>(CMSG_DATA(cmsg));
1043 unsigned num_file_descriptors = payload_len / 4;
1044 input_fds_.insert(input_fds_.end(),
1045 file_descriptors,
1046 file_descriptors + num_file_descriptors);
1048 // Check this after adding the FDs so we don't leak them.
1049 if (msg->msg_flags & MSG_CTRUNC) {
1050 ClearInputFDs();
1051 return false;
1054 return true;
1058 // No file descriptors found, but that's OK.
1059 return true;
1062 void Channel::ChannelImpl::ClearInputFDs() {
1063 for (size_t i = 0; i < input_fds_.size(); ++i) {
1064 if (HANDLE_EINTR(close(input_fds_[i])) < 0)
1065 PLOG(ERROR) << "close ";
1067 input_fds_.clear();
1070 void Channel::ChannelImpl::HandleHelloMessage(const Message& msg) {
1071 // The Hello message contains only the process id.
1072 PickleIterator iter(msg);
1073 int pid;
1074 if (!msg.ReadInt(&iter, &pid))
1075 NOTREACHED();
1077 #if defined(IPC_USES_READWRITE)
1078 if (mode_ & MODE_SERVER_FLAG) {
1079 // With IPC_USES_READWRITE, the Hello message from the client to the
1080 // server also contains the fd_pipe_, which will be used for all
1081 // subsequent file descriptor passing.
1082 DCHECK_EQ(msg.file_descriptor_set()->size(), 1U);
1083 base::FileDescriptor descriptor;
1084 if (!msg.ReadFileDescriptor(&iter, &descriptor)) {
1085 NOTREACHED();
1087 fd_pipe_ = descriptor.fd;
1088 CHECK(descriptor.auto_close);
1090 #endif // IPC_USES_READWRITE
1091 peer_pid_ = pid;
1092 listener()->OnChannelConnected(pid);
1095 void Channel::ChannelImpl::Close() {
1096 // Close can be called multiple time, so we need to make sure we're
1097 // idempotent.
1099 ResetToAcceptingConnectionState();
1101 if (must_unlink_) {
1102 unlink(pipe_name_.c_str());
1103 must_unlink_ = false;
1105 if (server_listen_pipe_ != -1) {
1106 if (HANDLE_EINTR(close(server_listen_pipe_)) < 0)
1107 DPLOG(ERROR) << "close " << server_listen_pipe_;
1108 server_listen_pipe_ = -1;
1109 // Unregister libevent for the listening socket and close it.
1110 server_listen_connection_watcher_.StopWatchingFileDescriptor();
1113 CloseClientFileDescriptor();
1116 //------------------------------------------------------------------------------
1117 // Channel's methods simply call through to ChannelImpl.
1118 Channel::Channel(const IPC::ChannelHandle& channel_handle, Mode mode,
1119 Listener* listener)
1120 : channel_impl_(new ChannelImpl(channel_handle, mode, listener)) {
1123 Channel::~Channel() {
1124 delete channel_impl_;
1127 bool Channel::Connect() {
1128 return channel_impl_->Connect();
1131 void Channel::Close() {
1132 if (channel_impl_)
1133 channel_impl_->Close();
1136 base::ProcessId Channel::peer_pid() const {
1137 return channel_impl_->peer_pid();
1140 bool Channel::Send(Message* message) {
1141 return channel_impl_->Send(message);
1144 int Channel::GetClientFileDescriptor() const {
1145 return channel_impl_->GetClientFileDescriptor();
1148 int Channel::TakeClientFileDescriptor() {
1149 return channel_impl_->TakeClientFileDescriptor();
1152 bool Channel::AcceptsConnections() const {
1153 return channel_impl_->AcceptsConnections();
1156 bool Channel::HasAcceptedConnection() const {
1157 return channel_impl_->HasAcceptedConnection();
1160 bool Channel::GetClientEuid(uid_t* client_euid) const {
1161 return channel_impl_->GetClientEuid(client_euid);
1164 void Channel::ResetToAcceptingConnectionState() {
1165 channel_impl_->ResetToAcceptingConnectionState();
1168 // static
1169 bool Channel::IsNamedServerInitialized(const std::string& channel_id) {
1170 return ChannelImpl::IsNamedServerInitialized(channel_id);
1173 // static
1174 std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) {
1175 // A random name is sufficient validation on posix systems, so we don't need
1176 // an additional shared secret.
1178 std::string id = prefix;
1179 if (!id.empty())
1180 id.append(".");
1182 return id.append(GenerateUniqueRandomChannelID());
1186 #if defined(OS_LINUX)
1187 // static
1188 void Channel::SetGlobalPid(int pid) {
1189 ChannelImpl::SetGlobalPid(pid);
1191 #endif // OS_LINUX
1193 } // namespace IPC