VirtualBox

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

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

NAT: some dhcp clients happy to have at least " " domain name than to have nothing.

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