1 // Copyright 2014 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 "chrome/browser/apps/app_shim/unix_domain_socket_acceptor.h"
7 #include "base/files/file_util.h"
8 #include "base/files/scoped_file.h"
9 #include "base/logging.h"
10 #include "ipc/unix_domain_socket_util.h"
14 UnixDomainSocketAcceptor::UnixDomainSocketAcceptor(const base::FilePath
& path
,
16 : path_(path
), delegate_(delegate
), listen_fd_(-1) {
21 UnixDomainSocketAcceptor::~UnixDomainSocketAcceptor() {
25 bool UnixDomainSocketAcceptor::CreateSocket() {
26 DCHECK(listen_fd_
< 0);
29 return IPC::CreateServerUnixDomainSocket(path_
, &listen_fd_
);
32 bool UnixDomainSocketAcceptor::Listen() {
36 // Watch the fd for connections, and turn any connections into
38 base::MessageLoopForIO::current()->WatchFileDescriptor(
41 base::MessageLoopForIO::WATCH_READ
,
42 &server_listen_connection_watcher_
,
47 // Called by libevent when we can read from the fd without blocking.
48 void UnixDomainSocketAcceptor::OnFileCanReadWithoutBlocking(int fd
) {
49 DCHECK(fd
== listen_fd_
);
51 if (!IPC::ServerAcceptConnection(listen_fd_
, &new_fd
)) {
53 delegate_
->OnListenError();
56 base::ScopedFD
scoped_fd(new_fd
);
58 if (!scoped_fd
.is_valid()) {
59 // The accept() failed, but not in such a way that the factory needs to be
64 // Verify that the IPC channel peer is running as the same user.
65 if (!IPC::IsPeerAuthorized(scoped_fd
.get()))
68 IPC::ChannelHandle
handle(std::string(),
69 base::FileDescriptor(scoped_fd
.release(), true));
70 delegate_
->OnClientConnected(handle
);
73 void UnixDomainSocketAcceptor::OnFileCanWriteWithoutBlocking(int fd
) {
74 NOTREACHED() << "Listen fd should never be writable.";
77 void UnixDomainSocketAcceptor::Close() {
80 if (IGNORE_EINTR(close(listen_fd_
)) < 0)
81 PLOG(ERROR
) << "close";
83 if (unlink(path_
.value().c_str()) < 0)
84 PLOG(ERROR
) << "unlink";
86 // Unregister libevent for the listening socket and close it.
87 server_listen_connection_watcher_
.StopWatchingFileDescriptor();