File: plugin.cxx

package info (click to toggle)
ncmpc 0.33-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 1,976 kB
  • sloc: cpp: 10,895; python: 133; makefile: 39; ruby: 28; sh: 11
file content (394 lines) | stat: -rw-r--r-- 9,006 bytes parent folder | download
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
/* ncmpc (Ncurses MPD Client)
 * (c) 2004-2018 The Music Player Daemon Project
 * Project homepage: http://musicpd.org
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "plugin.hxx"
#include "io/Path.hxx"
#include "util/Compiler.h"
#include "util/ScopeExit.hxx"
#include "util/UriUtil.hxx"

#include <boost/asio/steady_timer.hpp>
#include <boost/asio/posix/stream_descriptor.hpp>

#include <algorithm>
#include <memory>

#include <assert.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/wait.h>

struct PluginCycle;

struct PluginPipe {
	PluginCycle *cycle;

	/** the pipe to the plugin process */
	boost::asio::posix::stream_descriptor fd;

	/** the output of the current plugin */
	std::string data;

	std::array<char, 256> buffer;

	PluginPipe(boost::asio::io_service &io_service) noexcept
		:fd(io_service) {}

	~PluginPipe() noexcept {
		Close();
	}

	void AsyncRead() noexcept {
		fd.async_read_some(boost::asio::buffer(buffer),
				   std::bind(&PluginPipe::OnRead, this,
					     std::placeholders::_1,
					     std::placeholders::_2));
	}

	void OnRead(const boost::system::error_code &error,
		    std::size_t bytes_transferred) noexcept;

	void Close() noexcept {
		if (!fd.is_open())
			return;

		fd.cancel();
		fd.close();
	}
};

struct PluginCycle {
	/** the plugin list; used for traversing to the next plugin */
	PluginList *list;

	/** arguments passed to execv() */
	std::unique_ptr<char *[]> argv;

	/** caller defined callback function */
	plugin_callback_t callback;
	/** caller defined pointer passed to #callback */
	void *callback_data;

	/** the index of the next plugin which is going to be
	    invoked */
	unsigned next_plugin = 0;

	/** the pid of the plugin process, or -1 if none is currently
	    running */
	pid_t pid = -1;

	/** the stdout pipe */
	PluginPipe pipe_stdout;
	/** the stderr pipe */
	PluginPipe pipe_stderr;

	/** list of all error messages from failed plugins */
	std::string all_errors;

	boost::asio::steady_timer delayed_fail_timer;

	PluginCycle(boost::asio::io_service &io_service,
		    PluginList &_list, std::unique_ptr<char *[]> &&_argv,
		    plugin_callback_t _callback, void *_callback_data) noexcept
		:list(&_list), argv(std::move(_argv)),
		 callback(_callback), callback_data(_callback_data),
		 pipe_stdout(io_service), pipe_stderr(io_service),
		 delayed_fail_timer(io_service) {}

	void TryNextPlugin() noexcept;

	void ScheduleDelayedFail() noexcept {
		boost::system::error_code error;
		delayed_fail_timer.expires_from_now(std::chrono::seconds(0),
						    error);
		delayed_fail_timer.async_wait(std::bind(&PluginCycle::OnDelayedFail,
							this,
							std::placeholders::_1));
	}

	void OnEof() noexcept;

private:
	int LaunchPlugin(const char *plugin_path) noexcept;

	void OnDelayedFail(const boost::system::error_code &error) noexcept;
};

static bool
register_plugin(PluginList *list, std::string &&path) noexcept
{
	struct stat st;
	if (stat(path.c_str(), &st) < 0)
		return false;

	list->plugins.emplace_back(std::move(path));
	return true;
}

static constexpr bool
ShallSkipDirectoryEntry(const char *name) noexcept
{
	return name[0] == '.' && (name[1] == 0 || (name[1] == '.' && name[2] == 0));
}

bool
plugin_list_load_directory(PluginList *list, const char *path) noexcept
{
	DIR *dir = opendir(path);
	if (dir == nullptr)
		return false;

	AtScopeExit(dir) { closedir(dir); };

	while (const auto *e = readdir(dir)) {
		const char *name = e->d_name;
		if (!ShallSkipDirectoryEntry(name))
			register_plugin(list, BuildPath(path, name));
	}

	std::sort(list->plugins.begin(), list->plugins.end());

	return true;
}

void
PluginCycle::OnEof() noexcept
{
	/* Only if both pipes are have EOF status we are done */
	if (pipe_stdout.fd.is_open() || pipe_stderr.fd.is_open())
		return;

	int status, ret = waitpid(pid, &status, 0);
	pid = -1;

	if (ret < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
		/* If we encountered an error other than service unavailable
		 * (69), log it for later. If all plugins fail, we may get
		 * some hints for debugging.*/
		if (!pipe_stderr.data.empty() &&
		    WEXITSTATUS(status) != 69) {
			all_errors += "*** ";
			all_errors += argv[0];
			all_errors += " ***\n\n";
			all_errors += pipe_stderr.data;
			all_errors += "\n";
		}

		/* the plugin has failed */
		pipe_stdout.data.clear();
		pipe_stderr.data.clear();

		TryNextPlugin();
	} else {
		/* success: invoke the callback */
		callback(std::move(pipe_stdout.data), true,
			 argv[0], callback_data);
	}
}

