VirtualBox

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

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

build fix

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