VirtualBox

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

Last change on this file since 29445 was 29385, checked in by vboxsync, 15 years ago

Main: cleaned up some pedantic warnings.

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