summaryrefslogtreecommitdiffstats
path: root/ProtoProxy/Server.cpp
blob: e0abcb59605619880dfc5d40e362b4e13b587c8d (plain) (blame)
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

// Server.cpp

// Interfaces to the cServer class encapsulating the entire "server"

#include "Globals.h"
#include "Server.h"
#include "Connection.h"





cServer::cServer(void)
{
}





int cServer::Init(short a_ListenPort, short a_ConnectPort)
{
	m_ConnectPort = a_ConnectPort;
	WSAData wsa;
	int res = WSAStartup(0x0202, &wsa);
	if (res != 0)
	{
		printf("Cannot initialize WinSock: %d\n", res);
		return res;
	}
	
	printf("Generating protocol encryption keypair...\n");
	AutoSeededRandomPool rng;
	m_PrivateKey.GenerateRandomWithKeySize(rng, 1024);
	RSA::PublicKey pk(m_PrivateKey);
	m_PublicKey = pk;

	m_ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	sockaddr_in local;
	memset(&local, 0, sizeof(local));
	local.sin_family = AF_INET;
	local.sin_addr.s_addr = htonl(0x7f000001);  // localhost
	local.sin_port = htons(a_ListenPort);
	bind(m_ListenSocket, (sockaddr *)&local, sizeof(local));
	listen(m_ListenSocket, 1);
	return 0;
}





void cServer::Run(void)
{
	printf("Server running\n");
	while (true)
	{
		sockaddr_in Addr;
		ZeroMemory(&Addr, sizeof(Addr));
		int AddrSize = sizeof(Addr);
		SOCKET client = accept(m_ListenSocket, (sockaddr *)&Addr, &AddrSize);
		if (client == INVALID_SOCKET)
		{
			printf("accept returned an error: %d; bailing out", WSAGetLastError());
			return;
		}
		cConnection Connection(client, *this);
		Connection.Run();
	}
}