summaryrefslogtreecommitdiff
path: root/src/VBox/HostDrivers/Support/SUPSvc.cpp
blob: 4b3f2ae240b27f44fd01d3d42c79fca2f69c1504 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
/* $Id$ */
/** @file
 * VirtualBox Support Service - Common Code.
 */

/*
 * Copyright (C) 2008-2019 Oracle Corporation
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 *
 * The contents of this file may alternatively be used under the terms
 * of the Common Development and Distribution License Version 1.0
 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
 * VirtualBox OSE distribution, in which case the provisions of the
 * CDDL are applicable instead of those of the GPL.
 *
 * You may elect to license modified versions of this file under the
 * terms and conditions of either the GPL or the CDDL or both.
 */


/*********************************************************************************************************************************
*   Header Files                                                                                                                 *
*********************************************************************************************************************************/
#define LOG_GROUP   LOG_GROUP_SUP
#include <VBox/log.h>
#include <iprt/string.h>
#include <iprt/mem.h>
#include <iprt/stream.h>
#include <iprt/getopt.h>

#include "SUPSvcInternal.h"


/*********************************************************************************************************************************
*   Structures and Typedefs                                                                                                      *
*********************************************************************************************************************************/
/**
 * Service state.
 */
typedef enum SUPSVCSERVICESTATE
{
    kSupSvcServiceState_Invalid = 0,
    kSupSvcServiceState_NotCreated,
    kSupSvcServiceState_Paused,
    kSupSvcServiceState_Running,
    kSupSvcServiceState_End
} SUPSVCSERVICESTATE;


/**
 * Service descriptor.
 */
typedef struct SUPSVCSERVICE
{
    /** The service name. */
    const char *pszName;
    /** The service state. */
    SUPSVCSERVICESTATE enmState;
    /** The instance handle returned by pfnCreate. */
    void *pvInstance;

    /**
     * Create the service (don't start it).
     *
     * @returns VBox status code, log entry is written on failure.
     * @param   ppvInstance     Where to store the instance handle.
     */
    DECLCALLBACKMEMBER(int,  pfnCreate)(void **ppvInstance);

    /**
     * Start the service.
     *
     * @returns VBox status code, log entry is written on failure.
     * @param   pvInstance      The instance handle.
     */
    DECLCALLBACKMEMBER(void, pfnStart)(void *pvInstance);

    /**
     * Attempt to stop a running service.
     *
     * This should fail if there are active clients. A stopped service
     * can be restarted by calling pfnStart.
     *
     * @returns VBox status code, log entry is written on failure.
     * @param   pvInstance      The instance handle.
     */
    DECLCALLBACKMEMBER(int,  pfnTryStop)(void *pvInstance);

    /**
     * Destroy the service, stopping first it if necessary.
     *
     * @param   pvInstance      The instance handle.
     * @param   fRunning        Whether the service is running or not.
     */
    DECLCALLBACKMEMBER(void, pfnStopAndDestroy)(void *pvInstance, bool fRunning);
} SUPSVCSERVICE;
/** Pointer to a service descriptor. */
typedef SUPSVCSERVICE *PSUPSVCSERVICE;
/** Pointer to a const service descriptor. */
typedef SUPSVCSERVICE const *PCSUPSVCSERVICE;



/*********************************************************************************************************************************
*   Global Variables                                                                                                             *
*********************************************************************************************************************************/
static SUPSVCSERVICE g_aServices[] =
{
    {
        "Global",
        kSupSvcServiceState_NotCreated,
        NULL,
        supSvcGlobalCreate,
        supSvcGlobalStart,
        supSvcGlobalTryStop,
        supSvcGlobalStopAndDestroy,
    }
#ifdef RT_OS_WINDOWS
    ,
    {
        "Grant",
        kSupSvcServiceState_NotCreated,
        NULL,
        supSvcGrantCreate,
        supSvcGrantStart,
        supSvcGrantTryStop,
        supSvcGrantStopAndDestroy,
    }
#endif
};



/**
 * Instantiates and starts the services.
 *
 * @returns VBox status code. Done bitching on failure.
 */
