NfsStorage.cxx 9.01 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 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 36 37
#include "thread/Cond.hxx"
#include "event/Loop.hxx"
#include "event/Call.hxx"
#include "event/DeferredMonitor.hxx"
#include "event/TimeoutMonitor.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 52 53 54 55 56 57
class NfsStorage final
	: public Storage, NfsLease, DeferredMonitor, TimeoutMonitor {

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

58 59
	const std::string base;

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

	NfsConnection *connection;

	Mutex mutex;
	Cond cond;
	State state;
67
	std::exception_ptr last_exception;
68 69

public:
70 71 72 73 74 75 76
	NfsStorage(EventLoop &_loop, const char *_base,
		   std::string &&_server, std::string &&_export_name)
		:DeferredMonitor(_loop), TimeoutMonitor(_loop),
		 base(_base),
		 server(std::move(_server)),
		 export_name(std::move(_export_name)),
		 state(State::INITIAL) {
77
		nfs_init(_loop);
78
	}
79

80 81 82
	~NfsStorage() {
		BlockingCall(GetEventLoop(), [this](){ Disconnect(); });
		nfs_finish();
83 84 85
	}

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

88
	StorageDirectoryReader *OpenDirectory(const char *uri_utf8) override;
89

90
	std::string MapUTF8(const char *uri_utf8) const override;
91

92
	const char *MapToRelativeUTF8(const char *uri_utf8) const override;
93 94 95 96 97 98 99 100

	/* virtual methods from NfsLease */
	void OnNfsConnectionReady() final {
		assert(state == State::CONNECTING);

		SetState(State::READY);
	}

101
	void OnNfsConnectionFailed(std::exception_ptr e) final {
102 103
		assert(state == State::CONNECTING);

104
		SetState(State::DELAY, std::move(e));
105
		TimeoutMonitor::Schedule(std::chrono::minutes(1));
106 107
	}

108
	void OnNfsConnectionDisconnected(std::exception_ptr e) final {
109 110
		assert(state == State::READY);

111
		SetState(State::DELAY, std::move(e));
112
		TimeoutMonitor::Schedule(std::chrono::seconds(5));
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
	}

	/* virtual methods from DeferredMonitor */
	void RunDeferred() final {
		if (state == State::INITIAL)
			Connect();
	}

	/* virtual methods from TimeoutMonitor */
	void OnTimeout() final {
		assert(state == State::DELAY);

		Connect();
	}

private:
	EventLoop &GetEventLoop() {
		return DeferredMonitor::GetEventLoop();
	}

	void SetState(State _state) {
		assert(GetEventLoop().IsInside());

136
		const std::lock_guard<Mutex> protect(mutex);
137 138 139 140
		state = _state;
		cond.broadcast();
	}

141
	void SetState(State _state, std::exception_ptr &&e) {
142 143
		assert(GetEventLoop().IsInside());

144
		const std::lock_guard<Mutex> protect(mutex);
145
		state = _state;
146
		last_exception = std::move(e);
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
		cond.broadcast();
	}

	void Connect() {
		assert(state != State::READY);
		assert(GetEventLoop().IsInside());

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

		SetState(State::CONNECTING);
	}

	void EnsureConnected() {
		if (state != State::READY)
			Connect();
	}

166
	void WaitConnected() {
167
		const std::lock_guard<Mutex> protect(mutex);
168 169 170 171 172 173 174 175

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

			case State::CONNECTING:
			case State::READY:
182
				return;
183 184

			case State::DELAY:
185 186
				assert(last_exception);
				std::rethrow_exception(last_exception);
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
			}
		}
	}

	void Disconnect() {
		assert(GetEventLoop().IsInside());

		switch (state) {
		case State::INITIAL:
			DeferredMonitor::Cancel();
			break;

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

		case State::DELAY:
			TimeoutMonitor::Cancel();
			SetState(State::INITIAL);
			break;
		}
	}
211 212
};

213
static std::string
214
UriToNfsPath(const char *_uri_utf8)
215
{
216 217
	assert(_uri_utf8 != nullptr);

218
	/* libnfs paths must begin with a slash */
219 220
	std::string uri_utf8("/");
	uri_utf8.append(_uri_utf8);
221

222
	return AllocatedPath::FromUTF8Throw(uri_utf8.c_str()).Steal();
223 224
}

225 226 227 228 229
std::string
NfsStorage::MapUTF8(const char *uri_utf8) const
{
	assert(uri_utf8 != nullptr);

230
	if (StringIsEmpty(uri_utf8))
231 232 233 234 235 236 237 238 239 240 241
		return base;

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

const char *
NfsStorage::MapToRelativeUTF8(const char *uri_utf8) const
{
	return PathTraitsUTF8::Relative(base.c_str(), uri_utf8);
}

242
static void
243
Copy(StorageFileInfo &info, const struct stat &st)
244 245
{
	if (S_ISREG(st.st_mode))
246
		info.type = StorageFileInfo::Type::REGULAR;
247
	else if (S_ISDIR(st.st_mode))
248
		info.type = StorageFileInfo::Type::DIRECTORY;
249
	else
250
		info.type = StorageFileInfo::Type::OTHER;
251 252 253 254 255

	info.size = st.st_size;
	info.mtime = st.st_mtime;
	info.device = st.st_dev;
	info.inode = st.st_ino;
256 257
}

258 259
class NfsGetInfoOperation final : public BlockingNfsOperation {
	const char *const path;
260
	StorageFileInfo info;
261 262

public:
263 264 265 266 267 268
	NfsGetInfoOperation(NfsConnection &_connection, const char *_path)
		:BlockingNfsOperation(_connection), path(_path) {}

	const StorageFileInfo &GetInfo() const {
		return info;
	}
269 270

protected:
271 272
	void Start() override {
		connection.Stat(path, *this);
273 274
	}

275 276 277 278
	void HandleResult(gcc_unused unsigned status, void *data) override {
		Copy(info, *(const struct stat *)data);
	}
};
279

280 281
StorageFileInfo
NfsStorage::GetInfo(const char *uri_utf8, gcc_unused bool follow)
282
{
283
	const std::string path = UriToNfsPath(uri_utf8);
284

285
	WaitConnected();
286

287
	NfsGetInfoOperation operation(*connection, path.c_str());
288
	operation.Run();
289
	return operation.GetInfo();
290 291 292 293 294 295 296 297 298 299 300
}

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

301
static void
302
Copy(StorageFileInfo &info, const struct nfsdirent &ent)
303
{
304
	switch (ent.type) {
305
	case NF3REG:
306
		info.type = StorageFileInfo::Type::REGULAR;
307 308 309
		break;

	case NF3DIR:
310
		info.type = StorageFileInfo::Type::DIRECTORY;
311 312 313
		break;

	default:
314
		info.type = StorageFileInfo::Type::OTHER;
315 316 317
		break;
	}

318 319
	info.size = ent.size;
	info.mtime = ent.mtime.tv_sec;
320
	info.device = 0;
321 322 323
	info.inode = ent.inode;
}

324 325
class NfsListDirectoryOperation final : public BlockingNfsOperation {
	const char *const path;
326

327 328 329 330 331 332 333 334 335
	MemoryStorageDirectoryReader::List entries;

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

	StorageDirectoryReader *ToReader() {
		return new MemoryStorageDirectoryReader(std::move(entries));
336 337
	}

338
protected:
339 340
	void Start() override {
		connection.OpenDirectory(path, *this);
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
	}

	void HandleResult(gcc_unused unsigned status, void *data) override {
		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());
358 359

	const struct nfsdirent *ent;
360
	while ((ent = connection.ReadDirectory(dir)) != nullptr) {
361 362 363 364 365 366 367 368 369 370 371 372 373
		const Path name_fs = Path::FromFS(ent->name);
		if (SkipNameFS(name_fs.c_str()))
			continue;

		std::string name_utf8 = name_fs.ToUTF8();
		if (name_utf8.empty())
			/* ignore files whose name cannot be converted
			   to UTF-8 */
			continue;

		entries.emplace_front(std::move(name_utf8));
		Copy(entries.front().info, *ent);
	}
374
}
375

376
StorageDirectoryReader *
377
NfsStorage::OpenDirectory(const char *uri_utf8)
378
{
379
	const std::string path = UriToNfsPath(uri_utf8);
380

381
	WaitConnected();
382 383

	NfsListDirectoryOperation operation(*connection, path.c_str());
384
	operation.Run();
385 386

	return operation.ToReader();
387 388 389
}

static Storage *
390
CreateNfsStorageURI(EventLoop &event_loop, const char *base)
391
{
392
	if (strncmp(base, "nfs://", 6) != 0)
393 394 395 396 397
		return nullptr;

	const char *p = base + 6;

	const char *mount = strchr(p, '/');
398 399
	if (mount == nullptr)
		throw std::runtime_error("Malformed nfs:// URI");
400 401 402

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

403 404
	nfs_set_base(server.c_str(), mount);

405
	return new NfsStorage(event_loop, base, server.c_str(), mount);
406 407 408 409 410 411
}

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