1 // Copyright 2013 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_factory.h"
7 #include "base/file_util.h"
8 #include "base/logging.h"
9 #include "ipc/unix_domain_socket_util.h"
13 ChannelFactory::ChannelFactory(const base::FilePath
& path
, Delegate
* delegate
)
14 : path_(path
), delegate_(delegate
), listen_fd_(-1) {
19 ChannelFactory::~ChannelFactory() {
23 bool ChannelFactory::CreateSocket() {
24 DCHECK(listen_fd_
< 0);
27 return CreateServerUnixDomainSocket(path_
, &listen_fd_
);
30 bool ChannelFactory::Listen() {
34 // Watch the fd for connections, and turn any connections into
36 base::MessageLoopForIO::current()->WatchFileDescriptor(
39 base::MessageLoopForIO::WATCH_READ
,
40 &server_listen_connection_watcher_
,
45 // Called by libevent when we can read from the fd without blocking.
46 void ChannelFactory::OnFileCanReadWithoutBlocking(int fd
) {
47 DCHECK(fd
== listen_fd_
);
49 if (!ServerAcceptConnection(listen_fd_
, &new_fd
)) {
51 delegate_
->OnListenError();
56 // The accept() failed, but not in such a way that the factory needs to be
61 file_util::ScopedFD
scoped_fd(&new_fd
);
63 // Verify that the IPC channel peer is running as the same user.
64 if (!IsPeerAuthorized(new_fd
))
67 ChannelHandle
handle(std::string(),
68 base::FileDescriptor(*scoped_fd
.release(), true));
69 delegate_
->OnClientConnected(handle
);
72 void ChannelFactory::OnFileCanWriteWithoutBlocking(int fd
) {
73 NOTREACHED() << "Listen fd should never be writable.";
76 void ChannelFactory::Close() {
79 if (HANDLE_EINTR(close(listen_fd_
)) < 0)
80 PLOG(ERROR
) << "close";
82 if (unlink(path_
.value().c_str()) < 0)
83 PLOG(ERROR
) << "unlink";
85 // Unregister libevent for the listening socket and close it.
86 server_listen_connection_watcher_
.StopWatchingFileDescriptor();