DevTools: consistently use camel case for URL parameter names
[chromium-blink-merge.git] / ipc / ipc_channel_posix.cc
blob9cb78aa800aa9751d7ab6cca36bb421cecd3a2de
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"
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <stddef.h>
10 #include <sys/types.h>
11 #include <sys/socket.h>
12 #include <sys/stat.h>
13 #include <sys/un.h>
15 #include <string>
16 #include <map>
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"
36 namespace IPC {
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 //------------------------------------------------------------------------------
53 namespace {
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
80 // this scheme.
82 class PipeMap {
83 public:
84 static PipeMap* GetInstance() {
85 return Singleton<PipeMap>::get();
88 ~PipeMap() {
89 // Shouldn't have left over pipes.
90 DCHECK(map_.empty());
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);
98 if (i == map_.end())
99 return -1;
100 return i->second;
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;
112 map_.erase(i);
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_);
120 DCHECK_NE(-1, fd);
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;
129 private:
130 base::Lock lock_;
131 typedef std::map<std::string, int> ChannelToFDMap;
132 ChannelToFDMap map_;
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
143 // for connections.
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) {
151 return false;
154 // Create socket.
155 int fd = socket(AF_UNIX, SOCK_STREAM, 0);
156 if (fd < 0) {
157 return false;
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;
165 return false;
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)) {
175 return false;
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;
188 // Bind the socket.
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;
194 return false;
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;
203 return false;
206 *server_listen_fd = fd;
207 return true;
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));
215 if (accept_fd < 0)
216 return false;
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;
221 return false;
224 *server_socket = accept_fd;
225 return true;
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) {
235 return false;
238 // Create socket.
239 int fd = socket(AF_UNIX, SOCK_STREAM, 0);
240 if (fd < 0) {
241 PLOG(ERROR) << "socket " << pipe_name;
242 return false;
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;
250 return false;
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;
268 return false;
271 *client_socket = fd;
272 return true;
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;
289 #else
290 return errno == EAGAIN;
291 #endif // OS_MACOSX
294 } // namespace
295 //------------------------------------------------------------------------------
297 Channel::ChannelImpl::ChannelImpl(const IPC::ChannelHandle& channel_handle,
298 Mode mode, Listener* listener)
299 : mode_(mode),
300 is_blocked_on_write_(false),
301 waiting_connect_(true),
302 message_send_bytes_written_(0),
303 server_listen_pipe_(-1),
304 pipe_(-1),
305 client_pipe_(-1),
306 #if defined(IPC_USES_READWRITE)
307 fd_pipe_(-1),
308 remote_fd_pipe_(-1),
309 #endif // IPC_USES_READWRITE
310 pipe_name_(channel_handle.name),
311 listener_(listener),
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() {
325 Close();
328 bool SocketPair(int* fd1, int* fd2) {
329 int pipe_fds[2];
330 if (socketpair(AF_UNIX, SOCK_STREAM, 0, pipe_fds) != 0) {
331 PLOG(ERROR) << "socketpair()";
332 return false;
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";
343 return false;
346 *fd1 = pipe_fds[0];
347 *fd2 = pipe_fds[1];
349 return true;
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
360 // in unittesting.
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.
365 int local_pipe = -1;
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);
373 if (value == -1) {
374 PLOG(ERROR) << "fcntl(F_GETFL) " << pipe_name_;
375 return false;
377 if (!(value & O_NONBLOCK)) {
378 LOG(ERROR) << "Socket " << pipe_name_ << " must be O_NONBLOCK";
379 return false;
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)) {
386 return false;
388 must_unlink_ = true;
389 } else if (mode_ & MODE_CLIENT_FLAG) {
390 if (!CreateClientUnixDomainSocket(pipe_name_, &local_pipe)) {
391 return false;
393 } else {
394 LOG(ERROR) << "Bad mode: " << mode_;
395 return false;
397 } else {
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_);
405 } else {
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 "
413 << pipe_name_;
414 return false;
416 used_initial_channel = true;
418 local_pipe =
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_;
425 return false;
427 if (!SocketPair(&local_pipe, &client_pipe_))
428 return false;
429 PipeMap::GetInstance()->Insert(pipe_name_, client_pipe_);
430 } else {
431 LOG(ERROR) << "Bad mode: " << mode_;
432 return false;
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_)) {
441 return false;
444 #endif // IPC_USES_READWRITE
446 if ((mode_ & MODE_SERVER_FLAG) && (mode_ & MODE_NAMED_FLAG)) {
447 server_listen_pipe_ = local_pipe;
448 local_pipe = -1;
451 pipe_ = local_pipe;
452 return true;
455 bool Channel::ChannelImpl::Connect() {
456 if (server_listen_pipe_ == -1 && pipe_ == -1) {
457 DLOG(INFO) << "Channel creation failed: " << pipe_name_;
458 return false;
461 bool did_connect = true;
462 if (server_listen_pipe_ != -1) {
463 // Watch the pipe for connections, and turn any connections into
464 // active sockets.
465 MessageLoopForIO::current()->WatchFileDescriptor(
466 server_listen_pipe_,
467 true,
468 MessageLoopForIO::WATCH_READ,
469 &server_listen_connection_watcher_,
470 this);
471 } else {
472 did_connect = AcceptConnection();
474 return did_connect;
477 bool Channel::ChannelImpl::ProcessIncomingMessages() {
478 ssize_t bytes_read = 0;
480 struct msghdr msg = {0};
481 struct iovec iov = {input_buf_, Channel::kReadBufferSize};
483 msg.msg_iovlen = 1;
484 msg.msg_control = input_cmsg_buf_;
486 for (;;) {
487 msg.msg_iov = &iov;
489 if (bytes_read == 0) {
490 if (pipe_ == -1)
491 return false;
493 // Read from pipe.
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)
497 if (fd_pipe_ >= 0) {
498 bytes_read = HANDLE_EINTR(read(pipe_, input_buf_,
499 Channel::kReadBufferSize));
500 msg.msg_controllen = 0;
501 } else
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) {
509 return true;
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
514 // to the console.
515 return false;
516 #endif // OS_MACOSX
517 } else if (errno == ECONNRESET || errno == EPIPE) {
518 return false;
519 } else {
520 PLOG(ERROR) << "pipe error (" << pipe_ << ")";
521 return false;
523 } else if (bytes_read == 0) {
524 // The pipe has closed...
525 return false;
528 DCHECK(bytes_read);
530 if (client_pipe_ != -1) {
531 PipeMap::GetInstance()->RemoveAndClose(pipe_name_);
532 client_pipe_ = -1;
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:
546 // int main() {
547 // struct msghdr msg;
548 // msg.msg_control = &msg;
549 // msg.msg_controllen = 0;
550 // if (CMSG_FIRSTHDR(&msg))
551 // printf("Bug found!\n");
552 // }
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
568 << " fd:" << pipe_;
569 for (unsigned i = 0; i < num_wire_fds; ++i)
570 if (HANDLE_EINTR(close(wire_fds[i])) < 0)
571 PLOG(ERROR) << "close " << i;
572 return false;
574 break;
579 // Process messages from input buffer.
580 const char *p;
581 const char *end;
582 if (input_overflow_buf_.empty()) {
583 p = input_buf_;
584 end = p + bytes_read;
585 } else {
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";
590 return false;
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()) {
604 fds = wire_fds;
605 num_fds = num_wire_fds;
606 } else {
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();
617 while (p < end) {
618 const char* message_tail = Message::FindNext(p, end);
619 if (message_tail) {
620 int len = static_cast<int>(message_tail - p);
621 Message m(p, len);
622 const uint16 header_fds = m.header()->num_fds;
623 if (header_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)
630 char dummy;
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
648 << " fd:" << pipe_;
649 for (unsigned i = 0; i < num_wire_fds; ++i)
650 if (HANDLE_EINTR(close(wire_fds[i])) < 0)
651 PLOG(ERROR) << "close " << i;
652 return false;
654 break;
657 if (input_overflow_fds_.empty()) {
658 fds = wire_fds;
659 num_fds = num_wire_fds;
660 } else {
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";
676 if (header_fds >
677 FileDescriptorSet::MAX_DESCRIPTORS_PER_MESSAGE) {
678 // There are too many descriptors in this message
679 error = "Message requires an excessive number of descriptors";
682 if (error) {
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
700 return false;
703 m.file_descriptor_set()->SetDescriptors(
704 &fds[fds_i], header_fds);
705 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.
711 void *iter = NULL;
712 int pid;
713 if (!m.ReadInt(&iter, &pid)) {
714 NOTREACHED();
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)) {
724 NOTREACHED();
726 fd_pipe_ = descriptor.fd;
727 CHECK(descriptor.auto_close);
729 #endif // IPC_USES_READWRITE
730 listener_->OnChannelConnected(pid);
731 } else {
732 listener_->OnMessageReceived(m);
734 p = message_tail;
735 } else {
736 // Last message is partial.
737 break;
739 input_overflow_fds_ = std::vector<int>(&fds[fds_i], &fds[num_fds]);
740 fds_i = 0;
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()
752 return false;
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
761 // no connection?
762 if (output_queue_.empty())
763 return true;
765 if (pipe_ == -1)
766 return false;
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};
780 msgh.msg_iov = &iov;
781 msgh.msg_iovlen = 1;
782 char buf[CMSG_SPACE(
783 sizeof(int[FileDescriptorSet::MAX_DESCRIPTORS_PER_MESSAGE]))];
785 ssize_t bytes_written = 1;
786 int fd_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
802 // filesystem.
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));
828 msgh.msg_iov = &iov;
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) {
838 fd_written = pipe_;
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));
845 } else
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) {
858 Close();
859 return false;
861 #endif // OS_MACOSX
862 if (errno == EPIPE) {
863 Close();
864 return false;
866 PLOG(ERROR) << "pipe error on "
867 << fd_written
868 << " Currently writing message of size: "
869 << msg->size();
870 return false;
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(
882 pipe_,
883 false, // One shot
884 MessageLoopForIO::WATCH_WRITE,
885 &write_watcher_,
886 this);
887 return true;
888 } else {
889 message_send_bytes_written_ = 0;
891 // Message sent OK!
892 DVLOG(2) << "sent message @" << msg << " on channel @" << this
893 << " with type " << msg->type() << " on fd " << pipe_;
894 delete output_queue_.front();
895 output_queue_.pop();
898 return true;
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();
915 return true;
918 int Channel::ChannelImpl::GetClientFileDescriptor() const {
919 return client_pipe_;
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)
933 uid_t peer_euid;
934 gid_t peer_gid;
935 if (getpeereid(pipe_, &peer_euid, &peer_gid) != 0) {
936 PLOG(ERROR) << "getpeereid " << pipe_;
937 return false;
939 *client_euid = peer_euid;
940 return true;
941 #elif defined(OS_SOLARIS)
942 return false;
943 #else
944 struct ucred cred;
945 socklen_t cred_len = sizeof(cred);
946 if (getsockopt(pipe_, SOL_SOCKET, SO_PEERCRED, &cred, &cred_len) != 0) {
947 PLOG(ERROR) << "getsockopt " << pipe_;
948 return false;
950 if (cred_len < sizeof(cred)) {
951 NOTREACHED() << "Truncated ucred from SO_PEERCRED?";
952 return false;
954 *client_euid = cred.uid;
955 return true;
956 #endif
959 void Channel::ChannelImpl::ResetToAcceptingConnectionState() {
960 // Unregister libevent for the unix domain socket and close it.
961 read_watcher_.StopWatchingFileDescriptor();
962 write_watcher_.StopWatchingFileDescriptor();
963 if (pipe_ != -1) {
964 if (HANDLE_EINTR(close(pipe_)) < 0)
965 PLOG(ERROR) << "close pipe_ " << pipe_name_;
966 pipe_ = -1;
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_;
972 fd_pipe_ = -1;
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();
983 output_queue_.pop();
984 delete m;
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_) {
1000 int new_pipe = 0;
1001 if (!ServerAcceptConnection(server_listen_pipe_, &new_pipe)) {
1002 Close();
1003 listener_->OnChannelListenError();
1006 if (pipe_ != -1) {
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();
1014 return;
1016 pipe_ = new_pipe;
1018 if ((mode_ & MODE_OPEN_ACCESS_FLAG) == 0) {
1019 // Verify that the IPC channel peer is running as the same user.
1020 uid_t client_euid;
1021 if (!GetClientEuid(&client_euid)) {
1022 LOG(ERROR) << "Unable to query client euid";
1023 ResetToAcceptingConnectionState();
1024 return;
1026 if (client_euid != geteuid()) {
1027 LOG(WARNING) << "Client euid is not authorised";
1028 ResetToAcceptingConnectionState();
1029 return;
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;
1047 ClosePipeOnError();
1049 } else {
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
1056 // is invalid.
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()) {
1067 ClosePipeOnError();
1071 bool Channel::ChannelImpl::AcceptConnection() {
1072 MessageLoopForIO::current()->WatchFileDescriptor(pipe_,
1073 true,
1074 MessageLoopForIO::WATCH_READ,
1075 &read_watcher_,
1076 this);
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
1082 // client.
1083 waiting_connect_ = false;
1084 return ProcessOutgoingMessages();
1085 } else if (mode_ & MODE_SERVER_FLAG) {
1086 waiting_connect_ = true;
1087 return true;
1088 } else {
1089 NOTREACHED();
1090 return false;
1094 void Channel::ChannelImpl::ClosePipeOnError() {
1095 if (HasAcceptedConnection()) {
1096 ResetToAcceptingConnectionState();
1097 listener_->OnChannelError();
1098 } else {
1099 Close();
1100 if (AcceptsConnections()) {
1101 listener_->OnChannelListenError();
1102 } else {
1103 listener_->OnChannelError();
1108 void Channel::ChannelImpl::QueueHelloMessage() {
1109 // Create the Hello message
1110 scoped_ptr<Message> msg(new Message(MSG_ROUTING_NONE,
1111 HELLO_MESSAGE_TYPE,
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_,
1121 false))) {
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
1136 // idempotent.
1138 ResetToAcceptingConnectionState();
1140 if (must_unlink_) {
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_);
1154 client_pipe_ = -1;
1158 //------------------------------------------------------------------------------
1159 // Channel's methods simply call through to ChannelImpl.
1160 Channel::Channel(const IPC::ChannelHandle& channel_handle, Mode mode,
1161 Listener* listener)
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();
1205 } // namespace IPC