summaryrefslogtreecommitdiff
path: root/protocols/MSN/msn_natdetect.cpp
blob: 827f51590d019d3d91c1d496e2b179a0fa1c0ef4 (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
/*
Plugin of Miranda IM for communicating with users of the MSN Messenger protocol.
Copyright (c) 2007-2012 Boris Krasnovskiy.

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, see <http://www.gnu.org/licenses/>.
*/

#include "msn_global.h"
#include "msn_proto.h"
#include "SDK/netfw.h"

#ifndef CLSID_NetFwMgr
#define MDEF_CLSID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
	const CLSID name = { l, w1, w2, { b1, b2,  b3,  b4,  b5,  b6,  b7,  b8 } }

	MDEF_CLSID(CLSID_NetFwMgr, 0x304ce942, 0x6e39, 0x40d8, 0x94, 0x3a, 0xb9, 0x13, 0xc4, 0x0c, 0x9c, 0xd4);
	MDEF_CLSID(IID_INetFwMgr, 0xf7898af5, 0xcac4, 0x4632, 0xa2, 0xec, 0xda ,0x06, 0xe5, 0x11, 0x1a, 0xf2);
#endif


MyConnectionType MyConnection;

const char* conStr[] =
{
	"Unknown-Connect",
	"Direct-Connect",
	"Unknown-NAT",
	"IP-Restrict-NAT",
	"Port-Restrict-NAT",
	"Symmetric-NAT",
	"Firewall",
	"ISALike"
};


void CMsnProto::DecryptEchoPacket(UDPProbePkt& pkt)
{
	pkt.clientPort ^= 0x3141;
	pkt.discardPort ^= 0x3141;
	pkt.testPort ^= 0x3141;
	pkt.clientIP ^= 0x31413141;
	pkt.testIP ^= 0x31413141;


	IN_ADDR addr;
	MSN_DebugLog("Echo packet: version: 0x%x  service code: 0x%x  transaction ID: 0x%x",
		pkt.version, pkt.serviceCode, pkt.trId);
	addr.S_un.S_addr = pkt.clientIP;
	MSN_DebugLog("Echo packet: client port: %u  client addr: %s",
		pkt.clientPort, inet_ntoa(addr));
	addr.S_un.S_addr = pkt.testIP;
	MSN_DebugLog("Echo packet: discard port: %u  test port: %u test addr: %s",
		pkt.discardPort, pkt.testPort, inet_ntoa(addr));
}


static void DiscardExtraPackets(SOCKET s)
{
	Sleep(3000);

	static const TIMEVAL tv = {0, 0};
	unsigned buf;

	for (;;)
	{
		if (Miranda_Terminated()) break;

		fd_set fd;
		FD_ZERO(&fd);
		FD_SET(s, &fd);

		if (select(1, &fd, NULL, NULL, &tv) == 1)
			recv(s, (char*)&buf, sizeof(buf), 0);
		else
			break;
	}
}


void CMsnProto::MSNatDetect(void)
{
	unsigned i;

	PHOSTENT host = gethostbyname("echo.edge.messenger.live.com");
	if (host == NULL)
	{
		MSN_DebugLog("P2PNAT could not find echo server \"echo.edge.messenger.live.com\"");
		return;
	}

	SOCKADDR_IN addr;
	addr.sin_family = AF_INET;
	addr.sin_port = _htons(7001);
	addr.sin_addr = *( PIN_ADDR )host->h_addr_list[0];

	MSN_DebugLog("P2PNAT Detected echo server IP %d.%d.%d.%d",
		addr.sin_addr.S_un.S_un_b.s_b1, addr.sin_addr.S_un.S_un_b.s_b2,
		addr.sin_addr.S_un.S_un_b.s_b3, addr.sin_addr.S_un.S_un_b.s_b4);

	SOCKET s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

	connect(s, (SOCKADDR*)&addr, sizeof(addr));

	UDPProbePkt pkt = { 0 };
	UDPProbePkt pkt2;

	// Detect My IP
	pkt.version = 2;
	pkt.serviceCode = 4;
	send(s, (char*)&pkt, sizeof(pkt), 0);

	SOCKADDR_IN  myaddr;
	int szname = sizeof(myaddr);
	getsockname(s, (SOCKADDR*)&myaddr, &szname);

	MyConnection.intIP = myaddr.sin_addr.S_un.S_addr;
	MSN_DebugLog("P2PNAT Detected IP facing internet %d.%d.%d.%d",
		myaddr.sin_addr.S_un.S_un_b.s_b1, myaddr.sin_addr.S_un.S_un_b.s_b2,
		myaddr.sin_addr.S_un.S_un_b.s_b3, myaddr.sin_addr.S_un.S_un_b.s_b4);

	SOCKET s1 = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

	pkt.version = 2;
	pkt.serviceCode = 1;
	pkt.clientPort = 0x3141;
	pkt.clientIP = 0x31413141;

	UDPProbePkt rpkt = {0};

	// NAT detection
	for (i=0; i<4; ++i)
	{
		if (Miranda_Terminated()) break;

		// Send echo request to server 1
		MSN_DebugLog("P2PNAT Request 1 attempt %d sent", i);
		sendto(s1, (char*)&pkt, sizeof(pkt), 0, (SOCKADDR*)&addr, sizeof(addr));

		fd_set fd;
		FD_ZERO(&fd);
		FD_SET(s1, &fd);
		TIMEVAL tv = {0, 200000 * (1 << i) };

		if (select(1, &fd, NULL, NULL, &tv) == 1)
		{
			MSN_DebugLog("P2PNAT Request 1 attempt %d response", i);
			recv(s1, (char*)&rpkt, sizeof(rpkt), 0);
			pkt2 = rpkt;
			DecryptEchoPacket(rpkt);
			break;
		}
		else
			MSN_DebugLog("P2PNAT Request 1 attempt %d timeout", i);
	}

	closesocket(s);

	// Server did not respond
	if (i >= 4)
	{
		MyConnection.udpConType = conFirewall;
		closesocket(s1);
		return;
	}

	MyConnection.extIP = rpkt.clientIP;

	// Check if NAT not found
	if (MyConnection.extIP == MyConnection.intIP)
	{
		if (msnExternalIP != NULL && inet_addr(msnExternalIP) != MyConnection.extIP)
			MyConnection.udpConType = conISALike;
		else
			MyConnection.udpConType = conDirect;

		closesocket(s1);
		return;
	}

	// Detect UPnP NAT
	NETLIBBIND nlb = {0};
	nlb.cbSize = sizeof(nlb);
	nlb.pfnNewConnectionV2 = MSN_ConnectionProc;
	nlb.pExtra = this;

	HANDLE sb = (HANDLE) MSN_CallService(MS_NETLIB_BINDPORT, (WPARAM)hNetlibUser, (LPARAM)&nlb);
	if ( sb != NULL )
	{
		MyConnection.upnpNAT = htonl(nlb.dwExternalIP) == MyConnection.extIP;
		Sleep(100);
		Netlib_CloseHandle(sb);
	}

	DiscardExtraPackets(s1);

	// Start IP Restricted NAT detection
	UDPProbePkt rpkt2 = {0};
	pkt2.serviceCode = 3;
	SOCKADDR_IN addr2 = addr;
	addr2.sin_addr.S_un.S_addr = rpkt.testIP;
	addr2.sin_port = rpkt.discardPort;
	for (i=0; i<4; ++i)
	{
		if (Miranda_Terminated()) break;

		MSN_DebugLog("P2PNAT Request 2 attempt %d sent", i);
		// Remove IP restriction for server 2
		sendto(s1, NULL, 0, 0, (SOCKADDR*)&addr2, sizeof(addr2));
		// Send echo request to server 1 for server 2
		sendto(s1, (char*)&pkt2, sizeof(pkt2), 0, (SOCKADDR*)&addr, sizeof(addr));

		fd_set fd;
		FD_ZERO(&fd);
		FD_SET(s1, &fd);
		TIMEVAL tv = {0, 200000 * (1 << i) };

		if (select(1, &fd, NULL, NULL, &tv) == 1)
		{
			MSN_DebugLog("P2PNAT Request 2 attempt %d response", i);
			recv(s1, (char*)&rpkt2, sizeof(rpkt2), 0);
			DecryptEchoPacket(rpkt2);
			break;
		}
		else
			MSN_DebugLog("P2PNAT Request 2 attempt %d timeout", i);
	}

	// Response recieved so it's an IP Restricted NAT (Restricted Cone NAT)
	// (MSN does not detect Full Cone NAT and consider it as IP Restricted NAT)
	if (i < 4)
	{
		MyConnection.udpConType = conIPRestrictNAT;
		closesocket(s1);
		return;
	}

	DiscardExtraPackets(s1);

	// Symmetric NAT detection
	addr2.sin_port = rpkt.testPort;
	for (i=0; i<4; ++i)
	{
		if (Miranda_Terminated()) break;

		MSN_DebugLog("P2PNAT Request 3 attempt %d sent", i);
		// Send echo request to server 1
		sendto(s1, (char*)&pkt, sizeof(pkt), 0, (SOCKADDR*)&addr2, sizeof(addr2));

		fd_set fd;
		FD_ZERO(&fd);
		FD_SET(s1, &fd);
		TIMEVAL tv = {1 << i, 0 };

		if ( select(1, &fd, NULL, NULL, &tv) == 1 )
		{
			MSN_DebugLog("P2PNAT Request 3 attempt %d response", i);
			recv(s1, (char*)&rpkt2, sizeof(rpkt2), 0);
			DecryptEchoPacket(rpkt2);
			break;
		}
		else
			MSN_DebugLog("P2PNAT Request 3 attempt %d timeout", i);
	}
	if (i < 4)
	{
		// If ports different it's symmetric NAT
		MyConnection.udpConType = rpkt.clientPort == rpkt2.clientPort ?
			conPortRestrictNAT : conSymmetricNAT;
	}
	closesocket(s1);
}


static bool IsIcfEnabled(void)
{
	HRESULT hr;
	VARIANT_BOOL fwEnabled = VARIANT_FALSE;

	INetFwProfile* fwProfile = NULL;
	INetFwMgr* fwMgr = NULL;
	INetFwPolicy* fwPolicy = NULL;
	INetFwAuthorizedApplication* fwApp = NULL;
	INetFwAuthorizedApplications* fwApps = NULL;
	BSTR fwBstrProcessImageFileName = NULL;
	wchar_t *wszFileName = NULL;

	hr = CoInitialize(NULL);
	if (FAILED(hr)) return false;

	// Create an instance of the firewall settings manager.
	hr = CoCreateInstance(CLSID_NetFwMgr, NULL, CLSCTX_INPROC_SERVER,
			IID_INetFwMgr, (void**)&fwMgr );
	if (FAILED(hr)) goto error;

	// Retrieve the local firewall policy.
	hr = fwMgr->get_LocalPolicy(&fwPolicy);
	if (FAILED(hr)) goto error;

	// Retrieve the firewall profile currently in effect.
	hr = fwPolicy->get_CurrentProfile(&fwProfile);
	if (FAILED(hr)) goto error;

	// Get the current state of the firewall.
	hr = fwProfile->get_FirewallEnabled(&fwEnabled);
	if (FAILED(hr)) goto error;

	if (fwEnabled == VARIANT_FALSE) goto error;

	// Retrieve the authorized application collection.
	hr = fwProfile->get_AuthorizedApplications(&fwApps);
	if (FAILED(hr)) goto error;

	TCHAR szFileName[MAX_PATH];
	GetModuleFileName(NULL, szFileName, SIZEOF(szFileName));

	wszFileName = mir_t2u(szFileName);

	// Allocate a BSTR for the process image file name.
	fwBstrProcessImageFileName = SysAllocString(wszFileName);
	if (FAILED(hr)) goto error;

	// Attempt to retrieve the authorized application.
	hr = fwApps->Item(fwBstrProcessImageFileName, &fwApp);
	if (SUCCEEDED(hr))
	{
		// Find out if the authorized application is enabled.
		fwApp->get_Enabled(&fwEnabled);
		fwEnabled = ~fwEnabled;
	}

error:
	// Free the BSTR.
	SysFreeString(fwBstrProcessImageFileName);
	mir_free(wszFileName);

	// Release the authorized application instance.
	if (fwApp != NULL) fwApp->Release();

	// Release the authorized application collection.
	if (fwApps != NULL) fwApps->Release();

	// Release the firewall profile.
	if (fwProfile != NULL) fwProfile->Release();

	// Release the local firewall policy.
	if (fwPolicy != NULL) fwPolicy->Release();

	// Release the firewall settings manager.
	if (fwMgr != NULL) fwMgr->Release();

	CoUninitialize();

	return fwEnabled != VARIANT_FALSE;
}


void CMsnProto::MSNConnDetectThread( void* )
{
	char parBuf[512] = "";

	memset(&MyConnection, 0, sizeof(MyConnection));

	MyConnection.icf = IsIcfEnabled();
	bool portsMapped = getByte("NLSpecifyIncomingPorts", 0) != 0;

	unsigned gethst = getByte("AutoGetHost", 1);
	switch (gethst)
	{
		case 0:
			MSN_DebugLog("P2PNAT User overwrote IP connection is guessed by user settings only");

			// User specified host by himself so check if it matches MSN information
			// if it does, move to connection type autodetection,
			// if it does not, guess connection type from available info
			getStaticString(NULL, "YourHost", parBuf, sizeof(parBuf));
			if (msnExternalIP == NULL || strcmp(msnExternalIP, parBuf) != 0)
			{
				MyConnection.extIP = inet_addr(parBuf);
				if (MyConnection.extIP == INADDR_NONE)
				{
					PHOSTENT myhost = gethostbyname(parBuf);
					if (myhost != NULL)
						MyConnection.extIP = ((PIN_ADDR)myhost->h_addr)->S_un.S_addr;
					else
						setByte("AutoGetHost", 1);
				}
				if (MyConnection.extIP != INADDR_NONE)
				{
					MyConnection.intIP = MyConnection.extIP;
					MyConnection.udpConType = MyConnection.extIP ? (ConEnum)portsMapped : conUnknown;
					MyConnection.CalculateWeight();
					return;
				}
				else
					MyConnection.extIP = 0;
			}
			break;

		case 1:
			if (msnExternalIP != NULL)
				MyConnection.extIP = inet_addr(msnExternalIP);
			else
			{
				gethostname(parBuf, sizeof(parBuf));
				PHOSTENT myhost = gethostbyname(parBuf);
				if (myhost != NULL)
					MyConnection.extIP = ((PIN_ADDR)myhost->h_addr)->S_un.S_addr;
			}
			MyConnection.intIP = MyConnection.extIP;
			break;

		case 2:
			MyConnection.udpConType = conUnknown;
			MyConnection.CalculateWeight();
			return;
	}

	if (getByte( "NLSpecifyOutgoingPorts", 0))
	{
		// User specified outgoing ports so the connection must be firewalled
		// do not autodetect and guess connection type from available info
		MyConnection.intIP = MyConnection.extIP;
		MyConnection.udpConType = (ConEnum)portsMapped;
		MyConnection.upnpNAT = false;
		MyConnection.CalculateWeight();
		return;
	}

	MSNatDetect();

	// If user mapped incoming ports consider direct connection
	if (portsMapped)
	{
		MSN_DebugLog("P2PNAT User manually mapped ports for incoming connection");
		switch(MyConnection.udpConType)
		{
		case conUnknown:
		case conFirewall:
		case conISALike:
			MyConnection.udpConType = conDirect;
			break;

		case conUnknownNAT:
		case conPortRestrictNAT:
		case conIPRestrictNAT:
		case conSymmetricNAT:
			MyConnection.upnpNAT = true;
			break;
		}
	}

	MSN_DebugLog("P2PNAT Connection %s found UPnP: %d ICF: %d", conStr[MyConnection.udpConType],
		MyConnection.upnpNAT, MyConnection.icf);

	MyConnection.CalculateWeight();
}


void MyConnectionType::SetUdpCon(const char* str)
{
	for (unsigned i=0; i<sizeof(conStr)/sizeof(char*); ++i)
	{
		if (strcmp(conStr[i], str) == 0)
		{
			udpConType = (ConEnum)i;
			break;
		}
	}
}


void MyConnectionType::CalculateWeight(void)
{
	if (icf) weight = 0;
	else if (udpConType == conDirect) weight = 6;
	else if (udpConType >= conIPRestrictNAT && udpConType <= conSymmetricNAT)
		weight = upnpNAT ? 5 : 2;
	else if (udpConType == conUnknownNAT)
		weight = upnpNAT ? 4 : 1;
	else if (udpConType == conUnknown) weight = 1;
	else if (udpConType == conFirewall) weight = 2;
	else if (udpConType == conISALike) weight = 3;
}