void
PluginPipe::OnRead(const boost::system::error_code &error,
		   std::size_t bytes_transferred) noexcept
{
	if (error) {
		if (error == boost::asio::error::operation_aborted)
			/* this object has already been deleted; bail out
			   quickly without touching anything */
			return;

		fd.close();
		cycle->OnEof();
		return;
	}

	data.append(&buffer.front(), bytes_transferred);
	AsyncRead();
}

/**
 * This is a timer callback which calls the plugin callback "some time
 * later".  This solves the problem that plugin_run() may fail
 * immediately, leaving its return value in an undefined state.
 * Instead, install a timer which calls the plugin callback in the
 * moment after.
 */
void
PluginCycle::OnDelayedFail(const boost::system::error_code &error) noexcept
{
	if (error)
		return;

	assert(!pipe_stdout.fd.is_open());
	assert(!pipe_stderr.fd.is_open());
	assert(pid < 0);

	callback(std::move(all_errors), false, nullptr,
		 callback_data);
}

static void
plugin_fd_add(PluginCycle *cycle, PluginPipe *p, int fd) noexcept
{
	p->cycle = cycle;
	p->fd.assign(fd);
	p->AsyncRead();
}

int
PluginCycle::LaunchPlugin(const char *plugin_path) noexcept
{
	assert(pid < 0);
	assert(!pipe_stdout.fd.is_open());
	assert(!pipe_stderr.fd.is_open());
	assert(pipe_stdout.data.empty());
	assert(pipe_stderr.data.empty());

	/* set new program name, but free the one from the previous
	   plugin */
	argv[0] = const_cast<char *>(GetUriFilename(plugin_path));

	int fds_stdout[2];
	if (pipe(fds_stdout) < 0)
		return -1;

	int fds_stderr[2];
	if (pipe(fds_stderr) < 0) {
		close(fds_stdout[0]);
		close(fds_stdout[1]);
		return -1;
	}

	pid = fork();

	if (pid < 0) {
		close(fds_stdout[0]);
		close(fds_stdout[1]);
		close(fds_stderr[0]);
		close(fds_stderr[1]);
		return -1;
	}

	if (pid == 0) {
		dup2(fds_stdout[1], 1);
		dup2(fds_stderr[1], 2);
		close(fds_stdout[0]);
		close(fds_stdout[1]);
		close(fds_stderr[0]);
		close(fds_stderr[1]);
		close(0);
		/* XXX close other fds? */

		execv(plugin_path, argv.get());
		_exit(1);
	}

	close(fds_stdout[1]);
	close(fds_stderr[1]);

	/* XXX CLOEXEC? */

	plugin_fd_add(this, &pipe_stdout, fds_stdout[0]);
	plugin_fd_add(this, &pipe_stderr, fds_stderr[0]);

	return 0;
}

void
PluginCycle::TryNextPlugin() noexcept
{
	assert(pid < 0);
	assert(!pipe_stdout.fd.is_open());
	assert(!pipe_stderr.fd.is_open());
	assert(pipe_stdout.data.empty());
	assert(pipe_stderr.data.empty());

	if (next_plugin >= list->plugins.size()) {
		/* no plugins left */
		ScheduleDelayedFail();
		return;
	}

	const char *plugin_path = (const char *)
		list->plugins[next_plugin++].c_str();
	if (LaunchPlugin(plugin_path) < 0) {
		/* system error */
		ScheduleDelayedFail();
		return;
	}
}

static auto
make_argv(const char*const* args) noexcept
{
	unsigned num = 0;
	while (args[num] != nullptr)
		++num;
	num += 2;

	std::unique_ptr<char *[]> result(new char *[num]);

	char **ret = result.get();

	/* reserve space for the program name */
	*ret++ = nullptr;

	while (*args != nullptr)
		*ret++ = const_cast<char *>(*args++);

	/* end of argument vector */
	*ret++ = nullptr;

	return result;
}

PluginCycle *
plugin_run(boost::asio::io_service &io_service,
	   PluginList *list, const char *const*args,
	   plugin_callback_t callback, void *callback_data) noexcept
{
	assert(args != nullptr);

	auto *cycle = new PluginCycle(io_service, *list, make_argv(args),
				      callback, callback_data);
	cycle->TryNextPlugin();

	return cycle;
}

void
plugin_stop(PluginCycle *cycle) noexcept
{
	if (cycle->pid > 0) {
		/* kill the plugin process */

		cycle->pipe_stdout.Close();
		cycle->pipe_stderr.Close();

		int status;

		kill(cycle->pid, SIGTERM);
		waitpid(cycle->pid, &status, 0);
	}

	delete cycle;
}