VirtualBox

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

Last change on this file since 25810 was 25810, checked in by vboxsync, 14 years ago

OSE build fix

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

© 2023 Oracle
ContactPrivacy policyTerms of Use