VirtualBox

source: vbox/trunk/src/VBox/HostDrivers/VBoxNetFlt/darwin/VBoxNetFlt-darwin.cpp@ 50761

Last change on this file since 50761 was 50761, checked in by vboxsync, 11 years ago

VBoxNetFlt-darwin.cpp: style + only detect p_count offset once.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 45.9 KB
Line 
1/* $Id: VBoxNetFlt-darwin.cpp 50761 2014-03-13 08:30:17Z vboxsync $ */
2/** @file
3 * VBoxNetFlt - Network Filter Driver (Host), Darwin Specific Code.
4 */
5
6/*
7 * Copyright (C) 2006-2014 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18/*******************************************************************************
19* Header Files *
20*******************************************************************************/
21/*
22 * Deal with conflicts first.
23 * PVM - BSD mess, that FreeBSD has correct a long time ago.
24 * iprt/types.h before sys/param.h - prevents UINT32_C and friends.
25 */
26#include <iprt/types.h>
27#include <sys/param.h>
28#undef PVM
29
30#include <IOKit/IOLib.h> /* Assert as function */
31
32#define LOG_GROUP LOG_GROUP_NET_FLT_DRV
33#include <VBox/log.h>
34#include <VBox/err.h>
35#include <VBox/intnetinline.h>
36#include <VBox/version.h>
37#include <iprt/initterm.h>
38#include <iprt/assert.h>
39#include <iprt/spinlock.h>
40#include <iprt/semaphore.h>
41#include <iprt/process.h>
42#include <iprt/alloc.h>
43#include <iprt/alloca.h>
44#include <iprt/time.h>
45#include <iprt/net.h>
46#include <iprt/thread.h>
47
48#include "../../darwin/VBoxNetSend.h"
49
50#include <mach/kmod.h>
51#include <sys/conf.h>
52#include <sys/errno.h>
53#include <sys/ioccom.h>
54#include <sys/malloc.h>
55#include <sys/proc.h>
56#include <sys/socket.h>
57#include <sys/sockio.h>
58#include <sys/kern_event.h>
59#include <net/kpi_interface.h>
60RT_C_DECLS_BEGIN /* Buggy 10.4 headers, fixed in 10.5. */
61#include <sys/kpi_mbuf.h>
62#include <net/kpi_interfacefilter.h>
63RT_C_DECLS_END
64#include <net/if.h>
65
66#define VBOXNETFLT_OS_SPECFIC 1
67#include "../VBoxNetFltInternal.h"
68
69
70/*******************************************************************************
71* Defined Constants And Macros *
72*******************************************************************************/
73/** The maximum number of SG segments.
74 * Used to prevent stack overflow and similar bad stuff. */
75#define VBOXNETFLT_DARWIN_MAX_SEGS 32
76
77#if 0
78/** For testing extremely segmented frames. */
79#define VBOXNETFLT_DARWIN_TEST_SEG_SIZE 14
80#endif
81
82
83/*******************************************************************************
84* Internal Functions *
85*******************************************************************************/
86RT_C_DECLS_BEGIN
87static kern_return_t VBoxNetFltDarwinStart(struct kmod_info *pKModInfo, void *pvData);
88static kern_return_t VBoxNetFltDarwinStop(struct kmod_info *pKModInfo, void *pvData);
89RT_C_DECLS_END
90
91
92/*******************************************************************************
93* Structures and Typedefs *
94*******************************************************************************/
95/**
96 * The mbuf tag data.
97 *
98 * We have to associate the ethernet header with each packet we're sending
99 * because things like icmp will inherit the tag it self so the tag along
100 * isn't sufficient to identify our mbufs. For the icmp scenario the ethernet
101 * header naturally changes before the packet is send pack, so let check it.
102 */
103typedef struct VBOXNETFLTTAG
104{
105 /** The ethernet header of the outgoing frame. */
106 RTNETETHERHDR EthHdr;
107} VBOXNETFLTTAG;
108/** Pointer to a VBoxNetFlt mbuf tag. */
109typedef VBOXNETFLTTAG *PVBOXNETFLTTAG;
110/** Pointer to a const VBoxNetFlt mbuf tag. */
111typedef VBOXNETFLTTAG const *PCVBOXNETFLTTAG;
112
113
114/*******************************************************************************
115* Global Variables *
116*******************************************************************************/
117/**
118 * Declare the module stuff.
119 */
120RT_C_DECLS_BEGIN
121extern kern_return_t _start(struct kmod_info *pKModInfo, void *pvData);
122extern kern_return_t _stop(struct kmod_info *pKModInfo, void *pvData);
123
124KMOD_EXPLICIT_DECL(VBoxNetFlt, VBOX_VERSION_STRING, _start, _stop)
125DECLHIDDEN(kmod_start_func_t *) _realmain = VBoxNetFltDarwinStart;
126DECLHIDDEN(kmod_stop_func_t *) _antimain = VBoxNetFltDarwinStop;
127DECLHIDDEN(int) _kext_apple_cc = __APPLE_CC__;
128RT_C_DECLS_END
129
130
131/**
132 * The (common) global data.
133 */
134static VBOXNETFLTGLOBALS g_VBoxNetFltGlobals;
135
136/** The unique tag id for this module.
137 * This is basically a unique string hash that lives on until reboot.
138 * It is used for tagging mbufs. */
139static mbuf_tag_id_t g_idTag;
140
141/** The offset of the struct ifnet::if_pcount variable.
142 * @remarks Initial value is valid for Lion and earlier. We adjust it on attach
143 * for later releases. */
144static unsigned g_offIfNetPCount = sizeof(void *) * (1 /*if_softc*/ + 1 /*if_name*/ + 2 /*if_link*/ + 2 /*if_addrhead*/ + 1 /*if_check_multi*/)
145 + sizeof(u_long) /*if_refcnt*/;
146/** Macro for accessing ifnet::if_pcount. */
147#define VBOX_GET_PCOUNT(pIfNet) ( *(int *)((uintptr_t)pIfNet + g_offIfNetPCount) )
148/** The size of area of ifnet structure we try to locate if_pcount in. */
149#define VBOXNETFLT_DARWIN_IFNET_SIZE 256
150/** Indicates whether g_offIfNetPCount has been adjusted already (no point in
151 * doing it more than once). */
152static bool g_fNetPCountFound = false;
153
154
155/**
156 * Change the promiscuous setting and try spot the changed in @a pIfNet.
157 *
158 * @returns Offset of potential p_count field.
159 * @param pIfNet The interface we're attaching to.
160 * @param iPromisc Whether to enable (1) or disable (0) promiscuous mode.
161 *
162 * @note This implementation relies on if_pcount to be aligned on sizeof(int).
163 */
164static unsigned vboxNetFltDarwinSetAndDiff(ifnet_t pIfNet, int iPromisc)
165{
166 int aiSavedState[VBOXNETFLT_DARWIN_IFNET_SIZE / sizeof(int)];
167 memcpy(aiSavedState, pIfNet, sizeof(aiSavedState));
168
169 ifnet_set_promiscuous(pIfNet, iPromisc);
170
171 int const iDiff = iPromisc ? 1 : -1;
172
173 /*
174 * We assume that ifnet structure will never have less members in front of if_pcount
175 * than it used to have in Lion. If this turns out to be false assumption we will
176 * have to start from zero offset.
177 */
178 for (unsigned i = g_offIfNetPCount / sizeof(int); i < RT_ELEMENTS(aiSavedState); i++)
179 if (((int*)pIfNet)[i] - aiSavedState[i] == iDiff)
180 return i * sizeof(int);
181
182 return 0;
183}
184
185
186/**
187 * Detect and adjust the offset of ifnet::if_pcount.
188 *
189 * @param pIfNet The interface we're attaching to.
190 */
191static void vboxNetFltDarwinDetectPCountOffset(ifnet_t pIfNet)
192{
193 if (g_fNetPCountFound)
194 return;
195
196 /*
197 * It would be nice to use locking at this point, but it is not available via KPI.
198 * This is why we try several times. At each attempt we modify if_pcount four times
199 * to rule out false detections.
200 */
201 unsigned offTry1, offTry2, offTry3, offTry4;
202 for (int iAttempt = 0; iAttempt < 3; iAttempt++)
203 {
204 offTry1 = vboxNetFltDarwinSetAndDiff(pIfNet, 1);
205 offTry2 = vboxNetFltDarwinSetAndDiff(pIfNet, 1);
206 offTry3 = vboxNetFltDarwinSetAndDiff(pIfNet, 0);
207 offTry4 = vboxNetFltDarwinSetAndDiff(pIfNet, 0);
208
209 /* If any attempt has failed we won't continue as our algorithm is flawed. */
210 if (!offTry1 || !offTry2 || !offTry3 || !offTry4)
211 break;
212 if (offTry1 == offTry2 && offTry2 == offTry3 && offTry3 == offTry4)
213 {
214 if (g_offIfNetPCount != offTry1)
215 {
216 Log(("VBoxNetFltDarwinDetectPCountOffset: Adjusted if_pcount offset to %x from %x.\n", offTry1, g_offIfNetPCount));
217 g_offIfNetPCount = offTry1;
218 g_fNetPCountFound = true;
219 }
220 break;
221 }
222 }
223
224 if (g_offIfNetPCount != offTry1)
225 LogRel(("VBoxNetFlt: Failed to detect promiscuous count, all traffic may reach wire (%x != %x).\n", g_offIfNetPCount, offTry1));
226}
227
228
229/**
230 * Start the kernel module.
231 */
232static kern_return_t VBoxNetFltDarwinStart(struct kmod_info *pKModInfo, void *pvData)
233{
234 int rc;
235
236 /*
237 * Initialize IPRT and find our module tag id.
238 * (IPRT is shared with VBoxDrv, it creates the loggers.)
239 */
240 rc = RTR0Init(0);
241 if (RT_SUCCESS(rc))
242 {
243 Log(("VBoxNetFltDarwinStart\n"));
244 errno_t err = mbuf_tag_id_find("org.VirtualBox.kext.VBoxFltDrv", &g_idTag);
245 if (!err)
246 {
247 /*
248 * Initialize the globals and connect to the support driver.
249 *
250 * This will call back vboxNetFltOsOpenSupDrv (and maybe vboxNetFltOsCloseSupDrv)
251 * for establishing the connect to the support driver.
252 */
253 memset(&g_VBoxNetFltGlobals, 0, sizeof(g_VBoxNetFltGlobals));
254 rc = vboxNetFltInitGlobalsAndIdc(&g_VBoxNetFltGlobals);
255 if (RT_SUCCESS(rc))
256 {
257 LogRel(("VBoxFltDrv: version " VBOX_VERSION_STRING " r%d\n", VBOX_SVN_REV));
258 return KMOD_RETURN_SUCCESS;
259 }
260
261 LogRel(("VBoxFltDrv: failed to initialize device extension (rc=%d)\n", rc));
262 }
263 else
264 LogRel(("VBoxFltDrv: mbuf_tag_id_find failed, err=%d\n", err));
265 RTR0Term();
266 }
267 else
268 printf("VBoxFltDrv: failed to initialize IPRT (rc=%d)\n", rc);
269
270 memset(&g_VBoxNetFltGlobals, 0, sizeof(g_VBoxNetFltGlobals));
271 return KMOD_RETURN_FAILURE;
272}
273
274
275/**
276 * Stop the kernel module.
277 */
278static kern_return_t VBoxNetFltDarwinStop(struct kmod_info *pKModInfo, void *pvData)
279{
280 Log(("VBoxNetFltDarwinStop\n"));
281
282 /*
283 * Refuse to unload if anyone is currently using the filter driver.
284 * This is important as I/O kit / xnu will to be able to do usage
285 * tracking for us!
286 */
287 int rc = vboxNetFltTryDeleteIdcAndGlobals(&g_VBoxNetFltGlobals);
288 if (RT_FAILURE(rc))
289 {
290 Log(("VBoxNetFltDarwinStop - failed, busy.\n"));
291 return KMOD_RETURN_FAILURE;
292 }
293
294 /*
295 * Undo the work done during start (in reverse order).
296 */
297 memset(&g_VBoxNetFltGlobals, 0, sizeof(g_VBoxNetFltGlobals));
298
299 RTR0Term();
300
301 return KMOD_RETURN_SUCCESS;
302}
303
304
305/**
306 * Reads and retains the host interface handle.
307 *
308 * @returns The handle, NULL if detached.
309 * @param pThis
310 */
311DECLINLINE(ifnet_t) vboxNetFltDarwinRetainIfNet(PVBOXNETFLTINS pThis)
312{
313 ifnet_t pIfNet = NULL;
314
315 /*
316 * Be careful here to avoid problems racing the detached callback.
317 */
318 RTSpinlockAcquire(pThis->hSpinlock);
319 if (!ASMAtomicUoReadBool(&pThis->fDisconnectedFromHost))
320 {
321 pIfNet = ASMAtomicUoReadPtrT(&pThis->u.s.pIfNet, ifnet_t);
322 if (pIfNet)
323 ifnet_reference(pIfNet);
324 }
325 RTSpinlockReleaseNoInts(pThis->hSpinlock);
326
327 return pIfNet;
328}
329
330
331/**
332 * Release the host interface handle previously retained
333 * by vboxNetFltDarwinRetainIfNet.
334 *
335 * @param pThis The instance.
336 * @param pIfNet The vboxNetFltDarwinRetainIfNet return value, NULL is fine.
337 */
338DECLINLINE(void) vboxNetFltDarwinReleaseIfNet(PVBOXNETFLTINS pThis, ifnet_t pIfNet)
339{
340 NOREF(pThis);
341 if (pIfNet)
342 ifnet_release(pIfNet);
343}
344
345
346/**
347 * Checks whether this is an mbuf created by vboxNetFltDarwinMBufFromSG,
348 * i.e. a buffer which we're pushing and should be ignored by the filter callbacks.
349 *
350 * @returns true / false accordingly.
351 * @param pThis The instance.
352 * @param pMBuf The mbuf.
353 * @param pvFrame The frame pointer, optional.
354 */
355DECLINLINE(bool) vboxNetFltDarwinMBufIsOur(PVBOXNETFLTINS pThis, mbuf_t pMBuf, void *pvFrame)
356{
357 NOREF(pThis);
358
359 /*
360 * Lookup the tag set by vboxNetFltDarwinMBufFromSG.
361 */
362 PCVBOXNETFLTTAG pTagData;
363 size_t cbTagData;
364 errno_t err = mbuf_tag_find(pMBuf, g_idTag, 0 /* type */, &cbTagData, (void **)&pTagData);
365 if (err)
366 return false;
367 AssertReturn(cbTagData == sizeof(*pTagData), false);
368
369 /*
370 * Dig out the ethernet header from the mbuf.
371 */
372 PCRTNETETHERHDR pEthHdr = (PCRTNETETHERHDR)pvFrame;
373 if (!pEthHdr)
374 pEthHdr = (PCRTNETETHERHDR)mbuf_pkthdr_header(pMBuf);
375 if (!pEthHdr)
376 pEthHdr = (PCRTNETETHERHDR)mbuf_data(pMBuf);
377 /* ASSUMING that there is enough data to work on! */
378 if ( pEthHdr->DstMac.au8[0] != pTagData->EthHdr.DstMac.au8[0]
379 || pEthHdr->DstMac.au8[1] != pTagData->EthHdr.DstMac.au8[1]
380 || pEthHdr->DstMac.au8[2] != pTagData->EthHdr.DstMac.au8[2]
381 || pEthHdr->DstMac.au8[3] != pTagData->EthHdr.DstMac.au8[3]
382 || pEthHdr->DstMac.au8[4] != pTagData->EthHdr.DstMac.au8[4]
383 || pEthHdr->DstMac.au8[5] != pTagData->EthHdr.DstMac.au8[5]
384 || pEthHdr->SrcMac.au8[0] != pTagData->EthHdr.SrcMac.au8[0]
385 || pEthHdr->SrcMac.au8[1] != pTagData->EthHdr.SrcMac.au8[1]
386 || pEthHdr->SrcMac.au8[2] != pTagData->EthHdr.SrcMac.au8[2]
387 || pEthHdr->SrcMac.au8[3] != pTagData->EthHdr.SrcMac.au8[3]
388 || pEthHdr->SrcMac.au8[4] != pTagData->EthHdr.SrcMac.au8[4]
389 || pEthHdr->SrcMac.au8[5] != pTagData->EthHdr.SrcMac.au8[5]
390 || pEthHdr->EtherType != pTagData->EthHdr.EtherType)
391 {
392 Log3(("tagged, but the ethernet header has changed\n"));
393 return false;
394 }
395
396 return true;
397}
398
399
400/**
401 * Internal worker that create a darwin mbuf for a (scatter/)gather list.
402 *
403 * @returns Pointer to the mbuf.
404 * @param pThis The instance.
405 * @param pSG The (scatter/)gather list.
406 */
407static mbuf_t vboxNetFltDarwinMBufFromSG(PVBOXNETFLTINS pThis, PINTNETSG pSG)
408{
409 /// @todo future? mbuf_how_t How = preemption enabled ? MBUF_DONTWAIT : MBUF_WAITOK;
410 mbuf_how_t How = MBUF_WAITOK;
411
412 /*
413 * We need some way of getting back to our instance data when
414 * the mbuf is freed, so use pvUserData for this.
415 * -- this is not relevant anylonger! --
416 */
417 Assert(!pSG->pvUserData || pSG->pvUserData == pThis);
418 Assert(!pSG->pvUserData2);
419 pSG->pvUserData = pThis;
420
421 /*
422 * Allocate a packet and copy over the data.
423 *
424 * Using mbuf_attachcluster() here would've been nice but there are two
425 * issues with it: (1) it's 10.5.x only, and (2) the documentation indicates
426 * that it's not supposed to be used for really external buffers. The 2nd
427 * point might be argued against considering that the only m_clattach user
428 * is mallocs memory for the ext mbuf and not doing what's stated in the docs.
429 * However, it's hard to tell if these m_clattach buffers actually makes it
430 * to the NICs or not, and even if they did, the NIC would need the physical
431 * addresses for the pages they contain and might end up copying the data
432 * to a new mbuf anyway.
433 *
434 * So, in the end it's better to just do it the simple way that will work
435 * 100%, even if it involves some extra work (alloc + copy) we really wished
436 * to avoid.
437 *
438 * Note. We can't make use of the physical addresses on darwin because the
439 * way the mbuf / cluster stuff works (see mbuf_data_to_physical and
440 * mcl_to_paddr).
441 */
442 mbuf_t pPkt = NULL;
443 errno_t err = mbuf_allocpacket(How, pSG->cbTotal, NULL, &pPkt);
444 if (!err)
445 {
446 /* Skip zero sized memory buffers (paranoia). */
447 mbuf_t pCur = pPkt;
448 while (pCur && !mbuf_maxlen(pCur))
449 pCur = mbuf_next(pCur);
450 Assert(pCur);
451
452 /* Set the required packet header attributes. */
453 mbuf_pkthdr_setlen(pPkt, pSG->cbTotal);
454 mbuf_pkthdr_setheader(pPkt, mbuf_data(pCur));
455
456 /* Special case the single buffer copy. */
457 if ( mbuf_next(pCur)
458 && mbuf_maxlen(pCur) >= pSG->cbTotal)
459 {
460 mbuf_setlen(pCur, pSG->cbTotal);
461 IntNetSgRead(pSG, mbuf_data(pCur));
462 }
463 else
464 {
465 /* Multi buffer copying. */
466 size_t cbLeft = pSG->cbTotal;
467 size_t offSrc = 0;
468 while (cbLeft > 0 && pCur)
469 {
470 size_t cb = mbuf_maxlen(pCur);
471 if (cb > cbLeft)
472 cb = cbLeft;
473 mbuf_setlen(pCur, cb);
474 IntNetSgReadEx(pSG, offSrc, cb, mbuf_data(pCur));
475
476 /* advance */
477 offSrc += cb;
478 cbLeft -= cb;
479 pCur = mbuf_next(pCur);
480 }
481 Assert(cbLeft == 0);
482 }
483 if (!err)
484 {
485 /*
486 * Tag the packet and return successfully.
487 */
488 PVBOXNETFLTTAG pTagData;
489 err = mbuf_tag_allocate(pPkt, g_idTag, 0 /* type */, sizeof(VBOXNETFLTTAG) /* tag len */, How, (void **)&pTagData);
490 if (!err)
491 {
492 Assert(pSG->aSegs[0].cb >= sizeof(pTagData->EthHdr));
493 memcpy(&pTagData->EthHdr, pSG->aSegs[0].pv, sizeof(pTagData->EthHdr));
494 return pPkt;
495 }
496
497 /* bailout: */
498 AssertMsg(err == ENOMEM || err == EWOULDBLOCK, ("err=%d\n", err));
499 }
500
501 mbuf_freem(pPkt);
502 }
503 else
504 AssertMsg(err == ENOMEM || err == EWOULDBLOCK, ("err=%d\n", err));
505 pSG->pvUserData = NULL;
506
507 return NULL;
508}
509
510
511/**
512 * Calculates the number of segments required to represent the mbuf.
513 *
514 * @returns Number of segments.
515 * @param pThis The instance.
516 * @param pMBuf The mbuf.
517 * @param pvFrame The frame pointer, optional.
518 */
519DECLINLINE(unsigned) vboxNetFltDarwinMBufCalcSGSegs(PVBOXNETFLTINS pThis, mbuf_t pMBuf, void *pvFrame)
520{
521 NOREF(pThis);
522
523 /*
524 * Count the buffers in the chain.
525 */
526 unsigned cSegs = 0;
527 for (mbuf_t pCur = pMBuf; pCur; pCur = mbuf_next(pCur))
528 if (mbuf_len(pCur))
529 cSegs++;
530 else if ( !cSegs
531 && pvFrame
532 && (uintptr_t)pvFrame - (uintptr_t)mbuf_datastart(pMBuf) < mbuf_maxlen(pMBuf))
533 cSegs++;
534
535#ifdef PADD_RUNT_FRAMES_FROM_HOST
536 /*
537 * Add one buffer if the total is less than the ethernet minimum 60 bytes.
538 * This may allocate a segment too much if the ethernet header is separated,
539 * but that shouldn't harm us much.
540 */
541 if (mbuf_pkthdr_len(pMBuf) < 60)
542 cSegs++;
543#endif
544
545#ifdef VBOXNETFLT_DARWIN_TEST_SEG_SIZE
546 /* maximize the number of segments. */
547 cSegs = RT_MAX(VBOXNETFLT_DARWIN_MAX_SEGS - 1, cSegs);
548#endif
549
550 return cSegs ? cSegs : 1;
551}
552
553
554/**
555 * Initializes a SG list from an mbuf.
556 *
557 * @returns Number of segments.
558 * @param pThis The instance.
559 * @param pMBuf The mbuf.
560 * @param pSG The SG.
561 * @param pvFrame The frame pointer, optional.
562 * @param cSegs The number of segments allocated for the SG.
563 * This should match the number in the mbuf exactly!
564 * @param fSrc The source of the frame.
565 */
566DECLINLINE(void) vboxNetFltDarwinMBufToSG(PVBOXNETFLTINS pThis, mbuf_t pMBuf, void *pvFrame, PINTNETSG pSG, unsigned cSegs, uint32_t fSrc)
567{
568 NOREF(pThis);
569
570 /*
571 * Walk the chain and convert the buffers to segments. Works INTNETSG::cbTotal.
572 */
573 unsigned iSeg = 0;
574 IntNetSgInitTempSegs(pSG, 0 /*cbTotal*/, cSegs, 0 /*cSegsUsed*/);
575 for (mbuf_t pCur = pMBuf; pCur; pCur = mbuf_next(pCur))
576 {
577 size_t cbSeg = mbuf_len(pCur);
578 if (cbSeg)
579 {
580 void *pvSeg = mbuf_data(pCur);
581
582 /* deal with pvFrame */
583 if (!iSeg && pvFrame && pvFrame != pvSeg)
584 {
585 void *pvStart = mbuf_datastart(pMBuf);
586 uintptr_t offSeg = (uintptr_t)pvSeg - (uintptr_t)pvStart;
587 uintptr_t offSegEnd = offSeg + cbSeg;
588 Assert(pvStart && pvSeg && offSeg < mbuf_maxlen(pMBuf) && offSegEnd <= mbuf_maxlen(pMBuf)); NOREF(offSegEnd);
589 uintptr_t offFrame = (uintptr_t)pvFrame - (uintptr_t)pvStart;
590 if (RT_LIKELY(offFrame < offSeg))
591 {
592 pvSeg = pvFrame;
593 cbSeg += offSeg - offFrame;
594 }
595 else
596 AssertMsgFailed(("pvFrame=%p pvStart=%p pvSeg=%p offSeg=%p cbSeg=%#zx offSegEnd=%p offFrame=%p maxlen=%#zx\n",
597 pvFrame, pvStart, pvSeg, offSeg, cbSeg, offSegEnd, offFrame, mbuf_maxlen(pMBuf)));
598 pvFrame = NULL;
599 }
600
601 AssertBreak(iSeg < cSegs);
602 pSG->cbTotal += cbSeg;
603 pSG->aSegs[iSeg].cb = cbSeg;
604 pSG->aSegs[iSeg].pv = pvSeg;
605 pSG->aSegs[iSeg].Phys = NIL_RTHCPHYS;
606 iSeg++;
607 }
608 /* The pvFrame might be in a now empty buffer. */
609 else if ( !iSeg
610 && pvFrame
611 && (uintptr_t)pvFrame - (uintptr_t)mbuf_datastart(pMBuf) < mbuf_maxlen(pMBuf))
612 {
613 cbSeg = (uintptr_t)mbuf_datastart(pMBuf) + mbuf_maxlen(pMBuf) - (uintptr_t)pvFrame;
614 pSG->cbTotal += cbSeg;
615 pSG->aSegs[iSeg].cb = cbSeg;
616 pSG->aSegs[iSeg].pv = pvFrame;
617 pSG->aSegs[iSeg].Phys = NIL_RTHCPHYS;
618 iSeg++;
619 pvFrame = NULL;
620 }
621 }
622
623 Assert(iSeg && iSeg <= cSegs);
624 pSG->cSegsUsed = iSeg;
625
626#ifdef PADD_RUNT_FRAMES_FROM_HOST
627 /*
628 * Add a trailer if the frame is too small.
629 *
630 * Since we're getting to the packet before it is framed, it has not
631 * yet been padded. The current solution is to add a segment pointing
632 * to a buffer containing all zeros and pray that works for all frames...
633 */
634 if (pSG->cbTotal < 60 && (fSrc & INTNETTRUNKDIR_HOST))
635 {
636 AssertReturnVoid(iSeg < cSegs);
637
638 static uint8_t const s_abZero[128] = {0};
639 pSG->aSegs[iSeg].Phys = NIL_RTHCPHYS;
640 pSG->aSegs[iSeg].pv = (void *)&s_abZero[0];
641 pSG->aSegs[iSeg].cb = 60 - pSG->cbTotal;
642 pSG->cbTotal = 60;
643 pSG->cSegsUsed++;
644 }
645#endif
646
647#ifdef VBOXNETFLT_DARWIN_TEST_SEG_SIZE
648 /*
649 * Redistribute the segments.
650 */
651 if (pSG->cSegsUsed < pSG->cSegsAlloc)
652 {
653 /* copy the segments to the end. */
654 int iSrc = pSG->cSegsUsed;
655 int iDst = pSG->cSegsAlloc;
656 while (iSrc > 0)
657 {
658 iDst--;
659 iSrc--;
660 pSG->aSegs[iDst] = pSG->aSegs[iSrc];
661 }
662
663 /* create small segments from the start. */
664 pSG->cSegsUsed = pSG->cSegsAlloc;
665 iSrc = iDst;
666 iDst = 0;
667 while ( iDst < iSrc
668 && iDst < pSG->cSegsAlloc)
669 {
670 pSG->aSegs[iDst].Phys = NIL_RTHCPHYS;
671 pSG->aSegs[iDst].pv = pSG->aSegs[iSrc].pv;
672 pSG->aSegs[iDst].cb = RT_MIN(pSG->aSegs[iSrc].cb, VBOXNETFLT_DARWIN_TEST_SEG_SIZE);
673 if (pSG->aSegs[iDst].cb != pSG->aSegs[iSrc].cb)
674 {
675 pSG->aSegs[iSrc].cb -= pSG->aSegs[iDst].cb;
676 pSG->aSegs[iSrc].pv = (uint8_t *)pSG->aSegs[iSrc].pv + pSG->aSegs[iDst].cb;
677 }
678 else if (++iSrc >= pSG->cSegsAlloc)
679 {
680 pSG->cSegsUsed = iDst + 1;
681 break;
682 }
683 iDst++;
684 }
685 }
686#endif
687
688 AssertMsg(!pvFrame, ("pvFrame=%p pMBuf=%p iSeg=%d\n", pvFrame, pMBuf, iSeg));
689}
690
691
692/**
693 * Helper for determining whether the host wants the interface to be
694 * promiscuous.
695 */
696static bool vboxNetFltDarwinIsPromiscuous(PVBOXNETFLTINS pThis)
697{
698 bool fRc = false;
699 ifnet_t pIfNet = vboxNetFltDarwinRetainIfNet(pThis);
700 if (pIfNet)
701 {
702 /* gather the data */
703 uint16_t fIf = ifnet_flags(pIfNet);
704 unsigned cPromisc = VBOX_GET_PCOUNT(pIfNet);
705 bool fSetPromiscuous = ASMAtomicUoReadBool(&pThis->u.s.fSetPromiscuous);
706 vboxNetFltDarwinReleaseIfNet(pThis, pIfNet);
707
708 /* calc the return. */
709 fRc = (fIf & IFF_PROMISC)
710 && cPromisc > fSetPromiscuous;
711 }
712 return fRc;
713}
714
715
716
717/**
718 *
719 * @see iff_detached_func in the darwin kpi.
720 */
721static void vboxNetFltDarwinIffDetached(void *pvThis, ifnet_t pIfNet)
722{
723 PVBOXNETFLTINS pThis = (PVBOXNETFLTINS)pvThis;
724 uint64_t NanoTS = RTTimeSystemNanoTS();
725 LogFlow(("vboxNetFltDarwinIffDetached: pThis=%p NanoTS=%RU64 (%d)\n",
726 pThis, NanoTS, VALID_PTR(pIfNet) ? VBOX_GET_PCOUNT(pIfNet) : -1));
727
728 Assert(!pThis->fDisconnectedFromHost);
729 Assert(!pThis->fRediscoveryPending);
730
731 /*
732 * If we've put it into promiscuous mode, undo that now. If we don't
733 * the if_pcount will go all wrong when it's replugged.
734 */
735 if (ASMAtomicXchgBool(&pThis->u.s.fSetPromiscuous, false))
736 ifnet_set_promiscuous(pIfNet, 0);
737
738 /*
739 * We carefully take the spinlock and increase the interface reference
740 * behind it in order to avoid problematic races with the detached callback.
741 */
742 RTSpinlockAcquire(pThis->hSpinlock);
743
744 pIfNet = ASMAtomicUoReadPtrT(&pThis->u.s.pIfNet, ifnet_t);
745 int cPromisc = VALID_PTR(pIfNet) ? VBOX_GET_PCOUNT(pIfNet) : - 1;
746
747 ASMAtomicUoWriteNullPtr(&pThis->u.s.pIfNet);
748 ASMAtomicUoWriteNullPtr(&pThis->u.s.pIfFilter);
749 ASMAtomicWriteBool(&pThis->u.s.fNeedSetPromiscuous, false);
750 pThis->u.s.fSetPromiscuous = false;
751 ASMAtomicUoWriteU64(&pThis->NanoTSLastRediscovery, NanoTS);
752 ASMAtomicUoWriteBool(&pThis->fRediscoveryPending, false);
753 ASMAtomicWriteBool(&pThis->fDisconnectedFromHost, true);
754
755 RTSpinlockReleaseNoInts(pThis->hSpinlock);
756
757 if (pIfNet)
758 ifnet_release(pIfNet);
759 LogRel(("VBoxNetFlt: was detached from '%s' (%d)\n", pThis->szName, cPromisc));
760}
761
762
763/**
764 *
765 * @see iff_ioctl_func in the darwin kpi.
766 */
767static errno_t vboxNetFltDarwinIffIoCtl(void *pvThis, ifnet_t pIfNet, protocol_family_t eProtocol, u_long uCmd, void *pvArg)
768{
769 PVBOXNETFLTINS pThis = (PVBOXNETFLTINS)pvThis;
770 LogFlow(("vboxNetFltDarwinIffIoCtl: pThis=%p uCmd=%lx\n", pThis, uCmd));
771
772 /*
773 * Update fOtherPromiscuous.
774 */
775 /** @todo we'll have to find the offset of if_pcount to get this right! */
776 //if (uCmd == SIOCSIFFLAGS)
777 //{
778 //
779 //}
780
781 /*
782 * We didn't handle it, continue processing.
783 */
784 NOREF(pThis);
785 NOREF(eProtocol);
786 NOREF(uCmd);
787 NOREF(pvArg);
788 return EOPNOTSUPP;
789}
790
791
792/**
793 *
794 * @see iff_event_func in the darwin kpi.
795 */
796static void vboxNetFltDarwinIffEvent(void *pvThis, ifnet_t pIfNet, protocol_family_t eProtocol, const struct kev_msg *pEvMsg)
797{
798 PVBOXNETFLTINS pThis = (PVBOXNETFLTINS)pvThis;
799 LogFlow(("vboxNetFltDarwinIffEvent: pThis=%p\n", pThis));
800
801 NOREF(pThis);
802 NOREF(pIfNet);
803 NOREF(eProtocol);
804 NOREF(pEvMsg);
805
806 /*
807 * Watch out for the interface going online / offline.
808 */
809 if ( VALID_PTR(pThis)
810 && VALID_PTR(pEvMsg)
811 && pEvMsg->vendor_code == KEV_VENDOR_APPLE
812 && pEvMsg->kev_class == KEV_NETWORK_CLASS
813 && pEvMsg->kev_subclass == KEV_DL_SUBCLASS)
814 {
815 if (pThis->u.s.pIfNet == pIfNet)
816 {
817 if (pEvMsg->event_code == KEV_DL_LINK_ON)
818 {
819 if (ASMAtomicUoReadBool(&pThis->u.s.fNeedSetPromiscuous))
820 {
821 /* failed to bring it online. */
822 errno_t err = ifnet_set_promiscuous(pIfNet, 1);
823 if (!err)
824 {
825 ASMAtomicWriteBool(&pThis->u.s.fSetPromiscuous, true);
826 ASMAtomicWriteBool(&pThis->u.s.fNeedSetPromiscuous, false);
827 Log(("vboxNetFltDarwinIffEvent: enabled promiscuous mode on %s (%d)\n", pThis->szName, VBOX_GET_PCOUNT(pIfNet)));
828 }
829 else
830 Log(("vboxNetFltDarwinIffEvent: ifnet_set_promiscuous failed on %s, err=%d (%d)\n", pThis->szName, err, VBOX_GET_PCOUNT(pIfNet)));
831 }
832 else if ( ASMAtomicUoReadBool(&pThis->u.s.fSetPromiscuous)
833 && !(ifnet_flags(pIfNet) & IFF_PROMISC))
834 {
835 /* Try fix the inconsistency. */
836 errno_t err = ifnet_set_flags(pIfNet, IFF_PROMISC, IFF_PROMISC);
837 if (!err)
838 err = ifnet_ioctl(pIfNet, 0, SIOCSIFFLAGS, NULL);
839 if (!err && (ifnet_flags(pIfNet) & IFF_PROMISC))
840 Log(("vboxNetFltDarwinIffEvent: fixed IFF_PROMISC on %s (%d)\n", pThis->szName, VBOX_GET_PCOUNT(pIfNet)));
841 else
842 Log(("vboxNetFltDarwinIffEvent: failed to fix IFF_PROMISC on %s, err=%d flags=%#x (%d)\n",
843 pThis->szName, err, ifnet_flags(pIfNet), VBOX_GET_PCOUNT(pIfNet)));
844 }
845 else
846 Log(("vboxNetFltDarwinIffEvent: online, '%s'. flags=%#x (%d)\n", pThis->szName, ifnet_flags(pIfNet), VBOX_GET_PCOUNT(pIfNet)));
847 }
848 else if (pEvMsg->event_code == KEV_DL_LINK_OFF)
849 Log(("vboxNetFltDarwinIffEvent: %s goes down (%d)\n", pThis->szName, VBOX_GET_PCOUNT(pIfNet)));
850/** @todo KEV_DL_LINK_ADDRESS_CHANGED -> pfnReportMacAddress */
851/** @todo KEV_DL_SIFFLAGS -> pfnReportPromiscuousMode */
852 }
853 else
854 Log(("vboxNetFltDarwinIffEvent: pThis->u.s.pIfNet=%p pIfNet=%p (%d)\n", pThis->u.s.pIfNet, pIfNet, VALID_PTR(pIfNet) ? VBOX_GET_PCOUNT(pIfNet) : -1));
855 }
856 else if (VALID_PTR(pEvMsg))
857 Log(("vboxNetFltDarwinIffEvent: vendor_code=%#x kev_class=%#x kev_subclass=%#x event_code=%#x\n",
858 pEvMsg->vendor_code, pEvMsg->kev_class, pEvMsg->kev_subclass, pEvMsg->event_code));
859}
860
861
862/**
863 * Internal worker for vboxNetFltDarwinIffInput and vboxNetFltDarwinIffOutput,
864 *
865 * @returns 0 or EJUSTRETURN.
866 * @param pThis The instance.
867 * @param pMBuf The mbuf.
868 * @param pvFrame The start of the frame, optional.
869 * @param fSrc Where the packet (allegedly) comes from, one INTNETTRUNKDIR_* value.
870 * @param eProtocol The protocol.
871 */
872static errno_t vboxNetFltDarwinIffInputOutputWorker(PVBOXNETFLTINS pThis, mbuf_t pMBuf, void *pvFrame,
873 uint32_t fSrc, protocol_family_t eProtocol)
874{
875 /*
876 * Drop it immediately?
877 */
878 Log2(("vboxNetFltDarwinIffInputOutputWorker: pThis=%p pMBuf=%p pvFrame=%p fSrc=%#x cbPkt=%x\n",
879 pThis, pMBuf, pvFrame, fSrc, pMBuf ? mbuf_pkthdr_len(pMBuf) : -1));
880 if (!pMBuf)
881 return 0;
882#if 0 /* debugging lost icmp packets */
883 if (mbuf_pkthdr_len(pMBuf) > 0x300)
884 {
885 uint8_t *pb = (uint8_t *)(pvFrame ? pvFrame : mbuf_data(pMBuf));
886 Log3(("D=%.6Rhxs S=%.6Rhxs T=%04x IFF\n", pb, pb + 6, RT_BE2H_U16(*(uint16_t *)(pb + 12))));
887 }
888#endif
889 if (vboxNetFltDarwinMBufIsOur(pThis, pMBuf, pvFrame))
890 return 0;
891
892 /*
893 * Active? Retain the instance and increment the busy counter.
894 */
895 if (!vboxNetFltTryRetainBusyActive(pThis))
896 return 0;
897
898 /*
899 * Finalize out-bound packets since the stack puts off finalizing
900 * TCP/IP checksums as long as possible.
901 * ASSUMES this only applies to outbound IP packets.
902 */
903 if ( (fSrc & INTNETTRUNKDIR_HOST)
904 && eProtocol == PF_INET)
905 {
906 Assert(!pvFrame);
907 mbuf_outbound_finalize(pMBuf, eProtocol, sizeof(RTNETETHERHDR));
908 }
909
910 /*
911 * Create a (scatter/)gather list for the mbuf and feed it to the internal network.
912 */
913 bool fDropIt = false;
914 unsigned cSegs = vboxNetFltDarwinMBufCalcSGSegs(pThis, pMBuf, pvFrame);
915 if (cSegs < VBOXNETFLT_DARWIN_MAX_SEGS)
916 {
917 PINTNETSG pSG = (PINTNETSG)alloca(RT_OFFSETOF(INTNETSG, aSegs[cSegs]));
918 vboxNetFltDarwinMBufToSG(pThis, pMBuf, pvFrame, pSG, cSegs, fSrc);
919
920 fDropIt = pThis->pSwitchPort->pfnRecv(pThis->pSwitchPort, NULL /* pvIf */, pSG, fSrc);
921 if (fDropIt)
922 {
923 /*
924 * Check if this interface is in promiscuous mode. We should not drop
925 * any packets before they get to the driver as it passes them to tap
926 * callbacks in order for BPF to work properly.
927 */
928 if (vboxNetFltDarwinIsPromiscuous(pThis))
929 fDropIt = false;
930 else
931 mbuf_freem(pMBuf);
932 }
933 }
934
935 vboxNetFltRelease(pThis, true /* fBusy */);
936
937 return fDropIt ? EJUSTRETURN : 0;
938}
939
940
941/**
942 * From the host.
943 *
944 * @see iff_output_func in the darwin kpi.
945 */
946static errno_t vboxNetFltDarwinIffOutput(void *pvThis, ifnet_t pIfNet, protocol_family_t eProtocol, mbuf_t *ppMBuf)
947{
948 /** @todo there was some note about the ethernet header here or something like that... */
949
950 NOREF(eProtocol);
951 NOREF(pIfNet);
952 return vboxNetFltDarwinIffInputOutputWorker((PVBOXNETFLTINS)pvThis, *ppMBuf, NULL, INTNETTRUNKDIR_HOST, eProtocol);
953}
954
955
956/**
957 * From the wire.
958 *
959 * @see iff_input_func in the darwin kpi.
960 */
961static errno_t vboxNetFltDarwinIffInput(void *pvThis, ifnet_t pIfNet, protocol_family_t eProtocol, mbuf_t *ppMBuf, char **ppchFrame)
962{
963 NOREF(eProtocol);
964 NOREF(pIfNet);
965 return vboxNetFltDarwinIffInputOutputWorker((PVBOXNETFLTINS)pvThis, *ppMBuf, *ppchFrame, INTNETTRUNKDIR_WIRE, eProtocol);
966}
967
968
969/** A worker thread for vboxNetFltSendDummy(). */
970static DECLCALLBACK(int) vboxNetFltSendDummyWorker(RTTHREAD hThreadSelf, void *pvUser)
971{
972 Assert(pvUser);
973 ifnet_t pIfNet = (ifnet_t)pvUser;
974 return VBoxNetSendDummy(pIfNet);
975}
976
977
978/**
979 * Prevent GUI icon freeze issue when VirtualBoxVM process terminates.
980 *
981 * This function is a workaround for stuck-in-dock issue. The idea here is to
982 * send a dummy packet to an interface from the context of a kernel thread.
983 * Therefore, an XNU's receive thread (which is created as a result if we are
984 * the first who is communicating with the interface) will be associated with
985 * the kernel thread instead of VirtualBoxVM process.
986 *
987 * @param pIfNet Interface to be used to send data.
988 */
989static void vboxNetFltSendDummy(ifnet_t pIfNet)
990{
991 RTTHREAD hThread;
992 int rc = RTThreadCreate(&hThread, vboxNetFltSendDummyWorker, (void *)pIfNet, 0,
993 RTTHREADTYPE_DEFAULT, RTTHREADFLAGS_WAITABLE, "DummyThread");
994 if (RT_SUCCESS(rc))
995 {
996 RTThreadWait(hThread, RT_INDEFINITE_WAIT, NULL);
997 LogFlow(("vboxNetFltSendDummy: a dummy packet has been successfully sent in order to prevent stuck-in-dock issue\n"));
998 }
999 else
1000 LogFlow(("vboxNetFltSendDummy: unable to send dummy packet in order to prevent stuck-in-dock issue\n"));
1001}
1002
1003
1004/**
1005 * Internal worker for vboxNetFltOsInitInstance and vboxNetFltOsMaybeRediscovered.
1006 *
1007 * @returns VBox status code.
1008 * @param pThis The instance.
1009 * @param fRediscovery If set we're doing a rediscovery attempt, so, don't
1010 * flood the release log.
1011 */
1012static int vboxNetFltDarwinAttachToInterface(PVBOXNETFLTINS pThis, bool fRediscovery)
1013{
1014 LogFlow(("vboxNetFltDarwinAttachToInterface: pThis=%p (%s)\n", pThis, pThis->szName));
1015
1016 /*
1017 * Locate the interface first.
1018 *
1019 * The pIfNet member is updated before iflt_attach is called and used
1020 * to deal with the hypothetical case where someone rips out the
1021 * interface immediately after our iflt_attach call.
1022 */
1023 ifnet_t pIfNet = NULL;
1024 errno_t err = ifnet_find_by_name(pThis->szName, &pIfNet);
1025 if (err)
1026 {
1027 Assert(err == ENXIO);
1028 if (!fRediscovery)
1029 LogRel(("VBoxFltDrv: failed to find ifnet '%s' (err=%d)\n", pThis->szName, err));
1030 else
1031 Log(("VBoxFltDrv: failed to find ifnet '%s' (err=%d)\n", pThis->szName, err));
1032 return VERR_INTNET_FLT_IF_NOT_FOUND;
1033 }
1034
1035 RTSpinlockAcquire(pThis->hSpinlock);
1036 ASMAtomicUoWritePtr(&pThis->u.s.pIfNet, pIfNet);
1037 RTSpinlockReleaseNoInts(pThis->hSpinlock);
1038
1039 /* Adjust g_offIfNetPCount as it varies for different versions of xnu. */
1040 vboxNetFltDarwinDetectPCountOffset(pIfNet);
1041
1042 /* Prevent stuck-in-dock issue by associating interface receive thread with kernel thread. */
1043 vboxNetFltSendDummy(pIfNet);
1044
1045 /*
1046 * Get the mac address while we still have a valid ifnet reference.
1047 */
1048 err = ifnet_lladdr_copy_bytes(pIfNet, &pThis->u.s.MacAddr, sizeof(pThis->u.s.MacAddr));
1049 if (!err)
1050 {
1051 /*
1052 * Try attach the filter.
1053 */
1054 struct iff_filter RegRec;
1055 RegRec.iff_cookie = pThis;
1056 RegRec.iff_name = "VBoxNetFlt";
1057 RegRec.iff_protocol = 0;
1058 RegRec.iff_input = vboxNetFltDarwinIffInput;
1059 RegRec.iff_output = vboxNetFltDarwinIffOutput;
1060 RegRec.iff_event = vboxNetFltDarwinIffEvent;
1061 RegRec.iff_ioctl = vboxNetFltDarwinIffIoCtl;
1062 RegRec.iff_detached = vboxNetFltDarwinIffDetached;
1063 interface_filter_t pIfFilter = NULL;
1064 err = iflt_attach(pIfNet, &RegRec, &pIfFilter);
1065 Assert(err || pIfFilter);
1066
1067 RTSpinlockAcquire(pThis->hSpinlock);
1068 pIfNet = ASMAtomicUoReadPtrT(&pThis->u.s.pIfNet, ifnet_t);
1069 if (pIfNet && !err)
1070 {
1071 ASMAtomicUoWriteBool(&pThis->fDisconnectedFromHost, false);
1072 ASMAtomicUoWritePtr(&pThis->u.s.pIfFilter, pIfFilter);
1073 pIfNet = NULL; /* don't dereference it */
1074 }
1075 RTSpinlockReleaseNoInts(pThis->hSpinlock);
1076
1077 /* Report capabilities. */
1078 if ( !pIfNet
1079 && vboxNetFltTryRetainBusyNotDisconnected(pThis))
1080 {
1081 Assert(pThis->pSwitchPort);
1082 pThis->pSwitchPort->pfnReportMacAddress(pThis->pSwitchPort, &pThis->u.s.MacAddr);
1083 pThis->pSwitchPort->pfnReportPromiscuousMode(pThis->pSwitchPort, vboxNetFltDarwinIsPromiscuous(pThis));
1084 pThis->pSwitchPort->pfnReportGsoCapabilities(pThis->pSwitchPort, 0, INTNETTRUNKDIR_WIRE | INTNETTRUNKDIR_HOST);
1085 pThis->pSwitchPort->pfnReportNoPreemptDsts(pThis->pSwitchPort, 0 /* none */);
1086 vboxNetFltRelease(pThis, true /*fBusy*/);
1087 }
1088 }
1089
1090 /* Release the interface on failure. */
1091 if (pIfNet)
1092 ifnet_release(pIfNet);
1093
1094 int rc = RTErrConvertFromErrno(err);
1095 if (RT_SUCCESS(rc))
1096 LogRel(("VBoxFltDrv: attached to '%s' / %.*Rhxs\n", pThis->szName, sizeof(pThis->u.s.MacAddr), &pThis->u.s.MacAddr));
1097 else
1098 LogRel(("VBoxFltDrv: failed to attach to ifnet '%s' (err=%d)\n", pThis->szName, err));
1099 return rc;
1100}
1101
1102
1103bool vboxNetFltOsMaybeRediscovered(PVBOXNETFLTINS pThis)
1104{
1105 vboxNetFltDarwinAttachToInterface(pThis, true /* fRediscovery */);
1106 return !ASMAtomicUoReadBool(&pThis->fDisconnectedFromHost);
1107}
1108
1109
1110int vboxNetFltPortOsXmit(PVBOXNETFLTINS pThis, void *pvIfData, PINTNETSG pSG, uint32_t fDst)
1111{
1112 NOREF(pvIfData);
1113
1114 int rc = VINF_SUCCESS;
1115 ifnet_t pIfNet = vboxNetFltDarwinRetainIfNet(pThis);
1116 if (pIfNet)
1117 {
1118 /*
1119 * Create a mbuf for the gather list and push it onto the wire.
1120 *
1121 * Note! If the interface is in the promiscuous mode we need to send the
1122 * packet down the stack so it reaches the driver and Berkeley
1123 * Packet Filter (see @bugref{5817}).
1124 */
1125 if ((fDst & INTNETTRUNKDIR_WIRE) || vboxNetFltDarwinIsPromiscuous(pThis))
1126 {
1127 mbuf_t pMBuf = vboxNetFltDarwinMBufFromSG(pThis, pSG);
1128 if (pMBuf)
1129 {
1130 errno_t err = ifnet_output_raw(pIfNet, PF_LINK, pMBuf);
1131 if (err)
1132 rc = RTErrConvertFromErrno(err);
1133 }
1134 else
1135 rc = VERR_NO_MEMORY;
1136 }
1137
1138 /*
1139 * Create a mbuf for the gather list and push it onto the host stack.
1140 */
1141 if (fDst & INTNETTRUNKDIR_HOST)
1142 {
1143 mbuf_t pMBuf = vboxNetFltDarwinMBufFromSG(pThis, pSG);
1144 if (pMBuf)
1145 {
1146 /* This is what IONetworkInterface::inputPacket does. */
1147 unsigned const cbEthHdr = 14;
1148 mbuf_pkthdr_setheader(pMBuf, mbuf_data(pMBuf));
1149 mbuf_pkthdr_setlen(pMBuf, mbuf_pkthdr_len(pMBuf) - cbEthHdr);
1150 mbuf_setdata(pMBuf, (uint8_t *)mbuf_data(pMBuf) + cbEthHdr, mbuf_len(pMBuf) - cbEthHdr);
1151 mbuf_pkthdr_setrcvif(pMBuf, pIfNet); /* will crash without this. */
1152
1153 errno_t err = ifnet_input(pIfNet, pMBuf, NULL);
1154 if (err)
1155 rc = RTErrConvertFromErrno(err);
1156 }
1157 else
1158 rc = VERR_NO_MEMORY;
1159 }
1160
1161 vboxNetFltDarwinReleaseIfNet(pThis, pIfNet);
1162 }
1163
1164 return rc;
1165}
1166
1167
1168void vboxNetFltPortOsSetActive(PVBOXNETFLTINS pThis, bool fActive)
1169{
1170 ifnet_t pIfNet = vboxNetFltDarwinRetainIfNet(pThis);
1171 if (pIfNet)
1172 {
1173 if (pThis->fDisablePromiscuous)
1174 {
1175 /*
1176 * Promiscuous mode should not be used (wireless), we just need to
1177 * make sure the interface is up.
1178 */
1179 if (fActive)
1180 {
1181 u_int16_t fIf = ifnet_flags(pIfNet);
1182 if ((fIf & (IFF_UP | IFF_RUNNING)) != (IFF_UP | IFF_RUNNING))
1183 {
1184 ifnet_set_flags(pIfNet, IFF_UP, IFF_UP);
1185 ifnet_ioctl(pIfNet, 0, SIOCSIFFLAGS, NULL);
1186 }
1187 }
1188 }
1189 else
1190 {
1191 /*
1192 * This api is a bit weird, the best reference is the code.
1193 *
1194 * Also, we have a bit or race conditions wrt the maintenance of
1195 * host the interface promiscuity for vboxNetFltPortOsIsPromiscuous.
1196 */
1197 unsigned const cPromiscBefore = VBOX_GET_PCOUNT(pIfNet);
1198 u_int16_t fIf;
1199 if (fActive)
1200 {
1201 Assert(!pThis->u.s.fSetPromiscuous);
1202 errno_t err = ENETDOWN;
1203 ASMAtomicWriteBool(&pThis->u.s.fNeedSetPromiscuous, true);
1204
1205 /*
1206 * Try bring the interface up and running if it's down.
1207 */
1208 fIf = ifnet_flags(pIfNet);
1209 if ((fIf & (IFF_UP | IFF_RUNNING)) != (IFF_UP | IFF_RUNNING))
1210 {
1211 err = ifnet_set_flags(pIfNet, IFF_UP, IFF_UP);
1212 errno_t err2 = ifnet_ioctl(pIfNet, 0, SIOCSIFFLAGS, NULL);
1213 if (!err)
1214 err = err2;
1215 fIf = ifnet_flags(pIfNet);
1216 }
1217
1218 /*
1219 * Is it already up? If it isn't, leave it to the link event or
1220 * we'll upset if_pcount (as stated above, ifnet_set_promiscuous is weird).
1221 */
1222 if ((fIf & (IFF_UP | IFF_RUNNING)) == (IFF_UP | IFF_RUNNING))
1223 {
1224 err = ifnet_set_promiscuous(pIfNet, 1);
1225 pThis->u.s.fSetPromiscuous = err == 0;
1226 if (!err)
1227 {
1228 ASMAtomicWriteBool(&pThis->u.s.fNeedSetPromiscuous, false);
1229
1230 /* check if it actually worked, this stuff is not always behaving well. */
1231 if (!(ifnet_flags(pIfNet) & IFF_PROMISC))
1232 {
1233 err = ifnet_set_flags(pIfNet, IFF_PROMISC, IFF_PROMISC);
1234 if (!err)
1235 err = ifnet_ioctl(pIfNet, 0, SIOCSIFFLAGS, NULL);
1236 if (!err)
1237 Log(("vboxNetFlt: fixed IFF_PROMISC on %s (%d->%d)\n", pThis->szName, cPromiscBefore, VBOX_GET_PCOUNT(pIfNet)));
1238 else
1239 Log(("VBoxNetFlt: failed to fix IFF_PROMISC on %s, err=%d (%d->%d)\n",
1240 pThis->szName, err, cPromiscBefore, VBOX_GET_PCOUNT(pIfNet)));
1241 }
1242 }
1243 else
1244 Log(("VBoxNetFlt: ifnet_set_promiscuous -> err=%d grr! (%d->%d)\n", err, cPromiscBefore, VBOX_GET_PCOUNT(pIfNet)));
1245 }
1246 else if (!err)
1247 Log(("VBoxNetFlt: Waiting for the link to come up... (%d->%d)\n", cPromiscBefore, VBOX_GET_PCOUNT(pIfNet)));
1248 if (err)
1249 LogRel(("VBoxNetFlt: Failed to put '%s' into promiscuous mode, err=%d (%d->%d)\n", pThis->szName, err, cPromiscBefore, VBOX_GET_PCOUNT(pIfNet)));
1250 }
1251 else
1252 {
1253 ASMAtomicWriteBool(&pThis->u.s.fNeedSetPromiscuous, false);
1254 if (pThis->u.s.fSetPromiscuous)
1255 {
1256 errno_t err = ifnet_set_promiscuous(pIfNet, 0);
1257 AssertMsg(!err, ("%d\n", err)); NOREF(err);
1258 }
1259 pThis->u.s.fSetPromiscuous = false;
1260
1261 fIf = ifnet_flags(pIfNet);
1262 Log(("VBoxNetFlt: fIf=%#x; %d->%d\n", fIf, cPromiscBefore, VBOX_GET_PCOUNT(pIfNet)));
1263 }
1264 }
1265
1266 vboxNetFltDarwinReleaseIfNet(pThis, pIfNet);
1267 }
1268}
1269
1270
1271int vboxNetFltOsDisconnectIt(PVBOXNETFLTINS pThis)
1272{
1273 /* Nothing to do here. */
1274 return VINF_SUCCESS;
1275}
1276
1277
1278int vboxNetFltOsConnectIt(PVBOXNETFLTINS pThis)
1279{
1280 /* Nothing to do here. */
1281 return VINF_SUCCESS;
1282}
1283
1284
1285void vboxNetFltOsDeleteInstance(PVBOXNETFLTINS pThis)
1286{
1287 interface_filter_t pIfFilter;
1288
1289 /*
1290 * Carefully obtain the interface filter reference and detach it.
1291 */
1292 RTSpinlockAcquire(pThis->hSpinlock);
1293 pIfFilter = ASMAtomicUoReadPtrT(&pThis->u.s.pIfFilter, interface_filter_t);
1294 if (pIfFilter)
1295 ASMAtomicUoWriteNullPtr(&pThis->u.s.pIfFilter);
1296 RTSpinlockReleaseNoInts(pThis->hSpinlock);
1297
1298 if (pIfFilter)
1299 iflt_detach(pIfFilter);
1300}
1301
1302
1303int vboxNetFltOsInitInstance(PVBOXNETFLTINS pThis, void *pvContext)
1304{
1305 NOREF(pvContext);
1306 return vboxNetFltDarwinAttachToInterface(pThis, false /* fRediscovery */);
1307}
1308
1309
1310int vboxNetFltOsPreInitInstance(PVBOXNETFLTINS pThis)
1311{
1312 /*
1313 * Init the darwin specific members.
1314 */
1315 pThis->u.s.pIfNet = NULL;
1316 pThis->u.s.pIfFilter = NULL;
1317 pThis->u.s.fSetPromiscuous = false;
1318 pThis->u.s.fNeedSetPromiscuous = false;
1319 //pThis->u.s.MacAddr = {0};
1320
1321 return VINF_SUCCESS;
1322}
1323
1324
1325void vboxNetFltPortOsNotifyMacAddress(PVBOXNETFLTINS pThis, void *pvIfData, PCRTMAC pMac)
1326{
1327 NOREF(pThis); NOREF(pvIfData); NOREF(pMac);
1328}
1329
1330
1331int vboxNetFltPortOsConnectInterface(PVBOXNETFLTINS pThis, void *pvIf, void **ppvIfData)
1332{
1333 /* Nothing to do */
1334 NOREF(pThis); NOREF(pvIf); NOREF(ppvIfData);
1335 return VINF_SUCCESS;
1336}
1337
1338
1339int vboxNetFltPortOsDisconnectInterface(PVBOXNETFLTINS pThis, void *pvIfData)
1340{
1341 /* Nothing to do */
1342 NOREF(pThis); NOREF(pvIfData);
1343 return VINF_SUCCESS;
1344}
1345
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