VirtualBox

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

Last change on this file since 21664 was 21631, checked in by vboxsync, 16 years ago

NAT: libalias's modules termination

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