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

mendersoftware / mender / 2189544880

01 Dec 2025 04:20PM UTC coverage: 75.865%. First build
2189544880

push

gitlab-ci

michalkopczan
fix: Sanitize Update Module paths - payload_type must not point outside of Update Modules' directory

(cherry picked from commit c76f042b3)

Ticket: MEN-9027
Changelog: Sanitized the payload_type field of Mender artifacts, removing relative paths pointing outside Update Modules directory.

Signed-off-by: Michal Kopczan <michal.kopczan@northern.tech>

37 of 54 new or added lines in 7 files covered. (68.52%)

7415 of 9774 relevant lines covered (75.86%)

13875.41 hits per line

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

76.67
/src/mender-update/daemon/states.cpp
1
// Copyright 2023 Northern.tech AS
2
//
3
//    Licensed under the Apache License, Version 2.0 (the "License");
4
//    you may not use this file except in compliance with the License.
5
//    You may obtain a copy of the License at
6
//
7
//        http://www.apache.org/licenses/LICENSE-2.0
8
//
9
//    Unless required by applicable law or agreed to in writing, software
10
//    distributed under the License is distributed on an "AS IS" BASIS,
11
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
//    See the License for the specific language governing permissions and
13
//    limitations under the License.
14

15
#include <mender-update/daemon/states.hpp>
16

17
#include <client_shared/conf.hpp>
18
#include <common/events_io.hpp>
19
#include <common/log.hpp>
20
#include <common/path.hpp>
21

22
#include <mender-update/daemon/context.hpp>
23
#include <mender-update/inventory.hpp>
24

25
namespace mender {
26
namespace update {
27
namespace daemon {
28

29
namespace conf = mender::client_shared::conf;
30
namespace error = mender::common::error;
31
namespace events = mender::common::events;
32
namespace kv_db = mender::common::key_value_database;
33
namespace path = mender::common::path;
34
namespace log = mender::common::log;
35

36
namespace main_context = mender::update::context;
37
namespace inventory = mender::update::inventory;
38

39
class DefaultStateHandler {
40
public:
41
        void operator()(const error::Error &err) {
294✔
42
                if (err != error::NoError) {
294✔
43
                        log::Error(err.String());
23✔
44
                        poster.PostEvent(StateEvent::Failure);
23✔
45
                        return;
23✔
46
                }
47
                poster.PostEvent(StateEvent::Success);
271✔
48
        }
49

50
        sm::EventPoster<StateEvent> &poster;
51
};
52

53
static void DefaultAsyncErrorHandler(sm::EventPoster<StateEvent> &poster, const error::Error &err) {
412✔
54
        if (err != error::NoError) {
412✔
55
                log::Error(err.String());
×
56
                poster.PostEvent(StateEvent::Failure);
×
57
        }
58
}
412✔
59

60
void EmptyState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
152✔
61
        // Keep this state truly empty.
62
}
152✔
63

64
void InitState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
59✔
65
        // I will never run - just a placeholder to start the state-machine at
66
        poster.PostEvent(StateEvent::Started); // Start the state machine
59✔
67
}
59✔
68

69
void StateScriptState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
1,052✔
70
        string state_name {script_executor::Name(this->state_, this->action_)};
1,052✔
71
        log::Debug("Executing the  " + state_name + " State Scripts...");
2,104✔
72
        auto err = this->script_.AsyncRunScripts(
73
                this->state_,
74
                this->action_,
75
                [state_name, &poster](error::Error err) {
7,869✔
76
                        if (err != error::NoError) {
1,052✔
77
                                log::Error(
21✔
78
                                        "Received error: (" + err.String() + ") when running the State Script scripts "
42✔
79
                                        + state_name);
63✔
80
                                poster.PostEvent(StateEvent::Failure);
21✔
81
                                return;
21✔
82
                        }
83
                        log::Debug("Successfully ran the " + state_name + " State Scripts...");
2,062✔
84
                        poster.PostEvent(StateEvent::Success);
1,031✔
85
                },
86
                this->on_error_);
2,104✔
87

88
        if (err != error::NoError) {
1,052✔
89
                log::Error(
×
90
                        "Failed to schedule the state script execution for: " + state_name
×
91
                        + " got error: " + err.String());
×
92
                poster.PostEvent(StateEvent::Failure);
×
93
                return;
94
        }
95
}
96

97

98
void SaveStateScriptState::OnEnterSaveState(Context &ctx, sm::EventPoster<StateEvent> &poster) {
278✔
99
        return state_script_state_.OnEnter(ctx, poster);
278✔
100
}
101

102
void IdleState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
120✔
103
        log::Debug("Entering Idle state");
240✔
104
}
120✔
105

106
ScheduleNextPollState::ScheduleNextPollState(
×
107
        events::Timer &timer, const string &poll_action, const StateEvent event, int interval) :
108
        timer_ {timer},
109
        poll_action_ {poll_action},
110
        event_ {event},
111
        interval_ {interval} {
×
112
}
×
113

114
void ScheduleNextPollState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
119✔
115
        log::Debug("Scheduling the next " + poll_action_ + " in: " + to_string(interval_) + " seconds");
238✔
116
        timer_.AsyncWait(chrono::seconds(interval_), [this, &poster](error::Error err) {
119✔
117
                if (err != error::NoError) {
5✔
118
                        if (err.code != make_error_condition(errc::operation_canceled)) {
2✔
119
                                log::Error("Timer caused error: " + err.String());
×
120
                        }
121
                } else {
122
                        poster.PostEvent(event_);
3✔
123
                }
124
        });
5✔
125

126
        poster.PostEvent(StateEvent::Success);
119✔
127
}
119✔
128

129
SubmitInventoryState::SubmitInventoryState(int retry_interval_seconds, int retry_count) :
96✔
130
        backoff_ {chrono::seconds(retry_interval_seconds), retry_count} {
192✔
131
}
96✔
132

