1 // Copyright (c) 2011 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"
10 #include <sys/types.h>
11 #include <sys/socket.h>
18 #include "base/command_line.h"
19 #include "base/eintr_wrapper.h"
20 #include "base/file_path.h"
21 #include "base/file_util.h"
22 #include "base/global_descriptors_posix.h"
23 #include "base/logging.h"
24 #include "base/memory/scoped_ptr.h"
25 #include "base/memory/singleton.h"
26 #include "base/process_util.h"
27 #include "base/stl_util-inl.h"
28 #include "base/string_util.h"
29 #include "base/synchronization/lock.h"
30 #include "ipc/ipc_descriptors.h"
31 #include "ipc/ipc_switches.h"
32 #include "ipc/file_descriptor_set_posix.h"
33 #include "ipc/ipc_logging.h"
34 #include "ipc/ipc_message_utils.h"
38 // IPC channels on Windows use named pipes (CreateNamedPipe()) with
39 // channel ids as the pipe names. Channels on POSIX use sockets as
40 // pipes These don't quite line up.
42 // When creating a child subprocess we use a socket pair and the parent side of
43 // the fork arranges it such that the initial control channel ends up on the
44 // magic file descriptor kPrimaryIPCChannel in the child. Future
45 // connections (file descriptors) can then be passed via that
46 // connection via sendmsg().
48 // A POSIX IPC channel can also be set up as a server for a bound UNIX domain
49 // socket, and will handle multiple connect and disconnect sequences. Currently
50 // it is limited to one connection at a time.
52 //------------------------------------------------------------------------------
55 // The PipeMap class works around this quirk related to unit tests:
57 // When running as a server, we install the client socket in a
58 // specific file descriptor number (@kPrimaryIPCChannel). However, we
59 // also have to support the case where we are running unittests in the
60 // same process. (We do not support forking without execing.)
62 // Case 1: normal running
63 // The IPC server object will install a mapping in PipeMap from the
64 // name which it was given to the client pipe. When forking the client, the
65 // GetClientFileDescriptorMapping will ensure that the socket is installed in
66 // the magic slot (@kPrimaryIPCChannel). The client will search for the
67 // mapping, but it won't find any since we are in a new process. Thus the
68 // magic fd number is returned. Once the client connects, the server will
69 // close its copy of the client socket and remove the mapping.
71 // Case 2: unittests - client and server in the same process
72 // The IPC server will install a mapping as before. The client will search
73 // for a mapping and find out. It duplicates the file descriptor and
74 // connects. Once the client connects, the server will close the original
75 // copy of the client socket and remove the mapping. Thus, when the client
76 // object closes, it will close the only remaining copy of the client socket
77 // in the fd table and the server will see EOF on its side.
79 // TODO(port): a client process cannot connect to multiple IPC channels with
84 static PipeMap
* GetInstance() {
85 return Singleton
<PipeMap
>::get();
89 // Shouldn't have left over pipes.
93 // Lookup a given channel id. Return -1 if not found.
94 int Lookup(const std::string
& channel_id
) {
95 base::AutoLock
locked(lock_
);
97 ChannelToFDMap::const_iterator i
= map_
.find(channel_id
);
103 // Remove the mapping for the given channel id. No error is signaled if the
104 // channel_id doesn't exist
105 void RemoveAndClose(const std::string
& channel_id
) {
106 base::AutoLock
locked(lock_
);
108 ChannelToFDMap::iterator i
= map_
.find(channel_id
);
109 if (i
!= map_
.end()) {
110 if (HANDLE_EINTR(close(i
->second
)) < 0)
111 PLOG(ERROR
) << "close " << channel_id
;
116 // Insert a mapping from @channel_id to @fd. It's a fatal error to insert a
117 // mapping if one already exists for the given channel_id
118 void Insert(const std::string
& channel_id
, int fd
) {
119 base::AutoLock
locked(lock_
);
122 ChannelToFDMap::const_iterator i
= map_
.find(channel_id
);
123 CHECK(i
== map_
.end()) << "Creating second IPC server (fd " << fd
<< ") "
124 << "for '" << channel_id
<< "' while first "
125 << "(fd " << i
->second
<< ") still exists";
126 map_
[channel_id
] = fd
;
131 typedef std::map
<std::string
, int> ChannelToFDMap
;
134 friend struct DefaultSingletonTraits
<PipeMap
>;
137 //------------------------------------------------------------------------------
138 // Verify that kMaxPipeNameLength is a decent size.
139 COMPILE_ASSERT(sizeof(((sockaddr_un
*)0)->sun_path
) >= kMaxPipeNameLength
,
140 BAD_SUN_PATH_LENGTH
);
142 // Creates a unix domain socket bound to the specified name that is listening
144 bool CreateServerUnixDomainSocket(const std::string
& pipe_name
,
145 int* server_listen_fd
) {
146 DCHECK(server_listen_fd
);
147 DCHECK_GT(pipe_name
.length(), 0u);
148 DCHECK_LT(pipe_name
.length(), kMaxPipeNameLength
);
150 if (pipe_name
.length() == 0 || pipe_name
.length() >= kMaxPipeNameLength
) {
155 int fd
= socket(AF_UNIX
, SOCK_STREAM
, 0);
160 // Make socket non-blocking
161 if (fcntl(fd
, F_SETFL
, O_NONBLOCK
) == -1) {
162 PLOG(ERROR
) << "fcntl(O_NONBLOCK) " << pipe_name
;
163 if (HANDLE_EINTR(close(fd
)) < 0)
164 PLOG(ERROR
) << "close " << pipe_name
;
168 // Delete any old FS instances.
169 unlink(pipe_name
.c_str());
171 // Make sure the path we need exists.
172 FilePath
path(pipe_name
);
173 FilePath dir_path
= path
.DirName();
174 if (!file_util::CreateDirectory(dir_path
)) {
178 // Create unix_addr structure.
179 struct sockaddr_un unix_addr
;
180 memset(&unix_addr
, 0, sizeof(unix_addr
));
181 unix_addr
.sun_family
= AF_UNIX
;
182 int path_len
= snprintf(unix_addr
.sun_path
, IPC::kMaxPipeNameLength
,
183 "%s", pipe_name
.c_str());
184 DCHECK_EQ(static_cast<int>(pipe_name
.length()), path_len
);
185 size_t unix_addr_len
= offsetof(struct sockaddr_un
,
186 sun_path
) + path_len
+ 1;
189 if (bind(fd
, reinterpret_cast<const sockaddr
*>(&unix_addr
),
190 unix_addr_len
) != 0) {
191 PLOG(ERROR
) << "bind " << pipe_name
;
192 if (HANDLE_EINTR(close(fd
)) < 0)
193 PLOG(ERROR
) << "close " << pipe_name
;
197 // Start listening on the socket.
198 const int listen_queue_length
= 1;
199 if (listen(fd
, listen_queue_length
) != 0) {
200 PLOG(ERROR
) << "listen " << pipe_name
;
201 if (HANDLE_EINTR(close(fd
)) < 0)
202 PLOG(ERROR
) << "close " << pipe_name
;
206 *server_listen_fd
= fd
;
210 // Accept a connection on a socket we are listening to.
211 bool ServerAcceptConnection(int server_listen_fd
, int* server_socket
) {
212 DCHECK(server_socket
);
214 int accept_fd
= HANDLE_EINTR(accept(server_listen_fd
, NULL
, 0));
217 if (fcntl(accept_fd
, F_SETFL
, O_NONBLOCK
) == -1) {
218 PLOG(ERROR
) << "fcntl(O_NONBLOCK) " << accept_fd
;
219 if (HANDLE_EINTR(close(accept_fd
)) < 0)
220 PLOG(ERROR
) << "close " << accept_fd
;
224 *server_socket
= accept_fd
;
228 bool CreateClientUnixDomainSocket(const std::string
& pipe_name
,
229 int* client_socket
) {
230 DCHECK(client_socket
);
231 DCHECK_GT(pipe_name
.length(), 0u);
232 DCHECK_LT(pipe_name
.length(), kMaxPipeNameLength
);
234 if (pipe_name
.length() == 0 || pipe_name
.length() >= kMaxPipeNameLength
) {
239 int fd
= socket(AF_UNIX
, SOCK_STREAM
, 0);
241 PLOG(ERROR
) << "socket " << pipe_name
;
245 // Make socket non-blocking
246 if (fcntl(fd
, F_SETFL
, O_NONBLOCK
) == -1) {
247 PLOG(ERROR
) << "fcntl(O_NONBLOCK) " << pipe_name
;
248 if (HANDLE_EINTR(close(fd
)) < 0)
249 PLOG(ERROR
) << "close " << pipe_name
;
253 // Create server side of socket.
254 struct sockaddr_un server_unix_addr
;
255 memset(&server_unix_addr
, 0, sizeof(server_unix_addr
));
256 server_unix_addr
.sun_family
= AF_UNIX
;
257 int path_len
= snprintf(server_unix_addr
.sun_path
, IPC::kMaxPipeNameLength
,
258 "%s", pipe_name
.c_str());
259 DCHECK_EQ(static_cast<int>(pipe_name
.length()), path_len
);
260 size_t server_unix_addr_len
= offsetof(struct sockaddr_un
,
261 sun_path
) + path_len
+ 1;
263 if (HANDLE_EINTR(connect(fd
, reinterpret_cast<sockaddr
*>(&server_unix_addr
),
264 server_unix_addr_len
)) != 0) {
265 PLOG(ERROR
) << "connect " << pipe_name
;
266 if (HANDLE_EINTR(close(fd
)) < 0)
267 PLOG(ERROR
) << "close " << pipe_name
;
275 bool SocketWriteErrorIsRecoverable() {
276 #if defined(OS_MACOSX)
277 // On OS X if sendmsg() is trying to send fds between processes and there
278 // isn't enough room in the output buffer to send the fd structure over
279 // atomically then EMSGSIZE is returned.
281 // EMSGSIZE presents a problem since the system APIs can only call us when
282 // there's room in the socket buffer and not when there is "enough" room.
284 // The current behavior is to return to the event loop when EMSGSIZE is
285 // received and hopefull service another FD. This is however still
286 // technically a busy wait since the event loop will call us right back until
287 // the receiver has read enough data to allow passing the FD over atomically.
288 return errno
== EAGAIN
|| errno
== EMSGSIZE
;
290 return errno
== EAGAIN
;
295 //------------------------------------------------------------------------------
297 Channel::ChannelImpl::ChannelImpl(const IPC::ChannelHandle
& channel_handle
,
298 Mode mode
, Listener
* listener
)
300 is_blocked_on_write_(false),
301 waiting_connect_(true),
302 message_send_bytes_written_(0),
303 server_listen_pipe_(-1),
306 #if defined(IPC_USES_READWRITE)
309 #endif // IPC_USES_READWRITE
310 pipe_name_(channel_handle
.name
),
312 must_unlink_(false) {
313 memset(input_buf_
, 0, sizeof(input_buf_
));
314 memset(input_cmsg_buf_
, 0, sizeof(input_cmsg_buf_
));
315 if (!CreatePipe(channel_handle
)) {
316 // The pipe may have been closed already.
317 const char *modestr
= (mode_
& MODE_SERVER_FLAG
) ? "server" : "client";
318 // The pipe may have been closed already.
319 LOG(WARNING
) << "Unable to create pipe named \"" << channel_handle
.name
320 << "\" in " << modestr
<< " mode";
324 Channel::ChannelImpl::~ChannelImpl() {
328 bool SocketPair(int* fd1
, int* fd2
) {
330 if (socketpair(AF_UNIX
, SOCK_STREAM
, 0, pipe_fds
) != 0) {
331 PLOG(ERROR
) << "socketpair()";
335 // Set both ends to be non-blocking.
336 if (fcntl(pipe_fds
[0], F_SETFL
, O_NONBLOCK
) == -1 ||
337 fcntl(pipe_fds
[1], F_SETFL
, O_NONBLOCK
) == -1) {
338 PLOG(ERROR
) << "fcntl(O_NONBLOCK)";
339 if (HANDLE_EINTR(close(pipe_fds
[0])) < 0)
340 PLOG(ERROR
) << "close";
341 if (HANDLE_EINTR(close(pipe_fds
[1])) < 0)
342 PLOG(ERROR
) << "close";
352 bool Channel::ChannelImpl::CreatePipe(
353 const IPC::ChannelHandle
& channel_handle
) {
354 DCHECK(server_listen_pipe_
== -1 && pipe_
== -1);
356 // Four possible cases:
357 // 1) It's a channel wrapping a pipe that is given to us.
358 // 2) It's for a named channel, so we create it.
359 // 3) It's for a client that we implement ourself. This is used
361 // 4) It's the initial IPC channel:
362 // 4a) Client side: Pull the pipe out of the GlobalDescriptors set.
363 // 4b) Server side: create the pipe.
366 if (channel_handle
.socket
.fd
!= -1) {
367 // Case 1 from comment above.
368 local_pipe
= channel_handle
.socket
.fd
;
369 #if defined(IPC_USES_READWRITE)
370 // Test the socket passed into us to make sure it is nonblocking.
371 // We don't want to call read/write on a blocking socket.
372 int value
= fcntl(local_pipe
, F_GETFL
);
374 PLOG(ERROR
) << "fcntl(F_GETFL) " << pipe_name_
;
377 if (!(value
& O_NONBLOCK
)) {
378 LOG(ERROR
) << "Socket " << pipe_name_
<< " must be O_NONBLOCK";
381 #endif // IPC_USES_READWRITE
382 } else if (mode_
& MODE_NAMED_FLAG
) {
383 // Case 2 from comment above.
384 if (mode_
& MODE_SERVER_FLAG
) {
385 if (!CreateServerUnixDomainSocket(pipe_name_
, &local_pipe
)) {
389 } else if (mode_
& MODE_CLIENT_FLAG
) {
390 if (!CreateClientUnixDomainSocket(pipe_name_
, &local_pipe
)) {
394 LOG(ERROR
) << "Bad mode: " << mode_
;
398 local_pipe
= PipeMap::GetInstance()->Lookup(pipe_name_
);
399 if (mode_
& MODE_CLIENT_FLAG
) {
400 if (local_pipe
!= -1) {
401 // Case 3 from comment above.
402 // We only allow one connection.
403 local_pipe
= HANDLE_EINTR(dup(local_pipe
));
404 PipeMap::GetInstance()->RemoveAndClose(pipe_name_
);
406 // Case 4a from comment above.
407 // Guard against inappropriate reuse of the initial IPC channel. If
408 // an IPC channel closes and someone attempts to reuse it by name, the
409 // initial channel must not be recycled here. http://crbug.com/26754.
410 static bool used_initial_channel
= false;
411 if (used_initial_channel
) {
412 LOG(FATAL
) << "Denying attempt to reuse initial IPC channel for "
416 used_initial_channel
= true;
419 base::GlobalDescriptors::GetInstance()->Get(kPrimaryIPCChannel
);
421 } else if (mode_
& MODE_SERVER_FLAG
) {
422 // Case 4b from comment above.
423 if (local_pipe
!= -1) {
424 LOG(ERROR
) << "Server already exists for " << pipe_name_
;
427 if (!SocketPair(&local_pipe
, &client_pipe_
))
429 PipeMap::GetInstance()->Insert(pipe_name_
, client_pipe_
);
431 LOG(ERROR
) << "Bad mode: " << mode_
;
436 #if defined(IPC_USES_READWRITE)
437 // Create a dedicated socketpair() for exchanging file descriptors.
438 // See comments for IPC_USES_READWRITE for details.
439 if (mode_
& MODE_CLIENT_FLAG
) {
440 if (!SocketPair(&fd_pipe_
, &remote_fd_pipe_
)) {
444 #endif // IPC_USES_READWRITE
446 if ((mode_
& MODE_SERVER_FLAG
) && (mode_
& MODE_NAMED_FLAG
)) {
447 server_listen_pipe_
= local_pipe
;
455 bool Channel::ChannelImpl::Connect() {
456 if (server_listen_pipe_
== -1 && pipe_
== -1) {
457 DLOG(INFO
) << "Channel creation failed: " << pipe_name_
;
461 bool did_connect
= true;
462 if (server_listen_pipe_
!= -1) {
463 // Watch the pipe for connections, and turn any connections into
465 MessageLoopForIO::current()->WatchFileDescriptor(
468 MessageLoopForIO::WATCH_READ
,
469 &server_listen_connection_watcher_
,
472 did_connect
= AcceptConnection();
477 bool Channel::ChannelImpl::ProcessIncomingMessages() {
478 ssize_t bytes_read
= 0;
480 struct msghdr msg
= {0};
481 struct iovec iov
= {input_buf_
, Channel::kReadBufferSize
};
484 msg
.msg_control
= input_cmsg_buf_
;
489 if (bytes_read
== 0) {
494 // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
495 // is waiting on the pipe.
496 #if defined(IPC_USES_READWRITE)
498 bytes_read
= HANDLE_EINTR(read(pipe_
, input_buf_
,
499 Channel::kReadBufferSize
));
500 msg
.msg_controllen
= 0;
502 #endif // IPC_USES_READWRITE
504 msg
.msg_controllen
= sizeof(input_cmsg_buf_
);
505 bytes_read
= HANDLE_EINTR(recvmsg(pipe_
, &msg
, MSG_DONTWAIT
));
507 if (bytes_read
< 0) {
508 if (errno
== EAGAIN
) {
510 #if defined(OS_MACOSX)
511 } else if (errno
== EPERM
) {
512 // On OSX, reading from a pipe with no listener returns EPERM
513 // treat this as a special case to prevent spurious error messages
517 } else if (errno
== ECONNRESET
|| errno
== EPIPE
) {
520 PLOG(ERROR
) << "pipe error (" << pipe_
<< ")";
523 } else if (bytes_read
== 0) {
524 // The pipe has closed...
530 if (client_pipe_
!= -1) {
531 PipeMap::GetInstance()->RemoveAndClose(pipe_name_
);
535 // a pointer to an array of |num_wire_fds| file descriptors from the read
536 const int* wire_fds
= NULL
;
537 unsigned num_wire_fds
= 0;
539 // walk the list of control messages and, if we find an array of file
540 // descriptors, save a pointer to the array
542 // This next if statement is to work around an OSX issue where
543 // CMSG_FIRSTHDR will return non-NULL in the case that controllen == 0.
544 // Here's a test case:
547 // struct msghdr msg;
548 // msg.msg_control = &msg;
549 // msg.msg_controllen = 0;
550 // if (CMSG_FIRSTHDR(&msg))
551 // printf("Bug found!\n");
553 if (msg
.msg_controllen
> 0) {
554 // On OSX, CMSG_FIRSTHDR doesn't handle the case where controllen is 0
555 // and will return a pointer into nowhere.
556 for (struct cmsghdr
* cmsg
= CMSG_FIRSTHDR(&msg
); cmsg
;
557 cmsg
= CMSG_NXTHDR(&msg
, cmsg
)) {
558 if (cmsg
->cmsg_level
== SOL_SOCKET
&&
559 cmsg
->cmsg_type
== SCM_RIGHTS
) {
560 const unsigned payload_len
= cmsg
->cmsg_len
- CMSG_LEN(0);
561 DCHECK_EQ(0U, payload_len
% sizeof(int));
562 wire_fds
= reinterpret_cast<int*>(CMSG_DATA(cmsg
));
563 num_wire_fds
= payload_len
/ 4;
565 if (msg
.msg_flags
& MSG_CTRUNC
) {
566 LOG(ERROR
) << "SCM_RIGHTS message was truncated"
567 << " cmsg_len:" << cmsg
->cmsg_len
569 for (unsigned i
= 0; i
< num_wire_fds
; ++i
)
570 if (HANDLE_EINTR(close(wire_fds
[i
])) < 0)
571 PLOG(ERROR
) << "close " << i
;
579 // Process messages from input buffer.
582 if (input_overflow_buf_
.empty()) {
584 end
= p
+ bytes_read
;
586 if (input_overflow_buf_
.size() >
587 static_cast<size_t>(kMaximumMessageSize
- bytes_read
)) {
588 input_overflow_buf_
.clear();
589 LOG(ERROR
) << "IPC message is too big";
592 input_overflow_buf_
.append(input_buf_
, bytes_read
);
593 p
= input_overflow_buf_
.data();
594 end
= p
+ input_overflow_buf_
.size();
597 // A pointer to an array of |num_fds| file descriptors which includes any
598 // fds that have spilled over from a previous read.
599 const int* fds
= NULL
;
600 unsigned num_fds
= 0;
601 unsigned fds_i
= 0; // the index of the first unused descriptor
603 if (input_overflow_fds_
.empty()) {
605 num_fds
= num_wire_fds
;
607 if (num_wire_fds
> 0) {
608 const size_t prev_size
= input_overflow_fds_
.size();
609 input_overflow_fds_
.resize(prev_size
+ num_wire_fds
);
610 memcpy(&input_overflow_fds_
[prev_size
], wire_fds
,
611 num_wire_fds
* sizeof(int));
613 fds
= &input_overflow_fds_
[0];
614 num_fds
= input_overflow_fds_
.size();
618 const char* message_tail
= Message::FindNext(p
, end
);
620 int len
= static_cast<int>(message_tail
- p
);
622 const uint16 header_fds
= m
.header()->num_fds
;
624 // the message has file descriptors
625 const char* error
= NULL
;
626 if (header_fds
> num_fds
- fds_i
) {
627 // the message has been completely received, but we didn't get
628 // enough file descriptors.
629 #if defined(IPC_USES_READWRITE)
631 struct iovec fd_pipe_iov
= { &dummy
, 1 };
632 msg
.msg_iov
= &fd_pipe_iov
;
633 msg
.msg_controllen
= sizeof(input_cmsg_buf_
);
634 ssize_t n
= HANDLE_EINTR(recvmsg(fd_pipe_
, &msg
, MSG_DONTWAIT
));
635 if (n
== 1 && msg
.msg_controllen
> 0) {
636 for (struct cmsghdr
* cmsg
= CMSG_FIRSTHDR(&msg
); cmsg
;
637 cmsg
= CMSG_NXTHDR(&msg
, cmsg
)) {
638 if (cmsg
->cmsg_level
== SOL_SOCKET
&&
639 cmsg
->cmsg_type
== SCM_RIGHTS
) {
640 const unsigned payload_len
= cmsg
->cmsg_len
- CMSG_LEN(0);
641 DCHECK_EQ(0U, payload_len
% sizeof(int));
642 wire_fds
= reinterpret_cast<int*>(CMSG_DATA(cmsg
));
643 num_wire_fds
= payload_len
/ 4;
645 if (msg
.msg_flags
& MSG_CTRUNC
) {
646 LOG(ERROR
) << "SCM_RIGHTS message was truncated"
647 << " cmsg_len:" << cmsg
->cmsg_len
649 for (unsigned i
= 0; i
< num_wire_fds
; ++i
)
650 if (HANDLE_EINTR(close(wire_fds
[i
])) < 0)
651 PLOG(ERROR
) << "close " << i
;
657 if (input_overflow_fds_
.empty()) {
659 num_fds
= num_wire_fds
;
661 if (num_wire_fds
> 0) {
662 const size_t prev_size
= input_overflow_fds_
.size();
663 input_overflow_fds_
.resize(prev_size
+ num_wire_fds
);
664 memcpy(&input_overflow_fds_
[prev_size
], wire_fds
,
665 num_wire_fds
* sizeof(int));
667 fds
= &input_overflow_fds_
[0];
668 num_fds
= input_overflow_fds_
.size();
671 if (header_fds
> num_fds
- fds_i
)
672 #endif // IPC_USES_READWRITE
673 error
= "Message needs unreceived descriptors";
677 FileDescriptorSet::MAX_DESCRIPTORS_PER_MESSAGE
) {
678 // There are too many descriptors in this message
679 error
= "Message requires an excessive number of descriptors";
683 LOG(WARNING
) << error
684 << " channel:" << this
685 << " message-type:" << m
.type()
686 << " header()->num_fds:" << header_fds
687 << " num_fds:" << num_fds
688 << " fds_i:" << fds_i
;
689 #if defined(CHROMIUM_SELINUX)
690 LOG(WARNING
) << "In the case of SELinux this can be caused when "
691 "using a --user-data-dir to which the default "
692 "policy doesn't give the renderer access to. ";
693 #endif // CHROMIUM_SELINUX
694 // close the existing file descriptors so that we don't leak them
695 for (unsigned i
= fds_i
; i
< num_fds
; ++i
)
696 if (HANDLE_EINTR(close(fds
[i
])) < 0)
697 PLOG(ERROR
) << "close " << i
;
698 input_overflow_fds_
.clear();
699 // abort the connection
703 m
.file_descriptor_set()->SetDescriptors(
704 &fds
[fds_i
], header_fds
);
707 DVLOG(2) << "received message on channel @" << this
708 << " with type " << m
.type() << " on fd " << pipe_
;
709 if (IsHelloMessage(&m
)) {
710 // The Hello message contains only the process id.
713 if (!m
.ReadInt(&iter
, &pid
)) {
716 #if defined(IPC_USES_READWRITE)
717 if (mode_
& MODE_SERVER_FLAG
) {
718 // With IPC_USES_READWRITE, the Hello message from the client to the
719 // server also contains the fd_pipe_, which will be used for all
720 // subsequent file descriptor passing.
721 DCHECK_EQ(m
.file_descriptor_set()->size(), 1U);
722 base::FileDescriptor descriptor
;
723 if (!m
.ReadFileDescriptor(&iter
, &descriptor
)) {
726 fd_pipe_
= descriptor
.fd
;
727 CHECK(descriptor
.auto_close
);
729 #endif // IPC_USES_READWRITE
730 listener_
->OnChannelConnected(pid
);
732 listener_
->OnMessageReceived(m
);
736 // Last message is partial.
739 input_overflow_fds_
= std::vector
<int>(&fds
[fds_i
], &fds
[num_fds
]);
741 fds
= vector_as_array(&input_overflow_fds_
);
742 num_fds
= input_overflow_fds_
.size();
744 input_overflow_buf_
.assign(p
, end
- p
);
745 input_overflow_fds_
= std::vector
<int>(&fds
[fds_i
], &fds
[num_fds
]);
747 // When the input data buffer is empty, the overflow fds should be too. If
748 // this is not the case, we probably have a rogue renderer which is trying
749 // to fill our descriptor table.
750 if (input_overflow_buf_
.empty() && !input_overflow_fds_
.empty()) {
751 // We close these descriptors in Close()
755 bytes_read
= 0; // Get more data.
759 bool Channel::ChannelImpl::ProcessOutgoingMessages() {
760 DCHECK(!waiting_connect_
); // Why are we trying to send messages if there's
762 if (output_queue_
.empty())
768 // Write out all the messages we can till the write blocks or there are no
769 // more outgoing messages.
770 while (!output_queue_
.empty()) {
771 Message
* msg
= output_queue_
.front();
773 size_t amt_to_write
= msg
->size() - message_send_bytes_written_
;
774 DCHECK_NE(0U, amt_to_write
);
775 const char* out_bytes
= reinterpret_cast<const char*>(msg
->data()) +
776 message_send_bytes_written_
;
778 struct msghdr msgh
= {0};
779 struct iovec iov
= {const_cast<char*>(out_bytes
), amt_to_write
};
783 sizeof(int[FileDescriptorSet::MAX_DESCRIPTORS_PER_MESSAGE
]))];
785 ssize_t bytes_written
= 1;
788 if (message_send_bytes_written_
== 0 &&
789 !msg
->file_descriptor_set()->empty()) {
790 // This is the first chunk of a message which has descriptors to send
791 struct cmsghdr
*cmsg
;
792 const unsigned num_fds
= msg
->file_descriptor_set()->size();
794 DCHECK_LE(num_fds
, FileDescriptorSet::MAX_DESCRIPTORS_PER_MESSAGE
);
795 if (msg
->file_descriptor_set()->ContainsDirectoryDescriptor()) {
796 LOG(FATAL
) << "Panic: attempting to transport directory descriptor over"
797 " IPC. Aborting to maintain sandbox isolation.";
798 // If you have hit this then something tried to send a file descriptor
799 // to a directory over an IPC channel. Since IPC channels span
800 // sandboxes this is very bad: the receiving process can use openat
801 // with ".." elements in the path in order to reach the real
805 msgh
.msg_control
= buf
;
806 msgh
.msg_controllen
= CMSG_SPACE(sizeof(int) * num_fds
);
807 cmsg
= CMSG_FIRSTHDR(&msgh
);
808 cmsg
->cmsg_level
= SOL_SOCKET
;
809 cmsg
->cmsg_type
= SCM_RIGHTS
;
810 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int) * num_fds
);
811 msg
->file_descriptor_set()->GetDescriptors(
812 reinterpret_cast<int*>(CMSG_DATA(cmsg
)));
813 msgh
.msg_controllen
= cmsg
->cmsg_len
;
815 // DCHECK_LE above already checks that
816 // num_fds < MAX_DESCRIPTORS_PER_MESSAGE so no danger of overflow.
817 msg
->header()->num_fds
= static_cast<uint16
>(num_fds
);
819 #if defined(IPC_USES_READWRITE)
820 if (!IsHelloMessage(msg
)) {
821 // Only the Hello message sends the file descriptor with the message.
822 // Subsequently, we can send file descriptors on the dedicated
823 // fd_pipe_ which makes Seccomp sandbox operation more efficient.
824 struct iovec fd_pipe_iov
= { const_cast<char *>(""), 1 };
825 msgh
.msg_iov
= &fd_pipe_iov
;
826 fd_written
= fd_pipe_
;
827 bytes_written
= HANDLE_EINTR(sendmsg(fd_pipe_
, &msgh
, MSG_DONTWAIT
));
829 msgh
.msg_controllen
= 0;
830 if (bytes_written
> 0) {
831 msg
->file_descriptor_set()->CommitAll();
834 #endif // IPC_USES_READWRITE
837 if (bytes_written
== 1) {
839 #if defined(IPC_USES_READWRITE)
840 if ((mode_
& MODE_CLIENT_FLAG
) && IsHelloMessage(msg
)) {
841 DCHECK_EQ(msg
->file_descriptor_set()->size(), 1U);
843 if (!msgh
.msg_controllen
) {
844 bytes_written
= HANDLE_EINTR(write(pipe_
, out_bytes
, amt_to_write
));
846 #endif // IPC_USES_READWRITE
848 bytes_written
= HANDLE_EINTR(sendmsg(pipe_
, &msgh
, MSG_DONTWAIT
));
851 if (bytes_written
> 0)
852 msg
->file_descriptor_set()->CommitAll();
854 if (bytes_written
< 0 && !SocketWriteErrorIsRecoverable()) {
855 #if defined(OS_MACOSX)
856 // On OSX writing to a pipe with no listener returns EPERM.
857 if (errno
== EPERM
) {
862 if (errno
== EPIPE
) {
866 PLOG(ERROR
) << "pipe error on "
868 << " Currently writing message of size: "
873 if (static_cast<size_t>(bytes_written
) != amt_to_write
) {
874 if (bytes_written
> 0) {
875 // If write() fails with EAGAIN then bytes_written will be -1.
876 message_send_bytes_written_
+= bytes_written
;
879 // Tell libevent to call us back once things are unblocked.
880 is_blocked_on_write_
= true;
881 MessageLoopForIO::current()->WatchFileDescriptor(
884 MessageLoopForIO::WATCH_WRITE
,
889 message_send_bytes_written_
= 0;
892 DVLOG(2) << "sent message @" << msg
<< " on channel @" << this
893 << " with type " << msg
->type() << " on fd " << pipe_
;
894 delete output_queue_
.front();
901 bool Channel::ChannelImpl::Send(Message
* message
) {
902 DVLOG(2) << "sending message @" << message
<< " on channel @" << this
903 << " with type " << message
->type()
904 << " (" << output_queue_
.size() << " in queue)";
906 #ifdef IPC_MESSAGE_LOG_ENABLED
907 Logging::GetInstance()->OnSendMessage(message
, "");
908 #endif // IPC_MESSAGE_LOG_ENABLED
910 output_queue_
.push(message
);
911 if (!is_blocked_on_write_
&& !waiting_connect_
) {
912 return ProcessOutgoingMessages();
918 int Channel::ChannelImpl::GetClientFileDescriptor() const {
922 bool Channel::ChannelImpl::AcceptsConnections() const {
923 return server_listen_pipe_
!= -1;
926 bool Channel::ChannelImpl::HasAcceptedConnection() const {
927 return AcceptsConnections() && pipe_
!= -1;
930 bool Channel::ChannelImpl::GetClientEuid(uid_t
* client_euid
) const {
931 DCHECK(HasAcceptedConnection());
932 #if defined(OS_MACOSX)
935 if (getpeereid(pipe_
, &peer_euid
, &peer_gid
) != 0) {
936 PLOG(ERROR
) << "getpeereid " << pipe_
;
939 *client_euid
= peer_euid
;
941 #elif defined(OS_SOLARIS)
945 socklen_t cred_len
= sizeof(cred
);
946 if (getsockopt(pipe_
, SOL_SOCKET
, SO_PEERCRED
, &cred
, &cred_len
) != 0) {
947 PLOG(ERROR
) << "getsockopt " << pipe_
;
950 if (cred_len
< sizeof(cred
)) {
951 NOTREACHED() << "Truncated ucred from SO_PEERCRED?";
954 *client_euid
= cred
.uid
;
959 void Channel::ChannelImpl::ResetToAcceptingConnectionState() {
960 // Unregister libevent for the unix domain socket and close it.
961 read_watcher_
.StopWatchingFileDescriptor();
962 write_watcher_
.StopWatchingFileDescriptor();
964 if (HANDLE_EINTR(close(pipe_
)) < 0)
965 PLOG(ERROR
) << "close pipe_ " << pipe_name_
;
968 #if defined(IPC_USES_READWRITE)
969 if (fd_pipe_
!= -1) {
970 if (HANDLE_EINTR(close(fd_pipe_
)) < 0)
971 PLOG(ERROR
) << "close fd_pipe_ " << pipe_name_
;
974 if (remote_fd_pipe_
!= -1) {
975 if (HANDLE_EINTR(close(remote_fd_pipe_
)) < 0)
976 PLOG(ERROR
) << "close remote_fd_pipe_ " << pipe_name_
;
977 remote_fd_pipe_
= -1;
979 #endif // IPC_USES_READWRITE
981 while (!output_queue_
.empty()) {
982 Message
* m
= output_queue_
.front();
987 // Close any outstanding, received file descriptors.
988 for (std::vector
<int>::iterator
989 i
= input_overflow_fds_
.begin(); i
!= input_overflow_fds_
.end(); ++i
) {
990 if (HANDLE_EINTR(close(*i
)) < 0)
991 PLOG(ERROR
) << "close";
993 input_overflow_fds_
.clear();
996 // Called by libevent when we can read from the pipe without blocking.
997 void Channel::ChannelImpl::OnFileCanReadWithoutBlocking(int fd
) {
998 bool send_server_hello_msg
= false;
999 if (fd
== server_listen_pipe_
) {
1001 if (!ServerAcceptConnection(server_listen_pipe_
, &new_pipe
)) {
1003 listener_
->OnChannelListenError();
1007 // We already have a connection. We only handle one at a time.
1008 // close our new descriptor.
1009 if (HANDLE_EINTR(shutdown(new_pipe
, SHUT_RDWR
)) < 0)
1010 PLOG(ERROR
) << "shutdown " << pipe_name_
;
1011 if (HANDLE_EINTR(close(new_pipe
)) < 0)
1012 PLOG(ERROR
) << "close " << pipe_name_
;
1013 listener_
->OnChannelDenied();
1018 if ((mode_
& MODE_OPEN_ACCESS_FLAG
) == 0) {
1019 // Verify that the IPC channel peer is running as the same user.
1021 if (!GetClientEuid(&client_euid
)) {
1022 LOG(ERROR
) << "Unable to query client euid";
1023 ResetToAcceptingConnectionState();
1026 if (client_euid
!= geteuid()) {
1027 LOG(WARNING
) << "Client euid is not authorised";
1028 ResetToAcceptingConnectionState();
1033 if (!AcceptConnection()) {
1034 NOTREACHED() << "AcceptConnection should not fail on server";
1036 send_server_hello_msg
= true;
1037 waiting_connect_
= false;
1038 } else if (fd
== pipe_
) {
1039 if (waiting_connect_
&& (mode_
& MODE_SERVER_FLAG
)) {
1040 send_server_hello_msg
= true;
1041 waiting_connect_
= false;
1043 if (!ProcessIncomingMessages()) {
1044 // ClosePipeOnError may delete this object, so we mustn't call
1045 // ProcessOutgoingMessages.
1046 send_server_hello_msg
= false;
1050 NOTREACHED() << "Unknown pipe " << fd
;
1053 // If we're a server and handshaking, then we want to make sure that we
1054 // only send our handshake message after we've processed the client's.
1055 // This gives us a chance to kill the client if the incoming handshake
1057 if (send_server_hello_msg
) {
1058 ProcessOutgoingMessages();
1062 // Called by libevent when we can write to the pipe without blocking.
1063 void Channel::ChannelImpl::OnFileCanWriteWithoutBlocking(int fd
) {
1064 DCHECK_EQ(pipe_
, fd
);
1065 is_blocked_on_write_
= false;
1066 if (!ProcessOutgoingMessages()) {
1071 bool Channel::ChannelImpl::AcceptConnection() {
1072 MessageLoopForIO::current()->WatchFileDescriptor(pipe_
,
1074 MessageLoopForIO::WATCH_READ
,
1077 QueueHelloMessage();
1079 if (mode_
& MODE_CLIENT_FLAG
) {
1080 // If we are a client we want to send a hello message out immediately.
1081 // In server mode we will send a hello message when we receive one from a
1083 waiting_connect_
= false;
1084 return ProcessOutgoingMessages();
1085 } else if (mode_
& MODE_SERVER_FLAG
) {
1086 waiting_connect_
= true;
1094 void Channel::ChannelImpl::ClosePipeOnError() {
1095 if (HasAcceptedConnection()) {
1096 ResetToAcceptingConnectionState();
1097 listener_
->OnChannelError();
1100 if (AcceptsConnections()) {
1101 listener_
->OnChannelListenError();
1103 listener_
->OnChannelError();
1108 void Channel::ChannelImpl::QueueHelloMessage() {
1109 // Create the Hello message
1110 scoped_ptr
<Message
> msg(new Message(MSG_ROUTING_NONE
,
1112 IPC::Message::PRIORITY_NORMAL
));
1114 if (!msg
->WriteInt(base::GetCurrentProcId())) {
1115 NOTREACHED() << "Unable to pickle hello message proc id";
1117 #if defined(IPC_USES_READWRITE)
1118 scoped_ptr
<Message
> hello
;
1119 if (remote_fd_pipe_
!= -1) {
1120 if (!msg
->WriteFileDescriptor(base::FileDescriptor(remote_fd_pipe_
,
1122 NOTREACHED() << "Unable to pickle hello message file descriptors";
1124 DCHECK_EQ(msg
->file_descriptor_set()->size(), 1U);
1126 #endif // IPC_USES_READWRITE
1127 output_queue_
.push(msg
.release());
1130 bool Channel::ChannelImpl::IsHelloMessage(const Message
* m
) const {
1131 return m
->routing_id() == MSG_ROUTING_NONE
&& m
->type() == HELLO_MESSAGE_TYPE
;
1134 void Channel::ChannelImpl::Close() {
1135 // Close can be called multiple time, so we need to make sure we're
1138 ResetToAcceptingConnectionState();
1141 unlink(pipe_name_
.c_str());
1142 must_unlink_
= false;
1144 if (server_listen_pipe_
!= -1) {
1145 if (HANDLE_EINTR(close(server_listen_pipe_
)) < 0)
1146 PLOG(ERROR
) << "close " << server_listen_pipe_
;
1147 server_listen_pipe_
= -1;
1148 // Unregister libevent for the listening socket and close it.
1149 server_listen_connection_watcher_
.StopWatchingFileDescriptor();
1152 if (client_pipe_
!= -1) {
1153 PipeMap::GetInstance()->RemoveAndClose(pipe_name_
);
1158 //------------------------------------------------------------------------------
1159 // Channel's methods simply call through to ChannelImpl.
1160 Channel::Channel(const IPC::ChannelHandle
& channel_handle
, Mode mode
,
1162 : channel_impl_(new ChannelImpl(channel_handle
, mode
, listener
)) {
1165 Channel::~Channel() {
1166 delete channel_impl_
;
1169 bool Channel::Connect() {
1170 return channel_impl_
->Connect();
1173 void Channel::Close() {
1174 channel_impl_
->Close();
1177 void Channel::set_listener(Listener
* listener
) {
1178 channel_impl_
->set_listener(listener
);
1181 bool Channel::Send(Message
* message
) {
1182 return channel_impl_
->Send(message
);
1185 int Channel::GetClientFileDescriptor() const {
1186 return channel_impl_
->GetClientFileDescriptor();
1189 bool Channel::AcceptsConnections() const {
1190 return channel_impl_
->AcceptsConnections();
1193 bool Channel::HasAcceptedConnection() const {
1194 return channel_impl_
->HasAcceptedConnection();
1197 bool Channel::GetClientEuid(uid_t
* client_euid
) const {
1198 return channel_impl_
->GetClientEuid(client_euid
);
1201 void Channel::ResetToAcceptingConnectionState() {
1202 channel_impl_
->ResetToAcceptingConnectionState();