int supSvcCreateAndStartServices(void)
{
    LogFlowFuncEnter();

    /*
     * Validate that all services are in the NotCreated state.
     */
    unsigned i;
    for (i = 0; i < RT_ELEMENTS(g_aServices); i++)
        if (g_aServices[i].enmState != kSupSvcServiceState_NotCreated)
        {
            supSvcLogError("service %s in state %d, expected state %d (NotCreated)",
                           g_aServices[i].pszName,  g_aServices[i].enmState, kSupSvcServiceState_NotCreated);
            return VERR_WRONG_ORDER;
        }

    /*
     * Create all the services, then start them.
     */
    int rc = VINF_SUCCESS;
    for (i = 0; i < RT_ELEMENTS(g_aServices); i++)
    {
        void *pvInstance = NULL;
        int rc = g_aServices[i].pfnCreate(&pvInstance);
        if (RT_FAILURE(rc))
        {
            Log(("supSvcCreateAndStartServices: %s -> %Rrc\n", g_aServices[i].pszName, rc));
            break;
        }
        g_aServices[i].pvInstance = pvInstance;
        g_aServices[i].enmState = kSupSvcServiceState_Paused;
    }
    if (RT_SUCCESS(rc))
    {
        for (i = 0; i < RT_ELEMENTS(g_aServices); i++)
        {
            g_aServices[i].pfnStart(g_aServices[i].pvInstance);
            g_aServices[i].enmState = kSupSvcServiceState_Running;
        }
    }
    else
    {
        /*
         * Destroy any services we managed to instantiate.
         */
        while (i-- > 0)
        {
            g_aServices[i].pfnStopAndDestroy(g_aServices[i].pvInstance, false /* fRunning */);
            g_aServices[i].pvInstance = NULL;
            g_aServices[i].enmState = kSupSvcServiceState_NotCreated;
        }
    }

    LogFlow(("supSvcCreateAndStartServices: returns %Rrc\n", rc));
    return rc;
}


/**
 * Checks if it's possible to stop the services.
 *
 * @returns VBox status code, done bitching on failure.
 */
int supSvcTryStopServices(void)
{
    LogFlowFuncEnter();

    /*
     * Check that the services are all created and count the running ones.
     */
    unsigned i;
    unsigned cRunning = 0;
    for (i = 0; i < RT_ELEMENTS(g_aServices); i++)
        if (g_aServices[i].enmState == kSupSvcServiceState_Running)
            cRunning++;
        else if (g_aServices[i].enmState == kSupSvcServiceState_NotCreated)
        {
            supSvcLogError("service %s in state %d (NotCreated), expected pause or running",
                           g_aServices[i].pszName,  g_aServices[i].enmState, kSupSvcServiceState_NotCreated);
            return VERR_WRONG_ORDER;
        }
    if (!cRunning)
        return VINF_SUCCESS; /* all stopped, nothing to do. */
    Assert(cRunning == RT_ELEMENTS(g_aServices)); /* all or nothing */

    /*
     * Try stop them in reverse of start order.
     */
    int rc = VINF_SUCCESS;
    i = RT_ELEMENTS(g_aServices);
    while (i-- > 0)
    {
        rc = g_aServices[i].pfnTryStop(g_aServices[i].pvInstance);
        if (RT_FAILURE(rc))
        {
            Log(("supSvcTryStopServices: %s -> %Rrc\n", g_aServices[i].pszName, rc));
            break;
        }
        g_aServices[i].enmState = kSupSvcServiceState_Paused;
    }
    if (RT_FAILURE(rc))
    {
        /* Failed, restart the ones we succeeded in stopping. */
        while (++i < RT_ELEMENTS(g_aServices))
        {
            g_aServices[i].pfnStart(g_aServices[i].pvInstance);
            g_aServices[i].enmState = kSupSvcServiceState_Running;
        }
    }
    LogFlow(("supSvcTryStopServices: returns %Rrc\n", rc));
    return rc;
}


/**
 * Stops and destroys the services.
 */
void supSvcStopAndDestroyServices(void)
{
    LogFlowFuncEnter();

    /*
     * Stop and destroy the service in reverse of start order.
     */
    unsigned i = RT_ELEMENTS(g_aServices);
    while (i-- > 0)
        if (g_aServices[i].enmState != kSupSvcServiceState_NotCreated)
        {
            g_aServices[i].pfnStopAndDestroy(g_aServices[i].pvInstance,
                                             g_aServices[i].enmState == kSupSvcServiceState_Running);
            g_aServices[i].pvInstance = NULL;
            g_aServices[i].enmState = kSupSvcServiceState_NotCreated;
        }

    LogFlowFuncLeave();
}



/**
 * Logs the message to the appropriate system log.
 *
 * In debug builds this will also put it in the debug log.
 *
 * @param   pszMsg      The log string.
 *
 * @remarks This may later be replaced by the release logger and callback destination(s).
 */
void supSvcLogErrorStr(const char *pszMsg)
{
    supSvcOsLogErrorStr(pszMsg);
    LogRel(("%s\n", pszMsg));
}