133
void SubmitInventoryState::HandlePollingError(Context &ctx, sm::EventPoster<StateEvent> &poster) {
×
134
        // When using short polling intervals, we should adjust the backoff to ensure
135
        // that the intervals do not exceed the maximum retry polling interval, which
136
        // converts the backoff to a fixed interval.
137
        chrono::milliseconds max_interval =
138
                chrono::seconds(ctx.mender_context.GetConfig().retry_poll_interval_seconds);
×
139
        if (max_interval < backoff_.SmallestInterval()) {
×
140
                backoff_.SetSmallestInterval(max_interval);
×
141
                backoff_.SetMaxInterval(max_interval);
×
142
        }
143
        auto exp_interval = backoff_.NextInterval();
×
144
        if (!exp_interval) {
×
145
                log::Debug(
×
146
                        "Not retrying with backoff, retrying InventoryPollIntervalSeconds: "
147
                        + exp_interval.error().String());
×
148
                return;
149
        }
150
        log::Info(
×
151
                "Retrying inventory polling in "
152
                + to_string(chrono::duration_cast<chrono::seconds>(*exp_interval).count()) + " seconds");
×
153

154
        ctx.inventory_timer.Cancel();
×
155
        ctx.inventory_timer.AsyncWait(*exp_interval, [&poster](error::Error err) {
×
156
                if (err != error::NoError) {
×
157
                        if (err.code != make_error_condition(errc::operation_canceled)) {
×
158
                                log::Error("Retry poll timer caused error: " + err.String());
×
159
                        }
160
                } else {
161
                        poster.PostEvent(StateEvent::InventoryPollingTriggered);
×
162
                }
163
        });
×
164
}
165

166
void SubmitInventoryState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
59✔
167
        log::Debug("Submitting inventory");
118✔
168

169
        auto handler = [this, &ctx, &poster](error::Error err) {
59✔
170
                if (err != error::NoError) {
59✔
171
                        log::Error("Failed to submit inventory: " + err.String());
×
172
                        // Replace the inventory poll timer with a backoff
173
                        HandlePollingError(ctx, poster);
×
174
                        poster.PostEvent(StateEvent::Failure);
×
175
                        return;
×
176
                }
177
                backoff_.Reset();
178
                ctx.inventory_client->has_submitted_inventory = true;
59✔
179
                poster.PostEvent(StateEvent::Success);
59✔
180
        };
59✔
181

182
        auto err = ctx.inventory_client->PushData(
183
                ctx.mender_context.GetConfig().paths.GetInventoryScriptsDir(),
59✔
184
                ctx.event_loop,
185
                ctx.http_client,
186
                handler);
59✔
187

188
        if (err != error::NoError) {
59✔
189
                // This is the only case the handler won't be called for us by
190
                // PushData() (see inventory::PushInventoryData()).
191
                handler(err);
×
192
        }
193
}
59✔
194

195
PollForDeploymentState::PollForDeploymentState(int retry_interval_seconds, int retry_count) :
96✔
196
        backoff_ {chrono::seconds(retry_interval_seconds), retry_count} {
192✔
197
}
96✔
198

199
void PollForDeploymentState::HandlePollingError(Context &ctx, sm::EventPoster<StateEvent> &poster) {
×
200
        // When using short polling intervals, we should adjust the backoff to ensure
201
        // that the intervals do not exceed the maximum retry polling interval, which
202
        // converts the backoff to a fixed interval.
203
        chrono::milliseconds max_interval =
204
                chrono::seconds(ctx.mender_context.GetConfig().retry_poll_interval_seconds);
×
205
        if (max_interval < backoff_.SmallestInterval()) {
×
206
                backoff_.SetSmallestInterval(max_interval);
×
207
                backoff_.SetMaxInterval(max_interval);
×
208
        }
209
        auto exp_interval = backoff_.NextInterval();
×
210
        if (!exp_interval) {
×
211
                log::Debug(
×
212
                        "Not retrying with backoff, retrying with UpdatePollIntervalSeconds: "
213
                        + exp_interval.error().String());
×
214
                return;
215
        }
216
        log::Info(
×
217
                "Retrying deployment polling in "
218
                + to_string(chrono::duration_cast<chrono::seconds>(*exp_interval).count()) + " seconds");
×
219

220
        ctx.deployment_timer.Cancel();
×
221
        ctx.deployment_timer.AsyncWait(*exp_interval, [&poster](error::Error err) {
×
222
                if (err != error::NoError) {
×
223
                        if (err.code != make_error_condition(errc::operation_canceled)) {
×
224
                                log::Error("Retry poll timer caused error: " + err.String());
×
225
                        }
226
                } else {
227
                        poster.PostEvent(StateEvent::DeploymentPollingTriggered);
×
228
                }
229
        });
×
230
}
231

232
void PollForDeploymentState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
59✔
233
        log::Debug("Polling for update");
118✔
234

235
        auto err = ctx.deployment_client->CheckNewDeployments(
236
                ctx.mender_context,
237
                ctx.http_client,
238
                [this, &ctx, &poster](mender::update::deployments::CheckUpdatesAPIResponse response) {
116✔
239
                        if (!response) {
58✔
240
                                log::Error("Error while polling for deployment: " + response.error().String());
×
241
                                // Replace the update poll timer with a backoff
242
                                HandlePollingError(ctx, poster);
×
243
                                poster.PostEvent(StateEvent::Failure);
×
244
                                return;
1✔
245
                        } else if (!response.value()) {
58✔
246
                                log::Info("No update available");
2✔
247
                                poster.PostEvent(StateEvent::NothingToDo);
1✔
248
                                if (not ctx.inventory_client->has_submitted_inventory) {
1✔
249
                                        // If we have not submitted inventory successfully at least
250
                                        // once, schedule this after receiving a successful response
251
                                        // with no update. This enables inventory to be submitted
252
                                        // immediately after the device has been accepted. If there
253
                                        // is an update available, an inventory update will be
254
                                        // scheduled at the end of it unconditionally.
255
                                        poster.PostEvent(StateEvent::InventoryPollingTriggered);
×
256
                                }
257

258
                                backoff_.Reset();
259
                                return;
1✔
260
                        }
261
                        backoff_.Reset();
262

263
                        auto exp_data = ApiResponseJsonToStateData(response.value().value());
57✔
264
                        if (!exp_data) {
57✔
265
                                log::Error("Error in API response: " + exp_data.error().String());
×
266
                                poster.PostEvent(StateEvent::Failure);
×
267
                                return;
268
                        }
269

270
                        // Make a new set of update data.
271
                        ctx.deployment.state_data.reset(new StateData(std::move(exp_data.value())));
57✔
272

273
                        ctx.BeginDeploymentLogging();
57✔
274

275
                        log::Info("Running Mender client " + conf::kMenderVersion);
114✔
276
                        log::Info(
57✔
277
                                "Deployment with ID " + ctx.deployment.state_data->update_info.id + " started.");
114✔
278

279
                        poster.PostEvent(StateEvent::DeploymentStarted);
57✔
280
                        poster.PostEvent(StateEvent::Success);
57✔
281
                });
