VirtualBox

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

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

NAT:

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