VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/UpdateAgentImpl.cpp@ 94706

Last change on this file since 94706 was 94706, checked in by vboxsync, 3 years ago

Main/Update check: Use VERR_COM_IPRT_ERROR for now when reporting errors as error info, as we don't support resolving HTTP errors to COM yet. See @todo. ​​bugref:7983

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 32.7 KB
Line 
1/* $Id: UpdateAgentImpl.cpp 94706 2022-04-25 11:46:12Z vboxsync $ */
2/** @file
3 * IUpdateAgent COM class implementations.
4 */
5
6/*
7 * Copyright (C) 2020-2022 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.215389.xyz. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19#define LOG_GROUP LOG_GROUP_MAIN_UPDATEAGENT
20
21#include <iprt/cpp/utils.h>
22#include <iprt/param.h>
23#include <iprt/path.h>
24#include <iprt/http.h>
25#include <iprt/system.h>
26#include <iprt/message.h>
27#include <iprt/pipe.h>
28#include <iprt/env.h>
29#include <iprt/process.h>
30#include <iprt/assert.h>
31#include <iprt/err.h>
32#include <iprt/stream.h>
33#include <iprt/time.h>
34#include <VBox/com/defs.h>
35#include <VBox/err.h>
36#include <VBox/version.h>
37
38#include "HostImpl.h"
39#include "UpdateAgentImpl.h"
40#include "ProgressImpl.h"
41#include "AutoCaller.h"
42#include "LoggingNew.h"
43#include "VirtualBoxImpl.h"
44#include "VBoxEvents.h"
45#include "ThreadTask.h"
46#include "VirtualBoxBase.h"
47
48
49/*********************************************************************************************************************************
50* Update agent task implementation *
51*********************************************************************************************************************************/
52
53/**
54 * Base task class for asynchronous update agent tasks.
55 */
56class UpdateAgentTask : public ThreadTask
57{
58public:
59 UpdateAgentTask(UpdateAgentBase *aThat, Progress *aProgress)
60 : m_pParent(aThat)
61 , m_pProgress(aProgress)
62 {
63 m_strTaskName = "UpdateAgentTask";
64 }
65 virtual ~UpdateAgentTask(void) { }
66
67private:
68 void handler(void);
69
70 /** Weak pointer to parent (update agent). */
71 UpdateAgentBase *m_pParent;
72 /** Smart pointer to the progress object for this job. */
73 ComObjPtr<Progress> m_pProgress;
74
75 friend class UpdateAgent; // allow member functions access to private data
76};
77
78void UpdateAgentTask::handler(void)
79{
80 UpdateAgentBase *pUpdateAgent = this->m_pParent;
81 AssertPtr(pUpdateAgent);
82
83 /** @todo Differentiate tasks once we have more stuff to do (downloading, installing, ++). */
84
85 HRESULT rc = pUpdateAgent->i_checkForUpdateTask(this);
86
87 if (!m_pProgress.isNull())
88 m_pProgress->i_notifyComplete(rc);
89
90 LogFlowFunc(("rc=%Rhrc\n", rc)); RT_NOREF(rc);
91}
92
93
94/*********************************************************************************************************************************
95* Update agent base class implementation *
96*********************************************************************************************************************************/
97
98/**
99 * Returns platform information as a string.
100 *
101 * @returns HRESULT
102 */
103/* static */
104Utf8Str UpdateAgentBase::i_getPlatformInfo(void)
105{
106 /* Prepare platform report: */
107 Utf8Str strPlatform;
108
109# if defined (RT_OS_WINDOWS)
110 strPlatform = "win";
111# elif defined (RT_OS_LINUX)
112 strPlatform = "linux";
113# elif defined (RT_OS_DARWIN)
114 strPlatform = "macosx";
115# elif defined (RT_OS_OS2)
116 strPlatform = "os2";
117# elif defined (RT_OS_FREEBSD)
118 strPlatform = "freebsd";
119# elif defined (RT_OS_SOLARIS)
120 strPlatform = "solaris";
121# else
122 strPlatform = "unknown";
123# endif
124
125 /* The format is <system>.<bitness>: */
126 strPlatform.appendPrintf(".%lu", ARCH_BITS);
127
128 /* Add more system information: */
129 int vrc;
130# ifdef RT_OS_LINUX
131 // WORKAROUND:
132 // On Linux we try to generate information using script first of all..
133
134 /* Get script path: */
135 char szAppPrivPath[RTPATH_MAX];
136 vrc = RTPathAppPrivateNoArch(szAppPrivPath, sizeof(szAppPrivPath));
137 AssertRC(vrc);
138 if (RT_SUCCESS(vrc))
139 vrc = RTPathAppend(szAppPrivPath, sizeof(szAppPrivPath), "/VBoxSysInfo.sh");
140 AssertRC(vrc);
141 if (RT_SUCCESS(vrc))
142 {
143 RTPIPE hPipeR;
144 RTHANDLE hStdOutPipe;
145 hStdOutPipe.enmType = RTHANDLETYPE_PIPE;
146 vrc = RTPipeCreate(&hPipeR, &hStdOutPipe.u.hPipe, RTPIPE_C_INHERIT_WRITE);
147 AssertLogRelRC(vrc);
148
149 char const *szAppPrivArgs[2];
150 szAppPrivArgs[0] = szAppPrivPath;
151 szAppPrivArgs[1] = NULL;
152 RTPROCESS hProc = NIL_RTPROCESS;
153
154 /* Run script: */
155 vrc = RTProcCreateEx(szAppPrivPath, szAppPrivArgs, RTENV_DEFAULT, 0 /*fFlags*/, NULL /*phStdin*/, &hStdOutPipe,
156 NULL /*phStderr*/, NULL /*pszAsUser*/, NULL /*pszPassword*/, NULL /*pvExtraData*/, &hProc);
157
158 (void) RTPipeClose(hStdOutPipe.u.hPipe);
159 hStdOutPipe.u.hPipe = NIL_RTPIPE;
160
161 if (RT_SUCCESS(vrc))
162 {
163 RTPROCSTATUS ProcStatus;
164 size_t cbStdOutBuf = 0;
165 size_t offStdOutBuf = 0;
166 char *pszStdOutBuf = NULL;
167 do
168 {
169 if (hPipeR != NIL_RTPIPE)
170 {
171 char achBuf[1024];
172 size_t cbRead;
173 vrc = RTPipeReadBlocking(hPipeR, achBuf, sizeof(achBuf), &cbRead);
174 if (RT_SUCCESS(vrc))
175 {
176 /* grow the buffer? */
177 size_t cbBufReq = offStdOutBuf + cbRead + 1;
178 if ( cbBufReq > cbStdOutBuf
179 && cbBufReq < _256K)
180 {
181 size_t cbNew = RT_ALIGN_Z(cbBufReq, 16); // 1024
182 void *pvNew = RTMemRealloc(pszStdOutBuf, cbNew);
183 if (pvNew)
184 {
185 pszStdOutBuf = (char *)pvNew;
186 cbStdOutBuf = cbNew;
187 }
188 }
189
190 /* append if we've got room. */
191 if (cbBufReq <= cbStdOutBuf)
192 {
193 (void) memcpy(&pszStdOutBuf[offStdOutBuf], achBuf, cbRead);
194 offStdOutBuf = offStdOutBuf + cbRead;
195 pszStdOutBuf[offStdOutBuf] = '\0';
196 }
197 }
198 else
199 {
200 AssertLogRelMsg(vrc == VERR_BROKEN_PIPE, ("%Rrc\n", vrc));
201 RTPipeClose(hPipeR);
202 hPipeR = NIL_RTPIPE;
203 }
204 }
205
206 /*
207 * Service the process. Block if we have no pipe.
208 */
209 if (hProc != NIL_RTPROCESS)
210 {
211 vrc = RTProcWait(hProc,
212 hPipeR == NIL_RTPIPE ? RTPROCWAIT_FLAGS_BLOCK : RTPROCWAIT_FLAGS_NOBLOCK,
213 &ProcStatus);
214 if (RT_SUCCESS(vrc))
215 hProc = NIL_RTPROCESS;
216 else
217 AssertLogRelMsgStmt(vrc == VERR_PROCESS_RUNNING, ("%Rrc\n", vrc), hProc = NIL_RTPROCESS);
218 }
219 } while ( hPipeR != NIL_RTPIPE
220 || hProc != NIL_RTPROCESS);
221
222 if ( ProcStatus.enmReason == RTPROCEXITREASON_NORMAL
223 && ProcStatus.iStatus == 0) {
224 pszStdOutBuf[offStdOutBuf-1] = '\0'; // remove trailing newline
225 Utf8Str pszStdOutBufUTF8(pszStdOutBuf);
226 strPlatform.appendPrintf(" [%s]", pszStdOutBufUTF8.strip().c_str());
227 // For testing, here is some sample output:
228 //strPlatform.appendPrintf(" [Distribution: Redhat | Version: 7.6.1810 | Kernel: Linux version 3.10.0-952.27.2.el7.x86_64 (gcc version 4.8.5 20150623 (Red Hat 4.8.5-36) (GCC) ) #1 SMP Mon Jul 29 17:46:05 UTC 2019]");
229 }
230 }
231 else
232 vrc = VERR_TRY_AGAIN; /* (take the fallback path) */
233 }
234
235 LogRelFunc(("strPlatform (Linux) = %s\n", strPlatform.c_str()));
236
237 if (RT_FAILURE(vrc))
238# endif /* RT_OS_LINUX */
239 {
240 /* Use RTSystemQueryOSInfo: */
241 char szTmp[256];
242
243 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_PRODUCT, szTmp, sizeof(szTmp));
244 if ((RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW) && szTmp[0] != '\0')
245 strPlatform.appendPrintf(" [Product: %s", szTmp);
246
247 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE, szTmp, sizeof(szTmp));
248 if ((RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW) && szTmp[0] != '\0')
249 strPlatform.appendPrintf(" %sRelease: %s", strlen(szTmp) == 0 ? "[" : "| ", szTmp);
250
251 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_VERSION, szTmp, sizeof(szTmp));
252 if ((RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW) && szTmp[0] != '\0')
253 strPlatform.appendPrintf(" %sVersion: %s", strlen(szTmp) == 0 ? "[" : "| ", szTmp);
254
255 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_SERVICE_PACK, szTmp, sizeof(szTmp));
256 if ((RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW) && szTmp[0] != '\0')
257 strPlatform.appendPrintf(" %sSP: %s]", strlen(szTmp) == 0 ? "[" : "| ", szTmp);
258
259 if (!strPlatform.endsWith("]"))
260 strPlatform.append("]");
261
262 LogRelFunc(("strPlatform = %s\n", strPlatform.c_str()));
263 }
264
265 return strPlatform;
266}
267
268
269/*********************************************************************************************************************************
270* Update agent class implementation *
271*********************************************************************************************************************************/
272UpdateAgent::UpdateAgent()
273{
274}
275
276UpdateAgent::~UpdateAgent()
277{
278}
279
280HRESULT UpdateAgent::FinalConstruct(void)
281{
282 return BaseFinalConstruct();
283}
284
285void UpdateAgent::FinalRelease(void)
286{
287 uninit();
288
289 BaseFinalRelease();
290}
291
292HRESULT UpdateAgent::init(VirtualBox *aVirtualBox)
293{
294 // Enclose the state transition NotReady->InInit->Ready.
295 AutoInitSpan autoInitSpan(this);
296 AssertReturn(autoInitSpan.isOk(), E_FAIL);
297
298 /* Weak reference to a VirtualBox object */
299 unconst(m_VirtualBox) = aVirtualBox;
300
301 HRESULT hr = unconst(m_EventSource).createObject();
302 if (SUCCEEDED(hr))
303 {
304 hr = m_EventSource->init();
305 if (SUCCEEDED(hr))
306 autoInitSpan.setSucceeded();
307 }
308
309 return hr;
310}
311
312void UpdateAgent::uninit(void)
313{
314 // Enclose the state transition Ready->InUninit->NotReady.
315 AutoUninitSpan autoUninitSpan(this);
316 if (autoUninitSpan.uninitDone())
317 return;
318
319 unconst(m_EventSource).setNull();
320}
321
322HRESULT UpdateAgent::checkFor(ComPtr<IProgress> &aProgress)
323{
324 RT_NOREF(aProgress);
325
326 return VBOX_E_NOT_SUPPORTED;
327}
328
329HRESULT UpdateAgent::download(ComPtr<IProgress> &aProgress)
330{
331 RT_NOREF(aProgress);
332
333 return VBOX_E_NOT_SUPPORTED;
334}
335
336HRESULT UpdateAgent::install(ComPtr<IProgress> &aProgress)
337{
338 RT_NOREF(aProgress);
339
340 return VBOX_E_NOT_SUPPORTED;
341}
342
343HRESULT UpdateAgent::rollback(void)
344{
345 return VBOX_E_NOT_SUPPORTED;
346}
347
348HRESULT UpdateAgent::getName(com::Utf8Str &aName)
349{
350 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
351
352 aName = mData.m_strName;
353
354 return S_OK;
355}
356
357HRESULT UpdateAgent::getEventSource(ComPtr<IEventSource> &aEventSource)
358{
359 LogFlowThisFuncEnter();
360
361 /* No need to lock - lifetime constant. */
362 m_EventSource.queryInterfaceTo(aEventSource.asOutParam());
363
364 LogFlowFuncLeaveRC(S_OK);
365 return S_OK;
366}
367
368HRESULT UpdateAgent::getOrder(ULONG *aOrder)
369{
370 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
371
372 *aOrder = 0; /* 0 means no order / disabled. */
373
374 return S_OK;
375}
376
377HRESULT UpdateAgent::getDependsOn(std::vector<com::Utf8Str> &aDeps)
378{
379 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
380
381 aDeps.resize(0); /* No dependencies by default. */
382
383 return S_OK;
384}
385
386HRESULT UpdateAgent::getVersion(com::Utf8Str &aVer)
387{
388 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
389
390 aVer = mData.m_lastResult.strVer;
391
392 return S_OK;
393}
394
395HRESULT UpdateAgent::getDownloadUrl(com::Utf8Str &aUrl)
396{
397 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
398
399 aUrl = mData.m_lastResult.strDownloadUrl;
400
401 return S_OK;
402}
403
404
405HRESULT UpdateAgent::getWebUrl(com::Utf8Str &aUrl)
406{
407 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
408
409 aUrl = mData.m_lastResult.strWebUrl;
410
411 return S_OK;
412}
413
414HRESULT UpdateAgent::getReleaseNotes(com::Utf8Str &aRelNotes)
415{
416 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
417
418 aRelNotes = mData.m_lastResult.strReleaseNotes;
419
420 return S_OK;
421}
422
423HRESULT UpdateAgent::getEnabled(BOOL *aEnabled)
424{
425 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
426
427 *aEnabled = m->fEnabled;
428
429 return S_OK;
430}
431
432HRESULT UpdateAgent::setEnabled(const BOOL aEnabled)
433{
434 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
435
436 m->fEnabled = aEnabled;
437
438 return i_commitSettings(alock);
439}
440
441
442HRESULT UpdateAgent::getHidden(BOOL *aHidden)
443{
444 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
445
446 *aHidden = mData.m_fHidden;
447
448 return S_OK;
449}
450
451HRESULT UpdateAgent::getState(UpdateState_T *aState)
452{
453 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
454
455 *aState = mData.m_enmState;
456
457 return S_OK;
458}
459
460HRESULT UpdateAgent::getCheckFrequency(ULONG *aFreqSeconds)
461{
462 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
463
464 *aFreqSeconds = m->uCheckFreqSeconds;
465
466 return S_OK;
467}
468
469HRESULT UpdateAgent::setCheckFrequency(ULONG aFreqSeconds)
470{
471 if (aFreqSeconds < RT_SEC_1DAY) /* Don't allow more frequent checks for now. */
472 return setError(E_INVALIDARG, tr("Frequency too small; one day is the minimum"));
473
474 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
475
476 m->uCheckFreqSeconds = aFreqSeconds;
477
478 return i_commitSettings(alock);
479}
480
481HRESULT UpdateAgent::getChannel(UpdateChannel_T *aChannel)
482{
483 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
484
485 *aChannel = m->enmChannel;
486
487 return S_OK;
488}
489
490HRESULT UpdateAgent::setChannel(UpdateChannel_T aChannel)
491{
492 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
493
494 m->enmChannel = aChannel;
495
496 return i_commitSettings(alock);
497}
498
499HRESULT UpdateAgent::getCheckCount(ULONG *aCount)
500{
501 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
502
503 *aCount = m->uCheckCount;
504
505 return S_OK;
506}
507
508HRESULT UpdateAgent::getRepositoryURL(com::Utf8Str &aRepo)
509{
510 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
511
512 aRepo = m->strRepoUrl;
513
514 return S_OK;
515}
516
517HRESULT UpdateAgent::setRepositoryURL(const com::Utf8Str &aRepo)
518{
519 if (!aRepo.startsWith("https://", com::Utf8Str::CaseInsensitive))
520 return setError(E_INVALIDARG, tr("Invalid URL scheme specified; only https:// is supported."));
521
522 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
523
524 m->strRepoUrl = aRepo;
525
526 return i_commitSettings(alock);
527}
528
529HRESULT UpdateAgent::getProxyMode(ProxyMode_T *aMode)
530{
531 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
532
533 *aMode = m->enmProxyMode;
534
535 return S_OK;
536}
537
538HRESULT UpdateAgent::setProxyMode(ProxyMode_T aMode)
539{
540 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
541
542 m->enmProxyMode = aMode;
543
544 return i_commitSettings(alock);
545}
546
547HRESULT UpdateAgent::getProxyURL(com::Utf8Str &aAddress)
548{
549 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
550
551 aAddress = m->strProxyUrl;
552
553 return S_OK;
554}
555
556HRESULT UpdateAgent::setProxyURL(const com::Utf8Str &aAddress)
557{
558 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
559
560 m->strProxyUrl = aAddress;
561
562 return i_commitSettings(alock);
563}
564
565HRESULT UpdateAgent::getLastCheckDate(com::Utf8Str &aDate)
566{
567 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
568
569 aDate = m->strLastCheckDate;
570
571 return S_OK;
572}
573
574HRESULT UpdateAgent::getIsCheckNeeded(BOOL *aCheckNeeded)
575{
576 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
577
578 /*
579 * Is update checking enabled at all?
580 */
581 if (!m->fEnabled)
582 {
583 *aCheckNeeded = FALSE;
584 return S_OK;
585 }
586
587 /*
588 * When was the last update?
589 */
590 if (m->strLastCheckDate.isEmpty()) /* No prior update check performed -- do so now. */
591 {
592 *aCheckNeeded = TRUE;
593 return S_OK;
594 }
595
596 RTTIMESPEC LastCheckTime;
597 if (!RTTimeSpecFromString(&LastCheckTime, Utf8Str(m->strLastCheckDate).c_str()))
598 {
599 *aCheckNeeded = TRUE; /* Invalid date set or error? Perform check. */
600 return S_OK;
601 }
602
603 /*
604 * Compare last update with how often we are supposed to check for updates.
605 */
606 if ( !m->uCheckFreqSeconds /* Paranoia */
607 || m->uCheckFreqSeconds < RT_SEC_1DAY) /* This is the minimum we currently allow. */
608 {
609 /* Consider config (enable, 0 day interval) as checking once but never again.
610 We've already check since we've got a date. */
611 *aCheckNeeded = FALSE;
612 return S_OK;
613 }
614
615 uint64_t const cCheckFreqDays = m->uCheckFreqSeconds / RT_SEC_1DAY_64;
616
617 RTTIMESPEC TimeDiff;
618 RTTimeSpecSub(RTTimeNow(&TimeDiff), &LastCheckTime);
619
620 int64_t const diffLastCheckSecs = RTTimeSpecGetSeconds(&TimeDiff);
621 int64_t const diffLastCheckDays = diffLastCheckSecs / RT_SEC_1DAY_64;
622
623 /* Be as accurate as possible. */
624 *aCheckNeeded = diffLastCheckSecs >= (int64_t)m->uCheckFreqSeconds ? TRUE : FALSE;
625
626 LogRel2(("Update agent (%s): Last update %RU64 days (%RU64 seconds) ago, check frequency is every %RU64 days (%RU64 seconds) -> Check %s\n",
627 mData.m_strName.c_str(), diffLastCheckDays, diffLastCheckSecs, cCheckFreqDays, m->uCheckFreqSeconds,
628 *aCheckNeeded ? "needed" : "not needed"));
629
630 return S_OK;
631}
632
633
634/*********************************************************************************************************************************
635* Internal helper methods of update agent class *
636*********************************************************************************************************************************/
637
638/**
639 * Loads the settings of the update agent base class.
640 *
641 * @returns HRESULT
642 * @param data Where to load the settings from.
643 */
644HRESULT UpdateAgent::i_loadSettings(const settings::UpdateAgent &data)
645{
646 AutoCaller autoCaller(this);
647 if (FAILED(autoCaller.rc())) return autoCaller.rc();
648
649 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
650
651 m->fEnabled = data.fEnabled;
652 m->enmChannel = data.enmChannel;
653 m->uCheckFreqSeconds = data.uCheckFreqSeconds;
654 m->strRepoUrl = data.strRepoUrl;
655 m->enmProxyMode = data.enmProxyMode;
656 m->strProxyUrl = data.strProxyUrl;
657 m->strLastCheckDate = data.strLastCheckDate;
658 m->uCheckCount = data.uCheckCount;
659
660 return S_OK;
661}
662
663/**
664 * Saves the settings of the update agent base class.
665 *
666 * @returns HRESULT
667 * @param data Where to save the settings to.
668 */
669HRESULT UpdateAgent::i_saveSettings(settings::UpdateAgent &data)
670{
671 AutoCaller autoCaller(this);
672 if (FAILED(autoCaller.rc())) return autoCaller.rc();
673
674 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
675
676 data = *m;
677
678 return S_OK;
679}
680
681/**
682 * Sets the update check count.
683 *
684 * @returns HRESULT
685 * @param aCount Update check count to set.
686 */
687HRESULT UpdateAgent::i_setCheckCount(ULONG aCount)
688{
689 AutoCaller autoCaller(this);
690 if (FAILED(autoCaller.rc())) return autoCaller.rc();
691
692 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
693
694 m->uCheckCount = aCount;
695
696 return i_commitSettings(alock);
697}
698
699/**
700 * Sets the last update check date.
701 *
702 * @returns HRESULT
703 * @param aDate Last update check date to set.
704 * Must be in ISO 8601 format (e.g. 2020-05-11T21:13:39.348416000Z).
705 */
706HRESULT UpdateAgent::i_setLastCheckDate(const com::Utf8Str &aDate)
707{
708 AutoCaller autoCaller(this);
709 if (FAILED(autoCaller.rc())) return autoCaller.rc();
710
711 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
712
713 m->strLastCheckDate = aDate;
714
715 return i_commitSettings(alock);
716}
717
718/**
719 * Internal helper function to commit modified settings.
720 *
721 * @returns HRESULT
722 * @param aLock Write lock to release before committing settings.
723 */
724HRESULT UpdateAgent::i_commitSettings(AutoWriteLock &aLock)
725{
726 aLock.release();
727
728 ::FireUpdateAgentSettingsChangedEvent(m_EventSource, "" /** @todo Include attribute hints */);
729
730 AutoWriteLock vboxLock(m_VirtualBox COMMA_LOCKVAL_SRC_POS);
731 return m_VirtualBox->i_saveSettings();
732}
733
734/**
735 * Reports an error by setting the error info and also information subscribed listeners.
736 *
737 * @returns HRESULT
738 * @param vrc Result code (IPRT-style) to report.
739 * @param pcszMsgFmt Error message to report.
740 * @param ... Format string for \a pcszMsgFmt.
741 */
742HRESULT UpdateAgent::i_reportError(int vrc, const char *pcszMsgFmt, ...)
743{
744 va_list va;
745 va_start(va, pcszMsgFmt);
746
747 char *psz = NULL;
748 if (RTStrAPrintfV(&psz, pcszMsgFmt, va) <= 0)
749 return E_OUTOFMEMORY;
750
751 LogRel(("Update agent (%s): %s\n", mData.m_strName.c_str(), psz));
752
753 ::FireUpdateAgentErrorEvent(m_EventSource, psz, vrc);
754
755 HRESULT const rc = setErrorVrc(VERR_COM_IPRT_ERROR /** @todo Translate HTTP errors to COM? */, pcszMsgFmt, va);
756
757 va_end(va);
758 RTStrFree(psz);
759
760 return rc;
761}
762
763
764/*********************************************************************************************************************************
765* Host update implementation *
766*********************************************************************************************************************************/
767
768HostUpdateAgent::HostUpdateAgent(void)
769{
770}
771
772HostUpdateAgent::~HostUpdateAgent(void)
773{
774}
775
776
777HRESULT HostUpdateAgent::FinalConstruct(void)
778{
779 return BaseFinalConstruct();
780}
781
782void HostUpdateAgent::FinalRelease(void)
783{
784 uninit();
785
786 BaseFinalRelease();
787}
788
789HRESULT HostUpdateAgent::init(VirtualBox *aVirtualBox)
790{
791 // Enclose the state transition NotReady->InInit->Ready.
792 AutoInitSpan autoInitSpan(this);
793 AssertReturn(autoInitSpan.isOk(), E_FAIL);
794
795 /* Weak reference to a VirtualBox object */
796 unconst(m_VirtualBox) = aVirtualBox;
797
798 /* Initialize the bare minimum to get things going.
799 ** @todo Add more stuff later here. */
800 mData.m_strName = "VirtualBox";
801 mData.m_fHidden = false;
802
803 /* Set default repository. */
804 m->strRepoUrl = "https://update.virtualbox.org";
805
806 autoInitSpan.setSucceeded();
807 return S_OK;
808}
809
810void HostUpdateAgent::uninit(void)
811{
812 // Enclose the state transition Ready->InUninit->NotReady.
813 AutoUninitSpan autoUninitSpan(this);
814 if (autoUninitSpan.uninitDone())
815 return;
816}
817
818HRESULT HostUpdateAgent::checkFor(ComPtr<IProgress> &aProgress)
819{
820 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
821
822 ComObjPtr<Progress> pProgress;
823 HRESULT rc = pProgress.createObject();
824 if (FAILED(rc))
825 return rc;
826
827 rc = pProgress->init(m_VirtualBox,
828 static_cast<IUpdateAgent*>(this),
829 tr("Checking for update for %s ...", this->mData.m_strName.c_str()),
830 TRUE /* aCancelable */);
831 if (FAILED(rc))
832 return rc;
833
834 /* initialize the worker task */
835 UpdateAgentTask *pTask = new UpdateAgentTask(this, pProgress);
836 rc = pTask->createThread();
837 pTask = NULL;
838 if (FAILED(rc))
839 return rc;
840
841 return pProgress.queryInterfaceTo(aProgress.asOutParam());
842}
843
844
845/*********************************************************************************************************************************
846* Host update internal functions *
847*********************************************************************************************************************************/
848
849/**
850 * Task callback to perform an update check for the VirtualBox host (core).
851 *
852 * @returns HRESULT
853 * @param pTask Associated update agent task to use.
854 */
855DECLCALLBACK(HRESULT) HostUpdateAgent::i_checkForUpdateTask(UpdateAgentTask *pTask)
856{
857 RT_NOREF(pTask);
858
859 // Following the sequence of steps in UIUpdateStepVirtualBox::sltStartStep()
860 // Build up our query URL starting with the configured repository.
861 Utf8Str strUrl;
862 strUrl.appendPrintf("%s/query.php/?", m->strRepoUrl.c_str());
863
864 // Add platform ID.
865 Bstr platform;
866 HRESULT rc = m_VirtualBox->COMGETTER(PackageType)(platform.asOutParam());
867 AssertComRCReturn(rc, rc);
868 strUrl.appendPrintf("platform=%ls", platform.raw()); // e.g. SOLARIS_64BITS_GENERIC
869
870 // Get the complete current version string for the query URL
871 Bstr versionNormalized;
872 rc = m_VirtualBox->COMGETTER(VersionNormalized)(versionNormalized.asOutParam());
873 AssertComRCReturn(rc, rc);
874 strUrl.appendPrintf("&version=%ls", versionNormalized.raw()); // e.g. 6.1.1
875#ifdef DEBUG // Comment out previous line and uncomment this one for testing.
876// strUrl.appendPrintf("&version=6.0.12");
877#endif
878
879 ULONG revision = 0;
880 rc = m_VirtualBox->COMGETTER(Revision)(&revision);
881 AssertComRCReturn(rc, rc);
882 strUrl.appendPrintf("_%u", revision); // e.g. 135618
883
884 // Update the last update check timestamp.
885 RTTIME Time;
886 RTTIMESPEC TimeNow;
887 char szTimeStr[RTTIME_STR_LEN];
888 RTTimeToString(RTTimeExplode(&Time, RTTimeNow(&TimeNow)), szTimeStr, sizeof(szTimeStr));
889 LogRel2(("Update agent (%s): Setting last update check timestamp to '%s'\n", mData.m_strName.c_str(), szTimeStr));
890
891 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
892
893 m->strLastCheckDate = szTimeStr;
894 m->uCheckCount++;
895
896 rc = i_commitSettings(alock);
897 AssertComRCReturn(rc, rc);
898
899 strUrl.appendPrintf("&count=%RU32", m->uCheckCount);
900
901 // Update the query URL (if necessary) with the 'channel' information.
902 switch (m->enmChannel)
903 {
904 case UpdateChannel_All:
905 strUrl.appendPrintf("&branch=allrelease"); // query.php expects 'allrelease' and not 'allreleases'
906 break;
907 case UpdateChannel_WithBetas:
908 strUrl.appendPrintf("&branch=withbetas");
909 break;
910 /** @todo Handle UpdateChannel_WithTesting once implemented on the backend. */
911 case UpdateChannel_Stable:
912 RT_FALL_THROUGH();
913 default:
914 strUrl.appendPrintf("&branch=stable");
915 break;
916 }
917
918 LogRel2(("Update agent (%s): Using URL '%s'\n", mData.m_strName.c_str(), strUrl.c_str()));
919
920 /*
921 * Compose the User-Agent header for the GET request.
922 */
923 Bstr version;
924 rc = m_VirtualBox->COMGETTER(Version)(version.asOutParam()); // e.g. 6.1.0_RC1
925 AssertComRCReturn(rc, rc);
926
927 Utf8StrFmt const strUserAgent("VirtualBox %ls <%s>", version.raw(), UpdateAgent::i_getPlatformInfo().c_str());
928 LogRel2(("Update agent (%s): Using user agent '%s'\n", mData.m_strName.c_str(), strUserAgent.c_str()));
929
930 /*
931 * Create the HTTP client instance and pass it to a inner worker method to
932 * ensure proper cleanup.
933 */
934 RTHTTP hHttp = NIL_RTHTTP;
935 int vrc = RTHttpCreate(&hHttp);
936 if (RT_SUCCESS(vrc))
937 {
938 try
939 {
940 rc = i_checkForUpdateInner(hHttp, strUrl, strUserAgent);
941 }
942 catch (...)
943 {
944 AssertFailed();
945 rc = E_UNEXPECTED;
946 }
947 RTHttpDestroy(hHttp);
948 }
949 else
950 rc = i_reportError(vrc, tr("RTHttpCreate() failed: %Rrc"), vrc);
951
952 return rc;
953}
954
955/**
956 * Inner function of the actual update checking mechanism.
957 *
958 * @returns HRESULT
959 * @param hHttp HTTP client instance to use for checking.
960 * @param strUrl URL of repository to check.
961 * @param strUserAgent HTTP user agent to use for checking.
962 */
963HRESULT HostUpdateAgent::i_checkForUpdateInner(RTHTTP hHttp, Utf8Str const &strUrl, Utf8Str const &strUserAgent)
964{
965 /** @todo Are there any other headers needed to be added first via RTHttpSetHeaders()? */
966 int vrc = RTHttpAddHeader(hHttp, "User-Agent", strUserAgent.c_str(), strUserAgent.length(), RTHTTPADDHDR_F_BACK);
967 if (RT_FAILURE(vrc))
968 return i_reportError(vrc, tr("RTHttpAddHeader() failed: %Rrc (user agent)"), vrc);
969
970 /*
971 * Configure proxying.
972 */
973 if (m->enmProxyMode == ProxyMode_Manual)
974 {
975 vrc = RTHttpSetProxyByUrl(hHttp, m->strProxyUrl.c_str());
976 if (RT_FAILURE(vrc))
977 return i_reportError(vrc, tr("RTHttpSetProxyByUrl() failed: %Rrc"), vrc);
978 }
979 else if (m->enmProxyMode == ProxyMode_System)
980 {
981 vrc = RTHttpUseSystemProxySettings(hHttp);
982 if (RT_FAILURE(vrc))
983 return i_reportError(vrc, tr("RTHttpUseSystemProxySettings() failed: %Rrc"), vrc);
984 }
985 else
986 Assert(m->enmProxyMode == ProxyMode_NoProxy);
987
988 /*
989 * Perform the GET request, returning raw binary stuff.
990 */
991 void *pvResponse = NULL;
992 size_t cbResponse = 0;
993 vrc = RTHttpGetBinary(hHttp, strUrl.c_str(), &pvResponse, &cbResponse);
994 if (RT_FAILURE(vrc))
995 return i_reportError(vrc, tr("RTHttpGetBinary() failed: %Rrc"), vrc);
996
997 /* Note! We can do nothing that might throw exceptions till we call RTHttpFreeResponse! */
998
999 /*
1000 * If url is platform=DARWIN_64BITS_GENERIC&version=6.0.12&branch=stable for example, the reply is:
1001 * 6.0.14<SPACE>https://download.virtualbox.org/virtualbox/6.0.14/VirtualBox-6.0.14-133895-OSX.dmg
1002 * If no update required, 'UPTODATE' is returned.
1003 */
1004 /* Parse out the two first words of the response, ignoring whatever follows: */
1005 const char *pchResponse = (const char *)pvResponse;
1006 while (cbResponse > 0 && *pchResponse == ' ')
1007 cbResponse--, pchResponse++;
1008
1009 char ch;
1010 const char *pchWord0 = pchResponse;
1011 while (cbResponse > 0 && (ch = *pchResponse) != ' ' && ch != '\0')
1012 cbResponse--, pchResponse++;
1013 size_t const cchWord0 = (size_t)(pchResponse - pchWord0);
1014
1015 while (cbResponse > 0 && *pchResponse == ' ')
1016 cbResponse--, pchResponse++;
1017 const char *pchWord1 = pchResponse;
1018 while (cbResponse > 0 && (ch = *pchResponse) != ' ' && ch != '\0')
1019 cbResponse--, pchResponse++;
1020 size_t const cchWord1 = (size_t)(pchResponse - pchWord1);
1021
1022 HRESULT rc;
1023
1024 /* Decode the two word: */
1025 static char const s_szUpToDate[] = "UPTODATE";
1026 if ( cchWord0 == sizeof(s_szUpToDate) - 1
1027 && memcmp(pchWord0, s_szUpToDate, sizeof(s_szUpToDate) - 1) == 0)
1028 {
1029 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1030
1031 mData.m_enmState = UpdateState_NotAvailable;
1032 rc = S_OK;
1033
1034 alock.release(); /* Release lock before firing off event. */
1035
1036 ::FireUpdateAgentStateChangedEvent(m_EventSource, UpdateState_NotAvailable);
1037 }
1038 else
1039 {
1040 mData.m_enmState = UpdateState_Error; /* Play safe by default. */
1041
1042 vrc = RTStrValidateEncodingEx(pchWord0, cchWord0, 0 /*fFlags*/);
1043 if (RT_SUCCESS(vrc))
1044 vrc = RTStrValidateEncodingEx(pchWord1, cchWord1, 0 /*fFlags*/);
1045 if (RT_SUCCESS(vrc))
1046 {
1047 /** @todo Any additional sanity checks we could perform here? */
1048 rc = mData.m_lastResult.strVer.assignEx(pchWord0, cchWord0);
1049 if (SUCCEEDED(rc))
1050 rc = mData.m_lastResult.strDownloadUrl.assignEx(pchWord1, cchWord1);
1051
1052 if (SUCCEEDED(rc))
1053 {
1054 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1055
1056 /** @todo Implement this on the backend first.
1057 * We also could do some guessing based on the installed version vs. reported update version? */
1058 mData.m_lastResult.enmSeverity = UpdateSeverity_Invalid;
1059 mData.m_enmState = UpdateState_Available;
1060
1061 alock.release(); /* Release lock before firing off events. */
1062
1063 ::FireUpdateAgentStateChangedEvent(m_EventSource, UpdateState_Available);
1064 ::FireUpdateAgentAvailableEvent(m_EventSource, mData.m_lastResult.strVer, m->enmChannel,
1065 mData.m_lastResult.enmSeverity, mData.m_lastResult.strDownloadUrl,
1066 mData.m_lastResult.strWebUrl, mData.m_lastResult.strReleaseNotes);
1067 }
1068 else
1069 rc = i_reportError(VERR_GENERAL_FAILURE /** @todo Use a better rc */,
1070 tr("Invalid server response [1]: %Rhrc (%.*Rhxs -- %.*Rhxs)"),
1071 rc, cchWord0, pchWord0, cchWord1, pchWord1);
1072
1073 LogRel(("Update agent (%s): HTTP server replied: %.*s %.*s\n",
1074 mData.m_strName.c_str(), cchWord0, pchWord0, cchWord1, pchWord1));
1075 }
1076 else
1077 rc = i_reportError(vrc, tr("Invalid server response [2]: %Rrc (%.*Rhxs -- %.*Rhxs)"),
1078 vrc, cchWord0, pchWord0, cchWord1, pchWord1);
1079 }
1080
1081 RTHttpFreeResponse(pvResponse);
1082
1083 return rc;
1084}
1085
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette