[go: up one dir, main page]

File: network.c

package info (click to toggle)
uhub 0.3.2-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 1,016 kB
  • sloc: ansic: 12,630; xml: 588; sh: 356; perl: 233; makefile: 60
file content (792 lines) | stat: -rw-r--r-- 15,121 bytes parent folder | download
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
/*
 * uhub - A tiny ADC p2p connection hub
 * Copyright (C) 2007-2010, Jan Vidar Krey
 *
 * 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 3 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 "uhub.h"

static int is_ipv6_supported = -1; /* -1 = CHECK, 0 = NO, 1 = YES */
static int net_initialized = 0;

static struct net_statistics stats;
static struct net_statistics stats_total;

#if defined(IPV6_BINDV6ONLY)
#define SOCK_DUAL_STACK_OPT IPV6_BINDV6ONLY
#elif defined(IPV6_V6ONLY)
#define SOCK_DUAL_STACK_OPT IPV6_V6ONLY
#endif


int net_initialize()
{
	if (!net_initialized)
	{
		LOG_TRACE("Initializing network monitor.");

#ifdef WINSOCK
		struct WSAData wsa;
		if (WSAStartup(MAKEWORD(2, 2), &wsa) != NO_ERROR)
		{
			LOG_ERROR("Unable to initialize winsock.");
			return -1;
		}
#endif /* WINSOCK */

		if (!net_backend_init())
		{
#ifdef WINSOCK
			WSACleanup();
#endif
			return -1;
		}
		net_stats_initialize();

#ifdef SSL_SUPPORT
		LOG_TRACE("Initializing OpenSSL...");
		SSL_library_init();
		SSL_load_error_strings();
		OpenSSL_add_all_algorithms();
#endif /*  SSL_SUPPORT */

		net_initialized = 1;
		return 0;
	}
	return -1;
}

size_t net_get_max_sockets()
{
#ifdef HAVE_GETRLIMIT
	struct rlimit limits;
	if (getrlimit(RLIMIT_NOFILE, &limits) == 0)
	{
		return MIN(limits.rlim_max, 65536);
	}
	LOG_ERROR("getrlimit() failed");
	return 1024;
#else
#ifdef WIN32
	LOG_WARN("Windows system, limited to 4096 connections.");
	return 4096;
#else
	LOG_WARN("System does not have getrlimit(): constrained to 1024 sockets");
	return 1024;
#endif
#endif /* HAVE_GETRLIMIT */
}


int net_destroy()
{
	if (net_initialized)
	{
		LOG_TRACE("Shutting down network monitor");

		net_backend_shutdown();
		
#ifdef SSL_SUPPORT
		/* FIXME: Shutdown OpenSSL here. */
#endif

#ifdef WINSOCK
		WSACleanup();
#endif
		net_initialized = 0;
		return 0;
	}
	return -1;
}

#ifdef USE_LIBEVENT
struct event_base* net_get_evbase()
{
	return net_evbase;
}
#endif

static void net_error_out(int fd, const char* func)
{
	int err = net_error();
	LOG_ERROR("%s, fd=%d: %s (%d)", func, fd, net_error_string(err), err);
}

int net_error()
{
#ifdef WINSOCK
	return WSAGetLastError();
#else
	return errno;
#endif
}


const char* net_error_string(int code)
{
#ifdef WINSOCK
	static char string[32];
	snprintf(string, 32, "error code: %d", code);
	return string;
#else
	return strerror(code);
#endif
}


static int net_setsockopt(int fd, int level, int opt, const void* optval, socklen_t optlen)
{
	int ret = -1;
#ifdef WINSOCK
	ret = setsockopt(fd, level, opt, (const char*) optval, optlen);
#else
	ret = setsockopt(fd, level, opt, optval, optlen);
#endif

	if (ret == -1)
	{
		net_error_out(fd, "net_setsockopt");
	}

	return ret;
}

