VirtualBox

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

Last change on this file since 20716 was 20713, checked in by vboxsync, 16 years ago

DrvNAT,slirp: Even simpler.

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