sockscape/server/Socks/MasterUdpServer.cs

86 lines
2.8 KiB
C#
Raw Normal View History

2017-06-16 21:00:01 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
2017-08-30 21:02:51 +00:00
using Glove;
using SockScape.Encryption;
2017-06-16 21:00:01 +00:00
2017-08-29 20:14:44 +00:00
namespace SockScape {
2017-06-16 21:00:01 +00:00
static class MasterUdpServer {
2017-08-30 21:02:51 +00:00
private static Dictionary<string, Client> Prospects;
private static Dictionary<string, Client> Clients;
2017-06-16 21:00:01 +00:00
private static UdpClient Sock;
2017-08-21 21:03:32 +00:00
private static Thread ListeningThread;
private static bool IsOpen;
2017-06-16 21:00:01 +00:00
public static void Initialize() {
if(IsOpen || ListeningThread != null)
2017-06-16 21:00:01 +00:00
return;
2017-08-30 21:02:51 +00:00
Clients = new Dictionary<string, Client>();
2017-06-16 21:00:01 +00:00
short port = (short)Configuration.General["Master Port"];
2017-08-29 20:14:44 +00:00
Sock = new UdpClient(new IPEndPoint(IPAddress.Any, port));
2017-06-16 21:00:01 +00:00
IsOpen = true;
2017-08-21 21:03:32 +00:00
ListeningThread = new Thread(Listener);
2017-06-16 21:00:01 +00:00
ListeningThread.Start();
}
2017-08-30 21:02:51 +00:00
private static bool IsClientConnected(string client) {
return Clients.ContainsKey(client);
}
2017-06-16 21:00:01 +00:00
public static void Listener() {
while(IsOpen) {
2017-08-30 21:02:51 +00:00
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 0);
2017-06-16 21:00:01 +00:00
while(Sock.Available > 0) {
2017-08-30 21:02:51 +00:00
var data = Sock.Receive(ref endPoint);
var client = endPoint.ToString();
var encryptor = IsClientConnected(client) ? Clients[client].Encryptor : null;
Packet packet =
encryptor == null ? Packet.FromBytes(data)
: Packet.FromBytes(encryptor.Parse(data));
switch((kIntraMasterId)packet.Id) {
case kIntraMasterId.InitiationAttempt:
if(packet.RegionCount != 1)
break;
if(packet[0] == Configuration.General["Master Secret"]) {
var request =
var request = Key.GenerateRequestPacket().GetBytes();
Sock.Send(request, request.Length, endPoint);
}
break;
case kIntraMasterId.KeyExchange:
break;
}
2017-06-16 21:00:01 +00:00
}
Thread.Sleep(1);
}
}
public static void Close() {
IsOpen = false;
ListeningThread.Join();
ListeningThread = null;
2017-08-29 20:14:44 +00:00
Sock.Dispose();
2017-06-16 21:00:01 +00:00
}
2017-08-30 21:02:51 +00:00
class Client {
public DateTime LastReceive { get; set; }
public Cipher Encryptor { get; set; }
public Key Key { get; set; }
}
}
2017-06-16 21:00:01 +00:00
}