59✔
282

283
        if (err != error::NoError) {
59✔
284
                log::Error("Error when trying to poll for deployment: " + err.String());
2✔
285
                poster.PostEvent(StateEvent::Failure);
1✔
286
        }
287
}
59✔
288

289
void SaveState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
535✔
290
        assert(ctx.deployment.state_data);
291

292
        ctx.deployment.state_data->state = DatabaseStateString();
535✔
293

294
        log::Trace("Storing deployment state in the DB (database-string): " + DatabaseStateString());
1,070✔
295

296
        auto err = ctx.SaveDeploymentStateData(*ctx.deployment.state_data);
535✔
297
        if (err != error::NoError) {
535✔
298
                log::Error(err.String());
10✔
299
                if (err.code
10✔
300
                        == main_context::MakeError(main_context::StateDataStoreCountExceededError, "").code) {
10✔
301
                        poster.PostEvent(StateEvent::StateLoopDetected);
1✔
302
                        return;
303
                } else if (!IsFailureState()) {
9✔
304
                        // Non-failure states should be interrupted, but failure states should be
305
                        // allowed to do their work, even if a database error was detected.
306
                        poster.PostEvent(StateEvent::Failure);
2✔
307
                        return;
308
                }
309
        }
310

311
        OnEnterSaveState(ctx, poster);
532✔
312
}
313

314
void UpdateDownloadState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
54✔
315
        log::Debug("Entering Download state");
108✔
316

317
        auto req = make_shared<http::OutgoingRequest>();
54✔
318
        req->SetMethod(http::Method::GET);
54✔
319
        auto err = req->SetAddress(ctx.deployment.state_data->update_info.artifact.source.uri);
54✔
320
        if (err != error::NoError) {
54✔
321
                log::Error(err.String());
×
322
                poster.PostEvent(StateEvent::Failure);
×
323
                return;
324
        }
325

326
        err = ctx.download_client->AsyncCall(
54✔
327
                req,
328
                [&ctx, &poster](http::ExpectedIncomingResponsePtr exp_resp) {
107✔
329
                        if (!exp_resp) {
54✔
330
                                log::Error("Unexpected error during download: " + exp_resp.error().String());
×
331
                                poster.PostEvent(StateEvent::Failure);
×
332
                                return;
1✔
333
                        }
334

335
                        auto &resp = exp_resp.value();
54✔
336
                        if (resp->GetStatusCode() != http::StatusOK) {
54✔
337
                                log::Error(
1✔
338
                                        "Unexpected status code while fetching artifact: " + resp->GetStatusMessage());
2✔
339
                                poster.PostEvent(StateEvent::Failure);
1✔
340
                                return;
1✔
341
                        }
342

343
                        auto http_reader = resp->MakeBodyAsyncReader();
53✔
344
                        if (!http_reader) {
53✔
345
                                log::Error(http_reader.error().String());
×
346
                                poster.PostEvent(StateEvent::Failure);
×
347
                                return;
348
                        }
349
                        ctx.deployment.artifact_reader =
350
                                make_shared<events::io::ReaderFromAsyncReader>(ctx.event_loop, http_reader.value());
53✔
351
                        ParseArtifact(ctx, poster);
53✔
352
                },
353
                [](http::ExpectedIncomingResponsePtr exp_resp) {
54✔
354
                        if (!exp_resp) {
54✔
355
                                log::Error(exp_resp.error().String());
6✔
356
                                // Cannot handle error here, because this handler is called at the
357
                                // end of the download, when we have already left this state. So
358
                                // rely on this error being propagated through the BodyAsyncReader
359
                                // above instead.
360
                                return;
6✔
361
                        }
362
                });
108✔
363

364
        if (err != error::NoError) {
54✔
365
                log::Error(err.String());
×
366
                poster.PostEvent(StateEvent::Failure);
×
367
                return;
368
        }
369
}
370