static int net_getsockopt(int fd, int level, int opt, void* optval, socklen_t* optlen)
{
	int ret = -1;
#ifdef WINSOCK
	ret = getsockopt(fd, level, opt, (char*) optval, optlen);
#else
	ret = getsockopt(fd, level, opt, optval, optlen);
#endif

	if (ret == -1)
	{
		net_error_out(fd, "net_getsockopt");
	}

	return ret;
}


int net_set_nonblocking(int fd, int toggle)
{
	int ret = -1;
#ifdef WINSOCK
	u_long on = toggle ? 1 : 0;
	ret = ioctlsocket(fd, FIONBIO, &on);
#else
#ifdef __sun__
	int flags = fcntl(fd, F_GETFL, 0);
	if (flags != -1)
	{
		if (toggle) flags |= O_NONBLOCK;
		else        flags &= ~O_NONBLOCK;
		ret = fcntl(fd, F_SETFL, flags);
	}
#else
	ret = ioctl(fd, FIONBIO, &toggle);
#endif
#endif
	if (ret == -1)
	{
		net_error_out(fd, "net_set_nonblocking");
	}
	return ret;
}

/* NOTE: Possibly only supported on BSD and OSX? */
int net_set_nosigpipe(int fd, int toggle)
{
	int ret = -1;
#ifdef SO_NOSIGPIPE
	ret = net_setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &toggle, sizeof(toggle));
	if (ret == -1)
	{
		net_error_out(fd, "net_set_nosigpipe");
	}
#endif
	return ret;
}

int net_set_close_on_exec(int fd, int toggle)
{
#ifdef WINSOCK
	return -1; /* FIXME: How is this done on Windows? */
#else
	return fcntl(fd, F_SETFD, toggle);
#endif
}

int net_set_linger(int fd, int toggle)
{
	int ret;
	ret = net_setsockopt(fd, SOL_SOCKET, SO_LINGER, &toggle, sizeof(toggle));
	if (ret == -1)
	{
		net_error_out(fd, "net_set_linger");
	}
	return ret;
}

int net_set_keepalive(int fd, int toggle)
{
	int ret;
	ret = net_setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &toggle, sizeof(toggle));
	if (ret == -1)
	{
		net_error_out(fd, "net_set_keepalive");
	}
	return ret;
}


int net_set_reuseaddress(int fd, int toggle)
{
	int ret;
	ret = net_setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &toggle, sizeof(toggle));
	if (ret == -1)
	{
		net_error_out(fd, "net_set_reuseaddress");
	}
	return ret;
}

int net_set_sendbuf_size(int fd, size_t size)
{
	return net_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &size, sizeof(size));
}

int net_get_sendbuf_size(int fd, size_t* size)
{
	socklen_t sz = sizeof(*size);
	return net_getsockopt(fd, SOL_SOCKET, SO_SNDBUF, size, &sz);
}

int net_set_recvbuf_size(int fd, size_t size)
{
	return net_setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size));
}

int net_get_recvbuf_size(int fd, size_t* size)
{
	socklen_t sz = sizeof(*size);
	return net_getsockopt(fd, SOL_SOCKET, SO_RCVBUF, size, &sz);
}



int net_close(int fd)
{
#ifdef WINSOCK
	int ret = closesocket(fd);
#else
	int ret = close(fd);
#endif

	if (ret == 0)
	{
		net_stats_add_close();
	}
	else
	{
		if (ret != -1)
		{
			net_stats_add_error();
		}
	}
	return ret;
}

int net_shutdown_r(int fd)
{
#ifdef WINSOCK
	return shutdown(fd, SD_RECEIVE);
#else
	return shutdown(fd, SHUT_RD);
#endif
}

int net_shutdown_w(int fd)
{
#ifdef WINSOCK
	return shutdown(fd, SD_SEND);
#else
	return shutdown(fd, SHUT_WR);
#endif
}

int net_shutdown_rw(int fd)
{
#ifdef WINSOCK
	return shutdown(fd, SD_BOTH);
#else
	return shutdown(fd, SHUT_RDWR);
#endif
}

