VirtualBox

source: vbox/trunk/src/VBox/Main/HostImpl.cpp@ 22294

Last change on this file since 22294 was 22211, checked in by vboxsync, 15 years ago

HostImpl: Removed the return parameter from RemoveHostOnlyNetworkInterface()
and RemoveUSBDeviceFilter() methods so as to be consistent with Main API.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 79.8 KB
Line 
1/* $Id: HostImpl.cpp 22211 2009-08-12 16:05:19Z vboxsync $ */
2/** @file
3 * VirtualBox COM class implementation: Host
4 */
5
6/*
7 * Copyright (C) 2006-2009 Sun Microsystems, Inc.
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 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
18 * Clara, CA 95054 USA or visit http://www.sun.com if you need
19 * additional information or have any questions.
20 */
21
22#define __STDC_LIMIT_MACROS
23#define __STDC_CONSTANT_MACROS
24
25#if defined(RT_OS_WINDOWS) && defined(VBOX_WITH_NETFLT)
26# include <VBox/WinNetConfig.h>
27#endif /* #if defined(RT_OS_WINDOWS) && defined(VBOX_WITH_NETFLT) */
28
29#ifdef RT_OS_LINUX
30// # include <sys/types.h>
31// # include <sys/stat.h>
32// # include <unistd.h>
33# include <sys/ioctl.h>
34// # include <fcntl.h>
35// # include <mntent.h>
36/* bird: This is a hack to work around conflicts between these linux kernel headers
37 * and the GLIBC tcpip headers. They have different declarations of the 4
38 * standard byte order functions. */
39// # define _LINUX_BYTEORDER_GENERIC_H
40// # include <linux/cdrom.h>
41# include <errno.h>
42# include <net/if.h>
43# include <net/if_arp.h>
44#endif /* RT_OS_LINUX */
45
46#ifdef RT_OS_SOLARIS
47# include <fcntl.h>
48# include <unistd.h>
49# include <stropts.h>
50# include <errno.h>
51# include <limits.h>
52# include <stdio.h>
53# ifdef VBOX_SOLARIS_NSL_RESOLVED
54# include <libdevinfo.h>
55# endif
56# include <net/if.h>
57# include <sys/socket.h>
58# include <sys/sockio.h>
59# include <net/if_arp.h>
60# include <net/if.h>
61# include <sys/types.h>
62# include <sys/stat.h>
63# include <sys/cdio.h>
64# include <sys/dkio.h>
65# include <sys/mnttab.h>
66# include <sys/mntent.h>
67/* Dynamic loading of libhal on Solaris hosts */
68# ifdef VBOX_USE_LIBHAL
69# include "vbox-libhal.h"
70extern "C" char *getfullrawname(char *);
71# endif
72# include "solaris/DynLoadLibSolaris.h"
73#endif /* RT_OS_SOLARIS */
74
75#ifdef RT_OS_WINDOWS
76# define _WIN32_DCOM
77# include <windows.h>
78# include <shellapi.h>
79# define INITGUID
80# include <guiddef.h>
81# include <devguid.h>
82# include <objbase.h>
83//# include <setupapi.h>
84# include <shlobj.h>
85# include <cfgmgr32.h>
86
87#endif /* RT_OS_WINDOWS */
88
89#ifdef RT_OS_FREEBSD
90# ifdef VBOX_USE_LIBHAL
91# include "vbox-libhal.h"
92# endif
93#endif
94
95#include "HostImpl.h"
96#include "HostDVDDriveImpl.h"
97#include "HostFloppyDriveImpl.h"
98#include "HostNetworkInterfaceImpl.h"
99#ifdef VBOX_WITH_USB
100# include "HostUSBDeviceImpl.h"
101# include "USBDeviceFilterImpl.h"
102# include "USBProxyService.h"
103#endif
104#include "VirtualBoxImpl.h"
105#include "MachineImpl.h"
106#include "Logging.h"
107#include "Performance.h"
108
109#ifdef RT_OS_DARWIN
110# include "darwin/iokit.h"
111#endif
112
113#ifdef VBOX_WITH_CROGL
114extern bool is3DAccelerationSupported();
115#endif /* VBOX_WITH_CROGL */
116
117#include <iprt/asm.h>
118#include <iprt/string.h>
119#include <iprt/mp.h>
120#include <iprt/time.h>
121#include <iprt/param.h>
122#include <iprt/env.h>
123#include <iprt/mem.h>
124#include <iprt/system.h>
125#ifdef RT_OS_SOLARIS
126# include <iprt/path.h>
127# include <iprt/ctype.h>
128#endif
129#ifdef VBOX_WITH_HOSTNETIF_API
130#include "netif.h"
131#endif
132
133#include <VBox/usb.h>
134#include <VBox/x86.h>
135#include <VBox/err.h>
136#include <VBox/settings.h>
137
138#include <stdio.h>
139
140#include <algorithm>
141
142
143
144// constructor / destructor
145/////////////////////////////////////////////////////////////////////////////
146
147HRESULT Host::FinalConstruct()
148{
149 return S_OK;
150}
151
152void Host::FinalRelease()
153{
154 uninit();
155}
156
157// public initializer/uninitializer for internal purposes only
158/////////////////////////////////////////////////////////////////////////////
159
160/**
161 * Initializes the host object.
162 *
163 * @param aParent VirtualBox parent object.
164 */
165HRESULT Host::init(VirtualBox *aParent)
166{
167 LogFlowThisFunc(("aParent=%p\n", aParent));
168
169 /* Enclose the state transition NotReady->InInit->Ready */
170 AutoInitSpan autoInitSpan(this);
171 AssertReturn(autoInitSpan.isOk(), E_FAIL);
172
173 mParent = aParent;
174
175#ifdef VBOX_WITH_USB
176 /*
177 * Create and initialize the USB Proxy Service.
178 */
179# if defined (RT_OS_DARWIN)
180 mUSBProxyService = new USBProxyServiceDarwin (this);
181# elif defined (RT_OS_LINUX)
182 mUSBProxyService = new USBProxyServiceLinux (this);
183# elif defined (RT_OS_OS2)
184 mUSBProxyService = new USBProxyServiceOs2 (this);
185# elif defined (RT_OS_SOLARIS)
186 mUSBProxyService = new USBProxyServiceSolaris (this);
187# elif defined (RT_OS_WINDOWS)
188 mUSBProxyService = new USBProxyServiceWindows (this);
189# else
190 mUSBProxyService = new USBProxyService (this);
191# endif
192 HRESULT hrc = mUSBProxyService->init();
193 AssertComRCReturn(hrc, hrc);
194#endif /* VBOX_WITH_USB */
195
196#ifdef VBOX_WITH_RESOURCE_USAGE_API
197 registerMetrics (aParent->performanceCollector());
198#endif /* VBOX_WITH_RESOURCE_USAGE_API */
199
200#if defined (RT_OS_WINDOWS)
201 mHostPowerService = new HostPowerServiceWin (mParent);
202#elif defined (RT_OS_DARWIN)
203 mHostPowerService = new HostPowerServiceDarwin (mParent);
204#else
205 mHostPowerService = new HostPowerService (mParent);
206#endif
207
208 /* Cache the features reported by GetProcessorFeature. */
209 fVTxAMDVSupported = false;
210 fLongModeSupported = false;
211 fPAESupported = false;
212
213 if (ASMHasCpuId())
214 {
215 uint32_t u32FeaturesECX;
216 uint32_t u32Dummy;
217 uint32_t u32FeaturesEDX;
218 uint32_t u32VendorEBX, u32VendorECX, u32VendorEDX, u32AMDFeatureEDX, u32AMDFeatureECX;
219
220 ASMCpuId (0, &u32Dummy, &u32VendorEBX, &u32VendorECX, &u32VendorEDX);
221 ASMCpuId (1, &u32Dummy, &u32Dummy, &u32FeaturesECX, &u32FeaturesEDX);
222 /* Query AMD features. */
223 ASMCpuId (0x80000001, &u32Dummy, &u32Dummy, &u32AMDFeatureECX, &u32AMDFeatureEDX);
224
225 fLongModeSupported = !!(u32AMDFeatureEDX & X86_CPUID_AMD_FEATURE_EDX_LONG_MODE);
226 fPAESupported = !!(u32FeaturesEDX & X86_CPUID_FEATURE_EDX_PAE);
227
228 if ( u32VendorEBX == X86_CPUID_VENDOR_INTEL_EBX
229 && u32VendorECX == X86_CPUID_VENDOR_INTEL_ECX
230 && u32VendorEDX == X86_CPUID_VENDOR_INTEL_EDX
231 )
232 {
233 if ( (u32FeaturesECX & X86_CPUID_FEATURE_ECX_VMX)
234 && (u32FeaturesEDX & X86_CPUID_FEATURE_EDX_MSR)
235 && (u32FeaturesEDX & X86_CPUID_FEATURE_EDX_FXSR)
236 )
237 fVTxAMDVSupported = true;
238 }
239 else
240 if ( u32VendorEBX == X86_CPUID_VENDOR_AMD_EBX
241 && u32VendorECX == X86_CPUID_VENDOR_AMD_ECX
242 && u32VendorEDX == X86_CPUID_VENDOR_AMD_EDX
243 )
244 {
245 if ( (u32AMDFeatureECX & X86_CPUID_AMD_FEATURE_ECX_SVM)
246 && (u32FeaturesEDX & X86_CPUID_FEATURE_EDX_MSR)
247 && (u32FeaturesEDX & X86_CPUID_FEATURE_EDX_FXSR)
248 )
249 fVTxAMDVSupported = true;
250 }
251 }
252
253 /* Test for 3D hardware acceleration support */
254 f3DAccelerationSupported = false;
255
256#ifdef VBOX_WITH_CROGL
257 f3DAccelerationSupported = is3DAccelerationSupported();
258#endif /* VBOX_WITH_CROGL */
259
260 /* Confirm a successful initialization */
261 autoInitSpan.setSucceeded();
262
263 return S_OK;
264}
265
266/**
267 * Uninitializes the host object and sets the ready flag to FALSE.
268 * Called either from FinalRelease() or by the parent when it gets destroyed.
269 */
270void Host::uninit()
271{
272 LogFlowThisFunc(("\n"));
273
274 /* Enclose the state transition Ready->InUninit->NotReady */
275 AutoUninitSpan autoUninitSpan(this);
276 if (autoUninitSpan.uninitDone())
277 return;
278
279#ifdef VBOX_WITH_RESOURCE_USAGE_API
280 unregisterMetrics (mParent->performanceCollector());
281#endif /* VBOX_WITH_RESOURCE_USAGE_API */
282
283#ifdef VBOX_WITH_USB
284 /* wait for USB proxy service to terminate before we uninit all USB
285 * devices */
286 LogFlowThisFunc(("Stopping USB proxy service...\n"));
287 delete mUSBProxyService;
288 mUSBProxyService = NULL;
289 LogFlowThisFunc(("Done stopping USB proxy service.\n"));
290#endif
291
292 delete mHostPowerService;
293
294 /* uninit all USB device filters still referenced by clients */
295 uninitDependentChildren();
296
297#ifdef VBOX_WITH_USB
298 mUSBDeviceFilters.clear();
299#endif
300}
301
302// IHost properties
303/////////////////////////////////////////////////////////////////////////////
304
305/**
306 * Returns a list of host DVD drives.
307 *
308 * @returns COM status code
309 * @param drives address of result pointer
310 */
311STDMETHODIMP Host::COMGETTER(DVDDrives) (ComSafeArrayOut(IHostDVDDrive *, aDrives))
312{
313 CheckComArgOutSafeArrayPointerValid(aDrives);
314
315 AutoCaller autoCaller(this);
316 CheckComRCReturnRC(autoCaller.rc());
317
318 AutoWriteLock alock(this);
319
320 std::list< ComObjPtr<HostDVDDrive> > list;
321 HRESULT rc = S_OK;
322 try
323 {
324#if defined(RT_OS_WINDOWS)
325 int sz = GetLogicalDriveStrings(0, NULL);
326 TCHAR *hostDrives = new TCHAR[sz+1];
327 GetLogicalDriveStrings(sz, hostDrives);
328 wchar_t driveName[3] = { '?', ':', '\0' };
329 TCHAR *p = hostDrives;
330 do
331 {
332 if (GetDriveType(p) == DRIVE_CDROM)
333 {
334 driveName[0] = *p;
335 ComObjPtr<HostDVDDrive> hostDVDDriveObj;
336 hostDVDDriveObj.createObject();
337 hostDVDDriveObj->init (Bstr (driveName));
338 list.push_back (hostDVDDriveObj);
339 }
340 p += _tcslen(p) + 1;
341 }
342 while (*p);
343 delete[] hostDrives;
344
345#elif defined(RT_OS_SOLARIS)
346# ifdef VBOX_USE_LIBHAL
347 if (!getDVDInfoFromHal(list))
348# endif
349 // Not all Solaris versions ship with libhal.
350 // So use a fallback approach similar to Linux.
351 {
352 if (RTEnvGet("VBOX_CDROM"))
353 {
354 char *cdromEnv = strdup(RTEnvGet("VBOX_CDROM"));
355 char *cdromDrive;
356 cdromDrive = strtok(cdromEnv, ":"); /** @todo use strtok_r. */
357 while (cdromDrive)
358 {
359 if (validateDevice(cdromDrive, true))
360 {
361 ComObjPtr<HostDVDDrive> hostDVDDriveObj;
362 hostDVDDriveObj.createObject();
363 hostDVDDriveObj->init (Bstr (cdromDrive));
364 list.push_back (hostDVDDriveObj);
365 }
366 cdromDrive = strtok(NULL, ":");
367 }
368 free(cdromEnv);
369 }
370 else
371 {
372 // this might work on Solaris version older than Nevada.
373 if (validateDevice("/cdrom/cdrom0", true))
374 {
375 ComObjPtr<HostDVDDrive> hostDVDDriveObj;
376 hostDVDDriveObj.createObject();
377 hostDVDDriveObj->init (Bstr ("cdrom/cdrom0"));
378 list.push_back (hostDVDDriveObj);
379 }
380
381 // check the mounted drives
382 parseMountTable(MNTTAB, list);
383 }
384 }
385
386#elif defined(RT_OS_LINUX)
387 if (RT_SUCCESS(mHostDrives.updateDVDs()))
388 for (DriveInfoList::const_iterator it = mHostDrives.DVDBegin();
389 SUCCEEDED(rc) && it != mHostDrives.DVDEnd(); ++it)
390 {
391 ComObjPtr<HostDVDDrive> hostDVDDriveObj;
392 Bstr device(it->mDevice);
393 Bstr udi(it->mUdi);
394 Bstr description(it->mDescription);
395 if (SUCCEEDED(rc))
396 rc = hostDVDDriveObj.createObject();
397 if (SUCCEEDED(rc))
398 rc = hostDVDDriveObj->init (device, udi, description);
399 if (SUCCEEDED(rc))
400 list.push_back(hostDVDDriveObj);
401 }
402#elif defined(RT_OS_DARWIN)
403 PDARWINDVD cur = DarwinGetDVDDrives();
404 while (cur)
405 {
406 ComObjPtr<HostDVDDrive> hostDVDDriveObj;
407 hostDVDDriveObj.createObject();
408 hostDVDDriveObj->init(Bstr(cur->szName));
409 list.push_back(hostDVDDriveObj);
410
411 /* next */
412 void *freeMe = cur;
413 cur = cur->pNext;
414 RTMemFree(freeMe);
415 }
416#elif defined(RT_OS_FREEBSD)
417# ifdef VBOX_USE_LIBHAL
418 if (!getDVDInfoFromHal(list))
419# endif
420 {
421 /** @todo: Scan for accessible /dev/cd* devices. */
422 }
423#else
424 /* PORTME */
425#endif
426
427 SafeIfaceArray<IHostDVDDrive> array (list);
428 array.detachTo(ComSafeArrayOutArg(aDrives));
429 }
430 catch(std::bad_alloc &)
431 {
432 rc = E_OUTOFMEMORY;
433 }
434 return rc;
435}
436
437/**
438 * Returns a list of host floppy drives.
439 *
440 * @returns COM status code
441 * @param drives address of result pointer
442 */
443STDMETHODIMP Host::COMGETTER(FloppyDrives) (ComSafeArrayOut(IHostFloppyDrive *, aDrives))
444{
445 CheckComArgOutPointerValid(aDrives);
446
447 AutoCaller autoCaller(this);
448 CheckComRCReturnRC(autoCaller.rc());
449
450 AutoWriteLock alock(this);
451
452 std::list<ComObjPtr<HostFloppyDrive> > list;
453 HRESULT rc = S_OK;
454
455 try
456 {
457#ifdef RT_OS_WINDOWS
458 int sz = GetLogicalDriveStrings(0, NULL);
459 TCHAR *hostDrives = new TCHAR[sz+1];
460 GetLogicalDriveStrings(sz, hostDrives);
461 wchar_t driveName[3] = { '?', ':', '\0' };
462 TCHAR *p = hostDrives;
463 do
464 {
465 if (GetDriveType(p) == DRIVE_REMOVABLE)
466 {
467 driveName[0] = *p;
468 ComObjPtr<HostFloppyDrive> hostFloppyDriveObj;
469 hostFloppyDriveObj.createObject();
470 hostFloppyDriveObj->init (Bstr (driveName));
471 list.push_back (hostFloppyDriveObj);
472 }
473 p += _tcslen(p) + 1;
474 }
475 while (*p);
476 delete[] hostDrives;
477#elif defined(RT_OS_LINUX)
478 if (RT_SUCCESS(mHostDrives.updateFloppies()))
479 for (DriveInfoList::const_iterator it = mHostDrives.FloppyBegin();
480 SUCCEEDED(rc) && it != mHostDrives.FloppyEnd(); ++it)
481 {
482 ComObjPtr<HostFloppyDrive> hostFloppyDriveObj;
483 Bstr device(it->mDevice);
484 Bstr udi(it->mUdi);
485 Bstr description(it->mDescription);
486 if (SUCCEEDED(rc))
487 rc = hostFloppyDriveObj.createObject();
488 if (SUCCEEDED(rc))
489 rc = hostFloppyDriveObj->init (device, udi, description);
490 if (SUCCEEDED(rc))
491 list.push_back(hostFloppyDriveObj);
492 }
493#else
494 /* PORTME */
495#endif
496
497 SafeIfaceArray<IHostFloppyDrive> collection (list);
498 collection.detachTo(ComSafeArrayOutArg(aDrives));
499 }
500 catch(std::bad_alloc &)
501 {
502 rc = E_OUTOFMEMORY;
503 }
504 return rc;
505}
506
507
508#if defined(RT_OS_WINDOWS) && defined(VBOX_WITH_NETFLT)
509# define VBOX_APP_NAME L"VirtualBox"
510
511static int vboxNetWinAddComponent(std::list <ComObjPtr<HostNetworkInterface> > * pPist, INetCfgComponent * pncc)
512{
513 LPWSTR lpszName;
514 GUID IfGuid;
515 HRESULT hr;
516 int rc = VERR_GENERAL_FAILURE;
517
518 hr = pncc->GetDisplayName( &lpszName );
519 Assert(hr == S_OK);
520 if(hr == S_OK)
521 {
522 size_t cUnicodeName = wcslen(lpszName) + 1;
523 size_t uniLen = (cUnicodeName * 2 + sizeof (OLECHAR) - 1) / sizeof (OLECHAR);
524 Bstr name (uniLen + 1 /* extra zero */);
525 wcscpy((wchar_t *) name.mutableRaw(), lpszName);
526
527 hr = pncc->GetInstanceGuid(&IfGuid);
528 Assert(hr == S_OK);
529 if (hr == S_OK)
530 {
531 /* create a new object and add it to the list */
532 ComObjPtr<HostNetworkInterface> iface;
533 iface.createObject();
534 /* remove the curly bracket at the end */
535 if (SUCCEEDED(iface->init (name, Guid (IfGuid), HostNetworkInterfaceType_Bridged)))
536 {
537// iface->setVirtualBox(mParent);
538 pPist->push_back (iface);
539 rc = VINF_SUCCESS;
540 }
541 else
542 {
543 Assert(0);
544 }
545 }
546 CoTaskMemFree(lpszName);
547 }
548
549 return rc;
550}
551#endif /* defined(RT_OS_WINDOWS) && defined(VBOX_WITH_NETFLT) */
552/**
553 * Returns a list of host network interfaces.
554 *
555 * @returns COM status code
556 * @param drives address of result pointer
557 */
558STDMETHODIMP Host::COMGETTER(NetworkInterfaces) (ComSafeArrayOut(IHostNetworkInterface *, aNetworkInterfaces))
559{
560#if defined(RT_OS_WINDOWS) || defined(VBOX_WITH_NETFLT) /*|| defined(RT_OS_OS2)*/
561 if (ComSafeArrayOutIsNull(aNetworkInterfaces))
562 return E_POINTER;
563
564 AutoCaller autoCaller(this);
565 CheckComRCReturnRC(autoCaller.rc());
566
567 AutoWriteLock alock(this);
568
569 std::list <ComObjPtr<HostNetworkInterface> > list;
570
571# ifdef VBOX_WITH_HOSTNETIF_API
572 int rc = NetIfList(list);
573 if (rc)
574 {
575 Log(("Failed to get host network interface list with rc=%Vrc\n", rc));
576 }
577# else
578
579# if defined(RT_OS_DARWIN)
580 PDARWINETHERNIC pEtherNICs = DarwinGetEthernetControllers();
581 while (pEtherNICs)
582 {
583 ComObjPtr<HostNetworkInterface> IfObj;
584 IfObj.createObject();
585 if (SUCCEEDED(IfObj->init(Bstr(pEtherNICs->szName), Guid(pEtherNICs->Uuid), HostNetworkInterfaceType_Bridged)))
586 list.push_back(IfObj);
587
588 /* next, free current */
589 void *pvFree = pEtherNICs;
590 pEtherNICs = pEtherNICs->pNext;
591 RTMemFree(pvFree);
592 }
593
594# elif defined(RT_OS_SOLARIS)
595
596# ifdef VBOX_SOLARIS_NSL_RESOLVED
597
598 /*
599 * Use libdevinfo for determining all physical interfaces.
600 */
601 di_node_t Root;
602 Root = di_init("/", DINFOCACHE);
603 if (Root != DI_NODE_NIL)
604 {
605 di_walk_minor(Root, DDI_NT_NET, 0, &list, vboxSolarisAddPhysHostIface);
606 di_fini(Root);
607 }
608
609 /*
610 * Use libdlpi for determining all DLPI interfaces.
611 */
612 if (VBoxSolarisLibDlpiFound())
613 g_pfnLibDlpiWalk(vboxSolarisAddLinkHostIface, &list, 0);
614
615# endif /* VBOX_SOLARIS_NSL_RESOLVED */
616
617 /*
618 * This gets only the list of all plumbed logical interfaces.
619 * This is needed for zones which cannot access the device tree
620 * and in this case we just let them use the list of plumbed interfaces
621 * on the zone.
622 */
623 int Sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
624 if (Sock > 0)
625 {
626 struct lifnum IfNum;
627 memset(&IfNum, 0, sizeof(IfNum));
628 IfNum.lifn_family = AF_INET;
629 int rc = ioctl(Sock, SIOCGLIFNUM, &IfNum);
630 if (!rc)
631 {
632 struct lifreq Ifaces[24];
633 struct lifconf IfConfig;
634 memset(&IfConfig, 0, sizeof(IfConfig));
635 IfConfig.lifc_family = AF_INET;
636 IfConfig.lifc_len = sizeof(Ifaces);
637 IfConfig.lifc_buf = (caddr_t)&(Ifaces[0]);
638 rc = ioctl(Sock, SIOCGLIFCONF, &IfConfig);
639 if (!rc)
640 {
641 for (int i = 0; i < IfNum.lifn_count; i++)
642 {
643 /*
644 * Skip loopback interfaces.
645 */
646 if (!strncmp(Ifaces[i].lifr_name, "lo", 2))
647 continue;
648
649#if 0
650 rc = ioctl(Sock, SIOCGLIFADDR, &(Ifaces[i]));
651 if (!rc)
652 {
653 RTMAC Mac;
654 struct arpreq ArpReq;
655 memcpy(&ArpReq.arp_pa, &Ifaces[i].lifr_addr, sizeof(struct sockaddr_in));
656
657 /*
658 * We might fail if the interface has not been assigned an IP address.
659 * That doesn't matter; as long as it's plumbed we can pick it up.
660 * But, if it has not acquired an IP address we cannot obtain it's MAC
661 * address this way, so we just use all zeros there.
662 */
663 rc = ioctl(Sock, SIOCGARP, &ArpReq);
664 if (!rc)
665 memcpy(&Mac, ArpReq.arp_ha.sa_data, sizeof(RTMAC));
666 else
667 memset(&Mac, 0, sizeof(Mac));
668
669 char szNICDesc[LIFNAMSIZ + 256];
670 char *pszIface = Ifaces[i].lifr_name;
671 strcpy(szNICDesc, pszIface);
672
673 vboxSolarisAddLinkHostIface(pszIface, &list);
674 }
675#endif
676
677 char *pszIface = Ifaces[i].lifr_name;
678 vboxSolarisAddLinkHostIface(pszIface, &list);
679 }
680 }
681 }
682 close(Sock);
683 }
684
685 /*
686 * Weed out duplicates caused by dlpi_walk inconsistencies across Nevadas.
687 */
688 list.sort(vboxSolarisSortNICList);
689 list.unique(vboxSolarisSameNIC);
690
691# elif defined RT_OS_WINDOWS
692# ifndef VBOX_WITH_NETFLT
693 hr = E_NOTIMPL;
694# else /* # if defined VBOX_WITH_NETFLT */
695 INetCfg *pNc;
696 INetCfgComponent *pMpNcc;
697 INetCfgComponent *pTcpIpNcc;
698 LPWSTR lpszApp;
699 HRESULT hr;
700 IEnumNetCfgBindingPath *pEnumBp;
701 INetCfgBindingPath *pBp;
702 IEnumNetCfgBindingInterface *pEnumBi;
703 INetCfgBindingInterface *pBi;
704
705 /* we are using the INetCfg API for getting the list of miniports */
706 hr = VBoxNetCfgWinQueryINetCfg( FALSE,
707 VBOX_APP_NAME,
708 &pNc,
709 &lpszApp );
710 Assert(hr == S_OK);
711 if(hr == S_OK)
712 {
713# ifdef VBOX_NETFLT_ONDEMAND_BIND
714 /* for the protocol-based approach for now we just get all miniports the MS_TCPIP protocol binds to */
715 hr = pNc->FindComponent(L"MS_TCPIP", &pTcpIpNcc);
716# else
717 /* for the filter-based approach we get all miniports our filter (sun_VBoxNetFlt)is bound to */
718 hr = pNc->FindComponent(L"sun_VBoxNetFlt", &pTcpIpNcc);
719# ifndef VBOX_WITH_HARDENING
720 if(hr != S_OK)
721 {
722 /* TODO: try to install the netflt from here */
723 }
724# endif
725
726# endif
727
728 if(hr == S_OK)
729 {
730 hr = VBoxNetCfgWinGetBindingPathEnum(pTcpIpNcc, EBP_BELOW, &pEnumBp);
731 Assert(hr == S_OK);
732 if ( hr == S_OK )
733 {
734 hr = VBoxNetCfgWinGetFirstBindingPath(pEnumBp, &pBp);
735 Assert(hr == S_OK || hr == S_FALSE);
736 while( hr == S_OK )
737 {
738 /* S_OK == enabled, S_FALSE == disabled */
739 if(pBp->IsEnabled() == S_OK)
740 {
741 hr = VBoxNetCfgWinGetBindingInterfaceEnum(pBp, &pEnumBi);
742 Assert(hr == S_OK);
743 if ( hr == S_OK )
744 {
745 hr = VBoxNetCfgWinGetFirstBindingInterface(pEnumBi, &pBi);
746 Assert(hr == S_OK);
747 while(hr == S_OK)
748 {
749 hr = pBi->GetLowerComponent( &pMpNcc );
750 Assert(hr == S_OK);
751 if(hr == S_OK)
752 {
753 ULONG uComponentStatus;
754 hr = pMpNcc->GetDeviceStatus(&uComponentStatus);
755 Assert(hr == S_OK);
756 if(hr == S_OK)
757 {
758 if(uComponentStatus == 0)
759 {
760 vboxNetWinAddComponent(&list, pMpNcc);
761 }
762 }
763 VBoxNetCfgWinReleaseRef( pMpNcc );
764 }
765 VBoxNetCfgWinReleaseRef(pBi);
766
767 hr = VBoxNetCfgWinGetNextBindingInterface(pEnumBi, &pBi);
768 }
769 VBoxNetCfgWinReleaseRef(pEnumBi);
770 }
771 }
772 VBoxNetCfgWinReleaseRef(pBp);
773
774 hr = VBoxNetCfgWinGetNextBindingPath(pEnumBp, &pBp);
775 }
776 VBoxNetCfgWinReleaseRef(pEnumBp);
777 }
778 VBoxNetCfgWinReleaseRef(pTcpIpNcc);
779 }
780 else
781 {
782 LogRel(("failed to get the sun_VBoxNetFlt component, error (0x%x)", hr));
783 }
784
785 VBoxNetCfgWinReleaseINetCfg(pNc, FALSE);
786 }
787# endif /* # if defined VBOX_WITH_NETFLT */
788
789
790# elif defined RT_OS_LINUX
791 int sock = socket(AF_INET, SOCK_DGRAM, 0);
792 if (sock >= 0)
793 {
794 char pBuffer[2048];
795 struct ifconf ifConf;
796 ifConf.ifc_len = sizeof(pBuffer);
797 ifConf.ifc_buf = pBuffer;
798 if (ioctl(sock, SIOCGIFCONF, &ifConf) >= 0)
799 {
800 for (struct ifreq *pReq = ifConf.ifc_req; (char*)pReq < pBuffer + ifConf.ifc_len; pReq++)
801 {
802 if (ioctl(sock, SIOCGIFHWADDR, pReq) >= 0)
803 {
804 if (pReq->ifr_hwaddr.sa_family == ARPHRD_ETHER)
805 {
806 RTUUID uuid;
807 Assert(sizeof(uuid) <= sizeof(*pReq));
808 memcpy(&uuid, pReq, sizeof(uuid));
809
810 ComObjPtr<HostNetworkInterface> IfObj;
811 IfObj.createObject();
812 if (SUCCEEDED(IfObj->init(Bstr(pReq->ifr_name), Guid(uuid), HostNetworkInterfaceType_Bridged)))
813 list.push_back(IfObj);
814 }
815 }
816 }
817 }
818 close(sock);
819 }
820# endif /* RT_OS_LINUX */
821# endif
822
823 std::list <ComObjPtr<HostNetworkInterface> >::iterator it;
824 for (it = list.begin(); it != list.end(); ++it)
825 {
826 (*it)->setVirtualBox(mParent);
827 }
828
829 SafeIfaceArray<IHostNetworkInterface> networkInterfaces (list);
830 networkInterfaces.detachTo(ComSafeArrayOutArg(aNetworkInterfaces));
831
832 return S_OK;
833
834#else
835 /* Not implemented / supported on this platform. */
836 ReturnComNotImplemented();
837#endif
838}
839
840STDMETHODIMP Host::COMGETTER(USBDevices)(ComSafeArrayOut(IHostUSBDevice *, aUSBDevices))
841{
842#ifdef VBOX_WITH_USB
843 CheckComArgOutSafeArrayPointerValid(aUSBDevices);
844
845 AutoCaller autoCaller(this);
846 CheckComRCReturnRC(autoCaller.rc());
847
848 AutoWriteLock alock(this);
849
850 MultiResult rc = checkUSBProxyService();
851 CheckComRCReturnRC(rc);
852
853 return mUSBProxyService->getDeviceCollection (ComSafeArrayOutArg(aUSBDevices));
854
855#else
856 /* Note: The GUI depends on this method returning E_NOTIMPL with no
857 * extended error info to indicate that USB is simply not available
858 * (w/o treating it as a failure), for example, as in OSE. */
859 NOREF(aUSBDevices);
860# ifndef RT_OS_WINDOWS
861 NOREF(aUSBDevicesSize);
862# endif
863 ReturnComNotImplemented();
864#endif
865}
866
867STDMETHODIMP Host::COMGETTER(USBDeviceFilters) (ComSafeArrayOut(IHostUSBDeviceFilter *, aUSBDeviceFilters))
868{
869#ifdef VBOX_WITH_USB
870 CheckComArgOutSafeArrayPointerValid(aUSBDeviceFilters);
871
872 AutoCaller autoCaller(this);
873 CheckComRCReturnRC(autoCaller.rc());
874
875 AutoWriteLock alock(this);
876
877 MultiResult rc = checkUSBProxyService();
878 CheckComRCReturnRC(rc);
879
880 SafeIfaceArray<IHostUSBDeviceFilter> collection (mUSBDeviceFilters);
881 collection.detachTo(ComSafeArrayOutArg(aUSBDeviceFilters));
882
883 return rc;
884#else
885 /* Note: The GUI depends on this method returning E_NOTIMPL with no
886 * extended error info to indicate that USB is simply not available
887 * (w/o treating it as a failure), for example, as in OSE. */
888 NOREF(aUSBDeviceFilters);
889# ifndef RT_OS_WINDOWS
890 NOREF(aUSBDeviceFiltersSize);
891# endif
892 ReturnComNotImplemented();
893#endif
894}
895
896/**
897 * Returns the number of installed logical processors
898 *
899 * @returns COM status code
900 * @param count address of result variable
901 */
902STDMETHODIMP Host::COMGETTER(ProcessorCount)(ULONG *aCount)
903{
904 CheckComArgOutPointerValid(aCount);
905// AutoCaller autoCaller(this);
906// CheckComRCReturnRC(autoCaller.rc());
907
908// AutoReadLock alock(this);
909
910 *aCount = RTMpGetPresentCount();
911 return S_OK;
912}
913
914/**
915 * Returns the number of online logical processors
916 *
917 * @returns COM status code
918 * @param count address of result variable
919 */
920STDMETHODIMP Host::COMGETTER(ProcessorOnlineCount)(ULONG *aCount)
921{
922 CheckComArgOutPointerValid(aCount);
923// AutoCaller autoCaller(this);
924// CheckComRCReturnRC(autoCaller.rc());
925
926// AutoReadLock alock(this);
927
928 *aCount = RTMpGetOnlineCount();
929 return S_OK;
930}
931
932/**
933 * Returns the (approximate) maximum speed of the given host CPU in MHz
934 *
935 * @returns COM status code
936 * @param cpu id to get info for.
937 * @param speed address of result variable, speed is 0 if unknown or aCpuId is invalid.
938 */
939STDMETHODIMP Host::GetProcessorSpeed(ULONG aCpuId, ULONG *aSpeed)
940{
941 CheckComArgOutPointerValid(aSpeed);
942// AutoCaller autoCaller(this);
943// CheckComRCReturnRC(autoCaller.rc());
944
945// AutoReadLock alock(this);
946
947 *aSpeed = RTMpGetMaxFrequency(aCpuId);
948 return S_OK;
949}
950/**
951 * Returns a description string for the host CPU
952 *
953 * @returns COM status code
954 * @param cpu id to get info for.
955 * @param description address of result variable, empty string if not known or aCpuId is invalid.
956 */
957STDMETHODIMP Host::GetProcessorDescription(ULONG aCpuId, BSTR *aDescription)
958{
959 CheckComArgOutPointerValid(aDescription);
960// AutoCaller autoCaller(this);
961// CheckComRCReturnRC(autoCaller.rc());
962
963// AutoReadLock alock(this);
964
965
966 char szCPUModel[80];
967 int vrc = RTMpGetDescription(aCpuId, szCPUModel, sizeof(szCPUModel));
968 if (RT_FAILURE(vrc))
969 return E_FAIL; /** @todo error reporting? */
970 Bstr (szCPUModel).cloneTo(aDescription);
971 return S_OK;
972}
973
974/**
975 * Returns whether a host processor feature is supported or not
976 *
977 * @returns COM status code
978 * @param Feature to query.
979 * @param address of supported bool result variable
980 */
981STDMETHODIMP Host::GetProcessorFeature(ProcessorFeature_T aFeature, BOOL *aSupported)
982{
983 CheckComArgOutPointerValid(aSupported);
984 AutoCaller autoCaller(this);
985 CheckComRCReturnRC(autoCaller.rc());
986
987 AutoReadLock alock(this);
988
989 switch (aFeature)
990 {
991 case ProcessorFeature_HWVirtEx:
992 *aSupported = fVTxAMDVSupported;
993 break;
994
995 case ProcessorFeature_PAE:
996 *aSupported = fPAESupported;
997 break;
998
999 case ProcessorFeature_LongMode:
1000 *aSupported = fLongModeSupported;
1001 break;
1002
1003 default:
1004 ReturnComNotImplemented();
1005 }
1006 return S_OK;
1007}
1008
1009/**
1010 * Returns the amount of installed system memory in megabytes
1011 *
1012 * @returns COM status code
1013 * @param size address of result variable
1014 */
1015STDMETHODIMP Host::COMGETTER(MemorySize)(ULONG *aSize)
1016{
1017 CheckComArgOutPointerValid(aSize);
1018 AutoCaller autoCaller(this);
1019 CheckComRCReturnRC(autoCaller.rc());
1020
1021 AutoWriteLock alock(this);
1022
1023 /* @todo This is an ugly hack. There must be a function in IPRT for that. */
1024 pm::CollectorHAL *hal = pm::createHAL();
1025 if (!hal)
1026 return E_FAIL;
1027 ULONG tmp;
1028 int rc = hal->getHostMemoryUsage(aSize, &tmp, &tmp);
1029 *aSize /= 1024;
1030 delete hal;
1031 return rc;
1032}
1033
1034/**
1035 * Returns the current system memory free space in megabytes
1036 *
1037 * @returns COM status code
1038 * @param available address of result variable
1039 */
1040STDMETHODIMP Host::COMGETTER(MemoryAvailable)(ULONG *aAvailable)
1041{
1042 CheckComArgOutPointerValid(aAvailable);
1043 AutoCaller autoCaller(this);
1044 CheckComRCReturnRC(autoCaller.rc());
1045
1046 AutoWriteLock alock(this);
1047
1048 /* @todo This is an ugly hack. There must be a function in IPRT for that. */
1049 pm::CollectorHAL *hal = pm::createHAL();
1050 if (!hal)
1051 return E_FAIL;
1052 ULONG tmp;
1053 int rc = hal->getHostMemoryUsage(&tmp, &tmp, aAvailable);
1054 *aAvailable /= 1024;
1055 delete hal;
1056 return rc;
1057}
1058
1059/**
1060 * Returns the name string of the host operating system
1061 *
1062 * @returns COM status code
1063 * @param os address of result variable
1064 */
1065STDMETHODIMP Host::COMGETTER(OperatingSystem)(BSTR *aOs)
1066{
1067 CheckComArgOutPointerValid(aOs);
1068// AutoCaller autoCaller(this);
1069// CheckComRCReturnRC(autoCaller.rc());
1070
1071// AutoReadLock alock(this);
1072
1073 char szOSName[80];
1074 int vrc = RTSystemQueryOSInfo(RTSYSOSINFO_PRODUCT, szOSName, sizeof(szOSName));
1075 if (RT_FAILURE(vrc))
1076 return E_FAIL; /** @todo error reporting? */
1077 Bstr (szOSName).cloneTo(aOs);
1078 return S_OK;
1079}
1080
1081/**
1082 * Returns the version string of the host operating system
1083 *
1084 * @returns COM status code
1085 * @param os address of result variable
1086 */
1087STDMETHODIMP Host::COMGETTER(OSVersion)(BSTR *aVersion)
1088{
1089 CheckComArgOutPointerValid(aVersion);
1090// AutoCaller autoCaller(this);
1091// CheckComRCReturnRC(autoCaller.rc());
1092
1093// AutoReadLock alock(this);
1094
1095 /* Get the OS release. Reserve some buffer space for the service pack. */
1096 char szOSRelease[128];
1097 int vrc = RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE, szOSRelease, sizeof(szOSRelease) - 32);
1098 if (RT_FAILURE(vrc))
1099 return E_FAIL; /** @todo error reporting? */
1100
1101 /* Append the service pack if present. */
1102 char szOSServicePack[80];
1103 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_SERVICE_PACK, szOSServicePack, sizeof(szOSServicePack));
1104 if (RT_FAILURE(vrc))
1105 {
1106 if (vrc != VERR_NOT_SUPPORTED)
1107 return E_FAIL; /** @todo error reporting? */
1108 szOSServicePack[0] = '\0';
1109 }
1110 if (szOSServicePack[0] != '\0')
1111 {
1112 char *psz = strchr(szOSRelease, '\0');
1113 RTStrPrintf(psz, &szOSRelease[sizeof(szOSRelease)] - psz, "sp%s", szOSServicePack);
1114 }
1115
1116 Bstr (szOSRelease).cloneTo(aVersion);
1117 return S_OK;
1118}
1119
1120/**
1121 * Returns the current host time in milliseconds since 1970-01-01 UTC.
1122 *
1123 * @returns COM status code
1124 * @param time address of result variable
1125 */
1126STDMETHODIMP Host::COMGETTER(UTCTime)(LONG64 *aUTCTime)
1127{
1128 CheckComArgOutPointerValid(aUTCTime);
1129// AutoCaller autoCaller(this);
1130// CheckComRCReturnRC(autoCaller.rc());
1131
1132// AutoReadLock alock(this);
1133
1134 RTTIMESPEC now;
1135 *aUTCTime = RTTimeSpecGetMilli(RTTimeNow(&now));
1136
1137 return S_OK;
1138}
1139
1140STDMETHODIMP Host::COMGETTER(Acceleration3DAvailable)(BOOL *aSupported)
1141{
1142 CheckComArgOutPointerValid(aSupported);
1143 AutoCaller autoCaller(this);
1144 CheckComRCReturnRC(autoCaller.rc());
1145
1146 AutoReadLock alock(this);
1147
1148 *aSupported = f3DAccelerationSupported;
1149
1150 return S_OK;
1151}
1152
1153// IHost methods
1154////////////////////////////////////////////////////////////////////////////////
1155STDMETHODIMP
1156Host::CreateHostOnlyNetworkInterface (IHostNetworkInterface **aHostNetworkInterface,
1157 IProgress **aProgress)
1158{
1159 CheckComArgOutPointerValid(aHostNetworkInterface);
1160 CheckComArgOutPointerValid(aProgress);
1161
1162 AutoCaller autoCaller(this);
1163 CheckComRCReturnRC(autoCaller.rc());
1164
1165 AutoWriteLock alock(this);
1166
1167 int r = NetIfCreateHostOnlyNetworkInterface (mParent, aHostNetworkInterface, aProgress);
1168 if(RT_SUCCESS(r))
1169 {
1170 return S_OK;
1171 }
1172
1173 return r == VERR_NOT_IMPLEMENTED ? E_NOTIMPL : E_FAIL;
1174}
1175
1176STDMETHODIMP
1177Host::RemoveHostOnlyNetworkInterface (IN_BSTR aId, IProgress **aProgress)
1178{
1179 CheckComArgOutPointerValid(aProgress);
1180
1181 AutoCaller autoCaller(this);
1182 CheckComRCReturnRC(autoCaller.rc());
1183
1184 AutoWriteLock alock(this);
1185
1186 /* first check whether an interface with the given name already exists */
1187 {
1188 ComPtr<IHostNetworkInterface> iface;
1189 if (FAILED (FindHostNetworkInterfaceById (aId, iface.asOutParam())))
1190 return setError (VBOX_E_OBJECT_NOT_FOUND,
1191 tr ("Host network interface with UUID {%RTuuid} does not exist"),
1192 Guid (aId).raw());
1193 }
1194
1195 int r = NetIfRemoveHostOnlyNetworkInterface (mParent, Guid(aId), aProgress);
1196 if(RT_SUCCESS(r))
1197 {
1198 return S_OK;
1199 }
1200
1201 return r == VERR_NOT_IMPLEMENTED ? E_NOTIMPL : E_FAIL;
1202}
1203
1204STDMETHODIMP Host::CreateUSBDeviceFilter (IN_BSTR aName, IHostUSBDeviceFilter **aFilter)
1205{
1206#ifdef VBOX_WITH_USB
1207 CheckComArgStrNotEmptyOrNull(aName);
1208 CheckComArgOutPointerValid(aFilter);
1209
1210 AutoCaller autoCaller(this);
1211 CheckComRCReturnRC(autoCaller.rc());
1212
1213 AutoWriteLock alock(this);
1214
1215 ComObjPtr<HostUSBDeviceFilter> filter;
1216 filter.createObject();
1217 HRESULT rc = filter->init (this, aName);
1218 ComAssertComRCRet (rc, rc);
1219 rc = filter.queryInterfaceTo(aFilter);
1220 AssertComRCReturn (rc, rc);
1221 return S_OK;
1222#else
1223 /* Note: The GUI depends on this method returning E_NOTIMPL with no
1224 * extended error info to indicate that USB is simply not available
1225 * (w/o treating it as a failure), for example, as in OSE. */
1226 NOREF(aName);
1227 NOREF(aFilter);
1228 ReturnComNotImplemented();
1229#endif
1230}
1231
1232STDMETHODIMP Host::InsertUSBDeviceFilter (ULONG aPosition, IHostUSBDeviceFilter *aFilter)
1233{
1234#ifdef VBOX_WITH_USB
1235 CheckComArgNotNull(aFilter);
1236
1237 /* Note: HostUSBDeviceFilter and USBProxyService also uses this lock. */
1238 AutoCaller autoCaller(this);
1239 CheckComRCReturnRC(autoCaller.rc());
1240
1241 AutoWriteLock alock(this);
1242
1243 MultiResult rc = checkUSBProxyService();
1244 CheckComRCReturnRC(rc);
1245
1246 ComObjPtr<HostUSBDeviceFilter> filter = getDependentChild (aFilter);
1247 if (!filter)
1248 return setError (VBOX_E_INVALID_OBJECT_STATE,
1249 tr ("The given USB device filter is not created within "
1250 "this VirtualBox instance"));
1251
1252 if (filter->mInList)
1253 return setError (E_INVALIDARG,
1254 tr ("The given USB device filter is already in the list"));
1255
1256 /* iterate to the position... */
1257 USBDeviceFilterList::iterator it = mUSBDeviceFilters.begin();
1258 std::advance (it, aPosition);
1259 /* ...and insert */
1260 mUSBDeviceFilters.insert (it, filter);
1261 filter->mInList = true;
1262
1263 /* notify the proxy (only when the filter is active) */
1264 if (mUSBProxyService->isActive() && filter->data().mActive)
1265 {
1266 ComAssertRet (filter->id() == NULL, E_FAIL);
1267 filter->id() = mUSBProxyService->insertFilter (&filter->data().mUSBFilter);
1268 }
1269
1270 /* save the global settings */
1271 alock.unlock();
1272 return rc = mParent->saveSettings();
1273#else
1274 /* Note: The GUI depends on this method returning E_NOTIMPL with no
1275 * extended error info to indicate that USB is simply not available
1276 * (w/o treating it as a failure), for example, as in OSE. */
1277 NOREF(aPosition);
1278 NOREF(aFilter);
1279 ReturnComNotImplemented();
1280#endif
1281}
1282
1283STDMETHODIMP Host::RemoveUSBDeviceFilter (ULONG aPosition)
1284{
1285#ifdef VBOX_WITH_USB
1286
1287 /* Note: HostUSBDeviceFilter and USBProxyService also uses this lock. */
1288 AutoCaller autoCaller(this);
1289 CheckComRCReturnRC(autoCaller.rc());
1290
1291 AutoWriteLock alock(this);
1292
1293 MultiResult rc = checkUSBProxyService();
1294 CheckComRCReturnRC(rc);
1295
1296 if (!mUSBDeviceFilters.size())
1297 return setError (E_INVALIDARG,
1298 tr ("The USB device filter list is empty"));
1299
1300 if (aPosition >= mUSBDeviceFilters.size())
1301 return setError (E_INVALIDARG,
1302 tr ("Invalid position: %lu (must be in range [0, %lu])"),
1303 aPosition, mUSBDeviceFilters.size() - 1);
1304
1305 ComObjPtr<HostUSBDeviceFilter> filter;
1306 {
1307 /* iterate to the position... */
1308 USBDeviceFilterList::iterator it = mUSBDeviceFilters.begin();
1309 std::advance (it, aPosition);
1310 /* ...get an element from there... */
1311 filter = *it;
1312 /* ...and remove */
1313 filter->mInList = false;
1314 mUSBDeviceFilters.erase (it);
1315 }
1316
1317 /* notify the proxy (only when the filter is active) */
1318 if (mUSBProxyService->isActive() && filter->data().mActive)
1319 {
1320 ComAssertRet (filter->id() != NULL, E_FAIL);
1321 mUSBProxyService->removeFilter (filter->id());
1322 filter->id() = NULL;
1323 }
1324
1325 /* save the global settings */
1326 alock.unlock();
1327 return rc = mParent->saveSettings();
1328#else
1329 /* Note: The GUI depends on this method returning E_NOTIMPL with no
1330 * extended error info to indicate that USB is simply not available
1331 * (w/o treating it as a failure), for example, as in OSE. */
1332 NOREF(aPosition);
1333 ReturnComNotImplemented();
1334#endif
1335}
1336
1337// public methods only for internal purposes
1338////////////////////////////////////////////////////////////////////////////////
1339
1340HRESULT Host::loadSettings(const settings::Host &data)
1341{
1342 AutoCaller autoCaller(this);
1343 CheckComRCReturnRC(autoCaller.rc());
1344
1345 AutoWriteLock alock(this);
1346
1347 HRESULT rc = S_OK;
1348
1349#ifdef VBOX_WITH_USB
1350 for (settings::USBDeviceFiltersList::const_iterator it = data.llUSBDeviceFilters.begin();
1351 it != data.llUSBDeviceFilters.end();
1352 ++it)
1353 {
1354 const settings::USBDeviceFilter &f = *it;
1355 ComObjPtr<HostUSBDeviceFilter> pFilter;
1356 pFilter.createObject();
1357 rc = pFilter->init(this, f);
1358 CheckComRCBreakRC (rc);
1359
1360 mUSBDeviceFilters.push_back(pFilter);
1361 pFilter->mInList = true;
1362
1363 /* notify the proxy (only when the filter is active) */
1364 if (pFilter->data().mActive)
1365 {
1366 HostUSBDeviceFilter *flt = pFilter; /* resolve ambiguity */
1367 flt->id() = mUSBProxyService->insertFilter(&pFilter->data().mUSBFilter);
1368 }
1369 }
1370#endif /* VBOX_WITH_USB */
1371
1372 return rc;
1373}
1374
1375HRESULT Host::saveSettings(settings::Host &data)
1376{
1377 AutoCaller autoCaller(this);
1378 CheckComRCReturnRC(autoCaller.rc());
1379
1380 AutoWriteLock alock(this);
1381
1382#ifdef VBOX_WITH_USB
1383 data.llUSBDeviceFilters.clear();
1384
1385 for (USBDeviceFilterList::const_iterator it = mUSBDeviceFilters.begin();
1386 it != mUSBDeviceFilters.end();
1387 ++it)
1388 {
1389 ComObjPtr<HostUSBDeviceFilter> pFilter = *it;
1390 settings::USBDeviceFilter f;
1391 pFilter->saveSettings(f);
1392 data.llUSBDeviceFilters.push_back(f);
1393 }
1394#endif /* VBOX_WITH_USB */
1395
1396 return S_OK;
1397}
1398
1399#ifdef VBOX_WITH_USB
1400/**
1401 * Called by setter methods of all USB device filters.
1402 */
1403HRESULT Host::onUSBDeviceFilterChange (HostUSBDeviceFilter *aFilter,
1404 BOOL aActiveChanged /* = FALSE */)
1405{
1406 AutoCaller autoCaller(this);
1407 CheckComRCReturnRC(autoCaller.rc());
1408
1409 AutoWriteLock alock(this);
1410
1411 if (aFilter->mInList)
1412 {
1413 if (aActiveChanged)
1414 {
1415 // insert/remove the filter from the proxy
1416 if (aFilter->data().mActive)
1417 {
1418 ComAssertRet (aFilter->id() == NULL, E_FAIL);
1419 aFilter->id() = mUSBProxyService->insertFilter (&aFilter->data().mUSBFilter);
1420 }
1421 else
1422 {
1423 ComAssertRet (aFilter->id() != NULL, E_FAIL);
1424 mUSBProxyService->removeFilter (aFilter->id());
1425 aFilter->id() = NULL;
1426 }
1427 }
1428 else
1429 {
1430 if (aFilter->data().mActive)
1431 {
1432 // update the filter in the proxy
1433 ComAssertRet (aFilter->id() != NULL, E_FAIL);
1434 mUSBProxyService->removeFilter (aFilter->id());
1435 aFilter->id() = mUSBProxyService->insertFilter (&aFilter->data().mUSBFilter);
1436 }
1437 }
1438
1439 // save the global settings... yeah, on every single filter property change
1440 alock.unlock();
1441 return mParent->saveSettings();
1442 }
1443
1444 return S_OK;
1445}
1446
1447
1448/**
1449 * Interface for obtaining a copy of the USBDeviceFilterList,
1450 * used by the USBProxyService.
1451 *
1452 * @param aGlobalFilters Where to put the global filter list copy.
1453 * @param aMachines Where to put the machine vector.
1454 */
1455void Host::getUSBFilters(Host::USBDeviceFilterList *aGlobalFilters, VirtualBox::SessionMachineVector *aMachines)
1456{
1457 AutoWriteLock alock(this);
1458
1459 mParent->getOpenedMachines (*aMachines);
1460 *aGlobalFilters = mUSBDeviceFilters;
1461}
1462
1463#endif /* VBOX_WITH_USB */
1464
1465// private methods
1466////////////////////////////////////////////////////////////////////////////////
1467
1468#if (defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)) && defined(VBOX_USE_LIBHAL)
1469/* Solaris and FreeBSD hosts, loading libhal at runtime */
1470
1471/**
1472 * Helper function to query the hal subsystem for information about DVD drives attached to the
1473 * system.
1474 *
1475 * @returns true if information was successfully obtained, false otherwise
1476 * @retval list drives found will be attached to this list
1477 */
1478bool Host::getDVDInfoFromHal(std::list <ComObjPtr<HostDVDDrive> > &list)
1479{
1480 bool halSuccess = false;
1481 DBusError dbusError;
1482 if (!gLibHalCheckPresence())
1483 return false;
1484 gDBusErrorInit (&dbusError);
1485 DBusConnection *dbusConnection = gDBusBusGet(DBUS_BUS_SYSTEM, &dbusError);
1486 if (dbusConnection != 0)
1487 {
1488 LibHalContext *halContext = gLibHalCtxNew();
1489 if (halContext != 0)
1490 {
1491 if (gLibHalCtxSetDBusConnection (halContext, dbusConnection))
1492 {
1493 if (gLibHalCtxInit(halContext, &dbusError))
1494 {
1495 int numDevices;
1496 char **halDevices = gLibHalFindDeviceStringMatch(halContext,
1497 "storage.drive_type", "cdrom",
1498 &numDevices, &dbusError);
1499 if (halDevices != 0)
1500 {
1501 /* Hal is installed and working, so if no devices are reported, assume
1502 that there are none. */
1503 halSuccess = true;
1504 for (int i = 0; i < numDevices; i++)
1505 {
1506 char *devNode = gLibHalDeviceGetPropertyString(halContext,
1507 halDevices[i], "block.device", &dbusError);
1508#ifdef RT_OS_SOLARIS
1509 /* The CD/DVD ioctls work only for raw device nodes. */
1510 char *tmp = getfullrawname(devNode);
1511 gLibHalFreeString(devNode);
1512 devNode = tmp;
1513#endif
1514
1515#ifdef RT_OS_FREEBSD
1516 /*
1517 * Don't show devices handled by the 'acd' driver.
1518 * The ioctls don't work with it.
1519 */
1520 char *driverName = gLibHalDeviceGetPropertyString(halContext,
1521 halDevices[i], "freebsd.driver", &dbusError);
1522 if (driverName)
1523 {
1524 if (RTStrCmp(driverName, "acd") == 0)
1525 {
1526 gLibHalFreeString(devNode);
1527 devNode = NULL;
1528 }
1529 gLibHalFreeString(driverName);
1530 }
1531#endif
1532
1533 if (devNode != 0)
1534 {
1535// if (validateDevice(devNode, true))
1536// {
1537 Utf8Str description;
1538 char *vendor, *product;
1539 /* We do not check the error here, as this field may
1540 not even exist. */
1541 vendor = gLibHalDeviceGetPropertyString(halContext,
1542 halDevices[i], "info.vendor", 0);
1543 product = gLibHalDeviceGetPropertyString(halContext,
1544 halDevices[i], "info.product", &dbusError);
1545 if ((product != 0 && product[0] != 0))
1546 {
1547 if ((vendor != 0) && (vendor[0] != 0))
1548 {
1549 description = Utf8StrFmt ("%s %s",
1550 vendor, product);
1551 }
1552 else
1553 {
1554 description = product;
1555 }
1556 ComObjPtr<HostDVDDrive> hostDVDDriveObj;
1557 hostDVDDriveObj.createObject();
1558 hostDVDDriveObj->init (Bstr (devNode),
1559 Bstr (halDevices[i]),
1560 Bstr (description));
1561 list.push_back (hostDVDDriveObj);
1562 }
1563 else
1564 {
1565 if (product == 0)
1566 {
1567 LogRel(("Host::COMGETTER(DVDDrives): failed to get property \"info.product\" for device %s. dbus error: %s (%s)\n",
1568 halDevices[i], dbusError.name, dbusError.message));
1569 gDBusErrorFree(&dbusError);
1570 }
1571 ComObjPtr<HostDVDDrive> hostDVDDriveObj;
1572 hostDVDDriveObj.createObject();
1573 hostDVDDriveObj->init (Bstr (devNode),
1574 Bstr (halDevices[i]));
1575 list.push_back (hostDVDDriveObj);
1576 }
1577 if (vendor != 0)
1578 {
1579 gLibHalFreeString(vendor);
1580 }
1581 if (product != 0)
1582 {
1583 gLibHalFreeString(product);
1584 }
1585// }
1586// else
1587// {
1588// LogRel(("Host::COMGETTER(DVDDrives): failed to validate the block device %s as a DVD drive\n"));
1589// }
1590#ifndef RT_OS_SOLARIS
1591 gLibHalFreeString(devNode);
1592#else
1593 free(devNode);
1594#endif
1595 }
1596 else
1597 {
1598 LogRel(("Host::COMGETTER(DVDDrives): failed to get property \"block.device\" for device %s. dbus error: %s (%s)\n",
1599 halDevices[i], dbusError.name, dbusError.message));
1600 gDBusErrorFree(&dbusError);
1601 }
1602 }
1603 gLibHalFreeStringArray(halDevices);
1604 }
1605 else
1606 {
1607 LogRel(("Host::COMGETTER(DVDDrives): failed to get devices with capability \"storage.cdrom\". dbus error: %s (%s)\n", dbusError.name, dbusError.message));
1608 gDBusErrorFree(&dbusError);
1609 }
1610 if (!gLibHalCtxShutdown(halContext, &dbusError)) /* what now? */
1611 {
1612 LogRel(("Host::COMGETTER(DVDDrives): failed to shutdown the libhal context. dbus error: %s (%s)\n", dbusError.name, dbusError.message));
1613 gDBusErrorFree(&dbusError);
1614 }
1615 }
1616 else
1617 {
1618 LogRel(("Host::COMGETTER(DVDDrives): failed to initialise libhal context. dbus error: %s (%s)\n", dbusError.name, dbusError.message));
1619 gDBusErrorFree(&dbusError);
1620 }
1621 gLibHalCtxFree(halContext);
1622 }
1623 else
1624 {
1625 LogRel(("Host::COMGETTER(DVDDrives): failed to set libhal connection to dbus.\n"));
1626 }
1627 }
1628 else
1629 {
1630 LogRel(("Host::COMGETTER(DVDDrives): failed to get a libhal context - out of memory?\n"));
1631 }
1632 gDBusConnectionUnref(dbusConnection);
1633 }
1634 else
1635 {
1636 LogRel(("Host::COMGETTER(DVDDrives): failed to connect to dbus. dbus error: %s (%s)\n", dbusError.name, dbusError.message));
1637 gDBusErrorFree(&dbusError);
1638 }
1639 return halSuccess;
1640}
1641
1642
1643/**
1644 * Helper function to query the hal subsystem for information about floppy drives attached to the
1645 * system.
1646 *
1647 * @returns true if information was successfully obtained, false otherwise
1648 * @retval list drives found will be attached to this list
1649 */
1650bool Host::getFloppyInfoFromHal(std::list <ComObjPtr<HostFloppyDrive> > &list)
1651{
1652 bool halSuccess = false;
1653 DBusError dbusError;
1654 if (!gLibHalCheckPresence())
1655 return false;
1656 gDBusErrorInit (&dbusError);
1657 DBusConnection *dbusConnection = gDBusBusGet(DBUS_BUS_SYSTEM, &dbusError);
1658 if (dbusConnection != 0)
1659 {
1660 LibHalContext *halContext = gLibHalCtxNew();
1661 if (halContext != 0)
1662 {
1663 if (gLibHalCtxSetDBusConnection (halContext, dbusConnection))
1664 {
1665 if (gLibHalCtxInit(halContext, &dbusError))
1666 {
1667 int numDevices;
1668 char **halDevices = gLibHalFindDeviceStringMatch(halContext,
1669 "storage.drive_type", "floppy",
1670 &numDevices, &dbusError);
1671 if (halDevices != 0)
1672 {
1673 /* Hal is installed and working, so if no devices are reported, assume
1674 that there are none. */
1675 halSuccess = true;
1676 for (int i = 0; i < numDevices; i++)
1677 {
1678 char *driveType = gLibHalDeviceGetPropertyString(halContext,
1679 halDevices[i], "storage.drive_type", 0);
1680 if (driveType != 0)
1681 {
1682 if (strcmp(driveType, "floppy") != 0)
1683 {
1684 gLibHalFreeString(driveType);
1685 continue;
1686 }
1687 gLibHalFreeString(driveType);
1688 }
1689 else
1690 {
1691 /* An error occurred. The attribute "storage.drive_type"
1692 probably didn't exist. */
1693 continue;
1694 }
1695 char *devNode = gLibHalDeviceGetPropertyString(halContext,
1696 halDevices[i], "block.device", &dbusError);
1697 if (devNode != 0)
1698 {
1699// if (validateDevice(devNode, false))
1700// {
1701 Utf8Str description;
1702 char *vendor, *product;
1703 /* We do not check the error here, as this field may
1704 not even exist. */
1705 vendor = gLibHalDeviceGetPropertyString(halContext,
1706 halDevices[i], "info.vendor", 0);
1707 product = gLibHalDeviceGetPropertyString(halContext,
1708 halDevices[i], "info.product", &dbusError);
1709 if ((product != 0) && (product[0] != 0))
1710 {
1711 if ((vendor != 0) && (vendor[0] != 0))
1712 {
1713 description = Utf8StrFmt ("%s %s",
1714 vendor, product);
1715 }
1716 else
1717 {
1718 description = product;
1719 }
1720 ComObjPtr<HostFloppyDrive> hostFloppyDrive;
1721 hostFloppyDrive.createObject();
1722 hostFloppyDrive->init (Bstr (devNode),
1723 Bstr (halDevices[i]),
1724 Bstr (description));
1725 list.push_back (hostFloppyDrive);
1726 }
1727 else
1728 {
1729 if (product == 0)
1730 {
1731 LogRel(("Host::COMGETTER(FloppyDrives): failed to get property \"info.product\" for device %s. dbus error: %s (%s)\n",
1732 halDevices[i], dbusError.name, dbusError.message));
1733 gDBusErrorFree(&dbusError);
1734 }
1735 ComObjPtr<HostFloppyDrive> hostFloppyDrive;
1736 hostFloppyDrive.createObject();
1737 hostFloppyDrive->init (Bstr (devNode),
1738 Bstr (halDevices[i]));
1739 list.push_back (hostFloppyDrive);
1740 }
1741 if (vendor != 0)
1742 {
1743 gLibHalFreeString(vendor);
1744 }
1745 if (product != 0)
1746 {
1747 gLibHalFreeString(product);
1748 }
1749// }
1750// else
1751// {
1752// LogRel(("Host::COMGETTER(FloppyDrives): failed to validate the block device %s as a floppy drive\n"));
1753// }
1754 gLibHalFreeString(devNode);
1755 }
1756 else
1757 {
1758 LogRel(("Host::COMGETTER(FloppyDrives): failed to get property \"block.device\" for device %s. dbus error: %s (%s)\n",
1759 halDevices[i], dbusError.name, dbusError.message));
1760 gDBusErrorFree(&dbusError);
1761 }
1762 }
1763 gLibHalFreeStringArray(halDevices);
1764 }
1765 else
1766 {
1767 LogRel(("Host::COMGETTER(FloppyDrives): failed to get devices with capability \"storage.cdrom\". dbus error: %s (%s)\n", dbusError.name, dbusError.message));
1768 gDBusErrorFree(&dbusError);
1769 }
1770 if (!gLibHalCtxShutdown(halContext, &dbusError)) /* what now? */
1771 {
1772 LogRel(("Host::COMGETTER(FloppyDrives): failed to shutdown the libhal context. dbus error: %s (%s)\n", dbusError.name, dbusError.message));
1773 gDBusErrorFree(&dbusError);
1774 }
1775 }
1776 else
1777 {
1778 LogRel(("Host::COMGETTER(FloppyDrives): failed to initialise libhal context. dbus error: %s (%s)\n", dbusError.name, dbusError.message));
1779 gDBusErrorFree(&dbusError);
1780 }
1781 gLibHalCtxFree(halContext);
1782 }
1783 else
1784 {
1785 LogRel(("Host::COMGETTER(FloppyDrives): failed to set libhal connection to dbus.\n"));
1786 }
1787 }
1788 else
1789 {
1790 LogRel(("Host::COMGETTER(FloppyDrives): failed to get a libhal context - out of memory?\n"));
1791 }
1792 gDBusConnectionUnref(dbusConnection);
1793 }
1794 else
1795 {
1796 LogRel(("Host::COMGETTER(FloppyDrives): failed to connect to dbus. dbus error: %s (%s)\n", dbusError.name, dbusError.message));
1797 gDBusErrorFree(&dbusError);
1798 }
1799 return halSuccess;
1800}
1801#endif /* RT_OS_SOLARIS and VBOX_USE_HAL */
1802
1803#if defined(RT_OS_SOLARIS)
1804
1805/**
1806 * Helper function to parse the given mount file and add found entries
1807 */
1808void Host::parseMountTable(char *mountTable, std::list <ComObjPtr<HostDVDDrive> > &list)
1809{
1810#ifdef RT_OS_LINUX
1811 FILE *mtab = setmntent(mountTable, "r");
1812 if (mtab)
1813 {
1814 struct mntent *mntent;
1815 char *mnt_type;
1816 char *mnt_dev;
1817 char *tmp;
1818 while ((mntent = getmntent(mtab)))
1819 {
1820 mnt_type = (char*)malloc(strlen(mntent->mnt_type) + 1);
1821 mnt_dev = (char*)malloc(strlen(mntent->mnt_fsname) + 1);
1822 strcpy(mnt_type, mntent->mnt_type);
1823 strcpy(mnt_dev, mntent->mnt_fsname);
1824 // supermount fs case
1825 if (strcmp(mnt_type, "supermount") == 0)
1826 {
1827 tmp = strstr(mntent->mnt_opts, "fs=");
1828 if (tmp)
1829 {
1830 free(mnt_type);
1831 mnt_type = strdup(tmp + strlen("fs="));
1832 if (mnt_type)
1833 {
1834 tmp = strchr(mnt_type, ',');
1835 if (tmp)
1836 *tmp = '\0';
1837 }
1838 }
1839 tmp = strstr(mntent->mnt_opts, "dev=");
1840 if (tmp)
1841 {
1842 free(mnt_dev);
1843 mnt_dev = strdup(tmp + strlen("dev="));
1844 if (mnt_dev)
1845 {
1846 tmp = strchr(mnt_dev, ',');
1847 if (tmp)
1848 *tmp = '\0';
1849 }
1850 }
1851 }
1852 // use strstr here to cover things fs types like "udf,iso9660"
1853 if (strstr(mnt_type, "iso9660") == 0)
1854 {
1855 /** @todo check whether we've already got the drive in our list! */
1856 if (validateDevice(mnt_dev, true))
1857 {
1858 ComObjPtr<HostDVDDrive> hostDVDDriveObj;
1859 hostDVDDriveObj.createObject();
1860 hostDVDDriveObj->init (Bstr (mnt_dev));
1861 list.push_back (hostDVDDriveObj);
1862 }
1863 }
1864 free(mnt_dev);
1865 free(mnt_type);
1866 }
1867 endmntent(mtab);
1868 }
1869#else // RT_OS_SOLARIS
1870 FILE *mntFile = fopen(mountTable, "r");
1871 if (mntFile)
1872 {
1873 struct mnttab mntTab;
1874 while (getmntent(mntFile, &mntTab) == 0)
1875 {
1876 char *mountName = strdup(mntTab.mnt_special);
1877 char *mountPoint = strdup(mntTab.mnt_mountp);
1878 char *mountFSType = strdup(mntTab.mnt_fstype);
1879
1880 // skip devices we are not interested in
1881 if ((*mountName && mountName[0] == '/') && // skip 'fake' devices (like -hosts, proc, fd, swap)
1882 (*mountFSType && (strcmp(mountFSType, "devfs") != 0 && // skip devfs (i.e. /devices)
1883 strcmp(mountFSType, "dev") != 0 && // skip dev (i.e. /dev)
1884 strcmp(mountFSType, "lofs") != 0)) && // skip loop-back file-system (lofs)
1885 (*mountPoint && strcmp(mountPoint, "/") != 0)) // skip point '/' (Can CD/DVD be mounted at '/' ???)
1886 {
1887 char *rawDevName = getfullrawname(mountName);
1888 if (validateDevice(rawDevName, true))
1889 {
1890 ComObjPtr<HostDVDDrive> hostDVDDriveObj;
1891 hostDVDDriveObj.createObject();
1892 hostDVDDriveObj->init (Bstr (rawDevName));
1893 list.push_back (hostDVDDriveObj);
1894 }
1895 free(rawDevName);
1896 }
1897
1898 free(mountName);
1899 free(mountPoint);
1900 free(mountFSType);
1901 }
1902
1903 fclose(mntFile);
1904 }
1905#endif
1906}
1907
1908/**
1909 * Helper function to check whether the given device node is a valid drive
1910 */
1911bool Host::validateDevice(const char *deviceNode, bool isCDROM)
1912{
1913 struct stat statInfo;
1914 bool retValue = false;
1915
1916 // sanity check
1917 if (!deviceNode)
1918 {
1919 return false;
1920 }
1921
1922 // first a simple stat() call
1923 if (stat(deviceNode, &statInfo) < 0)
1924 {
1925 return false;
1926 } else
1927 {
1928 if (isCDROM)
1929 {
1930 if (S_ISCHR(statInfo.st_mode) || S_ISBLK(statInfo.st_mode))
1931 {
1932 int fileHandle;
1933 // now try to open the device
1934 fileHandle = open(deviceNode, O_RDONLY | O_NONBLOCK, 0);
1935 if (fileHandle >= 0)
1936 {
1937 cdrom_subchnl cdChannelInfo;
1938 cdChannelInfo.cdsc_format = CDROM_MSF;
1939 // this call will finally reveal the whole truth
1940#ifdef RT_OS_LINUX
1941 if ((ioctl(fileHandle, CDROMSUBCHNL, &cdChannelInfo) == 0) ||
1942 (errno == EIO) || (errno == ENOENT) ||
1943 (errno == EINVAL) || (errno == ENOMEDIUM))
1944#else
1945 if ((ioctl(fileHandle, CDROMSUBCHNL, &cdChannelInfo) == 0) ||
1946 (errno == EIO) || (errno == ENOENT) ||
1947 (errno == EINVAL))
1948#endif
1949 {
1950 retValue = true;
1951 }
1952 close(fileHandle);
1953 }
1954 }
1955 } else
1956 {
1957 // floppy case
1958 if (S_ISCHR(statInfo.st_mode) || S_ISBLK(statInfo.st_mode))
1959 {
1960 /// @todo do some more testing, maybe a nice IOCTL!
1961 retValue = true;
1962 }
1963 }
1964 }
1965 return retValue;
1966}
1967#endif // RT_OS_SOLARIS
1968
1969#ifdef VBOX_WITH_USB
1970/**
1971 * Checks for the presense and status of the USB Proxy Service.
1972 * Returns S_OK when the Proxy is present and OK, VBOX_E_HOST_ERROR (as a
1973 * warning) if the proxy service is not available due to the way the host is
1974 * configured (at present, that means that usbfs and hal/DBus are not
1975 * available on a Linux host) or E_FAIL and a corresponding error message
1976 * otherwise. Intended to be used by methods that rely on the Proxy Service
1977 * availability.
1978 *
1979 * @note This method may return a warning result code. It is recommended to use
1980 * MultiError to store the return value.
1981 *
1982 * @note Locks this object for reading.
1983 */
1984HRESULT Host::checkUSBProxyService()
1985{
1986 AutoCaller autoCaller(this);
1987 CheckComRCReturnRC(autoCaller.rc());
1988
1989 AutoWriteLock alock(this);
1990
1991 AssertReturn(mUSBProxyService, E_FAIL);
1992 if (!mUSBProxyService->isActive())
1993 {
1994 /* disable the USB controller completely to avoid assertions if the
1995 * USB proxy service could not start. */
1996
1997 if (mUSBProxyService->getLastError() == VERR_FILE_NOT_FOUND)
1998 return setWarning (E_FAIL,
1999 tr ("Could not load the Host USB Proxy Service (%Rrc). "
2000 "The service might not be installed on the host computer"),
2001 mUSBProxyService->getLastError());
2002 if (mUSBProxyService->getLastError() == VINF_SUCCESS)
2003#ifdef RT_OS_LINUX
2004 return setWarning (VBOX_E_HOST_ERROR,
2005# ifdef VBOX_WITH_DBUS
2006 tr ("The USB Proxy Service could not be started, because neither the USB file system (usbfs) nor the hardware information service (hal) is available")
2007# else
2008 tr ("The USB Proxy Service could not be started, because the USB file system (usbfs) is not available")
2009# endif
2010 );
2011#else /* !RT_OS_LINUX */
2012 return setWarning (E_FAIL,
2013 tr ("The USB Proxy Service has not yet been ported to this host"));
2014#endif /* !RT_OS_LINUX */
2015 return setWarning (E_FAIL,
2016 tr ("Could not load the Host USB Proxy service (%Rrc)"),
2017 mUSBProxyService->getLastError());
2018 }
2019
2020 return S_OK;
2021}
2022#endif /* VBOX_WITH_USB */
2023
2024#ifdef VBOX_WITH_RESOURCE_USAGE_API
2025void Host::registerMetrics (PerformanceCollector *aCollector)
2026{
2027 pm::CollectorHAL *hal = aCollector->getHAL();
2028 /* Create sub metrics */
2029 pm::SubMetric *cpuLoadUser = new pm::SubMetric ("CPU/Load/User",
2030 "Percentage of processor time spent in user mode.");
2031 pm::SubMetric *cpuLoadKernel = new pm::SubMetric ("CPU/Load/Kernel",
2032 "Percentage of processor time spent in kernel mode.");
2033 pm::SubMetric *cpuLoadIdle = new pm::SubMetric ("CPU/Load/Idle",
2034 "Percentage of processor time spent idling.");
2035 pm::SubMetric *cpuMhzSM = new pm::SubMetric ("CPU/MHz",
2036 "Average of current frequency of all processors.");
2037 pm::SubMetric *ramUsageTotal = new pm::SubMetric ("RAM/Usage/Total",
2038 "Total physical memory installed.");
2039 pm::SubMetric *ramUsageUsed = new pm::SubMetric ("RAM/Usage/Used",
2040 "Physical memory currently occupied.");
2041 pm::SubMetric *ramUsageFree = new pm::SubMetric ("RAM/Usage/Free",
2042 "Physical memory currently available to applications.");
2043 /* Create and register base metrics */
2044 IUnknown *objptr;
2045 ComObjPtr<Host> tmp = this;
2046 tmp.queryInterfaceTo(&objptr);
2047 pm::BaseMetric *cpuLoad = new pm::HostCpuLoadRaw (hal, objptr, cpuLoadUser, cpuLoadKernel,
2048 cpuLoadIdle);
2049 aCollector->registerBaseMetric (cpuLoad);
2050 pm::BaseMetric *cpuMhz = new pm::HostCpuMhz (hal, objptr, cpuMhzSM);
2051 aCollector->registerBaseMetric (cpuMhz);
2052 pm::BaseMetric *ramUsage = new pm::HostRamUsage (hal, objptr, ramUsageTotal, ramUsageUsed,
2053 ramUsageFree);
2054 aCollector->registerBaseMetric (ramUsage);
2055
2056 aCollector->registerMetric (new pm::Metric(cpuLoad, cpuLoadUser, 0));
2057 aCollector->registerMetric (new pm::Metric(cpuLoad, cpuLoadUser,
2058 new pm::AggregateAvg()));
2059 aCollector->registerMetric (new pm::Metric(cpuLoad, cpuLoadUser,
2060 new pm::AggregateMin()));
2061 aCollector->registerMetric (new pm::Metric(cpuLoad, cpuLoadUser,
2062 new pm::AggregateMax()));
2063
2064 aCollector->registerMetric (new pm::Metric(cpuLoad, cpuLoadKernel, 0));
2065 aCollector->registerMetric (new pm::Metric(cpuLoad, cpuLoadKernel,
2066 new pm::AggregateAvg()));
2067 aCollector->registerMetric (new pm::Metric(cpuLoad, cpuLoadKernel,
2068 new pm::AggregateMin()));
2069 aCollector->registerMetric (new pm::Metric(cpuLoad, cpuLoadKernel,
2070 new pm::AggregateMax()));
2071
2072 aCollector->registerMetric (new pm::Metric(cpuLoad, cpuLoadIdle, 0));
2073 aCollector->registerMetric (new pm::Metric(cpuLoad, cpuLoadIdle,
2074 new pm::AggregateAvg()));
2075 aCollector->registerMetric (new pm::Metric(cpuLoad, cpuLoadIdle,
2076 new pm::AggregateMin()));
2077 aCollector->registerMetric (new pm::Metric(cpuLoad, cpuLoadIdle,
2078 new pm::AggregateMax()));
2079
2080 aCollector->registerMetric (new pm::Metric(cpuMhz, cpuMhzSM, 0));
2081 aCollector->registerMetric (new pm::Metric(cpuMhz, cpuMhzSM,
2082 new pm::AggregateAvg()));
2083 aCollector->registerMetric (new pm::Metric(cpuMhz, cpuMhzSM,
2084 new pm::AggregateMin()));
2085 aCollector->registerMetric (new pm::Metric(cpuMhz, cpuMhzSM,
2086 new pm::AggregateMax()));
2087
2088 aCollector->registerMetric (new pm::Metric(ramUsage, ramUsageTotal, 0));
2089 aCollector->registerMetric (new pm::Metric(ramUsage, ramUsageTotal,
2090 new pm::AggregateAvg()));
2091 aCollector->registerMetric (new pm::Metric(ramUsage, ramUsageTotal,
2092 new pm::AggregateMin()));
2093 aCollector->registerMetric (new pm::Metric(ramUsage, ramUsageTotal,
2094 new pm::AggregateMax()));
2095
2096 aCollector->registerMetric (new pm::Metric(ramUsage, ramUsageUsed, 0));
2097 aCollector->registerMetric (new pm::Metric(ramUsage, ramUsageUsed,
2098 new pm::AggregateAvg()));
2099 aCollector->registerMetric (new pm::Metric(ramUsage, ramUsageUsed,
2100 new pm::AggregateMin()));
2101 aCollector->registerMetric (new pm::Metric(ramUsage, ramUsageUsed,
2102 new pm::AggregateMax()));
2103
2104 aCollector->registerMetric (new pm::Metric(ramUsage, ramUsageFree, 0));
2105 aCollector->registerMetric (new pm::Metric(ramUsage, ramUsageFree,
2106 new pm::AggregateAvg()));
2107 aCollector->registerMetric (new pm::Metric(ramUsage, ramUsageFree,
2108 new pm::AggregateMin()));
2109 aCollector->registerMetric (new pm::Metric(ramUsage, ramUsageFree,
2110 new pm::AggregateMax()));
2111};
2112
2113void Host::unregisterMetrics (PerformanceCollector *aCollector)
2114{
2115 aCollector->unregisterMetricsFor (this);
2116 aCollector->unregisterBaseMetricsFor (this);
2117};
2118#endif /* VBOX_WITH_RESOURCE_USAGE_API */
2119
2120STDMETHODIMP Host::FindHostDVDDrive(IN_BSTR aName, IHostDVDDrive **aDrive)
2121{
2122 CheckComArgNotNull(aName);
2123 CheckComArgOutPointerValid(aDrive);
2124
2125 *aDrive = NULL;
2126
2127 SafeIfaceArray<IHostDVDDrive> drivevec;
2128 HRESULT rc = COMGETTER(DVDDrives) (ComSafeArrayAsOutParam(drivevec));
2129 CheckComRCReturnRC(rc);
2130
2131 for (size_t i = 0; i < drivevec.size(); ++i)
2132 {
2133 Bstr name;
2134 rc = drivevec[i]->COMGETTER(Name) (name.asOutParam());
2135 CheckComRCReturnRC(rc);
2136 if (name == aName)
2137 {
2138 ComObjPtr<HostDVDDrive> found;
2139 found.createObject();
2140 Bstr udi, description;
2141 rc = drivevec[i]->COMGETTER(Udi) (udi.asOutParam());
2142 CheckComRCReturnRC(rc);
2143 rc = drivevec[i]->COMGETTER(Description) (description.asOutParam());
2144 CheckComRCReturnRC(rc);
2145 found->init(name, udi, description);
2146 return found.queryInterfaceTo(aDrive);
2147 }
2148 }
2149
2150 return setError (VBOX_E_OBJECT_NOT_FOUND, HostDVDDrive::tr (
2151 "The host DVD drive named '%ls' could not be found"), aName);
2152}
2153
2154STDMETHODIMP Host::FindHostFloppyDrive(IN_BSTR aName, IHostFloppyDrive **aDrive)
2155{
2156 CheckComArgNotNull(aName);
2157 CheckComArgOutPointerValid(aDrive);
2158
2159 *aDrive = NULL;
2160
2161 SafeIfaceArray<IHostFloppyDrive> drivevec;
2162 HRESULT rc = COMGETTER(FloppyDrives) (ComSafeArrayAsOutParam(drivevec));
2163 CheckComRCReturnRC(rc);
2164
2165 for (size_t i = 0; i < drivevec.size(); ++i)
2166 {
2167 Bstr name;
2168 rc = drivevec[i]->COMGETTER(Name) (name.asOutParam());
2169 CheckComRCReturnRC(rc);
2170 if (name == aName)
2171 {
2172 ComObjPtr<HostFloppyDrive> found;
2173 found.createObject();
2174 Bstr udi, description;
2175 rc = drivevec[i]->COMGETTER(Udi) (udi.asOutParam());
2176 CheckComRCReturnRC(rc);
2177 rc = drivevec[i]->COMGETTER(Description) (description.asOutParam());
2178 CheckComRCReturnRC(rc);
2179 found->init(name, udi, description);
2180 return found.queryInterfaceTo(aDrive);
2181 }
2182 }
2183
2184 return setError (VBOX_E_OBJECT_NOT_FOUND, HostFloppyDrive::tr (
2185 "The host floppy drive named '%ls' could not be found"), aName);
2186}
2187
2188STDMETHODIMP Host::FindHostNetworkInterfaceByName(IN_BSTR name, IHostNetworkInterface **networkInterface)
2189{
2190#ifndef VBOX_WITH_HOSTNETIF_API
2191 return E_NOTIMPL;
2192#else
2193 if (!name)
2194 return E_INVALIDARG;
2195 if (!networkInterface)
2196 return E_POINTER;
2197
2198 *networkInterface = NULL;
2199 ComObjPtr<HostNetworkInterface> found;
2200 std::list <ComObjPtr<HostNetworkInterface> > list;
2201 int rc = NetIfList(list);
2202 if (RT_FAILURE(rc))
2203 {
2204 Log(("Failed to get host network interface list with rc=%Vrc\n", rc));
2205 return E_FAIL;
2206 }
2207 std::list <ComObjPtr<HostNetworkInterface> >::iterator it;
2208 for (it = list.begin(); it != list.end(); ++it)
2209 {
2210 Bstr n;
2211 (*it)->COMGETTER(Name) (n.asOutParam());
2212 if (n == name)
2213 found = *it;
2214 }
2215
2216 if (!found)
2217 return setError (E_INVALIDARG, HostNetworkInterface::tr (
2218 "The host network interface with the given name could not be found"));
2219
2220 found->setVirtualBox(mParent);
2221
2222 return found.queryInterfaceTo(networkInterface);
2223#endif
2224}
2225
2226STDMETHODIMP Host::FindHostNetworkInterfaceById(IN_BSTR id, IHostNetworkInterface **networkInterface)
2227{
2228#ifndef VBOX_WITH_HOSTNETIF_API
2229 return E_NOTIMPL;
2230#else
2231 if (Guid(id).isEmpty())
2232 return E_INVALIDARG;
2233 if (!networkInterface)
2234 return E_POINTER;
2235
2236 *networkInterface = NULL;
2237 ComObjPtr<HostNetworkInterface> found;
2238 std::list <ComObjPtr<HostNetworkInterface> > list;
2239 int rc = NetIfList(list);
2240 if (RT_FAILURE(rc))
2241 {
2242 Log(("Failed to get host network interface list with rc=%Vrc\n", rc));
2243 return E_FAIL;
2244 }
2245 std::list <ComObjPtr<HostNetworkInterface> >::iterator it;
2246 for (it = list.begin(); it != list.end(); ++it)
2247 {
2248 Bstr g;
2249 (*it)->COMGETTER(Id) (g.asOutParam());
2250 if (g == id)
2251 found = *it;
2252 }
2253
2254 if (!found)
2255 return setError (E_INVALIDARG, HostNetworkInterface::tr (
2256 "The host network interface with the given GUID could not be found"));
2257
2258 found->setVirtualBox(mParent);
2259
2260 return found.queryInterfaceTo(networkInterface);
2261#endif
2262}
2263
2264STDMETHODIMP Host::FindHostNetworkInterfacesOfType(HostNetworkInterfaceType_T type, ComSafeArrayOut(IHostNetworkInterface *, aNetworkInterfaces))
2265{
2266 std::list <ComObjPtr<HostNetworkInterface> > allList;
2267 int rc = NetIfList(allList);
2268 if(RT_FAILURE(rc))
2269 return E_FAIL;
2270
2271 std::list <ComObjPtr<HostNetworkInterface> > resultList;
2272
2273 std::list <ComObjPtr<HostNetworkInterface> >::iterator it;
2274 for (it = allList.begin(); it != allList.end(); ++it)
2275 {
2276 HostNetworkInterfaceType_T t;
2277 HRESULT hr = (*it)->COMGETTER(InterfaceType)(&t);
2278 if(FAILED(hr))
2279 return hr;
2280
2281 if(t == type)
2282 {
2283 (*it)->setVirtualBox(mParent);
2284 resultList.push_back (*it);
2285 }
2286 }
2287
2288 SafeIfaceArray<IHostNetworkInterface> filteredNetworkInterfaces (resultList);
2289 filteredNetworkInterfaces.detachTo(ComSafeArrayOutArg(aNetworkInterfaces));
2290
2291 return S_OK;
2292}
2293
2294STDMETHODIMP Host::FindUSBDeviceByAddress (IN_BSTR aAddress, IHostUSBDevice **aDevice)
2295{
2296#ifdef VBOX_WITH_USB
2297 CheckComArgNotNull(aAddress);
2298 CheckComArgOutPointerValid(aDevice);
2299
2300 *aDevice = NULL;
2301
2302 SafeIfaceArray<IHostUSBDevice> devsvec;
2303 HRESULT rc = COMGETTER(USBDevices) (ComSafeArrayAsOutParam(devsvec));
2304 CheckComRCReturnRC(rc);
2305
2306 for (size_t i = 0; i < devsvec.size(); ++i)
2307 {
2308 Bstr address;
2309 rc = devsvec[i]->COMGETTER(Address) (address.asOutParam());
2310 CheckComRCReturnRC(rc);
2311 if (address == aAddress)
2312 {
2313 return ComObjPtr<IHostUSBDevice> (devsvec[i]).queryInterfaceTo(aDevice);
2314 }
2315 }
2316
2317 return setErrorNoLog (VBOX_E_OBJECT_NOT_FOUND, tr (
2318 "Could not find a USB device with address '%ls'"),
2319 aAddress);
2320
2321#else /* !VBOX_WITH_USB */
2322 NOREF(aAddress);
2323 NOREF(aDevice);
2324 return E_NOTIMPL;
2325#endif /* !VBOX_WITH_USB */
2326}
2327
2328STDMETHODIMP Host::FindUSBDeviceById (IN_BSTR aId, IHostUSBDevice **aDevice)
2329{
2330#ifdef VBOX_WITH_USB
2331 CheckComArgExpr(aId, Guid (aId).isEmpty() == false);
2332 CheckComArgOutPointerValid(aDevice);
2333
2334 *aDevice = NULL;
2335
2336 SafeIfaceArray<IHostUSBDevice> devsvec;
2337 HRESULT rc = COMGETTER(USBDevices) (ComSafeArrayAsOutParam(devsvec));
2338 CheckComRCReturnRC(rc);
2339
2340 for (size_t i = 0; i < devsvec.size(); ++i)
2341 {
2342 Bstr id;
2343 rc = devsvec[i]->COMGETTER(Id) (id.asOutParam());
2344 CheckComRCReturnRC(rc);
2345 if (id == aId)
2346 {
2347 return ComObjPtr<IHostUSBDevice> (devsvec[i]).queryInterfaceTo(aDevice);
2348 }
2349 }
2350
2351 return setErrorNoLog (VBOX_E_OBJECT_NOT_FOUND, tr (
2352 "Could not find a USB device with uuid {%RTuuid}"),
2353 Guid (aId).raw());
2354
2355#else /* !VBOX_WITH_USB */
2356 NOREF(aId);
2357 NOREF(aDevice);
2358 return E_NOTIMPL;
2359#endif /* !VBOX_WITH_USB */
2360}
2361
2362
2363/* vi: set tabstop=4 shiftwidth=4 expandtab: */
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