1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "tools/android/forwarder2/daemon.h"
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <cstdlib>
#include <cstring>
#include <string>
#include "base/basictypes.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/posix/eintr_wrapper.h"
#include "base/safe_strerror_posix.h"
#include "base/string_number_conversions.h"
#include "base/stringprintf.h"
#include "tools/android/forwarder2/common.h"
#include "tools/android/forwarder2/socket.h"
namespace forwarder2 {
namespace {
const int kBufferSize = 256;
// Timeout constant used for polling when connecting to the daemon's Unix Domain
// Socket and also when waiting for its death when it is killed.
const int kNumTries = 100;
const int kIdleTimeMSec = 20;
void InitLoggingForDaemon(const std::string& log_file) {
CHECK(
logging::InitLogging(
log_file.c_str(),
log_file.empty() ?
logging::LOG_ONLY_TO_SYSTEM_DEBUG_LOG : logging::LOG_ONLY_TO_FILE,
logging::DONT_LOCK_LOG_FILE, logging::APPEND_TO_OLD_LOG_FILE,
logging::ENABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS));
}
bool RunServerAcceptLoop(const std::string& welcome_message,
Socket* server_socket,
Daemon::ServerDelegate* server_delegate) {
bool failed = false;
for (;;) {
scoped_ptr<Socket> client_socket(new Socket());
if (!server_socket->Accept(client_socket.get())) {
if (server_socket->exited())
break;
PError("Accept()");
failed = true;
break;
}
if (!client_socket->Write(welcome_message.c_str(),
welcome_message.length() + 1)) {
PError("Write()");
failed = true;
continue;
}
server_delegate->OnClientConnected(client_socket.Pass());
}
server_delegate->OnServerExited();
return !failed;
}
void SigChildHandler(int signal_number) {
DCHECK_EQ(signal_number, SIGCHLD);
int status;
pid_t child_pid = waitpid(-1 /* any child */, &status, WNOHANG);
if (child_pid < 0) {
PError("waitpid");
return;
}
if (child_pid == 0)
return;
if (WIFEXITED(status) && WEXITSTATUS(status) == 0)
return;
// Avoid using StringAppendF() since it's unsafe in a signal handler due to
// its use of LOG().
FixedSizeStringBuilder<256> string_builder;
string_builder.Append("Daemon (pid=%d) died unexpectedly with ", child_pid);
if (WIFEXITED(status))
string_builder.Append("status %d.", WEXITSTATUS(status));
else if (WIFSIGNALED(status))
string_builder.Append("signal %d.", WTERMSIG(status));
else
string_builder.Append("unknown reason.");
SIGNAL_SAFE_LOG(ERROR, string_builder.buffer());
}
// Note that 0 is written to |lock_owner_pid| in case the file is not locked.
bool GetFileLockOwnerPid(int fd, pid_t* lock_owner_pid) {
struct flock lock_info = {};
lock_info.l_type = F_WRLCK;
lock_info.l_whence = SEEK_CUR;
const int ret = HANDLE_EINTR(fcntl(fd, F_GETLK, &lock_info));
if (ret < 0) {
if (errno == EBADF) {
// Assume that the provided file descriptor corresponding to the PID file
// was valid until the daemon removed this file.
*lock_owner_pid = 0;
return true;
}
PError("fcntl");
return false;
}
if (lock_info.l_type == F_UNLCK) {
*lock_owner_pid = 0;
return true;
}
CHECK_EQ(F_WRLCK /* exclusive lock */, lock_info.l_type);
*lock_owner_pid = lock_info.l_pid;
return true;
}
scoped_ptr<Socket> ConnectToUnixDomainSocket(
const std::string& socket_name,
int tries_count,
int idle_time_msec,
const std::string& expected_welcome_message) {
for (int i = 0; i < tries_count; ++i) {
scoped_ptr<Socket> socket(new Socket());
if (!socket->ConnectUnix(socket_name, true)) {
if (idle_time_msec)
usleep(idle_time_msec * 1000);
continue;
}
char buf[kBufferSize];
DCHECK(expected_welcome_message.length() + 1 <= sizeof(buf));
memset(buf, 0, sizeof(buf));
if (socket->Read(buf, sizeof(buf)) < 0) {
perror("read");
continue;
}
if (expected_welcome_message != buf) {
LOG(ERROR) << "Unexpected message read from daemon: " << buf;
break;
}
return socket.Pass();
}
return scoped_ptr<Socket>(NULL);
}
} // namespace
// Handles creation and destruction of the PID file.
class Daemon::PIDFile {
public:
static bool Create(const std::string& path, scoped_ptr<PIDFile>* pid_file) {
int pid_file_fd = HANDLE_EINTR(
open(path.c_str(), O_CREAT | O_WRONLY, 0666));
if (pid_file_fd < 0) {
PError("open()");
return false;
}
file_util::ScopedFD fd_closer(&pid_file_fd);
struct flock lock_info = {};
lock_info.l_type = F_WRLCK;
lock_info.l_whence = SEEK_CUR;
if (HANDLE_EINTR(fcntl(pid_file_fd, F_SETLK, &lock_info)) < 0) {
if (errno == EAGAIN || errno == EACCES) {
LOG(INFO) << "Daemon already running (PID file already locked)";
// Don't consider this case as a failure. This can happen when trying to
// spawn multiple daemons concurrently.
return true;
}
PError("lockf()");
return false;
}
const std::string pid_string = base::StringPrintf("%d\n", getpid());
CHECK(HANDLE_EINTR(write(pid_file_fd, pid_string.c_str(),
pid_string.length())));
pid_file->reset(new PIDFile(*fd_closer.release(), path));
return true;
}
~PIDFile() {
CloseFD(fd_); // This also releases the lock.
if (remove(path_.c_str()) < 0)
PError("remove");
}
private:
PIDFile(int fd, const std::string& path) : fd_(fd), path_(path) {
DCHECK(fd_ >= 0);
}
const int fd_;
const std::string path_;
DISALLOW_COPY_AND_ASSIGN(PIDFile);
};
Daemon::Daemon(const std::string& log_file_path,
const std::string& pid_file_path,
const std::string& identifier,
ClientDelegate* client_delegate,
ServerDelegate* server_delegate,
GetExitNotifierFDCallback get_exit_fd_callback)
: log_file_path_(log_file_path),
pid_file_path_(pid_file_path),
identifier_(identifier),
client_delegate_(client_delegate),
server_delegate_(server_delegate),
get_exit_fd_callback_(get_exit_fd_callback) {
DCHECK(client_delegate_);
DCHECK(server_delegate_);
DCHECK(get_exit_fd_callback_);
}
Daemon::~Daemon() {}
bool Daemon::SpawnIfNeeded() {
const int kSingleTry = 1;
const int kNoIdleTime = 0;
scoped_ptr<Socket> client_socket = ConnectToUnixDomainSocket(
identifier_, kSingleTry, kNoIdleTime, identifier_);
if (!client_socket) {
switch (fork()) {
case -1:
PError("fork()");
return false;
// Child.
case 0: {
DCHECK(!pid_file_);
if (!PIDFile::Create(pid_file_path_, &pid_file_))
exit(1);
if (!pid_file_.get()) // Another daemon was spawn concurrently.
exit(0);
if (setsid() < 0) { // Detach the child process from its parent.
PError("setsid()");
exit(1);
}
InitLoggingForDaemon(log_file_path_);
CloseFD(STDIN_FILENO);
CloseFD(STDOUT_FILENO);
CloseFD(STDERR_FILENO);
const int null_fd = open("/dev/null", O_RDWR);
CHECK_EQ(null_fd, STDIN_FILENO);
CHECK_EQ(dup(null_fd), STDOUT_FILENO);
CHECK_EQ(dup(null_fd), STDERR_FILENO);
Socket command_socket;
if (!command_socket.BindUnix(identifier_, true)) {
PError("bind()");
exit(1);
}
server_delegate_->Init();
command_socket.set_exit_notifier_fd(get_exit_fd_callback_());
exit(!RunServerAcceptLoop(identifier_, &command_socket,
server_delegate_));
}
default:
break;
}
}
// Parent.
// Install the custom SIGCHLD handler.
sigset_t blocked_signals_set;
if (sigprocmask(0 /* first arg ignored */, NULL, &blocked_signals_set) < 0) {
PError("sigprocmask()");
return false;
}
struct sigaction old_action;
struct sigaction new_action;
memset(&new_action, 0, sizeof(new_action));
new_action.sa_handler = SigChildHandler;
new_action.sa_flags = SA_NOCLDSTOP;
sigemptyset(&new_action.sa_mask);
if (sigaction(SIGCHLD, &new_action, &old_action) < 0) {
PError("sigaction()");
return false;
}
// Connect to the daemon's Unix Domain Socket.
bool failed = false;
if (!client_socket) {
client_socket = ConnectToUnixDomainSocket(
identifier_, kNumTries, kIdleTimeMSec, identifier_);
if (!client_socket) {
LOG(ERROR) << "Could not connect to daemon's Unix Daemon socket";
failed = true;
}
}
if (!failed)
client_delegate_->OnDaemonReady(client_socket.get());
// Restore the previous signal action for SIGCHLD.
if (sigaction(SIGCHLD, &old_action, NULL) < 0) {
PError("sigaction");
failed = true;
}
return !failed;
}
bool Daemon::Kill() {
int pid_file_fd = HANDLE_EINTR(open(pid_file_path_.c_str(), O_WRONLY));
if (pid_file_fd < 0) {
if (errno == ENOENT)
return true;
LOG(ERROR) << "Could not open " << pid_file_path_ << " in write mode: "
<< safe_strerror(errno);
return false;
}
const file_util::ScopedFD fd_closer(&pid_file_fd);
pid_t lock_owner_pid;
if (!GetFileLockOwnerPid(pid_file_fd, &lock_owner_pid))
return false;
if (lock_owner_pid == 0)
// No daemon running.
return true;
if (kill(lock_owner_pid, SIGTERM) < 0) {
if (errno == ESRCH /* invalid PID */)
// The daemon exited for some reason (e.g. kill by a process other than
// us) right before the call to kill() above.
return true;
PError("kill");
return false;
}
// Wait until the daemon exits. Rely on the fact that the daemon releases the
// lock on the PID file when it exits.
// TODO(pliard): Consider using a mutex + condition in shared memory to avoid
// polling.
for (int i = 0; i < kNumTries; ++i) {
pid_t current_lock_owner_pid;
if (!GetFileLockOwnerPid(pid_file_fd, ¤t_lock_owner_pid))
return false;
if (current_lock_owner_pid == 0)
// The daemon released the PID file's lock.
return true;
// Since we are polling we might not see the 'daemon exited' event if
// another daemon was spawned during our idle period.
if (current_lock_owner_pid != lock_owner_pid) {
LOG(WARNING) << "Daemon (pid=" << lock_owner_pid
<< ") was successfully killed but a new daemon (pid="
<< current_lock_owner_pid << ") seems to be running now.";
return true;
}
usleep(kIdleTimeMSec * 1000);
}
LOG(ERROR) << "Timed out while killing daemon. "
"It might still be tearing down.";
return false;
}
} // namespace forwarder2
|