-
Notifications
You must be signed in to change notification settings - Fork 0
/
PeerService.cs
397 lines (307 loc) · 15.3 KB
/
PeerService.cs
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
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Squared.Task;
using Squared.Task.IO;
using Squared.Task.Http;
using System.Windows.Forms;
using System.Web;
using System.IO;
using System.Net.Sockets;
using System.Net;
using Newtonsoft.Json;
using System.Diagnostics;
namespace Tsunagaro {
public delegate IEnumerator<object> MessageHandler (PeerService.Connection sender, Dictionary<string, object> message);
public class PeerService {
public class PendingConnection : IDisposable {
public readonly IPEndPoint RemoteEndPoint;
public readonly int Port;
public readonly TcpListener Listener;
public readonly Future<TcpClient> Future;
public PendingConnection (IPEndPoint remoteEndPoint) {
RemoteEndPoint = remoteEndPoint;
Listener = new TcpListener(0);
Listener.Start();
Port = ((IPEndPoint)Listener.LocalEndpoint).Port;
Future = Listener.AcceptIncomingConnection();
}
public void Dispose () {
Listener.Stop();
}
}
public class Connection : IDisposable {
public struct PendingResponse {
public string Message;
public IFuture Future;
}
public readonly string HostName;
public readonly IPEndPoint RemoteEndPoint;
public readonly int Port;
public readonly SocketDataAdapter Channel;
public readonly AsyncTextReader Input;
public readonly AsyncTextWriter Output;
public readonly TcpClient TcpClient;
private int NextResponseToken;
public readonly Dictionary<int, PendingResponse> PendingResponses = new Dictionary<int, PendingResponse>();
public Connection (TcpClient tcpClient, IPEndPoint remoteEndPoint) {
TcpClient = tcpClient;
Channel = new SocketDataAdapter(tcpClient.Client, false) {
ThrowOnDisconnect = true,
ThrowOnFullSendBuffer = false
};
RemoteEndPoint = remoteEndPoint;
HostName = Dns.GetHostByAddress(RemoteEndPoint.Address).HostName;
Input = new AsyncTextReader(Channel, false);
Output = new AsyncTextWriter(Channel, false) {
AutoFlush = true
};
}
private SignalFuture WriteMessage (Dictionary<string, object> body) {
if (body == null)
throw new ArgumentNullException("body");
return Output.WriteLine(JsonConvert.SerializeObject(body, Formatting.None));
}
// Does not wait for a response
public SignalFuture PostMessage (string message, Dictionary<string, object> payload = null) {
if (payload == null)
payload = new Dictionary<string, object>();
payload["_Message_"] = message;
return WriteMessage(payload);
}
// Waits for a response
public Future<TResult> SendMessage<TResult> (string message, Dictionary<string, object> payload = null) {
if (payload == null)
payload = new Dictionary<string, object>();
var result = new Future<TResult>();
int token = NextResponseToken++;
payload["_Message_"] = message;
payload["_Token_"] = token;
PendingResponses[token] = new PendingResponse {
Message = message,
Future = result
};
// Wait?
WriteMessage(payload);
return result;
}
public void Dispose () {
TcpClient.Close();
Channel.Dispose();
}
}
public readonly HashSet<IPEndPoint> Pending = new HashSet<IPEndPoint>();
public readonly Dictionary<IPEndPoint, Connection> Peers = new Dictionary<IPEndPoint, Connection>();
public readonly Dictionary<string, MessageHandler> MessageHandlers = new Dictionary<string, MessageHandler>();
public readonly TaskScheduler Scheduler;
public PeerService (TaskScheduler scheduler) {
Scheduler = scheduler;
}
public IEnumerator<object> Initialize () {
Program.Control.Handlers.Add("/connect", ServeConnect);
Program.Control.Handlers.Add("/kill-network", ServeKillNetwork);
Program.Control.Handlers.Add("/restart-network", ServeRestartNetwork);
Program.Peer.MessageHandlers.Add("Kill", OnKill);
Program.Peer.MessageHandlers.Add("Restart", OnRestart);
yield break;
}
public IEnumerator<object> ServeKillNetwork (HttpServer.Request request) {
yield return ControlService.WriteResponseBody(request, "Bye-bye!");
Scheduler.Start(OnKill(null, null), TaskExecutionPolicy.RunAsBackgroundTask);
yield return Program.Peer.Broadcast("Kill");
}
public IEnumerator<object> ServeRestartNetwork (HttpServer.Request request) {
yield return ControlService.WriteResponseBody(request, "Restarting...");
Scheduler.Start(OnRestart(null, null), TaskExecutionPolicy.RunAsBackgroundTask);
yield return Program.Peer.Broadcast("Restart");
}
private IEnumerator<object> OnKill (PeerService.Connection sender, Dictionary<string, object> message) {
yield return new Sleep(2);
Application.Exit();
}
private IEnumerator<object> OnRestart (PeerService.Connection sender, Dictionary<string, object> message) {
yield return new Sleep(1);
var psi = new ProcessStartInfo("Restart", "15 Tsunagaro") {
UseShellExecute = false
};
Process.Start(psi);
yield return new Sleep(1);
Application.Exit();
}
public IEnumerator<object> ServeConnect (HttpServer.Request request) {
if (
!request.QueryString.ContainsKey("myAddress") ||
!request.QueryString.ContainsKey("myPort")
) {
yield return ControlService.ServeError(request, 501, "argument missing");
Console.WriteLine("Rejected connection attempt from {0} with missing arguments", request.RemoteEndPoint);
yield break;
}
var fRemoteEndPoint = Future.RunInThread(() =>
new IPEndPoint(
Dns.GetHostByName(request.QueryString["myAddress"]).AddressList.First(),
int.Parse(request.QueryString["myPort"])
)
);
yield return fRemoteEndPoint;
if (!fRemoteEndPoint.Result.Address.Equals(((IPEndPoint)request.RemoteEndPoint).Address)) {
yield return ControlService.ServeError(request, 501, "address mismatch");
Console.WriteLine("Rejected mismatched connection attempt from {0}", request.RemoteEndPoint);
yield break;
}
if (
Pending.Contains(fRemoteEndPoint.Result) ||
Peers.ContainsKey(fRemoteEndPoint.Result)
) {
yield return ControlService.ServeError(request, 501, "already connecting or connected");
// FIXME: If a dead peer reconnects, this rejects the attempt
Console.WriteLine("Rejected duplicate connection attempt from {0}", request.RemoteEndPoint);
yield break;
}
Console.WriteLine("Establishing connection with {0}", fRemoteEndPoint.Result);
request.Response.ContentType = "text/plain";
var fPc = Future.RunInThread(() => new PendingConnection(fRemoteEndPoint.Result));
yield return fPc;
Scheduler.Start(AwaitConnection(fPc.Result), TaskExecutionPolicy.RunAsBackgroundTask);
var address = String.Format("{0}:{1}", Program.Control.HostName, fPc.Result.Port);
yield return ControlService.WriteResponseBody(request, address);
}
private IEnumerator<object> AwaitConnection (PendingConnection pc) {
if (Pending.Contains(pc.RemoteEndPoint))
throw new InvalidOperationException(String.Format("Already connecting to {0}", pc.RemoteEndPoint));
Pending.Add(pc.RemoteEndPoint);
try {
var wwt = new WaitWithTimeout(pc.Future, 5);
var f = Scheduler.Start(wwt);
yield return f;
if (f.Failed)
Console.WriteLine("Connection request from {0} timed out", pc.RemoteEndPoint);
else
Console.WriteLine("Connection established with {0}", pc.RemoteEndPoint);
var conn = new Connection(pc.Future.Result, pc.RemoteEndPoint);
Scheduler.Start(HandleConnection(conn), TaskExecutionPolicy.RunAsBackgroundTask);
} finally {
Pending.Remove(pc.RemoteEndPoint);
pc.Dispose();
}
}
private IEnumerator<object> ProcessMessage (Connection conn, string messageJson) {
var fParsedMessage = Future.RunInThread(() => JsonConvert.DeserializeObject<Dictionary<string, object>>(messageJson));
yield return fParsedMessage;
var msg = fParsedMessage.Result;
MessageHandler handler;
var messageName = Convert.ToString(msg["_Message_"]);
if (messageName == "_Result_") {
int token = Convert.ToInt32(msg["Token"]);
Connection.PendingResponse pr;
if (conn.PendingResponses.TryGetValue(token, out pr)) {
conn.PendingResponses.Remove(token);
if (msg.ContainsKey("Result")) {
// Console.WriteLine("{0} <- {1}[{2}] = {3}", conn.RemoteEndPoint, pr.Message, token, msg["Result"]);
pr.Future.Complete(msg["Result"]);
} else if (msg.ContainsKey("Error")) {
Console.WriteLine("{0} <- {1}[{2}] = error", conn.RemoteEndPoint, pr.Message, token);
pr.Future.Fail(new Exception(Convert.ToString(msg["Error"])));
} else {
Console.WriteLine("{0} <- {1}[{2}] = error", conn.RemoteEndPoint, pr.Message, token);
pr.Future.Fail(new Exception("Unknown error"));
}
}
yield break;
}
if (MessageHandlers.TryGetValue(messageName, out handler)) {
// Console.WriteLine("{0} -> {1} (handled by {2}.{3})", conn.RemoteEndPoint, messageName, handler.Target.GetType().Name, handler.Method.Name);
var fHandler = Scheduler.Start(handler(conn, msg), TaskExecutionPolicy.RunAsBackgroundTask);
yield return fHandler;
if (msg.ContainsKey("_Token_")) {
int token = Convert.ToInt32(msg["_Token_"]);
var payload = new Dictionary<string, object> {
{"Token", token},
};
if (fHandler.Failed) {
payload["Error"] = fHandler.Error.ToString();
} else {
payload["Result"] = fHandler.Result;
}
yield return conn.PostMessage(
"_Result_", payload
);
}
} else {
Console.WriteLine("{0} -> {1} (unhandled)", conn.RemoteEndPoint, messageName);
}
}
private IEnumerator<object> HandleConnection (Connection conn) {
if (Peers.ContainsKey(conn.RemoteEndPoint))
throw new InvalidOperationException(String.Format("Got duplicate connection for {0}", conn.RemoteEndPoint));
Peers.Add(conn.RemoteEndPoint, conn);
try {
while (true) {
var fMsg = conn.Input.ReadLine();
yield return fMsg;
if (fMsg.Failed)
break;
Scheduler.Start(ProcessMessage(conn, fMsg.Result), TaskExecutionPolicy.RunAsBackgroundTask);
}
} finally {
Console.WriteLine("Disconnected from {0}", conn.RemoteEndPoint);
Peers.Remove(conn.RemoteEndPoint);
conn.Dispose();
}
}
public IEnumerator<object> TryConnectTo (IPEndPoint endpoint) {
if (Peers.ContainsKey(endpoint)) {
// Console.WriteLine("Already connected to {0}", endpoint);
yield return new Result(true);
yield break;
} else if (Pending.Contains(endpoint)) {
// Console.WriteLine("Already connecting to {0}", endpoint);
yield return new Result(true);
yield break;
}
try {
Pending.Add(endpoint);
Console.WriteLine("Handshaking with {0}", endpoint);
var req = WebRequest.CreateHttp(String.Format(
"http://{0}/connect?myAddress={1}&myPort={2}",
endpoint,
HttpUtility.UrlEncode(Program.Control.HostName),
Program.Control.Port
));
var fResponse = req.IssueAsync(Scheduler);
yield return fResponse;
if (fResponse.Failed) {
Console.WriteLine("Connection to {0} failed: {1}", endpoint, fResponse.Error);
yield return new Result(false);
yield break;
}
var addressText = fResponse.Result.Body;
var channelHost = addressText.Substring(0, addressText.IndexOf(":"));
var channelPort = int.Parse(addressText.Substring(addressText.IndexOf(":") + 1));
Console.WriteLine("Connecting to {0} at {1}", endpoint, addressText);
var fClient = Network.ConnectTo(channelHost, channelPort);
yield return fClient;
if (fClient.Failed) {
Console.WriteLine("Connection to {0} failed: {1}", endpoint, fClient.Error);
yield return new Result(false);
yield break;
}
Console.WriteLine("Connection established with {0}", endpoint);
var conn = new Connection(fClient.Result, endpoint);
Scheduler.Start(HandleConnection(conn), TaskExecutionPolicy.RunAsBackgroundTask);
yield return new Result(true);
} finally {
Pending.Remove(endpoint);
}
}
public IFuture Broadcast (string message, Dictionary<string, object> payload = null) {
if (Peers.Count == 0)
return new SignalFuture(true);
var futures = new List<SignalFuture>();
foreach (var peer in Peers.Values)
futures.Add(peer.PostMessage(message, payload));
return Future.WaitForAll(futures);
}
}
}