NfsStorage.cxx 9.83 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2020 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 "NfsStorage.hxx"
#include "storage/StoragePlugin.hxx"
#include "storage/StorageInterface.hxx"
#include "storage/FileInfo.hxx"
24
#include "storage/MemoryDirectoryReader.hxx"
25
#include "lib/nfs/Blocking.hxx"
26
#include "lib/nfs/Base.hxx"
27 28 29
#include "lib/nfs/Lease.hxx"
#include "lib/nfs/Connection.hxx"
#include "lib/nfs/Glue.hxx"
30
#include "fs/AllocatedPath.hxx"
31
#include "thread/Mutex.hxx"
32 33 34
#include "thread/Cond.hxx"
#include "event/Loop.hxx"
#include "event/Call.hxx"
35
#include "event/InjectEvent.hxx"
36
#include "event/TimerEvent.hxx"
37
#include "util/ASCII.hxx"
38
#include "util/StringCompare.hxx"
39 40 41 42 43 44

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

45
#include <cassert>
46 47
#include <string>

48 49 50
#include <sys/stat.h>
#include <fcntl.h>

51
class NfsStorage final
52
	: public Storage, NfsLease {
53 54 55 56 57

	enum class State {
		INITIAL, CONNECTING, READY, DELAY,
	};

58 59
	const std::string base;

60 61 62 63
	const std::string server, export_name;

	NfsConnection *connection;

64
	InjectEvent defer_connect;
65 66
	TimerEvent reconnect_timer;

67 68
	Mutex mutex;
	Cond cond;
69
	State state = State::INITIAL;
70
	std::exception_ptr last_exception;
71 72

public:
73 74
	NfsStorage(EventLoop &_loop, const char *_base,
		   std::string &&_server, std::string &&_export_name)
75
		:base(_base),
76 77
		 server(std::move(_server)),
		 export_name(std::move(_export_name)),
78
		 defer_connect(_loop, BIND_THIS_METHOD(OnDeferredConnect)),
79
		 reconnect_timer(_loop, BIND_THIS_METHOD(OnReconnectTimer)) {
80
		nfs_init(_loop);
81
	}
82

83
	~NfsStorage() override {
84 85
		BlockingCall(GetEventLoop(), [this](){ Disconnect(); });
		nfs_finish();
86 87 88
	}

	/* virtual methods from class Storage */
89
	StorageFileInfo GetInfo(std::string_view uri_utf8, bool follow) override;
90

91
	std::unique_ptr<StorageDirectoryReader> OpenDirectory(std::string_view uri_utf8) override;
92

93
	[[nodiscard]] std::string MapUTF8(std::string_view uri_utf8) const noexcept override;
94

95
	[[nodiscard]] std::string_view MapToRelativeUTF8(std::string_view uri_utf8) const noexcept override;
96 97

	/* virtual methods from NfsLease */
98
	void OnNfsConnectionReady() noexcept final {
99 100 101 102 103
		assert(state == State::CONNECTING);

		SetState(State::READY);
	}

104
	void OnNfsConnectionFailed(std::exception_ptr e) noexcept final {
105 106
		assert(state == State::CONNECTING);

107
		SetState(State::DELAY, std::move(e));
108
		reconnect_timer.Schedule(std::chrono::minutes(1));
109 110
	}

111
	void OnNfsConnectionDisconnected(std::exception_ptr e) noexcept final {
112 113
		assert(state == State::READY);

114
		SetState(State::DELAY, std::move(e));
115
		reconnect_timer.Schedule(std::chrono::seconds(5));
116 117
	}

118
	/* InjectEvent callback */
119
	void OnDeferredConnect() noexcept {
120 121 122 123
		if (state == State::INITIAL)
			Connect();
	}

124
	/* callback for #reconnect_timer */
125
	void OnReconnectTimer() noexcept {
126 127 128 129 130 131
		assert(state == State::DELAY);

		Connect();
	}

private:
132
	[[nodiscard]] EventLoop &GetEventLoop() const noexcept {
133
		return defer_connect.GetEventLoop();
134 135
	}

136
	void SetState(State _state) noexcept {
137 138
		assert(GetEventLoop().IsInside());

139
		const std::lock_guard<Mutex> protect(mutex);
140
		state = _state;
141
		cond.notify_all();
142 143
	}

144
	void SetState(State _state, std::exception_ptr &&e) noexcept {
145 146
		assert(GetEventLoop().IsInside());

147
		const std::lock_guard<Mutex> protect(mutex);
148
		state = _state;
149
		last_exception = std::move(e);
150
		cond.notify_all();
151 152
	}

153
	void Connect() noexcept {
154 155 156 157 158 159 160 161 162 163
		assert(state != State::READY);
		assert(GetEventLoop().IsInside());

		connection = &nfs_get_connection(server.c_str(),
						 export_name.c_str());
		connection->AddLease(*this);

		SetState(State::CONNECTING);
	}

164
	void EnsureConnected() noexcept {
165 166 167 168
		if (state != State::READY)
			Connect();
	}

169
	void WaitConnected() {
170
		std::unique_lock<Mutex> lock(mutex);
171 172 173 174 175

		while (true) {
			switch (state) {
			case State::INITIAL:
				/* schedule connect */
176 177 178 179 180
				{
					const ScopeUnlock unlock(mutex);
					defer_connect.Schedule();
				}

181
				if (state == State::INITIAL)
182
					cond.wait(lock);
183 184 185 186
				break;

			case State::CONNECTING:
			case State::READY:
187
				return;
188 189

			case State::DELAY:
190 191
				assert(last_exception);
				std::rethrow_exception(last_exception);
192 193 194 195
			}
		}
	}

196
	void Disconnect() noexcept {
197
		assert(!GetEventLoop().IsAlive() || GetEventLoop().IsInside());
198 199 200

		switch (state) {
		case State::INITIAL:
201
			defer_connect.Cancel();
202 203 204 205 206 207 208 209 210
			break;

		case State::CONNECTING:
		case State::READY:
			connection->RemoveLease(*this);
			SetState(State::INITIAL);
			break;

		case State::DELAY:
211
			reconnect_timer.Cancel();
212 213 214 215
			SetState(State::INITIAL);
			break;
		}
	}
216 217
};

