Connection.cxx 13.8 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2017 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 * http://www.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 "config.h"
#include "Connection.hxx"
#include "Lease.hxx"
#include "Callback.hxx"
24
#include "event/Loop.hxx"
25
#include "system/fd_util.h"
26
#include "util/RuntimeError.hxx"
27 28 29 30 31 32 33

extern "C" {
#include <nfsc/libnfs.h>
}

#include <utility>

34 35
#include <poll.h> /* for POLLIN, POLLOUT */

36 37
static constexpr std::chrono::steady_clock::duration NFS_MOUNT_TIMEOUT =
	std::chrono::minutes(1);
38

39
inline void
40
NfsConnection::CancellableCallback::Stat(nfs_context *ctx,
41
					 const char *path)
42
{
43 44
	assert(connection.GetEventLoop().IsInside());

45
	int result = nfs_stat_async(ctx, path, Callback, this);
46 47 48
	if (result < 0)
		throw FormatRuntimeError("nfs_stat_async() failed: %s",
					 nfs_get_error(ctx));
49 50
}

51
inline void
52
NfsConnection::CancellableCallback::OpenDirectory(nfs_context *ctx,
53
						  const char *path)
54
{
55 56
	assert(connection.GetEventLoop().IsInside());

57
	int result = nfs_opendir_async(ctx, path, Callback, this);
58 59 60
	if (result < 0)
		throw FormatRuntimeError("nfs_opendir_async() failed: %s",
					 nfs_get_error(ctx));
61 62
}

63
inline void
64
NfsConnection::CancellableCallback::Open(nfs_context *ctx,
65
					 const char *path, int flags)
66
{
67 68
	assert(connection.GetEventLoop().IsInside());

69 70
	int result = nfs_open_async(ctx, path, flags,
				    Callback, this);
71 72 73
	if (result < 0)
		throw FormatRuntimeError("nfs_open_async() failed: %s",
					 nfs_get_error(ctx));
74 75
}

76
inline void
77
NfsConnection::CancellableCallback::Stat(nfs_context *ctx,
78
					 struct nfsfh *fh)
79
{
80 81
	assert(connection.GetEventLoop().IsInside());

82
	int result = nfs_fstat_async(ctx, fh, Callback, this);
83 84 85
	if (result < 0)
		throw FormatRuntimeError("nfs_fstat_async() failed: %s",
					 nfs_get_error(ctx));
86 87
}

88
inline void
89
NfsConnection::CancellableCallback::Read(nfs_context *ctx, struct nfsfh *fh,
90
					 uint64_t offset, size_t size)
91
{
92 93
	assert(connection.GetEventLoop().IsInside());

94
	int result = nfs_pread_async(ctx, fh, offset, size, Callback, this);
95 96 97
	if (result < 0)
		throw FormatRuntimeError("nfs_pread_async() failed: %s",
					 nfs_get_error(ctx));
98 99
}

100 101 102
inline void
NfsConnection::CancellableCallback::CancelAndScheduleClose(struct nfsfh *fh)
{
103
	assert(connection.GetEventLoop().IsInside());
104 105 106 107 108 109 110 111
	assert(!open);
	assert(close_fh == nullptr);
	assert(fh != nullptr);

	close_fh = fh;
	Cancel();
}

112 113 114 115 116 117 118 119 120 121 122
inline void
NfsConnection::CancellableCallback::PrepareDestroyContext()
{
	assert(IsCancelled());

	if (close_fh != nullptr) {
		connection.InternalClose(close_fh);
		close_fh = nullptr;
	}
}

123 124 125
inline void
NfsConnection::CancellableCallback::Callback(int err, void *data)
{
126 127
	assert(connection.GetEventLoop().IsInside());

128
	if (!IsCancelled()) {
129 130
		assert(close_fh == nullptr);

131 132 133 134 135 136 137
		NfsCallback &cb = Get();

		connection.callbacks.Remove(*this);

		if (err >= 0)
			cb.OnNfsCallback((unsigned)err, data);
		else
138
			cb.OnNfsError(std::make_exception_ptr(std::runtime_error((const char *)data)));
139
	} else {
140 141 142 143
		if (open) {
			/* a nfs_open_async() call was cancelled - to
			   avoid a memory leak, close the newly
			   allocated file handle immediately */
144 145
			assert(close_fh == nullptr);

146 147 148 149
			if (err >= 0) {
				struct nfsfh *fh = (struct nfsfh *)data;
				connection.Close(fh);
			}
150 151
		} else if (close_fh != nullptr)
			connection.DeferClose(close_fh);
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
		connection.callbacks.Remove(*this);
	}
}

