VirtualBox

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

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

NAT:MT improvements

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