371
void UpdateDownloadState::ParseArtifact(Context &ctx, sm::EventPoster<StateEvent> &poster) {
53✔
372
        string art_scripts_path = ctx.mender_context.GetConfig().paths.GetArtScriptsPath();
53✔
373

374
        // Clear the artifact scripts directory so we don't risk old scripts lingering.
375
        auto err = path::DeleteRecursively(art_scripts_path);
53✔
376
        if (err != error::NoError) {
53✔
377
                log::Error("When preparing to parse artifact: " + err.String());
×
378
                poster.PostEvent(StateEvent::Failure);
×
379
                return;
380
        }
381

382
        artifact::config::ParserConfig config {
53✔
383
                .artifact_scripts_filesystem_path = art_scripts_path,
384
                .artifact_scripts_version = 3,
385
                .artifact_verify_keys = ctx.mender_context.GetConfig().artifact_verify_keys,
53✔
386
        };
102✔
387
        auto exp_parser = artifact::Parse(*ctx.deployment.artifact_reader, config);
106✔
388
        if (!exp_parser) {
53✔
389
                log::Error(exp_parser.error().String());
×
390
                poster.PostEvent(StateEvent::Failure);
×
391
                return;
392
        }
393
        ctx.deployment.artifact_parser.reset(new artifact::Artifact(std::move(exp_parser.value())));
53✔
394

395
        auto exp_header = artifact::View(*ctx.deployment.artifact_parser, 0);
53✔
396
        if (!exp_header) {
53✔
397
                log::Error(exp_header.error().String());
×
398
                poster.PostEvent(StateEvent::Failure);
×
399
                return;
400
        }
401
        auto &header = exp_header.value();
53✔
402

403
        auto exp_matches = ctx.mender_context.MatchesArtifactDepends(header.header);
53✔
404
        if (!exp_matches) {
53✔
405
                log::Error(exp_matches.error().String());
2✔
406
                poster.PostEvent(StateEvent::Failure);
2✔
407
                return;
408
        } else if (!exp_matches.value()) {
51✔
409
                // reasons already logged
410
                poster.PostEvent(StateEvent::Failure);
1✔
411
                return;
412
        }
413

414
        log::Info("Installing artifact...");
100✔
415

416
        ctx.deployment.state_data->FillUpdateDataFromArtifact(header);
50✔
417

418
        ctx.deployment.state_data->state = Context::kUpdateStateDownload;
50✔
419

420
        assert(ctx.deployment.state_data->update_info.artifact.payload_types.size() == 1);
421

422
        // Initial state data save, now that we have enough information from the artifact.
423
        err = ctx.SaveDeploymentStateData(*ctx.deployment.state_data);
50✔
424
        if (err != error::NoError) {
50✔
425
                log::Error(err.String());
×
426
                if (err.code
×
427
                        == main_context::MakeError(main_context::StateDataStoreCountExceededError, "").code) {
×
428
                        poster.PostEvent(StateEvent::StateLoopDetected);
×
429
                        return;
430
                } else {
431
                        poster.PostEvent(StateEvent::Failure);
×
432
                        return;
433
                }
434
        }
435

436
        if (header.header.payload_type == "") {
50✔
437
                // Empty-payload-artifact, aka "bootstrap artifact".
438
                poster.PostEvent(StateEvent::NothingToDo);
1✔
439
                return;
440
        }
441

442
        auto exp_update_module =
443
                update_module::UpdateModule::Create(ctx.mender_context, header.header.payload_type);
49✔
444
        if (!exp_update_module.has_value()) {
49✔
NEW
445
                log::Error(
×
446
                        "Error creating an Update Module when parsing artifact: "
NEW
447
                        + exp_update_module.error().String());
×
NEW
448
                poster.PostEvent(StateEvent::Failure);
×
449
                return;
450
        }
451
        ctx.deployment.update_module = std::move(exp_update_module.value());
49✔
452

453
        err = ctx.deployment.update_module->CleanAndPrepareFileTree(
49✔
454
                ctx.deployment.update_module->GetUpdateModuleWorkDir(), header);
49✔
455
        if (err != error::NoError) {
49✔
456
                log::Error(err.String());
×
457
                poster.PostEvent(StateEvent::Failure);
×
458
                return;
459
        }
460

461
        err = ctx.deployment.update_module->AsyncProvidePayloadFileSizes(
49✔
462
                ctx.event_loop, [&ctx, &poster](expected::ExpectedBool download_with_sizes) {
49✔
463
                        if (!download_with_sizes.has_value()) {
49✔
464
                                log::Error(download_with_sizes.error().String());
×
465
                                poster.PostEvent(StateEvent::Failure);
×
466
                                return;
×
467
                        }
468
                        ctx.deployment.download_with_sizes = download_with_sizes.value();
49✔
469
                        DoDownload(ctx, poster);
49✔
470
                });
49✔
471

472
        if (err != error::NoError) {
49✔
473
                log::Error(err.String());
×
474
                poster.PostEvent(StateEvent::Failure);
×
475
                return;
476
        }
477
}
478

479
void UpdateDownloadState::DoDownload(Context &ctx, sm::EventPoster<StateEvent> &poster) {
49✔
480
        auto exp_payload = ctx.deployment.artifact_parser->Next();
49✔
481
        if (!exp_payload) {
49✔
482
                log::Error(exp_payload.error().String());
×
483
                poster.PostEvent(StateEvent::Failure);
×
484
                return;
485
        }
486
        ctx.deployment.artifact_payload.reset(new artifact::Payload(std::move(exp_payload.value())));
49✔
487

488
        auto handler = [&poster, &ctx](error::Error err) {
47✔
489
                if (err != error::NoError) {
49✔
490
                        log::Error(err.String());
2✔
491
                        poster.PostEvent(StateEvent::Failure);
2✔
492
                        return;
2✔
493
                }
494

495
                auto exp_payload = ctx.deployment.artifact_parser->Next();
47✔
496
                if (exp_payload) {
47✔
497
                        log::Error("Multiple payloads are not yet supported in daemon mode.");
×
498
                        poster.PostEvent(StateEvent::Failure);
×
499
                        return;
500
                } else if (
47✔
501
                        exp_payload.error().code
502
                        != artifact::parser_error::MakeError(artifact::parser_error::EOFError, "").code) {
47✔
503
                        log::Error(exp_payload.error().String());
×
504
                        poster.PostEvent(StateEvent::Failure);
×
505
                        return;
506
                }
507

508
                poster.PostEvent(StateEvent::Success);
47✔
509
        };
510

511
        if (ctx.deployment.download_with_sizes) {
49✔
512
                ctx.deployment.update_module->AsyncDownloadWithFileSizes(
1✔
513
                        ctx.event_loop, *ctx.deployment.artifact_payload, handler);
1✔
514
        } else {
515
                ctx.deployment.update_module->AsyncDownload(
48✔
516
                        ctx.event_loop, *ctx.deployment.artifact_payload, handler);
48✔
517
        }
518
}
519

520
void UpdateDownloadCancelState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
6✔
521
        log::Debug("Entering DownloadCancel state");
12✔
522
        ctx.download_client->Cancel();
6✔
523
        poster.PostEvent(StateEvent::Success);
6✔
524
}
6✔
525