void
NfsConnection::CancellableCallback::Callback(int err,
					     gcc_unused struct nfs_context *nfs,
					     void *data, void *private_data)
{
	CancellableCallback &c = *(CancellableCallback *)private_data;
	c.Callback(err, data);
}

static constexpr unsigned
libnfs_to_events(int i)
{
	return ((i & POLLIN) ? SocketMonitor::READ : 0) |
		((i & POLLOUT) ? SocketMonitor::WRITE : 0);
}

static constexpr int
events_to_libnfs(unsigned i)
{
	return ((i & SocketMonitor::READ) ? POLLIN : 0) |
		((i & SocketMonitor::WRITE) ? POLLOUT : 0);
}

NfsConnection::~NfsConnection()
{
182
	assert(GetEventLoop().IsInside());
183 184 185
	assert(new_leases.empty());
	assert(active_leases.empty());
	assert(callbacks.IsEmpty());
186
	assert(deferred_close.empty());
187 188

	if (context != nullptr)
189
		DestroyContext();
190 191 192 193 194
}

void
NfsConnection::AddLease(NfsLease &lease)
{
195 196 197
	assert(GetEventLoop().IsInside());

	new_leases.push_back(&lease);
198 199 200 201 202 203 204

	DeferredMonitor::Schedule();
}

void
NfsConnection::RemoveLease(NfsLease &lease)
{
205
	assert(GetEventLoop().IsInside());
206 207 208 209 210

	new_leases.remove(&lease);
	active_leases.remove(&lease);
}

211 212
void
NfsConnection::Stat(const char *path, NfsCallback &callback)
213
{
214
	assert(GetEventLoop().IsInside());
215 216 217
	assert(!callbacks.Contains(callback));

	auto &c = callbacks.Add(callback, *this, false);
218 219 220
	try {
		c.Stat(context, path);
	} catch (...) {
221
		callbacks.Remove(c);
222
		throw;
223 224 225 226 227
	}

	ScheduleSocket();
}

228 229
void
NfsConnection::OpenDirectory(const char *path, NfsCallback &callback)
230
{
231
	assert(GetEventLoop().IsInside());
232 233 234
	assert(!callbacks.Contains(callback));

	auto &c = callbacks.Add(callback, *this, true);
235 236 237
	try {
		c.OpenDirectory(context, path);
	} catch (...) {
238
		callbacks.Remove(c);
239
		throw;
240 241 242 243 244 245 246 247
	}

	ScheduleSocket();
}

const struct nfsdirent *
NfsConnection::ReadDirectory(struct nfsdir *dir)
{
248 249
	assert(GetEventLoop().IsInside());

250 251 252 253 254 255
	return nfs_readdir(context, dir);
}

void
NfsConnection::CloseDirectory(struct nfsdir *dir)
{
256 257
	assert(GetEventLoop().IsInside());

258 259 260
	return nfs_closedir(context, dir);
}

261 262
void
NfsConnection::Open(const char *path, int flags, NfsCallback &callback)
263
{
264
	assert(GetEventLoop().IsInside());
265 266
	assert(!callbacks.Contains(callback));

267
	auto &c = callbacks.Add(callback, *this, true);
268 269 270
	try {
		c.Open(context, path, flags);
	} catch (...) {
271
		callbacks.Remove(c);
272
		throw;
273 274 275 276 277
	}

	ScheduleSocket();
}

278 279
void
NfsConnection::Stat(struct nfsfh *fh, NfsCallback &callback)
280
{
281
	assert(GetEventLoop().IsInside());
282 283
	assert(!callbacks.Contains(callback));

284
	auto &c = callbacks.Add(callback, *this, false);
285 286 287
	try {
		c.Stat(context, fh);
	} catch (...) {
288
		callbacks.Remove(c);
289
		throw;
290 291 292 293 294
	}

	ScheduleSocket();
}

295
void
296
NfsConnection::Read(struct nfsfh *fh, uint64_t offset, size_t size,
297
		    NfsCallback &callback)
298
{
299
	assert(GetEventLoop().IsInside());
300 301
	assert(!callbacks.Contains(callback));

302
	auto &c = callbacks.Add(callback, *this, false);
303 304 305
	try {
		c.Read(context, fh, offset, size);
	} catch (...) {
306
		callbacks.Remove(c);
307
		throw;
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
	}

	ScheduleSocket();
}

void
NfsConnection::Cancel(NfsCallback &callback)
{
	callbacks.Cancel(callback);
}

static void
DummyCallback(int, struct nfs_context *, void *, void *)
{
}

324 325 326 327 328 329 330 331 332 333
inline void
NfsConnection::InternalClose(struct nfsfh *fh)
{
	assert(GetEventLoop().IsInside());
	assert(context != nullptr);
	assert(fh != nullptr);

	nfs_close_async(context, fh, DummyCallback, nullptr);
}

