Fix reconnect in case of empty global network policy.
[chromium-blink-merge.git] / ipc / ipc_channel_posix.cc
blob2dfd17e6730cbd305d7a2046def6d90276dea172
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/files/file_path.h"
25 #include "base/files/file_util.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/process_handle.h"
33 #include "base/rand_util.h"
34 #include "base/stl_util.h"
35 #include "base/strings/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"
43 #include "ipc/unix_domain_socket_util.h"
45 namespace IPC {
47 // IPC channels on Windows use named pipes (CreateNamedPipe()) with
48 // channel ids as the pipe names. Channels on POSIX use sockets as
49 // pipes These don't quite line up.
51 // When creating a child subprocess we use a socket pair and the parent side of
52 // the fork arranges it such that the initial control channel ends up on the
53 // magic file descriptor kPrimaryIPCChannel in the child. Future
54 // connections (file descriptors) can then be passed via that
55 // connection via sendmsg().
57 // A POSIX IPC channel can also be set up as a server for a bound UNIX domain
58 // socket, and will handle multiple connect and disconnect sequences. Currently
59 // it is limited to one connection at a time.
61 //------------------------------------------------------------------------------
62 namespace {
64 // The PipeMap class works around this quirk related to unit tests:
66 // When running as a server, we install the client socket in a
67 // specific file descriptor number (@kPrimaryIPCChannel). However, we
68 // also have to support the case where we are running unittests in the
69 // same process. (We do not support forking without execing.)
71 // Case 1: normal running
72 // The IPC server object will install a mapping in PipeMap from the
73 // name which it was given to the client pipe. When forking the client, the
74 // GetClientFileDescriptorMapping will ensure that the socket is installed in
75 // the magic slot (@kPrimaryIPCChannel). The client will search for the
76 // mapping, but it won't find any since we are in a new process. Thus the
77 // magic fd number is returned. Once the client connects, the server will
78 // close its copy of the client socket and remove the mapping.
80 // Case 2: unittests - client and server in the same process
81 // The IPC server will install a mapping as before. The client will search
82 // for a mapping and find out. It duplicates the file descriptor and
83 // connects. Once the client connects, the server will close the original
84 // copy of the client socket and remove the mapping. Thus, when the client
85 // object closes, it will close the only remaining copy of the client socket
86 // in the fd table and the server will see EOF on its side.
88 // TODO(port): a client process cannot connect to multiple IPC channels with
89 // this scheme.
91 class PipeMap {
92 public:
93 static PipeMap* GetInstance() {
94 return Singleton<PipeMap>::get();
97 ~PipeMap() {
98 // Shouldn't have left over pipes.
99 DCHECK(map_.empty());
102 // Lookup a given channel id. Return -1 if not found.
103 int Lookup(const std::string& channel_id) {
104 base::AutoLock locked(lock_);
106 ChannelToFDMap::const_iterator i = map_.find(channel_id);
107 if (i == map_.end())
108 return -1;
109 return i->second;
112 // Remove the mapping for the given channel id. No error is signaled if the
113 // channel_id doesn't exist
114 void Remove(const std::string& channel_id) {
115 base::AutoLock locked(lock_);
116 map_.erase(channel_id);
119 // Insert a mapping from @channel_id to @fd. It's a fatal error to insert a
120 // mapping if one already exists for the given channel_id
121 void Insert(const std::string& channel_id, int fd) {
122 base::AutoLock locked(lock_);
123 DCHECK_NE(-1, fd);
125 ChannelToFDMap::const_iterator i = map_.find(channel_id);
126 CHECK(i == map_.end()) << "Creating second IPC server (fd " << fd << ") "
127 << "for '" << channel_id << "' while first "
128 << "(fd " << i->second << ") still exists";
129 map_[channel_id] = fd;
132 private:
133 base::Lock lock_;
134 typedef std::map<std::string, int> ChannelToFDMap;
135 ChannelToFDMap map_;
137 friend struct DefaultSingletonTraits<PipeMap>;
138 #if defined(OS_ANDROID)
139 friend void ::IPC::Channel::NotifyProcessForkedForTesting();
140 #endif
143 //------------------------------------------------------------------------------
145 bool SocketWriteErrorIsRecoverable() {
146 #if defined(OS_MACOSX)
147 // On OS X if sendmsg() is trying to send fds between processes and there
148 // isn't enough room in the output buffer to send the fd structure over
149 // atomically then EMSGSIZE is returned.
151 // EMSGSIZE presents a problem since the system APIs can only call us when
152 // there's room in the socket buffer and not when there is "enough" room.
154 // The current behavior is to return to the event loop when EMSGSIZE is
155 // received and hopefull service another FD. This is however still
156 // technically a busy wait since the event loop will call us right back until
157 // the receiver has read enough data to allow passing the FD over atomically.
158 return errno == EAGAIN || errno == EMSGSIZE;
159 #else
160 return errno == EAGAIN;
161 #endif // OS_MACOSX
164 } // namespace
166 #if defined(OS_ANDROID)
167 // When we fork for simple tests on Android, we can't 'exec', so we need to
168 // reset these entries manually to get the expected testing behavior.
169 void Channel::NotifyProcessForkedForTesting() {
170 PipeMap::GetInstance()->map_.clear();
172 #endif
174 //------------------------------------------------------------------------------
176 #if defined(OS_LINUX)
177 int ChannelPosix::global_pid_ = 0;
178 #endif // OS_LINUX
180 ChannelPosix::ChannelPosix(const IPC::ChannelHandle& channel_handle,
181 Mode mode, Listener* listener)
182 : ChannelReader(listener),
183 mode_(mode),
184 peer_pid_(base::kNullProcessId),
185 is_blocked_on_write_(false),
186 waiting_connect_(true),
187 message_send_bytes_written_(0),
188 pipe_name_(channel_handle.name),
189 must_unlink_(false) {
190 memset(input_cmsg_buf_, 0, sizeof(input_cmsg_buf_));
191 if (!CreatePipe(channel_handle)) {
192 // The pipe may have been closed already.
193 const char *modestr = (mode_ & MODE_SERVER_FLAG) ? "server" : "client";
194 LOG(WARNING) << "Unable to create pipe named \"" << channel_handle.name
195 << "\" in " << modestr << " mode";
199 ChannelPosix::~ChannelPosix() {
200 Close();
203 bool SocketPair(int* fd1, int* fd2) {
204 int pipe_fds[2];
205 if (socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds) != 0) {
206 PLOG(ERROR) << "socketpair()";
207 return false;
210 // Set both ends to be non-blocking.
211 if (fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK) == -1 ||
212 fcntl(pipe_fds[1], F_SETFL, O_NONBLOCK) == -1) {
213 PLOG(ERROR) << "fcntl(O_NONBLOCK)";
214 if (IGNORE_EINTR(close(pipe_fds[0])) < 0)
215 PLOG(ERROR) << "close";
216 if (IGNORE_EINTR(close(pipe_fds[1])) < 0)
217 PLOG(ERROR) << "close";
218 return false;
221 *fd1 = pipe_fds[0];
222 *fd2 = pipe_fds[1];
224 return true;
227 bool ChannelPosix::CreatePipe(
228 const IPC::ChannelHandle& channel_handle) {
229 DCHECK(!server_listen_pipe_.is_valid() && !pipe_.is_valid());
231 // Four possible cases:
232 // 1) It's a channel wrapping a pipe that is given to us.
233 // 2) It's for a named channel, so we create it.
234 // 3) It's for a client that we implement ourself. This is used
235 // in single-process unittesting.
236 // 4) It's the initial IPC channel:
237 // 4a) Client side: Pull the pipe out of the GlobalDescriptors set.
238 // 4b) Server side: create the pipe.
240 base::ScopedFD local_pipe;
241 if (channel_handle.socket.fd != -1) {
242 // Case 1 from comment above.
243 local_pipe.reset(channel_handle.socket.fd);
244 #if defined(IPC_USES_READWRITE)
245 // Test the socket passed into us to make sure it is nonblocking.
246 // We don't want to call read/write on a blocking socket.
247 int value = fcntl(local_pipe.get(), F_GETFL);
248 if (value == -1) {
249 PLOG(ERROR) << "fcntl(F_GETFL) " << pipe_name_;
250 return false;
252 if (!(value & O_NONBLOCK)) {
253 LOG(ERROR) << "Socket " << pipe_name_ << " must be O_NONBLOCK";
254 return false;
256 #endif // IPC_USES_READWRITE
257 } else if (mode_ & MODE_NAMED_FLAG) {
258 // Case 2 from comment above.
259 int local_pipe_fd = -1;
261 if (mode_ & MODE_SERVER_FLAG) {
262 if (!CreateServerUnixDomainSocket(base::FilePath(pipe_name_),
263 &local_pipe_fd)) {
264 return false;
267 must_unlink_ = true;
268 } else if (mode_ & MODE_CLIENT_FLAG) {
269 if (!CreateClientUnixDomainSocket(base::FilePath(pipe_name_),
270 &local_pipe_fd)) {
271 return false;
273 } else {
274 LOG(ERROR) << "Bad mode: " << mode_;
275 return false;
278 local_pipe.reset(local_pipe_fd);
279 } else {
280 local_pipe.reset(PipeMap::GetInstance()->Lookup(pipe_name_));
281 if (mode_ & MODE_CLIENT_FLAG) {
282 if (local_pipe.is_valid()) {
283 // Case 3 from comment above.
284 // We only allow one connection.
285 local_pipe.reset(HANDLE_EINTR(dup(local_pipe.release())));
286 PipeMap::GetInstance()->Remove(pipe_name_);
287 } else {
288 // Case 4a from comment above.
289 // Guard against inappropriate reuse of the initial IPC channel. If
290 // an IPC channel closes and someone attempts to reuse it by name, the
291 // initial channel must not be recycled here. http://crbug.com/26754.
292 static bool used_initial_channel = false;
293 if (used_initial_channel) {
294 LOG(FATAL) << "Denying attempt to reuse initial IPC channel for "
295 << pipe_name_;
296 return false;
298 used_initial_channel = true;
300 local_pipe.reset(
301 base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel));
303 } else if (mode_ & MODE_SERVER_FLAG) {
304 // Case 4b from comment above.
305 if (local_pipe.is_valid()) {
306 LOG(ERROR) << "Server already exists for " << pipe_name_;
307 // This is a client side pipe registered by other server and
308 // shouldn't be closed.
309 ignore_result(local_pipe.release());
310 return false;
312 base::AutoLock lock(client_pipe_lock_);
313 int local_pipe_fd = -1, client_pipe_fd = -1;
314 if (!SocketPair(&local_pipe_fd, &client_pipe_fd))
315 return false;
316 local_pipe.reset(local_pipe_fd);
317 client_pipe_.reset(client_pipe_fd);
318 PipeMap::GetInstance()->Insert(pipe_name_, client_pipe_fd);
319 } else {
320 LOG(ERROR) << "Bad mode: " << mode_;
321 return false;
325 #if defined(IPC_USES_READWRITE)
326 // Create a dedicated socketpair() for exchanging file descriptors.
327 // See comments for IPC_USES_READWRITE for details.
328 if (mode_ & MODE_CLIENT_FLAG) {
329 int fd_pipe_fd = 1, remote_fd_pipe_fd = -1;
330 if (!SocketPair(&fd_pipe_fd, &remote_fd_pipe_fd)) {
331 return false;
334 fd_pipe_.reset(fd_pipe_fd);
335 remote_fd_pipe_.reset(remote_fd_pipe_fd);
337 #endif // IPC_USES_READWRITE
339 if ((mode_ & MODE_SERVER_FLAG) && (mode_ & MODE_NAMED_FLAG))
340 server_listen_pipe_.reset(local_pipe.release());
341 else
342 pipe_.reset(local_pipe.release());
343 return true;
346 bool ChannelPosix::Connect() {
347 if (!server_listen_pipe_.is_valid() && !pipe_.is_valid()) {
348 DLOG(WARNING) << "Channel creation failed: " << pipe_name_;
349 return false;
352 bool did_connect = true;
353 if (server_listen_pipe_.is_valid()) {
354 // Watch the pipe for connections, and turn any connections into
355 // active sockets.
356 base::MessageLoopForIO::current()->WatchFileDescriptor(
357 server_listen_pipe_.get(),
358 true,
359 base::MessageLoopForIO::WATCH_READ,
360 &server_listen_connection_watcher_,
361 this);
362 } else {
363 did_connect = AcceptConnection();
365 return did_connect;
368 void ChannelPosix::CloseFileDescriptors(Message* msg) {
369 #if defined(OS_MACOSX)
370 // There is a bug on OSX which makes it dangerous to close
371 // a file descriptor while it is in transit. So instead we
372 // store the file descriptor in a set and send a message to
373 // the recipient, which is queued AFTER the message that
374 // sent the FD. The recipient will reply to the message,
375 // letting us know that it is now safe to close the file
376 // descriptor. For more information, see:
377 // http://crbug.com/298276
378 std::vector<int> to_close;
379 msg->file_descriptor_set()->ReleaseFDsToClose(&to_close);
380 for (size_t i = 0; i < to_close.size(); i++) {
381 fds_to_close_.insert(to_close[i]);
382 QueueCloseFDMessage(to_close[i], 2);
384 #else
385 msg->file_descriptor_set()->CommitAll();
386 #endif
389 bool ChannelPosix::ProcessOutgoingMessages() {
390 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
391 // no connection?
392 if (output_queue_.empty())
393 return true;
395 if (!pipe_.is_valid())
396 return false;
398 // Write out all the messages we can till the write blocks or there are no
399 // more outgoing messages.
400 while (!output_queue_.empty()) {
401 Message* msg = output_queue_.front();
403 size_t amt_to_write = msg->size() - message_send_bytes_written_;
404 DCHECK_NE(0U, amt_to_write);
405 const char* out_bytes = reinterpret_cast<const char*>(msg->data()) +
406 message_send_bytes_written_;
408 struct msghdr msgh = {0};
409 struct iovec iov = {const_cast<char*>(out_bytes), amt_to_write};
410 msgh.msg_iov = &iov;
411 msgh.msg_iovlen = 1;
412 char buf[CMSG_SPACE(
413 sizeof(int) * FileDescriptorSet::kMaxDescriptorsPerMessage)];
415 ssize_t bytes_written = 1;
416 int fd_written = -1;
418 if (message_send_bytes_written_ == 0 &&
419 !msg->file_descriptor_set()->empty()) {
420 // This is the first chunk of a message which has descriptors to send
421 struct cmsghdr *cmsg;
422 const unsigned num_fds = msg->file_descriptor_set()->size();
424 DCHECK(num_fds <= FileDescriptorSet::kMaxDescriptorsPerMessage);
425 if (msg->file_descriptor_set()->ContainsDirectoryDescriptor()) {
426 LOG(FATAL) << "Panic: attempting to transport directory descriptor over"
427 " IPC. Aborting to maintain sandbox isolation.";
428 // If you have hit this then something tried to send a file descriptor
429 // to a directory over an IPC channel. Since IPC channels span
430 // sandboxes this is very bad: the receiving process can use openat
431 // with ".." elements in the path in order to reach the real
432 // filesystem.
435 msgh.msg_control = buf;
436 msgh.msg_controllen = CMSG_SPACE(sizeof(int) * num_fds);
437 cmsg = CMSG_FIRSTHDR(&msgh);
438 cmsg->cmsg_level = SOL_SOCKET;
439 cmsg->cmsg_type = SCM_RIGHTS;
440 cmsg->cmsg_len = CMSG_LEN(sizeof(int) * num_fds);
441 msg->file_descriptor_set()->PeekDescriptors(
442 reinterpret_cast<int*>(CMSG_DATA(cmsg)));
443 msgh.msg_controllen = cmsg->cmsg_len;
445 // DCHECK_LE above already checks that
446 // num_fds < kMaxDescriptorsPerMessage so no danger of overflow.
447 msg->header()->num_fds = static_cast<uint16>(num_fds);
449 #if defined(IPC_USES_READWRITE)
450 if (!IsHelloMessage(*msg)) {
451 // Only the Hello message sends the file descriptor with the message.
452 // Subsequently, we can send file descriptors on the dedicated
453 // fd_pipe_ which makes Seccomp sandbox operation more efficient.
454 struct iovec fd_pipe_iov = { const_cast<char *>(""), 1 };
455 msgh.msg_iov = &fd_pipe_iov;
456 fd_written = fd_pipe_.get();
457 bytes_written =
458 HANDLE_EINTR(sendmsg(fd_pipe_.get(), &msgh, MSG_DONTWAIT));
459 msgh.msg_iov = &iov;
460 msgh.msg_controllen = 0;
461 if (bytes_written > 0) {
462 CloseFileDescriptors(msg);
465 #endif // IPC_USES_READWRITE
468 if (bytes_written == 1) {
469 fd_written = pipe_.get();
470 #if defined(IPC_USES_READWRITE)
471 if ((mode_ & MODE_CLIENT_FLAG) && IsHelloMessage(*msg)) {
472 DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
474 if (!msgh.msg_controllen) {
475 bytes_written =
476 HANDLE_EINTR(write(pipe_.get(), out_bytes, amt_to_write));
477 } else
478 #endif // IPC_USES_READWRITE
480 bytes_written = HANDLE_EINTR(sendmsg(pipe_.get(), &msgh, MSG_DONTWAIT));
483 if (bytes_written > 0)
484 CloseFileDescriptors(msg);
486 if (bytes_written < 0 && !SocketWriteErrorIsRecoverable()) {
487 // We can't close the pipe here, because calling OnChannelError
488 // may destroy this object, and that would be bad if we are
489 // called from Send(). Instead, we return false and hope the
490 // caller will close the pipe. If they do not, the pipe will
491 // still be closed next time OnFileCanReadWithoutBlocking is
492 // called.
493 #if defined(OS_MACOSX)
494 // On OSX writing to a pipe with no listener returns EPERM.
495 if (errno == EPERM) {
496 return false;
498 #endif // OS_MACOSX
499 if (errno == EPIPE) {
500 return false;
502 PLOG(ERROR) << "pipe error on "
503 << fd_written
504 << " Currently writing message of size: "
505 << msg->size();
506 return false;
509 if (static_cast<size_t>(bytes_written) != amt_to_write) {
510 if (bytes_written > 0) {
511 // If write() fails with EAGAIN then bytes_written will be -1.
512 message_send_bytes_written_ += bytes_written;
515 // Tell libevent to call us back once things are unblocked.
516 is_blocked_on_write_ = true;
517 base::MessageLoopForIO::current()->WatchFileDescriptor(
518 pipe_.get(),
519 false, // One shot
520 base::MessageLoopForIO::WATCH_WRITE,
521 &write_watcher_,
522 this);
523 return true;
524 } else {
525 message_send_bytes_written_ = 0;
527 // Message sent OK!
528 DVLOG(2) << "sent message @" << msg << " on channel @" << this
529 << " with type " << msg->type() << " on fd " << pipe_.get();
530 delete output_queue_.front();
531 output_queue_.pop();
534 return true;
537 bool ChannelPosix::Send(Message* message) {
538 DVLOG(2) << "sending message @" << message << " on channel @" << this
539 << " with type " << message->type()
540 << " (" << output_queue_.size() << " in queue)";
542 #ifdef IPC_MESSAGE_LOG_ENABLED
543 Logging::GetInstance()->OnSendMessage(message, "");
544 #endif // IPC_MESSAGE_LOG_ENABLED
546 message->TraceMessageBegin();
547 output_queue_.push(message);
548 if (!is_blocked_on_write_ && !waiting_connect_) {
549 return ProcessOutgoingMessages();
552 return true;
555 int ChannelPosix::GetClientFileDescriptor() const {
556 base::AutoLock lock(client_pipe_lock_);
557 return client_pipe_.get();
560 int ChannelPosix::TakeClientFileDescriptor() {
561 base::AutoLock lock(client_pipe_lock_);
562 if (!client_pipe_.is_valid())
563 return -1;
564 PipeMap::GetInstance()->Remove(pipe_name_);
565 return client_pipe_.release();
568 void ChannelPosix::CloseClientFileDescriptor() {
569 base::AutoLock lock(client_pipe_lock_);
570 if (!client_pipe_.is_valid())
571 return;
572 PipeMap::GetInstance()->Remove(pipe_name_);
573 client_pipe_.reset();
576 bool ChannelPosix::AcceptsConnections() const {
577 return server_listen_pipe_.is_valid();
580 bool ChannelPosix::HasAcceptedConnection() const {
581 return AcceptsConnections() && pipe_.is_valid();
584 bool ChannelPosix::GetPeerEuid(uid_t* peer_euid) const {
585 DCHECK(!(mode_ & MODE_SERVER) || HasAcceptedConnection());
586 return IPC::GetPeerEuid(pipe_.get(), peer_euid);
589 void ChannelPosix::ResetToAcceptingConnectionState() {
590 // Unregister libevent for the unix domain socket and close it.
591 read_watcher_.StopWatchingFileDescriptor();
592 write_watcher_.StopWatchingFileDescriptor();
593 pipe_.reset();
594 #if defined(IPC_USES_READWRITE)
595 fd_pipe_.reset();
596 remote_fd_pipe_.reset();
597 #endif // IPC_USES_READWRITE
599 while (!output_queue_.empty()) {
600 Message* m = output_queue_.front();
601 output_queue_.pop();
602 delete m;
605 // Close any outstanding, received file descriptors.
606 ClearInputFDs();
608 #if defined(OS_MACOSX)
609 // Clear any outstanding, sent file descriptors.
610 for (std::set<int>::iterator i = fds_to_close_.begin();
611 i != fds_to_close_.end();
612 ++i) {
613 if (IGNORE_EINTR(close(*i)) < 0)
614 PLOG(ERROR) << "close";
616 fds_to_close_.clear();
617 #endif
620 // static
621 bool ChannelPosix::IsNamedServerInitialized(
622 const std::string& channel_id) {
623 return base::PathExists(base::FilePath(channel_id));
626 #if defined(OS_LINUX)
627 // static
628 void ChannelPosix::SetGlobalPid(int pid) {
629 global_pid_ = pid;
631 #endif // OS_LINUX
633 // Called by libevent when we can read from the pipe without blocking.
634 void ChannelPosix::OnFileCanReadWithoutBlocking(int fd) {
635 if (fd == server_listen_pipe_.get()) {
636 int new_pipe = 0;
637 if (!ServerAcceptConnection(server_listen_pipe_.get(), &new_pipe) ||
638 new_pipe < 0) {
639 Close();
640 listener()->OnChannelListenError();
643 if (pipe_.is_valid()) {
644 // We already have a connection. We only handle one at a time.
645 // close our new descriptor.
646 if (HANDLE_EINTR(shutdown(new_pipe, SHUT_RDWR)) < 0)
647 DPLOG(ERROR) << "shutdown " << pipe_name_;
648 if (IGNORE_EINTR(close(new_pipe)) < 0)
649 DPLOG(ERROR) << "close " << pipe_name_;
650 listener()->OnChannelDenied();
651 return;
653 pipe_.reset(new_pipe);
655 if ((mode_ & MODE_OPEN_ACCESS_FLAG) == 0) {
656 // Verify that the IPC channel peer is running as the same user.
657 uid_t client_euid;
658 if (!GetPeerEuid(&client_euid)) {
659 DLOG(ERROR) << "Unable to query client euid";
660 ResetToAcceptingConnectionState();
661 return;
663 if (client_euid != geteuid()) {
664 DLOG(WARNING) << "Client euid is not authorised";
665 ResetToAcceptingConnectionState();
666 return;
670 if (!AcceptConnection()) {
671 NOTREACHED() << "AcceptConnection should not fail on server";
673 waiting_connect_ = false;
674 } else if (fd == pipe_) {
675 if (waiting_connect_ && (mode_ & MODE_SERVER_FLAG)) {
676 waiting_connect_ = false;
678 if (!ProcessIncomingMessages()) {
679 // ClosePipeOnError may delete this object, so we mustn't call
680 // ProcessOutgoingMessages.
681 ClosePipeOnError();
682 return;
684 } else {
685 NOTREACHED() << "Unknown pipe " << fd;
688 // If we're a server and handshaking, then we want to make sure that we
689 // only send our handshake message after we've processed the client's.
690 // This gives us a chance to kill the client if the incoming handshake
691 // is invalid. This also flushes any closefd messages.
692 if (!is_blocked_on_write_) {
693 if (!ProcessOutgoingMessages()) {
694 ClosePipeOnError();
699 // Called by libevent when we can write to the pipe without blocking.
700 void ChannelPosix::OnFileCanWriteWithoutBlocking(int fd) {
701 DCHECK_EQ(pipe_.get(), fd);
702 is_blocked_on_write_ = false;
703 if (!ProcessOutgoingMessages()) {
704 ClosePipeOnError();
708 bool ChannelPosix::AcceptConnection() {
709 base::MessageLoopForIO::current()->WatchFileDescriptor(
710 pipe_.get(),
711 true,
712 base::MessageLoopForIO::WATCH_READ,
713 &read_watcher_,
714 this);
715 QueueHelloMessage();
717 if (mode_ & MODE_CLIENT_FLAG) {
718 // If we are a client we want to send a hello message out immediately.
719 // In server mode we will send a hello message when we receive one from a
720 // client.
721 waiting_connect_ = false;
722 return ProcessOutgoingMessages();
723 } else if (mode_ & MODE_SERVER_FLAG) {
724 waiting_connect_ = true;
725 return true;
726 } else {
727 NOTREACHED();
728 return false;
732 void ChannelPosix::ClosePipeOnError() {
733 if (HasAcceptedConnection()) {
734 ResetToAcceptingConnectionState();
735 listener()->OnChannelError();
736 } else {
737 Close();
738 if (AcceptsConnections()) {
739 listener()->OnChannelListenError();
740 } else {
741 listener()->OnChannelError();
746 int ChannelPosix::GetHelloMessageProcId() const {
747 int pid = base::GetCurrentProcId();
748 #if defined(OS_LINUX)
749 // Our process may be in a sandbox with a separate PID namespace.
750 if (global_pid_) {
751 pid = global_pid_;
753 #endif
754 return pid;
757 void ChannelPosix::QueueHelloMessage() {
758 // Create the Hello message
759 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
760 HELLO_MESSAGE_TYPE,
761 IPC::Message::PRIORITY_NORMAL));
762 if (!msg->WriteInt(GetHelloMessageProcId())) {
763 NOTREACHED() << "Unable to pickle hello message proc id";
765 #if defined(IPC_USES_READWRITE)
766 scoped_ptr<Message> hello;
767 if (remote_fd_pipe_.is_valid()) {
768 if (!msg->WriteBorrowingFile(remote_fd_pipe_.get())) {
769 NOTREACHED() << "Unable to pickle hello message file descriptors";
771 DCHECK_EQ(msg->file_descriptor_set()->size(), 1U);
773 #endif // IPC_USES_READWRITE
774 output_queue_.push(msg.release());
777 ChannelPosix::ReadState ChannelPosix::ReadData(
778 char* buffer,
779 int buffer_len,
780 int* bytes_read) {
781 if (!pipe_.is_valid())
782 return READ_FAILED;
784 struct msghdr msg = {0};
786 struct iovec iov = {buffer, static_cast<size_t>(buffer_len)};
787 msg.msg_iov = &iov;
788 msg.msg_iovlen = 1;
790 msg.msg_control = input_cmsg_buf_;
792 // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
793 // is waiting on the pipe.
794 #if defined(IPC_USES_READWRITE)
795 if (fd_pipe_.is_valid()) {
796 *bytes_read = HANDLE_EINTR(read(pipe_.get(), buffer, buffer_len));
797 msg.msg_controllen = 0;
798 } else
799 #endif // IPC_USES_READWRITE
801 msg.msg_controllen = sizeof(input_cmsg_buf_);
802 *bytes_read = HANDLE_EINTR(recvmsg(pipe_.get(), &msg, MSG_DONTWAIT));
804 if (*bytes_read < 0) {
805 if (errno == EAGAIN) {
806 return READ_PENDING;
807 #if defined(OS_MACOSX)
808 } else if (errno == EPERM) {
809 // On OSX, reading from a pipe with no listener returns EPERM
810 // treat this as a special case to prevent spurious error messages
811 // to the console.
812 return READ_FAILED;
813 #endif // OS_MACOSX
814 } else if (errno == ECONNRESET || errno == EPIPE) {
815 return READ_FAILED;
816 } else {
817 PLOG(ERROR) << "pipe error (" << pipe_.get() << ")";
818 return READ_FAILED;
820 } else if (*bytes_read == 0) {
821 // The pipe has closed...
822 return READ_FAILED;
824 DCHECK(*bytes_read);
826 CloseClientFileDescriptor();
828 // Read any file descriptors from the message.
829 if (!ExtractFileDescriptorsFromMsghdr(&msg))
830 return READ_FAILED;
831 return READ_SUCCEEDED;
834 #if defined(IPC_USES_READWRITE)
835 bool ChannelPosix::ReadFileDescriptorsFromFDPipe() {
836 char dummy;
837 struct iovec fd_pipe_iov = { &dummy, 1 };
839 struct msghdr msg = { 0 };
840 msg.msg_iov = &fd_pipe_iov;
841 msg.msg_iovlen = 1;
842 msg.msg_control = input_cmsg_buf_;
843 msg.msg_controllen = sizeof(input_cmsg_buf_);
844 ssize_t bytes_received =
845 HANDLE_EINTR(recvmsg(fd_pipe_.get(), &msg, MSG_DONTWAIT));
847 if (bytes_received != 1)
848 return true; // No message waiting.
850 if (!ExtractFileDescriptorsFromMsghdr(&msg))
851 return false;
852 return true;
854 #endif
856 // On Posix, we need to fix up the file descriptors before the input message
857 // is dispatched.
859 // This will read from the input_fds_ (READWRITE mode only) and read more
860 // handles from the FD pipe if necessary.
861 bool ChannelPosix::WillDispatchInputMessage(Message* msg) {
862 uint16 header_fds = msg->header()->num_fds;
863 if (!header_fds)
864 return true; // Nothing to do.
866 // The message has file descriptors.
867 const char* error = NULL;
868 if (header_fds > input_fds_.size()) {
869 // The message has been completely received, but we didn't get
870 // enough file descriptors.
871 #if defined(IPC_USES_READWRITE)
872 if (!ReadFileDescriptorsFromFDPipe())
873 return false;
874 if (header_fds > input_fds_.size())
875 #endif // IPC_USES_READWRITE
876 error = "Message needs unreceived descriptors";
879 if (header_fds > FileDescriptorSet::kMaxDescriptorsPerMessage)
880 error = "Message requires an excessive number of descriptors";
882 if (error) {
883 LOG(WARNING) << error
884 << " channel:" << this
885 << " message-type:" << msg->type()
886 << " header()->num_fds:" << header_fds;
887 // Abort the connection.
888 ClearInputFDs();
889 return false;
892 // The shenaniganery below with &foo.front() requires input_fds_ to have
893 // contiguous underlying storage (such as a simple array or a std::vector).
894 // This is why the header warns not to make input_fds_ a deque<>.
895 msg->file_descriptor_set()->AddDescriptorsToOwn(&input_fds_.front(),
896 header_fds);
897 input_fds_.erase(input_fds_.begin(), input_fds_.begin() + header_fds);
898 return true;
901 bool ChannelPosix::DidEmptyInputBuffers() {
902 // When the input data buffer is empty, the fds should be too. If this is
903 // not the case, we probably have a rogue renderer which is trying to fill
904 // our descriptor table.
905 return input_fds_.empty();
908 bool ChannelPosix::ExtractFileDescriptorsFromMsghdr(msghdr* msg) {
909 // Check that there are any control messages. On OSX, CMSG_FIRSTHDR will
910 // return an invalid non-NULL pointer in the case that controllen == 0.
911 if (msg->msg_controllen == 0)
912 return true;
914 for (cmsghdr* cmsg = CMSG_FIRSTHDR(msg);
915 cmsg;
916 cmsg = CMSG_NXTHDR(msg, cmsg)) {
917 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
918 unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
919 DCHECK_EQ(0U, payload_len % sizeof(int));
920 const int* file_descriptors = reinterpret_cast<int*>(CMSG_DATA(cmsg));
921 unsigned num_file_descriptors = payload_len / 4;
922 input_fds_.insert(input_fds_.end(),
923 file_descriptors,
924 file_descriptors + num_file_descriptors);
926 // Check this after adding the FDs so we don't leak them.
927 if (msg->msg_flags & MSG_CTRUNC) {
928 ClearInputFDs();
929 return false;
932 return true;
936 // No file descriptors found, but that's OK.
937 return true;
940 void ChannelPosix::ClearInputFDs() {
941 for (size_t i = 0; i < input_fds_.size(); ++i) {
942 if (IGNORE_EINTR(close(input_fds_[i])) < 0)
943 PLOG(ERROR) << "close ";
945 input_fds_.clear();
948 void ChannelPosix::QueueCloseFDMessage(int fd, int hops) {
949 switch (hops) {
950 case 1:
951 case 2: {
952 // Create the message
953 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
954 CLOSE_FD_MESSAGE_TYPE,
955 IPC::Message::PRIORITY_NORMAL));
956 if (!msg->WriteInt(hops - 1) || !msg->WriteInt(fd)) {
957 NOTREACHED() << "Unable to pickle close fd.";
959 // Send(msg.release());
960 output_queue_.push(msg.release());
961 break;
964 default:
965 NOTREACHED();
966 break;
970 void ChannelPosix::HandleInternalMessage(const Message& msg) {
971 // The Hello message contains only the process id.
972 PickleIterator iter(msg);
974 switch (msg.type()) {
975 default:
976 NOTREACHED();
977 break;
979 case Channel::HELLO_MESSAGE_TYPE:
980 int pid;
981 if (!msg.ReadInt(&iter, &pid))
982 NOTREACHED();
984 #if defined(IPC_USES_READWRITE)
985 if (mode_ & MODE_SERVER_FLAG) {
986 // With IPC_USES_READWRITE, the Hello message from the client to the
987 // server also contains the fd_pipe_, which will be used for all
988 // subsequent file descriptor passing.
989 DCHECK_EQ(msg.file_descriptor_set()->size(), 1U);
990 base::ScopedFD descriptor;
991 if (!msg.ReadFile(&iter, &descriptor)) {
992 NOTREACHED();
994 fd_pipe_.reset(descriptor.release());
996 #endif // IPC_USES_READWRITE
997 peer_pid_ = pid;
998 listener()->OnChannelConnected(pid);
999 break;
1001 #if defined(OS_MACOSX)
1002 case Channel::CLOSE_FD_MESSAGE_TYPE:
1003 int fd, hops;
1004 if (!msg.ReadInt(&iter, &hops))
1005 NOTREACHED();
1006 if (!msg.ReadInt(&iter, &fd))
1007 NOTREACHED();
1008 if (hops == 0) {
1009 if (fds_to_close_.erase(fd) > 0) {
1010 if (IGNORE_EINTR(close(fd)) < 0)
1011 PLOG(ERROR) << "close";
1012 } else {
1013 NOTREACHED();
1015 } else {
1016 QueueCloseFDMessage(fd, hops);
1018 break;
1019 #endif
1023 void ChannelPosix::Close() {
1024 // Close can be called multiple time, so we need to make sure we're
1025 // idempotent.
1027 ResetToAcceptingConnectionState();
1029 if (must_unlink_) {
1030 unlink(pipe_name_.c_str());
1031 must_unlink_ = false;
1034 if (server_listen_pipe_.is_valid()) {
1035 server_listen_pipe_.reset();
1036 // Unregister libevent for the listening socket and close it.
1037 server_listen_connection_watcher_.StopWatchingFileDescriptor();
1040 CloseClientFileDescriptor();
1043 base::ProcessId ChannelPosix::GetPeerPID() const {
1044 return peer_pid_;
1047 base::ProcessId ChannelPosix::GetSelfPID() const {
1048 return GetHelloMessageProcId();
1051 //------------------------------------------------------------------------------
1052 // Channel's methods
1054 // static
1055 scoped_ptr<Channel> Channel::Create(
1056 const IPC::ChannelHandle &channel_handle, Mode mode, Listener* listener) {
1057 return make_scoped_ptr(new ChannelPosix(channel_handle, mode, listener));
1060 // static
1061 std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) {
1062 // A random name is sufficient validation on posix systems, so we don't need
1063 // an additional shared secret.
1065 std::string id = prefix;
1066 if (!id.empty())
1067 id.append(".");
1069 return id.append(GenerateUniqueRandomChannelID());
1073 bool Channel::IsNamedServerInitialized(
1074 const std::string& channel_id) {
1075 return ChannelPosix::IsNamedServerInitialized(channel_id);
1078 #if defined(OS_LINUX)
1079 // static
1080 void Channel::SetGlobalPid(int pid) {
1081 ChannelPosix::SetGlobalPid(pid);
1083 #endif // OS_LINUX
1085 } // namespace IPC