VirtualBox

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

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

NAT:DNS freeing DNS server list

  • Property svn:eol-style set to native
File size: 39.7 KB
Line 
1#include "slirp.h"
2#ifdef RT_OS_OS2
3# include <paths.h>
4#endif
5
6#include <VBox/err.h>
7#include <VBox/pdmdrv.h>
8#include <iprt/assert.h>
9
10#ifdef VBOX_WITH_SLIRP_MT
11# define CONTINUE(label) goto loop_end_ ## label ## _mt
12/* @todo replace queue parameter with macrodinition */
13# define LOOP_LABEL(label, so, sonext) loop_end_ ## label ## _mt: \
14 SOCKET_UNLOCK(so); \
15 QSOCKET_LOCK(_X(queue_ ## label ## _label)); \
16 (so) = (sonext)
17#else
18#define CONTINUE(label) continue;
19# define LOOP_LABEL(label, so, sonext) /* empty*/
20#endif
21#if !defined(VBOX_WITH_SIMPLIFIED_SLIRP_SYNC) || !defined(RT_OS_WINDOWS)
22
23# define DO_ENGAGE_EVENT1(so, fdset, label) \
24 do { \
25 FD_SET((so)->s, (fdset)); \
26 UPD_NFDS((so)->s); \
27 } while(0)
28
29
30# define DO_ENGAGE_EVENT2(so, fdset1, fdset2, label) \
31 do { \
32 FD_SET((so)->s, (fdset1)); \
33 FD_SET((so)->s, (fdset2)); \
34 UPD_NFDS((so)->s); \
35 } while(0)
36
37# define DO_POLL_EVENTS(rc, error, so, events, label) do {} while (0)
38
39# define DO_CHECK_FD_SET(so, events, fdset) (FD_ISSET((so)->s, (fdset)))
40
41# define DO_WIN_CHECK_FD_SET(so, events, fdset ) 0 /* specific for Windows Winsock API */
42
43# ifndef RT_OS_WINDOWS
44# define ICMP_ENGAGE_EVENT(so, fdset) \
45 do { \
46 if (pData->icmp_socket.s != -1) \
47 DO_ENGAGE_EVENT1((so), (fdset), ICMP); \
48 } while (0)
49# else /* !RT_OS_WINDOWS */
50# define ICMP_ENGAGE_EVENT(so, fdset) do {} while(0)
51#endif /* RT_OS_WINDOWS */
52
53#else /* defined(VBOX_WITH_SIMPLIFIED_SLIRP_SYNC) && defined(RT_OS_WINDOWS) */
54
55/*
56 * On Windows, we will be notified by IcmpSendEcho2() when the response arrives.
57 * So no call to WSAEventSelect necessary.
58 */
59# define ICMP_ENGAGE_EVENT(so, fdset) do {} while(0)
60
61# define DO_ENGAGE_EVENT1(so, fdset1, label) \
62 do { \
63 rc = WSAEventSelect((so)->s, VBOX_SOCKET_EVENT, FD_ALL_EVENTS); \
64 if (rc == SOCKET_ERROR) \
65 { \
66 /* This should not happen */ \
67 error = WSAGetLastError(); \
68 LogRel(("WSAEventSelector (" #label ") error %d (so=%x, socket=%s, event=%x)\n", \
69 error, (so), (so)->s, VBOX_SOCKET_EVENT)); \
70 } \
71 } while(0); \
72 CONTINUE(label)
73
74# define DO_ENGAGE_EVENT2(so, fdset1, fdset2, label) \
75 DO_ENGAGE_EVENT1((so), (fdset1), label)
76
77# define DO_POLL_EVENTS(rc, error, so, events, label) \
78 (rc) = WSAEnumNetworkEvents((so)->s, VBOX_SOCKET_EVENT, (events)); \
79 if ((rc) == SOCKET_ERROR) \
80 { \
81 (error) = WSAGetLastError(); \
82 LogRel(("WSAEnumNetworkEvents " #label " error %d\n", (error))); \
83 CONTINUE(label); \
84 }
85
86# define acceptds_win FD_ACCEPT
87# define acceptds_win_bit FD_ACCEPT_BIT
88
89# define readfds_win FD_READ
90# define readfds_win_bit FD_READ_BIT
91
92# define writefds_win FD_WRITE
93# define writefds_win_bit FD_WRITE_BIT
94
95# define xfds_win FD_OOB
96# define xfds_win_bit FD_OOB_BIT
97
98# define DO_CHECK_FD_SET(so, events, fdset) \
99 (((events).lNetworkEvents & fdset ## _win) && ((events).iErrorCode[fdset ## _win_bit] == 0))
100
101# define DO_WIN_CHECK_FD_SET(so, events, fdset ) DO_CHECK_FD_SET((so), (events), fdset)
102
103#endif /* defined(VBOX_WITH_SIMPLIFIED_SLIRP_SYNC) && defined(RT_OS_WINDOWS) */
104
105#define TCP_ENGAGE_EVENT1(so, fdset) \
106 DO_ENGAGE_EVENT1((so), (fdset), tcp)
107
108#define TCP_ENGAGE_EVENT2(so, fdset1, fdset2) \
109 DO_ENGAGE_EVENT2((so), (fdset1), (fdset2), tcp)
110
111#define UDP_ENGAGE_EVENT(so, fdset) \
112 DO_ENGAGE_EVENT1((so), (fdset), udp)
113
114#define POLL_TCP_EVENTS(rc, error, so, events) \
115 DO_POLL_EVENTS((rc), (error), (so), (events), tcp)
116
117#define POLL_UDP_EVENTS(rc, error, so, events) \
118 DO_POLL_EVENTS((rc), (error), (so), (events), udp)
119
120#define CHECK_FD_SET(so, events, set) \
121 (DO_CHECK_FD_SET((so), (events), set))
122
123#define WIN_CHECK_FD_SET(so, events, set) \
124 (DO_WIN_CHECK_FD_SET((so), (events), set))
125
126/*
127 * Loging macros
128 */
129#if VBOX_WITH_DEBUG_NAT_SOCKETS
130# if defined(VBOX_WITH_SIMPLIFIED_SLIRP_SYNC) && defined(RT_OS_WINDOWS)
131# define DO_LOG_NAT_SOCK(so, proto, winevent, r_fdset, w_fdset, x_fdset) \
132 do { \
133 LogRel((" " #proto "%R[natsock] %R[natwinnetevents]\n", (so), (winevent))); \
134 } while (0)
135# else
136# define DO_LOG_NAT_SOCK(so, proto, winevent, r_fdset, w_fdset, x_fdset) \
137 do { \
138 LogRel((" " #proto " %R[natsock] %s %s %s\n", (so), FD_ISSET((so)->s, (r_fdset))?"READ":"",\
139 FD_ISSET((so)->s, (w_fdset))?"WRITE":"", FD_ISSET((so)->s, (x_fdset))?"OOB":"")); \
140 } while (0)
141# endif /* VBOX_WITH_DEBUG_NAT_SOCKETS */
142#else
143# define DO_LOG_NAT_SOCK(so, proto, winevent, r_fdset, w_fdset, x_fdset) do {} while (0)
144#endif /* !VBOX_WITH_DEBUG_NAT_SOCKETS */
145
146#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))
147
148static const uint8_t special_ethaddr[6] =
149{
150 0x52, 0x54, 0x00, 0x12, 0x35, 0x00
151};
152
153#ifdef RT_OS_WINDOWS
154
155static int get_dns_addr_domain(PNATState pData, bool fVerbose,
156 struct in_addr *pdns_addr,
157 const char **ppszDomain)
158{
159 int rc = 0;
160 FIXED_INFO *FixedInfo = NULL;
161 ULONG BufLen;
162 DWORD ret;
163 IP_ADDR_STRING *pIPAddr;
164 struct in_addr tmp_addr;
165
166 FixedInfo = (FIXED_INFO *)GlobalAlloc(GPTR, sizeof(FIXED_INFO));
167 BufLen = sizeof(FIXED_INFO);
168
169 /** @todo: this API returns all DNS servers, no matter whether the
170 * corresponding network adapter is disabled or not. Maybe replace
171 * this by GetAdapterAddresses(), which is XP/Vista only though. */
172 if (ERROR_BUFFER_OVERFLOW == GetNetworkParams(FixedInfo, &BufLen))
173 {
174 if (FixedInfo)
175 {
176 GlobalFree(FixedInfo);
177 FixedInfo = NULL;
178 }
179 FixedInfo = GlobalAlloc(GPTR, BufLen);
180 }
181
182 if ((ret = GetNetworkParams(FixedInfo, &BufLen)) != ERROR_SUCCESS)
183 {
184 Log(("GetNetworkParams failed. ret = %08x\n", (u_int)ret ));
185 if (FixedInfo)
186 {
187 GlobalFree(FixedInfo);
188 FixedInfo = NULL;
189 }
190 rc = -1;
191 goto get_dns_prefix;
192 }
193
194#ifndef VBOX_WITH_MULTI_DNS
195 pIPAddr = &(FixedInfo->DnsServerList);
196 inet_aton(pIPAddr->IpAddress.String, &tmp_addr);
197 Log(("nat: DNS Servers:\n"));
198 if (fVerbose || pdns_addr->s_addr != tmp_addr.s_addr)
199 LogRel(("NAT: DNS address: %s\n", pIPAddr->IpAddress.String));
200 *pdns_addr = tmp_addr;
201
202 pIPAddr = FixedInfo -> DnsServerList.Next;
203 while (pIPAddr)
204 {
205 if (fVerbose)
206 LogRel(("NAT: ignored DNS address: %s\n", pIPAddr ->IpAddress.String));
207 pIPAddr = pIPAddr ->Next;
208 }
209#else
210 /*localhost mask */
211 for (pIPAddr = &FixedInfo->DnsServerList; pIPAddr != NULL; pIPAddr = pIPAddr->Next)
212 {
213 struct dns_entry *da;
214 if(!inet_aton(pIPAddr->IpAddress.String, &tmp_addr))
215 continue;
216 da = RTMemAllocZ(sizeof (struct dns_entry));
217 if (da == NULL)
218 {
219 LogRel(("can't alloc memory for DNS entry\n"));
220 return -1;
221 }
222 /*check */
223 if ((da->de_addr.s_addr & htonl(IN_CLASSA_NET)) == ntohl(INADDR_LOOPBACK & IN_CLASSA_NET)) {
224 da->de_addr.s_addr = htonl(ntohl(special_addr.s_addr) | CTL_ALIAS);
225 }
226 LIST_INSERT_HEAD(&pData->dns_list_head, da, de_list);
227 }
228#endif
229 if (FixedInfo)
230 {
231 GlobalFree(FixedInfo);
232 FixedInfo = NULL;
233 }
234
235get_dns_prefix:
236 if (ppszDomain)
237 {
238 OSVERSIONINFO ver;
239 char szDnsDomain[256];
240 DWORD dwSize = sizeof(szDnsDomain);
241
242 *ppszDomain = NULL;
243 GetVersionEx(&ver);
244 if (ver.dwMajorVersion >= 5)
245 {
246 /* GetComputerNameEx exists in Windows versions starting with 2000. */
247 if (GetComputerNameEx(ComputerNameDnsDomain, szDnsDomain, &dwSize))
248 {
249 if (szDnsDomain[0])
250 {
251 /* Just non-empty strings are valid. */
252 *ppszDomain = RTStrDup(szDnsDomain);
253 if (pData->fPassDomain)
254 {
255 if (fVerbose)
256 LogRel(("NAT: passing domain name %s\n", szDnsDomain));
257 }
258 else
259 Log(("nat: ignoring domain %s\n", szDnsDomain));
260 }
261 }
262 else
263 Log(("nat: GetComputerNameEx failed (%d)\n", GetLastError()));
264 }
265 }
266 return rc;
267}
268
269#else
270
271static int get_dns_addr_domain(PNATState pData, bool fVerbose,
272 struct in_addr *pdns_addr,
273 const char **ppszDomain)
274{
275 char buff[512];
276 char buff2[256];
277 FILE *f;
278 int found = 0;
279 struct in_addr tmp_addr;
280
281#ifdef RT_OS_OS2
282 /* Try various locations. */
283 char *etc = getenv("ETC");
284 f = NULL;
285 if (etc)
286 {
287 snprintf(buff, sizeof(buff), "%s/RESOLV2", etc);
288 f = fopen(buff, "rt");
289 }
290 if (!f)
291 {
292 snprintf(buff, sizeof(buff), "%s/RESOLV2", _PATH_ETC);
293 f = fopen(buff, "rt");
294 }
295 if (!f)
296 {
297 snprintf(buff, sizeof(buff), "%s/resolv.conf", _PATH_ETC);
298 f = fopen(buff, "rt");
299 }
300#else
301 f = fopen("/etc/resolv.conf", "r");
302#endif
303 if (!f)
304 return -1;
305
306 if (ppszDomain)
307 *ppszDomain = NULL;
308 Log(("nat: DNS Servers:\n"));
309 while (fgets(buff, 512, f) != NULL)
310 {
311#ifdef VBOX_WITH_MULTI_DNS
312 struct dns_entry *da = NULL;
313#endif
314 if (sscanf(buff, "nameserver%*[ \t]%256s", buff2) == 1)
315 {
316 if (!inet_aton(buff2, &tmp_addr))
317 continue;
318#ifndef VBOX_WITH_MULTI_DNS
319 /* If it's the first one, set it to dns_addr */
320 if (!found)
321 {
322 if (fVerbose || pdns_addr->s_addr != tmp_addr.s_addr)
323 LogRel(("NAT: DNS address: %s\n", buff2));
324 *pdns_addr = tmp_addr;
325 }
326 else
327 {
328 if (fVerbose)
329 LogRel(("NAT: ignored DNS address: %s\n", buff2));
330 }
331#else
332 /*localhost mask */
333 da = RTMemAllocZ(sizeof (struct dns_entry));
334 if (da == NULL)
335 {
336 LogRel(("can't alloc memory for DNS entry\n"));
337 return -1;
338 }
339 /*check */
340 da->de_addr.s_addr = tmp_addr.s_addr;
341 if ((da->de_addr.s_addr & htonl(IN_CLASSA_NET)) == ntohl(INADDR_LOOPBACK & IN_CLASSA_NET)) {
342 da->de_addr.s_addr = htonl(ntohl(special_addr.s_addr) | CTL_ALIAS);
343 }
344 LIST_INSERT_HEAD(&pData->dns_list_head, da, de_list);
345#endif
346 found++;
347 }
348 if ( ppszDomain
349 && (!strncmp(buff, "domain", 6) || !strncmp(buff, "search", 6)))
350 {
351 /* Domain name/search list present. Pick first entry */
352 if (*ppszDomain == NULL)
353 {
354 char *tok;
355 char *saveptr;
356 tok = strtok_r(&buff[6], " \t\n", &saveptr);
357 if (tok)
358 {
359 *ppszDomain = RTStrDup(tok);
360 if (pData->fPassDomain)
361 {
362 if (fVerbose)
363 LogRel(("NAT: passing domain name %s\n", tok));
364 }
365 else
366 Log(("nat: ignoring domain %s\n", tok));
367 }
368 }
369 }
370 }
371 fclose(f);
372 if (!found)
373 return -1;
374 return 0;
375}
376
377#endif
378
379int get_dns_addr(PNATState pData, struct in_addr *pdns_addr)
380{
381 return get_dns_addr_domain(pData, false, pdns_addr, NULL);
382}
383
384int slirp_init(PNATState *ppData, const char *pszNetAddr, uint32_t u32Netmask,
385 bool fPassDomain, const char *pszTFTPPrefix,
386 const char *pszBootFile, void *pvUser)
387{
388 int fNATfailed = 0;
389 PNATState pData = RTMemAlloc(sizeof(NATState));
390 *ppData = pData;
391 if (!pData)
392 return VERR_NO_MEMORY;
393 if (u32Netmask & 0x1f)
394 /* CTL is x.x.x.15, bootp passes up to 16 IPs (15..31) */
395 return VERR_INVALID_PARAMETER;
396 memset(pData, '\0', sizeof(NATState));
397 pData->fPassDomain = fPassDomain;
398 pData->pvUser = pvUser;
399 tftp_prefix = pszTFTPPrefix;
400 bootp_filename = pszBootFile;
401 pData->netmask = u32Netmask;
402
403#ifdef RT_OS_WINDOWS
404 {
405 WSADATA Data;
406 WSAStartup(MAKEWORD(2,0), &Data);
407 }
408# if defined(VBOX_WITH_SIMPLIFIED_SLIRP_SYNC)
409 pData->phEvents[VBOX_SOCKET_EVENT_INDEX] = CreateEvent(NULL, FALSE, FALSE, NULL);
410# endif
411#endif
412
413 link_up = 1;
414
415 debug_init();
416 if_init(pData);
417 ip_init(pData);
418 icmp_init(pData);
419
420 /* Initialise mbufs *after* setting the MTU */
421 m_init(pData);
422
423 inet_aton(pszNetAddr, &special_addr);
424 alias_addr.s_addr = special_addr.s_addr | htonl(CTL_ALIAS);
425 /* @todo: add ability to configure this staff */
426 pData->tftp_server.s_addr = htonl(ntohl(special_addr.s_addr) | CTL_TFTP);
427
428 /* set default addresses */
429 inet_aton("127.0.0.1", &loopback_addr);
430#ifndef VBOX_WITH_MULTI_DNS
431 inet_aton("127.0.0.1", &dns_addr);
432
433 if (get_dns_addr_domain(pData, true, &dns_addr, &pData->pszDomain) < 0)
434#else
435 LIST_INIT(&pData->dns_list_head);
436 if (get_dns_addr_domain(pData, true, NULL, &pData->pszDomain) < 0)
437#endif
438 fNATfailed = 1;
439
440 getouraddr(pData);
441 return fNATfailed ? VINF_NAT_DNS : VINF_SUCCESS;
442}
443
444/**
445 * Statistics counters.
446 */
447void slirp_register_timers(PNATState pData, PPDMDRVINS pDrvIns)
448{
449#ifdef VBOX_WITH_STATISTICS
450 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatFill, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS,
451 STAMUNIT_TICKS_PER_CALL, "Profiling slirp fills", "/Drivers/NAT%d/Fill", pDrvIns->iInstance);
452 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatPoll, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS,
453 STAMUNIT_TICKS_PER_CALL, "Profiling slirp polls", "/Drivers/NAT%d/Poll", pDrvIns->iInstance);
454 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatFastTimer, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS,
455 STAMUNIT_TICKS_PER_CALL, "Profiling slirp fast timer", "/Drivers/NAT%d/TimerFast", pDrvIns->iInstance);
456 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatSlowTimer, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS,
457 STAMUNIT_TICKS_PER_CALL, "Profiling slirp slow timer", "/Drivers/NAT%d/TimerSlow", pDrvIns->iInstance);
458 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatTCP, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS,
459 STAMUNIT_COUNT, "TCP sockets", "/Drivers/NAT%d/SockTCP", pDrvIns->iInstance);
460 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatTCPHot, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS,
461 STAMUNIT_COUNT, "TCP sockets active", "/Drivers/NAT%d/SockTCPHot", pDrvIns->iInstance);
462 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatUDP, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS,
463 STAMUNIT_COUNT, "UDP sockets", "/Drivers/NAT%d/SockUDP", pDrvIns->iInstance);
464 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatUDPHot, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS,
465 STAMUNIT_COUNT, "UDP sockets active", "/Drivers/NAT%d/SockUDPHot", pDrvIns->iInstance);
466#endif /* VBOX_WITH_STATISTICS */
467}
468
469/**
470 * Marks the link as up, making it possible to establish new connections.
471 */
472void slirp_link_up(PNATState pData)
473{
474 link_up = 1;
475}
476
477/**
478 * Marks the link as down and cleans up the current connections.
479 */
480void slirp_link_down(PNATState pData)
481{
482 struct socket *so;
483
484 while ((so = tcb.so_next) != &tcb)
485 {
486 if (so->so_state & SS_NOFDREF || so->s == -1)
487 sofree(pData, so);
488 else
489 tcp_drop(pData, sototcpcb(so), 0);
490 }
491
492 while ((so = udb.so_next) != &udb)
493 udp_detach(pData, so);
494
495 link_up = 0;
496}
497
498/**
499 * Terminates the slirp component.
500 */
501void slirp_term(PNATState pData)
502{
503#ifdef VBOX_WITH_MULTI_DNS
504 struct dns_entry *de = NULL;
505#endif
506 if (pData->pszDomain)
507 RTStrFree((char *)(void *)pData->pszDomain);
508
509#ifdef RT_OS_WINDOWS
510 pData->pfIcmpCloseHandle(pData->icmp_socket.sh);
511 FreeLibrary(pData->hmIcmpLibrary);
512 RTMemFree(pData->pvIcmpBuffer);
513# else
514 closesocket(pData->icmp_socket.s);
515#endif
516
517 slirp_link_down(pData);
518#ifdef VBOX_WITH_MULTI_DNS
519 while(!LIST_EMPTY(&pData->dns_list_head)) {
520 de = LIST_FIRST(&pData->dns_list_head);
521 LIST_REMOVE(de, de_list);
522 RTMemFree(de);
523 }
524#endif
525#ifdef RT_OS_WINDOWS
526 WSACleanup();
527#endif
528#ifdef LOG_ENABLED
529 Log(("\n"
530 "NAT statistics\n"
531 "--------------\n"
532 "\n"));
533 ipstats(pData);
534 tcpstats(pData);
535 udpstats(pData);
536 icmpstats(pData);
537 mbufstats(pData);
538 sockstats(pData);
539 Log(("\n"
540 "\n"
541 "\n"));
542#endif
543 RTMemFree(pData);
544}
545
546
547#define CONN_CANFSEND(so) (((so)->so_state & (SS_FCANTSENDMORE|SS_ISFCONNECTED)) == SS_ISFCONNECTED)
548#define CONN_CANFRCV(so) (((so)->so_state & (SS_FCANTRCVMORE|SS_ISFCONNECTED)) == SS_ISFCONNECTED)
549#define UPD_NFDS(x) if (nfds < (x)) nfds = (x)
550
551/*
552 * curtime kept to an accuracy of 1ms
553 */
554#ifdef RT_OS_WINDOWS
555static void updtime(PNATState pData)
556{
557 struct _timeb tb;
558
559 _ftime(&tb);
560 curtime = (u_int)tb.time * (u_int)1000;
561 curtime += (u_int)tb.millitm;
562}
563#else
564static void updtime(PNATState pData)
565{
566 gettimeofday(&tt, 0);
567
568 curtime = (u_int)tt.tv_sec * (u_int)1000;
569 curtime += (u_int)tt.tv_usec / (u_int)1000;
570
571 if ((tt.tv_usec % 1000) >= 500)
572 curtime++;
573}
574#endif
575
576void slirp_select_fill(PNATState pData, int *pnfds,
577 fd_set *readfds, fd_set *writefds, fd_set *xfds)
578{
579 struct socket *so, *so_next;
580 int nfds;
581#if defined(VBOX_WITH_SIMPLIFIED_SLIRP_SYNC) && defined(RT_OS_WINDOWS)
582 int rc;
583 int error;
584#endif
585 int i;
586
587 STAM_PROFILE_START(&pData->StatFill, a);
588
589 nfds = *pnfds;
590
591 /*
592 * First, TCP sockets
593 */
594 do_slowtimo = 0;
595 if (link_up)
596 {
597 /*
598 * *_slowtimo needs calling if there are IP fragments
599 * in the fragment queue, or there are TCP connections active
600 */
601 /* XXX:
602 * triggering of fragment expiration should be the same but use new macroses
603 */
604 do_slowtimo = (tcb.so_next != &tcb);
605 if (!do_slowtimo)
606 {
607 for (i = 0; i < IPREASS_NHASH; i++)
608 {
609 if (!TAILQ_EMPTY(&ipq[i]))
610 {
611 do_slowtimo = 1;
612 break;
613 }
614 }
615 }
616 ICMP_ENGAGE_EVENT(&pData->icmp_socket, readfds);
617
618 STAM_COUNTER_RESET(&pData->StatTCP);
619 STAM_COUNTER_RESET(&pData->StatTCPHot);
620
621 QSOCKET_FOREACH(so, so_next, tcp)
622 /* { */
623 STAM_COUNTER_INC(&pData->StatTCP);
624
625 /*
626 * See if we need a tcp_fasttimo
627 */
628 if (time_fasttimo == 0 && so->so_tcpcb->t_flags & TF_DELACK)
629 time_fasttimo = curtime; /* Flag when we want a fasttimo */
630
631 /*
632 * NOFDREF can include still connecting to local-host,
633 * newly socreated() sockets etc. Don't want to select these.
634 */
635 if (so->so_state & SS_NOFDREF || so->s == -1)
636 CONTINUE(tcp);
637
638 /*
639 * Set for reading sockets which are accepting
640 */
641 if (so->so_state & SS_FACCEPTCONN)
642 {
643 STAM_COUNTER_INC(&pData->StatTCPHot);
644 TCP_ENGAGE_EVENT1(so, readfds);
645 CONTINUE(tcp);
646 }
647
648 /*
649 * Set for writing sockets which are connecting
650 */
651 if (so->so_state & SS_ISFCONNECTING)
652 {
653 Log2(("connecting %R[natsock] engaged\n",so));
654 STAM_COUNTER_INC(&pData->StatTCPHot);
655 TCP_ENGAGE_EVENT1(so, writefds);
656 }
657
658 /*
659 * Set for writing if we are connected, can send more, and
660 * we have something to send
661 */
662 if (CONN_CANFSEND(so) && so->so_rcv.sb_cc)
663 {
664 STAM_COUNTER_INC(&pData->StatTCPHot);
665 TCP_ENGAGE_EVENT1(so, writefds);
666 }
667
668 /*
669 * Set for reading (and urgent data) if we are connected, can
670 * receive more, and we have room for it XXX /2 ?
671 */
672 if (CONN_CANFRCV(so) && (so->so_snd.sb_cc < (so->so_snd.sb_datalen/2)))
673 {
674 STAM_COUNTER_INC(&pData->StatTCPHot);
675 TCP_ENGAGE_EVENT2(so, readfds, xfds);
676 }
677 LOOP_LABEL(tcp, so, so_next);
678 }
679
680 /*
681 * UDP sockets
682 */
683 STAM_COUNTER_RESET(&pData->StatUDP);
684 STAM_COUNTER_RESET(&pData->StatUDPHot);
685
686 QSOCKET_FOREACH(so, so_next, udp)
687 /* { */
688 so_next = so->so_next;
689
690 STAM_COUNTER_INC(&pData->StatUDP);
691
692 /*
693 * See if it's timed out
694 */
695 if (so->so_expire)
696 {
697 if (so->so_expire <= curtime)
698 {
699 udp_detach(pData, so);
700 CONTINUE(udp);
701 }
702 else
703 do_slowtimo = 1; /* Let socket expire */
704 }
705
706 /*
707 * When UDP packets are received from over the link, they're
708 * sendto()'d straight away, so no need for setting for writing
709 * Limit the number of packets queued by this session to 4.
710 * Note that even though we try and limit this to 4 packets,
711 * the session could have more queued if the packets needed
712 * to be fragmented.
713 *
714 * (XXX <= 4 ?)
715 */
716 if ((so->so_state & SS_ISFCONNECTED) && so->so_queued <= 4)
717 {
718 STAM_COUNTER_INC(&pData->StatUDPHot);
719 UDP_ENGAGE_EVENT(so, readfds);
720 }
721 LOOP_LABEL(udp, so, so_next);
722 }
723
724 }
725
726#if !defined(VBOX_WITH_SIMPLIFIED_SLIRP_SYNC) || !defined(RT_OS_WINDOWS)
727 *pnfds = nfds;
728#else
729 *pnfds = VBOX_EVENT_COUNT;
730#endif
731
732 STAM_PROFILE_STOP(&pData->StatFill, a);
733}
734
735#if defined(VBOX_WITH_SIMPLIFIED_SLIRP_SYNC) && defined(RT_OS_WINDOWS)
736void slirp_select_poll(PNATState pData, int fTimeout, int fIcmp)
737#else
738void slirp_select_poll(PNATState pData, fd_set *readfds, fd_set *writefds, fd_set *xfds)
739#endif
740{
741 struct socket *so, *so_next;
742 int ret;
743#if defined(VBOX_WITH_SIMPLIFIED_SLIRP_SYNC) && defined(RT_OS_WINDOWS)
744 WSANETWORKEVENTS NetworkEvents;
745 int rc;
746 int error;
747#endif
748
749 STAM_PROFILE_START(&pData->StatPoll, a);
750
751 /* Update time */
752 updtime(pData);
753
754 /*
755 * See if anything has timed out
756 */
757 if (link_up)
758 {
759 if (time_fasttimo && ((curtime - time_fasttimo) >= 2))
760 {
761 STAM_PROFILE_START(&pData->StatFastTimer, a);
762 tcp_fasttimo(pData);
763 time_fasttimo = 0;
764 STAM_PROFILE_STOP(&pData->StatFastTimer, a);
765 }
766 if (do_slowtimo && ((curtime - last_slowtimo) >= 499))
767 {
768 STAM_PROFILE_START(&pData->StatSlowTimer, a);
769 ip_slowtimo(pData);
770 tcp_slowtimo(pData);
771 last_slowtimo = curtime;
772 STAM_PROFILE_STOP(&pData->StatSlowTimer, a);
773 }
774 }
775#if defined(VBOX_WITH_SIMPLIFIED_SLIRP_SYNC) && defined(RT_OS_WINDOWS)
776 if (fTimeout)
777 return; /* only timer update */
778#endif
779
780 /*
781 * Check sockets
782 */
783 if (link_up)
784 {
785#if defined(RT_OS_WINDOWS)
786 /*XXX: before renaming please make see define
787 * fIcmp in slirp_state.h
788 */
789 if (fIcmp)
790 sorecvfrom(pData, &pData->icmp_socket);
791#else
792 if (pData->icmp_socket.s != -1 && FD_ISSET(pData->icmp_socket.s, readfds))
793 sorecvfrom(pData, &pData->icmp_socket);
794#endif
795 /*
796 * Check TCP sockets
797 */
798 for (so = tcb.so_next; so != &tcb; so = so_next)
799 {
800 so_next = so->so_next;
801
802 /*
803 * FD_ISSET is meaningless on these sockets
804 * (and they can crash the program)
805 */
806 if (so->so_state & SS_NOFDREF || so->s == -1)
807 CONTINUE(tcp);
808
809 POLL_TCP_EVENTS(rc, error, so, &NetworkEvents);
810
811 LOG_NAT_SOCK(so, TCP, &NetworkEvents, readfds, writefds, xfds);
812
813 /*
814 * Check for URG data
815 * This will soread as well, so no need to
816 * test for readfds below if this succeeds
817 */
818
819 /* out-of-band data */
820 if (CHECK_FD_SET(so, NetworkEvents, xfds))
821 {
822 sorecvoob(pData, so);
823 }
824
825 /*
826 * Check sockets for reading
827 */
828 else if ( CHECK_FD_SET(so, NetworkEvents, readfds)
829 || WIN_CHECK_FD_SET(so, NetworkEvents, acceptds))
830 {
831 /*
832 * Check for incoming connections
833 */
834 if (so->so_state & SS_FACCEPTCONN)
835 {
836 tcp_connect(pData, so);
837#if defined(VBOX_WITH_SIMPLIFIED_SLIRP_SYNC) && defined(RT_OS_WINDOWS)
838 if (!(NetworkEvents.lNetworkEvents & FD_CLOSE))
839#endif
840 CONTINUE(tcp);
841 }
842
843 ret = soread(pData, so, /*fCloseIfNothingRead=*/false);
844 /* Output it if we read something */
845 if (ret > 0)
846 tcp_output(pData, sototcpcb(so));
847 }
848
849#if defined(VBOX_WITH_SIMPLIFIED_SLIRP_SYNC) && defined(RT_OS_WINDOWS)
850 /*
851 * Check for FD_CLOSE events.
852 */
853 if (NetworkEvents.lNetworkEvents & FD_CLOSE)
854 {
855 /*
856 * drain the socket
857 */
858 for (;;)
859 {
860 ret = soread(pData, so, /*fCloseIfNothingRead=*/true);
861 if (ret > 0)
862 tcp_output(pData, sototcpcb(so));
863 else
864 break;
865 }
866 }
867#endif
868
869 /*
870 * Check sockets for writing
871 */
872 if (CHECK_FD_SET(so, NetworkEvents, writefds))
873 {
874 /*
875 * Check for non-blocking, still-connecting sockets
876 */
877 if (so->so_state & SS_ISFCONNECTING)
878 {
879 Log2(("connecting %R[natsock] catched\n", so));
880 /* Connected */
881 so->so_state &= ~SS_ISFCONNECTING;
882
883 /*
884 * This should be probably guarded by PROBE_CONN too. Anyway,
885 * we disable it on OS/2 because the below send call returns
886 * EFAULT which causes the opened TCP socket to close right
887 * after it has been opened and connected.
888 */
889#ifndef RT_OS_OS2
890 ret = send(so->s, (const char *)&ret, 0, 0);
891 if (ret < 0)
892 {
893 /* XXXXX Must fix, zero bytes is a NOP */
894 if ( errno == EAGAIN
895 || errno == EWOULDBLOCK
896 || errno == EINPROGRESS
897 || errno == ENOTCONN)
898 CONTINUE(tcp);
899
900 /* else failed */
901 so->so_state = SS_NOFDREF;
902 }
903 /* else so->so_state &= ~SS_ISFCONNECTING; */
904#endif
905
906 /*
907 * Continue tcp_input
908 */
909 tcp_input(pData, (struct mbuf *)NULL, sizeof(struct ip), so);
910 /* continue; */
911 }
912 else
913 ret = sowrite(pData, so);
914 /*
915 * XXX If we wrote something (a lot), there could be the need
916 * for a window update. In the worst case, the remote will send
917 * a window probe to get things going again.
918 */
919 }
920
921 /*
922 * Probe a still-connecting, non-blocking socket
923 * to check if it's still alive
924 */
925#ifdef PROBE_CONN
926 if (so->so_state & SS_ISFCONNECTING)
927 {
928 ret = recv(so->s, (char *)&ret, 0, 0);
929
930 if (ret < 0)
931 {
932 /* XXX */
933 if ( errno == EAGAIN
934 || errno == EWOULDBLOCK
935 || errno == EINPROGRESS
936 || errno == ENOTCONN)
937 {
938 CONTINUE(tcp); /* Still connecting, continue */
939 }
940
941 /* else failed */
942 so->so_state = SS_NOFDREF;
943
944 /* tcp_input will take care of it */
945 }
946 else
947 {
948 ret = send(so->s, &ret, 0, 0);
949 if (ret < 0)
950 {
951 /* XXX */
952 if ( errno == EAGAIN
953 || errno == EWOULDBLOCK
954 || errno == EINPROGRESS
955 || errno == ENOTCONN)
956 {
957 CONTINUE(tcp);
958 }
959 /* else failed */
960 so->so_state = SS_NOFDREF;
961 }
962 else
963 so->so_state &= ~SS_ISFCONNECTING;
964
965 }
966 tcp_input((struct mbuf *)NULL, sizeof(struct ip),so);
967 } /* SS_ISFCONNECTING */
968#endif
969 LOOP_LABEL(tcp, so, so_next);
970 }
971
972 /*
973 * Now UDP sockets.
974 * Incoming packets are sent straight away, they're not buffered.
975 * Incoming UDP data isn't buffered either.
976 */
977 for (so = udb.so_next; so != &udb; so = so_next)
978 {
979 so_next = so->so_next;
980
981 POLL_UDP_EVENTS(rc, error, so, &NetworkEvents);
982
983 LOG_NAT_SOCK(so, UDP, &NetworkEvents, readfds, writefds, xfds);
984
985 if (so->s != -1 && CHECK_FD_SET(so, NetworkEvents, readfds))
986 {
987 sorecvfrom(pData, so);
988 }
989 LOOP_LABEL(udp, so, so_next);
990 }
991
992 }
993
994#ifndef VBOX_WITH_SLIRP_MT
995 /*
996 * See if we can start outputting
997 */
998 if (if_queued && link_up)
999 if_start(pData);
1000#endif
1001
1002 STAM_PROFILE_STOP(&pData->StatPoll, a);
1003}
1004
1005#define ETH_ALEN 6
1006#define ETH_HLEN 14
1007
1008#define ARPOP_REQUEST 1 /* ARP request */
1009#define ARPOP_REPLY 2 /* ARP reply */
1010
1011struct ethhdr
1012{
1013 unsigned char h_dest[ETH_ALEN]; /* destination eth addr */
1014 unsigned char h_source[ETH_ALEN]; /* source ether addr */
1015 unsigned short h_proto; /* packet type ID field */
1016};
1017
1018struct arphdr
1019{
1020 unsigned short ar_hrd; /* format of hardware address */
1021 unsigned short ar_pro; /* format of protocol address */
1022 unsigned char ar_hln; /* length of hardware address */
1023 unsigned char ar_pln; /* length of protocol address */
1024 unsigned short ar_op; /* ARP opcode (command) */
1025
1026 /*
1027 * Ethernet looks like this : This bit is variable sized however...
1028 */
1029 unsigned char ar_sha[ETH_ALEN]; /* sender hardware address */
1030 unsigned char ar_sip[4]; /* sender IP address */
1031 unsigned char ar_tha[ETH_ALEN]; /* target hardware address */
1032 unsigned char ar_tip[4]; /* target IP address */
1033};
1034
1035static
1036#ifdef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
1037void arp_input(PNATState pData, struct mbuf *m)
1038#else
1039void arp_input(PNATState pData, const uint8_t *pkt, int pkt_len)
1040#endif
1041{
1042 struct ethhdr *eh;
1043 struct ethhdr *reh;
1044 struct arphdr *ah;
1045 struct arphdr *rah;
1046 int ar_op;
1047 struct ex_list *ex_ptr;
1048 uint32_t htip;
1049#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
1050 uint8_t arp_reply[sizeof(struct arphdr) + ETH_HLEN];
1051 eh = (struct ethhdr *)pkt;
1052#else
1053 struct mbuf *mr;
1054 eh = mtod(m, struct ethhdr *);
1055#endif
1056 ah = (struct arphdr *)&eh[1];
1057 htip = ntohl(*(uint32_t*)ah->ar_tip);
1058
1059#ifdef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
1060 mr = m_get(pData);
1061 mr->m_data += if_maxlinkhdr;
1062 mr->m_len = sizeof(struct arphdr);
1063 rah = mtod(mr, struct arphdr *);
1064#else
1065 reh = (struct ethhdr *)arp_reply;
1066 rah = (struct arphdr *)&reh[1];
1067#endif
1068
1069 ar_op = ntohs(ah->ar_op);
1070 switch(ar_op)
1071 {
1072 case ARPOP_REQUEST:
1073 if ((htip & pData->netmask) == ntohl(special_addr.s_addr))
1074 {
1075 if ( CTL_CHECK(htip,CTL_DNS)
1076 || CTL_CHECK(htip, CTL_ALIAS)
1077 || CTL_CHECK(htip, CTL_TFTP))
1078 goto arp_ok;
1079 for (ex_ptr = exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next)
1080 {
1081 if ((htip & ~pData->netmask) == ex_ptr->ex_addr)
1082 goto arp_ok;
1083 }
1084 return;
1085 arp_ok:
1086
1087#ifndef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
1088 memcpy(reh->h_dest, eh->h_source, ETH_ALEN);
1089 memcpy(reh->h_source, &special_addr, ETH_ALEN);
1090 reh->h_source[5] = ah->ar_tip[3];
1091 reh->h_proto = htons(ETH_P_ARP);
1092#endif
1093 rah->ar_hrd = htons(1);
1094 rah->ar_pro = htons(ETH_P_IP);
1095 rah->ar_hln = ETH_ALEN;
1096 rah->ar_pln = 4;
1097 rah->ar_op = htons(ARPOP_REPLY);
1098 memcpy(rah->ar_sha, special_ethaddr, ETH_ALEN);
1099
1100 switch (htip & ~pData->netmask)
1101 {
1102 case CTL_DNS:
1103 case CTL_ALIAS:
1104 rah->ar_sha[5] = (uint8_t)(htip & ~pData->netmask);
1105 break;
1106 default:;
1107 }
1108
1109 memcpy(rah->ar_sip, ah->ar_tip, 4);
1110 memcpy(rah->ar_tha, ah->ar_sha, ETH_ALEN);
1111 memcpy(rah->ar_tip, ah->ar_sip, 4);
1112#ifdef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
1113 if_encap(pData, ETH_P_ARP, mr);
1114 m_free(pData, m);
1115#else
1116 slirp_output(pData->pvUser, arp_reply, sizeof(arp_reply));
1117#endif
1118 }
1119 break;
1120 default:
1121 break;
1122 }
1123}
1124
1125void slirp_input(PNATState pData, const uint8_t *pkt, int pkt_len)
1126{
1127 struct mbuf *m;
1128 int proto;
1129 static bool fWarnedIpv6;
1130
1131 if (pkt_len < ETH_HLEN)
1132 {
1133 LogRel(("NAT: packet having size %d has been ingnored\n", pkt_len));
1134 return;
1135 }
1136
1137 m = m_get(pData);
1138 if (!m)
1139 {
1140 LogRel(("can't allocate new mbuf\n"));
1141 return;
1142 }
1143
1144 /* Note: we add to align the IP header */
1145
1146 if (M_FREEROOM(m) < pkt_len)
1147 m_inc(m, pkt_len);
1148
1149 m->m_len = pkt_len ;
1150 memcpy(m->m_data, pkt, pkt_len);
1151
1152 proto = ntohs(*(uint16_t *)(pkt + 12));
1153 switch(proto)
1154 {
1155 case ETH_P_ARP:
1156#ifdef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
1157 arp_input(pData, m);
1158#else
1159 arp_input(pData, pkt, pkt_len);
1160 m_free(pData, m);
1161#endif
1162 break;
1163 case ETH_P_IP:
1164 /* Update time. Important if the network is very quiet, as otherwise
1165 * the first outgoing connection gets an incorrect timestamp. */
1166 updtime(pData);
1167 m->m_data += ETH_HLEN;
1168 m->m_len -= ETH_HLEN;
1169 ip_input(pData, m);
1170 break;
1171 case ETH_P_IPV6:
1172 m_free(pData, m);
1173 if (!fWarnedIpv6)
1174 {
1175 LogRel(("NAT: IPv6 not supported\n"));
1176 fWarnedIpv6 = true;
1177 }
1178 break;
1179 default:
1180 LogRel(("NAT: Unsupported protocol %x\n", proto));
1181 m_free(pData, m);
1182 break;
1183 }
1184}
1185
1186/* output the IP packet to the ethernet device */
1187#ifdef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
1188void if_encap(PNATState pData, uint16_t eth_proto, struct mbuf *m)
1189#else
1190void if_encap(PNATState pData, uint8_t *ip_data, int ip_data_len)
1191#endif
1192{
1193#ifdef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
1194 struct ethhdr *eh;
1195 uint8_t *buf = RTMemAlloc(1600);
1196 m->m_data -= if_maxlinkhdr;
1197 m->m_len += ETH_HLEN;
1198 eh = mtod(m, struct ethhdr *);
1199#else
1200 uint8_t buf[1600];
1201 struct ethhdr *eh = (struct ethhdr *)buf;
1202
1203 if (ip_data_len + ETH_HLEN > sizeof(buf))
1204 return;
1205
1206 memcpy(buf + sizeof(struct ethhdr), ip_data, ip_data_len);
1207#endif
1208
1209
1210 memcpy(eh->h_dest, client_ethaddr, ETH_ALEN);
1211 memcpy(eh->h_source, special_ethaddr, ETH_ALEN - 1);
1212 /* XXX: not correct */
1213 eh->h_source[5] = CTL_ALIAS;
1214#ifdef VBOX_WITH_SIMPLIFIED_SLIRP_SYNC
1215 eh->h_proto = htons(eth_proto);
1216#if 0
1217 slirp_output(pData->pvUser, m, mtod(m, uint8_t *), m->m_len);
1218#else
1219 memcpy(buf, mtod(m, uint8_t *), m->m_len);
1220 slirp_output(pData->pvUser, NULL, buf, m->m_len);
1221 m_free(pData, m);
1222#endif
1223#else
1224 eh->h_proto = htons(ETH_P_IP);
1225 slirp_output(pData->pvUser, buf, ip_data_len + ETH_HLEN);
1226#endif
1227}
1228
1229int slirp_redir(PNATState pData, int is_udp, int host_port,
1230 struct in_addr guest_addr, int guest_port)
1231{
1232 if (is_udp)
1233 {
1234 if (!udp_listen(pData, htons(host_port), guest_addr.s_addr,
1235 htons(guest_port), 0))
1236 return -1;
1237 }
1238 else
1239 {
1240 if (!solisten(pData, htons(host_port), guest_addr.s_addr,
1241 htons(guest_port), 0))
1242 return -1;
1243 }
1244 return 0;
1245}
1246
1247int slirp_add_exec(PNATState pData, int do_pty, const char *args, int addr_low_byte,
1248 int guest_port)
1249{
1250 return add_exec(&exec_list, do_pty, (char *)args,
1251 addr_low_byte, htons(guest_port));
1252}
1253
1254void slirp_set_ethaddr(PNATState pData, const uint8_t *ethaddr)
1255{
1256 memcpy(client_ethaddr, ethaddr, ETH_ALEN);
1257}
1258
1259#if defined(VBOX_WITH_SIMPLIFIED_SLIRP_SYNC) && defined(RT_OS_WINDOWS)
1260HANDLE *slirp_get_events(PNATState pData)
1261{
1262 return pData->phEvents;
1263}
1264void slirp_register_external_event(PNATState pData, HANDLE hEvent, int index)
1265{
1266 pData->phEvents[index] = hEvent;
1267}
1268#endif
1269
1270unsigned int slirp_get_timeout_ms(PNATState pData)
1271{
1272 if (link_up)
1273 {
1274 if (time_fasttimo)
1275 return 2;
1276 if (do_slowtimo)
1277 return 500; /* see PR_SLOWHZ */
1278 }
1279 return 0;
1280}
1281
1282/*
1283 * this function called from NAT thread
1284 */
1285void slirp_post_sent(PNATState pData, void *pvArg)
1286{
1287 struct socket *so = 0;
1288 struct tcpcb *tp = 0;
1289 struct mbuf *m = (struct mbuf *)pvArg;
1290 m_free(pData, m);
1291}
Note: See TracBrowser for help on using the repository browser.

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