334 335 336
void
NfsConnection::Close(struct nfsfh *fh)
{
337 338
	assert(GetEventLoop().IsInside());

339
	InternalClose(fh);
340 341 342
	ScheduleSocket();
}

343 344 345 346 347 348 349
void
NfsConnection::CancelAndClose(struct nfsfh *fh, NfsCallback &callback)
{
	CancellableCallback &cancel = callbacks.Get(callback);
	cancel.CancelAndScheduleClose(fh);
}

350 351 352
void
NfsConnection::DestroyContext()
{
353
	assert(GetEventLoop().IsInside());
354 355
	assert(context != nullptr);

356 357 358 359 360
#ifndef NDEBUG
	assert(!in_destroy);
	in_destroy = true;
#endif

361 362 363 364 365
	if (!mount_finished) {
		assert(TimeoutMonitor::IsActive());
		TimeoutMonitor::Cancel();
	}

366 367 368 369
	/* cancel pending DeferredMonitor that was scheduled to notify
	   new leases */
	DeferredMonitor::Cancel();

370
	if (SocketMonitor::IsDefined())
371
		SocketMonitor::Steal();
372

373 374 375 376
	callbacks.ForEach([](CancellableCallback &c){
			c.PrepareDestroyContext();
		});

377 378 379 380
	nfs_destroy_context(context);
	context = nullptr;
}

381 382 383
inline void
NfsConnection::DeferClose(struct nfsfh *fh)
{
384
	assert(GetEventLoop().IsInside());
385 386
	assert(in_event);
	assert(in_service);
387 388
	assert(context != nullptr);
	assert(fh != nullptr);
389 390 391 392

	deferred_close.push_front(fh);
}

393 394 395
void
NfsConnection::ScheduleSocket()
{
396
	assert(GetEventLoop().IsInside());
397 398
	assert(context != nullptr);

399 400 401 402 403 404 405 406 407 408 409
	const int which_events = nfs_which_events(context);

	if (which_events == POLLOUT && SocketMonitor::IsDefined())
		/* kludge: if libnfs asks only for POLLOUT, it means
		   that it is currently waiting for the connect() to
		   finish - rpc_reconnect_requeue() may have been
		   called from inside nfs_service(); we must now
		   unregister the old socket and register the new one
		   instead */
		SocketMonitor::Steal();

410 411
	if (!SocketMonitor::IsDefined()) {
		int _fd = nfs_get_fd(context);
412 413 414
		if (_fd < 0)
			return;

415 416 417 418
		fd_set_cloexec(_fd, true);
		SocketMonitor::Open(_fd);
	}

419 420
	SocketMonitor::Schedule(libnfs_to_events(which_events)
				| SocketMonitor::HANGUP);
421 422
}

423 424
inline int
NfsConnection::Service(unsigned flags)
425
{
426
	assert(GetEventLoop().IsInside());
427
	assert(context != nullptr);
428

429
#ifndef NDEBUG
430 431 432 433 434
	assert(!in_event);
	in_event = true;

	assert(!in_service);
	in_service = true;
435
#endif
436 437 438

	int result = nfs_service(context, events_to_libnfs(flags));

439
#ifndef NDEBUG
440 441 442
	assert(context != nullptr);
	assert(in_service);
	in_service = false;
443
#endif
444

445 446 447 448 449 450 451 452 453 454 455 456
	return result;
}

bool
NfsConnection::OnSocketReady(unsigned flags)
{
	assert(GetEventLoop().IsInside());
	assert(deferred_close.empty());

	bool closed = false;

	const bool was_mounted = mount_finished;
457
	if (!mount_finished || (flags & SocketMonitor::HANGUP) != 0)
458 459 460
		/* until the mount is finished, the NFS client may use
		   various sockets, therefore we unregister and
		   re-register it each time */
461 462 463 464
		/* also re-register the socket if we got a HANGUP,
		   which is a sure sign that libnfs will close the
		   socket, which can lead to a race condition if
		   epoll_ctl() is called later */
465 466 467 468
		SocketMonitor::Steal();

	const int result = Service(flags);

469
	while (!deferred_close.empty()) {
470
		InternalClose(deferred_close.front());
471 472 473
		deferred_close.pop_front();
	}

474
	if (!was_mounted && mount_finished) {
475
		if (postponed_mount_error) {
476 477 478 479 480 481 482 483
			DestroyContext();
			closed = true;
			BroadcastMountError(std::move(postponed_mount_error));
		} else if (result == 0)
			BroadcastMountSuccess();
	} else if (result < 0) {
		/* the connection has failed */

484 485 486
		auto e = FormatRuntimeError("NFS connection has failed: %s",
					    nfs_get_error(context));
		BroadcastError(std::make_exception_ptr(e));
487

488 489
		DestroyContext();
		closed = true;
490
	} else if (nfs_get_fd(context) < 0) {
491
		/* this happens when rpc_reconnect_requeue() is called
492
		   after the connection broke, but autoreconnect was
493
		   disabled - nfs_service() returns 0 */
494

495 496
		const char *msg = nfs_get_error(context);
		if (msg == nullptr)
497 498
			msg = "<unknown>";
		auto e = FormatRuntimeError("NFS socket disappeared: %s", msg);
499

500
		BroadcastError(std::make_exception_ptr(e));
501

502 503
		DestroyContext();
		closed = true;
504 505
	}

506 507
	assert(context == nullptr || nfs_get_fd(context) >= 0);

508
#ifndef NDEBUG
509 510
	assert(in_event);
	in_event = false;
511
#endif
512 513 514 515 516 517 518 519 520 521 522

	if (context != nullptr)
		ScheduleSocket();

	return !closed;
}

