VirtualBox

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

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

Netflt: ifnet::if_pcount offset detection for Darwin (#7279)

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