218
static std::string
219
UriToNfsPath(std::string_view _uri_utf8)
220 221
{
	/* libnfs paths must begin with a slash */
222 223
	std::string uri_utf8("/");
	uri_utf8.append(_uri_utf8);
224

225 226 227 228
#ifdef _WIN32
	/* assume UTF-8 when accessing NFS from Windows */
	return uri_utf8;
#else
229
	return AllocatedPath::FromUTF8Throw(uri_utf8).Steal();
230
#endif
231 232
}

233
std::string
234
NfsStorage::MapUTF8(std::string_view uri_utf8) const noexcept
235
{
236
	if (uri_utf8.empty())
237 238
		return base;

239
	return PathTraitsUTF8::Build(base, uri_utf8);
240 241
}

242 243
std::string_view
NfsStorage::MapToRelativeUTF8(std::string_view uri_utf8) const noexcept
244
{
245
	return PathTraitsUTF8::Relative(base, uri_utf8);
246 247
}

248
static void
249
Copy(StorageFileInfo &info, const struct nfs_stat_64 &st) noexcept
250
{
251
	if (S_ISREG(st.nfs_mode))
252
		info.type = StorageFileInfo::Type::REGULAR;
253
	else if (S_ISDIR(st.nfs_mode))
254
		info.type = StorageFileInfo::Type::DIRECTORY;
255
	else
256
		info.type = StorageFileInfo::Type::OTHER;
257

258
	info.size = st.nfs_size;
259
	info.mtime = std::chrono::system_clock::from_time_t(st.nfs_mtime);
260 261
	info.device = st.nfs_dev;
	info.inode = st.nfs_ino;
262 263
}

264 265
class NfsGetInfoOperation final : public BlockingNfsOperation {
	const char *const path;
266
	StorageFileInfo info;
267
	bool follow;
268 269

public:
270 271 272 273
	NfsGetInfoOperation(NfsConnection &_connection, const char *_path,
			    bool _follow)
		:BlockingNfsOperation(_connection), path(_path),
		 follow(_follow) {}
274

275
	[[nodiscard]] const StorageFileInfo &GetInfo() const {
276 277
		return info;
	}
278 279

protected:
280
	void Start() override {
281 282 283 284
		if (follow)
			connection.Stat(path, *this);
		else
			connection.Lstat(path, *this);
285 286
	}

Rosen Penev's avatar
Rosen Penev committed
287
	void HandleResult([[maybe_unused]] unsigned status, void *data) noexcept override {
288
		Copy(info, *(const struct nfs_stat_64 *)data);
289 290
	}
};
291

