• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

stefanberger / swtpm / #2810

30 Apr 2025 01:23AM UTC coverage: 73.265% (-0.2%) from 73.433%
#2810

push

travis-ci

web-flow
Merge 6d94f1c83 into 485787d76

8057 of 10997 relevant lines covered (73.27%)

13565.56 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

92.36
/src/swtpm/mainloop.c
1
/*
2
 * mainloop.c -- The TPM Emulator's main processing loop
3
 *
4
 * (c) Copyright IBM Corporation 2014, 2015, 2016
5
 *
6
 * Author: Stefan Berger <stefanb@us.ibm.com>
7
 *
8
 * All rights reserved.
9
 *
10
 * Redistribution and use in source and binary forms, with or without
11
 * modification, are permitted provided that the following conditions are
12
 * met:
13
 *
14
 * Redistributions of source code must retain the above copyright notice,
15
 * this list of conditions and the following disclaimer.
16
 *
17
 * Redistributions in binary form must reproduce the above copyright
18
 * notice, this list of conditions and the following disclaimer in the
19
 * documentation and/or other materials provided with the distribution.
20
 *
21
 * Neither the names of the IBM Corporation nor the names of its
22
 * contributors may be used to endorse or promote products derived from
23
 * this software without specific prior written permission.
24
 *
25
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36
 */
37

38
/* mainLoop() is the main server loop.
39

40
   It reads a TPM request, processes the ordinal, and writes the response
41
*/
42

43
#include <config.h>
44

45
#include <errno.h>
46
#include <stdio.h>
47
#include <stdint.h>
48
#include <stdbool.h>
49
#include <stdlib.h>
50
#include <string.h>
51
#include <poll.h>
52
#include <sys/stat.h>
53
#include <fcntl.h>
54
#include <sys/socket.h>
55

56
#include <libtpms/tpm_error.h>
57
#include <libtpms/tpm_library.h>
58
#include <libtpms/tpm_memory.h>
59

60
#include "swtpm_debug.h"
61
#include "swtpm_io.h"
62
#include "tpmlib.h"
63
#include "locality.h"
64
#include "logging.h"
65
#include "ctrlchannel.h"
66
#include "mainloop.h"
67
#include "utils.h"
68
#include "sys_dependencies.h"
69
#include "compiler_dependencies.h"
70
#include "swtpm_utils.h"
71
#include "swtpm_nvstore.h"
72

73
/* local variables */
74
static TPM_MODIFIER_INDICATOR g_locality;
75

76
bool g_mainloop_terminate;
77

78
TPM_RESULT
79
mainloop_cb_get_locality(TPM_MODIFIER_INDICATOR *loc,
28,336✔
80
                         uint32_t tpmnum SWTPM_ATTR_UNUSED)
81
{
82
    *loc = g_locality;
28,336✔
83

84
    return TPM_SUCCESS;
28,336✔
85
}
86

87
/* ensure that the storage is locked; returns false in case of failure */
88
bool mainloop_ensure_locked_storage(struct mainLoopParams *mlp)
42,387✔
89
{
90
    TPM_RESULT res;
42,387✔
91

92
    if (mlp->storage_locked)
42,387✔
93
        return true;
94

95
    /* if NVRAM hasn't been initialized yet locking may need to be retried */
96
    res = SWTPM_NVRAM_Lock_Storage(mlp->locking_retries);
154✔
97
    if (res == TPM_RETRY)
154✔
98
        return true;
99
    if (res != TPM_SUCCESS)
29✔
100
        return false;
101

102
    mlp->locking_retries = 0;
29✔
103
    mlp->storage_locked = true;
29✔
104
    mlp->incoming_migration = false;
29✔
105

106
    return true;
29✔
107
}
108

109
void mainloop_unlock_nvram(struct mainLoopParams *mlp,
7✔
110
                           unsigned int locking_retries)
111
{
112
    SWTPM_NVRAM_Unlock();
7✔
113

114
    mlp->storage_locked = false;
7✔
115
    mlp->locking_retries = locking_retries;
7✔
116
}
7✔
117