526
SendStatusUpdateState::SendStatusUpdateState(optional<deployments::DeploymentStatus> status) :
×
527
        status_(status),
528
        mode_(FailureMode::Ignore) {
×
529
}
×
530

531
SendStatusUpdateState::SendStatusUpdateState(
192✔
532
        optional<deployments::DeploymentStatus> status,
533
        events::EventLoop &event_loop,
534
        int retry_interval_seconds,
535
        int retry_count) :
536
        status_(status),
537
        mode_(FailureMode::RetryThenFail),
538
        retry_(Retry {
192✔
539
                http::ExponentialBackoff(chrono::seconds(retry_interval_seconds), retry_count),
540
                event_loop}) {
576✔
541
}
192✔
542

543
void SendStatusUpdateState::SetSmallestWaitInterval(chrono::milliseconds interval) {
182✔
544
        if (retry_) {
182✔
545
                retry_->backoff.SetSmallestInterval(interval);
182✔
546
        }
547
}
182✔
548

549
void SendStatusUpdateState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
246✔
550
        // Reset this every time we enter the state, which means a new round of retries.
551
        if (retry_) {
246✔
552
                retry_->backoff.Reset();
553
        }
554

555
        DoStatusUpdate(ctx, poster);
246✔
556
}
246✔
557

558
void SendStatusUpdateState::DoStatusUpdate(Context &ctx, sm::EventPoster<StateEvent> &poster) {
265✔
559
        assert(ctx.deployment_client);
560
        assert(ctx.deployment.state_data);
561

562
        log::Info("Sending status update to server");
530✔
563

564
        auto result_handler = [this, &ctx, &poster](const error::Error &err) {
552✔
565
                if (err != error::NoError) {
265✔
566
                        log::Error("Could not send deployment status: " + err.String());
50✔
567

568
                        if (err.code == deployments::MakeError(deployments::DeploymentAbortedError, "").code) {
25✔
569
                                // If the deployment was aborted upstream it is an immediate
570
                                // failure, even if retry is enabled.
571
                                poster.PostEvent(StateEvent::DeploymentAborted);
3✔
572
                                return;
3✔
573
                        }
574

575
                        switch (mode_) {
22✔
576
                        case FailureMode::Ignore:
577
                                break;
2✔
578
                        case FailureMode::RetryThenFail:
20✔
579

580
                                auto exp_interval = retry_->backoff.NextInterval();
20✔
581
                                if (!exp_interval) {
20✔
582
                                        log::Error(
1✔
583
                                                "Giving up on sending status updates to server: "
584
                                                + exp_interval.error().String());
2✔
585
                                        poster.PostEvent(StateEvent::Failure);
1✔
586
                                        return;
587
                                }
588

589
                                log::Info(
19✔
590
                                        "Retrying status update after "
591
                                        + to_string(chrono::duration_cast<chrono::seconds>(*exp_interval).count())
38✔
592
                                        + " seconds");
38✔
593
                                retry_->wait_timer.AsyncWait(
19✔
594
                                        *exp_interval, [this, &ctx, &poster](error::Error err) {
38✔
595
                                                // Error here is quite unexpected (from a timer), so treat
596
                                                // this as an immediate error, despite Retry flag.
597
                                                if (err != error::NoError) {
19✔
598
                                                        log::Error(
×
599
                                                                "Unexpected error in SendStatusUpdateState wait timer: "
600
                                                                + err.String());
×
601
                                                        poster.PostEvent(StateEvent::Failure);
×
602
                                                        return;
×
603
                                                }
604

605
                                                // Try again. Since both status and logs are sent
606
                                                // from here, there's a chance this might resubmit
607
                                                // the status, but there's no harm in it, and it
608
                                                // won't happen often.
609
                                                DoStatusUpdate(ctx, poster);
19✔
610
                                        });
19✔
611
                                return;
19✔
612
                        }
613
                }
614

615
                poster.PostEvent(StateEvent::Success);
242✔
616
        };
265✔
617

618
        deployments::DeploymentStatus status;
619
        if (status_) {
265✔
620
                status = status_.value();
172✔
621
        } else {
622
                // If nothing is specified, grab success/failure status from the deployment status.
623
                if (ctx.deployment.failed) {
93✔
624
                        status = deployments::DeploymentStatus::Failure;
625
                } else {
626
                        status = deployments::DeploymentStatus::Success;
627
                }
628
        }
629

630
        // Push status.
631
        log::Debug("Pushing deployment status: " + DeploymentStatusString(status));
530✔
632
        auto err = ctx.deployment_client->PushStatus(
633
                ctx.deployment.state_data->update_info.id,
265✔
634
                status,
635
                "",
636
                ctx.http_client,
637
                [result_handler, &ctx](error::Error err) {
75✔
638
                        // If there is an error, we don't submit logs now, but call the handler,
639
                        // which may schedule a retry later. If there is no error, and the
640
                        // deployment as a whole was successful, then also call the handler here,
641
                        // since we don't need to submit logs at all then.
642
                        if (err != error::NoError || !ctx.deployment.failed) {
265✔
643
                                result_handler(err);
190✔
644
                                return;
190✔
645
                        }
646

647
                        // Push logs.
648
                        err = ctx.deployment_client->PushLogs(
75✔
649
                                ctx.deployment.state_data->update_info.id,
75✔
650
                                ctx.deployment.logger->LogFilePath(),
150✔
651
                                ctx.http_client,
652
                                result_handler);
75✔
653

654
                        if (err != error::NoError) {
75✔
655
                                result_handler(err);
×
656
                        }
657
                });
530✔
658

659
        if (err != error::NoError) {
265✔
660
                result_handler(err);
×
661
        }
662

663
        // No action, wait for reply from status endpoint.
664
}
265✔
665

666
void UpdateInstallState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
42✔
667
        log::Debug("Entering ArtifactInstall state");
84✔
668

669
        DefaultAsyncErrorHandler(
42✔
670
                poster,
671
                ctx.deployment.update_module->AsyncArtifactInstall(
42✔
672
                        ctx.event_loop, DefaultStateHandler {poster}));
