VirtualBox

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

最後變更 在這個檔案從23154是 23154,由 vboxsync 提交於 15 年 前

NAT: BSD mbuf

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

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