summaryrefslogtreecommitdiff
path: root/src/main.cpp
blob: 387fe4a2a4d7ad11e2e7f6c7e03d6e132fbc1ce2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
#include <erebos/attach.h>
#include <erebos/identity.h>
#include <erebos/network.h>
#include <erebos/set.h>
#include <erebos/storage.h>
#include <erebos/sync.h>

#include "storage.h"

#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>

#include <filesystem>
#include <functional>
#include <future>
#include <iostream>
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include <sstream>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>

using std::cerr;
using std::cout;
using std::endl;
using std::function;
using std::future;
using std::invalid_argument;
using std::make_unique;
using std::map;
using std::mutex;
using std::optional;
using std::ostringstream;
using std::promise;
using std::scoped_lock;
using std::string;
using std::thread;
using std::to_string;
using std::unique_ptr;
using std::vector;

namespace fs = std::filesystem;

using namespace erebos;

namespace {

fs::path getErebosDir()
{
	const char * value = getenv("EREBOS_DIR");
	if (value)
		return value;
	return "./.erebos";
}

mutex outputMutex;
void printLine(const string & line)
{
	scoped_lock lock(outputMutex);
	cout << line << std::endl;
}

Storage st(getErebosDir());
optional<Head<LocalState>> h;
optional<Server> server;

struct TestPeer
{
	Peer peer;
	size_t id;
	bool deleted = false;
	promise<bool> attachAnswer {};
};
vector<TestPeer> testPeers;

TestPeer & getPeer(const string & name)
{
	try {
		return testPeers.at(std::stoi(name) - 1);
	}
	catch (const std::invalid_argument &) {}

	for (auto & p : testPeers)
		if (p.peer.name() == name)
			return p;

	ostringstream ss;
	ss << "peer '" << name << "' not found";
	throw invalid_argument(ss.str().c_str());
}

TestPeer & getPeer(const Peer & peer)
{
	for (auto & p : testPeers)
		if (p.peer == peer)
			return p;
	throw invalid_argument("peer not found");
}

struct Command
{
	string name;
	function<void(const vector<string> &)> action;
};

void store(const vector<string> & args)
{
	auto type = args.at(0);

	vector<uint8_t> inner, data;

	char * line = nullptr;
	size_t size = 0;

	while (getline(&line, &size, stdin) > 0 && strlen(line) > 1)
		copy(line, line + strlen(line), std::back_inserter(inner));

	free(line);

	auto inserter = std::back_inserter(data);
	copy(type.begin(), type.end(), inserter);
	inserter = ' ';

	auto slen = to_string(inner.size());
	copy(slen.begin(), slen.end(), inserter);
	inserter = '\n';

	copy(inner.begin(), inner.end(), inserter);

	auto digest = st.priv().storeBytes(data);

	ostringstream ss;
	ss << "store-done " << string(digest);
	printLine(ss.str());
}

void storedGeneration(const vector<string> & args)
{
	auto ref = st.ref(Digest(args.at(0)));
	if (!ref)
		throw invalid_argument("ref " + args.at(0) + " not found");

	ostringstream ss;
	ss << "stored-generation " << string(ref->digest()) << " " << string(ref->generation());
	printLine(ss.str());
}

void storedRoots(const vector<string> & args)
{
	auto ref = st.ref(Digest(args.at(0)));
	if (!ref)
		throw invalid_argument("ref " + args.at(0) + " not found");

	ostringstream ss;
	ss << "stored-roots " << string(ref->digest());
	for (const auto & dgst : ref->roots())
		ss << " " << string(dgst);
	printLine(ss.str());
}

void storedSetAdd(const vector<string> & args)
{
	auto iref = st.ref(Digest(args.at(0)));
	if (!iref)
		throw invalid_argument("ref " + args.at(0) + " not found");

	auto set = args.size() > 1 ?
		Set<vector<Stored<Object>>>::load({ *st.ref(Digest(args.at(1))) }) :
		Set<vector<Stored<Object>>>();

	ostringstream ss;
	ss << "stored-set-add";
	for (const auto & d : set.add(st, { Stored<Object>::load(*iref) }).digests())
		ss << " " << string(d);
	printLine(ss.str());
}

void storedSetList(const vector<string> & args)
{
	auto ref = st.ref(Digest(args.at(0)));
	if (!ref)
		throw invalid_argument("ref " + args.at(0) + " not found");

	for (const auto & vec : Set<vector<Stored<Object>>>::load({ *ref }).view(std::less{})) {
		ostringstream ss;
		ss << "stored-set-item";
		for (const auto & x : vec)
			ss << " " << string(x.ref().digest());
		printLine(ss.str());
	}
	printLine("stored-set-done");
}

void createIdentity(const vector<string> & args)
{
	optional<Identity> identity;
	for (ssize_t i = args.size() - 1; i >= 0; i--) {
		const auto & name = args[i];
		auto builder = Identity::create(st);
		builder.name(name);
		if (identity)
			builder.owner(*identity);
		identity = builder.commit();
	}

	if (identity) {
		auto nh = h->update([&identity] (const auto & loc) {
			auto ret = loc->identity(*identity);
			if (identity->owner())
				ret = ret.template shared<optional<Identity>>(identity->finalOwner());
			return st.store(ret);
		});
		if (nh)
			*h = *nh;
	}
}

void printPairingResult(string prefix, Peer peer, future<PairingServiceBase::Outcome> && future)
{
	auto outcome = future.get();
	ostringstream ss;
	ss << prefix <<
		(outcome == PairingServiceBase::Outcome::Success ? "-done " : "-failed ") <<
		getPeer(peer).id;
	switch (outcome)
	{
	case PairingServiceBase::Outcome::Success: break;
	case PairingServiceBase::Outcome::PeerRejected: ss << " rejected"; break;
	case PairingServiceBase::Outcome::UserRejected: ss << " user"; break;
	case PairingServiceBase::Outcome::UnexpectedMessage: ss << " unexpected"; break;
	case PairingServiceBase::Outcome::NonceMismatch: ss << " nonce"; break;
	case PairingServiceBase::Outcome::Stale: ss << " stale"; break;
	}
	printLine(ss.str());
}

future<bool> confirmPairing(string prefix, const Peer & peer, string confirm, future<PairingServiceBase::Outcome> && outcome)
{
	thread(printPairingResult, prefix, peer, move(outcome)).detach();

	promise<bool> promise;
	auto input = promise.get_future();
	getPeer(peer).attachAnswer = move(promise);

	ostringstream ss;
	ss << prefix << " " << getPeer(peer).id << " " << confirm;
	printLine(ss.str());
	return input;
}

void startServer(const vector<string> &)
{
	vector<unique_ptr<Service>> services;

	using namespace std::placeholders;

	auto atts = make_unique<AttachService>();
	atts->onRequest(bind(confirmPairing, "attach-request", _1, _2, _3));
	atts->onResponse(bind(confirmPairing, "attach-response", _1, _2, _3));
	services.push_back(move(atts));

	services.push_back(make_unique<SyncService>());

	server.emplace(*h, move(services));

	server->peerList().onUpdate([](size_t idx, const Peer * peer) {
		size_t i = 0;
		while (idx > 0 && i < testPeers.size()) {
			if (!testPeers[i].deleted)
				idx--;
			i++;
		}

		string prefix = "peer " + to_string(i + 1);
		if (peer) {
			if (i >= testPeers.size()) {
				testPeers.push_back(TestPeer { .peer = *peer, .id = i + 1 });
				const auto & paddr = peer->address();

				ostringstream ss;
				ss << prefix << " addr " << inet_ntoa(paddr.sin_addr) << " " << ntohs(paddr.sin_port);
				printLine(ss.str());
			}

			if (peer->identity()) {
				ostringstream ss;
				ss << prefix << " id";
				for (auto idt = peer->identity(); idt; idt = idt->owner())
					ss << " " << (idt->name() ? *idt->name() : "<unnamed>");
				printLine(ss.str());
			}
		} else {
			testPeers[i].deleted = true;
			printLine(prefix + " deleted");
		}
	});
}

void stopServer(const vector<string> &)
{
	server.reset();
}

void sharedStateGet(const vector<string> &)
{
	ostringstream ss;
	ss << "shared-state-get";
	for (const auto & r : h->behavior().lens<vector<Ref>>().get())
		ss << " " << string(r.digest());
	printLine(ss.str());
}

void sharedStateWait(const vector<string> & args)
{
	static optional<Watched<vector<Ref>>> watched;
	watched = h->behavior().lens<vector<Ref>>().watch([args, watched = watched] (const vector<Ref> & refs) mutable {
		vector<Stored<Object>> objs;
		objs.reserve(refs.size());
		for (const auto & r : refs)
			objs.push_back(Stored<Object>::load(r));

		auto objs2 = objs;
		for (const auto & a : args)
			if (auto ref = st.ref(Digest(a)))
				objs2.push_back(Stored<Object>::load(*ref));
			else
				return;

		filterAncestors(objs2);
		if (objs2 == objs) {
			ostringstream ss;
			ss << "shared-state-wait";
			for (const auto & a : args)
				ss << " " << a;
			printLine(ss.str());

			watched = std::nullopt;
		}
	});
}

void watchLocalIdentity(const vector<string> &)
{
	auto bhv = h->behavior().lens<optional<Identity>>();
	static auto watchedLocalIdentity = bhv.watch([] (const optional<Identity> & idt) {
		if (idt) {
			ostringstream ss;
			ss << "local-identity";
			for (optional<Identity> i = idt; i; i = i->owner())
				ss << " " << i->name().value();
			printLine(ss.str());
		}
	});
}

void watchSharedIdentity(const vector<string> &)
{
	auto bhv = h->behavior().lens<SharedState>().lens<optional<Identity>>();
	static auto watchedSharedIdentity = bhv.watch([] (const optional<Identity> & idt) {
		if (idt) {
			ostringstream ss;
			ss << "shared-identity";
			for (optional<Identity> i = idt; i; i = i->owner())
				ss << " " << i->name().value();
			printLine(ss.str());
		}
	});
}

void updateLocalIdentity(const vector<string> & params)
{
	if (params.size() != 1) {
		throw invalid_argument("usage: update-local-identity <name>");
	}

	auto nh = h->update([&params] (const Stored<LocalState> & loc) {
		auto st = loc.ref().storage();

		auto b = loc->identity()->modify();
		b.name(params[0]);
		return st.store(loc->identity(b.commit()));
	});
	if (nh)
		*h = *nh;
}

void updateSharedIdentity(const vector<string> & params)
{
	if (params.size() != 1) {
		throw invalid_argument("usage: update-shared-identity <name>");
	}

	auto nh = h->update([&params] (const Stored<LocalState> & loc) {
		auto st = loc.ref().storage();
		auto mbid = loc->shared<optional<Identity>>();
		if (!mbid)
			return loc;

		auto b = mbid->modify();
		b.name(params[0]);
		return st.store(loc->shared<optional<Identity>>(optional(b.commit())));
	});
	if (nh)
		*h = *nh;
}

void attachTo(const vector<string> & params)
{
	server->svc<AttachService>().attachTo(getPeer(params.at(0)).peer);
}

void attachAccept(const vector<string> & params)
{
	getPeer(params.at(0)).attachAnswer.set_value(true);
}

void attachReject(const vector<string> & params)
{
	getPeer(params.at(0)).attachAnswer.set_value(false);
}

vector<Command> commands = {
	{ "store", store },
	{ "stored-generation", storedGeneration },
	{ "stored-roots", storedRoots },
	{ "stored-set-add", storedSetAdd },
	{ "stored-set-list", storedSetList },
	{ "create-identity", createIdentity },
	{ "start-server", startServer },
	{ "stop-server", stopServer },
	{ "shared-state-get", sharedStateGet },
	{ "shared-state-wait", sharedStateWait },
	{ "watch-local-identity", watchLocalIdentity },
	{ "watch-shared-identity", watchSharedIdentity },
	{ "update-local-identity", updateLocalIdentity },
	{ "update-shared-identity", updateSharedIdentity },
	{ "attach-to", attachTo },
	{ "attach-accept", attachAccept },
	{ "attach-reject", attachReject },
};

}