42✔
673
}
42✔
674

675
void UpdateCheckRebootState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
73✔
676
        DefaultAsyncErrorHandler(
73✔
677
                poster,
678
                ctx.deployment.update_module->AsyncNeedsReboot(
73✔
679
                        ctx.event_loop, [&ctx, &poster](update_module::ExpectedRebootAction reboot_action) {
144✔
680
                                if (!reboot_action.has_value()) {
73✔
681
                                        log::Error(reboot_action.error().String());
2✔
682
                                        poster.PostEvent(StateEvent::Failure);
2✔
683
                                        return;
2✔
684
                                }
685

686
                                ctx.deployment.state_data->update_info.reboot_requested.resize(1);
71✔
687
                                ctx.deployment.state_data->update_info.reboot_requested[0] =
688
                                        NeedsRebootToDbString(*reboot_action);
71✔
689
                                switch (*reboot_action) {
71✔
690
                                case update_module::RebootAction::No:
8✔
691
                                        poster.PostEvent(StateEvent::NothingToDo);
8✔
692
                                        break;
8✔
693
                                case update_module::RebootAction::Yes:
63✔
694
                                case update_module::RebootAction::Automatic:
695
                                        poster.PostEvent(StateEvent::Success);
63✔
696
                                        break;
63✔
697
                                }
698
                        }));
73✔
699
}
73✔
700

701
void UpdateRebootState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
26✔
702
        log::Debug("Entering ArtifactReboot state");
52✔
703

704
        assert(ctx.deployment.state_data->update_info.reboot_requested.size() == 1);
705
        auto exp_reboot_mode =
706
                DbStringToNeedsReboot(ctx.deployment.state_data->update_info.reboot_requested[0]);
26✔
707
        // Should always be true because we check it at load time.
708
        assert(exp_reboot_mode);
709

710
        switch (exp_reboot_mode.value()) {
26✔
711
        case update_module::RebootAction::No:
×
712
                // Should not happen because then we don't enter this state.
713
                assert(false);
714
                poster.PostEvent(StateEvent::Failure);
×
715
                break;
716
        case update_module::RebootAction::Yes:
26✔
717
                DefaultAsyncErrorHandler(
26✔
718
                        poster,
719
                        ctx.deployment.update_module->AsyncArtifactReboot(
26✔
720
                                ctx.event_loop, DefaultStateHandler {poster}));
26✔
721
                break;
26✔
722
        case update_module::RebootAction::Automatic:
×
723
                DefaultAsyncErrorHandler(
×
724
                        poster,
725
                        ctx.deployment.update_module->AsyncSystemReboot(
×
726
                                ctx.event_loop, DefaultStateHandler {poster}));
×
727
                break;
×
728
        }
729
}
26✔
730

731
void UpdateVerifyRebootState::OnEnterSaveState(Context &ctx, sm::EventPoster<StateEvent> &poster) {
29✔
732
        log::Debug("Entering ArtifactVerifyReboot state");
58✔
733

734
        ctx.deployment.update_module->EnsureRootfsImageFileTree(
29✔
735
                ctx.deployment.update_module->GetUpdateModuleWorkDir());
58✔
736

737
        DefaultAsyncErrorHandler(
29✔
738
                poster,
739
                ctx.deployment.update_module->AsyncArtifactVerifyReboot(
29✔
740
                        ctx.event_loop, DefaultStateHandler {poster}));
29✔
741
}
29✔
742

743
void UpdateBeforeCommitState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
22✔
744
        // It's possible that the update we have done has changed our credentials. Therefore it's
745
        // important that we try to log in from scratch and do not use the token we already have.
746
        ctx.http_client.ExpireToken();
22✔
747

748
        poster.PostEvent(StateEvent::Success);
22✔
749
}
22✔
750

751
void UpdateCommitState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
19✔
752
        log::Debug("Entering ArtifactCommit state");
38✔
753

754
        // Explicitly check if state scripts version is supported
755
        auto err = script_executor::CheckScriptsCompatibility(
756
                ctx.mender_context.GetConfig().paths.GetRootfsScriptsPath());
19✔
757
        if (err != error::NoError) {
19✔
758
                log::Error("Failed script compatibility check: " + err.String());
×
759
                poster.PostEvent(StateEvent::Failure);
×
760
                return;
761
        }
762

763
        DefaultAsyncErrorHandler(
19✔
764
                poster,
765
                ctx.deployment.update_module->AsyncArtifactCommit(
19✔
766
                        ctx.event_loop, DefaultStateHandler {poster}));
38✔
767
}
768

769
void UpdateAfterCommitState::OnEnterSaveState(Context &ctx, sm::EventPoster<StateEvent> &poster) {
19✔
770
        // Now we have committed. If we had a schema update, re-save state data with the new schema.
771
        assert(ctx.deployment.state_data);
772
        auto &state_data = *ctx.deployment.state_data;
773
        if (state_data.update_info.has_db_schema_update) {
19✔
774
                state_data.update_info.has_db_schema_update = false;
×
775
                auto err = ctx.SaveDeploymentStateData(state_data);
×
776
                if (err != error::NoError) {
×
777
                        log::Error("Not able to commit schema update: " + err.String());
×
778
                        poster.PostEvent(StateEvent::Failure);
×
779
                        return;
780
                }
781
        }
782

783
        poster.PostEvent(StateEvent::Success);
19✔
784
}
785

786
void UpdateCheckRollbackState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
45✔
787
        DefaultAsyncErrorHandler(
45✔
788
                poster,
789
                ctx.deployment.update_module->AsyncSupportsRollback(
45✔
790
                        ctx.event_loop, [&ctx, &poster](expected::ExpectedBool rollback_supported) {
89✔
791
                                if (!rollback_supported.has_value()) {
45✔
792
                                        log::Error(rollback_supported.error().String());
1✔
793
                                        poster.PostEvent(StateEvent::Failure);
1✔
794
                                        return;
1✔
795
                                }
796

797
                                ctx.deployment.state_data->update_info.supports_rollback =
798
                                        SupportsRollbackToDbString(*rollback_supported);
44✔
799
                                if (*rollback_supported) {
44✔
800
                                        poster.PostEvent(StateEvent::RollbackStarted);
38✔
801
                                        poster.PostEvent(StateEvent::Success);
38✔
802
                                } else {
803
                                        poster.PostEvent(StateEvent::NothingToDo);
6✔
804
                                }
805
                        }));
