VirtualBox

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

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

NAT:MT

  1. slirp queue inroduced
  2. main points of thread interactions are saved with critical sections
  3. slirp polling routine and timers communicates with NAT guest IO thread via queue

TODO: not works well, not compilable on Unixes.

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