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

stefanberger / swtpm / #2812

02 May 2025 12:09PM UTC coverage: 73.552% (+0.3%) from 73.293%
#2812

push

travis-ci

web-flow
Merge db5122d7f into 6d951a7a3

100 of 128 new or added lines in 5 files covered. (78.13%)

154 existing lines in 5 files now uncovered.

8140 of 11067 relevant lines covered (73.55%)

13478.66 hits per line

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

92.45
/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,338✔
80
                         uint32_t tpmnum SWTPM_ATTR_UNUSED)
81
{
82
    *loc = g_locality;
28,338✔
83

84
    return TPM_SUCCESS;
28,338✔
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,390✔
89
{
90
    TPM_RESULT res;
42,390✔
91

92
    if (mlp->storage_locked)
42,390✔
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);
155✔
97
    if (res == TPM_RETRY)
155✔
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)
410✔
119
{
120
    TPM_RESULT          rc = 0;
410✔
121
    TPM_CONNECTION_FD   connection_fd;             /* file descriptor for read/write */
410✔
122
    unsigned char       *command = NULL;           /* command buffer */
410✔
123
    uint32_t            command_length;            /* actual length of command bytes */
410✔
124
    uint32_t            max_command_length;        /* command buffer size */
410✔
125
    off_t               cmd_offset;
410✔
126
    /* The response buffer is reused for each command. Thus it can grow but never shrink */
127
    unsigned char       *rbuffer = NULL;           /* actual response bytes */
410✔
128
    uint32_t            rlength = 0;               /* bytes in response buffer */
410✔
129
    uint32_t            rTotal = 0;                /* total allocated bytes */
410✔
130
    int                 ctrlfd;
410✔
131
    int                 ctrlclntfd;
410✔
132
    int                 sockfd;
410✔
133
    int                 ready;
410✔
134
    struct iovec        iov[3];
410✔
135
    uint32_t            ack = htobe32(0);
410✔
136
    struct tpm2_resp_prefix respprefix;
410✔
137
    uint32_t            lastCommand;
410✔
138

139
    /* poolfd[] indexes */
140
    enum {
410✔
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");
410✔
149

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

153
    command = malloc(max_command_length);
410✔
154
    if (!command) {
410✔
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;
410✔
162
    iov[0].iov_len = 0;
410✔
163
    iov[2].iov_base = &ack;
410✔
164
    iov[2].iov_len = 0;
410✔
165

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

170
    sockfd = SWTPM_IO_GetSocketFD();
410✔
171

172
    if (mlp->startupType != _TPM_ST_NONE) {
410✔
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,414✔
191

192
        while (rc == 0) {
142,159✔
193
            if (mlp->flags & MAIN_LOOP_FLAG_USE_FD) {
122,107✔
194
                if (connection_fd.fd != mlp->fd) {
1,338✔
195
                    SWTPM_IO_Disconnect(&connection_fd);
140✔
196
                    connection_fd.fd = mlp->fd;
140✔
197
                }
198
            }
199

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

229
            /* only listend for clients if we don't have one */
230
            if (connection_fd.fd < 0)
122,107✔
231
                pollfds[DATA_SERVER_FD].fd = sockfd;
79,440✔
232
            if (ctrlclntfd < 0)
122,107✔
233
                pollfds[CTRL_SERVER_FD].fd = ctrlfd;
80,594✔
234

235
            ready = poll(pollfds, 5, -1);
122,107✔
236
            if (ready < 0 && errno == EINTR)
122,107✔
237
                continue;
79,403✔
238

239
            if (ready < 0 ||
122,104✔
240
                (pollfds[NOTIFY_FD].revents & POLLIN) != 0) {
122,104✔
241
                SWTPM_IO_Disconnect(&connection_fd);
3✔
242
                break;
959✔
243
            }
244

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

256
            if (pollfds[DATA_SERVER_FD].revents & POLLIN)
122,101✔
257
                connection_fd.fd = accept(pollfds[DATA_SERVER_FD].fd, NULL, 0);
20,599✔
258

259
            if (pollfds[CTRL_SERVER_FD].revents & POLLIN)
122,101✔
260
                ctrlclntfd = accept(ctrlfd, NULL, 0);
18,720✔
261

262
            if (pollfds[CTRL_CLIENT_FD].revents & POLLIN) {
122,101✔
263
                ctrlclntfd = ctrlchannel_process_fd(ctrlclntfd,
40,542✔
264
                                                    &g_mainloop_terminate,
265
                                                    &g_locality, &tpm_running,
266
                                                    mlp);
267
                if (ctrlclntfd < 0 &&
40,542✔
268
                    mlp->flags & MAIN_LOOP_FLAG_CTRL_END_ON_HUP)
18,454✔
269
                    g_mainloop_terminate = true;
4✔
270

271
                if (g_mainloop_terminate)
40,542✔
272
                    break;
273
            }
274

275
            if (pollfds[CTRL_CLIENT_FD].revents & POLLHUP) {
121,697✔
276
                if (ctrlclntfd >= 0)
510✔
277
                    close(ctrlclntfd);
×
278
                ctrlclntfd = -1;
510✔
279
                /* unixio gets this signal, not tcp */
280
                if (mlp->flags & MAIN_LOOP_FLAG_CTRL_END_ON_HUP) {
510✔
UNCOV
281
                    g_mainloop_terminate = true;
×
UNCOV
282
                    break;
×
283
                }
284
            }
285

286
            if (!(pollfds[DATA_CLIENT_FD].revents & POLLIN))
121,697✔
287
                continue;
79,400✔
288

289
            /* before processing a command ensure that the storage is locked */
290
            if ((g_mainloop_terminate = !mainloop_ensure_locked_storage(mlp)))
42,297✔
291
                break;
292

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

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

319
            if (rc == 0) {
42,297✔
320
                if (!tpm_running) {
22,071✔
321
                    tpmlib_write_fatal_error_response(&rbuffer, &rlength,
14✔
322
                                                      &rTotal,
323
                                                      mlp->tpmversion);
324
                    goto skip_process;
14✔
325
                }
326
            }
327

328
            if (rc == 0) {
42,283✔
329
                lastCommand =
22,057✔
330
                    tpmlib_get_cmd_ordinal(&command[cmd_offset],
44,114✔
331
                                           command_length - cmd_offset);
22,057✔
332
                if (lastCommand != TPM_ORDINAL_NONE)
22,057✔
333
                    mlp->lastCommand = lastCommand;
22,057✔
334
            }
335

336
            if (rc == 0) {
42,283✔
337
                rlength = 0;                                /* clear the response buffer */
22,057✔
338
                rc = tpmlib_process(&rbuffer,
22,057✔
339
                                    &rlength,
340
                                    &rTotal,
341
                                    &command[cmd_offset],
342
                                    command_length - cmd_offset,
343
                                    mlp->locality_flags,
344
                                    &g_locality,
345
                                    mlp->tpmversion);
346
                if (rlength)
22,057✔
UNCOV
347
                    goto skip_process;
×
348
            }
349

350
            if (rc == 0) {
42,283✔
351
                rlength = 0;                                /* clear the response buffer */
22,057✔
352
                rc = TPMLIB_Process(&rbuffer,
22,057✔
353
                                    &rlength,
354
                                    &rTotal,
355
                                    &command[cmd_offset],
356
                                    command_length - cmd_offset);
357
            }
358

359
skip_process:
20,226✔
360
            /* write the results */
361
            if (rc == 0) {
42,297✔
362
                respprefix.size = htobe32(rlength);
22,071✔
363
                iov[1].iov_base = rbuffer;
22,071✔
364
                iov[1].iov_len  = rlength;
22,071✔
365

366
                SWTPM_IO_Write(&connection_fd, iov, ARRAY_LEN(iov));
22,071✔
367
            }
368

369
            if (!(mlp->flags & MAIN_LOOP_FLAG_KEEP_CONNECTION)) {
42,297✔
370
                SWTPM_IO_Disconnect(&connection_fd);
549✔
371
                break;
549✔
372
            }
373
        }
374

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

382
    if (tpm_running && !mlp->disable_auto_shutdown)
410✔
383
        tpmlib_maybe_send_tpm2_shutdown(mlp->tpmversion, &mlp->lastCommand);
5✔
384

385
    free(rbuffer);
410✔
386
    free(command);
410✔
387

388
    if (ctrlclntfd >= 0)
410✔
389
        close(ctrlclntfd);
401✔
390
    ctrlchannel_set_client_fd(mlp->cc, -1);
410✔
391

392
    if (connection_fd.fd >= 0 && !(mlp->flags & MAIN_LOOP_FLAG_USE_FD))
410✔
UNCOV
393
        close(connection_fd.fd);
×
394

395
    if (mlp->fd >= 0) {
410✔
396
        close(mlp->fd);
388✔
397
        mlp->fd = -1;
388✔
398
    }
399

400
    return rc;
410✔
401
}
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