NfsStorage.cxx 9.82 KB
Newer Older
1
/*
2
 * Copyright 2003-2018 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/DeferEvent.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 46 47
#include <string>

#include <assert.h>
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
	DeferEvent 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 84 85
	~NfsStorage() {
		BlockingCall(GetEventLoop(), [this](){ Disconnect(); });
		nfs_finish();
86 87 88
	}

	/* virtual methods from class Storage */
89
	StorageFileInfo GetInfo(const char *uri_utf8, bool follow) override;
90

91
	std::unique_ptr<StorageDirectoryReader> OpenDirectory(const char *uri_utf8) override;
92

93
	std::string MapUTF8(const char *uri_utf8) const noexcept override;
94

95
	const char *MapToRelativeUTF8(const char *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 119
	/* DeferEvent callback */
	void OnDeferredConnect() noexcept {
120 121 122 123
		if (state == State::INITIAL)
			Connect();
	}

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

		Connect();
	}

private:
132
	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 141 142 143
		state = _state;
		cond.broadcast();
	}

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 151 152
		cond.broadcast();
	}

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
		const std::lock_guard<Mutex> protect(mutex);
171 172 173 174 175 176

		while (true) {
			switch (state) {
			case State::INITIAL:
				/* schedule connect */
				mutex.unlock();
177
				defer_connect.Schedule();
178
				mutex.lock();
179 180
				if (state == State::INITIAL)
					cond.wait(mutex);
181 182 183 184
				break;

			case State::CONNECTING:
			case State::READY:
185
				return;
186 187

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

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

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

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

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

216
static std::string
217
UriToNfsPath(const char *_uri_utf8)
218
{
219 220
	assert(_uri_utf8 != nullptr);

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.c_str()).Steal();
230
#endif
231 232
}

233
std::string
234
NfsStorage::MapUTF8(const char *uri_utf8) const noexcept
235 236 237
{
	assert(uri_utf8 != nullptr);

238
	if (StringIsEmpty(uri_utf8))
239 240 241 242 243 244
		return base;

	return PathTraitsUTF8::Build(base.c_str(), uri_utf8);
}

const char *
245
NfsStorage::MapToRelativeUTF8(const char *uri_utf8) const noexcept
246 247 248 249
{
	return PathTraitsUTF8::Relative(base.c_str(), uri_utf8);
}

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

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

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

public:
272 273 274 275
	NfsGetInfoOperation(NfsConnection &_connection, const char *_path,
			    bool _follow)
		:BlockingNfsOperation(_connection), path(_path),
		 follow(_follow) {}
276 277 278 279

	const StorageFileInfo &GetInfo() const {
		return info;
	}
280 281

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

289
	void HandleResult(gcc_unused unsigned status, void *data) noexcept override {
290
		Copy(info, *(const struct nfs_stat_64 *)data);
291 292
	}
};
293

294
StorageFileInfo
295
NfsStorage::GetInfo(const char *uri_utf8, bool follow)
296
{
297
	const std::string path = UriToNfsPath(uri_utf8);
298

299
	WaitConnected();
300

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

gcc_pure
static bool
308
SkipNameFS(PathTraitsFS::const_pointer_type name) noexcept
309 310 311 312 313 314
{
	return name[0] == '.' &&
		(name[1] == 0 ||
		 (name[1] == '.' && name[2] == 0));
}

315
static void
316
Copy(StorageFileInfo &info, const struct nfsdirent &ent)
317
{
318
	switch (ent.type) {
319
	case NF3REG:
320
		info.type = StorageFileInfo::Type::REGULAR;
321 322 323
		break;

	case NF3DIR:
324
		info.type = StorageFileInfo::Type::DIRECTORY;
325 326 327
		break;

	default:
328
		info.type = StorageFileInfo::Type::OTHER;
329 330 331
		break;
	}

332
	info.size = ent.size;
333
	info.mtime = std::chrono::system_clock::from_time_t(ent.mtime.tv_sec);
334
	info.device = 0;
335 336 337
	info.inode = ent.inode;
}

338 339
class NfsListDirectoryOperation final : public BlockingNfsOperation {
	const char *const path;
340

341 342 343 344 345 346 347
	MemoryStorageDirectoryReader::List entries;

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

348 349
	std::unique_ptr<StorageDirectoryReader> ToReader() {
		return std::make_unique<MemoryStorageDirectoryReader>(std::move(entries));
350 351
	}

352
protected:
353 354
	void Start() override {
		connection.OpenDirectory(path, *this);
355 356
	}

357 358
	void HandleResult(gcc_unused unsigned status,
			  void *data) noexcept override {
359 360 361 362 363 364 365 366 367 368 369 370 371 372
		struct nfsdir *const dir = (struct nfsdir *)data;

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

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

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

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

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

397
std::unique_ptr<StorageDirectoryReader>
398
NfsStorage::OpenDirectory(const char *uri_utf8)
399
{
400
	const std::string path = UriToNfsPath(uri_utf8);
401

402
	WaitConnected();
403 404

	NfsListDirectoryOperation operation(*connection, path.c_str());
405
	operation.Run();
406 407

	return operation.ToReader();
408 409
}

410
static std::unique_ptr<Storage>
411
CreateNfsStorageURI(EventLoop &event_loop, const char *base)
412
{
413 414
	const char *p = StringAfterPrefixCaseASCII(base, "nfs://");
	if (p == nullptr)
415 416 417
		return nullptr;

	const char *mount = strchr(p, '/');
418 419
	if (mount == nullptr)
		throw std::runtime_error("Malformed nfs:// URI");
420 421 422

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

423 424
	nfs_set_base(server.c_str(), mount);

425 426
	return std::make_unique<NfsStorage>(event_loop, base,
					    server.c_str(), mount);
427 428 429 430 431 432
}

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