VirtualBox

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

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

Main/Update check: Implemented and expose update agent events. ​​bugref:7983

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