int net_accept(int fd, struct ip_addr_encap* ipaddr)
{
	struct sockaddr_storage addr;
        struct sockaddr_in*  addr4;
        struct sockaddr_in6* addr6;
	socklen_t addr_size;
	int ret = 0;
	addr_size = sizeof(struct sockaddr_storage);

	memset(&addr, 0, addr_size);
	addr4 = (struct sockaddr_in*) &addr;
	addr6 = (struct sockaddr_in6*) &addr;

	ret = accept(fd, (struct sockaddr*) &addr, &addr_size);

	if (ret == -1)
	{
		switch (net_error())
		{
#if defined(__HAIKU__)
			case ETIMEDOUT:
#endif
#if defined(__linux__)
			case ENETDOWN:
			case EPROTO:
			case ENOPROTOOPT:
			case EHOSTDOWN:
			case ENONET:
			case EHOSTUNREACH:
			case EOPNOTSUPP:
				errno = EWOULDBLOCK;
#endif
			case EWOULDBLOCK:
				break;
			default:
				net_error_out(fd, "net_accept");
				net_stats_add_error();
				return -1;
		}
	}
	else
	{
		net_stats_add_accept();

		if (ipaddr)
		{
			memset(ipaddr, 0, sizeof(struct ip_addr_encap));
			ipaddr->af = addr.ss_family;;
			if (ipaddr->af == AF_INET6)
			{
				char address[INET6_ADDRSTRLEN+1] = { 0, };
				net_address_to_string(AF_INET6, (void*) &addr6->sin6_addr, address, INET6_ADDRSTRLEN+1);
				if (strchr(address, '.'))
				{
					/* Hack to convert IPv6 mapped IPv4 addresses to true IPv4 addresses */
					ipaddr->af = AF_INET;
					net_string_to_address(AF_INET, address, (void*) &ipaddr->internal_ip_data.in);
				}
				else
				{
					memcpy(&ipaddr->internal_ip_data.in6, &addr6->sin6_addr, sizeof(struct in6_addr));
				}
			}
			else
			{
				memcpy(&ipaddr->internal_ip_data.in, &addr4->sin_addr, sizeof(struct in_addr));
			}
		}
	}

	return ret;
}


int net_connect(int fd, const struct sockaddr *serv_addr, socklen_t addrlen)
{
	int ret = connect(fd, serv_addr, addrlen);
	if (ret == -1)
	{
		if (net_error() != EINPROGRESS)
		{
			net_error_out(fd, "net_connect");
			net_stats_add_error();
		}
	}
	return ret;
}



int net_is_ipv6_supported()
{
	if (is_ipv6_supported == -1)
	{
		int ret = socket(PF_INET6, SOCK_DGRAM, IPPROTO_UDP);
		if (ret == -1)
		{
#ifdef WINSOCK
			if (net_error() == WSAEAFNOSUPPORT)
#else
			if (net_error() == EAFNOSUPPORT)
#endif
			{
				LOG_TRACE("net_is_ipv6_supported(): IPv6 is not supported on this system.");
				is_ipv6_supported = 0;
				return 0;
			}
			
			net_error_out(ret, "net_is_ipv6_supported");
		}
		else
		{
#ifdef SOCK_DUAL_STACK_OPT
			int off = 0;
			if (net_setsockopt(ret, IPPROTO_IPV6, SOCK_DUAL_STACK_OPT, (char*) &off, sizeof(off)) < 0)
			{
				LOG_ERROR("net_socket_create(): Dual stack IPv6/IPv4 is not supported.");
				is_ipv6_supported = 0;
			}
			else
			{
				is_ipv6_supported = 1;
			}
#else
			is_ipv6_supported = 0;
#endif
			net_close(ret);
		}
	}
	return is_ipv6_supported;
}


int net_socket_create(int af, int type, int protocol)
{
	int sd = socket(af, type, protocol);
	if (sd == -1)
	{
		net_error_out(sd, "net_socket_create");
		return -1;
	}

#ifdef SOCK_DUAL_STACK_OPT
	/* BSD style */
	if (af == AF_INET6)
	{
		int off = 0;
		if (net_setsockopt(sd, IPPROTO_IPV6, SOCK_DUAL_STACK_OPT, (char*) &off, sizeof(off)) < 0)
		{
			LOG_ERROR("net_socket_create():  Cannot set socket to dual stack mode IPv6/IPv4 (%d - %s).", net_error(), net_error_string(net_error()));
		}
	}
#endif

	return sd;
}

const char* net_address_to_string(int af, const void* src, char* dst, socklen_t cnt)
{
#ifdef WINSOCK
	struct sockaddr_in  sin4;
	struct sockaddr_in6 sin6;
	struct in_addr*  addr4 = (struct in_addr*)  src;
	struct in6_addr* addr6 = (struct in6_addr*) src;
	size_t size;
	LPSOCKADDR addr;
	DWORD len = cnt;
	
	switch (af)
	{
		case AF_INET:
			sin4.sin_family  = AF_INET;
			sin4.sin_port    = 0;
			sin4.sin_addr    = *addr4;
			size             = sizeof(sin4);
			addr             = (LPSOCKADDR) &sin4;
			break;

		case AF_INET6:
			sin6.sin6_family = AF_INET6;
			sin6.sin6_port   = 0;
			sin6.sin6_addr   = *addr6;
			size             = sizeof(sin6);
			addr             = (LPSOCKADDR) &sin6;
			break;

		default:
			return NULL;
	}
	
	if (WSAAddressToString(addr, size, NULL, dst, &len) == 0)
	{
		return dst;
	}

	return NULL;
#else
	if (inet_ntop(af, src, dst, cnt))
	{
		if (af == AF_INET6 && strncmp(dst, "::ffff:", 7) == 0) /* IPv6 mapped IPv4 address. */
		{
			memmove(dst, dst + 7, cnt - 7);
		}
		return dst;
	}
	return NULL;
#endif
}

int net_string_to_address(int af, const char* src, void* dst)
{
#ifdef WINSOCK
	int ret, size;
	struct sockaddr_in  addr4;
	struct sockaddr_in6 addr6;
	struct sockaddr* addr = 0;
	if (af == AF_INET6)
	{
		if (net_is_ipv6_supported() != 1) return -1;
		size = sizeof(struct sockaddr_in6);
		addr = (struct sockaddr*) &addr6;
	}
	else
	{
		size = sizeof(struct sockaddr_in);
		addr = (struct sockaddr*) &addr4;
	}

	if (!net_initialized)
		net_initialize();

	ret = WSAStringToAddressA((char*) src, af, NULL, addr, &size);
	if (ret == -1)
	{
		return -1;
	}

	if (af == AF_INET6)
	{
		memcpy(dst, &addr6.sin6_addr, sizeof(addr6.sin6_addr));
	}
	else
	{
		memcpy(dst, &addr4.sin_addr, sizeof(addr4.sin_addr));
	}

	return 1;
#else
	return inet_pton(af, src, dst);
#endif
}

const char* net_get_peer_address(int fd)
{
	static char address[INET6_ADDRSTRLEN+1];
	struct sockaddr_storage storage;
	struct sockaddr_in6* name6;
	struct sockaddr_in*  name4;
	struct sockaddr*     name;
	socklen_t namelen;
	
	memset(address, 0, INET6_ADDRSTRLEN);
	namelen = sizeof(struct sockaddr_storage);
	memset(&storage, 0, namelen);
	
	name6 = (struct sockaddr_in6*) &storage;
	name4 = (struct sockaddr_in*)  &storage;
	name  = (struct sockaddr*)     &storage;
	
	if (getpeername(fd, (struct sockaddr*) name, &namelen) != -1)
	{
		int af = storage.ss_family;
		if (af == AF_INET6)
		{
			net_address_to_string(af, (void*) &name6->sin6_addr, address, INET6_ADDRSTRLEN);
		}
		else
		{
			net_address_to_string(af, (void*) &name4->sin_addr, address, INET6_ADDRSTRLEN);
		}
		return address;
	}
	else
	{
		net_error_out(fd, "net_get_peer_address");
		net_stats_add_error();
	}

	return "0.0.0.0";
}