292
StorageFileInfo
293
NfsStorage::GetInfo(std::string_view uri_utf8, bool follow)
294
{
295
	const std::string path = UriToNfsPath(uri_utf8);
296

297
	WaitConnected();
298

299
	NfsGetInfoOperation operation(*connection, path.c_str(), follow);
300
	operation.Run();
301
	return operation.GetInfo();
302 303 304 305
}

gcc_pure
static bool
306
SkipNameFS(PathTraitsFS::const_pointer name) noexcept
307
{
308
	return PathTraitsFS::IsSpecialFilename(name);
309 310
}

311
static void
312
Copy(StorageFileInfo &info, const struct nfsdirent &ent)
313
{
314
	switch (ent.type) {
315
	case NF3REG:
316
		info.type = StorageFileInfo::Type::REGULAR;
317 318 319
		break;

	case NF3DIR:
320
		info.type = StorageFileInfo::Type::DIRECTORY;
321 322 323
		break;

	default:
324
		info.type = StorageFileInfo::Type::OTHER;
325 326 327
		break;
	}

328
	info.size = ent.size;
329
	info.mtime = std::chrono::system_clock::from_time_t(ent.mtime.tv_sec);
330
	info.device = 0;
331 332 333
	info.inode = ent.inode;
}

334 335
class NfsListDirectoryOperation final : public BlockingNfsOperation {
	const char *const path;
336

337 338 339 340 341 342 343
	MemoryStorageDirectoryReader::List entries;

public:
	NfsListDirectoryOperation(NfsConnection &_connection,
				  const char *_path)
		:BlockingNfsOperation(_connection), path(_path) {}

344 345
	std::unique_ptr<StorageDirectoryReader> ToReader() {
		return std::make_unique<MemoryStorageDirectoryReader>(std::move(entries));
346 347
	}

348
protected:
349 350
	void Start() override {
		connection.OpenDirectory(path, *this);
351 352
	}

Rosen Penev's avatar
Rosen Penev committed
353
	void HandleResult([[maybe_unused]] unsigned status,
354
			  void *data) noexcept override {
Max Kellermann's avatar
Max Kellermann committed
355
		auto *const dir = (struct nfsdir *)data;
356 357 358 359 360 361 362 363 364 365 366 367 368

		CollectEntries(dir);
		connection.CloseDirectory(dir);
	}

private:
	void CollectEntries(struct nfsdir *dir);
};

inline void
NfsListDirectoryOperation::CollectEntries(struct nfsdir *dir)
{
	assert(entries.empty());
369 370

	const struct nfsdirent *ent;
371
	while ((ent = connection.ReadDirectory(dir)) != nullptr) {
372 373 374 375 376 377
#ifdef _WIN32
		/* assume UTF-8 when accessing NFS from Windows */
		const auto name_fs = AllocatedPath::FromUTF8Throw(ent->name);
		if (name_fs.IsNull())
			continue;
#else
378
		const Path name_fs = Path::FromFS(ent->name);
379
#endif
380 381 382
		if (SkipNameFS(name_fs.c_str()))
			continue;

383 384 385 386
		try {
			entries.emplace_front(name_fs.ToUTF8Throw());
			Copy(entries.front().info, *ent);
		} catch (...) {
387 388
			/* ignore files whose name cannot be converted
			   to UTF-8 */
389
		}
390
	}
391
}
392

393
std::unique_ptr<StorageDirectoryReader>
394
NfsStorage::OpenDirectory(std::string_view uri_utf8)
395
{
396
	const std::string path = UriToNfsPath(uri_utf8);
397

398
	WaitConnected();
399 400

	NfsListDirectoryOperation operation(*connection, path.c_str());
401
	operation.Run();
402 403

	return operation.ToReader();
404 405
}

406
static std::unique_ptr<Storage>
407
CreateNfsStorageURI(EventLoop &event_loop, const char *base)
408
{
409 410
	const char *p = StringAfterPrefixCaseASCII(base, "nfs://");
	if (p == nullptr)
411 412
		return nullptr;

Rosen Penev's avatar
Rosen Penev committed
413
	const char *mount = std::strchr(p, '/');
414 415
	if (mount == nullptr)
		throw std::runtime_error("Malformed nfs:// URI");
416 417 418

	const std::string server(p, mount);

419 420
	nfs_set_base(server.c_str(), mount);

421 422
	return std::make_unique<NfsStorage>(event_loop, base,
					    server.c_str(), mount);
423 424 425 426 427 428
}

const StoragePlugin nfs_storage_plugin = {
	"nfs",
	CreateNfsStorageURI,
};