VirtualBox

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

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

Main/Update check: Docs nits, formatting, logging tweaks. 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 94710 2022-04-25 17:26:14Z 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 Platform information as string.
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 if (RT_FAILURE(vrc))
236# endif /* RT_OS_LINUX */
237 {
238 /* Use RTSystemQueryOSInfo: */
239 char szTmp[256];
240
241 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_PRODUCT, szTmp, sizeof(szTmp));
242 if ((RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW) && szTmp[0] != '\0')
243 strPlatform.appendPrintf(" [Product: %s", szTmp);
244
245 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE, szTmp, sizeof(szTmp));
246 if ((RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW) && szTmp[0] != '\0')
247 strPlatform.appendPrintf(" %sRelease: %s", strlen(szTmp) == 0 ? "[" : "| ", szTmp);
248
249 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_VERSION, szTmp, sizeof(szTmp));
250 if ((RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW) && szTmp[0] != '\0')
251 strPlatform.appendPrintf(" %sVersion: %s", strlen(szTmp) == 0 ? "[" : "| ", szTmp);
252
253 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_SERVICE_PACK, szTmp, sizeof(szTmp));
254 if ((RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW) && szTmp[0] != '\0')
255 strPlatform.appendPrintf(" %sSP: %s]", strlen(szTmp) == 0 ? "[" : "| ", szTmp);
256
257 if (!strPlatform.endsWith("]"))
258 strPlatform.append("]");
259 }
260
261 LogRel2(("UpdateAgent: Platform is '%s'\n", strPlatform.c_str()));
262
263 return strPlatform;
264}
265
266
267/*********************************************************************************************************************************
268* Update agent class implementation *
269*********************************************************************************************************************************/
270UpdateAgent::UpdateAgent()
271{
272}
273
274UpdateAgent::~UpdateAgent()
275{
276}
277
278HRESULT UpdateAgent::FinalConstruct(void)
279{
280 return BaseFinalConstruct();
281}
282
283void UpdateAgent::FinalRelease(void)
284{
285 uninit();
286
287 BaseFinalRelease();
288}
289
290HRESULT UpdateAgent::init(VirtualBox *aVirtualBox)
291{
292 // Enclose the state transition NotReady->InInit->Ready.
293 AutoInitSpan autoInitSpan(this);
294 AssertReturn(autoInitSpan.isOk(), E_FAIL);
295
296 /* Weak reference to a VirtualBox object */
297 unconst(m_VirtualBox) = aVirtualBox;
298
299 HRESULT hr = unconst(m_EventSource).createObject();
300 if (SUCCEEDED(hr))
301 {
302 hr = m_EventSource->init();
303 if (SUCCEEDED(hr))
304 autoInitSpan.setSucceeded();
305 }
306
307 return hr;
308}
309
310void UpdateAgent::uninit(void)
311{
312 // Enclose the state transition Ready->InUninit->NotReady.
313 AutoUninitSpan autoUninitSpan(this);
314 if (autoUninitSpan.uninitDone())
315 return;
316
317 unconst(m_EventSource).setNull();
318}
319
320HRESULT UpdateAgent::checkFor(ComPtr<IProgress> &aProgress)
321{
322 RT_NOREF(aProgress);
323
324 return VBOX_E_NOT_SUPPORTED;
325}
326
327HRESULT UpdateAgent::download(ComPtr<IProgress> &aProgress)
328{
329 RT_NOREF(aProgress);
330
331 return VBOX_E_NOT_SUPPORTED;
332}
333
334HRESULT UpdateAgent::install(ComPtr<IProgress> &aProgress)
335{
336 RT_NOREF(aProgress);
337
338 return VBOX_E_NOT_SUPPORTED;
339}
340
341HRESULT UpdateAgent::rollback(void)
342{
343 return VBOX_E_NOT_SUPPORTED;
344}
345
346HRESULT UpdateAgent::getName(com::Utf8Str &aName)
347{
348 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
349
350 aName = mData.m_strName;
351
352 return S_OK;
353}
354
355HRESULT UpdateAgent::getEventSource(ComPtr<IEventSource> &aEventSource)
356{
357 LogFlowThisFuncEnter();
358
359 /* No need to lock - lifetime constant. */
360 m_EventSource.queryInterfaceTo(aEventSource.asOutParam());
361
362 LogFlowFuncLeaveRC(S_OK);
363 return S_OK;
364}
365
366HRESULT UpdateAgent::getOrder(ULONG *aOrder)
367{
368 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
369
370 *aOrder = 0; /* 0 means no order / disabled. */
371
372 return S_OK;
373}
374
375HRESULT UpdateAgent::getDependsOn(std::vector<com::Utf8Str> &aDeps)
376{
377 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
378
379 aDeps.resize(0); /* No dependencies by default. */
380
381 return S_OK;
382}
383
384HRESULT UpdateAgent::getVersion(com::Utf8Str &aVer)
385{
386 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
387
388 aVer = mData.m_lastResult.strVer;
389
390 return S_OK;
391}
392
393HRESULT UpdateAgent::getDownloadUrl(com::Utf8Str &aUrl)
394{
395 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
396
397 aUrl = mData.m_lastResult.strDownloadUrl;
398
399 return S_OK;
400}
401
402
403HRESULT UpdateAgent::getWebUrl(com::Utf8Str &aUrl)
404{
405 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
406
407 aUrl = mData.m_lastResult.strWebUrl;
408
409 return S_OK;
410}
411
412HRESULT UpdateAgent::getReleaseNotes(com::Utf8Str &aRelNotes)
413{
414 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
415
416 aRelNotes = mData.m_lastResult.strReleaseNotes;
417
418 return S_OK;
419}
420
421HRESULT UpdateAgent::getEnabled(BOOL *aEnabled)
422{
423 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
424
425 *aEnabled = m->fEnabled;
426
427 return S_OK;
428}
429
430HRESULT UpdateAgent::setEnabled(const BOOL aEnabled)
431{
432 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
433
434 m->fEnabled = aEnabled;
435
436 return i_commitSettings(alock);
437}
438
439
440HRESULT UpdateAgent::getHidden(BOOL *aHidden)
441{
442 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
443
444 *aHidden = mData.m_fHidden;
445
446 return S_OK;
447}
448
449HRESULT UpdateAgent::getState(UpdateState_T *aState)
450{
451 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
452
453 *aState = mData.m_enmState;
454
455 return S_OK;
456}
457
458HRESULT UpdateAgent::getCheckFrequency(ULONG *aFreqSeconds)
459{
460 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
461
462 *aFreqSeconds = m->uCheckFreqSeconds;
463
464 return S_OK;
465}
466
467HRESULT UpdateAgent::setCheckFrequency(ULONG aFreqSeconds)
468{
469 if (aFreqSeconds < RT_SEC_1DAY) /* Don't allow more frequent checks for now. */
470 return setError(E_INVALIDARG, tr("Frequency too small; one day is the minimum"));
471
472 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
473
474 m->uCheckFreqSeconds = aFreqSeconds;
475
476 return i_commitSettings(alock);
477}
478
479HRESULT UpdateAgent::getChannel(UpdateChannel_T *aChannel)
480{
481 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
482
483 *aChannel = m->enmChannel;
484
485 return S_OK;
486}
487
488HRESULT UpdateAgent::setChannel(UpdateChannel_T aChannel)
489{
490 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
491
492 m->enmChannel = aChannel;
493
494 return i_commitSettings(alock);
495}
496
497HRESULT UpdateAgent::getCheckCount(ULONG *aCount)
498{
499 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
500
501 *aCount = m->uCheckCount;
502
503 return S_OK;
504}
505
506HRESULT UpdateAgent::getRepositoryURL(com::Utf8Str &aRepo)
507{
508 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
509
510 aRepo = m->strRepoUrl;
511
512 return S_OK;
513}
514
515HRESULT UpdateAgent::setRepositoryURL(const com::Utf8Str &aRepo)
516{
517 if (!aRepo.startsWith("https://", com::Utf8Str::CaseInsensitive))
518 return setError(E_INVALIDARG, tr("Invalid URL scheme specified; only https:// is supported."));
519
520 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
521
522 m->strRepoUrl = aRepo;
523
524 return i_commitSettings(alock);
525}
526
527HRESULT UpdateAgent::getProxyMode(ProxyMode_T *aMode)
528{
529 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
530
531 *aMode = m->enmProxyMode;
532
533 return S_OK;
534}
535
536HRESULT UpdateAgent::setProxyMode(ProxyMode_T aMode)
537{
538 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
539
540 m->enmProxyMode = aMode;
541
542 return i_commitSettings(alock);
543}
544
545HRESULT UpdateAgent::getProxyURL(com::Utf8Str &aAddress)
546{
547 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
548
549 aAddress = m->strProxyUrl;
550
551 return S_OK;
552}
553
554HRESULT UpdateAgent::setProxyURL(const com::Utf8Str &aAddress)
555{
556 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
557
558 m->strProxyUrl = aAddress;
559
560 return i_commitSettings(alock);
561}
562
563HRESULT UpdateAgent::getLastCheckDate(com::Utf8Str &aDate)
564{
565 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
566
567 aDate = m->strLastCheckDate;
568
569 return S_OK;
570}
571
572HRESULT UpdateAgent::getIsCheckNeeded(BOOL *aCheckNeeded)
573{
574 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
575
576 /*
577 * Is update checking enabled at all?
578 */
579 if (!m->fEnabled)
580 {
581 *aCheckNeeded = FALSE;
582 return S_OK;
583 }
584
585 /*
586 * When was the last update?
587 */
588 if (m->strLastCheckDate.isEmpty()) /* No prior update check performed -- do so now. */
589 {
590 *aCheckNeeded = TRUE;
591 return S_OK;
592 }
593
594 RTTIMESPEC LastCheckTime;
595 if (!RTTimeSpecFromString(&LastCheckTime, Utf8Str(m->strLastCheckDate).c_str()))
596 {
597 *aCheckNeeded = TRUE; /* Invalid date set or error? Perform check. */
598 return S_OK;
599 }
600
601 /*
602 * Compare last update with how often we are supposed to check for updates.
603 */
604 if ( !m->uCheckFreqSeconds /* Paranoia */
605 || m->uCheckFreqSeconds < RT_SEC_1DAY) /* This is the minimum we currently allow. */
606 {
607 /* Consider config (enable, 0 day interval) as checking once but never again.
608 We've already check since we've got a date. */
609 *aCheckNeeded = FALSE;
610 return S_OK;
611 }
612
613 uint64_t const cCheckFreqDays = m->uCheckFreqSeconds / RT_SEC_1DAY_64;
614
615 RTTIMESPEC TimeDiff;
616 RTTimeSpecSub(RTTimeNow(&TimeDiff), &LastCheckTime);
617
618 int64_t const diffLastCheckSecs = RTTimeSpecGetSeconds(&TimeDiff);
619 int64_t const diffLastCheckDays = diffLastCheckSecs / RT_SEC_1DAY_64;
620
621 /* Be as accurate as possible. */
622 *aCheckNeeded = diffLastCheckSecs >= (int64_t)m->uCheckFreqSeconds ? TRUE : FALSE;
623
624 LogRel2(("Update agent (%s): Last update %RU64 days (%RU64 seconds) ago, check frequency is every %RU64 days (%RU64 seconds) -> Check %s\n",
625 mData.m_strName.c_str(), diffLastCheckDays, diffLastCheckSecs, cCheckFreqDays, m->uCheckFreqSeconds,
626 *aCheckNeeded ? "needed" : "not needed"));
627
628 return S_OK;
629}
630
631
632/*********************************************************************************************************************************
633* Internal helper methods of update agent class *
634*********************************************************************************************************************************/
635
636/**
637 * Loads the settings of the update agent base class.
638 *
639 * @returns HRESULT
640 * @param data Where to load the settings from.
641 */
642HRESULT UpdateAgent::i_loadSettings(const settings::UpdateAgent &data)
643{
644 AutoCaller autoCaller(this);
645 if (FAILED(autoCaller.rc())) return autoCaller.rc();
646
647 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
648
649 m->fEnabled = data.fEnabled;
650 m->enmChannel = data.enmChannel;
651 m->uCheckFreqSeconds = data.uCheckFreqSeconds;
652 m->strRepoUrl = data.strRepoUrl;
653 m->enmProxyMode = data.enmProxyMode;
654 m->strProxyUrl = data.strProxyUrl;
655 m->strLastCheckDate = data.strLastCheckDate;
656 m->uCheckCount = data.uCheckCount;
657
658 return S_OK;
659}
660
661/**
662 * Saves the settings of the update agent base class.
663 *
664 * @returns HRESULT
665 * @param data Where to save the settings to.
666 */
667HRESULT UpdateAgent::i_saveSettings(settings::UpdateAgent &data)
668{
669 AutoCaller autoCaller(this);
670 if (FAILED(autoCaller.rc())) return autoCaller.rc();
671
672 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
673
674 data = *m;
675
676 return S_OK;
677}
678
679/**
680 * Sets the update check count.
681 *
682 * @returns HRESULT
683 * @param aCount Update check count to set.
684 */
685HRESULT UpdateAgent::i_setCheckCount(ULONG aCount)
686{
687 AutoCaller autoCaller(this);
688 if (FAILED(autoCaller.rc())) return autoCaller.rc();
689
690 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
691
692 m->uCheckCount = aCount;
693
694 return i_commitSettings(alock);
695}
696
697/**
698 * Sets the last update check date.
699 *
700 * @returns HRESULT
701 * @param aDate Last update check date to set.
702 * Must be in ISO 8601 format (e.g. 2020-05-11T21:13:39.348416000Z).
703 */
704HRESULT UpdateAgent::i_setLastCheckDate(const com::Utf8Str &aDate)
705{
706 AutoCaller autoCaller(this);
707 if (FAILED(autoCaller.rc())) return autoCaller.rc();
708
709 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
710
711 m->strLastCheckDate = aDate;
712
713 return i_commitSettings(alock);
714}
715
716/**
717 * Internal helper function to commit modified settings.
718 *
719 * @returns HRESULT
720 * @param aLock Write lock to release before committing settings.
721 */
722HRESULT UpdateAgent::i_commitSettings(AutoWriteLock &aLock)
723{
724 aLock.release();
725
726 ::FireUpdateAgentSettingsChangedEvent(m_EventSource, "" /** @todo Include attribute hints */);
727
728 AutoWriteLock vboxLock(m_VirtualBox COMMA_LOCKVAL_SRC_POS);
729 return m_VirtualBox->i_saveSettings();
730}
731
732/**
733 * Reports an error by setting the error info and also information subscribed listeners.
734 *
735 * @returns HRESULT
736 * @param vrc Result code (IPRT-style) to report.
737 * @param pcszMsgFmt Error message to report.
738 * @param ... Format string for \a pcszMsgFmt.
739 */
740HRESULT UpdateAgent::i_reportError(int vrc, const char *pcszMsgFmt, ...)
741{
742 va_list va;
743 va_start(va, pcszMsgFmt);
744
745 char *psz = NULL;
746 if (RTStrAPrintfV(&psz, pcszMsgFmt, va) <= 0)
747 return E_OUTOFMEMORY;
748
749 LogRel(("Update agent (%s): %s\n", mData.m_strName.c_str(), psz));
750
751 ::FireUpdateAgentErrorEvent(m_EventSource, psz, vrc);
752
753 HRESULT const rc = setErrorVrc(VERR_COM_IPRT_ERROR /** @todo Translate HTTP errors to COM? */, pcszMsgFmt, va);
754
755 va_end(va);
756 RTStrFree(psz);
757
758 return rc;
759}
760
761
762/*********************************************************************************************************************************
763* Host update implementation *
764*********************************************************************************************************************************/
765
766HostUpdateAgent::HostUpdateAgent(void)
767{
768}
769
770HostUpdateAgent::~HostUpdateAgent(void)
771{
772}
773
774
775HRESULT HostUpdateAgent::FinalConstruct(void)
776{
777 return BaseFinalConstruct();
778}
779
780void HostUpdateAgent::FinalRelease(void)
781{
782 uninit();
783
784 BaseFinalRelease();
785}
786
787HRESULT HostUpdateAgent::init(VirtualBox *aVirtualBox)
788{
789 // Enclose the state transition NotReady->InInit->Ready.
790 AutoInitSpan autoInitSpan(this);
791 AssertReturn(autoInitSpan.isOk(), E_FAIL);
792
793 /* Weak reference to a VirtualBox object */
794 unconst(m_VirtualBox) = aVirtualBox;
795
796 /* Initialize the bare minimum to get things going.
797 ** @todo Add more stuff later here. */
798 mData.m_strName = "VirtualBox";
799 mData.m_fHidden = false;
800
801 /* Set default repository. */
802 m->strRepoUrl = "https://update.virtualbox.org";
803
804 autoInitSpan.setSucceeded();
805 return S_OK;
806}
807
808void HostUpdateAgent::uninit(void)
809{
810 // Enclose the state transition Ready->InUninit->NotReady.
811 AutoUninitSpan autoUninitSpan(this);
812 if (autoUninitSpan.uninitDone())
813 return;
814}
815
816HRESULT HostUpdateAgent::checkFor(ComPtr<IProgress> &aProgress)
817{
818 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
819
820 ComObjPtr<Progress> pProgress;
821 HRESULT rc = pProgress.createObject();
822 if (FAILED(rc))
823 return rc;
824
825 rc = pProgress->init(m_VirtualBox,
826 static_cast<IUpdateAgent*>(this),
827 tr("Checking for update for %s ...", this->mData.m_strName.c_str()),
828 TRUE /* aCancelable */);
829 if (FAILED(rc))
830 return rc;
831
832 /* initialize the worker task */
833 UpdateAgentTask *pTask = new UpdateAgentTask(this, pProgress);
834 rc = pTask->createThread();
835 pTask = NULL;
836 if (FAILED(rc))
837 return rc;
838
839 return pProgress.queryInterfaceTo(aProgress.asOutParam());
840}
841
842
843/*********************************************************************************************************************************
844* Host update internal functions *
845*********************************************************************************************************************************/
846
847/**
848 * Task callback to perform an update check for the VirtualBox host (core).
849 *
850 * @returns HRESULT
851 * @param pTask Associated update agent task to use.
852 */
853DECLCALLBACK(HRESULT) HostUpdateAgent::i_checkForUpdateTask(UpdateAgentTask *pTask)
854{
855 RT_NOREF(pTask);
856
857 // Following the sequence of steps in UIUpdateStepVirtualBox::sltStartStep()
858 // Build up our query URL starting with the configured repository.
859 Utf8Str strUrl;
860 strUrl.appendPrintf("%s/query.php/?", m->strRepoUrl.c_str());
861
862 // Add platform ID.
863 Bstr platform;
864 HRESULT rc = m_VirtualBox->COMGETTER(PackageType)(platform.asOutParam());
865 AssertComRCReturn(rc, rc);
866 strUrl.appendPrintf("platform=%ls", platform.raw()); // e.g. SOLARIS_64BITS_GENERIC
867
868 // Get the complete current version string for the query URL
869 Bstr versionNormalized;
870 rc = m_VirtualBox->COMGETTER(VersionNormalized)(versionNormalized.asOutParam());
871 AssertComRCReturn(rc, rc);
872 strUrl.appendPrintf("&version=%ls", versionNormalized.raw()); // e.g. 6.1.1
873#ifdef DEBUG // Comment out previous line and uncomment this one for testing.
874// strUrl.appendPrintf("&version=6.0.12");
875#endif
876
877 ULONG revision = 0;
878 rc = m_VirtualBox->COMGETTER(Revision)(&revision);
879 AssertComRCReturn(rc, rc);
880 strUrl.appendPrintf("_%u", revision); // e.g. 135618
881
882 // Update the last update check timestamp.
883 RTTIME Time;
884 RTTIMESPEC TimeNow;
885 char szTimeStr[RTTIME_STR_LEN];
886 RTTimeToString(RTTimeExplode(&Time, RTTimeNow(&TimeNow)), szTimeStr, sizeof(szTimeStr));
887 LogRel2(("Update agent (%s): Setting last update check timestamp to '%s'\n", mData.m_strName.c_str(), szTimeStr));
888
889 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
890
891 m->strLastCheckDate = szTimeStr;
892 m->uCheckCount++;
893
894 rc = i_commitSettings(alock);
895 AssertComRCReturn(rc, rc);
896
897 strUrl.appendPrintf("&count=%RU32", m->uCheckCount);
898
899 // Update the query URL (if necessary) with the 'channel' information.
900 switch (m->enmChannel)
901 {
902 case UpdateChannel_All:
903 strUrl.appendPrintf("&branch=allrelease"); // query.php expects 'allrelease' and not 'allreleases'
904 break;
905 case UpdateChannel_WithBetas:
906 strUrl.appendPrintf("&branch=withbetas");
907 break;
908 /** @todo Handle UpdateChannel_WithTesting once implemented on the backend. */
909 case UpdateChannel_Stable:
910 RT_FALL_THROUGH();
911 default:
912 strUrl.appendPrintf("&branch=stable");
913 break;
914 }
915
916 LogRel2(("Update agent (%s): Using URL '%s'\n", mData.m_strName.c_str(), strUrl.c_str()));
917
918 /*
919 * Compose the User-Agent header for the GET request.
920 */
921 Bstr version;
922 rc = m_VirtualBox->COMGETTER(Version)(version.asOutParam()); // e.g. 6.1.0_RC1
923 AssertComRCReturn(rc, rc);
924
925 Utf8StrFmt const strUserAgent("VirtualBox %ls <%s>", version.raw(), UpdateAgent::i_getPlatformInfo().c_str());
926 LogRel2(("Update agent (%s): Using user agent '%s'\n", mData.m_strName.c_str(), strUserAgent.c_str()));
927
928 /*
929 * Create the HTTP client instance and pass it to a inner worker method to
930 * ensure proper cleanup.
931 */
932 RTHTTP hHttp = NIL_RTHTTP;
933 int vrc = RTHttpCreate(&hHttp);
934 if (RT_SUCCESS(vrc))
935 {
936 try
937 {
938 rc = i_checkForUpdateInner(hHttp, strUrl, strUserAgent);
939 }
940 catch (...)
941 {
942 AssertFailed();
943 rc = E_UNEXPECTED;
944 }
945 RTHttpDestroy(hHttp);
946 }
947 else
948 rc = i_reportError(vrc, tr("RTHttpCreate() failed: %Rrc"), vrc);
949
950 return rc;
951}
952
953/**
954 * Inner function of the actual update checking mechanism.
955 *
956 * @returns HRESULT
957 * @param hHttp HTTP client instance to use for checking.
958 * @param strUrl URL of repository to check.
959 * @param strUserAgent HTTP user agent to use for checking.
960 */
961HRESULT HostUpdateAgent::i_checkForUpdateInner(RTHTTP hHttp, Utf8Str const &strUrl, Utf8Str const &strUserAgent)
962{
963 /** @todo Are there any other headers needed to be added first via RTHttpSetHeaders()? */
964 int vrc = RTHttpAddHeader(hHttp, "User-Agent", strUserAgent.c_str(), strUserAgent.length(), RTHTTPADDHDR_F_BACK);
965 if (RT_FAILURE(vrc))
966 return i_reportError(vrc, tr("RTHttpAddHeader() failed: %Rrc (user agent)"), vrc);
967
968 /*
969 * Configure proxying.
970 */
971 if (m->enmProxyMode == ProxyMode_Manual)
972 {
973 vrc = RTHttpSetProxyByUrl(hHttp, m->strProxyUrl.c_str());
974 if (RT_FAILURE(vrc))
975 return i_reportError(vrc, tr("RTHttpSetProxyByUrl() failed: %Rrc"), vrc);
976 }
977 else if (m->enmProxyMode == ProxyMode_System)
978 {
979 vrc = RTHttpUseSystemProxySettings(hHttp);
980 if (RT_FAILURE(vrc))
981 return i_reportError(vrc, tr("RTHttpUseSystemProxySettings() failed: %Rrc"), vrc);
982 }
983 else
984 Assert(m->enmProxyMode == ProxyMode_NoProxy);
985
986 /*
987 * Perform the GET request, returning raw binary stuff.
988 */
989 void *pvResponse = NULL;
990 size_t cbResponse = 0;
991 vrc = RTHttpGetBinary(hHttp, strUrl.c_str(), &pvResponse, &cbResponse);
992 if (RT_FAILURE(vrc))
993 return i_reportError(vrc, tr("RTHttpGetBinary() failed: %Rrc"), vrc);
994
995 /* Note! We can do nothing that might throw exceptions till we call RTHttpFreeResponse! */
996
997 /*
998 * If url is platform=DARWIN_64BITS_GENERIC&version=6.0.12&branch=stable for example, the reply is:
999 * 6.0.14<SPACE>https://download.virtualbox.org/virtualbox/6.0.14/VirtualBox-6.0.14-133895-OSX.dmg
1000 * If no update required, 'UPTODATE' is returned.
1001 */
1002 /* Parse out the two first words of the response, ignoring whatever follows: */
1003 const char *pchResponse = (const char *)pvResponse;
1004 while (cbResponse > 0 && *pchResponse == ' ')
1005 cbResponse--, pchResponse++;
1006
1007 char ch;
1008 const char *pchWord0 = pchResponse;
1009 while (cbResponse > 0 && (ch = *pchResponse) != ' ' && ch != '\0')
1010 cbResponse--, pchResponse++;
1011 size_t const cchWord0 = (size_t)(pchResponse - pchWord0);
1012
1013 while (cbResponse > 0 && *pchResponse == ' ')
1014 cbResponse--, pchResponse++;
1015 const char *pchWord1 = pchResponse;
1016 while (cbResponse > 0 && (ch = *pchResponse) != ' ' && ch != '\0')
1017 cbResponse--, pchResponse++;
1018 size_t const cchWord1 = (size_t)(pchResponse - pchWord1);
1019
1020 HRESULT rc;
1021
1022 /* Decode the two word: */
1023 static char const s_szUpToDate[] = "UPTODATE";
1024 if ( cchWord0 == sizeof(s_szUpToDate) - 1
1025 && memcmp(pchWord0, s_szUpToDate, sizeof(s_szUpToDate) - 1) == 0)
1026 {
1027 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1028
1029 mData.m_enmState = UpdateState_NotAvailable;
1030 rc = S_OK;
1031
1032 alock.release(); /* Release lock before firing off event. */
1033
1034 ::FireUpdateAgentStateChangedEvent(m_EventSource, UpdateState_NotAvailable);
1035 }
1036 else
1037 {
1038 mData.m_enmState = UpdateState_Error; /* Play safe by default. */
1039
1040 vrc = RTStrValidateEncodingEx(pchWord0, cchWord0, 0 /*fFlags*/);
1041 if (RT_SUCCESS(vrc))
1042 vrc = RTStrValidateEncodingEx(pchWord1, cchWord1, 0 /*fFlags*/);
1043 if (RT_SUCCESS(vrc))
1044 {
1045 /** @todo Any additional sanity checks we could perform here? */
1046 rc = mData.m_lastResult.strVer.assignEx(pchWord0, cchWord0);
1047 if (SUCCEEDED(rc))
1048 rc = mData.m_lastResult.strDownloadUrl.assignEx(pchWord1, cchWord1);
1049
1050 if (SUCCEEDED(rc))
1051 {
1052 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1053
1054 /** @todo Implement this on the backend first.
1055 * We also could do some guessing based on the installed version vs. reported update version? */
1056 mData.m_lastResult.enmSeverity = UpdateSeverity_Invalid;
1057 mData.m_enmState = UpdateState_Available;
1058
1059 alock.release(); /* Release lock before firing off events. */
1060
1061 ::FireUpdateAgentStateChangedEvent(m_EventSource, UpdateState_Available);
1062 ::FireUpdateAgentAvailableEvent(m_EventSource, mData.m_lastResult.strVer, m->enmChannel,
1063 mData.m_lastResult.enmSeverity, mData.m_lastResult.strDownloadUrl,
1064 mData.m_lastResult.strWebUrl, mData.m_lastResult.strReleaseNotes);
1065 }
1066 else
1067 rc = i_reportError(VERR_GENERAL_FAILURE /** @todo Use a better rc */,
1068 tr("Invalid server response [1]: %Rhrc (%.*Rhxs -- %.*Rhxs)"),
1069 rc, cchWord0, pchWord0, cchWord1, pchWord1);
1070
1071 LogRel2(("Update agent (%s): HTTP server replied: %.*s %.*s\n",
1072 mData.m_strName.c_str(), cchWord0, pchWord0, cchWord1, pchWord1));
1073 }
1074 else
1075 rc = i_reportError(vrc, tr("Invalid server response [2]: %Rrc (%.*Rhxs -- %.*Rhxs)"),
1076 vrc, cchWord0, pchWord0, cchWord1, pchWord1);
1077 }
1078
1079 RTHttpFreeResponse(pvResponse);
1080
1081 return rc;
1082}
1083
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