VirtualBox

source: vbox/trunk/src/VBox/Devices/Network/slirp/slirp.c@ 22020

Last change on this file since 22020 was 22020, checked in by vboxsync, 15 years ago

NAT: 1st stage of delayed port forwarding

  • Property svn:eol-style set to native
File size: 57.1 KB
Line 
1#include "slirp.h"
2#ifdef RT_OS_OS2
3# include <paths.h>
4#endif
5
6#include <VBox/err.h>
7#include <VBox/pdmdrv.h>
8#include <iprt/assert.h>
9#ifndef RT_OS_WINDOWS
10# include <sys/ioctl.h>
11# include <poll.h>
12#else
13# include <Winnls.h>
14# define _WINSOCK2API_
15# include <IPHlpApi.h>
16#endif
17#include <alias.h>
18
19#if !defined(RT_OS_WINDOWS)
20
21# define DO_ENGAGE_EVENT1(so, fdset, label) \
22 do { \
23 if( so->so_poll_index != -1 \
24 && so->s == polls[so->so_poll_index].fd) { \
25 polls[so->so_poll_index].events |= N_(fdset ## _poll); \
26 break; /* out of this loop */ \
27 } \
28 AssertRelease(poll_index < (nfds)); \
29 AssertRelease(poll_index >= 0 && poll_index < (nfds)); \
30 polls[poll_index].fd = (so)->s; \
31 (so)->so_poll_index = poll_index; \
32 polls[poll_index].events = N_(fdset ## _poll); \
33 polls[poll_index].revents = 0; \
34 poll_index++; \
35 } while(0)
36
37
38# define DO_ENGAGE_EVENT2(so, fdset1, fdset2, label) \
39 do { \
40 if( so->so_poll_index != -1 \
41 && so->s == polls[so->so_poll_index].fd) { \
42 polls[so->so_poll_index].events |= \
43 N_(fdset1 ## _poll) | N_(fdset1 ## _poll); \
44 break; /* out of this loop */ \
45 } \
46 AssertRelease(poll_index < (nfds)); \
47 polls[poll_index].fd = (so)->s; \
48 (so)->so_poll_index = poll_index; \
49 polls[poll_index].events = \
50 N_(fdset1 ## _poll) | N_(fdset1 ## _poll); \
51 poll_index++; \
52 } while(0)
53
54# define DO_POLL_EVENTS(rc, error, so, events, label) do {} while (0)
55
56# define DO_CHECK_FD_SET(so, events, fdset) ( ((so)->so_poll_index != -1) \
57 && ((so)->so_poll_index <= ndfs) \
58 && ((so)->s == polls[so->so_poll_index].fd) \
59 && (polls[(so)->so_poll_index].revents & N_(fdset ## _poll)))
60# define DO_UNIX_CHECK_FD_SET(so, events, fdset ) DO_CHECK_FD_SET((so), (events), fdset) /*specific for Unix API */
61# define DO_WIN_CHECK_FD_SET(so, events, fdset ) 0 /* specific for Windows Winsock API */
62
63# ifndef RT_OS_WINDOWS
64
65# ifndef RT_OS_LINUX
66# define readfds_poll (POLLRDNORM)
67# define writefds_poll (POLLWRNORM)
68# define xfds_poll (POLLRDBAND|POLLWRBAND|POLLPRI)
69# else
70# define readfds_poll (POLLIN)
71# define writefds_poll (POLLOUT)
72# define xfds_poll (POLLPRI)
73# endif
74# define rderr_poll (POLLERR)
75# define rdhup_poll (POLLHUP)
76# define nval_poll (POLLNVAL)
77
78# define ICMP_ENGAGE_EVENT(so, fdset) \
79 do { \
80 if (pData->icmp_socket.s != -1) \
81 DO_ENGAGE_EVENT1((so), fdset, ICMP); \
82 } while (0)
83# else /* !RT_OS_WINDOWS */
84# define DO_WIN_CHECK_FD_SET(so, events, fdset ) DO_CHECK_FD_SET((so), (events), fdset)
85# define ICMP_ENGAGE_EVENT(so, fdset) do {} while(0)
86#endif /* RT_OS_WINDOWS */
87
88#else /* defined(RT_OS_WINDOWS) */
89
90/*
91 * On Windows, we will be notified by IcmpSendEcho2() when the response arrives.
92 * So no call to WSAEventSelect necessary.
93 */
94# define ICMP_ENGAGE_EVENT(so, fdset) do {} while(0)
95
96# define DO_ENGAGE_EVENT1(so, fdset1, label) \
97 do { \
98 rc = WSAEventSelect((so)->s, VBOX_SOCKET_EVENT, FD_ALL_EVENTS); \
99 if (rc == SOCKET_ERROR) \
100 { \
101 /* This should not happen */ \
102 error = WSAGetLastError(); \
103 LogRel(("WSAEventSelect (" #label ") error %d (so=%x, socket=%s, event=%x)\n", \
104 error, (so), (so)->s, VBOX_SOCKET_EVENT)); \
105 } \
106 } while(0); \
107 CONTINUE(label)
108
109# define DO_ENGAGE_EVENT2(so, fdset1, fdset2, label) \
110 DO_ENGAGE_EVENT1((so), (fdset1), label)
111
112# define DO_POLL_EVENTS(rc, error, so, events, label) \
113 (rc) = WSAEnumNetworkEvents((so)->s, VBOX_SOCKET_EVENT, (events)); \
114 if ((rc) == SOCKET_ERROR) \
115 { \
116 (error) = WSAGetLastError(); \
117 LogRel(("WSAEnumNetworkEvents " #label " error %d\n", (error))); \
118 CONTINUE(label); \
119 }
120
121# define acceptds_win FD_ACCEPT
122# define acceptds_win_bit FD_ACCEPT_BIT
123
124# define readfds_win FD_READ
125# define readfds_win_bit FD_READ_BIT
126
127# define writefds_win FD_WRITE
128# define writefds_win_bit FD_WRITE_BIT
129
130# define xfds_win FD_OOB
131# define xfds_win_bit FD_OOB_BIT
132
133# define DO_CHECK_FD_SET(so, events, fdset) \
134 (((events).lNetworkEvents & fdset ## _win) && ((events).iErrorCode[fdset ## _win_bit] == 0))
135
136# define DO_WIN_CHECK_FD_SET(so, events, fdset ) DO_CHECK_FD_SET((so), (events), fdset)
137# define DO_UNIX_CHECK_FD_SET(so, events, fdset ) 1 /*specific for Unix API */
138
139#endif /* defined(RT_OS_WINDOWS) */
140
141#define TCP_ENGAGE_EVENT1(so, fdset) \
142 DO_ENGAGE_EVENT1((so), fdset, tcp)
143
144#define TCP_ENGAGE_EVENT2(so, fdset1, fdset2) \
145 DO_ENGAGE_EVENT2((so), fdset1, fdset2, tcp)
146
147#define UDP_ENGAGE_EVENT(so, fdset) \
148 DO_ENGAGE_EVENT1((so), fdset, udp)
149
150#define POLL_TCP_EVENTS(rc, error, so, events) \
151 DO_POLL_EVENTS((rc), (error), (so), (events), tcp)
152
153#define POLL_UDP_EVENTS(rc, error, so, events) \
154 DO_POLL_EVENTS((rc), (error), (so), (events), udp)
155
156#define CHECK_FD_SET(so, events, set) \
157 (DO_CHECK_FD_SET((so), (events), set))
158
159#define WIN_CHECK_FD_SET(so, events, set) \
160 (DO_WIN_CHECK_FD_SET((so), (events), set))
161#define UNIX_CHECK_FD_SET(so, events, set) \
162 (DO_UNIX_CHECK_FD_SET(so, events, set))
163
164/*
165 * Loging macros
166 */
167#if VBOX_WITH_DEBUG_NAT_SOCKETS
168# if defined(RT_OS_WINDOWS)
169# define DO_LOG_NAT_SOCK(so, proto, winevent, r_fdset, w_fdset, x_fdset) \
170 do { \
171 LogRel((" " #proto " %R[natsock] %R[natwinnetevents]\n", (so), (winevent))); \
172 } while (0)
173# else /* RT_OS_WINDOWS */
174# define DO_LOG_NAT_SOCK(so, proto, winevent, r_fdset, w_fdset, x_fdset) \
175 do { \
176 LogRel((" " #proto " %R[natsock] %s %s %s er: %s, %s, %s\n", (so), \
177 CHECK_FD_SET(so, ign ,r_fdset) ? "READ":"", \
178 CHECK_FD_SET(so, ign, w_fdset) ? "WRITE":"", \
179 CHECK_FD_SET(so, ign, x_fdset) ? "OOB":"", \
180 CHECK_FD_SET(so, ign, rderr) ? "RDERR":"", \
181 CHECK_FD_SET(so, ign, rdhup) ? "RDHUP":"", \
182 CHECK_FD_SET(so, ign, nval) ? "RDNVAL":"")); \
183 } while (0)
184# endif /* !RT_OS_WINDOWS */
185#else /* VBOX_WITH_DEBUG_NAT_SOCKETS */
186# define DO_LOG_NAT_SOCK(so, proto, winevent, r_fdset, w_fdset, x_fdset) do {} while (0)
187#endif /* !VBOX_WITH_DEBUG_NAT_SOCKETS */
188
189#define LOG_NAT_SOCK(so, proto, winevent, r_fdset, w_fdset, x_fdset) DO_LOG_NAT_SOCK((so), proto, (winevent), r_fdset, w_fdset, x_fdset)
190
191static void acivate_port_forwarding(PNATState, struct ethhdr *);
192static in_addr_t find_guest_ip(PNATState, uint8_t *);
193
194static const uint8_t special_ethaddr[6] =
195{
196 0x52, 0x54, 0x00, 0x12, 0x35, 0x00
197};
198
199static const uint8_t broadcast_ethaddr[6] =
200{
201 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
202};
203
204const uint8_t zerro_ethaddr[6] =
205{
206 0x0, 0x0, 0x0, 0x0, 0x0, 0x0
207};
208
209#ifdef RT_OS_WINDOWS
210static int get_dns_addr_domain(PNATState pData, bool fVerbose,
211 struct in_addr *pdns_addr,
212 const char **ppszDomain)
213{
214 /* Get amount of memory required for operation */
215 ULONG flags = GAA_FLAG_INCLUDE_PREFIX; /*GAA_FLAG_INCLUDE_ALL_INTERFACES;*/ /* all interfaces registered in NDIS */
216 PIP_ADAPTER_ADDRESSES addresses = NULL;
217 PIP_ADAPTER_ADDRESSES addr = NULL;
218 PIP_ADAPTER_DNS_SERVER_ADDRESS dns = NULL;
219 ULONG size = 0;
220 int wlen = 0;
221 char *suffix;
222 struct dns_entry *da = NULL;
223 struct dns_domain_entry *dd = NULL;
224 ULONG ret = ERROR_SUCCESS;
225
226 /* @todo add SKIPing flags to get only required information */
227
228 ret = pData->pfGetAdaptersAddresses(AF_INET, 0, NULL /* reserved */, addresses, &size);
229 if (ret != ERROR_BUFFER_OVERFLOW)
230 {
231 LogRel(("NAT: error %lu occurred on capacity detection operation\n", ret));
232 return -1;
233 }
234
235 if (size == 0)
236 {
237 LogRel(("NAT: Win socket API returns non capacity\n"));
238 return -1;
239 }
240
241 addresses = RTMemAllocZ(size);
242 if (addresses == NULL)
243 {
244 LogRel(("NAT: No memory available \n"));
245 return -1;
246 }
247
248 ret = pData->pfGetAdaptersAddresses(AF_INET, 0, NULL /* reserved */, addresses, &size);
249 if (ret != ERROR_SUCCESS)
250 {
251 LogRel(("NAT: error %lu occurred on fetching adapters info\n", ret));
252 RTMemFree(addresses);
253 return -1;
254 }
255 addr = addresses;
256 while(addr != NULL)
257 {
258 int found;
259 if (addr->OperStatus != IfOperStatusUp)
260 goto next;
261 dns = addr->FirstDnsServerAddress;
262 while (dns != NULL)
263 {
264 struct sockaddr *saddr = dns->Address.lpSockaddr;
265 if (saddr->sa_family != AF_INET)
266 goto next_dns;
267 /* add dns server to list */
268 da = RTMemAllocZ(sizeof(struct dns_entry));
269 if (da == NULL)
270 {
271 LogRel(("NAT: Can't allocate buffer for DNS entry\n"));
272 RTMemFree(addresses);
273 return VERR_NO_MEMORY;
274 }
275 LogRel(("NAT: adding %R[IP4] to DNS server list\n", &((struct sockaddr_in *)saddr)->sin_addr));
276 if ((((struct sockaddr_in *)saddr)->sin_addr.s_addr & htonl(IN_CLASSA_NET)) == ntohl(INADDR_LOOPBACK & IN_CLASSA_NET)) {
277 da->de_addr.s_addr = htonl(ntohl(special_addr.s_addr) | CTL_ALIAS);
278 }
279 else
280 {
281 da->de_addr.s_addr = ((struct sockaddr_in *)saddr)->sin_addr.s_addr;
282 }
283 TAILQ_INSERT_HEAD(&pData->dns_list_head, da, de_list);
284
285 if (addr->DnsSuffix == NULL)
286 goto next_dns;
287
288 /*uniq*/
289 RTUtf16ToUtf8(addr->DnsSuffix, &suffix);
290
291 if (!suffix || strlen(suffix) == 0) {
292 RTStrFree(suffix);
293 goto next_dns;
294 }
295
296 found = 0;
297 LIST_FOREACH(dd, &pData->dns_domain_list_head, dd_list)
298 {
299 if ( dd->dd_pszDomain != NULL
300 && strcmp(dd->dd_pszDomain, suffix) == 0)
301 {
302 found = 1;
303 RTStrFree(suffix);
304 break;
305 }
306 }
307 if (found == 0)
308 {
309 dd = RTMemAllocZ(sizeof(struct dns_domain_entry));
310 if (dd == NULL)
311 {
312 LogRel(("NAT: not enough memory\n"));
313 RTStrFree(suffix);
314 RTMemFree(addresses);
315 return VERR_NO_MEMORY;
316 }
317 dd->dd_pszDomain = suffix;
318 LogRel(("NAT: adding domain name %s to search list\n", dd->dd_pszDomain));
319 LIST_INSERT_HEAD(&pData->dns_domain_list_head, dd, dd_list);
320 }
321 next_dns:
322 dns = dns->Next;
323 }
324 next:
325 addr = addr->Next;
326 }
327 RTMemFree(addresses);
328 return 0;
329}
330
331#else /* !RT_OS_WINDOWS */
332
333static int get_dns_addr_domain(PNATState pData, bool fVerbose,
334 struct in_addr *pdns_addr,
335 const char **ppszDomain)
336{
337 char buff[512];
338 char buff2[256];
339 FILE *f = NULL;
340 int found = 0;
341 struct in_addr tmp_addr;
342
343#ifdef RT_OS_OS2
344 /* Try various locations. */
345 char *etc = getenv("ETC");
346 if (etc)
347 {
348 snprintf(buff, sizeof(buff), "%s/RESOLV2", etc);
349 f = fopen(buff, "rt");
350 }
351 if (!f)
352 {
353 snprintf(buff, sizeof(buff), "%s/RESOLV2", _PATH_ETC);
354 f = fopen(buff, "rt");
355 }
356 if (!f)
357 {
358 snprintf(buff, sizeof(buff), "%s/resolv.conf", _PATH_ETC);
359 f = fopen(buff, "rt");
360 }
361#else
362#ifndef DEBUG_vvl
363 f = fopen("/etc/resolv.conf", "r");
364#else
365 char *home = getenv("HOME");
366 snprintf(buff, sizeof(buff), "%s/resolv.conf", home);
367 f = fopen(buff, "r");
368 if (f != NULL)
369 {
370 Log(("NAT: DNS we're using %s\n", buff));
371 }
372 else
373 {
374 f = fopen("/etc/resolv.conf", "r");
375 Log(("NAT: DNS we're using %s\n", buff));
376 }
377#endif
378#endif
379 if (!f)
380 return -1;
381
382 if (ppszDomain)
383 *ppszDomain = NULL;
384 Log(("nat: DNS Servers:\n"));
385 while (fgets(buff, 512, f) != NULL)
386 {
387 struct dns_entry *da = NULL;
388 if (sscanf(buff, "nameserver%*[ \t]%256s", buff2) == 1)
389 {
390 if (!inet_aton(buff2, &tmp_addr))
391 continue;
392 /*localhost mask */
393 da = RTMemAllocZ(sizeof (struct dns_entry));
394 if (da == NULL)
395 {
396 LogRel(("can't alloc memory for DNS entry\n"));
397 return -1;
398 }
399 /*check */
400 da->de_addr.s_addr = tmp_addr.s_addr;
401 if ((da->de_addr.s_addr & htonl(IN_CLASSA_NET)) == ntohl(INADDR_LOOPBACK & IN_CLASSA_NET)) {
402 da->de_addr.s_addr = htonl(ntohl(special_addr.s_addr) | CTL_ALIAS);
403 }
404 TAILQ_INSERT_HEAD(&pData->dns_list_head, da, de_list);
405 found++;
406 }
407 if ((!strncmp(buff, "domain", 6) || !strncmp(buff, "search", 6)))
408 {
409 char *tok;
410 char *saveptr;
411 struct dns_domain_entry *dd = NULL;
412 int found = 0;
413 tok = strtok_r(&buff[6], " \t\n", &saveptr);
414 LIST_FOREACH(dd, &pData->dns_domain_list_head, dd_list)
415 {
416 if( tok != NULL
417 && strcmp(tok, dd->dd_pszDomain) == 0)
418 {
419 found = 1;
420 break;
421 }
422 }
423 if (tok != NULL && found == 0) {
424 dd = RTMemAllocZ(sizeof(struct dns_domain_entry));
425 if (dd == NULL)
426 {
427 LogRel(("NAT: not enought memory to add domain list\n"));
428 return VERR_NO_MEMORY;
429 }
430 dd->dd_pszDomain = RTStrDup(tok);
431 LogRel(("NAT: adding domain name %s to search list\n", dd->dd_pszDomain));
432 LIST_INSERT_HEAD(&pData->dns_domain_list_head, dd, dd_list);
433 }
434 }
435 }
436 fclose(f);
437 if (!found)
438 return -1;
439 return 0;
440}
441
442#endif
443
444static int slirp_init_dns_list(PNATState pData)
445{
446 TAILQ_INIT(&pData->dns_list_head);
447 LIST_INIT(&pData->dns_domain_list_head);
448 return get_dns_addr_domain(pData, true, NULL, NULL);
449}
450
451static void slirp_release_dns_list(PNATState pData)
452{
453 struct dns_entry *de = NULL;
454 struct dns_domain_entry *dd = NULL;
455 while(!TAILQ_EMPTY(&pData->dns_list_head)) {
456 de = TAILQ_FIRST(&pData->dns_list_head);
457 TAILQ_REMOVE(&pData->dns_list_head, de, de_list);
458 RTMemFree(de);
459 }
460 while(!LIST_EMPTY(&pData->dns_domain_list_head)) {
461 dd = LIST_FIRST(&pData->dns_domain_list_head);
462 LIST_REMOVE(dd, dd_list);
463 if (dd->dd_pszDomain != NULL)
464 RTStrFree(dd->dd_pszDomain);
465 RTMemFree(dd);
466 }
467}
468
469int get_dns_addr(PNATState pData, struct in_addr *pdns_addr)
470{
471 return get_dns_addr_domain(pData, false, pdns_addr, NULL);
472}
473
474#ifndef VBOX_WITH_NAT_SERVICE
475int slirp_init(PNATState *ppData, const char *pszNetAddr, uint32_t u32Netmask,
476 bool fPassDomain, void *pvUser)
477#else
478int slirp_init(PNATState *ppData, uint32_t u32NetAddr, uint32_t u32Netmask,
479 bool fPassDomain, void *pvUser)
480#endif
481{
482 int fNATfailed = 0;
483 int rc;
484 PNATState pData = RTMemAllocZ(sizeof(NATState));
485 *ppData = pData;
486 if (!pData)
487 return VERR_NO_MEMORY;
488 if (u32Netmask & 0x1f)
489 /* CTL is x.x.x.15, bootp passes up to 16 IPs (15..31) */
490 return VERR_INVALID_PARAMETER;
491 pData->fPassDomain = fPassDomain;
492 pData->pvUser = pvUser;
493 pData->netmask = u32Netmask;
494
495 /* sockets & TCP defaults */
496 pData->socket_rcv = 64 * _1K;
497 pData->socket_snd = 64 * _1K;
498 tcp_sndspace = 64 * _1K;
499 tcp_rcvspace = 64 * _1K;
500
501#ifdef RT_OS_WINDOWS
502 {
503 WSADATA Data;
504 WSAStartup(MAKEWORD(2, 0), &Data);
505 }
506 pData->phEvents[VBOX_SOCKET_EVENT_INDEX] = CreateEvent(NULL, FALSE, FALSE, NULL);
507#endif
508#ifdef VBOX_WITH_SLIRP_MT
509 QSOCKET_LOCK_CREATE(tcb);
510 QSOCKET_LOCK_CREATE(udb);
511 rc = RTReqCreateQueue(&pData->pReqQueue);
512 AssertReleaseRC(rc);
513#endif
514
515 link_up = 1;
516
517 debug_init();
518 if_init(pData);
519 ip_init(pData);
520 icmp_init(pData);
521
522 /* Initialise mbufs *after* setting the MTU */
523 m_init(pData);
524
525#ifndef VBOX_WITH_NAT_SERVICE
526 inet_aton(pszNetAddr, &special_addr);
527#else
528 special_addr.s_addr = u32NetAddr;
529#endif
530#ifdef VBOX_WITHOUT_SLIRP_CLIENT_ETHER
531 pData->slirp_ethaddr = &special_ethaddr[0];
532#endif
533 alias_addr.s_addr = special_addr.s_addr | htonl(CTL_ALIAS);
534 /* @todo: add ability to configure this staff */
535
536 /* set default addresses */
537 inet_aton("127.0.0.1", &loopback_addr);
538 if (slirp_init_dns_list(pData) < 0)
539 fNATfailed = 1;
540
541 dnsproxy_init(pData);
542
543 getouraddr(pData);
544 {
545 int flags = 0;
546 struct in_addr proxy_addr;
547 pData->proxy_alias = LibAliasInit(pData, NULL);
548 if (pData->proxy_alias == NULL)
549 {
550 LogRel(("NAT: LibAlias default rule wasn't initialized\n"));
551 AssertMsgFailed(("NAT: LibAlias default rule wasn't initialized\n"));
552 }
553 flags = LibAliasSetMode(pData->proxy_alias, 0, 0);
554 flags |= PKT_ALIAS_LOG; /* set logging */
555 flags = LibAliasSetMode(pData->proxy_alias, flags, ~0);
556 proxy_addr.s_addr = htonl(ntohl(special_addr.s_addr) | CTL_ALIAS);
557 LibAliasSetAddress(pData->proxy_alias, proxy_addr);
558 ftp_alias_load(pData);
559 nbt_alias_load(pData);
560 }
561 return fNATfailed ? VINF_NAT_DNS : VINF_SUCCESS;
562}
563
564/**
565 * Register statistics.
566 */
567void slirp_register_statistics(PNATState pData, PPDMDRVINS pDrvIns)
568{
569#ifdef VBOX_WITH_STATISTICS
570# define COUNTER(name, type, units, dsc) \
571 do { \
572 PDMDrvHlpSTAMRegisterF(pDrvIns, \
573 &pData->Stat ## name, \
574 type, \
575 STAMVISIBILITY_ALWAYS, \
576 units, \
577 dsc, \
578 "/Drivers/NAT%u/" #name, \
579 pDrvIns->iInstance); \
580 } while (0)
581
582# define PROFILE_COUNTER(name, dsc) COUNTER(name, STAMTYPE_PROFILE, STAMUNIT_TICKS_PER_CALL, dsc)
583# define COUNTING_COUNTER(name, dsc) COUNTER(name, STAMTYPE_COUNTER, STAMUNIT_COUNT, dsc)
584
585# include "counters.h"
586
587# undef COUNTER
588# undef PROFILE_COUNTER
589# undef COUNTING_COUNTER
590/** @todo register statistics for the variables dumped by:
591 * ipstats(pData); tcpstats(pData); udpstats(pData); icmpstats(pData);
592 * mbufstats(pData); sockstats(pData); */
593#endif /* VBOX_WITH_STATISTICS */
594}
595
596/**
597 * Deregister statistics.
598 */
599void slirp_deregister_statistics(PNATState pData, PPDMDRVINS pDrvIns)
600{
601#ifdef VBOX_WITH_STATISTICS
602# define PROFILE_COUNTER(name, dsc) PDMDrvHlpSTAMDeregister(pDrvIns, &pData->Stat ## name)
603# define COUNTING_COUNTER(name, dsc) PDMDrvHlpSTAMDeregister(pDrvIns, &pData->Stat ## name)
604
605# include "counters.h"
606
607# undef COUNTING_COUNTER
608# undef PROFILE_COUNTER
609#endif /* VBOX_WITH_STATISTICS */
610}
611
612/**
613 * Marks the link as up, making it possible to establish new connections.
614 */
615void slirp_link_up(PNATState pData)
616{
617 link_up = 1;
618}
619
620/**
621 * Marks the link as down and cleans up the current connections.
622 */
623void slirp_link_down(PNATState pData)
624{
625 struct socket *so;
626
627 while ((so = tcb.so_next) != &tcb)
628 {
629 if (so->so_state & SS_NOFDREF || so->s == -1)
630 sofree(pData, so);
631 else
632 tcp_drop(pData, sototcpcb(so), 0);
633 }
634
635 while ((so = udb.so_next) != &udb)
636 udp_detach(pData, so);
637
638 link_up = 0;
639}
640
641/**
642 * Terminates the slirp component.
643 */
644void slirp_term(PNATState pData)
645{
646#ifdef RT_OS_WINDOWS
647 pData->pfIcmpCloseHandle(pData->icmp_socket.sh);
648 FreeLibrary(pData->hmIcmpLibrary);
649 RTMemFree(pData->pvIcmpBuffer);
650#else
651 closesocket(pData->icmp_socket.s);
652#endif
653
654 slirp_link_down(pData);
655 slirp_release_dns_list(pData);
656 ftp_alias_unload(pData);
657 nbt_alias_unload(pData);
658 while(!LIST_EMPTY(&instancehead)) {
659 struct libalias *la = LIST_FIRST(&instancehead);
660 /* libalias do all clean up */
661 LibAliasUninit(la);
662 }
663#ifdef RT_OS_WINDOWS
664 WSACleanup();
665#endif
666#ifdef LOG_ENABLED
667 Log(("\n"
668 "NAT statistics\n"
669 "--------------\n"
670 "\n"));
671 ipstats(pData);
672 tcpstats(pData);
673 udpstats(pData);
674 icmpstats(pData);
675 mbufstats(pData);
676 sockstats(pData);
677 Log(("\n"
678 "\n"
679 "\n"));
680#endif
681 RTMemFree(pData);
682}
683
684
685#define CONN_CANFSEND(so) (((so)->so_state & (SS_FCANTSENDMORE|SS_ISFCONNECTED)) == SS_ISFCONNECTED)
686#define CONN_CANFRCV(so) (((so)->so_state & (SS_FCANTRCVMORE|SS_ISFCONNECTED)) == SS_ISFCONNECTED)
687
688/*
689 * curtime kept to an accuracy of 1ms
690 */
691static void updtime(PNATState pData)
692{
693#ifdef RT_OS_WINDOWS
694 struct _timeb tb;
695
696 _ftime(&tb);
697 curtime = (u_int)tb.time * (u_int)1000;
698 curtime += (u_int)tb.millitm;
699#else
700 gettimeofday(&tt, 0);
701
702 curtime = (u_int)tt.tv_sec * (u_int)1000;
703 curtime += (u_int)tt.tv_usec / (u_int)1000;
704
705 if ((tt.tv_usec % 1000) >= 500)
706 curtime++;
707#endif
708}
709
710#ifdef RT_OS_WINDOWS
711void slirp_select_fill(PNATState pData, int *pnfds)
712#else /* RT_OS_WINDOWS */
713void slirp_select_fill(PNATState pData, int *pnfds, struct pollfd *polls)
714#endif /* !RT_OS_WINDOWS */
715{
716 struct socket *so, *so_next;
717 int nfds;
718#if defined(RT_OS_WINDOWS)
719 int rc;
720 int error;
721#else
722 int poll_index = 0;
723#endif
724 int i;
725
726 STAM_PROFILE_START(&pData->StatFill, a);
727
728 nfds = *pnfds;
729
730 /*
731 * First, TCP sockets
732 */
733 do_slowtimo = 0;
734 if (!link_up)
735 goto done;
736 /*
737 * *_slowtimo needs calling if there are IP fragments
738 * in the fragment queue, or there are TCP connections active
739 */
740 /* XXX:
741 * triggering of fragment expiration should be the same but use new macroses
742 */
743 do_slowtimo = (tcb.so_next != &tcb);
744 if (!do_slowtimo)
745 {
746 for (i = 0; i < IPREASS_NHASH; i++)
747 {
748 if (!TAILQ_EMPTY(&ipq[i]))
749 {
750 do_slowtimo = 1;
751 break;
752 }
753 }
754 }
755 ICMP_ENGAGE_EVENT(&pData->icmp_socket, readfds);
756
757 STAM_COUNTER_RESET(&pData->StatTCP);
758 STAM_COUNTER_RESET(&pData->StatTCPHot);
759
760 QSOCKET_FOREACH(so, so_next, tcp)
761 /* { */
762#if !defined(RT_OS_WINDOWS)
763 so->so_poll_index = -1;
764#endif
765 STAM_COUNTER_INC(&pData->StatTCP);
766
767 /*
768 * See if we need a tcp_fasttimo
769 */
770 if ( time_fasttimo == 0
771 && so->so_tcpcb != NULL
772 && so->so_tcpcb->t_flags & TF_DELACK)
773 time_fasttimo = curtime; /* Flag when we want a fasttimo */
774
775 /*
776 * NOFDREF can include still connecting to local-host,
777 * newly socreated() sockets etc. Don't want to select these.
778 */
779 if (so->so_state & SS_NOFDREF || so->s == -1)
780 CONTINUE(tcp);
781
782 /*
783 * Set for reading sockets which are accepting
784 */
785 if (so->so_state & SS_FACCEPTCONN)
786 {
787 STAM_COUNTER_INC(&pData->StatTCPHot);
788 TCP_ENGAGE_EVENT1(so, readfds);
789 CONTINUE(tcp);
790 }
791
792 /*
793 * Set for writing sockets which are connecting
794 */
795 if (so->so_state & SS_ISFCONNECTING)
796 {
797 Log2(("connecting %R[natsock] engaged\n",so));
798 STAM_COUNTER_INC(&pData->StatTCPHot);
799 TCP_ENGAGE_EVENT1(so, writefds);
800 }
801
802 /*
803 * Set for writing if we are connected, can send more, and
804 * we have something to send
805 */
806 if (CONN_CANFSEND(so) && so->so_rcv.sb_cc)
807 {
808 STAM_COUNTER_INC(&pData->StatTCPHot);
809 TCP_ENGAGE_EVENT1(so, writefds);
810 }
811
812 /*
813 * Set for reading (and urgent data) if we are connected, can
814 * receive more, and we have room for it XXX /2 ?
815 */
816 if (CONN_CANFRCV(so) && (so->so_snd.sb_cc < (so->so_snd.sb_datalen/2)))
817 {
818 STAM_COUNTER_INC(&pData->StatTCPHot);
819 TCP_ENGAGE_EVENT2(so, readfds, xfds);
820 }
821 LOOP_LABEL(tcp, so, so_next);
822 }
823
824 /*
825 * UDP sockets
826 */
827 STAM_COUNTER_RESET(&pData->StatUDP);
828 STAM_COUNTER_RESET(&pData->StatUDPHot);
829
830 QSOCKET_FOREACH(so, so_next, udp)
831 /* { */
832
833 STAM_COUNTER_INC(&pData->StatUDP);
834#if !defined(RT_OS_WINDOWS)
835 so->so_poll_index = -1;
836#endif
837
838 /*
839 * See if it's timed out
840 */
841 if (so->so_expire)
842 {
843 if (so->so_expire <= curtime)
844 {
845 Log2(("NAT: %R[natsock] expired\n", so));
846 if (so->so_timeout != NULL)
847 {
848 so->so_timeout(pData, so, so->so_timeout_arg);
849 }
850#ifdef VBOX_WITH_SLIRP_MT
851 /* we need so_next for continue our cycle*/
852 so_next = so->so_next;
853#endif
854 UDP_DETACH(pData, so, so_next);
855 CONTINUE_NO_UNLOCK(udp);
856 }
857 else
858 do_slowtimo = 1; /* Let socket expire */
859 }
860
861 /*
862 * When UDP packets are received from over the link, they're
863 * sendto()'d straight away, so no need for setting for writing
864 * Limit the number of packets queued by this session to 4.
865 * Note that even though we try and limit this to 4 packets,
866 * the session could have more queued if the packets needed
867 * to be fragmented.
868 *
869 * (XXX <= 4 ?)
870 */
871 if ((so->so_state & SS_ISFCONNECTED) && so->so_queued <= 4)
872 {
873 STAM_COUNTER_INC(&pData->StatUDPHot);
874 UDP_ENGAGE_EVENT(so, readfds);
875 }
876 LOOP_LABEL(udp, so, so_next);
877 }
878done:
879
880#if defined(RT_OS_WINDOWS)
881 *pnfds = VBOX_EVENT_COUNT;
882#else /* RT_OS_WINDOWS */
883 AssertRelease(poll_index <= *pnfds);
884 *pnfds = poll_index;
885#endif /* !RT_OS_WINDOWS */
886
887 STAM_PROFILE_STOP(&pData->StatFill, a);
888}
889
890#if defined(RT_OS_WINDOWS)
891void slirp_select_poll(PNATState pData, int fTimeout, int fIcmp)
892#else /* RT_OS_WINDOWS */
893void slirp_select_poll(PNATState pData, struct pollfd *polls, int ndfs)
894#endif /* !RT_OS_WINDOWS */
895{
896 struct socket *so, *so_next;
897 int ret;
898#if defined(RT_OS_WINDOWS)
899 WSANETWORKEVENTS NetworkEvents;
900 int rc;
901 int error;
902#else
903 int poll_index = 0;
904#endif
905
906 STAM_PROFILE_START(&pData->StatPoll, a);
907
908 /* Update time */
909 updtime(pData);
910
911 /*
912 * See if anything has timed out
913 */
914 if (link_up)
915 {
916 if (time_fasttimo && ((curtime - time_fasttimo) >= 2))
917 {
918 STAM_PROFILE_START(&pData->StatFastTimer, a);
919 tcp_fasttimo(pData);
920 time_fasttimo = 0;
921 STAM_PROFILE_STOP(&pData->StatFastTimer, a);
922 }
923 if (do_slowtimo && ((curtime - last_slowtimo) >= 499))
924 {
925 STAM_PROFILE_START(&pData->StatSlowTimer, a);
926 ip_slowtimo(pData);
927 tcp_slowtimo(pData);
928 last_slowtimo = curtime;
929 STAM_PROFILE_STOP(&pData->StatSlowTimer, a);
930 }
931 }
932#if defined(RT_OS_WINDOWS)
933 if (fTimeout)
934 return; /* only timer update */
935#endif
936
937 /*
938 * Check sockets
939 */
940 if (!link_up)
941 goto done;
942#if defined(RT_OS_WINDOWS)
943 /*XXX: before renaming please make see define
944 * fIcmp in slirp_state.h
945 */
946 if (fIcmp)
947 sorecvfrom(pData, &pData->icmp_socket);
948#else
949 if ( (pData->icmp_socket.s != -1)
950 && CHECK_FD_SET(&pData->icmp_socket, ignored, readfds))
951 sorecvfrom(pData, &pData->icmp_socket);
952#endif
953 /*
954 * Check TCP sockets
955 */
956 QSOCKET_FOREACH(so, so_next, tcp)
957 /* { */
958
959#ifdef VBOX_WITH_SLIRP_MT
960 if ( so->so_state & SS_NOFDREF
961 && so->so_deleted == 1)
962 {
963 struct socket *son, *sop = NULL;
964 QSOCKET_LOCK(tcb);
965 if (so->so_next != NULL)
966 {
967 if (so->so_next != &tcb)
968 SOCKET_LOCK(so->so_next);
969 son = so->so_next;
970 }
971 if ( so->so_prev != &tcb
972 && so->so_prev != NULL)
973 {
974 SOCKET_LOCK(so->so_prev);
975 sop = so->so_prev;
976 }
977 QSOCKET_UNLOCK(tcb);
978 remque(pData, so);
979 NSOCK_DEC();
980 SOCKET_UNLOCK(so);
981 SOCKET_LOCK_DESTROY(so);
982 RTMemFree(so);
983 so_next = son;
984 if (sop != NULL)
985 SOCKET_UNLOCK(sop);
986 CONTINUE_NO_UNLOCK(tcp);
987 }
988#endif
989 /*
990 * FD_ISSET is meaningless on these sockets
991 * (and they can crash the program)
992 */
993 if (so->so_state & SS_NOFDREF || so->s == -1)
994 CONTINUE(tcp);
995
996 POLL_TCP_EVENTS(rc, error, so, &NetworkEvents);
997
998 LOG_NAT_SOCK(so, TCP, &NetworkEvents, readfds, writefds, xfds);
999
1000
1001 /*
1002 * Check for URG data
1003 * This will soread as well, so no need to
1004 * test for readfds below if this succeeds
1005 */
1006
1007 /* out-of-band data */
1008 if (CHECK_FD_SET(so, NetworkEvents, xfds))
1009 {
1010 sorecvoob(pData, so);
1011 }
1012
1013 /*
1014 * Check sockets for reading
1015 */
1016 else if ( CHECK_FD_SET(so, NetworkEvents, readfds)
1017 || WIN_CHECK_FD_SET(so, NetworkEvents, acceptds))
1018 {
1019 /*
1020 * Check for incoming connections
1021 */
1022 if (so->so_state & SS_FACCEPTCONN)
1023 {
1024 TCP_CONNECT(pData, so);
1025#if defined(RT_OS_WINDOWS)
1026 if (!(NetworkEvents.lNetworkEvents & FD_CLOSE))
1027#endif
1028 CONTINUE(tcp);
1029 }
1030
1031 ret = soread(pData, so);
1032 /* Output it if we read something */
1033 if (RT_LIKELY(ret > 0))
1034 TCP_OUTPUT(pData, sototcpcb(so));
1035 }
1036
1037#if defined(RT_OS_WINDOWS)
1038 /*
1039 * Check for FD_CLOSE events.
1040 * in some cases once FD_CLOSE engaged on socket it could be flashed latter (for some reasons)
1041 */
1042 if ( (NetworkEvents.lNetworkEvents & FD_CLOSE)
1043 || (so->so_close == 1))
1044 {
1045 so->so_close = 1; /* mark it */
1046 /*
1047 * drain the socket
1048 */
1049 for (;;)
1050 {
1051 ret = soread(pData, so);
1052 if (ret > 0)
1053 TCP_OUTPUT(pData, sototcpcb(so));
1054 else
1055 break;
1056 }
1057 CONTINUE(tcp);
1058 }
1059#endif
1060
1061 /*
1062 * Check sockets for writing
1063 */
1064 if (CHECK_FD_SET(so, NetworkEvents, writefds))
1065 {
1066 /*
1067 * Check for non-blocking, still-connecting sockets
1068 */
1069 if (so->so_state & SS_ISFCONNECTING)
1070 {
1071 Log2(("connecting %R[natsock] catched\n", so));
1072 /* Connected */
1073 so->so_state &= ~SS_ISFCONNECTING;
1074
1075 /*
1076 * This should be probably guarded by PROBE_CONN too. Anyway,
1077 * we disable it on OS/2 because the below send call returns
1078 * EFAULT which causes the opened TCP socket to close right
1079 * after it has been opened and connected.
1080 */
1081#ifndef RT_OS_OS2
1082 ret = send(so->s, (const char *)&ret, 0, 0);
1083 if (ret < 0)
1084 {
1085 /* XXXXX Must fix, zero bytes is a NOP */
1086 if ( errno == EAGAIN
1087 || errno == EWOULDBLOCK
1088 || errno == EINPROGRESS
1089 || errno == ENOTCONN)
1090 CONTINUE(tcp);
1091
1092 /* else failed */
1093 so->so_state = SS_NOFDREF;
1094 }
1095 /* else so->so_state &= ~SS_ISFCONNECTING; */
1096#endif
1097
1098 /*
1099 * Continue tcp_input
1100 */
1101 TCP_INPUT(pData, (struct mbuf *)NULL, sizeof(struct ip), so);
1102 /* continue; */
1103 }
1104 else
1105 SOWRITE(ret, pData, so);
1106 /*
1107 * XXX If we wrote something (a lot), there could be the need
1108 * for a window update. In the worst case, the remote will send
1109 * a window probe to get things going again.
1110 */
1111 }
1112
1113 /*
1114 * Probe a still-connecting, non-blocking socket
1115 * to check if it's still alive
1116 */
1117#ifdef PROBE_CONN
1118 if (so->so_state & SS_ISFCONNECTING)
1119 {
1120 ret = recv(so->s, (char *)&ret, 0, 0);
1121
1122 if (ret < 0)
1123 {
1124 /* XXX */
1125 if ( errno == EAGAIN
1126 || errno == EWOULDBLOCK
1127 || errno == EINPROGRESS
1128 || errno == ENOTCONN)
1129 {
1130 CONTINUE(tcp); /* Still connecting, continue */
1131 }
1132
1133 /* else failed */
1134 so->so_state = SS_NOFDREF;
1135
1136 /* tcp_input will take care of it */
1137 }
1138 else
1139 {
1140 ret = send(so->s, &ret, 0, 0);
1141 if (ret < 0)
1142 {
1143 /* XXX */
1144 if ( errno == EAGAIN
1145 || errno == EWOULDBLOCK
1146 || errno == EINPROGRESS
1147 || errno == ENOTCONN)
1148 {
1149 CONTINUE(tcp);
1150 }
1151 /* else failed */
1152 so->so_state = SS_NOFDREF;
1153 }
1154 else
1155 so->so_state &= ~SS_ISFCONNECTING;
1156
1157 }
1158 TCP_INPUT((struct mbuf *)NULL, sizeof(struct ip),so);
1159 } /* SS_ISFCONNECTING */
1160#endif
1161#ifndef RT_OS_WINDOWS
1162 if ( UNIX_CHECK_FD_SET(so, NetworkEvents, rdhup)
1163 || UNIX_CHECK_FD_SET(so, NetworkEvents, rderr))
1164 {
1165 int err;
1166 int inq, outq;
1167 int status;
1168 socklen_t optlen = sizeof(int);
1169 inq = outq = 0;
1170 status = getsockopt(so->s, SOL_SOCKET, SO_ERROR, &err, &optlen);
1171 if (status != 0)
1172 Log(("NAT: can't get error status from %R[natsock]\n", so));
1173#ifndef RT_OS_SOLARIS
1174 status = ioctl(so->s, FIONREAD, &inq); /* tcp(7) recommends SIOCINQ which is Linux specific */
1175 if (status != 0 || status != EINVAL)
1176 {
1177 /* EINVAL returned if socket in listen state tcp(7)*/
1178 Log(("NAT: can't get depth of IN queue status from %R[natsock]\n", so));
1179 }
1180 status = ioctl(so->s, TIOCOUTQ, &outq); /* SIOCOUTQ see previous comment */
1181 if (status != 0)
1182 Log(("NAT: can't get depth of OUT queue from %R[natsock]\n", so));
1183#else
1184 /*
1185 * Solaris has bit different ioctl commands and its handlings
1186 * hint: streamio(7) I_NREAD
1187 */
1188#endif
1189 if ( so->so_state & SS_ISFCONNECTING
1190 || UNIX_CHECK_FD_SET(so, NetworkEvents, readfds))
1191 {
1192 /**
1193 * Check if we need here take care about gracefull connection
1194 * @todo try with proxy server
1195 */
1196 if (UNIX_CHECK_FD_SET(so, NetworkEvents, readfds))
1197 {
1198 /*
1199 * Never meet inq != 0 or outq != 0, anyway let it stay for a while
1200 * in case it happens we'll able to detect it.
1201 * Give TCP/IP stack wait or expire the socket.
1202 */
1203 Log(("NAT: %R[natsock] err(%d:%s) s(in:%d,out:%d)happens on read I/O, "
1204 "other side close connection \n", so, err, strerror(err), inq, outq));
1205 CONTINUE(tcp);
1206 }
1207 goto tcp_input_close;
1208 }
1209 if ( !UNIX_CHECK_FD_SET(so, NetworkEvents, readfds)
1210 && !UNIX_CHECK_FD_SET(so, NetworkEvents, writefds)
1211 && !UNIX_CHECK_FD_SET(so, NetworkEvents, xfds))
1212 {
1213 Log(("NAT: system expires the socket %R[natsock] err(%d:%s) s(in:%d,out:%d) happens on non-I/O. ",
1214 so, err, strerror(err), inq, outq));
1215 goto tcp_input_close;
1216 }
1217 Log(("NAT: %R[natsock] we've met(%d:%s) s(in:%d, out:%d) unhandled combination hup (%d) "
1218 "rederr(%d) on (r:%d, w:%d, x:%d)\n",
1219 so, err, strerror(err),
1220 inq, outq,
1221 UNIX_CHECK_FD_SET(so, ign, rdhup),
1222 UNIX_CHECK_FD_SET(so, ign, rderr),
1223 UNIX_CHECK_FD_SET(so, ign, readfds),
1224 UNIX_CHECK_FD_SET(so, ign, writefds),
1225 UNIX_CHECK_FD_SET(so, ign, xfds)));
1226 /*
1227 * Give OS's TCP/IP stack a chance to resolve an issue or expire the socket.
1228 */
1229 CONTINUE(tcp);
1230tcp_input_close:
1231 so->so_state = SS_NOFDREF; /*cause connection valid tcp connection termination and socket closing */
1232 TCP_INPUT(pData, (struct mbuf *)NULL, sizeof(struct ip), so);
1233 CONTINUE(tcp);
1234 }
1235#endif
1236 LOOP_LABEL(tcp, so, so_next);
1237 }
1238
1239 /*
1240 * Now UDP sockets.
1241 * Incoming packets are sent straight away, they're not buffered.
1242 * Incoming UDP data isn't buffered either.
1243 */
1244 QSOCKET_FOREACH(so, so_next, udp)
1245 /* { */
1246#ifdef VBOX_WITH_SLIRP_MT
1247 if ( so->so_state & SS_NOFDREF
1248 && so->so_deleted == 1)
1249 {
1250 struct socket *son, *sop = NULL;
1251 QSOCKET_LOCK(udb);
1252 if (so->so_next != NULL)
1253 {
1254 if (so->so_next != &udb)
1255 SOCKET_LOCK(so->so_next);
1256 son = so->so_next;
1257 }
1258 if ( so->so_prev != &udb
1259 && so->so_prev != NULL)
1260 {
1261 SOCKET_LOCK(so->so_prev);
1262 sop = so->so_prev;
1263 }
1264 QSOCKET_UNLOCK(udb);
1265 remque(pData, so);
1266 NSOCK_DEC();
1267 SOCKET_UNLOCK(so);
1268 SOCKET_LOCK_DESTROY(so);
1269 RTMemFree(so);
1270 so_next = son;
1271 if (sop != NULL)
1272 SOCKET_UNLOCK(sop);
1273 CONTINUE_NO_UNLOCK(udp);
1274 }
1275#endif
1276 POLL_UDP_EVENTS(rc, error, so, &NetworkEvents);
1277
1278 LOG_NAT_SOCK(so, UDP, &NetworkEvents, readfds, writefds, xfds);
1279
1280 if (so->s != -1 && CHECK_FD_SET(so, NetworkEvents, readfds))
1281 {
1282 SORECVFROM(pData, so);
1283 }
1284 LOOP_LABEL(udp, so, so_next);
1285 }
1286
1287done:
1288#ifndef VBOX_WITH_SLIRP_MT
1289 /*
1290 * See if we can start outputting
1291 */
1292 if (if_queued && link_up)
1293 if_start(pData);
1294#endif
1295
1296 STAM_PROFILE_STOP(&pData->StatPoll, a);
1297}
1298
1299#ifndef VBOX_WITHOUT_SLIRP_CLIENT_ETHER
1300#define ETH_ALEN 6
1301#define ETH_HLEN 14
1302
1303#define ARPOP_REQUEST 1 /* ARP request */
1304#define ARPOP_REPLY 2 /* ARP reply */
1305
1306struct ethhdr
1307{
1308 unsigned char h_dest[ETH_ALEN]; /* destination eth addr */
1309 unsigned char h_source[ETH_ALEN]; /* source ether addr */
1310 unsigned short h_proto; /* packet type ID field */
1311};
1312AssertCompileSize(struct ethhdr, 14);
1313#endif
1314
1315struct arphdr
1316{
1317 unsigned short ar_hrd; /* format of hardware address */
1318 unsigned short ar_pro; /* format of protocol address */
1319 unsigned char ar_hln; /* length of hardware address */
1320 unsigned char ar_pln; /* length of protocol address */
1321 unsigned short ar_op; /* ARP opcode (command) */
1322
1323 /*
1324 * Ethernet looks like this : This bit is variable sized however...
1325 */
1326 unsigned char ar_sha[ETH_ALEN]; /* sender hardware address */
1327 unsigned char ar_sip[4]; /* sender IP address */
1328 unsigned char ar_tha[ETH_ALEN]; /* target hardware address */
1329 unsigned char ar_tip[4]; /* target IP address */
1330};
1331AssertCompileSize(struct arphdr, 28);
1332
1333static void arp_input(PNATState pData, struct mbuf *m)
1334{
1335 struct ethhdr *eh;
1336 struct ethhdr *reh;
1337 struct arphdr *ah;
1338 struct arphdr *rah;
1339 int ar_op;
1340 struct ex_list *ex_ptr;
1341 uint32_t htip;
1342 uint32_t tip;
1343 struct mbuf *mr;
1344 eh = mtod(m, struct ethhdr *);
1345 ah = (struct arphdr *)&eh[1];
1346 htip = ntohl(*(uint32_t*)ah->ar_tip);
1347 tip = *(uint32_t*)ah->ar_tip;
1348
1349 mr = m_get(pData);
1350#ifdef VBOX_WITHOUT_SLIRP_CLIENT_ETHER
1351 reh = mtod(mr, struct ethhdr *);
1352 memcpy(reh->h_source, eh->h_source, ETH_ALEN); /* XXX: if_encap will swap src and dst*/
1353 Log4(("NAT: arp:%R[ether]->%R[ether]\n",
1354 reh->h_source, reh->h_dest));
1355 Log4(("NAT: arp: %R[IP4]\n", &tip));
1356#endif
1357 mr->m_data += if_maxlinkhdr;
1358 mr->m_len = sizeof(struct arphdr);
1359 rah = mtod(mr, struct arphdr *);
1360
1361 ar_op = ntohs(ah->ar_op);
1362 switch(ar_op)
1363 {
1364 case ARPOP_REQUEST:
1365#ifdef VBOX_WITH_NAT_SERVICE
1366 if (tip == special_addr.s_addr) goto arp_ok;
1367#endif
1368 if ((htip & pData->netmask) == ntohl(special_addr.s_addr))
1369 {
1370 if ( CTL_CHECK(htip, CTL_DNS)
1371 || CTL_CHECK(htip, CTL_ALIAS)
1372 || CTL_CHECK(htip, CTL_TFTP))
1373 goto arp_ok;
1374 for (ex_ptr = exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next)
1375 {
1376 if ((htip & ~pData->netmask) == ex_ptr->ex_addr)
1377 {
1378 goto arp_ok;
1379 }
1380 }
1381 return;
1382 arp_ok:
1383 rah->ar_hrd = htons(1);
1384 rah->ar_pro = htons(ETH_P_IP);
1385 rah->ar_hln = ETH_ALEN;
1386 rah->ar_pln = 4;
1387 rah->ar_op = htons(ARPOP_REPLY);
1388 memcpy(rah->ar_sha, special_ethaddr, ETH_ALEN);
1389
1390 switch (htip & ~pData->netmask)
1391 {
1392 case CTL_DNS:
1393 case CTL_ALIAS:
1394 rah->ar_sha[5] = (uint8_t)(htip & ~pData->netmask);
1395 break;
1396 default:;
1397 }
1398
1399 memcpy(rah->ar_sip, ah->ar_tip, 4);
1400 memcpy(rah->ar_tha, ah->ar_sha, ETH_ALEN);
1401 memcpy(rah->ar_tip, ah->ar_sip, 4);
1402 if_encap(pData, ETH_P_ARP, mr);
1403 m_free(pData, m);
1404 }
1405 break;
1406 default:
1407 break;
1408 }
1409}
1410
1411void slirp_input(PNATState pData, const uint8_t *pkt, int pkt_len)
1412{
1413 struct mbuf *m;
1414 int proto;
1415 static bool fWarnedIpv6;
1416 struct ethhdr *eh = (struct ethhdr*)pkt;
1417
1418 Log2(("NAT: slirp_input %d\n", pkt_len));
1419 if (pkt_len < ETH_HLEN)
1420 {
1421 LogRel(("NAT: packet having size %d has been ingnored\n", pkt_len));
1422 return;
1423 }
1424 Log4(("NAT: in:%R[ether]->%R[ether]\n", &eh->h_source, &eh->h_dest));
1425#ifdef VBOX_WITHOUT_SLIRP_CLIENT_ETHER
1426 if (memcmp(eh->h_source, special_ethaddr, ETH_ALEN) == 0)
1427 {
1428 /* @todo vasily: add ether logging routine in debug.c */
1429 Log(("NAT: packet was addressed to other MAC\n"));
1430 RTMemFree((void *)pkt);
1431 return;
1432 }
1433#endif
1434
1435 m = m_get(pData);
1436 if (!m)
1437 {
1438 LogRel(("NAT: can't allocate new mbuf\n"));
1439 return;
1440 }
1441
1442 /* Note: we add to align the IP header */
1443
1444 if (M_FREEROOM(m) < pkt_len)
1445 m_inc(m, pkt_len);
1446
1447 m->m_len = pkt_len ;
1448 memcpy(m->m_data, pkt, pkt_len);
1449
1450 if (pData->port_forwarding_activated == 0)
1451 acivate_port_forwarding(pData, mtod(m, struct ethhdr *));
1452
1453 proto = ntohs(*(uint16_t *)(pkt + 12));
1454 switch(proto)
1455 {
1456 case ETH_P_ARP:
1457 arp_input(pData, m);
1458 break;
1459 case ETH_P_IP:
1460 /* Update time. Important if the network is very quiet, as otherwise
1461 * the first outgoing connection gets an incorrect timestamp. */
1462 updtime(pData);
1463 m_adj(m, ETH_HLEN);
1464 ip_input(pData, m);
1465 break;
1466 case ETH_P_IPV6:
1467 m_free(pData, m);
1468 if (!fWarnedIpv6)
1469 {
1470 LogRel(("NAT: IPv6 not supported\n"));
1471 fWarnedIpv6 = true;
1472 }
1473 break;
1474 default:
1475 Log(("NAT: Unsupported protocol %x\n", proto));
1476 m_free(pData, m);
1477 break;
1478 }
1479 RTMemFree((void *)pkt);
1480}
1481
1482/* output the IP packet to the ethernet device */
1483void if_encap(PNATState pData, uint16_t eth_proto, struct mbuf *m)
1484{
1485 struct ethhdr *eh;
1486 uint8_t *buf = RTMemAlloc(1600);
1487 STAM_PROFILE_START(&pData->StatIF_encap, a);
1488
1489 m->m_data -= if_maxlinkhdr;
1490 m->m_len += ETH_HLEN;
1491 eh = mtod(m, struct ethhdr *);
1492
1493 if(MBUF_HEAD(m) != m->m_data)
1494 {
1495 LogRel(("NAT: ethernet detects corruption of the packet"));
1496 AssertMsgFailed(("!!Ethernet frame corrupted!!"));
1497 }
1498
1499#ifndef VBOX_WITHOUT_SLIRP_CLIENT_ETHER
1500 memcpy(eh->h_dest, client_ethaddr, ETH_ALEN);
1501 memcpy(eh->h_source, special_ethaddr, ETH_ALEN - 1);
1502 /* XXX: not correct */
1503 eh->h_source[5] = CTL_ALIAS;
1504#else
1505 if (memcmp(eh->h_source, special_ethaddr, ETH_ALEN) != 0)
1506 {
1507 memcpy(eh->h_dest, eh->h_source, ETH_ALEN);
1508 memcpy(eh->h_source, special_ethaddr, ETH_ALEN);
1509 Assert(memcmp(eh->h_dest, special_ethaddr, ETH_ALEN) != 0);
1510 if (memcmp(eh->h_dest, zerro_ethaddr, ETH_ALEN) == 0)
1511 {
1512 /* don't do anything */
1513 goto done;
1514 }
1515 }
1516#endif
1517 eh->h_proto = htons(eth_proto);
1518 memcpy(buf, mtod(m, uint8_t *), m->m_len);
1519 slirp_output(pData->pvUser, NULL, buf, m->m_len);
1520done:
1521 STAM_PROFILE_STOP(&pData->StatIF_encap, a);
1522 m_free(pData, m);
1523}
1524
1525/**
1526 * Still we're using dhcp server leasing to map ether to IP
1527 * @todo see rt_lookup_in_cache
1528 */
1529static in_addr_t find_guest_ip(PNATState pData, uint8_t *eth_addr)
1530{
1531 int i;
1532 if (memcmp(eth_addr, zerro_ethaddr, ETH_ALEN) == 0
1533 || memcmp(eth_addr, broadcast_ethaddr, ETH_ALEN) == 0)
1534 goto done;
1535 for (i = 0; i < NB_ADDR; i++)
1536 {
1537 if ( bootp_clients[i].allocated
1538 && memcmp(bootp_clients[i].macaddr, eth_addr, ETH_ALEN) == 0)
1539 return bootp_clients[i].addr.s_addr;
1540 }
1541done:
1542 return INADDR_ANY;
1543}
1544
1545/**
1546 * We need check if we've activated port forwarding
1547 * for specific machine ... that of course relates to
1548 * service mode
1549 * @todo finish this for service case
1550 */
1551static void acivate_port_forwarding(PNATState pData, struct ethhdr *ethdr)
1552{
1553 struct port_forward_rule *rule = NULL;
1554
1555 pData->port_forwarding_activated = 1;
1556 /* check mac here */
1557 LIST_FOREACH(rule, &pData->port_forward_rule_head, list)
1558 {
1559 struct socket *so;
1560 struct alias_link *link;
1561 struct libalias *lib;
1562 int flags;
1563 struct sockaddr sa;
1564 struct sockaddr_in *psin;
1565 socklen_t socketlen;
1566 struct in_addr alias;
1567 int rc;
1568 in_addr_t guest_addr; /* need to understand if we already give address to guest */
1569
1570 if (rule->activated)
1571 continue; /*already activated */
1572#ifdef VBOX_WITH_NAT_SERVICE
1573 if (memcmp(rule->mac_address, ethdr->h_source, ETH_ALEN) != 0)
1574 continue; /*not right mac, @todo: it'd be better do the list port forwarding per mac */
1575 guest_addr = find_guest_ip(pData, ethdr->h_source);
1576#else
1577 if (memcmp(client_ethaddr, ethdr->h_source, ETH_ALEN) != 0)
1578 continue;
1579 guest_addr = find_guest_ip(pData, ethdr->h_source);
1580 Assert(rule->guest_addr.s_addr == guest_addr);
1581#endif
1582 if (guest_addr == INADDR_ANY)
1583 {
1584 /* the address wasn't granted */
1585 pData->port_forwarding_activated = 0;
1586 return;
1587 }
1588
1589 LogRel(("NAT: set redirect %s hp:%d gp:%d\n", (rule->proto == IPPROTO_UDP?"UDP":"TCP"),
1590 rule->host_port, rule->guest_port));
1591 if (rule->proto == IPPROTO_UDP)
1592 {
1593 so = udp_listen(pData, rule->bind_ip.s_addr, htons(rule->host_port), guest_addr,
1594 htons(rule->guest_port), 0);
1595 }
1596 else
1597 {
1598 so = solisten(pData, rule->bind_ip.s_addr, htons(rule->host_port), guest_addr,
1599 htons(rule->guest_port), 0);
1600 }
1601 if (so == NULL)
1602 {
1603 LogRel(("NAT: failed redirect %s hp:%d gp:%d\n", (rule->proto == IPPROTO_UDP?"UDP":"TCP"),
1604 rule->host_port, rule->guest_port));
1605 goto remove_port_forwarding;
1606 }
1607
1608 psin = (struct sockaddr_in *)&sa;
1609 psin->sin_family = AF_INET;
1610 psin->sin_port = 0;
1611 psin->sin_addr.s_addr = INADDR_ANY;
1612 socketlen = sizeof(struct sockaddr);
1613
1614 rc = getsockname(so->s, &sa, &socketlen);
1615 if (rc < 0 || sa.sa_family != AF_INET)
1616 {
1617 LogRel(("NAT: failed redirect %s hp:%d gp:%d\n", (rule->proto == IPPROTO_UDP?"UDP":"TCP"),
1618 rule->host_port, rule->guest_port));
1619 goto remove_port_forwarding;
1620 }
1621
1622 psin = (struct sockaddr_in *)&sa;
1623
1624 lib = LibAliasInit(pData, NULL);
1625 flags = LibAliasSetMode(lib, 0, 0);
1626 flags |= PKT_ALIAS_LOG; /* set logging */
1627 flags |= PKT_ALIAS_REVERSE; /* set logging */
1628 flags = LibAliasSetMode(lib, flags, ~0);
1629
1630 alias.s_addr = htonl(ntohl(guest_addr) | CTL_ALIAS);
1631 link = LibAliasRedirectPort(lib, psin->sin_addr, htons(rule->host_port),
1632 alias, htons(rule->guest_port),
1633 special_addr, -1, /* not very clear for now*/
1634 rule->proto);
1635 if (link == NULL)
1636 {
1637 LogRel(("NAT: failed redirect %s hp:%d gp:%d\n", (rule->proto == IPPROTO_UDP?"UDP":"TCP"),
1638 rule->host_port, rule->guest_port));
1639 goto remove_port_forwarding;
1640 }
1641 so->so_la = lib;
1642 rule->activated = 1;
1643 continue;
1644 remove_port_forwarding:
1645 LIST_REMOVE(rule, list);
1646 RTMemFree(rule);
1647 }
1648}
1649
1650/**
1651 * Changes in 3.1 instead of opening new socket do the following:
1652 * gain more information:
1653 * 1. bind IP
1654 * 2. host port
1655 * 3. guest port
1656 * 4. proto
1657 * 5. guest MAC address
1658 * the guest's MAC address is rather important for service, but we easily
1659 * could get it from VM configuration in DrvNAT or Service, the idea is activating
1660 * corresponding port-forwarding
1661 */
1662int slirp_redir(PNATState pData, int is_udp, struct in_addr host_addr, int host_port,
1663 struct in_addr guest_addr, int guest_port, const uint8_t *ethaddr)
1664{
1665 struct port_forward_rule *rule = NULL;
1666 Assert(memcmp(ethaddr, zerro_ethaddr, ETH_ALEN) == 0);
1667 rule = RTMemAllocZ(sizeof(struct port_forward_rule));
1668 if (rule == NULL)
1669 return 1;
1670 rule->proto = (is_udp ? IPPROTO_UDP : IPPROTO_TCP);
1671 rule->host_port = host_port;
1672 rule->guest_port = guest_port;
1673#ifndef VBOX_WITH_NAT_SERVICE
1674 rule->guest_addr.s_addr = guest_addr.s_addr;
1675#endif
1676 rule->bind_ip.s_addr = host_addr.s_addr;
1677 memcmp(rule->mac_address, ethaddr, ETH_ALEN);
1678 /* @todo add mac address */
1679 LIST_INSERT_HEAD(&pData->port_forward_rule_head, rule, list);
1680 return 0;
1681}
1682
1683int slirp_add_exec(PNATState pData, int do_pty, const char *args, int addr_low_byte,
1684 int guest_port)
1685{
1686 return add_exec(&exec_list, do_pty, (char *)args,
1687 addr_low_byte, htons(guest_port));
1688}
1689
1690void slirp_set_ethaddr(PNATState pData, const uint8_t *ethaddr)
1691{
1692#ifndef VBOX_WITH_NAT_SERVICE
1693 memcpy(client_ethaddr, ethaddr, ETH_ALEN);
1694#endif
1695}
1696
1697#if defined(RT_OS_WINDOWS)
1698HANDLE *slirp_get_events(PNATState pData)
1699{
1700 return pData->phEvents;
1701}
1702void slirp_register_external_event(PNATState pData, HANDLE hEvent, int index)
1703{
1704 pData->phEvents[index] = hEvent;
1705}
1706#endif
1707
1708unsigned int slirp_get_timeout_ms(PNATState pData)
1709{
1710 if (link_up)
1711 {
1712 if (time_fasttimo)
1713 return 2;
1714 if (do_slowtimo)
1715 return 500; /* see PR_SLOWHZ */
1716 }
1717 return 0;
1718}
1719
1720#ifndef RT_OS_WINDOWS
1721int slirp_get_nsock(PNATState pData)
1722{
1723 return pData->nsock;
1724}
1725#endif
1726
1727/*
1728 * this function called from NAT thread
1729 */
1730void slirp_post_sent(PNATState pData, void *pvArg)
1731{
1732 struct socket *so = 0;
1733 struct tcpcb *tp = 0;
1734 struct mbuf *m = (struct mbuf *)pvArg;
1735 m_free(pData, m);
1736}
1737#ifdef VBOX_WITH_SLIRP_MT
1738void slirp_process_queue(PNATState pData)
1739{
1740 RTReqProcess(pData->pReqQueue, RT_INDEFINITE_WAIT);
1741}
1742void *slirp_get_queue(PNATState pData)
1743{
1744 return pData->pReqQueue;
1745}
1746#endif
1747
1748void slirp_set_dhcp_TFTP_prefix(PNATState pData, const char *tftpPrefix)
1749{
1750 Log2(("tftp_prefix:%s\n", tftpPrefix));
1751 tftp_prefix = tftpPrefix;
1752}
1753
1754void slirp_set_dhcp_TFTP_bootfile(PNATState pData, const char *bootFile)
1755{
1756 Log2(("bootFile:%s\n", bootFile));
1757 bootp_filename = bootFile;
1758}
1759
1760void slirp_set_dhcp_next_server(PNATState pData, const char *next_server)
1761{
1762 Log2(("next_server:%s\n", next_server));
1763 if (next_server == NULL)
1764 pData->tftp_server.s_addr = htonl(ntohl(special_addr.s_addr) | CTL_TFTP);
1765 else
1766 inet_aton(next_server, &pData->tftp_server);
1767}
1768
1769int slirp_set_binding_address(PNATState pData, char *addr)
1770{
1771 if (addr == NULL || (inet_aton(addr, &pData->bindIP) == 0))
1772 {
1773 pData->bindIP.s_addr = INADDR_ANY;
1774 return 1;
1775 }
1776 return 0;
1777}
1778
1779void slirp_set_dhcp_dns_proxy(PNATState pData, bool fDNSProxy)
1780{
1781 Log2(("NAT: DNS proxy switched %s\n", (fDNSProxy ? "on" : "off")));
1782 pData->use_dns_proxy = fDNSProxy;
1783}
1784
1785#define CHECK_ARG(name, val, lim_min, lim_max) \
1786do { \
1787 if ((val) < (lim_min) || (val) > (lim_max)) \
1788 { \
1789 LogRel(("NAT: (" #name ":%d) has been ignored, " \
1790 "because out of range (%d, %d)\n", (val), (lim_min), (lim_max))); \
1791 return; \
1792 } \
1793 else \
1794 { \
1795 LogRel(("NAT: (" #name ":%d)\n", (val))); \
1796 } \
1797} while (0)
1798
1799/* don't allow user set less 8kB and more than 1M values */
1800#define _8K_1M_CHECK_ARG(name, val) CHECK_ARG(name, (val), 8, 1024)
1801void slirp_set_rcvbuf(PNATState pData, int kilobytes)
1802{
1803 _8K_1M_CHECK_ARG("SOCKET_RCVBUF", kilobytes);
1804 pData->socket_rcv = kilobytes;
1805}
1806void slirp_set_sndbuf(PNATState pData, int kilobytes)
1807{
1808 _8K_1M_CHECK_ARG("SOCKET_SNDBUF", kilobytes);
1809 pData->socket_snd = kilobytes * _1K;
1810}
1811void slirp_set_tcp_rcvspace(PNATState pData, int kilobytes)
1812{
1813 _8K_1M_CHECK_ARG("TCP_RCVSPACE", kilobytes);
1814 tcp_rcvspace = kilobytes * _1K;
1815}
1816void slirp_set_tcp_sndspace(PNATState pData, int kilobytes)
1817{
1818 _8K_1M_CHECK_ARG("TCP_SNDSPACE", kilobytes);
1819 tcp_sndspace = kilobytes * _1K;
1820}
1821
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette