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

stefanberger / swtpm / #2883

24 Feb 2026 06:04PM UTC coverage: 72.417% (+0.1%) from 72.285%
#2883

push

travis-ci

web-flow
Merge a664d119d into 48358b244

106 of 220 new or added lines in 7 files covered. (48.18%)

458 existing lines in 7 files now uncovered.

7611 of 10510 relevant lines covered (72.42%)

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

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

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

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

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

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

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

170
    sockfd = SWTPM_IO_GetSocketFD();
423✔
171

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

183
        if (rc || command_length == 0) {
213✔
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,475✔
191

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

200
            struct pollfd pollfds[] = {
122,619✔
201
                [DATA_CLIENT_FD] = {
202
                    .fd = connection_fd.fd,
122,619✔
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,619✔
231
                pollfds[DATA_SERVER_FD].fd = sockfd;
79,742✔
232
            if (ctrlclntfd < 0)
122,619✔
233
                pollfds[CTRL_SERVER_FD].fd = ctrlfd;
80,784✔
234

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

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

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

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

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

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

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

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

286
            if (!(pollfds[DATA_CLIENT_FD].revents & POLLIN))
122,196✔
287
                continue;
79,721✔
288

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

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

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

319
            if (rc == 0) {
42,475✔
320
                if (!tpm_running) {
22,213✔
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,461✔
329
                lastCommand =
22,199✔
330
                    tpmlib_get_cmd_ordinal(&command[cmd_offset],
44,398✔
331
                                           command_length - cmd_offset);
22,199✔
332
                if (lastCommand != TPM_ORDINAL_NONE)
22,199✔
333
                    mlp->lastCommand = lastCommand;
22,199✔
334
            }
335

336
            if (rc == 0) {
42,461✔
337
                rlength = 0;                                /* clear the response buffer */
22,199✔
338
                rc = tpmlib_process(&rbuffer,
22,199✔
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,199✔
347
                    goto skip_process;
×
348
            }
349

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

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

366
                SWTPM_IO_Write(&connection_fd, iov, ARRAY_LEN(iov),
22,213✔
367
                               &mlp->ps);
368
            }
369

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

376
        rc = 0; /* A fatal TPM_Process() error should cause the TPM to enter shutdown.  IO errors
21,056✔
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,056✔
380
            break;
381
    }
382

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

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

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

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

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

401
    return rc;
423✔
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