/**
 * Logs the message to the appropriate system log.
 *
 * In debug builds this will also put it in the debug log.
 *
 * @param   pszFormat   The log string. No trailing newline.
 * @param   va          Format arguments.
 *
 * @todo    This should later be replaced by the release logger and callback destination(s).
 */
void supSvcLogErrorV(const char *pszFormat, va_list va)
{
    if (*pszFormat)
    {
        char *pszMsg = NULL;
        if (RTStrAPrintfV(&pszMsg, pszFormat, va) != -1)
        {
            supSvcLogErrorStr(pszMsg);
            RTStrFree(pszMsg);
        }
        else
            supSvcLogErrorStr(pszFormat);
    }
}


/**
 * Logs the error message to the appropriate system log.
 *
 * In debug builds this will also put it in the debug log.
 *
 * @param   pszFormat   The log string. No trailing newline.
 * @param   ...         Format arguments.
 *
 * @todo    This should later be replaced by the release logger and callback destination(s).
 */
void supSvcLogError(const char *pszFormat, ...)
{
    va_list va;
    va_start(va, pszFormat);
    supSvcLogErrorV(pszFormat, va);
    va_end(va);
}


/**
 * Deals with RTGetOpt failure, bitching in the system log.
 *
 * @returns 1
 * @param   pszAction       The action name.
 * @param   rc              The RTGetOpt return value.
 * @param   argc            The argument count.
 * @param   argv            The argument vector.
 * @param   iArg            The argument index.
 * @param   pValue          The value returned by RTGetOpt.
 */
int supSvcLogGetOptError(const char *pszAction, int rc, int argc, char **argv, int iArg, PCRTOPTIONUNION pValue)
{
    supSvcLogError("%s - RTGetOpt failure, %Rrc (%d): %s",
                   pszAction, rc, rc, iArg < argc ? argv[iArg] : "<null>");
    return 1;
}


/**
 * Bitch about too many arguments (after RTGetOpt stops) in the system log.
 *
 * @returns 1
 * @param   pszAction       The action name.
 * @param   argc            The argument count.
 * @param   argv            The argument vector.
 * @param   iArg            The argument index.
 */
int supSvcLogTooManyArgsError(const char *pszAction, int argc, char **argv, int iArg)
{
    Assert(iArg < argc);
    supSvcLogError("%s - Too many arguments: %s", pszAction, argv[iArg]);
    for ( ; iArg < argc; iArg++)
        LogRel(("arg#%i: %s\n", iArg, argv[iArg]));
    return 1;
}


/**
 * Prints an error message to the screen.
 *
 * @param   pszFormat   The message format string.
 * @param   va          Format arguments.
 */
void supSvcDisplayErrorV(const char *pszFormat, va_list va)
{
    RTStrmPrintf(g_pStdErr, "VBoxSupSvc error: ");
    RTStrmPrintfV(g_pStdErr, pszFormat, va);
    Log(("supSvcDisplayErrorV: %s", pszFormat)); /** @todo format it! */
}


/**
 * Prints an error message to the screen.
 *
 * @param   pszFormat   The message format string.
 * @param   ...         Format arguments.
 */
void supSvcDisplayError(const char *pszFormat, ...)
{
    va_list va;
    va_start(va, pszFormat);
    supSvcDisplayErrorV(pszFormat, va);
    va_end(va);
}


/**
 * Deals with RTGetOpt failure.
 *
 * @returns 1
 * @param   pszAction       The action name.
 * @param   rc              The RTGetOpt return value.
 * @param   argc            The argument count.
 * @param   argv            The argument vector.
 * @param   iArg            The argument index.
 * @param   pValue          The value returned by RTGetOpt.
 */
int supSvcDisplayGetOptError(const char *pszAction, int rc, int argc, char **argv, int iArg, PCRTOPTIONUNION pValue)
{
    supSvcDisplayError("%s - RTGetOpt failure, %Rrc (%d): %s\n",
                       pszAction, rc, rc, iArg < argc ? argv[iArg] : "<null>");
    return 1;
}


/**
 * Bitch about too many arguments (after RTGetOpt stops).
 *
 * @returns 1
 * @param   pszAction       The action name.
 * @param   argc            The argument count.
 * @param   argv            The argument vector.
 * @param   iArg            The argument index.
 */
int supSvcDisplayTooManyArgsError(const char *pszAction, int argc, char **argv, int iArg)
{
    Assert(iArg < argc);
    supSvcDisplayError("%s - Too many arguments: %s\n", pszAction, argv[iArg]);
    return 1;
}