NfsStorage.cxx 9.8 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 24
 * 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 "NfsStorage.hxx"
#include "storage/StoragePlugin.hxx"
#include "storage/StorageInterface.hxx"
#include "storage/FileInfo.hxx"
25
#include "storage/MemoryDirectoryReader.hxx"
26
#include "lib/nfs/Blocking.hxx"
27
#include "lib/nfs/Base.hxx"
28 29 30
#include "lib/nfs/Lease.hxx"
#include "lib/nfs/Connection.hxx"
#include "lib/nfs/Glue.hxx"
31
#include "fs/AllocatedPath.hxx"
32
#include "thread/Mutex.hxx"
33 34 35
#include "thread/Cond.hxx"
#include "event/Loop.hxx"
#include "event/Call.hxx"
36
#include "event/DeferEvent.hxx"
37
#include "event/TimerEvent.hxx"
38
#include "util/ASCII.hxx"
39
#include "util/StringCompare.hxx"
40 41 42 43 44 45

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

46 47 48
#include <string>

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

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

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

59 60
	const std::string base;

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

	NfsConnection *connection;

65
	DeferEvent defer_connect;
66 67
	TimerEvent reconnect_timer;

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

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

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

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

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

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

96
	const char *MapToRelativeUTF8(const char *uri_utf8) const noexcept override;
97 98

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

		SetState(State::READY);
	}

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

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

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

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

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

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

		Connect();
	}

private:
133
	EventLoop &GetEventLoop() noexcept {
134
		return defer_connect.GetEventLoop();
135 136
	}

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

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

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

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

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

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

		SetState(State::CONNECTING);
	}

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

170
	void WaitConnected() {
171
		const std::lock_guard<Mutex> protect(mutex);
172 173 174 175 176 177

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

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

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

195
	void Disconnect() noexcept {
196 197 198 199
		assert(GetEventLoop().IsInside());

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

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

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

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

222
	/* libnfs paths must begin with a slash */
223 224
	std::string uri_utf8("/");
	uri_utf8.append(_uri_utf8);
225

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

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

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

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

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

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

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

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

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

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

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

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

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

300
	WaitConnected();
301

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

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

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

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

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

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

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

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

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

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

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

358 359
	void HandleResult(gcc_unused unsigned status,
			  void *data) noexcept override {
360 361 362 363 364 365 366 367 368 369 370 371 372 373
		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());
374 375

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

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

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

403
	WaitConnected();
404 405

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

	return operation.ToReader();
409 410
}

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

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

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

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

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

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