VirtualBox

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

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

NAT: clean up dhcp a bit, and fox the TFTP server address calculation

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

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