45✔
806
}
45✔
807

808
void UpdateRollbackState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
41✔
809
        log::Debug("Entering ArtifactRollback state");
82✔
810

811
        DefaultAsyncErrorHandler(
41✔
812
                poster,
813
                ctx.deployment.update_module->AsyncArtifactRollback(
41✔
814
                        ctx.event_loop, DefaultStateHandler {poster}));
41✔
815
}
41✔
816

817
void UpdateRollbackRebootState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
57✔
818
        log::Debug("Entering ArtifactRollbackReboot state");
114✔
819

820
        auto exp_reboot_mode =
821
                DbStringToNeedsReboot(ctx.deployment.state_data->update_info.reboot_requested[0]);
57✔
822
        // Should always be true because we check it at load time.
823
        assert(exp_reboot_mode);
824

825
        // We ignore errors in this state as long as the ArtifactVerifyRollbackReboot state
826
        // succeeds.
827
        auto handler = [&poster](error::Error err) {
114✔
828
                if (err != error::NoError) {
57✔
829
                        log::Error(err.String());
2✔
830
                }
831
                poster.PostEvent(StateEvent::Success);
57✔
832
        };
57✔
833

834
        error::Error err;
57✔
835
        switch (exp_reboot_mode.value()) {
57✔
836
        case update_module::RebootAction::No:
837
                // Should not happen because then we don't enter this state.
838
                assert(false);
839

840
                err = error::MakeError(
×
841
                        error::ProgrammingError, "Entered UpdateRollbackRebootState with RebootAction = No");
×
842
                break;
×
843

844
        case update_module::RebootAction::Yes:
57✔
845
                err = ctx.deployment.update_module->AsyncArtifactRollbackReboot(ctx.event_loop, handler);
114✔
846
                break;
57✔
847

848
        case update_module::RebootAction::Automatic:
×
849
                err = ctx.deployment.update_module->AsyncSystemReboot(ctx.event_loop, handler);
×
850
                break;
×
851
        }
852

853
        if (err != error::NoError) {
57✔
854
                log::Error(err.String());
×
855
                poster.PostEvent(StateEvent::Success);
×
856
        }
857
}
57✔
858

859
void UpdateVerifyRollbackRebootState::OnEnterSaveState(
60✔
860
        Context &ctx, sm::EventPoster<StateEvent> &poster) {
861
        log::Debug("Entering ArtifactVerifyRollbackReboot state");
120✔
862

863
        // In this state we only retry, we don't fail. If this keeps on going forever, then the
864
        // state loop detection will eventually kick in.
865
        auto err = ctx.deployment.update_module->AsyncArtifactVerifyRollbackReboot(
866
                ctx.event_loop, [&poster](error::Error err) {
120✔
867
                        if (err != error::NoError) {
60✔
868
                                log::Error(err.String());
22✔
869
                                poster.PostEvent(StateEvent::Retry);
22✔
870
                                return;
22✔
871
                        }
872
                        poster.PostEvent(StateEvent::Success);
38✔
873
                });
60✔
874
        if (err != error::NoError) {
60✔
875
                log::Error(err.String());
×
876
                poster.PostEvent(StateEvent::Retry);
×
877
        }
878
}
60✔
879

880
void UpdateRollbackSuccessfulState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
50✔
881
        ctx.deployment.state_data->update_info.all_rollbacks_successful = true;
50✔
882
        poster.PostEvent(StateEvent::Success);
50✔
883
}
50✔
884

885
void UpdateFailureState::OnEnterSaveState(Context &ctx, sm::EventPoster<StateEvent> &poster) {
55✔
886
        log::Debug("Entering ArtifactFailure state");
110✔
887

888
        DefaultAsyncErrorHandler(
55✔
889
                poster,
890
                ctx.deployment.update_module->AsyncArtifactFailure(
55✔
891
                        ctx.event_loop, DefaultStateHandler {poster}));
55✔
892
}
55✔
893

894
static string AddInconsistentSuffix(const string &str) {
21✔
895
        const auto &suffix = main_context::MenderContext::broken_artifact_name_suffix;
896
        // `string::ends_with` is C++20... grumble
897
        string ret {str};
21✔
898
        if (!common::EndsWith(ret, suffix)) {
21✔
899
                ret.append(suffix);
21✔
900
        }
901
        return ret;
21✔
902
}
903

904
void UpdateSaveProvidesState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
75✔
905
        if (ctx.deployment.failed && !ctx.deployment.rollback_failed) {
75✔
906
                // If the update failed, but we rolled back successfully, then we don't need to do
907
                // anything, just keep the old data.
908
                poster.PostEvent(StateEvent::Success);
38✔
909
                return;
38✔
910
        }
911

912
        assert(ctx.deployment.state_data);
913
        // This state should never happen: rollback failed, but update not failed??
914
        assert(!(!ctx.deployment.failed && ctx.deployment.rollback_failed));
915

916
        // We expect Cleanup to be the next state after this.
917
        ctx.deployment.state_data->state = ctx.kUpdateStateCleanup;
37✔
918

919
        auto &artifact = ctx.deployment.state_data->update_info.artifact;
920

921
        string artifact_name;
922
        if (ctx.deployment.rollback_failed) {
37✔
923
                artifact_name = AddInconsistentSuffix(artifact.artifact_name);
38✔
924
        } else {
925
                artifact_name = artifact.artifact_name;
18✔
926
        }
927

928
        bool deploy_failed = ctx.deployment.failed;
37✔
929

930
        // Only the artifact_name and group should be committed in the case of a
931
        // failing update in order to make this consistent with the old client
932
        // behaviour.
