Use GuestView embedder when determing the print preview dialog dimensions.
[chromium-blink-merge.git] / ipc / ipc_channel_posix.cc
blobc347b15c9e55ab4b5714df9f14d813f785baa89e
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_switches.h"
46 #include "ipc/unix_domain_socket_util.h"
48 namespace IPC {
50 // IPC channels on Windows use named pipes (CreateNamedPipe()) with
51 // channel ids as the pipe names. Channels on POSIX use sockets as
52 // pipes These don't quite line up.
54 // When creating a child subprocess we use a socket pair and the parent side of
55 // the fork arranges it such that the initial control channel ends up on the
56 // magic file descriptor kPrimaryIPCChannel in the child. Future
57 // connections (file descriptors) can then be passed via that
58 // connection via sendmsg().
60 // A POSIX IPC channel can also be set up as a server for a bound UNIX domain
61 // socket, and will handle multiple connect and disconnect sequences. Currently
62 // it is limited to one connection at a time.
64 //------------------------------------------------------------------------------
65 namespace {
67 // The PipeMap class works around this quirk related to unit tests:
69 // When running as a server, we install the client socket in a
70 // specific file descriptor number (@kPrimaryIPCChannel). However, we
71 // also have to support the case where we are running unittests in the
72 // same process. (We do not support forking without execing.)
74 // Case 1: normal running
75 // The IPC server object will install a mapping in PipeMap from the
76 // name which it was given to the client pipe. When forking the client, the
77 // GetClientFileDescriptorMapping will ensure that the socket is installed in
78 // the magic slot (@kPrimaryIPCChannel). The client will search for the
79 // mapping, but it won't find any since we are in a new process. Thus the
80 // magic fd number is returned. Once the client connects, the server will
81 // close its copy of the client socket and remove the mapping.
83 // Case 2: unittests - client and server in the same process
84 // The IPC server will install a mapping as before. The client will search
85 // for a mapping and find out. It duplicates the file descriptor and
86 // connects. Once the client connects, the server will close the original
87 // copy of the client socket and remove the mapping. Thus, when the client
88 // object closes, it will close the only remaining copy of the client socket
89 // in the fd table and the server will see EOF on its side.
91 // TODO(port): a client process cannot connect to multiple IPC channels with
92 // this scheme.
94 class PipeMap {
95 public:
96 static PipeMap* GetInstance() {
97 return Singleton<PipeMap>::get();
100 ~PipeMap() {
101 // Shouldn't have left over pipes.
102 DCHECK(map_.empty());
105 // Lookup a given channel id. Return -1 if not found.
106 int Lookup(const std::string& channel_id) {
107 base::AutoLock locked(lock_);
109 ChannelToFDMap::const_iterator i = map_.find(channel_id);
110 if (i == map_.end())
111 return -1;
112 return i->second;
115 // Remove the mapping for the given channel id. No error is signaled if the
116 // channel_id doesn't exist
117 void Remove(const std::string& channel_id) {
118 base::AutoLock locked(lock_);
119 map_.erase(channel_id);
122 // Insert a mapping from @channel_id to @fd. It's a fatal error to insert a
123 // mapping if one already exists for the given channel_id
124 void Insert(const std::string& channel_id, int fd) {
125 base::AutoLock locked(lock_);
126 DCHECK_NE(-1, fd);
128 ChannelToFDMap::const_iterator i = map_.find(channel_id);
129 CHECK(i == map_.end()) << "Creating second IPC server (fd " << fd << ") "
130 << "for '" << channel_id << "' while first "
131 << "(fd " << i->second << ") still exists";
132 map_[channel_id] = fd;
135 private:
136 base::Lock lock_;
137 typedef std::map<std::string, int> ChannelToFDMap;
138 ChannelToFDMap map_;
140 friend struct DefaultSingletonTraits<PipeMap>;
141 #if defined(OS_ANDROID)
142 friend void ::IPC::Channel::NotifyProcessForkedForTesting();
143 #endif
146 //------------------------------------------------------------------------------
148 bool SocketWriteErrorIsRecoverable() {
149 #if defined(OS_MACOSX)
150 // On OS X if sendmsg() is trying to send fds between processes and there
151 // isn't enough room in the output buffer to send the fd structure over
152 // atomically then EMSGSIZE is returned.
154 // EMSGSIZE presents a problem since the system APIs can only call us when
155 // there's room in the socket buffer and not when there is "enough" room.
157 // The current behavior is to return to the event loop when EMSGSIZE is
158 // received and hopefull service another FD. This is however still
159 // technically a busy wait since the event loop will call us right back until
160 // the receiver has read enough data to allow passing the FD over atomically.
161 return errno == EAGAIN || errno == EMSGSIZE;
162 #else
163 return errno == EAGAIN;
164 #endif // OS_MACOSX
167 } // namespace
169 #if defined(OS_ANDROID)
170 // When we fork for simple tests on Android, we can't 'exec', so we need to
171 // reset these entries manually to get the expected testing behavior.
172 void Channel::NotifyProcessForkedForTesting() {
173 PipeMap::GetInstance()->map_.clear();
175 #endif
177 //------------------------------------------------------------------------------
179 #if defined(OS_LINUX)
180 int ChannelPosix::global_pid_ = 0;
181 #endif // OS_LINUX
183 ChannelPosix::ChannelPosix(const IPC::ChannelHandle& channel_handle,
184 Mode mode, Listener* listener)
185 : ChannelReader(listener),
186 mode_(mode),
187 peer_pid_(base::kNullProcessId),
188 is_blocked_on_write_(false),
189 waiting_connect_(true),
190 message_send_bytes_written_(0),
191 pipe_name_(channel_handle.name),
192 must_unlink_(false) {
193 memset(input_cmsg_buf_, 0, sizeof(input_cmsg_buf_));
194 if (!CreatePipe(channel_handle)) {
195 // The pipe may have been closed already.
196 const char *modestr = (mode_ & MODE_SERVER_FLAG) ? "server" : "client";
197 LOG(WARNING) << "Unable to create pipe named \"" << channel_handle.name
198 << "\" in " << modestr << " mode";
202 ChannelPosix::~ChannelPosix() {
203 Close();
206 bool SocketPair(int* fd1, int* fd2) {
207 int pipe_fds[2];
208 if (socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds) != 0) {
209 PLOG(ERROR) << "socketpair()";
210 return false;
213 // Set both ends to be non-blocking.
214 if (fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK) == -1 ||
215 fcntl(pipe_fds[1], F_SETFL, O_NONBLOCK) == -1) {
216 PLOG(ERROR) << "fcntl(O_NONBLOCK)";
217 if (IGNORE_EINTR(close(pipe_fds[0])) < 0)
218 PLOG(ERROR) << "close";
219 if (IGNORE_EINTR(close(pipe_fds[1])) < 0)
220 PLOG(ERROR) << "close";
221 return false;
224 *fd1 = pipe_fds[0];
225 *fd2 = pipe_fds[1];
227 return true;
230 bool ChannelPosix::CreatePipe(
231 const IPC::ChannelHandle& channel_handle) {
232 DCHECK(!server_listen_pipe_.is_valid() && !pipe_.is_valid());
234 // Four possible cases:
235 // 1) It's a channel wrapping a pipe that is given to us.
236 // 2) It's for a named channel, so we create it.
237 // 3) It's for a client that we implement ourself. This is used
238 // in single-process unittesting.
239 // 4) It's the initial IPC channel:
240 // 4a) Client side: Pull the pipe out of the GlobalDescriptors set.
241 // 4b) Server side: create the pipe.
243 base::ScopedFD local_pipe;
244 if (channel_handle.socket.fd != -1) {
245 // Case 1 from comment above.
246 local_pipe.reset(channel_handle.socket.fd);
247 #if defined(IPC_USES_READWRITE)
248 // Test the socket passed into us to make sure it is nonblocking.
249 // We don't want to call read/write on a blocking socket.
250 int value = fcntl(local_pipe.get(), F_GETFL);
251 if (value == -1) {
252 PLOG(ERROR) << "fcntl(F_GETFL) " << pipe_name_;
253 return false;
255 if (!(value & O_NONBLOCK)) {
256 LOG(ERROR) << "Socket " << pipe_name_ << " must be O_NONBLOCK";
257 return false;
259 #endif // IPC_USES_READWRITE
260 } else if (mode_ & MODE_NAMED_FLAG) {
261 #if defined(OS_NACL_NONSFI)
262 LOG(FATAL)
263 << "IPC channels in nacl_helper_nonsfi should not be in NAMED mode.";
264 #else
265 // Case 2 from comment above.
266 int local_pipe_fd = -1;
268 if (mode_ & MODE_SERVER_FLAG) {
269 if (!CreateServerUnixDomainSocket(base::FilePath(pipe_name_),
270 &local_pipe_fd)) {
271 return false;
274 must_unlink_ = true;
275 } else if (mode_ & MODE_CLIENT_FLAG) {
276 if (!CreateClientUnixDomainSocket(base::FilePath(pipe_name_),
277 &local_pipe_fd)) {
278 return false;
280 } else {
281 LOG(ERROR) << "Bad mode: " << mode_;
282 return false;
285 local_pipe.reset(local_pipe_fd);
286 #endif // !defined(OS_NACL_NONSFI)
287 } else {
288 local_pipe.reset(PipeMap::GetInstance()->Lookup(pipe_name_));
289 if (mode_ & MODE_CLIENT_FLAG) {
290 if (local_pipe.is_valid()) {
291 // Case 3 from comment above.
292 // We only allow one connection.
293 local_pipe.reset(HANDLE_EINTR(dup(local_pipe.release())));
294 PipeMap::GetInstance()->Remove(pipe_name_);
295 } else {
296 // Case 4a from comment above.
297 // Guard against inappropriate reuse of the initial IPC channel. If
298 // an IPC channel closes and someone attempts to reuse it by name, the
299 // initial channel must not be recycled here. http://crbug.com/26754.
300 static bool used_initial_channel = false;
301 if (used_initial_channel) {
302 LOG(FATAL) << "Denying attempt to reuse initial IPC channel for "
303 << pipe_name_;
304 return false;
306 used_initial_channel = true;
308 local_pipe.reset(
309 base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel));
311 } else if (mode_ & MODE_SERVER_FLAG) {
312 // Case 4b from comment above.
313 if (local_pipe.is_valid()) {
314 LOG(ERROR) << "Server already exists for " << pipe_name_;
315 // This is a client side pipe registered by other server and
316 // shouldn't be closed.
317 ignore_result(local_pipe.release());
318 return false;
320 base::AutoLock lock(client_pipe_lock_);
321 int local_pipe_fd = -1, client_pipe_fd = -1;
322 if (!SocketPair(&local_pipe_fd, &client_pipe_fd))
323 return false;
324 local_pipe.reset(local_pipe_fd);
325 client_pipe_.reset(client_pipe_fd);
326 PipeMap::GetInstance()->Insert(pipe_name_, client_pipe_fd);
327 } else {
328 LOG(ERROR) << "Bad mode: " << mode_;
329 return false;
333 #if defined(IPC_USES_READWRITE)
334 // Create a dedicated socketpair() for exchanging file descriptors.
335 // See comments for IPC_USES_READWRITE for details.
336 if (mode_ & MODE_CLIENT_FLAG) {
337 int fd_pipe_fd = 1, remote_fd_pipe_fd = -1;
338 if (!SocketPair(&fd_pipe_fd, &remote_fd_pipe_fd)) {
339 return false;
342 fd_pipe_.reset(fd_pipe_fd);
343 remote_fd_pipe_.reset(remote_fd_pipe_fd);
345 #endif // IPC_USES_READWRITE
347 if ((mode_ & MODE_SERVER_FLAG) && (mode_ & MODE_NAMED_FLAG)) {
348 #if defined(OS_NACL_NONSFI)
349 LOG(FATAL) << "IPC channels in nacl_helper_nonsfi "
350 << "should not be in NAMED or SERVER mode.";
351 #else
352 server_listen_pipe_.reset(local_pipe.release());
353 #endif
354 } else {
355 pipe_.reset(local_pipe.release());
357 return true;
360 bool ChannelPosix::Connect() {
361 if (!server_listen_pipe_.is_valid() && !pipe_.is_valid()) {
362 DLOG(WARNING) << "Channel creation failed: " << pipe_name_;
363 return false;
366 bool did_connect = true;
367 if (server_listen_pipe_.is_valid()) {
368 #if defined(OS_NACL_NONSFI)
369 LOG(FATAL) << "IPC channels in nacl_helper_nonsfi "
370 << "should always be in client mode.";
371 #else
372 // Watch the pipe for connections, and turn any connections into
373 // active sockets.
374 base::MessageLoopForIO::current()->WatchFileDescriptor(
375 server_listen_pipe_.get(),
376 true,
377 base::MessageLoopForIO::WATCH_READ,
378 &server_listen_connection_watcher_,
379 this);
380 #endif
381 } else {
382 did_connect = AcceptConnection();
384 return did_connect;
387 void ChannelPosix::CloseFileDescriptors(Message* msg) {
388 #if defined(OS_MACOSX)
389 // There is a bug on OSX which makes it dangerous to close
390 // a file descriptor while it is in transit. So instead we
391 // store the file descriptor in a set and send a message to
392 // the recipient, which is queued AFTER the message that
393 // sent the FD. The recipient will reply to the message,
394 // letting us know that it is now safe to close the file
395 // descriptor. For more information, see:
396 // http://crbug.com/298276
397 std::vector<int> to_close;
398 msg->attachment_set()->ReleaseFDsToClose(&to_close);
399 for (size_t i = 0; i < to_close.size(); i++) {
400 fds_to_close_.insert(to_close[i]);
401 QueueCloseFDMessage(to_close[i], 2);
403 #else
404 msg->attachment_set()->CommitAll();
405 #endif
408 bool ChannelPosix::ProcessOutgoingMessages() {
409 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
410 // no connection?
411 if (output_queue_.empty())
412 return true;
414 if (!pipe_.is_valid())
415 return false;
417 // Write out all the messages we can till the write blocks or there are no
418 // more outgoing messages.
419 while (!output_queue_.empty()) {
420 Message* msg = output_queue_.front();
422 size_t amt_to_write = msg->size() - message_send_bytes_written_;
423 DCHECK_NE(0U, amt_to_write);
424 const char* out_bytes = reinterpret_cast<const char*>(msg->data()) +
425 message_send_bytes_written_;
427 struct msghdr msgh = {0};
428 struct iovec iov = {const_cast<char*>(out_bytes), amt_to_write};
429 msgh.msg_iov = &iov;
430 msgh.msg_iovlen = 1;
431 char buf[CMSG_SPACE(sizeof(int) *
432 MessageAttachmentSet::kMaxDescriptorsPerMessage)];
434 ssize_t bytes_written = 1;
435 int fd_written = -1;
437 if (message_send_bytes_written_ == 0 && !msg->attachment_set()->empty()) {
438 // This is the first chunk of a message which has descriptors to send
439 struct cmsghdr *cmsg;
440 const unsigned num_fds = msg->attachment_set()->size();
442 DCHECK(num_fds <= MessageAttachmentSet::kMaxDescriptorsPerMessage);
443 if (msg->attachment_set()->ContainsDirectoryDescriptor()) {
444 LOG(FATAL) << "Panic: attempting to transport directory descriptor over"
445 " IPC. Aborting to maintain sandbox isolation.";
446 // If you have hit this then something tried to send a file descriptor
447 // to a directory over an IPC channel. Since IPC channels span
448 // sandboxes this is very bad: the receiving process can use openat
449 // with ".." elements in the path in order to reach the real
450 // filesystem.
453 msgh.msg_control = buf;
454 msgh.msg_controllen = CMSG_SPACE(sizeof(int) * num_fds);
455 cmsg = CMSG_FIRSTHDR(&msgh);
456 cmsg->cmsg_level = SOL_SOCKET;
457 cmsg->cmsg_type = SCM_RIGHTS;
458 cmsg->cmsg_len = CMSG_LEN(sizeof(int) * num_fds);
459 msg->attachment_set()->PeekDescriptors(
460 reinterpret_cast<int*>(CMSG_DATA(cmsg)));
461 msgh.msg_controllen = cmsg->cmsg_len;
463 // DCHECK_LE above already checks that
464 // num_fds < kMaxDescriptorsPerMessage so no danger of overflow.
465 msg->header()->num_fds = static_cast<uint16>(num_fds);
467 #if defined(IPC_USES_READWRITE)
468 if (!IsHelloMessage(*msg)) {
469 // Only the Hello message sends the file descriptor with the message.
470 // Subsequently, we can send file descriptors on the dedicated
471 // fd_pipe_ which makes Seccomp sandbox operation more efficient.
472 struct iovec fd_pipe_iov = { const_cast<char *>(""), 1 };
473 msgh.msg_iov = &fd_pipe_iov;
474 fd_written = fd_pipe_.get();
475 bytes_written =
476 HANDLE_EINTR(sendmsg(fd_pipe_.get(), &msgh, MSG_DONTWAIT));
477 msgh.msg_iov = &iov;
478 msgh.msg_controllen = 0;
479 if (bytes_written > 0) {
480 CloseFileDescriptors(msg);
483 #endif // IPC_USES_READWRITE
486 if (bytes_written == 1) {
487 fd_written = pipe_.get();
488 #if defined(IPC_USES_READWRITE)
489 if ((mode_ & MODE_CLIENT_FLAG) && IsHelloMessage(*msg)) {
490 DCHECK_EQ(msg->attachment_set()->size(), 1U);
492 if (!msgh.msg_controllen) {
493 bytes_written =
494 HANDLE_EINTR(write(pipe_.get(), out_bytes, amt_to_write));
495 } else
496 #endif // IPC_USES_READWRITE
498 bytes_written = HANDLE_EINTR(sendmsg(pipe_.get(), &msgh, MSG_DONTWAIT));
501 if (bytes_written > 0)
502 CloseFileDescriptors(msg);
504 if (bytes_written < 0 && !SocketWriteErrorIsRecoverable()) {
505 // We can't close the pipe here, because calling OnChannelError
506 // may destroy this object, and that would be bad if we are
507 // called from Send(). Instead, we return false and hope the
508 // caller will close the pipe. If they do not, the pipe will
509 // still be closed next time OnFileCanReadWithoutBlocking is
510 // called.
511 #if defined(OS_MACOSX)
512 // On OSX writing to a pipe with no listener returns EPERM.
513 if (errno == EPERM) {
514 return false;
516 #endif // OS_MACOSX
517 if (errno == EPIPE) {
518 return false;
520 PLOG(ERROR) << "pipe error on "
521 << fd_written
522 << " Currently writing message of size: "
523 << msg->size();
524 return false;
527 if (static_cast<size_t>(bytes_written) != amt_to_write) {
528 if (bytes_written > 0) {
529 // If write() fails with EAGAIN then bytes_written will be -1.
530 message_send_bytes_written_ += bytes_written;
533 // Tell libevent to call us back once things are unblocked.
534 is_blocked_on_write_ = true;
535 base::MessageLoopForIO::current()->WatchFileDescriptor(
536 pipe_.get(),
537 false, // One shot
538 base::MessageLoopForIO::WATCH_WRITE,
539 &write_watcher_,
540 this);
541 return true;
542 } else {
543 message_send_bytes_written_ = 0;
545 // Message sent OK!
546 DVLOG(2) << "sent message @" << msg << " on channel @" << this
547 << " with type " << msg->type() << " on fd " << pipe_.get();
548 delete output_queue_.front();
549 output_queue_.pop();
552 return true;
555 bool ChannelPosix::Send(Message* message) {
556 DVLOG(2) << "sending message @" << message << " on channel @" << this
557 << " with type " << message->type()
558 << " (" << output_queue_.size() << " in queue)";
560 #ifdef IPC_MESSAGE_LOG_ENABLED
561 Logging::GetInstance()->OnSendMessage(message, "");
562 #endif // IPC_MESSAGE_LOG_ENABLED
564 message->TraceMessageBegin();
565 output_queue_.push(message);
566 if (!is_blocked_on_write_ && !waiting_connect_) {
567 return ProcessOutgoingMessages();
570 return true;
573 int ChannelPosix::GetClientFileDescriptor() const {
574 base::AutoLock lock(client_pipe_lock_);
575 return client_pipe_.get();
578 base::ScopedFD ChannelPosix::TakeClientFileDescriptor() {
579 base::AutoLock lock(client_pipe_lock_);
580 if (!client_pipe_.is_valid())
581 return base::ScopedFD();
582 PipeMap::GetInstance()->Remove(pipe_name_);
583 return client_pipe_.Pass();
586 void ChannelPosix::CloseClientFileDescriptor() {
587 base::AutoLock lock(client_pipe_lock_);
588 if (!client_pipe_.is_valid())
589 return;
590 PipeMap::GetInstance()->Remove(pipe_name_);
591 client_pipe_.reset();
594 bool ChannelPosix::AcceptsConnections() const {
595 return server_listen_pipe_.is_valid();
598 bool ChannelPosix::HasAcceptedConnection() const {
599 return AcceptsConnections() && pipe_.is_valid();
602 #if !defined(OS_NACL_NONSFI)
603 // GetPeerEuid is not supported in nacl_helper_nonsfi.
604 bool ChannelPosix::GetPeerEuid(uid_t* peer_euid) const {
605 DCHECK(!(mode_ & MODE_SERVER) || HasAcceptedConnection());
606 return IPC::GetPeerEuid(pipe_.get(), peer_euid);
608 #endif
610 void ChannelPosix::ResetToAcceptingConnectionState() {
611 // Unregister libevent for the unix domain socket and close it.
612 read_watcher_.StopWatchingFileDescriptor();
613 write_watcher_.StopWatchingFileDescriptor();
614 pipe_.reset();
615 #if defined(IPC_USES_READWRITE)
616 fd_pipe_.reset();
617 remote_fd_pipe_.reset();
618 #endif // IPC_USES_READWRITE
620 while (!output_queue_.empty()) {
621 Message* m = output_queue_.front();
622 output_queue_.pop();
623 delete m;
626 // Close any outstanding, received file descriptors.
627 ClearInputFDs();
629 #if defined(OS_MACOSX)
630 // Clear any outstanding, sent file descriptors.
631 for (std::set<int>::iterator i = fds_to_close_.begin();
632 i != fds_to_close_.end();
633 ++i) {
634 if (IGNORE_EINTR(close(*i)) < 0)
635 PLOG(ERROR) << "close";
637 fds_to_close_.clear();
638 #endif
641 // static
642 bool ChannelPosix::IsNamedServerInitialized(
643 const std::string& channel_id) {
644 return base::PathExists(base::FilePath(channel_id));
647 #if defined(OS_LINUX)
648 // static
649 void ChannelPosix::SetGlobalPid(int pid) {
650 global_pid_ = pid;
652 #endif // OS_LINUX
654 // Called by libevent when we can read from the pipe without blocking.
655 void ChannelPosix::OnFileCanReadWithoutBlocking(int fd) {
656 if (fd == server_listen_pipe_.get()) {
657 #if defined(OS_NACL_NONSFI)
658 LOG(FATAL)
659 << "IPC channels in nacl_helper_nonsfi should not be SERVER mode.";
660 #else
661 int new_pipe = 0;
662 if (!ServerAcceptConnection(server_listen_pipe_.get(), &new_pipe) ||
663 new_pipe < 0) {
664 Close();
665 listener()->OnChannelListenError();
668 if (pipe_.is_valid()) {
669 // We already have a connection. We only handle one at a time.
670 // close our new descriptor.
671 if (HANDLE_EINTR(shutdown(new_pipe, SHUT_RDWR)) < 0)
672 DPLOG(ERROR) << "shutdown " << pipe_name_;
673 if (IGNORE_EINTR(close(new_pipe)) < 0)
674 DPLOG(ERROR) << "close " << pipe_name_;
675 listener()->OnChannelDenied();
676 return;
678 pipe_.reset(new_pipe);
680 if ((mode_ & MODE_OPEN_ACCESS_FLAG) == 0) {
681 // Verify that the IPC channel peer is running as the same user.
682 uid_t client_euid;
683 if (!GetPeerEuid(&client_euid)) {
684 DLOG(ERROR) << "Unable to query client euid";
685 ResetToAcceptingConnectionState();
686 return;
688 if (client_euid != geteuid()) {
689 DLOG(WARNING) << "Client euid is not authorised";
690 ResetToAcceptingConnectionState();
691 return;
695 if (!AcceptConnection()) {
696 NOTREACHED() << "AcceptConnection should not fail on server";
698 waiting_connect_ = false;
699 #endif
700 } else if (fd == pipe_) {
701 if (waiting_connect_ && (mode_ & MODE_SERVER_FLAG)) {
702 waiting_connect_ = false;
704 if (!ProcessIncomingMessages()) {
705 // ClosePipeOnError may delete this object, so we mustn't call
706 // ProcessOutgoingMessages.
707 ClosePipeOnError();
708 return;
710 } else {
711 NOTREACHED() << "Unknown pipe " << fd;
714 // If we're a server and handshaking, then we want to make sure that we
715 // only send our handshake message after we've processed the client's.
716 // This gives us a chance to kill the client if the incoming handshake
717 // is invalid. This also flushes any closefd messages.
718 if (!is_blocked_on_write_) {
719 if (!ProcessOutgoingMessages()) {
720 ClosePipeOnError();
725 // Called by libevent when we can write to the pipe without blocking.
726 void ChannelPosix::OnFileCanWriteWithoutBlocking(int fd) {
727 DCHECK_EQ(pipe_.get(), fd);
728 is_blocked_on_write_ = false;
729 if (!ProcessOutgoingMessages()) {
730 ClosePipeOnError();
734 bool ChannelPosix::AcceptConnection() {
735 base::MessageLoopForIO::current()->WatchFileDescriptor(
736 pipe_.get(),
737 true,
738 base::MessageLoopForIO::WATCH_READ,
739 &read_watcher_,
740 this);
741 QueueHelloMessage();
743 if (mode_ & MODE_CLIENT_FLAG) {
744 // If we are a client we want to send a hello message out immediately.
745 // In server mode we will send a hello message when we receive one from a
746 // client.
747 waiting_connect_ = false;
748 return ProcessOutgoingMessages();
749 } else if (mode_ & MODE_SERVER_FLAG) {
750 waiting_connect_ = true;
751 return true;
752 } else {
753 NOTREACHED();
754 return false;
758 void ChannelPosix::ClosePipeOnError() {
759 if (HasAcceptedConnection()) {
760 ResetToAcceptingConnectionState();
761 listener()->OnChannelError();
762 } else {
763 Close();
764 if (AcceptsConnections()) {
765 listener()->OnChannelListenError();
766 } else {
767 listener()->OnChannelError();
772 int ChannelPosix::GetHelloMessageProcId() const {
773 int pid = base::GetCurrentProcId();
774 #if defined(OS_LINUX)
775 // Our process may be in a sandbox with a separate PID namespace.
776 if (global_pid_) {
777 pid = global_pid_;
779 #endif
780 return pid;
783 void ChannelPosix::QueueHelloMessage() {
784 // Create the Hello message
785 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
786 HELLO_MESSAGE_TYPE,
787 IPC::Message::PRIORITY_NORMAL));
788 if (!msg->WriteInt(GetHelloMessageProcId())) {
789 NOTREACHED() << "Unable to pickle hello message proc id";
791 #if defined(IPC_USES_READWRITE)
792 scoped_ptr<Message> hello;
793 if (remote_fd_pipe_.is_valid()) {
794 if (!msg->WriteBorrowingFile(remote_fd_pipe_.get())) {
795 NOTREACHED() << "Unable to pickle hello message file descriptors";
797 DCHECK_EQ(msg->attachment_set()->size(), 1U);
799 #endif // IPC_USES_READWRITE
800 output_queue_.push(msg.release());
803 ChannelPosix::ReadState ChannelPosix::ReadData(
804 char* buffer,
805 int buffer_len,
806 int* bytes_read) {
807 if (!pipe_.is_valid())
808 return READ_FAILED;
810 struct msghdr msg = {0};
812 struct iovec iov = {buffer, static_cast<size_t>(buffer_len)};
813 msg.msg_iov = &iov;
814 msg.msg_iovlen = 1;
816 msg.msg_control = input_cmsg_buf_;
818 // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
819 // is waiting on the pipe.
820 #if defined(IPC_USES_READWRITE)
821 if (fd_pipe_.is_valid()) {
822 *bytes_read = HANDLE_EINTR(read(pipe_.get(), buffer, buffer_len));
823 msg.msg_controllen = 0;
824 } else
825 #endif // IPC_USES_READWRITE
827 msg.msg_controllen = sizeof(input_cmsg_buf_);
828 *bytes_read = HANDLE_EINTR(recvmsg(pipe_.get(), &msg, MSG_DONTWAIT));
830 if (*bytes_read < 0) {
831 if (errno == EAGAIN) {
832 return READ_PENDING;
833 #if defined(OS_MACOSX)
834 } else if (errno == EPERM) {
835 // On OSX, reading from a pipe with no listener returns EPERM
836 // treat this as a special case to prevent spurious error messages
837 // to the console.
838 return READ_FAILED;
839 #endif // OS_MACOSX
840 } else if (errno == ECONNRESET || errno == EPIPE) {
841 return READ_FAILED;
842 } else {
843 PLOG(ERROR) << "pipe error (" << pipe_.get() << ")";
844 return READ_FAILED;
846 } else if (*bytes_read == 0) {
847 // The pipe has closed...
848 return READ_FAILED;
850 DCHECK(*bytes_read);
852 CloseClientFileDescriptor();
854 // Read any file descriptors from the message.
855 if (!ExtractFileDescriptorsFromMsghdr(&msg))
856 return READ_FAILED;
857 return READ_SUCCEEDED;
860 #if defined(IPC_USES_READWRITE)
861 bool ChannelPosix::ReadFileDescriptorsFromFDPipe() {
862 char dummy;
863 struct iovec fd_pipe_iov = { &dummy, 1 };
865 struct msghdr msg = { 0 };
866 msg.msg_iov = &fd_pipe_iov;
867 msg.msg_iovlen = 1;
868 msg.msg_control = input_cmsg_buf_;
869 msg.msg_controllen = sizeof(input_cmsg_buf_);
870 ssize_t bytes_received =
871 HANDLE_EINTR(recvmsg(fd_pipe_.get(), &msg, MSG_DONTWAIT));
873 if (bytes_received != 1)
874 return true; // No message waiting.
876 if (!ExtractFileDescriptorsFromMsghdr(&msg))
877 return false;
878 return true;
880 #endif
882 // On Posix, we need to fix up the file descriptors before the input message
883 // is dispatched.
885 // This will read from the input_fds_ (READWRITE mode only) and read more
886 // handles from the FD pipe if necessary.
887 bool ChannelPosix::WillDispatchInputMessage(Message* msg) {
888 uint16 header_fds = msg->header()->num_fds;
889 if (!header_fds)
890 return true; // Nothing to do.
892 // The message has file descriptors.
893 const char* error = NULL;
894 if (header_fds > input_fds_.size()) {
895 // The message has been completely received, but we didn't get
896 // enough file descriptors.
897 #if defined(IPC_USES_READWRITE)
898 if (!ReadFileDescriptorsFromFDPipe())
899 return false;
900 if (header_fds > input_fds_.size())
901 #endif // IPC_USES_READWRITE
902 error = "Message needs unreceived descriptors";
905 if (header_fds > MessageAttachmentSet::kMaxDescriptorsPerMessage)
906 error = "Message requires an excessive number of descriptors";
908 if (error) {
909 LOG(WARNING) << error
910 << " channel:" << this
911 << " message-type:" << msg->type()
912 << " header()->num_fds:" << header_fds;
913 // Abort the connection.
914 ClearInputFDs();
915 return false;
918 // The shenaniganery below with &foo.front() requires input_fds_ to have
919 // contiguous underlying storage (such as a simple array or a std::vector).
920 // This is why the header warns not to make input_fds_ a deque<>.
921 msg->attachment_set()->AddDescriptorsToOwn(&input_fds_.front(), header_fds);
922 input_fds_.erase(input_fds_.begin(), input_fds_.begin() + header_fds);
923 return true;
926 bool ChannelPosix::DidEmptyInputBuffers() {
927 // When the input data buffer is empty, the fds should be too. If this is
928 // not the case, we probably have a rogue renderer which is trying to fill
929 // our descriptor table.
930 return input_fds_.empty();
933 bool ChannelPosix::ExtractFileDescriptorsFromMsghdr(msghdr* msg) {
934 // Check that there are any control messages. On OSX, CMSG_FIRSTHDR will
935 // return an invalid non-NULL pointer in the case that controllen == 0.
936 if (msg->msg_controllen == 0)
937 return true;
939 for (cmsghdr* cmsg = CMSG_FIRSTHDR(msg);
940 cmsg;
941 cmsg = CMSG_NXTHDR(msg, cmsg)) {
942 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
943 unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
944 DCHECK_EQ(0U, payload_len % sizeof(int));
945 const int* file_descriptors = reinterpret_cast<int*>(CMSG_DATA(cmsg));
946 unsigned num_file_descriptors = payload_len / 4;
947 input_fds_.insert(input_fds_.end(),
948 file_descriptors,
949 file_descriptors + num_file_descriptors);
951 // Check this after adding the FDs so we don't leak them.
952 if (msg->msg_flags & MSG_CTRUNC) {
953 ClearInputFDs();
954 return false;
957 return true;
961 // No file descriptors found, but that's OK.
962 return true;
965 void ChannelPosix::ClearInputFDs() {
966 for (size_t i = 0; i < input_fds_.size(); ++i) {
967 if (IGNORE_EINTR(close(input_fds_[i])) < 0)
968 PLOG(ERROR) << "close ";
970 input_fds_.clear();
973 void ChannelPosix::QueueCloseFDMessage(int fd, int hops) {
974 switch (hops) {
975 case 1:
976 case 2: {
977 // Create the message
978 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
979 CLOSE_FD_MESSAGE_TYPE,
980 IPC::Message::PRIORITY_NORMAL));
981 if (!msg->WriteInt(hops - 1) || !msg->WriteInt(fd)) {
982 NOTREACHED() << "Unable to pickle close fd.";
984 // Send(msg.release());
985 output_queue_.push(msg.release());
986 break;
989 default:
990 NOTREACHED();
991 break;
995 void ChannelPosix::HandleInternalMessage(const Message& msg) {
996 // The Hello message contains only the process id.
997 PickleIterator iter(msg);
999 switch (msg.type()) {
1000 default:
1001 NOTREACHED();
1002 break;
1004 case Channel::HELLO_MESSAGE_TYPE:
1005 int pid;
1006 if (!iter.ReadInt(&pid))
1007 NOTREACHED();
1009 #if defined(IPC_USES_READWRITE)
1010 if (mode_ & MODE_SERVER_FLAG) {
1011 // With IPC_USES_READWRITE, the Hello message from the client to the
1012 // server also contains the fd_pipe_, which will be used for all
1013 // subsequent file descriptor passing.
1014 DCHECK_EQ(msg.attachment_set()->size(), 1U);
1015 base::ScopedFD descriptor;
1016 if (!msg.ReadFile(&iter, &descriptor)) {
1017 NOTREACHED();
1019 fd_pipe_.reset(descriptor.release());
1021 #endif // IPC_USES_READWRITE
1022 peer_pid_ = pid;
1023 listener()->OnChannelConnected(pid);
1024 break;
1026 #if defined(OS_MACOSX)
1027 case Channel::CLOSE_FD_MESSAGE_TYPE:
1028 int fd, hops;
1029 if (!iter.ReadInt(&hops))
1030 NOTREACHED();
1031 if (!iter.ReadInt(&fd))
1032 NOTREACHED();
1033 if (hops == 0) {
1034 if (fds_to_close_.erase(fd) > 0) {
1035 if (IGNORE_EINTR(close(fd)) < 0)
1036 PLOG(ERROR) << "close";
1037 } else {
1038 NOTREACHED();
1040 } else {
1041 QueueCloseFDMessage(fd, hops);
1043 break;
1044 #endif
1048 void ChannelPosix::Close() {
1049 // Close can be called multiple time, so we need to make sure we're
1050 // idempotent.
1052 ResetToAcceptingConnectionState();
1054 if (must_unlink_) {
1055 unlink(pipe_name_.c_str());
1056 must_unlink_ = false;
1059 if (server_listen_pipe_.is_valid()) {
1060 #if defined(OS_NACL_NONSFI)
1061 LOG(FATAL)
1062 << "IPC channels in nacl_helper_nonsfi should not be SERVER mode.";
1063 #else
1064 server_listen_pipe_.reset();
1065 // Unregister libevent for the listening socket and close it.
1066 server_listen_connection_watcher_.StopWatchingFileDescriptor();
1067 #endif
1070 CloseClientFileDescriptor();
1073 base::ProcessId ChannelPosix::GetPeerPID() const {
1074 return peer_pid_;
1077 base::ProcessId ChannelPosix::GetSelfPID() const {
1078 return GetHelloMessageProcId();
1081 //------------------------------------------------------------------------------
1082 // Channel's methods
1084 // static
1085 scoped_ptr<Channel> Channel::Create(
1086 const IPC::ChannelHandle &channel_handle, Mode mode, Listener* listener) {
1087 return make_scoped_ptr(new ChannelPosix(channel_handle, mode, listener));
1090 // static
1091 std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) {
1092 // A random name is sufficient validation on posix systems, so we don't need
1093 // an additional shared secret.
1095 std::string id = prefix;
1096 if (!id.empty())
1097 id.append(".");
1099 return id.append(GenerateUniqueRandomChannelID());
1103 bool Channel::IsNamedServerInitialized(
1104 const std::string& channel_id) {
1105 return ChannelPosix::IsNamedServerInitialized(channel_id);
1108 #if defined(OS_LINUX)
1109 // static
1110 void Channel::SetGlobalPid(int pid) {
1111 ChannelPosix::SetGlobalPid(pid);
1113 #endif // OS_LINUX
1115 } // namespace IPC