const char* net_get_local_address(int fd)
{
	static char address[INET6_ADDRSTRLEN+1];
	struct sockaddr_storage storage;
	struct sockaddr_in6* name6;
	struct sockaddr_in*  name4;
	struct sockaddr*     name;
	socklen_t namelen;

	memset(address, 0, INET6_ADDRSTRLEN);
	namelen = sizeof(struct sockaddr_storage);
	memset(&storage, 0, namelen);

	name6 = (struct sockaddr_in6*) &storage;
	name4 = (struct sockaddr_in*)  &storage;
	name  = (struct sockaddr*)     &storage;

	if (getsockname(fd, (struct sockaddr*) name, &namelen) != -1)
	{
		int af = storage.ss_family;
		if (af == AF_INET6)
		{
			net_address_to_string(af, (void*) &name6->sin6_addr, address, INET6_ADDRSTRLEN);
		}
		else
		{
			net_address_to_string(af, (void*) &name4->sin_addr, address, INET6_ADDRSTRLEN);
		}
		return address;
	}
	else
	{
		net_error_out(fd, "net_get_local_address");
		net_stats_add_error();
	}

	return "0.0.0.0";
}



ssize_t net_recv(int fd, void* buf, size_t len, int flags)
{
	ssize_t ret = recv(fd, buf, len, flags);
	if (ret >= 0)
	{
		net_stats_add_rx(ret);
	}
	else
	{
		if (net_error() != EWOULDBLOCK)
		{
			/* net_error_out(fd, "net_recv"); */
			net_stats_add_error();
		}
	}
	return ret;
}


ssize_t net_send(int fd, const void* buf, size_t len, int flags)
{
	ssize_t ret = send(fd, buf, len, flags);
	if (ret >= 0)
	{
		net_stats_add_tx(ret);
	}
	else
	{
		if (net_error() != EWOULDBLOCK)
		{
			/* net_error_out(fd, "net_send"); */
			net_stats_add_error();
		}
	}
	return ret;
}


int net_bind(int fd, const struct sockaddr *my_addr, socklen_t addrlen)
{
	int ret = bind(fd, my_addr, addrlen);
	if (ret == -1)
	{
		net_error_out(fd, "net_bind");
		net_stats_add_error();
	}
	return ret;
}


int net_listen(int fd, int backlog)
{
	int ret = listen(fd, backlog);
	if (ret == -1)
	{
		net_error_out(fd, "net_listen");
		net_stats_add_error();
	}
	return ret;
}


void net_stats_initialize()
{
	memset(&stats_total, 0, sizeof(struct net_statistics));
	stats_total.timestamp = time(NULL);

	memset(&stats, 0, sizeof(struct net_statistics));
	stats.timestamp = time(NULL);
}

void net_stats_get(struct net_statistics** intermediate, struct net_statistics** total)
{
	*intermediate = &stats;
	*total = &stats_total;
}

void net_stats_reset()
{
	stats_total.tx += stats.tx;
	stats_total.rx += stats.rx;
	stats_total.accept += stats.accept;
	stats_total.errors += stats.errors;
	stats_total.closed += stats.closed;

	memset(&stats, 0, sizeof(struct net_statistics));
	stats.timestamp = time(NULL);
}

int net_stats_timeout()
{
	return (difftime(time(NULL), stats.timestamp) > TIMEOUT_STATS) ? 1 : 0;
}

void net_stats_add_tx(size_t bytes)
{
	stats.tx += bytes;
}

void net_stats_add_rx(size_t bytes)
{
	stats.rx += bytes;
}

void net_stats_add_accept()
{
	stats.accept++;
}

void net_stats_add_error()
{
	stats.errors++;
}

void net_stats_add_close()
{
	stats.closed++;
}