933
        auto err = ctx.mender_context.CommitArtifactData(
37✔
934
                artifact_name,
935
                artifact.artifact_group,
37✔
936
                deploy_failed ? nullopt : optional<context::ProvidesData>(artifact.type_info_provides),
74✔
937
                /* Special case: Keep existing provides */
938
                deploy_failed ? context::ClearsProvidesData {}
93✔
939
                                          : optional<context::ClearsProvidesData>(artifact.clears_artifact_provides),
18✔
940
                [&ctx](kv_db::Transaction &txn) {
37✔
941
                        // Save the Cleanup state together with the artifact data, atomically.
942
                        return ctx.SaveDeploymentStateData(txn, *ctx.deployment.state_data);
37✔
943
                });
74✔
944
        if (err != error::NoError) {
37✔
945
                log::Error("Error saving artifact data: " + err.String());
×
946
                if (err.code
×
947
                        == main_context::MakeError(main_context::StateDataStoreCountExceededError, "").code) {
×
948
                        poster.PostEvent(StateEvent::StateLoopDetected);
×
949
                        return;
950
                }
951
                poster.PostEvent(StateEvent::Failure);
×
952
                return;
953
        }
954

955
        poster.PostEvent(StateEvent::Success);
37✔
956
}
957

958
void UpdateCleanupState::OnEnterSaveState(Context &ctx, sm::EventPoster<StateEvent> &poster) {
91✔
959
        log::Debug("Entering ArtifactCleanup state");
182✔
960

961
        // It's possible for there not to be an initialized update_module structure, if the
962
        // deployment failed before we could successfully parse the artifact. If so, cleanup is a
963
        // no-op.
964
        if (!ctx.deployment.update_module) {
91✔
965
                poster.PostEvent(StateEvent::Success);
9✔
966
                return;
9✔
967
        }
968

969
        DefaultAsyncErrorHandler(
82✔
970
                poster,
971
                ctx.deployment.update_module->AsyncCleanup(ctx.event_loop, DefaultStateHandler {poster}));
164✔
972
}
973

974
void ClearArtifactDataState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
93✔
975
        auto err = ctx.mender_context.GetMenderStoreDB().WriteTransaction([](kv_db::Transaction &txn) {
93✔
976
                // Remove state data, since we're done now.
977
                auto err = txn.Remove(main_context::MenderContext::state_data_key);
91✔
978
                if (err != error::NoError) {
91✔
979
                        return err;
×
980
                }
981
                return txn.Remove(main_context::MenderContext::state_data_key_uncommitted);
91✔
982
        });
93✔
983
        if (err != error::NoError) {
93✔
984
                log::Error("Error removing artifact data: " + err.String());
4✔
985
                poster.PostEvent(StateEvent::Failure);
2✔
986
                return;
987
        }
988

989
        poster.PostEvent(StateEvent::Success);
91✔
990
}
991

992
void StateLoopState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
2✔
993
        assert(ctx.deployment.state_data);
994
        auto &artifact = ctx.deployment.state_data->update_info.artifact;
995

996
        // Mark update as inconsistent.
997
        string artifact_name = AddInconsistentSuffix(artifact.artifact_name);
2✔
998

999
        auto err = ctx.mender_context.CommitArtifactData(
2✔
1000
                artifact_name,
1001
                artifact.artifact_group,
2✔
1002
                artifact.type_info_provides,
2✔
1003
                artifact.clears_artifact_provides,
2✔
1004
                [](kv_db::Transaction &txn) { return error::NoError; });
6✔
1005
        if (err != error::NoError) {
2✔
1006
                log::Error("Error saving inconsistent artifact data: " + err.String());
×
1007
                poster.PostEvent(StateEvent::Failure);
×
1008
                return;
1009
        }
1010

1011
        poster.PostEvent(StateEvent::Success);
2✔
1012
}
1013

1014
void EndOfDeploymentState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
93✔
1015
        log::Info(
93✔
1016
                "Deployment with ID " + ctx.deployment.state_data->update_info.id
186✔
1017
                + " finished with status: " + string(ctx.deployment.failed ? "Failure" : "Success"));
390✔
1018

1019
        ctx.FinishDeploymentLogging();
93✔
1020

1021
        ctx.deployment = {};
93✔
1022
        poster.PostEvent(
93✔
1023
                StateEvent::InventoryPollingTriggered); // Submit the inventory right after an update
93✔
1024
        poster.PostEvent(StateEvent::DeploymentEnded);
93✔
1025
        poster.PostEvent(StateEvent::Success);
93✔
1026
}
93✔
1027

1028
ExitState::ExitState(events::EventLoop &event_loop) :
96✔
1029
        event_loop_(event_loop) {
192✔
1030
}
96✔
1031

1032
void ExitState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
93✔
1033
#ifndef NDEBUG
1034
        if (--iterations_left_ <= 0) {
1035
                event_loop_.Stop();
1036
        } else {
1037
                poster.PostEvent(StateEvent::Success);
1038
        }
1039
#else
1040
        event_loop_.Stop();
93✔
1041
#endif
1042
}
93✔
1043

1044
namespace deployment_tracking {
1045

1046
void NoFailuresState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
63✔
1047
        ctx.deployment.failed = false;
63✔
1048
        ctx.deployment.rollback_failed = false;
63✔
1049
}
63✔
1050

1051
void FailureState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
60✔
1052
        ctx.deployment.failed = true;
60✔
1053
        ctx.deployment.rollback_failed = true;
60✔
1054
}
60✔
1055

1056
void RollbackAttemptedState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
52✔
1057
        ctx.deployment.failed = true;
52✔
1058
        ctx.deployment.rollback_failed = false;
52✔
1059
}
52✔
1060

1061
void RollbackFailedState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
12✔
1062
        ctx.deployment.failed = true;
12✔
1063
        ctx.deployment.rollback_failed = true;
12✔
1064
}
12✔
1065

1066
} // namespace deployment_tracking
1067

1068
} // namespace daemon
1069
} // namespace update
1070
} // namespace mender
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