inline void
NfsConnection::MountCallback(int status, gcc_unused nfs_context *nfs,
			     gcc_unused void *data)
{
523
	assert(GetEventLoop().IsInside());
524 525 526 527
	assert(context == nfs);

	mount_finished = true;

528 529 530
	assert(TimeoutMonitor::IsActive() || in_destroy);
	TimeoutMonitor::Cancel();

531
	if (status < 0) {
532 533 534
		auto e = FormatRuntimeError("nfs_mount_async() failed: %s",
					    nfs_get_error(context));
		postponed_mount_error = std::make_exception_ptr(e);
535 536 537 538 539 540 541 542 543 544 545 546 547
		return;
	}
}

void
NfsConnection::MountCallback(int status, nfs_context *nfs, void *data,
			     void *private_data)
{
	NfsConnection *c = (NfsConnection *)private_data;

	c->MountCallback(status, nfs, data);
}

548 549
inline void
NfsConnection::MountInternal()
550
{
551
	assert(GetEventLoop().IsInside());
552
	assert(context == nullptr);
553 554

	context = nfs_init_context();
555 556
	if (context == nullptr)
		throw std::runtime_error("nfs_init_context() failed");
557

558
	postponed_mount_error = std::exception_ptr();
559
	mount_finished = false;
560

561
	TimeoutMonitor::Schedule(NFS_MOUNT_TIMEOUT);
562

563
#ifndef NDEBUG
564 565
	in_service = false;
	in_event = false;
566
	in_destroy = false;
567
#endif
568 569 570

	if (nfs_mount_async(context, server.c_str(), export_name.c_str(),
			    MountCallback, this) != 0) {
571 572
		auto e = FormatRuntimeError("nfs_mount_async() failed: %s",
					    nfs_get_error(context));
573 574
		nfs_destroy_context(context);
		context = nullptr;
575
		throw e;
576 577 578 579 580 581 582 583
	}

	ScheduleSocket();
}

void
NfsConnection::BroadcastMountSuccess()
{
584 585
	assert(GetEventLoop().IsInside());

586 587 588 589 590 591 592 593
	while (!new_leases.empty()) {
		auto i = new_leases.begin();
		active_leases.splice(active_leases.end(), new_leases, i);
		(*i)->OnNfsConnectionReady();
	}
}

void
594
NfsConnection::BroadcastMountError(std::exception_ptr &&e)
595
{
596 597
	assert(GetEventLoop().IsInside());

598 599 600
	while (!new_leases.empty()) {
		auto l = new_leases.front();
		new_leases.pop_front();
601
		l->OnNfsConnectionFailed(e);
602 603
	}

604
	OnNfsConnectionError(std::move(e));
605 606 607
}

void
608
NfsConnection::BroadcastError(std::exception_ptr &&e)
609
{
610 611
	assert(GetEventLoop().IsInside());

612 613 614
	while (!active_leases.empty()) {
		auto l = active_leases.front();
		active_leases.pop_front();
615
		l->OnNfsConnectionDisconnected(e);
616 617
	}

618
	BroadcastMountError(std::move(e));
619 620
}

621 622 623 624 625 626 627 628 629
void
NfsConnection::OnTimeout()
{
	assert(GetEventLoop().IsInside());
	assert(!mount_finished);

	mount_finished = true;
	DestroyContext();

630
	BroadcastMountError(std::make_exception_ptr(std::runtime_error("Mount timeout")));
631 632
}

633 634 635
void
NfsConnection::RunDeferred()
{
636 637
	assert(GetEventLoop().IsInside());

638
	if (context == nullptr) {
639 640 641 642
		try {
			MountInternal();
		} catch (...) {
			BroadcastMountError(std::current_exception());
643 644 645 646
			return;
		}
	}

647
	if (mount_finished)
648 649
		BroadcastMountSuccess();
}