int main(int argc, char * argv[])
{
	h.emplace([] {
		auto hs = st.heads<LocalState>();
		if (!hs.empty())
			return hs[0];
		else
			return st.storeHead(LocalState());
	}());

	char * line = nullptr;
	size_t size = 0;

	if (argc > 1) {
		vector<string> args;
		for (int i = 2; i < argc; i++)
			args.emplace_back(argv[i]);

		for (const auto & cmd : commands) {
			if (cmd.name == argv[1]) {
				cmd.action(args);
				return 0;
			}
		}

		cerr << "Unknown command: '" << argv[1] << "'" << endl;
		return 1;
	}

	while (getline(&line, &size, stdin) > 0) {
		optional<string> command;
		vector<string> args;

		const char * last = line;
		for (const char * cur = line;; cur++) {
			if (isspace(*cur) || *cur == '\0') {
				if (last < cur) {
					if (!command)
						command.emplace(last, cur);
					else
						args.emplace_back(last, cur);
				}
				last = cur + 1;

				if (*cur == '\0')
					break;
			}
		}

		if (!command)
			continue;

		bool found = false;
		for (const auto & cmd : commands) {
			if (cmd.name == *command) {
				found = true;
				cmd.action(args);
				break;
			}
		}

		if (!found)
			cerr << "Unknown command: '" << *command << "'" << endl;
	}

	free(line);
	server.reset();
	return 0;
}