118
int mainLoop(struct mainLoopParams *mlp, int notify_fd, bool tpm_running)
409✔
119
{
120
    TPM_RESULT          rc = 0;
409✔
121
    TPM_CONNECTION_FD   connection_fd;             /* file descriptor for read/write */
409✔
122
    unsigned char       *command = NULL;           /* command buffer */
409✔
123
    uint32_t            command_length;            /* actual length of command bytes */
409✔
124
    uint32_t            max_command_length;        /* command buffer size */
409✔
125
    off_t               cmd_offset;
409✔
126
    /* The response buffer is reused for each command. Thus it can grow but never shrink */
127
    unsigned char       *rbuffer = NULL;           /* actual response bytes */
409✔
128
    uint32_t            rlength = 0;               /* bytes in response buffer */
409✔
129
    uint32_t            rTotal = 0;                /* total allocated bytes */
409✔
130
    int                 ctrlfd;
409✔
131
    int                 ctrlclntfd;
409✔
132
    int                 sockfd;
409✔
133
    int                 ready;
409✔
134
    struct iovec        iov[3];
409✔
135
    uint32_t            ack = htobe32(0);
409✔
136
    struct tpm2_resp_prefix respprefix;
409✔
137
    uint32_t            lastCommand;
409✔
138

139
    /* poolfd[] indexes */
140
    enum {
409✔
141
        DATA_CLIENT_FD = 0,
142
        NOTIFY_FD,
143
        CTRL_SERVER_FD,
144
        CTRL_CLIENT_FD,
145
        DATA_SERVER_FD
146
    };
147

148
    TPM_DEBUG("mainLoop:\n");
409✔
149

150
    max_command_length = tpmlib_get_tpm_property(TPMPROP_TPM_BUFFER_MAX) +
409✔
151
                         sizeof(struct tpm2_send_command_prefix);
152

153
    command = malloc(max_command_length);
409✔
154
    if (!command) {
409✔
155
        logprintf(STDERR_FILENO, "Could not allocate %u bytes for buffer.\n",
×
156
                  max_command_length);
157
        return TPM_FAIL;
×
158
    }
159

160
    /* header and trailer that we may send by setting iov_len */
161
    iov[0].iov_base = &respprefix;
409✔
162
    iov[0].iov_len = 0;
409✔
163
    iov[2].iov_base = &ack;
409✔
164
    iov[2].iov_len = 0;
409✔
165

166
    connection_fd.fd = -1;
409✔
167
    ctrlfd = ctrlchannel_get_fd(mlp->cc);
409✔
168
    ctrlclntfd = ctrlchannel_get_client_fd(mlp->cc);
409✔
169

170
    sockfd = SWTPM_IO_GetSocketFD();
409✔
171

172
    if (mlp->startupType != _TPM_ST_NONE) {
409✔
173
        command_length = tpmlib_create_startup_cmd(
200✔
174
                                  mlp->startupType,
175
                                  mlp->tpmversion,
176
                                  command, max_command_length);
177
        if (command_length > 0) {
200✔
178
            mlp->lastCommand = tpmlib_get_cmd_ordinal(command, command_length);
200✔
179
            rc = TPMLIB_Process(&rbuffer, &rlength, &rTotal,
200✔
180
                                command, command_length);
181
        }
182

183
        if (rc || command_length == 0) {
200✔
184
            g_mainloop_terminate = true;
×
185
            if (rc)
×
186
                logprintf(STDERR_FILENO, "Could not send Startup: 0x%x\n", rc);
×
187
        }
188
    }
189

190
    while (!g_mainloop_terminate) {
21,410✔
191

192
        while (rc == 0) {
142,121✔
193
            if (mlp->flags & MAIN_LOOP_FLAG_USE_FD)
122,070✔
194
                connection_fd.fd = mlp->fd;
1,338✔
195

196
            struct pollfd pollfds[] = {
122,070✔
197
                [DATA_CLIENT_FD] = {
198
                    .fd = connection_fd.fd,
122,070✔
199
                    .events = POLLIN | POLLHUP,
200
                    .revents = 0,
201
                },
202
                [NOTIFY_FD] = {
203
                    .fd = notify_fd,
204
                    .events = POLLIN,
205
                    .revents = 0,
206
                },
207
                [CTRL_SERVER_FD] = {
208
                    .fd = -1,
209
                    .events = POLLIN,
210
                    .revents = 0,
211
                },
212
                [CTRL_CLIENT_FD] = {
213
                    .fd = ctrlclntfd,
214
                    .events = POLLIN | POLLHUP,
215
                    .revents = 0,
216
                },
217
                [DATA_SERVER_FD] = {
218
                    /* listen socket for accepting clients */
219
                    .fd = -1,
220
                    .events = POLLIN,
221
                    .revents = 0,
222
                }
223
            };
224

225
            /* only listend for clients if we don't have one */
226
            if (connection_fd.fd < 0)
122,070✔
227
                pollfds[DATA_SERVER_FD].fd = sockfd;
79,406✔
228
            if (ctrlclntfd < 0)
122,070✔
229
                pollfds[CTRL_SERVER_FD].fd = ctrlfd;
80,560✔
230

231
            ready = poll(pollfds, 5, -1);
122,070✔
232
            if (ready < 0 && errno == EINTR)
122,070✔
233
                continue;
79,370✔
234

235
            if (ready < 0 ||
122,067✔
236
                (pollfds[NOTIFY_FD].revents & POLLIN) != 0) {
122,067✔
237
                SWTPM_IO_Disconnect(&connection_fd);
3✔
238
                break;
957✔
239
            }
240

241
            if (pollfds[DATA_CLIENT_FD].revents & (POLLHUP | POLLERR)) {
122,064✔
242
                logprintf(STDERR_FILENO, "Data client disconnected\n");
79✔
243
                mlp->fd = -1;
79✔
244
                /* chardev and unixio get this signal, not tcp */
245
                if (mlp->flags & MAIN_LOOP_FLAG_END_ON_HUP) {
79✔
246
                    /* only the chardev terminates here */
247
                    g_mainloop_terminate = true;
×
248
                    break;
×
249
                }
250
            }
251

252
            if (pollfds[DATA_SERVER_FD].revents & POLLIN)
122,064✔
253
                connection_fd.fd = accept(pollfds[DATA_SERVER_FD].fd, NULL, 0);
20,597✔
254

255
            if (pollfds[CTRL_SERVER_FD].revents & POLLIN)
122,064✔
256
                ctrlclntfd = accept(ctrlfd, NULL, 0);
18,717✔
257

258
            if (pollfds[CTRL_CLIENT_FD].revents & POLLIN) {
122,064✔
259
                ctrlclntfd = ctrlchannel_process_fd(ctrlclntfd,
40,537✔
260
                                                    &g_mainloop_terminate,
261
                                                    &g_locality, &tpm_running,
262
                                                    mlp);
263
                if (ctrlclntfd < 0 &&
40,537✔
264
                    mlp->flags & MAIN_LOOP_FLAG_CTRL_END_ON_HUP)
18,451✔
265
                    g_mainloop_terminate = true;
4✔
266

267
                if (g_mainloop_terminate)
40,537✔
268
                    break;
269
            }
270

271
            if (pollfds[CTRL_CLIENT_FD].revents & POLLHUP) {
121,661✔
272
                if (ctrlclntfd >= 0)
509✔
273
                    close(ctrlclntfd);
×
274
                ctrlclntfd = -1;
509✔
275
                /* unixio gets this signal, not tcp */
276
                if (mlp->flags & MAIN_LOOP_FLAG_CTRL_END_ON_HUP) {
509✔
277
                    g_mainloop_terminate = true;
×
278
                    break;
×
279
                }
280
            }
281

282
            if (!(pollfds[DATA_CLIENT_FD].revents & POLLIN))
121,661✔
283
                continue;
79,367✔
284

285
            /* before processing a command ensure that the storage is locked */
286
            if ((g_mainloop_terminate = !mainloop_ensure_locked_storage(mlp)))
42,294✔
287
                break;
288

289
            /* Read the command.  The number of bytes is determined by 'paramSize' in the stream */
290
            if (rc == 0) {
42,294✔
291
                rc = SWTPM_IO_Read(&connection_fd, command, &command_length,
42,294✔
292
                                   max_command_length);
293
                if (rc != 0) {
42,294✔
294
                    /* connection broke */
295
                    SWTPM_IO_Disconnect(&connection_fd);
20,224✔
296
                }
297
            }
298

299
            cmd_offset = 0;
42,294✔
300
            /* Handle optional TCG Header in front of TPM 2 Command */
301
            if (rc == 0 && mlp->tpmversion == TPMLIB_TPM_VERSION_2) {
42,294✔
302
                cmd_offset = tpmlib_handle_tcg_tpm2_cmd_header(command,
9,958✔
303
                                                               command_length,
304
                                                               &g_locality);
305
                if (cmd_offset > 0) {
9,958✔
306
                    /* send header and trailer */
307
                    iov[0].iov_len = sizeof(respprefix);
6,443✔
308
                    iov[2].iov_len = sizeof(ack);
6,443✔
309
                } else {
310
                    iov[0].iov_len = 0;
3,515✔
311
                    iov[2].iov_len = 0;
3,515✔
312
                }
313
            }
314

315
            if (rc == 0) {
42,294✔
316
                if (!tpm_running) {
22,070✔
317
                    tpmlib_write_fatal_error_response(&rbuffer, &rlength,
14✔
318
                                                      &rTotal,
319
                                                      mlp->tpmversion);
320
                    goto skip_process;
14✔
321
                }
322
            }
323

324
            if (rc == 0) {
42,280✔
325
                lastCommand =
22,056✔
326
                    tpmlib_get_cmd_ordinal(&command[cmd_offset],
44,112✔
327
                                           command_length - cmd_offset);
22,056✔
328
                if (lastCommand != TPM_ORDINAL_NONE)
22,056✔
329
                    mlp->lastCommand = lastCommand;
22,056✔
330
            }
331

332
            if (rc == 0) {
42,280✔
333
                rlength = 0;                                /* clear the response buffer */
22,056✔
334
                rc = tpmlib_process(&rbuffer,
22,056✔
335
                                    &rlength,
336
                                    &rTotal,
337
                                    &command[cmd_offset],
338
                                    command_length - cmd_offset,
339
                                    mlp->locality_flags,
340
                                    &g_locality,
341
                                    mlp->tpmversion);
342
                if (rlength)
22,056✔
343
                    goto skip_process;
×
344
            }
345

346
            if (rc == 0) {
42,280✔
347
                rlength = 0;                                /* clear the response buffer */
22,056✔
348
                rc = TPMLIB_Process(&rbuffer,
22,056✔
349
                                    &rlength,
350
                                    &rTotal,
351
                                    &command[cmd_offset],
352
                                    command_length - cmd_offset);
353
            }
354

355
skip_process:
20,224✔
356
            /* write the results */
357
            if (rc == 0) {
42,294✔
358
                respprefix.size = htobe32(rlength);
22,070✔
359
                iov[1].iov_base = rbuffer;
22,070✔
360
                iov[1].iov_len  = rlength;
22,070✔
361

362
                SWTPM_IO_Write(&connection_fd, iov, ARRAY_LEN(iov));
22,070✔
363
            }
364

365
            if (!(mlp->flags & MAIN_LOOP_FLAG_KEEP_CONNECTION)) {
42,294✔
366
                SWTPM_IO_Disconnect(&connection_fd);
548✔
367
                break;
548✔
368
            }
369
        }
370

371
        rc = 0; /* A fatal TPM_Process() error should cause the TPM to enter shutdown.  IO errors
21,005✔
372
                   are outside the TPM, so the TPM does not shut down.  The main loop should
373
                   continue to function.*/
374
        if (connection_fd.fd < 0 && mlp->flags & MAIN_LOOP_FLAG_TERMINATE)
21,005✔
375
            break;
376
    }
377

378
    if (tpm_running && !mlp->disable_auto_shutdown)
409✔
379
        tpmlib_maybe_send_tpm2_shutdown(mlp->tpmversion, &mlp->lastCommand);
5✔
380

381
    free(rbuffer);
409✔
382
    free(command);
409✔
383

384
    if (ctrlclntfd >= 0)
409✔
385
        close(ctrlclntfd);
401✔
386
    ctrlchannel_set_client_fd(mlp->cc, -1);
409✔
387

388
    if (connection_fd.fd >= 0 && !(mlp->flags & MAIN_LOOP_FLAG_USE_FD))
409✔
389
        close(connection_fd.fd);
×
390

391
    if (mlp->fd >= 0) {
409✔
392
        close(mlp->fd);
382✔
393
        mlp->fd = -1;
382✔
394
    }
395

396
    return rc;
409✔
397
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc