Changed for loop to c++11 style in chrome/browser/prerender/prerender_local_predictor...
[chromium-blink-merge.git] / ipc / ipc_channel_posix.cc
blobaac7e795257a4f0933e3ede563b5b989eedd01cd
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 <unistd.h>
15 #if defined(OS_OPENBSD)
16 #include <sys/uio.h>
17 #endif
19 #if !defined(OS_NACL_NONSFI)
20 #include <sys/un.h>
21 #endif
23 #include <map>
24 #include <string>
26 #include "base/command_line.h"
27 #include "base/files/file_path.h"
28 #include "base/files/file_util.h"
29 #include "base/location.h"
30 #include "base/logging.h"
31 #include "base/memory/scoped_ptr.h"
32 #include "base/memory/singleton.h"
33 #include "base/posix/eintr_wrapper.h"
34 #include "base/posix/global_descriptors.h"
35 #include "base/process/process_handle.h"
36 #include "base/rand_util.h"
37 #include "base/stl_util.h"
38 #include "base/strings/string_util.h"
39 #include "base/synchronization/lock.h"
40 #include "ipc/ipc_descriptors.h"
41 #include "ipc/ipc_listener.h"
42 #include "ipc/ipc_logging.h"
43 #include "ipc/ipc_message_attachment_set.h"
44 #include "ipc/ipc_message_utils.h"
45 #include "ipc/ipc_platform_file_attachment_posix.h"
46 #include "ipc/ipc_switches.h"
47 #include "ipc/unix_domain_socket_util.h"
49 namespace IPC {
51 // IPC channels on Windows use named pipes (CreateNamedPipe()) with
52 // channel ids as the pipe names. Channels on POSIX use sockets as
53 // pipes These don't quite line up.
55 // When creating a child subprocess we use a socket pair and the parent side of
56 // the fork arranges it such that the initial control channel ends up on the
57 // magic file descriptor kPrimaryIPCChannel in the child. Future
58 // connections (file descriptors) can then be passed via that
59 // connection via sendmsg().
61 // A POSIX IPC channel can also be set up as a server for a bound UNIX domain
62 // socket, and will handle multiple connect and disconnect sequences. Currently
63 // it is limited to one connection at a time.
65 //------------------------------------------------------------------------------
66 namespace {
68 // The PipeMap class works around this quirk related to unit tests:
70 // When running as a server, we install the client socket in a
71 // specific file descriptor number (@kPrimaryIPCChannel). However, we
72 // also have to support the case where we are running unittests in the
73 // same process. (We do not support forking without execing.)
75 // Case 1: normal running
76 // The IPC server object will install a mapping in PipeMap from the
77 // name which it was given to the client pipe. When forking the client, the
78 // GetClientFileDescriptorMapping will ensure that the socket is installed in
79 // the magic slot (@kPrimaryIPCChannel). The client will search for the
80 // mapping, but it won't find any since we are in a new process. Thus the
81 // magic fd number is returned. Once the client connects, the server will
82 // close its copy of the client socket and remove the mapping.
84 // Case 2: unittests - client and server in the same process
85 // The IPC server will install a mapping as before. The client will search
86 // for a mapping and find out. It duplicates the file descriptor and
87 // connects. Once the client connects, the server will close the original
88 // copy of the client socket and remove the mapping. Thus, when the client
89 // object closes, it will close the only remaining copy of the client socket
90 // in the fd table and the server will see EOF on its side.
92 // TODO(port): a client process cannot connect to multiple IPC channels with
93 // this scheme.
95 class PipeMap {
96 public:
97 static PipeMap* GetInstance() {
98 return 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 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, Listener* listener)
186 : ChannelReader(listener),
187 mode_(mode),
188 peer_pid_(base::kNullProcessId),
189 is_blocked_on_write_(false),
190 waiting_connect_(true),
191 message_send_bytes_written_(0),
192 pipe_name_(channel_handle.name),
193 in_dtor_(false),
194 must_unlink_(false) {
195 memset(input_cmsg_buf_, 0, sizeof(input_cmsg_buf_));
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 Close();
209 bool SocketPair(int* fd1, int* fd2) {
210 int pipe_fds[2];
211 if (socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds) != 0) {
212 PLOG(ERROR) << "socketpair()";
213 return false;
216 // Set both ends to be non-blocking.
217 if (fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK) == -1 ||
218 fcntl(pipe_fds[1], F_SETFL, O_NONBLOCK) == -1) {
219 PLOG(ERROR) << "fcntl(O_NONBLOCK)";
220 if (IGNORE_EINTR(close(pipe_fds[0])) < 0)
221 PLOG(ERROR) << "close";
222 if (IGNORE_EINTR(close(pipe_fds[1])) < 0)
223 PLOG(ERROR) << "close";
224 return false;
227 *fd1 = pipe_fds[0];
228 *fd2 = pipe_fds[1];
230 return true;
233 bool ChannelPosix::CreatePipe(
234 const IPC::ChannelHandle& channel_handle) {
235 DCHECK(!server_listen_pipe_.is_valid() && !pipe_.is_valid());
237 // Four possible cases:
238 // 1) It's a channel wrapping a pipe that is given to us.
239 // 2) It's for a named channel, so we create it.
240 // 3) It's for a client that we implement ourself. This is used
241 // in single-process unittesting.
242 // 4) It's the initial IPC channel:
243 // 4a) Client side: Pull the pipe out of the GlobalDescriptors set.
244 // 4b) Server side: create the pipe.
246 base::ScopedFD local_pipe;
247 if (channel_handle.socket.fd != -1) {
248 // Case 1 from comment above.
249 local_pipe.reset(channel_handle.socket.fd);
250 #if defined(IPC_USES_READWRITE)
251 // Test the socket passed into us to make sure it is nonblocking.
252 // We don't want to call read/write on a blocking socket.
253 int value = fcntl(local_pipe.get(), F_GETFL);
254 if (value == -1) {
255 PLOG(ERROR) << "fcntl(F_GETFL) " << pipe_name_;
256 return false;
258 if (!(value & O_NONBLOCK)) {
259 LOG(ERROR) << "Socket " << pipe_name_ << " must be O_NONBLOCK";
260 return false;
262 #endif // IPC_USES_READWRITE
263 } else if (mode_ & MODE_NAMED_FLAG) {
264 #if defined(OS_NACL_NONSFI)
265 LOG(FATAL)
266 << "IPC channels in nacl_helper_nonsfi should not be in NAMED mode.";
267 #else
268 // Case 2 from comment above.
269 int local_pipe_fd = -1;
271 if (mode_ & MODE_SERVER_FLAG) {
272 if (!CreateServerUnixDomainSocket(base::FilePath(pipe_name_),
273 &local_pipe_fd)) {
274 return false;
277 must_unlink_ = true;
278 } else if (mode_ & MODE_CLIENT_FLAG) {
279 if (!CreateClientUnixDomainSocket(base::FilePath(pipe_name_),
280 &local_pipe_fd)) {
281 return false;
283 } else {
284 LOG(ERROR) << "Bad mode: " << mode_;
285 return false;
288 local_pipe.reset(local_pipe_fd);
289 #endif // !defined(OS_NACL_NONSFI)
290 } else {
291 local_pipe.reset(PipeMap::GetInstance()->Lookup(pipe_name_));
292 if (mode_ & MODE_CLIENT_FLAG) {
293 if (local_pipe.is_valid()) {
294 // Case 3 from comment above.
295 // We only allow one connection.
296 local_pipe.reset(HANDLE_EINTR(dup(local_pipe.release())));
297 PipeMap::GetInstance()->Remove(pipe_name_);
298 } else {
299 // Case 4a from comment above.
300 // Guard against inappropriate reuse of the initial IPC channel. If
301 // an IPC channel closes and someone attempts to reuse it by name, the
302 // initial channel must not be recycled here. http://crbug.com/26754.
303 static bool used_initial_channel = false;
304 if (used_initial_channel) {
305 LOG(FATAL) << "Denying attempt to reuse initial IPC channel for "
306 << pipe_name_;
307 return false;
309 used_initial_channel = true;
311 local_pipe.reset(
312 base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel));
314 } else if (mode_ & MODE_SERVER_FLAG) {
315 // Case 4b from comment above.
316 if (local_pipe.is_valid()) {
317 LOG(ERROR) << "Server already exists for " << pipe_name_;
318 // This is a client side pipe registered by other server and
319 // shouldn't be closed.
320 ignore_result(local_pipe.release());
321 return false;
323 base::AutoLock lock(client_pipe_lock_);
324 int local_pipe_fd = -1, client_pipe_fd = -1;
325 if (!SocketPair(&local_pipe_fd, &client_pipe_fd))
326 return false;
327 local_pipe.reset(local_pipe_fd);
328 client_pipe_.reset(client_pipe_fd);
329 PipeMap::GetInstance()->Insert(pipe_name_, client_pipe_fd);
330 } else {
331 LOG(ERROR) << "Bad mode: " << mode_;
332 return false;
336 #if defined(IPC_USES_READWRITE)
337 // Create a dedicated socketpair() for exchanging file descriptors.
338 // See comments for IPC_USES_READWRITE for details.
339 if (mode_ & MODE_CLIENT_FLAG) {
340 int fd_pipe_fd = 1, remote_fd_pipe_fd = -1;
341 if (!SocketPair(&fd_pipe_fd, &remote_fd_pipe_fd)) {
342 return false;
345 fd_pipe_.reset(fd_pipe_fd);
346 remote_fd_pipe_.reset(remote_fd_pipe_fd);
348 #endif // IPC_USES_READWRITE
350 if ((mode_ & MODE_SERVER_FLAG) && (mode_ & MODE_NAMED_FLAG)) {
351 #if defined(OS_NACL_NONSFI)
352 LOG(FATAL) << "IPC channels in nacl_helper_nonsfi "
353 << "should not be in NAMED or SERVER mode.";
354 #else
355 server_listen_pipe_.reset(local_pipe.release());
356 #endif
357 } else {
358 pipe_.reset(local_pipe.release());
360 return true;
363 bool ChannelPosix::Connect() {
364 if (!server_listen_pipe_.is_valid() && !pipe_.is_valid()) {
365 DLOG(WARNING) << "Channel creation failed: " << pipe_name_;
366 return false;
369 bool did_connect = true;
370 if (server_listen_pipe_.is_valid()) {
371 #if defined(OS_NACL_NONSFI)
372 LOG(FATAL) << "IPC channels in nacl_helper_nonsfi "
373 << "should always be in client mode.";
374 #else
375 // Watch the pipe for connections, and turn any connections into
376 // active sockets.
377 base::MessageLoopForIO::current()->WatchFileDescriptor(
378 server_listen_pipe_.get(),
379 true,
380 base::MessageLoopForIO::WATCH_READ,
381 &server_listen_connection_watcher_,
382 this);
383 #endif
384 } else {
385 did_connect = AcceptConnection();
387 return did_connect;
390 void ChannelPosix::CloseFileDescriptors(Message* msg) {
391 #if defined(OS_MACOSX)
392 // There is a bug on OSX which makes it dangerous to close
393 // a file descriptor while it is in transit. So instead we
394 // store the file descriptor in a set and send a message to
395 // the recipient, which is queued AFTER the message that
396 // sent the FD. The recipient will reply to the message,
397 // letting us know that it is now safe to close the file
398 // descriptor. For more information, see:
399 // http://crbug.com/298276
400 std::vector<int> to_close;
401 msg->attachment_set()->ReleaseFDsToClose(&to_close);
402 for (size_t i = 0; i < to_close.size(); i++) {
403 fds_to_close_.insert(to_close[i]);
404 QueueCloseFDMessage(to_close[i], 2);
406 #else
407 msg->attachment_set()->CommitAll();
408 #endif
411 bool ChannelPosix::ProcessOutgoingMessages() {
412 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
413 // no connection?
414 if (output_queue_.empty())
415 return true;
417 if (!pipe_.is_valid())
418 return false;
420 // Write out all the messages we can till the write blocks or there are no
421 // more outgoing messages.
422 while (!output_queue_.empty()) {
423 Message* msg = output_queue_.front();
425 size_t amt_to_write = msg->size() - message_send_bytes_written_;
426 DCHECK_NE(0U, amt_to_write);
427 const char* out_bytes = reinterpret_cast<const char*>(msg->data()) +
428 message_send_bytes_written_;
430 struct msghdr msgh = {0};
431 struct iovec iov = {const_cast<char*>(out_bytes), amt_to_write};
432 msgh.msg_iov = &iov;
433 msgh.msg_iovlen = 1;
434 char buf[CMSG_SPACE(sizeof(int) *
435 MessageAttachmentSet::kMaxDescriptorsPerMessage)];
437 ssize_t bytes_written = 1;
438 int fd_written = -1;
440 if (message_send_bytes_written_ == 0 && !msg->attachment_set()->empty()) {
441 // This is the first chunk of a message which has descriptors to send
442 struct cmsghdr *cmsg;
443 const unsigned num_fds = msg->attachment_set()->size();
445 DCHECK(num_fds <= MessageAttachmentSet::kMaxDescriptorsPerMessage);
446 if (msg->attachment_set()->ContainsDirectoryDescriptor()) {
447 LOG(FATAL) << "Panic: attempting to transport directory descriptor over"
448 " IPC. Aborting to maintain sandbox isolation.";
449 // If you have hit this then something tried to send a file descriptor
450 // to a directory over an IPC channel. Since IPC channels span
451 // sandboxes this is very bad: the receiving process can use openat
452 // with ".." elements in the path in order to reach the real
453 // filesystem.
456 msgh.msg_control = buf;
457 msgh.msg_controllen = CMSG_SPACE(sizeof(int) * num_fds);
458 cmsg = CMSG_FIRSTHDR(&msgh);
459 cmsg->cmsg_level = SOL_SOCKET;
460 cmsg->cmsg_type = SCM_RIGHTS;
461 cmsg->cmsg_len = CMSG_LEN(sizeof(int) * num_fds);
462 msg->attachment_set()->PeekDescriptors(
463 reinterpret_cast<int*>(CMSG_DATA(cmsg)));
464 msgh.msg_controllen = cmsg->cmsg_len;
466 // DCHECK_LE above already checks that
467 // num_fds < kMaxDescriptorsPerMessage so no danger of overflow.
468 msg->header()->num_fds = static_cast<uint16>(num_fds);
470 #if defined(IPC_USES_READWRITE)
471 if (!IsHelloMessage(*msg)) {
472 // Only the Hello message sends the file descriptor with the message.
473 // Subsequently, we can send file descriptors on the dedicated
474 // fd_pipe_ which makes Seccomp sandbox operation more efficient.
475 struct iovec fd_pipe_iov = { const_cast<char *>(""), 1 };
476 msgh.msg_iov = &fd_pipe_iov;
477 fd_written = fd_pipe_.get();
478 bytes_written =
479 HANDLE_EINTR(sendmsg(fd_pipe_.get(), &msgh, MSG_DONTWAIT));
480 msgh.msg_iov = &iov;
481 msgh.msg_controllen = 0;
482 if (bytes_written > 0) {
483 CloseFileDescriptors(msg);
486 #endif // IPC_USES_READWRITE
489 if (bytes_written == 1) {
490 fd_written = pipe_.get();
491 #if defined(IPC_USES_READWRITE)
492 if ((mode_ & MODE_CLIENT_FLAG) && IsHelloMessage(*msg)) {
493 DCHECK_EQ(msg->attachment_set()->size(), 1U);
495 if (!msgh.msg_controllen) {
496 bytes_written =
497 HANDLE_EINTR(write(pipe_.get(), out_bytes, amt_to_write));
498 } else
499 #endif // IPC_USES_READWRITE
501 bytes_written = HANDLE_EINTR(sendmsg(pipe_.get(), &msgh, MSG_DONTWAIT));
504 if (bytes_written > 0)
505 CloseFileDescriptors(msg);
507 if (bytes_written < 0 && !SocketWriteErrorIsRecoverable()) {
508 // We can't close the pipe here, because calling OnChannelError
509 // may destroy this object, and that would be bad if we are
510 // called from Send(). Instead, we return false and hope the
511 // caller will close the pipe. If they do not, the pipe will
512 // still be closed next time OnFileCanReadWithoutBlocking is
513 // called.
514 #if defined(OS_MACOSX)
515 // On OSX writing to a pipe with no listener returns EPERM.
516 if (errno == EPERM) {
517 return false;
519 #endif // OS_MACOSX
520 if (errno == EPIPE) {
521 return false;
523 PLOG(ERROR) << "pipe error on "
524 << fd_written
525 << " Currently writing message of size: "
526 << msg->size();
527 return false;
530 if (static_cast<size_t>(bytes_written) != amt_to_write) {
531 if (bytes_written > 0) {
532 // If write() fails with EAGAIN then bytes_written will be -1.
533 message_send_bytes_written_ += bytes_written;
536 // Tell libevent to call us back once things are unblocked.
537 is_blocked_on_write_ = true;
538 base::MessageLoopForIO::current()->WatchFileDescriptor(
539 pipe_.get(),
540 false, // One shot
541 base::MessageLoopForIO::WATCH_WRITE,
542 &write_watcher_,
543 this);
544 return true;
545 } else {
546 message_send_bytes_written_ = 0;
548 // Message sent OK!
549 DVLOG(2) << "sent message @" << msg << " on channel @" << this
550 << " with type " << msg->type() << " on fd " << pipe_.get();
551 delete output_queue_.front();
552 output_queue_.pop();
555 return true;
558 bool ChannelPosix::Send(Message* message) {
559 DCHECK(!message->HasMojoHandles());
560 DVLOG(2) << "sending message @" << message << " on channel @" << this
561 << " with type " << message->type()
562 << " (" << output_queue_.size() << " in queue)";
564 #ifdef IPC_MESSAGE_LOG_ENABLED
565 Logging::GetInstance()->OnSendMessage(message, "");
566 #endif // IPC_MESSAGE_LOG_ENABLED
568 message->TraceMessageBegin();
569 output_queue_.push(message);
570 if (!is_blocked_on_write_ && !waiting_connect_) {
571 return ProcessOutgoingMessages();
574 return true;
577 int ChannelPosix::GetClientFileDescriptor() const {
578 base::AutoLock lock(client_pipe_lock_);
579 return client_pipe_.get();
582 base::ScopedFD ChannelPosix::TakeClientFileDescriptor() {
583 base::AutoLock lock(client_pipe_lock_);
584 if (!client_pipe_.is_valid())
585 return base::ScopedFD();
586 PipeMap::GetInstance()->Remove(pipe_name_);
587 return client_pipe_.Pass();
590 void ChannelPosix::CloseClientFileDescriptor() {
591 base::AutoLock lock(client_pipe_lock_);
592 if (!client_pipe_.is_valid())
593 return;
594 PipeMap::GetInstance()->Remove(pipe_name_);
595 client_pipe_.reset();
598 bool ChannelPosix::AcceptsConnections() const {
599 return server_listen_pipe_.is_valid();
602 bool ChannelPosix::HasAcceptedConnection() const {
603 return AcceptsConnections() && pipe_.is_valid();
606 #if !defined(OS_NACL_NONSFI)
607 // GetPeerEuid is not supported in nacl_helper_nonsfi.
608 bool ChannelPosix::GetPeerEuid(uid_t* peer_euid) const {
609 DCHECK(!(mode_ & MODE_SERVER) || HasAcceptedConnection());
610 return IPC::GetPeerEuid(pipe_.get(), peer_euid);
612 #endif
614 void ChannelPosix::ResetToAcceptingConnectionState() {
615 // Unregister libevent for the unix domain socket and close it.
616 read_watcher_.StopWatchingFileDescriptor();
617 write_watcher_.StopWatchingFileDescriptor();
618 ResetSafely(&pipe_);
619 #if defined(IPC_USES_READWRITE)
620 fd_pipe_.reset();
621 remote_fd_pipe_.reset();
622 #endif // IPC_USES_READWRITE
624 while (!output_queue_.empty()) {
625 Message* m = output_queue_.front();
626 output_queue_.pop();
627 delete m;
630 // Close any outstanding, received file descriptors.
631 ClearInputFDs();
633 #if defined(OS_MACOSX)
634 // Clear any outstanding, sent file descriptors.
635 for (std::set<int>::iterator i = fds_to_close_.begin();
636 i != fds_to_close_.end();
637 ++i) {
638 if (IGNORE_EINTR(close(*i)) < 0)
639 PLOG(ERROR) << "close";
641 fds_to_close_.clear();
642 #endif
645 // static
646 bool ChannelPosix::IsNamedServerInitialized(
647 const std::string& channel_id) {
648 return base::PathExists(base::FilePath(channel_id));
651 #if defined(OS_LINUX)
652 // static
653 void ChannelPosix::SetGlobalPid(int pid) {
654 global_pid_ = pid;
656 #endif // OS_LINUX
658 // Called by libevent when we can read from the pipe without blocking.
659 void ChannelPosix::OnFileCanReadWithoutBlocking(int fd) {
660 if (fd == server_listen_pipe_.get()) {
661 #if defined(OS_NACL_NONSFI)
662 LOG(FATAL)
663 << "IPC channels in nacl_helper_nonsfi should not be SERVER mode.";
664 #else
665 int new_pipe = 0;
666 if (!ServerAcceptConnection(server_listen_pipe_.get(), &new_pipe) ||
667 new_pipe < 0) {
668 Close();
669 listener()->OnChannelListenError();
672 if (pipe_.is_valid()) {
673 // We already have a connection. We only handle one at a time.
674 // close our new descriptor.
675 if (HANDLE_EINTR(shutdown(new_pipe, SHUT_RDWR)) < 0)
676 DPLOG(ERROR) << "shutdown " << pipe_name_;
677 if (IGNORE_EINTR(close(new_pipe)) < 0)
678 DPLOG(ERROR) << "close " << pipe_name_;
679 listener()->OnChannelDenied();
680 return;
682 pipe_.reset(new_pipe);
684 if ((mode_ & MODE_OPEN_ACCESS_FLAG) == 0) {
685 // Verify that the IPC channel peer is running as the same user.
686 uid_t client_euid;
687 if (!GetPeerEuid(&client_euid)) {
688 DLOG(ERROR) << "Unable to query client euid";
689 ResetToAcceptingConnectionState();
690 return;
692 if (client_euid != geteuid()) {
693 DLOG(WARNING) << "Client euid is not authorised";
694 ResetToAcceptingConnectionState();
695 return;
699 if (!AcceptConnection()) {
700 NOTREACHED() << "AcceptConnection should not fail on server";
702 waiting_connect_ = false;
703 #endif
704 } else if (fd == pipe_) {
705 if (waiting_connect_ && (mode_ & MODE_SERVER_FLAG)) {
706 waiting_connect_ = false;
708 if (!ProcessIncomingMessages()) {
709 // ClosePipeOnError may delete this object, so we mustn't call
710 // ProcessOutgoingMessages.
711 ClosePipeOnError();
712 return;
714 } else {
715 NOTREACHED() << "Unknown pipe " << fd;
718 // If we're a server and handshaking, then we want to make sure that we
719 // only send our handshake message after we've processed the client's.
720 // This gives us a chance to kill the client if the incoming handshake
721 // is invalid. This also flushes any closefd messages.
722 if (!is_blocked_on_write_) {
723 if (!ProcessOutgoingMessages()) {
724 ClosePipeOnError();
729 // Called by libevent when we can write to the pipe without blocking.
730 void ChannelPosix::OnFileCanWriteWithoutBlocking(int fd) {
731 DCHECK_EQ(pipe_.get(), fd);
732 is_blocked_on_write_ = false;
733 if (!ProcessOutgoingMessages()) {
734 ClosePipeOnError();
738 bool ChannelPosix::AcceptConnection() {
739 base::MessageLoopForIO::current()->WatchFileDescriptor(
740 pipe_.get(),
741 true,
742 base::MessageLoopForIO::WATCH_READ,
743 &read_watcher_,
744 this);
745 QueueHelloMessage();
747 if (mode_ & MODE_CLIENT_FLAG) {
748 // If we are a client we want to send a hello message out immediately.
749 // In server mode we will send a hello message when we receive one from a
750 // client.
751 waiting_connect_ = false;
752 return ProcessOutgoingMessages();
753 } else if (mode_ & MODE_SERVER_FLAG) {
754 waiting_connect_ = true;
755 return true;
756 } else {
757 NOTREACHED();
758 return false;
762 void ChannelPosix::ClosePipeOnError() {
763 if (HasAcceptedConnection()) {
764 ResetToAcceptingConnectionState();
765 listener()->OnChannelError();
766 } else {
767 Close();
768 if (AcceptsConnections()) {
769 listener()->OnChannelListenError();
770 } else {
771 listener()->OnChannelError();
776 int ChannelPosix::GetHelloMessageProcId() const {
777 #if defined(OS_NACL_NONSFI)
778 // In nacl_helper_nonsfi, getpid() invoked by GetCurrentProcId() is not
779 // allowed and would cause a SIGSYS crash because of the seccomp sandbox.
780 return -1;
781 #else
782 int pid = base::GetCurrentProcId();
783 #if defined(OS_LINUX)
784 // Our process may be in a sandbox with a separate PID namespace.
785 if (global_pid_) {
786 pid = global_pid_;
788 #endif // defined(OS_LINUX)
789 return pid;
790 #endif // defined(OS_NACL_NONSFI)
793 void ChannelPosix::QueueHelloMessage() {
794 // Create the Hello message
795 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
796 HELLO_MESSAGE_TYPE,
797 IPC::Message::PRIORITY_NORMAL));
798 if (!msg->WriteInt(GetHelloMessageProcId())) {
799 NOTREACHED() << "Unable to pickle hello message proc id";
801 #if defined(IPC_USES_READWRITE)
802 scoped_ptr<Message> hello;
803 if (remote_fd_pipe_.is_valid()) {
804 if (!msg->WriteAttachment(
805 new internal::PlatformFileAttachment(remote_fd_pipe_.get()))) {
806 NOTREACHED() << "Unable to pickle hello message file descriptors";
808 DCHECK_EQ(msg->attachment_set()->size(), 1U);
810 #endif // IPC_USES_READWRITE
811 output_queue_.push(msg.release());
814 ChannelPosix::ReadState ChannelPosix::ReadData(
815 char* buffer,
816 int buffer_len,
817 int* bytes_read) {
818 if (!pipe_.is_valid())
819 return READ_FAILED;
821 struct msghdr msg = {0};
823 struct iovec iov = {buffer, static_cast<size_t>(buffer_len)};
824 msg.msg_iov = &iov;
825 msg.msg_iovlen = 1;
827 msg.msg_control = input_cmsg_buf_;
829 // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
830 // is waiting on the pipe.
831 #if defined(IPC_USES_READWRITE)
832 if (fd_pipe_.is_valid()) {
833 *bytes_read = HANDLE_EINTR(read(pipe_.get(), buffer, buffer_len));
834 msg.msg_controllen = 0;
835 } else
836 #endif // IPC_USES_READWRITE
838 msg.msg_controllen = sizeof(input_cmsg_buf_);
839 *bytes_read = HANDLE_EINTR(recvmsg(pipe_.get(), &msg, MSG_DONTWAIT));
841 if (*bytes_read < 0) {
842 if (errno == EAGAIN) {
843 return READ_PENDING;
844 #if defined(OS_MACOSX)
845 } else if (errno == EPERM) {
846 // On OSX, reading from a pipe with no listener returns EPERM
847 // treat this as a special case to prevent spurious error messages
848 // to the console.
849 return READ_FAILED;
850 #endif // OS_MACOSX
851 } else if (errno == ECONNRESET || errno == EPIPE) {
852 return READ_FAILED;
853 } else {
854 PLOG(ERROR) << "pipe error (" << pipe_.get() << ")";
855 return READ_FAILED;
857 } else if (*bytes_read == 0) {
858 // The pipe has closed...
859 return READ_FAILED;
861 DCHECK(*bytes_read);
863 CloseClientFileDescriptor();
865 // Read any file descriptors from the message.
866 if (!ExtractFileDescriptorsFromMsghdr(&msg))
867 return READ_FAILED;
868 return READ_SUCCEEDED;
871 #if defined(IPC_USES_READWRITE)
872 bool ChannelPosix::ReadFileDescriptorsFromFDPipe() {
873 char dummy;
874 struct iovec fd_pipe_iov = { &dummy, 1 };
876 struct msghdr msg = { 0 };
877 msg.msg_iov = &fd_pipe_iov;
878 msg.msg_iovlen = 1;
879 msg.msg_control = input_cmsg_buf_;
880 msg.msg_controllen = sizeof(input_cmsg_buf_);
881 ssize_t bytes_received =
882 HANDLE_EINTR(recvmsg(fd_pipe_.get(), &msg, MSG_DONTWAIT));
884 if (bytes_received != 1)
885 return true; // No message waiting.
887 if (!ExtractFileDescriptorsFromMsghdr(&msg))
888 return false;
889 return true;
891 #endif
893 // On Posix, we need to fix up the file descriptors before the input message
894 // is dispatched.
896 // This will read from the input_fds_ (READWRITE mode only) and read more
897 // handles from the FD pipe if necessary.
898 bool ChannelPosix::WillDispatchInputMessage(Message* msg) {
899 uint16 header_fds = msg->header()->num_fds;
900 if (!header_fds)
901 return true; // Nothing to do.
903 // The message has file descriptors.
904 const char* error = NULL;
905 if (header_fds > input_fds_.size()) {
906 // The message has been completely received, but we didn't get
907 // enough file descriptors.
908 #if defined(IPC_USES_READWRITE)
909 if (!ReadFileDescriptorsFromFDPipe())
910 return false;
911 if (header_fds > input_fds_.size())
912 #endif // IPC_USES_READWRITE
913 error = "Message needs unreceived descriptors";
916 if (header_fds > MessageAttachmentSet::kMaxDescriptorsPerMessage)
917 error = "Message requires an excessive number of descriptors";
919 if (error) {
920 LOG(WARNING) << error
921 << " channel:" << this
922 << " message-type:" << msg->type()
923 << " header()->num_fds:" << header_fds;
924 // Abort the connection.
925 ClearInputFDs();
926 return false;
929 // The shenaniganery below with &foo.front() requires input_fds_ to have
930 // contiguous underlying storage (such as a simple array or a std::vector).
931 // This is why the header warns not to make input_fds_ a deque<>.
932 msg->attachment_set()->AddDescriptorsToOwn(&input_fds_.front(), header_fds);
933 input_fds_.erase(input_fds_.begin(), input_fds_.begin() + header_fds);
934 return true;
937 bool ChannelPosix::DidEmptyInputBuffers() {
938 // When the input data buffer is empty, the fds should be too. If this is
939 // not the case, we probably have a rogue renderer which is trying to fill
940 // our descriptor table.
941 return input_fds_.empty();
944 bool ChannelPosix::ExtractFileDescriptorsFromMsghdr(msghdr* msg) {
945 // Check that there are any control messages. On OSX, CMSG_FIRSTHDR will
946 // return an invalid non-NULL pointer in the case that controllen == 0.
947 if (msg->msg_controllen == 0)
948 return true;
950 for (cmsghdr* cmsg = CMSG_FIRSTHDR(msg);
951 cmsg;
952 cmsg = CMSG_NXTHDR(msg, cmsg)) {
953 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
954 unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
955 DCHECK_EQ(0U, payload_len % sizeof(int));
956 const int* file_descriptors = reinterpret_cast<int*>(CMSG_DATA(cmsg));
957 unsigned num_file_descriptors = payload_len / 4;
958 input_fds_.insert(input_fds_.end(),
959 file_descriptors,
960 file_descriptors + num_file_descriptors);
962 // Check this after adding the FDs so we don't leak them.
963 if (msg->msg_flags & MSG_CTRUNC) {
964 ClearInputFDs();
965 return false;
968 return true;
972 // No file descriptors found, but that's OK.
973 return true;
976 void ChannelPosix::ClearInputFDs() {
977 for (size_t i = 0; i < input_fds_.size(); ++i) {
978 if (IGNORE_EINTR(close(input_fds_[i])) < 0)
979 PLOG(ERROR) << "close ";
981 input_fds_.clear();
984 void ChannelPosix::QueueCloseFDMessage(int fd, int hops) {
985 switch (hops) {
986 case 1:
987 case 2: {
988 // Create the message
989 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
990 CLOSE_FD_MESSAGE_TYPE,
991 IPC::Message::PRIORITY_NORMAL));
992 if (!msg->WriteInt(hops - 1) || !msg->WriteInt(fd)) {
993 NOTREACHED() << "Unable to pickle close fd.";
995 // Send(msg.release());
996 output_queue_.push(msg.release());
997 break;
1000 default:
1001 NOTREACHED();
1002 break;
1006 void ChannelPosix::HandleInternalMessage(const Message& msg) {
1007 // The Hello message contains only the process id.
1008 PickleIterator iter(msg);
1010 switch (msg.type()) {
1011 default:
1012 NOTREACHED();
1013 break;
1015 case Channel::HELLO_MESSAGE_TYPE:
1016 int pid;
1017 if (!iter.ReadInt(&pid))
1018 NOTREACHED();
1020 #if defined(IPC_USES_READWRITE)
1021 if (mode_ & MODE_SERVER_FLAG) {
1022 // With IPC_USES_READWRITE, the Hello message from the client to the
1023 // server also contains the fd_pipe_, which will be used for all
1024 // subsequent file descriptor passing.
1025 DCHECK_EQ(msg.attachment_set()->size(), 1U);
1026 scoped_refptr<MessageAttachment> attachment;
1027 if (!msg.ReadAttachment(&iter, &attachment)) {
1028 NOTREACHED();
1030 fd_pipe_.reset(attachment->TakePlatformFile());
1032 #endif // IPC_USES_READWRITE
1033 peer_pid_ = pid;
1034 listener()->OnChannelConnected(pid);
1035 break;
1037 #if defined(OS_MACOSX)
1038 case Channel::CLOSE_FD_MESSAGE_TYPE:
1039 int fd, hops;
1040 if (!iter.ReadInt(&hops))
1041 NOTREACHED();
1042 if (!iter.ReadInt(&fd))
1043 NOTREACHED();
1044 if (hops == 0) {
1045 if (fds_to_close_.erase(fd) > 0) {
1046 if (IGNORE_EINTR(close(fd)) < 0)
1047 PLOG(ERROR) << "close";
1048 } else {
1049 NOTREACHED();
1051 } else {
1052 QueueCloseFDMessage(fd, hops);
1054 break;
1055 #endif
1059 void ChannelPosix::Close() {
1060 // Close can be called multiple time, so we need to make sure we're
1061 // idempotent.
1063 ResetToAcceptingConnectionState();
1065 if (must_unlink_) {
1066 unlink(pipe_name_.c_str());
1067 must_unlink_ = false;
1070 if (server_listen_pipe_.is_valid()) {
1071 #if defined(OS_NACL_NONSFI)
1072 LOG(FATAL)
1073 << "IPC channels in nacl_helper_nonsfi should not be SERVER mode.";
1074 #else
1075 server_listen_pipe_.reset();
1076 // Unregister libevent for the listening socket and close it.
1077 server_listen_connection_watcher_.StopWatchingFileDescriptor();
1078 #endif
1081 CloseClientFileDescriptor();
1084 base::ProcessId ChannelPosix::GetPeerPID() const {
1085 return peer_pid_;
1088 base::ProcessId ChannelPosix::GetSelfPID() const {
1089 return GetHelloMessageProcId();
1092 void ChannelPosix::ResetSafely(base::ScopedFD* fd) {
1093 if (!in_dtor_) {
1094 fd->reset();
1095 return;
1098 // crbug.com/449233
1099 // The CL [1] tightened the error check for closing FDs, but it turned
1100 // out that there are existing cases that hit the newly added check.
1101 // ResetSafely() is the workaround for that crash, turning it from
1102 // from PCHECK() to DPCHECK() so that it doesn't crash in production.
1103 // [1] https://crrev.com/ce44fef5fd60dd2be5c587d4b084bdcd36adcee4
1104 int fd_to_close = fd->release();
1105 if (-1 != fd_to_close) {
1106 int rv = IGNORE_EINTR(close(fd_to_close));
1107 DPCHECK(0 == rv);
1111 //------------------------------------------------------------------------------
1112 // Channel's methods
1114 // static
1115 scoped_ptr<Channel> Channel::Create(
1116 const IPC::ChannelHandle &channel_handle, Mode mode, Listener* listener) {
1117 return make_scoped_ptr(new ChannelPosix(channel_handle, mode, listener));
1120 // static
1121 std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) {
1122 // A random name is sufficient validation on posix systems, so we don't need
1123 // an additional shared secret.
1125 std::string id = prefix;
1126 if (!id.empty())
1127 id.append(".");
1129 return id.append(GenerateUniqueRandomChannelID());
1133 bool Channel::IsNamedServerInitialized(
1134 const std::string& channel_id) {
1135 return ChannelPosix::IsNamedServerInitialized(channel_id);
1138 #if defined(OS_LINUX)
1139 // static
1140 void Channel::SetGlobalPid(int pid) {
1141 ChannelPosix::SetGlobalPid(pid);
1143 #endif // OS_LINUX
1145 } // namespace IPC