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

stefanberger / swtpm / #2961

01 May 2026 01:51AM UTC coverage: 73.207% (-0.5%) from 73.671%
#2961

push

travis-ci

web-flow
Merge 2ac6ba54c into 208a85242

2 of 3 new or added lines in 1 file covered. (66.67%)

1889 existing lines in 28 files now uncovered.

8052 of 10999 relevant lines covered (73.21%)

13564.07 hits per line

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

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

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

92
    if (mlp->storage_locked)
42,391✔
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)
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
    /* if we are running with libtpms >= v0.11, then use 8kb buffer */
151
    if (TPMLIB_GetVersion() >= TPM_LIBRARY_VERSION_GEN(0, 11, 0)) {
410✔
152
        max_command_length = 8 * 1024;
153
    } else {
NEW
154
        max_command_length = tpmlib_get_tpm_property(TPMPROP_TPM_BUFFER_MAX);
×
155
    }
156
    max_command_length += sizeof(struct tpm2_send_command_prefix);
410✔
157

158
    command = malloc(max_command_length);
410✔
159
    if (!command) {
410✔
160
        logprintf(STDERR_FILENO, "Could not allocate %u bytes for buffer.\n",
×
161
                  max_command_length);
162
        return TPM_FAIL;
×
163
    }
164

165
    /* header and trailer that we may send by setting iov_len */
166
    iov[0].iov_base = &respprefix;
410✔
167
    iov[0].iov_len = 0;
410✔
168
    iov[2].iov_base = &ack;
410✔
169
    iov[2].iov_len = 0;
410✔
170

171
    connection_fd.fd = -1;
410✔
172
    ctrlfd = ctrlchannel_get_fd(mlp->cc);
410✔
173
    ctrlclntfd = ctrlchannel_get_client_fd(mlp->cc);
410✔
174

175
    sockfd = SWTPM_IO_GetSocketFD();
410✔
176

177
    if (mlp->startupType != _TPM_ST_NONE) {
410✔
178
        command_length = tpmlib_create_startup_cmd(
202✔
179
                                  mlp->startupType,
180
                                  mlp->tpmversion,
181
                                  command, max_command_length);
182
        if (command_length > 0) {
202✔
183
            mlp->lastCommand = tpmlib_get_cmd_ordinal(command, command_length);
202✔
184
            rc = TPMLIB_Process(&rbuffer, &rlength, &rTotal,
202✔
185
                                command, command_length);
186
        }
187

188
        if (rc || command_length == 0) {
202✔
UNCOV
189
            g_mainloop_terminate = true;
×
UNCOV
190
            if (rc)
×
UNCOV
191
                logprintf(STDERR_FILENO, "Could not send Startup: 0x%x\n", rc);
×
192
        }
193
    }
194

195
    while (!g_mainloop_terminate) {
21,412✔
196

197
        while (rc == 0) {
142,142✔
198
            if (mlp->flags & MAIN_LOOP_FLAG_USE_FD)
122,091✔
199
                connection_fd.fd = mlp->fd;
1,343✔
200

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

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

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

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

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

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

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

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

272
                if (g_mainloop_terminate)
40,537✔
273
                    break;
274
            }
275

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

287
            if (!(pollfds[DATA_CLIENT_FD].revents & POLLIN))
121,681✔
288
                continue;
79,383✔
289

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

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

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

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

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

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

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

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

367
                SWTPM_IO_Write(&connection_fd, iov, ARRAY_LEN(iov));
22,073✔
368
            }
369

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

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

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

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

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

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

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

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