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

systemd / systemd / 15720680019

17 Jun 2025 07:58PM UTC coverage: 72.087% (-0.02%) from 72.109%
15720680019

push

github

web-flow
sd-lldp: several improvements (#37845)

This makes
- sd-lldp-tx not send machine ID as chassis ID, but use application
specific machine ID,
- sd-lldp-tx emit vlan ID if it is running on a vlan interface,
- Describe() DBus method also reply LLDP configurations,
- io.systemd.Network.GetLLDPNeighbors varlink method provides vlan ID,
if received.

Closes #37613.

59 of 76 new or added lines in 3 files covered. (77.63%)

4663 existing lines in 75 files now uncovered.

300494 of 416851 relevant lines covered (72.09%)

704683.58 hits per line

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

66.14
/src/sysupdate/sysupdate-transfer.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <stdlib.h>
4
#include <sys/stat.h>
5

6
#include "sd-id128.h"
7

8
#include "alloc-util.h"
9
#include "build-path.h"
10
#include "chase.h"
11
#include "conf-parser.h"
12
#include "dirent-util.h"
13
#include "errno-util.h"
14
#include "event-util.h"
15
#include "extract-word.h"
16
#include "fd-util.h"
17
#include "fs-util.h"
18
#include "glyph-util.h"
19
#include "gpt.h"
20
#include "hashmap.h"
21
#include "hexdecoct.h"
22
#include "install-file.h"
23
#include "mkdir.h"
24
#include "notify-recv.h"
25
#include "parse-helpers.h"
26
#include "parse-util.h"
27
#include "percent-util.h"
28
#include "pidref.h"
29
#include "process-util.h"
30
#include "rm-rf.h"
31
#include "signal-util.h"
32
#include "specifier.h"
33
#include "stdio-util.h"
34
#include "strv.h"
35
#include "sync-util.h"
36
#include "sysupdate.h"
37
#include "sysupdate-feature.h"
38
#include "sysupdate-instance.h"
39
#include "sysupdate-pattern.h"
40
#include "sysupdate-resource.h"
41
#include "sysupdate-transfer.h"
42
#include "time-util.h"
43
#include "tmpfile-util.h"
44
#include "web-util.h"
45

46
/* Default value for InstancesMax= for fs object targets */
47
#define DEFAULT_FILE_INSTANCES_MAX 3
48

49
Transfer* transfer_free(Transfer *t) {
556✔
50
        if (!t)
556✔
51
                return NULL;
52

53
        t->temporary_path = rm_rf_subvolume_and_free(t->temporary_path);
556✔
54

55
        free(t->id);
556✔
56

57
        free(t->min_version);
556✔
58
        strv_free(t->protected_versions);
556✔
59
        free(t->current_symlink);
556✔
60
        free(t->final_path);
556✔
61

62
        strv_free(t->features);
556✔
63
        strv_free(t->requisite_features);
556✔
64

65
        strv_free(t->changelog);
556✔
66
        strv_free(t->appstream);
556✔
67

68
        partition_info_destroy(&t->partition_info);
556✔
69

70
        resource_destroy(&t->source);
556✔
71
        resource_destroy(&t->target);
556✔
72

73
        return mfree(t);
556✔
74
}
75

76
Transfer* transfer_new(Context *ctx) {
556✔
77
        Transfer *t;
556✔
78

79
        t = new(Transfer, 1);
556✔
80
        if (!t)
556✔
81
                return NULL;
82

83
        *t = (Transfer) {
556✔
84
                .source.type = _RESOURCE_TYPE_INVALID,
85
                .target.type = _RESOURCE_TYPE_INVALID,
86
                .remove_temporary = true,
87
                .mode = MODE_INVALID,
88
                .tries_left = UINT64_MAX,
89
                .tries_done = UINT64_MAX,
90
                .verify = true,
91

92
                /* the three flags, as configured by the user */
93
                .no_auto = -1,
94
                .read_only = -1,
95
                .growfs = -1,
96

97
                /* the read only flag, as ultimately determined */
98
                .install_read_only = -1,
99

100
                .partition_info = PARTITION_INFO_NULL,
101

102
                .context = ctx,
103
        };
104

105
        return t;
556✔
106
}
107

108
static int config_parse_protect_version(
×
109
                const char *unit,
110
                const char *filename,
111
                unsigned line,
112
                const char *section,
113
                unsigned section_line,
114
                const char *lvalue,
115
                int ltype,
116
                const char *rvalue,
117
                void *data,
118
                void *userdata) {
119

120
        _cleanup_free_ char *resolved = NULL;
×
121
        char ***protected_versions = ASSERT_PTR(data);
×
122
        int r;
×
123

124
        assert(rvalue);
×
125

126
        r = specifier_printf(rvalue, NAME_MAX, specifier_table, arg_root, NULL, &resolved);
×
127
        if (r < 0) {
×
128
                log_syntax(unit, LOG_WARNING, filename, line, r,
×
129
                           "Failed to expand specifiers in ProtectVersion=, ignoring: %s", rvalue);
130
                return 0;
×
131
        }
132

133
        if (!version_is_valid(resolved))  {
×
134
                log_syntax(unit, LOG_WARNING, filename, line, 0,
×
135
                           "ProtectVersion= string is not valid, ignoring: %s", resolved);
136
                return 0;
×
137
        }
138

139
        r = strv_extend(protected_versions, resolved);
×
140
        if (r < 0)
×
141
                return log_oom();
×
142

143
        return 0;
144
}
145

146
static int config_parse_min_version(
×
147
                const char *unit,
148
                const char *filename,
149
                unsigned line,
150
                const char *section,
151
                unsigned section_line,
152
                const char *lvalue,
153
                int ltype,
154
                const char *rvalue,
155
                void *data,
156
                void *userdata) {
157

158
        _cleanup_free_ char *resolved = NULL;
×
159
        char **version = ASSERT_PTR(data);
×
160
        int r;
×
161

162
        assert(rvalue);
×
163

164
        r = specifier_printf(rvalue, NAME_MAX, specifier_table, arg_root, NULL, &resolved);
×
165
        if (r < 0) {
×
166
                log_syntax(unit, LOG_WARNING, filename, line, r,
×
167
                           "Failed to expand specifiers in MinVersion=, ignoring: %s", rvalue);
168
                return 0;
×
169
        }
170

171
        if (!version_is_valid(rvalue)) {
×
172
                log_syntax(unit, LOG_WARNING, filename, line, 0,
×
173
                           "MinVersion= string is not valid, ignoring: %s", resolved);
174
                return 0;
×
175
        }
176

177
        return free_and_replace(*version, resolved);
×
178
}
179

180
static int config_parse_url_specifiers(
×
181
                const char *unit,
182
                const char *filename,
183
                unsigned line,
184
                const char *section,
185
                unsigned section_line,
186
                const char *lvalue,
187
                int ltype,
188
                const char *rvalue,
189
                void *data,
190
                void *userdata) {
191
        char ***s = ASSERT_PTR(data);
×
192
        _cleanup_free_ char *resolved = NULL;
×
193
        int r;
×
194

195
        assert(rvalue);
×
196

197
        if (isempty(rvalue)) {
×
198
                *s = strv_free(*s);
×
199
                return 0;
×
200
        }
201

202
        r = specifier_printf(rvalue, NAME_MAX, specifier_table, arg_root, NULL, &resolved);
×
203
        if (r < 0) {
×
204
                log_syntax(unit, LOG_WARNING, filename, line, r,
×
205
                           "Failed to expand specifiers in %s=, ignoring: %s", lvalue, rvalue);
206
                return 0;
×
207
        }
208

209
        if (!http_url_is_valid(resolved)) {
×
210
                log_syntax(unit, LOG_WARNING, filename, line, 0,
×
211
                           "%s= URL is not valid, ignoring: %s", lvalue, rvalue);
212
                return 0;
×
213
        }
214

215
        r = strv_push(s, TAKE_PTR(resolved));
×
216
        if (r < 0)
×
217
                return log_oom();
×
218

219
        return 0;
220
}
221

222
static int config_parse_current_symlink(
92✔
223
                const char *unit,
224
                const char *filename,
225
                unsigned line,
226
                const char *section,
227
                unsigned section_line,
228
                const char *lvalue,
229
                int ltype,
230
                const char *rvalue,
231
                void *data,
232
                void *userdata) {
233

234
        _cleanup_free_ char *resolved = NULL;
92✔
235
        char **current_symlink = ASSERT_PTR(data);
92✔
236
        int r;
92✔
237

238
        assert(rvalue);
92✔
239

240
        r = specifier_printf(rvalue, NAME_MAX, specifier_table, arg_root, NULL, &resolved);
92✔
241
        if (r < 0) {
92✔
242
                log_syntax(unit, LOG_WARNING, filename, line, r,
×
243
                           "Failed to expand specifiers in CurrentSymlink=, ignoring: %s", rvalue);
244
                return 0;
×
245
        }
246

247
        r = path_simplify_and_warn(resolved, 0, unit, filename, line, lvalue);
92✔
248
        if (r < 0)
92✔
249
                return 0;
250

251
        return free_and_replace(*current_symlink, resolved);
92✔
252
}
253

254
static int config_parse_instances_max(
368✔
255
                const char *unit,
256
                const char *filename,
257
                unsigned line,
258
                const char *section,
259
                unsigned section_line,
260
                const char *lvalue,
261
                int ltype,
262
                const char *rvalue,
263
                void *data,
264
                void *userdata) {
265

266
        uint64_t *instances_max = data, i;
368✔
267
        int r;
368✔
268

269
        assert(rvalue);
368✔
270
        assert(data);
368✔
271

272
        if (isempty(rvalue)) {
368✔
273
                *instances_max = 0; /* Revert to default logic, see transfer_read_definition() */
×
274
                return 0;
×
275
        }
276

277
        r = safe_atou64(rvalue, &i);
368✔
278
        if (r < 0) {
368✔
279
                log_syntax(unit, LOG_WARNING, filename, line, r,
×
280
                           "Failed to parse InstancesMax= value, ignoring: %s", rvalue);
281
                return 0;
×
282
        }
283

284
        if (i < 2) {
368✔
285
                log_syntax(unit, LOG_WARNING, filename, line, 0,
×
286
                           "InstancesMax= value must be at least 2, bumping: %s", rvalue);
287
                *instances_max = 2;
×
288
        } else
289
                *instances_max = i;
368✔
290

291
        return 0;
292
}
293

294
static int config_parse_resource_pattern(
1,112✔
295
                const char *unit,
296
                const char *filename,
297
                unsigned line,
298
                const char *section,
299
                unsigned section_line,
300
                const char *lvalue,
301
                int ltype,
302
                const char *rvalue,
303
                void *data,
304
                void *userdata) {
305

306
        char ***patterns = ASSERT_PTR(data);
1,112✔
307
        int r;
1,112✔
308

309
        assert(rvalue);
1,112✔
310

311
        if (isempty(rvalue)) {
1,112✔
312
                *patterns = strv_free(*patterns);
×
313
                return 0;
×
314
        }
315

316
        for (;;) {
3,704✔
317
                _cleanup_free_ char *word = NULL, *resolved = NULL;
1,296✔
318

319
                r = extract_first_word(&rvalue, &word, NULL, EXTRACT_CUNESCAPE|EXTRACT_UNESCAPE_RELAX);
2,408✔
320
                if (r < 0) {
2,408✔
321
                        log_syntax(unit, LOG_WARNING, filename, line, r,
×
322
                                   "Failed to extract first pattern from MatchPattern=, ignoring: %s", rvalue);
323
                        return 0;
×
324
                }
325
                if (r == 0)
2,408✔
326
                        break;
327

328
                r = specifier_printf(word, NAME_MAX, specifier_table, arg_root, NULL, &resolved);
1,296✔
329
                if (r < 0) {
1,296✔
330
                        log_syntax(unit, LOG_WARNING, filename, line, r,
×
331
                                   "Failed to expand specifiers in MatchPattern=, ignoring: %s", rvalue);
332
                        return 0;
×
333
                }
334

335
                if (!pattern_valid(resolved))
1,296✔
336
                        return log_syntax(unit, LOG_ERR, filename, line, SYNTHETIC_ERRNO(EINVAL),
×
337
                                          "MatchPattern= string is not valid, refusing: %s", resolved);
338

339
                r = strv_consume(patterns, TAKE_PTR(resolved));
1,296✔
340
                if (r < 0)
1,296✔
341
                        return log_oom();
×
342
        }
343

344
        strv_uniq(*patterns);
1,112✔
345
        return 0;
1,112✔
346
}
347

348
static int config_parse_resource_path(
1,112✔
349
                const char *unit,
350
                const char *filename,
351
                unsigned line,
352
                const char *section,
353
                unsigned section_line,
354
                const char *lvalue,
355
                int ltype,
356
                const char *rvalue,
357
                void *data,
358
                void *userdata) {
359
        _cleanup_free_ char *resolved = NULL;
1,112✔
360
        Resource *rr = ASSERT_PTR(data);
1,112✔
361
        int r;
1,112✔
362

363
        assert(rvalue);
1,112✔
364

365
        if (streq(rvalue, "auto")) {
1,112✔
366
                rr->path_auto = true;
×
367
                rr->path = mfree(rr->path);
×
368
                return 0;
×
369
        }
370

371
        r = specifier_printf(rvalue, PATH_MAX-1, specifier_table, arg_root, NULL, &resolved);
1,112✔
372
        if (r < 0) {
1,112✔
373
                log_syntax(unit, LOG_WARNING, filename, line, r,
×
374
                           "Failed to expand specifiers in Path=, ignoring: %s", rvalue);
375
                return 0;
×
376
        }
377

378
        /* Note that we don't validate the path as being absolute or normalized. We'll do that in
379
         * transfer_read_definition() as we might not know yet whether Path refers to a URL or a file system
380
         * path. */
381

382
        rr->path_auto = false;
1,112✔
383
        return free_and_replace(rr->path, resolved);
1,112✔
384
}
385

386
static DEFINE_CONFIG_PARSE_ENUM(config_parse_resource_type, resource_type, ResourceType);
1,112✔
387

388
static DEFINE_CONFIG_PARSE_ENUM_WITH_DEFAULT(config_parse_resource_path_relto, path_relative_to, PathRelativeTo,
552✔
389
                                             PATH_RELATIVE_TO_ROOT);
390

391
static int config_parse_resource_ptype(
188✔
392
                const char *unit,
393
                const char *filename,
394
                unsigned line,
395
                const char *section,
396
                unsigned section_line,
397
                const char *lvalue,
398
                int ltype,
399
                const char *rvalue,
400
                void *data,
401
                void *userdata) {
402

403
        Resource *rr = ASSERT_PTR(data);
188✔
404
        int r;
188✔
405

406
        assert(rvalue);
188✔
407

408
        r = gpt_partition_type_from_string(rvalue, &rr->partition_type);
188✔
409
        if (r < 0) {
188✔
410
                log_syntax(unit, LOG_WARNING, filename, line, r,
×
411
                           "Failed parse partition type, ignoring: %s", rvalue);
412
                return 0;
×
413
        }
414

415
        rr->partition_type_set = true;
188✔
416
        return 0;
188✔
417
}
418

419
static int config_parse_partition_uuid(
×
420
                const char *unit,
421
                const char *filename,
422
                unsigned line,
423
                const char *section,
424
                unsigned section_line,
425
                const char *lvalue,
426
                int ltype,
427
                const char *rvalue,
428
                void *data,
429
                void *userdata) {
430

431
        Transfer *t = ASSERT_PTR(data);
×
432
        int r;
×
433

434
        assert(rvalue);
×
435

436
        r = sd_id128_from_string(rvalue, &t->partition_uuid);
×
437
        if (r < 0) {
×
438
                log_syntax(unit, LOG_WARNING, filename, line, r,
×
439
                           "Failed parse partition UUID, ignoring: %s", rvalue);
440
                return 0;
×
441
        }
442

443
        t->partition_uuid_set = true;
×
444
        return 0;
×
445
}
446

447
static int config_parse_partition_flags(
×
448
                const char *unit,
449
                const char *filename,
450
                unsigned line,
451
                const char *section,
452
                unsigned section_line,
453
                const char *lvalue,
454
                int ltype,
455
                const char *rvalue,
456
                void *data,
457
                void *userdata) {
458

459
        Transfer *t = ASSERT_PTR(data);
×
460
        int r;
×
461

462
        assert(rvalue);
×
463

464
        r = safe_atou64(rvalue, &t->partition_flags);
×
465
        if (r < 0) {
×
466
                log_syntax(unit, LOG_WARNING, filename, line, r,
×
467
                           "Failed parse partition flags, ignoring: %s", rvalue);
468
                return 0;
×
469
        }
470

471
        t->partition_flags_set = true;
×
472
        return 0;
×
473
}
474

475
static bool transfer_decide_if_enabled(Transfer *t, Hashmap *known_features) {
556✔
476
        assert(t);
556✔
477

478
        /* Requisite feature disabled -> transfer disabled */
479
        STRV_FOREACH(id, t->requisite_features) {
556✔
480
                Feature *f = hashmap_get(known_features, *id);
×
481
                if (!f || !f->enabled) /* missing features are implicitly disabled */
×
482
                        return false;
483
        }
484

485
        /* No features defined -> transfer implicitly enabled */
486
        if (strv_isempty(t->features))
556✔
487
                return true;
488

489
        /* At least one feature enabled -> transfer enabled */
490
        STRV_FOREACH(id, t->features) {
174✔
491
                Feature *f = hashmap_get(known_features, *id);
92✔
492
                if (f && f->enabled)
92✔
493
                        return true;
494
        }
495

496
        /* All listed features disabled -> transfer disabled */
497
        return false;
498
}
499

500
int transfer_read_definition(Transfer *t, const char *path, const char **dirs, Hashmap *known_features) {
556✔
501
        assert(t);
556✔
502

503
        ConfigTableItem table[] = {
556✔
504
                { "Transfer",    "MinVersion",              config_parse_min_version,          0, &t->min_version             },
556✔
505
                { "Transfer",    "ProtectVersion",          config_parse_protect_version,      0, &t->protected_versions      },
556✔
506
                { "Transfer",    "Verify",                  config_parse_bool,                 0, &t->verify                  },
556✔
507
                { "Transfer",    "ChangeLog",               config_parse_url_specifiers,       0, &t->changelog               },
556✔
508
                { "Transfer",    "AppStream",               config_parse_url_specifiers,       0, &t->appstream               },
556✔
509
                { "Transfer",    "Features",                config_parse_strv,                 0, &t->features                },
556✔
510
                { "Transfer",    "RequisiteFeatures",       config_parse_strv,                 0, &t->requisite_features      },
556✔
511
                { "Source",      "Type",                    config_parse_resource_type,        0, &t->source.type             },
556✔
512
                { "Source",      "Path",                    config_parse_resource_path,        0, &t->source                  },
556✔
513
                { "Source",      "PathRelativeTo",          config_parse_resource_path_relto,  0, &t->source.path_relative_to },
556✔
514
                { "Source",      "MatchPattern",            config_parse_resource_pattern,     0, &t->source.patterns         },
556✔
515
                { "Target",      "Type",                    config_parse_resource_type,        0, &t->target.type             },
556✔
516
                { "Target",      "Path",                    config_parse_resource_path,        0, &t->target                  },
556✔
517
                { "Target",      "PathRelativeTo",          config_parse_resource_path_relto,  0, &t->target.path_relative_to },
556✔
518
                { "Target",      "MatchPattern",            config_parse_resource_pattern,     0, &t->target.patterns         },
556✔
519
                { "Target",      "MatchPartitionType",      config_parse_resource_ptype,       0, &t->target                  },
520
                { "Target",      "PartitionUUID",           config_parse_partition_uuid,       0, t                           },
521
                { "Target",      "PartitionFlags",          config_parse_partition_flags,      0, t                           },
522
                { "Target",      "PartitionNoAuto",         config_parse_tristate,             0, &t->no_auto                 },
556✔
523
                { "Target",      "PartitionGrowFileSystem", config_parse_tristate,             0, &t->growfs                  },
556✔
524
                { "Target",      "ReadOnly",                config_parse_tristate,             0, &t->read_only               },
556✔
525
                { "Target",      "Mode",                    config_parse_mode,                 0, &t->mode                    },
556✔
526
                { "Target",      "TriesLeft",               config_parse_uint64,               0, &t->tries_left              },
556✔
527
                { "Target",      "TriesDone",               config_parse_uint64,               0, &t->tries_done              },
556✔
528
                { "Target",      "InstancesMax",            config_parse_instances_max,        0, &t->instances_max           },
556✔
529
                { "Target",      "RemoveTemporary",         config_parse_bool,                 0, &t->remove_temporary        },
556✔
530
                { "Target",      "CurrentSymlink",          config_parse_current_symlink,      0, &t->current_symlink         },
556✔
531
                {}
532
        };
533

534
        _cleanup_free_ char *filename = NULL;
556✔
535
        char *e;
556✔
536
        int r;
556✔
537

538
        assert(path);
556✔
539
        assert(dirs);
556✔
540

541
        r = path_extract_filename(path, &filename);
556✔
542
        if (r < 0)
556✔
543
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
×
544

545
        r = config_parse_many(
1,668✔
546
                        STRV_MAKE_CONST(path),
556✔
547
                        dirs,
548
                        strjoina(filename, ".d"),
2,780✔
549
                        arg_root,
550
                        "Transfer\0"
551
                        "Source\0"
552
                        "Target\0",
553
                        config_item_table_lookup, table,
554
                        CONFIG_PARSE_WARN,
555
                        /* userdata= */ NULL,
556
                        /* stats_by_path= */ NULL,
557
                        /* drop_in_files= */ NULL);
558
        if (r < 0)
556✔
559
                return r;
560

561
        e = ASSERT_PTR(endswith(filename, ".transfer") ?: endswith(filename, ".conf"));
556✔
562
        *e = 0; /* Remove the file extension */
556✔
563
        t->id = TAKE_PTR(filename);
556✔
564

565
        t->enabled = transfer_decide_if_enabled(t, known_features);
556✔
566

567
        if (!RESOURCE_IS_SOURCE(t->source.type))
556✔
568
                return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
×
569
                                  "Source Type= must be one of url-file, url-tar, tar, regular-file, directory, subvolume.");
570

571
        if (t->target.type < 0) {
556✔
572
                switch (t->source.type) {
×
573

574
                case RESOURCE_URL_FILE:
×
575
                case RESOURCE_REGULAR_FILE:
576
                        t->target.type =
×
577
                                t->target.path && path_startswith(t->target.path, "/dev/") ?
×
578
                                RESOURCE_PARTITION : RESOURCE_REGULAR_FILE;
×
579
                        break;
×
580

581
                case RESOURCE_URL_TAR:
×
582
                case RESOURCE_TAR:
583
                case RESOURCE_DIRECTORY:
584
                        t->target.type = RESOURCE_DIRECTORY;
×
585
                        break;
×
586

587
                case RESOURCE_SUBVOLUME:
×
588
                        t->target.type = RESOURCE_SUBVOLUME;
×
589
                        break;
×
590

591
                default:
×
592
                        assert_not_reached();
×
593
                }
594
        }
595

596
        if (!RESOURCE_IS_TARGET(t->target.type))
556✔
597
                return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
×
598
                                  "Target Type= must be one of partition, regular-file, directory, subvolume.");
599

600
        if ((IN_SET(t->source.type, RESOURCE_URL_FILE, RESOURCE_PARTITION, RESOURCE_REGULAR_FILE) &&
556✔
601
             !IN_SET(t->target.type, RESOURCE_PARTITION, RESOURCE_REGULAR_FILE)) ||
464✔
602
            (IN_SET(t->source.type, RESOURCE_URL_TAR, RESOURCE_TAR, RESOURCE_DIRECTORY, RESOURCE_SUBVOLUME) &&
556✔
603
             !IN_SET(t->target.type, RESOURCE_DIRECTORY, RESOURCE_SUBVOLUME)))
92✔
604
                return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
×
605
                                  "Target type '%s' is incompatible with source type '%s', refusing.",
606
                                  resource_type_to_string(t->target.type), resource_type_to_string(t->source.type));
607

608
        if (!t->source.path && !t->source.path_auto)
556✔
609
                return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
×
610
                                  "Source specification lacks Path=.");
611

612
        if (t->source.path_relative_to == PATH_RELATIVE_TO_EXPLICIT && !arg_transfer_source)
556✔
613
                return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
×
614
                                  "PathRelativeTo=explicit requires --transfer-source= to be specified.");
615

616
        if (t->target.path_relative_to == PATH_RELATIVE_TO_EXPLICIT)
556✔
617
                return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
×
618
                                  "PathRelativeTo=explicit can only be used in source specifications.");
619

620
        if (t->source.path) {
556✔
621
                if (RESOURCE_IS_FILESYSTEM(t->source.type) || t->source.type == RESOURCE_PARTITION)
556✔
622
                        if (!path_is_absolute(t->source.path) || !path_is_normalized(t->source.path))
532✔
623
                                return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
×
624
                                                  "Source path is not a normalized, absolute path: %s", t->source.path);
625

626
                /* We unofficially support file:// in addition to http:// and https:// for url
627
                 * sources. That's mostly for testing, since it relieves us from having to set up a HTTP
628
                 * server, and CURL abstracts this away from us thankfully. */
629
                if (RESOURCE_IS_URL(t->source.type))
556✔
630
                        if (!http_url_is_valid(t->source.path) && !file_url_is_valid(t->source.path))
24✔
631
                                return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
×
632
                                                  "Source path is not a valid HTTP or HTTPS URL: %s", t->source.path);
633
        }
634

635
        if (strv_isempty(t->source.patterns))
556✔
636
                return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
×
637
                                  "Source specification lacks MatchPattern=.");
638

639
        if (!t->target.path && !t->target.path_auto)
556✔
640
                return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
×
641
                                  "Target specification lacks Path= field.");
642

643
        if (t->target.path &&
556✔
644
            (!path_is_absolute(t->target.path) || !path_is_normalized(t->target.path)))
556✔
645
                return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
×
646
                                  "Target path is not a normalized, absolute path: %s", t->target.path);
647

648
        if (strv_isempty(t->target.patterns)) {
556✔
649
                log_syntax(NULL, LOG_INFO, path, 1, 0, "Target specification lacks MatchPattern= expression. Assuming same value as in source specification.");
×
650
                strv_free(t->target.patterns);
×
651
                t->target.patterns = strv_copy(t->source.patterns);
×
652
                if (!t->target.patterns)
×
653
                        return log_oom();
×
654
        }
655

656
        if (t->current_symlink && !RESOURCE_IS_FILESYSTEM(t->target.type) && !path_is_absolute(t->current_symlink))
556✔
657
                return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
×
658
                                  "Current symlink must be absolute path if target is partition: %s", t->current_symlink);
659

660
        /* When no instance limit is set, use all available partition slots in case of partitions, or 3 in case of fs objects */
661
        if (t->instances_max == 0)
556✔
662
                t->instances_max = t->target.type == RESOURCE_PARTITION ? UINT64_MAX : DEFAULT_FILE_INSTANCES_MAX;
188✔
663

664
        return 0;
665
}
666

667
int transfer_resolve_paths(
556✔
668
                Transfer *t,
669
                const char *root,
670
                const char *node) {
671

672
        int r;
556✔
673

674
        /* If Path=auto is used in [Source] or [Target] sections, let's automatically detect the path of the
675
         * block device to use. Moreover, if this path points to a directory but we need a block device,
676
         * automatically determine the backing block device, so that users can reference block devices by
677
         * mount point. */
678

679
        assert(t);
556✔
680

681
        r = resource_resolve_path(&t->source, root, arg_transfer_source, node);
556✔
682
        if (r < 0)
556✔
683
                return r;
684

685
        r = resource_resolve_path(&t->target, root, /*relative_to_directory=*/ NULL, node);
556✔
686
        if (r < 0)
556✔
687
                return r;
×
688

689
        return 0;
690
}
691

692
static void transfer_remove_temporary(Transfer *t) {
102✔
693
        _cleanup_closedir_ DIR *d = NULL;
102✔
694
        int r;
102✔
695

696
        assert(t);
102✔
697

698
        if (!t->remove_temporary)
102✔
699
                return;
700

701
        if (!IN_SET(t->target.type, RESOURCE_REGULAR_FILE, RESOURCE_DIRECTORY, RESOURCE_SUBVOLUME))
102✔
702
                return;
703

704
        /* Removes all temporary files/dirs from previous runs in the target directory, i.e. all those starting with '.#' */
705

706
        d = opendir(t->target.path);
70✔
707
        if (!d) {
70✔
708
                if (errno == ENOENT)
×
709
                        return;
710

711
                log_debug_errno(errno, "Failed to open target directory '%s', ignoring: %m", t->target.path);
×
712
                return;
×
713
        }
714

715
        for (;;) {
266✔
716
                struct dirent *de;
266✔
717

718
                errno = 0;
266✔
719
                de = readdir_no_dot(d);
266✔
720
                if (!de) {
266✔
721
                        if (errno != 0)
70✔
722
                                log_debug_errno(errno, "Failed to read target directory '%s', ignoring: %m", t->target.path);
×
723
                        break;
70✔
724
                }
725

726
                if (!startswith(de->d_name, ".#"))
196✔
727
                        continue;
196✔
728

729
                r = rm_rf_child(dirfd(d), de->d_name, REMOVE_PHYSICAL|REMOVE_SUBVOLUME|REMOVE_CHMOD);
×
730
                if (r == -ENOENT)
×
731
                        continue;
×
732
                if (r < 0) {
×
733
                        log_warning_errno(r, "Failed to remove temporary resource instance '%s/%s', ignoring: %m", t->target.path, de->d_name);
×
734
                        continue;
×
735
                }
736

737
                log_debug("Removed temporary resource instance '%s/%s'.", t->target.path, de->d_name);
×
738
        }
739
}
740

741
int transfer_vacuum(
102✔
742
                Transfer *t,
743
                uint64_t space,
744
                const char *extra_protected_version) {
745

746
        uint64_t instances_max, limit;
102✔
747
        int r, count = 0;
102✔
748

749
        assert(t);
102✔
750

751
        transfer_remove_temporary(t);
102✔
752

753
        /* First, calculate how many instances to keep, based on the instance limit — but keep at least one */
754

755
        instances_max = arg_instances_max != UINT64_MAX ? arg_instances_max : t->instances_max;
102✔
756
        assert(instances_max >= 1);
102✔
757
        if (instances_max == UINT64_MAX) /* Keep infinite instances? */
102✔
758
                limit = UINT64_MAX;
759
        else if (space == UINT64_MAX) /* forcibly delete all instances? */
70✔
760
                limit = 0;
761
        else if (space > instances_max)
52✔
762
                return log_error_errno(SYNTHETIC_ERRNO(ENOSPC),
×
763
                                       "Asked to delete more instances than total maximum allowed number of instances, refusing.");
764
        else if (space == instances_max)
52✔
765
                return log_error_errno(SYNTHETIC_ERRNO(ENOSPC),
×
766
                                       "Asked to delete all possible instances, can't allow that. One instance must always remain.");
767
        else
768
                limit = instances_max - space;
52✔
769

770
        if (t->target.type == RESOURCE_PARTITION && space != UINT64_MAX) {
102✔
771
                uint64_t rm, remain;
32✔
772

773
                /* If we are looking at a partition table, we also have to take into account how many
774
                 * partition slots of the right type are available */
775

776
                if (t->target.n_empty + t->target.n_instances < 2)
32✔
777
                        return log_error_errno(SYNTHETIC_ERRNO(ENOSPC),
×
778
                                               "Partition table has less than two partition slots of the right type " SD_ID128_UUID_FORMAT_STR " (%s), refusing.",
779
                                               SD_ID128_FORMAT_VAL(t->target.partition_type.uuid),
780
                                               gpt_partition_type_uuid_to_string(t->target.partition_type.uuid));
781
                if (space > t->target.n_empty + t->target.n_instances)
32✔
782
                        return log_error_errno(SYNTHETIC_ERRNO(ENOSPC),
×
783
                                               "Partition table does not have enough partition slots of right type " SD_ID128_UUID_FORMAT_STR " (%s) for operation.",
784
                                               SD_ID128_FORMAT_VAL(t->target.partition_type.uuid),
785
                                               gpt_partition_type_uuid_to_string(t->target.partition_type.uuid));
786
                if (space == t->target.n_empty + t->target.n_instances)
32✔
787
                        return log_error_errno(SYNTHETIC_ERRNO(ENOSPC),
×
788
                                               "Asked to empty all partition table slots of the right type " SD_ID128_UUID_FORMAT_STR " (%s), can't allow that. One instance must always remain.",
789
                                               SD_ID128_FORMAT_VAL(t->target.partition_type.uuid),
790
                                               gpt_partition_type_uuid_to_string(t->target.partition_type.uuid));
791

792
                rm = LESS_BY(space, t->target.n_empty);
32✔
793
                remain = LESS_BY(t->target.n_instances, rm);
32✔
794
                limit = MIN(limit, remain);
32✔
795
        }
796

797
        while (t->target.n_instances > limit) {
152✔
798
                Instance *oldest;
50✔
799
                size_t p = t->target.n_instances - 1;
50✔
800

801
                for (;;) {
50✔
802
                        oldest = t->target.instances[p];
50✔
803
                        assert(oldest);
50✔
804

805
                        /* If this is listed among the protected versions, then let's not remove it */
806
                        if (!strv_contains(t->protected_versions, oldest->metadata.version) &&
50✔
807
                            (!extra_protected_version || !streq(extra_protected_version, oldest->metadata.version)))
48✔
808
                                break;
809

810
                        log_debug("Version '%s' is protected, not removing.", oldest->metadata.version);
×
811
                        if (p == 0) {
×
812
                                oldest = NULL;
813
                                break;
814
                        }
815

816
                        p--;
×
817
                }
818

819
                if (!oldest) /* Nothing more to remove */
50✔
820
                        break;
821

822
                assert(oldest->resource);
50✔
823

824
                log_info("%s Removing %s '%s' (%s).",
100✔
825
                         glyph(GLYPH_RECYCLING),
826
                         space == UINT64_MAX ? "disabled" : "old",
827
                         oldest->path,
828
                         resource_type_to_string(oldest->resource->type));
829

830
                switch (t->target.type) {
50✔
831

832
                case RESOURCE_REGULAR_FILE:
30✔
833
                case RESOURCE_DIRECTORY:
834
                case RESOURCE_SUBVOLUME:
835
                        r = rm_rf(oldest->path, REMOVE_ROOT|REMOVE_PHYSICAL|REMOVE_SUBVOLUME|REMOVE_MISSING_OK|REMOVE_CHMOD);
30✔
836
                        if (r < 0 && r != -ENOENT)
30✔
837
                                return log_error_errno(r, "Failed to make room, deleting '%s' failed: %m", oldest->path);
×
838

839
                        (void) rmdir_parents(oldest->path, t->target.path);
30✔
840

841
                        break;
30✔
842

843
                case RESOURCE_PARTITION: {
20✔
844
                        PartitionInfo pinfo = oldest->partition_info;
20✔
845

846
                        /* label "_empty" means "no contents" for our purposes */
847
                        pinfo.label = (char*) "_empty";
20✔
848

849
                        r = patch_partition(t->target.path, &pinfo, PARTITION_LABEL);
20✔
850
                        if (r < 0)
20✔
851
                                return r;
×
852

853
                        t->target.n_empty++;
20✔
854
                        break;
20✔
855
                }
856

857
                default:
×
858
                        assert_not_reached();
×
859
                }
860

861
                instance_free(oldest);
50✔
862
                memmove(t->target.instances + p, t->target.instances + p + 1, (t->target.n_instances - p - 1) * sizeof(Instance*));
50✔
863
                t->target.n_instances--;
50✔
864

865
                count++;
50✔
866
        }
867

868
        return count;
869
}
870

871
static void compile_pattern_fields(
74✔
872
                const Transfer *t,
873
                const Instance *i,
874
                InstanceMetadata *ret) {
875

876
        assert(t);
74✔
877
        assert(i);
74✔
878
        assert(ret);
74✔
879

880
        *ret = (InstanceMetadata) {
148✔
881
                .version = i->metadata.version,
74✔
882

883
                /* We generally prefer explicitly configured values for the transfer over those automatically
884
                 * derived from the source instance. Also, if the source is a tar archive, then let's not
885
                 * patch mtime/mode and use the one embedded in the tar file */
886
                .partition_uuid = t->partition_uuid_set ? t->partition_uuid : i->metadata.partition_uuid,
74✔
887
                .partition_uuid_set = t->partition_uuid_set || i->metadata.partition_uuid_set,
74✔
888
                .partition_flags = t->partition_flags_set ? t->partition_flags : i->metadata.partition_flags,
74✔
889
                .partition_flags_set = t->partition_flags_set || i->metadata.partition_flags_set,
74✔
890
                .mtime = RESOURCE_IS_TAR(i->resource->type) ? USEC_INFINITY : i->metadata.mtime,
74✔
891
                .mode = t->mode != MODE_INVALID ? t->mode : (RESOURCE_IS_TAR(i->resource->type) ? MODE_INVALID : i->metadata.mode),
74✔
892
                .size = i->metadata.size,
74✔
893
                .tries_done = t->tries_done != UINT64_MAX ? t->tries_done :
74✔
894
                              i->metadata.tries_done != UINT64_MAX ? i->metadata.tries_done : 0,
60✔
895
                .tries_left = t->tries_left != UINT64_MAX ? t->tries_left :
74✔
896
                              i->metadata.tries_left != UINT64_MAX ? i->metadata.tries_left : 3,
60✔
897
                .no_auto = t->no_auto >= 0 ? t->no_auto : i->metadata.no_auto,
74✔
898
                .read_only = t->read_only >= 0 ? t->read_only : i->metadata.read_only,
74✔
899
                .growfs = t->growfs >= 0 ? t->growfs : i->metadata.growfs,
74✔
900
                .sha256sum_set = i->metadata.sha256sum_set,
74✔
901
        };
902

903
        memcpy(ret->sha256sum, i->metadata.sha256sum, sizeof(ret->sha256sum));
74✔
904
}
74✔
905

906
typedef struct CalloutContext {
907
        const Transfer *transfer;
908
        const Instance *instance;
909
        TransferProgress callback;
910
        PidRef pid;
911
        const char *name;
912
        int helper_errno;
913
        void* userdata;
914
} CalloutContext;
915

916
static CalloutContext *callout_context_free(CalloutContext *ctx) {
74✔
917
        if (!ctx)
74✔
918
                return NULL;
919

920
        /* We don't own any data but need to clean up the job pid */
921
        pidref_done(&ctx->pid);
74✔
922

923
        return mfree(ctx);
74✔
924
}
925

926
DEFINE_TRIVIAL_CLEANUP_FUNC(CalloutContext*, callout_context_free);
148✔
927

928
static int callout_context_new(const Transfer *t, const Instance *i, TransferProgress cb,
74✔
929
                               const char *name, void* userdata, CalloutContext **ret) {
930
        _cleanup_(callout_context_freep) CalloutContext *ctx = NULL;
74✔
931

932
        assert(t);
74✔
933
        assert(i);
74✔
934
        assert(cb);
74✔
935

936
        ctx = new(CalloutContext, 1);
74✔
937
        if (!ctx)
74✔
938
                return -ENOMEM;
939

940
        *ctx = (CalloutContext) {
74✔
941
                .transfer = t,
942
                .instance = i,
943
                .callback = cb,
944
                .pid = PIDREF_NULL,
945
                .name = name,
946
                .userdata = userdata,
947
        };
948

949
        *ret = TAKE_PTR(ctx);
74✔
950
        return 0;
74✔
951
}
952

953
static int helper_on_exit(sd_event_source *s, const siginfo_t *si, void *userdata) {
74✔
954
        CalloutContext *ctx = ASSERT_PTR(userdata);
74✔
955
        int r;
74✔
956

957
        assert(s);
74✔
958
        assert(si);
74✔
959
        assert(ctx);
74✔
960

961
        if (si->si_code == CLD_EXITED) {
74✔
962
                if (si->si_status == EXIT_SUCCESS) {
74✔
963
                        r = 0;
74✔
964
                        log_debug("%s succeeded.", ctx->name);
74✔
965
                } else if (ctx->helper_errno != 0) {
×
966
                        r = -ctx->helper_errno;
×
967
                        log_error_errno(r, "%s failed with exit status %i: %m", ctx->name, si->si_status);
×
968
                } else {
969
                        r = -EPROTO;
×
970
                        log_error("%s failed with exit status %i.", ctx->name, si->si_status);
×
971
                }
972
        } else {
973
                r = -EPROTO;
×
974
                if (IN_SET(si->si_code, CLD_KILLED, CLD_DUMPED))
×
975
                        log_error("%s terminated by signal %s.", ctx->name, signal_to_string(si->si_status));
×
976
                else
977
                        log_error("%s failed due to unknown reason.", ctx->name);
×
978
        }
979

980
        return sd_event_exit(sd_event_source_get_event(s), r);
74✔
981
}
982

983
static int helper_on_notify(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
139✔
984
        CalloutContext *ctx = ASSERT_PTR(userdata);
139✔
985
        int r;
139✔
986

987
        assert(fd >= 0);
139✔
988

989
        _cleanup_free_ char *buf = NULL;
139✔
990
        _cleanup_(pidref_done) PidRef sender_pid = PIDREF_NULL;
139✔
991
        r = notify_recv(fd, &buf, /* ret_ucred= */ NULL, &sender_pid);
139✔
992
        if (r == -EAGAIN)
139✔
993
                return 0;
994
        if (r < 0)
139✔
995
                return r;
996

997
        if (!pidref_equal(&ctx->pid, &sender_pid)) {
139✔
998
                log_warning("Got notification datagram from unexpected peer, ignoring.");
×
999
                return 0;
×
1000
        }
1001

1002
        char *errno_str = find_line_startswith(buf, "ERRNO=");
139✔
1003
        if (errno_str) {
139✔
1004
                truncate_nl(errno_str);
×
1005
                r = parse_errno(errno_str);
×
1006
                if (r < 0)
×
1007
                        log_warning_errno(r, "Got invalid errno value '%s', ignoring: %m", errno_str);
×
1008
                else {
1009
                        ctx->helper_errno = r;
×
1010
                        log_debug_errno(r, "Got errno from callout: %i (%m)", r);
×
1011
                }
1012
        }
1013

1014
        char *progress_str = find_line_startswith(buf, "X_IMPORT_PROGRESS=");
139✔
1015
        if (progress_str) {
139✔
1016
                truncate_nl(progress_str);
65✔
1017

1018
                int progress = parse_percent(progress_str);
65✔
1019
                if (progress < 0)
65✔
1020
                        log_warning("Got invalid percent value '%s', ignoring.", progress_str);
×
1021
                else {
1022
                        r = ctx->callback(ctx->transfer, ctx->instance, progress);
65✔
1023
                        if (r < 0)
65✔
1024
                                return r;
×
1025
                }
1026
        }
1027

1028
        return 0;
1029
}
1030

1031
static int run_callout(
74✔
1032
                const char *name,
1033
                char *cmdline[],
1034
                const Transfer *transfer,
1035
                const Instance *instance,
1036
                TransferProgress callback,
1037
                void *userdata) {
1038

1039
        int r;
74✔
1040

1041
        assert(name);
74✔
1042
        assert(cmdline);
74✔
1043
        assert(cmdline[0]);
74✔
1044

1045
        _cleanup_(callout_context_freep) CalloutContext *ctx = NULL;
×
1046
        r = callout_context_new(transfer, instance, callback, name, userdata, &ctx);
74✔
1047
        if (r < 0)
74✔
1048
                return log_oom();
×
1049

1050
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
74✔
1051
        r = sd_event_new(&event);
74✔
1052
        if (r < 0)
74✔
1053
                return log_error_errno(r, "Failed to create event: %m");
×
1054

1055
        /* Kill the helper & return an error if we get interrupted by a signal */
1056
        r = sd_event_add_signal(event, NULL, SIGINT | SD_EVENT_SIGNAL_PROCMASK, NULL, INT_TO_PTR(-ECANCELED));
74✔
1057
        if (r < 0)
74✔
1058
                return log_error_errno(r, "Failed to register signal to event: %m");
×
1059
        r = sd_event_add_signal(event, NULL, SIGTERM | SD_EVENT_SIGNAL_PROCMASK, NULL, INT_TO_PTR(-ECANCELED));
74✔
1060
        if (r < 0)
74✔
1061
                return log_error_errno(r, "Failed to register signal to event: %m");
×
1062

1063
        _cleanup_free_ char *bind_name = NULL;
74✔
1064
        r = notify_socket_prepare(
74✔
1065
                        event,
1066
                        SD_EVENT_PRIORITY_NORMAL - 5,
1067
                        helper_on_notify,
1068
                        ctx,
1069
                        &bind_name);
1070
        if (r < 0)
74✔
UNCOV
1071
                return log_error_errno(r, "Failed to prepare notify socket: %m");
×
1072

1073
        r = pidref_safe_fork(ctx->name, FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGTERM|FORK_LOG, &ctx->pid);
74✔
1074
        if (r < 0)
148✔
UNCOV
1075
                return log_error_errno(r, "Failed to fork process %s: %m", ctx->name);
×
1076
        if (r == 0) {
148✔
1077
                /* Child */
1078
                if (setenv("NOTIFY_SOCKET", bind_name, 1) < 0) {
74✔
UNCOV
1079
                        log_error_errno(errno, "setenv() failed: %m");
×
1080
                        _exit(EXIT_FAILURE);
×
1081
                }
1082
                r = invoke_callout_binary(cmdline[0], (char *const*) cmdline);
74✔
UNCOV
1083
                log_error_errno(r, "Failed to execute %s tool: %m", cmdline[0]);
×
1084
                _exit(EXIT_FAILURE);
×
1085
        }
1086

1087
        /* Quit the loop w/ when child process exits */
1088
        _cleanup_(sd_event_source_unrefp) sd_event_source *exit_source = NULL;
74✔
1089
        r = event_add_child_pidref(event, &exit_source, &ctx->pid, WEXITED, helper_on_exit, ctx);
74✔
1090
        if (r < 0)
74✔
UNCOV
1091
                return log_error_errno(r, "Failed to add child process to event loop: %m");
×
1092

1093
        r = sd_event_source_set_child_process_own(exit_source, true);
74✔
1094
        if (r < 0)
74✔
UNCOV
1095
                return log_error_errno(r, "Failed to take ownership of child process: %m");
×
1096

1097
        /* Process events until the helper quits */
1098
        return sd_event_loop(event);
74✔
1099
}
1100

1101
int transfer_acquire_instance(Transfer *t, Instance *i, TransferProgress cb, void *userdata) {
74✔
1102
        _cleanup_free_ char *formatted_pattern = NULL, *digest = NULL;
74✔
1103
        char offset[DECIMAL_STR_MAX(uint64_t)+1], max_size[DECIMAL_STR_MAX(uint64_t)+1];
74✔
1104
        const char *where = NULL;
74✔
1105
        InstanceMetadata f;
74✔
1106
        Instance *existing;
74✔
1107
        int r;
74✔
1108

1109
        assert(t);
74✔
1110
        assert(i);
74✔
1111
        assert(i->resource == &t->source);
74✔
1112
        assert(cb);
74✔
1113

1114
        /* Does this instance already exist in the target? Then we don't need to acquire anything */
1115
        existing = resource_find_instance(&t->target, i->metadata.version);
74✔
1116
        if (existing) {
74✔
UNCOV
1117
                log_info("No need to acquire '%s', already installed.", i->path);
×
1118
                return 0;
×
1119
        }
1120

1121
        assert(!t->final_path);
74✔
1122
        assert(!t->temporary_path);
74✔
1123
        assert(!strv_isempty(t->target.patterns));
74✔
1124

1125
        /* Format the target name using the first pattern specified */
1126
        compile_pattern_fields(t, i, &f);
74✔
1127
        r = pattern_format(t->target.patterns[0], &f, &formatted_pattern);
74✔
1128
        if (r < 0)
74✔
UNCOV
1129
                return log_error_errno(r, "Failed to format target pattern: %m");
×
1130

1131
        if (RESOURCE_IS_FILESYSTEM(t->target.type)) {
74✔
1132

1133
                if (!path_is_valid_full(formatted_pattern, /* accept_dot_dot = */ false))
46✔
UNCOV
1134
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Formatted pattern is not suitable as file name, refusing: %s", formatted_pattern);
×
1135

1136
                t->final_path = path_join(t->target.path, formatted_pattern);
46✔
1137
                if (!t->final_path)
46✔
UNCOV
1138
                        return log_oom();
×
1139

1140
                r = mkdir_parents(t->final_path, 0755);
46✔
1141
                if (r < 0)
46✔
UNCOV
1142
                        return log_error_errno(r, "Cannot create target directory: %m");
×
1143

1144
                r = tempfn_random(t->final_path, "sysupdate", &t->temporary_path);
46✔
1145
                if (r < 0)
46✔
UNCOV
1146
                        return log_error_errno(r, "Failed to generate temporary target path: %m");
×
1147

1148
                where = t->final_path;
46✔
1149
        }
1150

1151
        if (t->target.type == RESOURCE_PARTITION) {
74✔
1152
                r = gpt_partition_label_valid(formatted_pattern);
28✔
1153
                if (r < 0)
28✔
UNCOV
1154
                        return log_error_errno(r, "Failed to determine if formatted pattern is suitable as GPT partition label: %s", formatted_pattern);
×
1155
                if (!r)
28✔
UNCOV
1156
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Formatted pattern is not suitable as GPT partition label, refusing: %s", formatted_pattern);
×
1157

1158
                r = find_suitable_partition(
28✔
1159
                                t->target.path,
28✔
1160
                                i->metadata.size,
1161
                                t->target.partition_type_set ? &t->target.partition_type.uuid : NULL,
28✔
1162
                                &t->partition_info);
1163
                if (r < 0)
28✔
1164
                        return r;
1165

1166
                xsprintf(offset, "%" PRIu64, t->partition_info.start);
28✔
1167
                xsprintf(max_size, "%" PRIu64, t->partition_info.size);
28✔
1168

1169
                where = t->partition_info.device;
28✔
1170
        }
1171

1172
        assert(where);
74✔
1173

1174
        log_info("%s Acquiring %s %s %s...", glyph(GLYPH_DOWNLOAD), i->path, glyph(GLYPH_ARROW_RIGHT), where);
148✔
1175

1176
        if (RESOURCE_IS_URL(i->resource->type)) {
74✔
1177
                /* For URL sources we require the SHA256 sum to be known so that we can validate the
1178
                 * download. */
1179

1180
                if (!i->metadata.sha256sum_set)
8✔
UNCOV
1181
                        return log_error_errno(r, "SHA256 checksum not known for download '%s', refusing.", i->path);
×
1182

1183
                digest = hexmem(i->metadata.sha256sum, sizeof(i->metadata.sha256sum));
8✔
1184
                if (!digest)
8✔
UNCOV
1185
                        return log_oom();
×
1186
        }
1187

1188
        switch (i->resource->type) { /* Source */
74✔
1189

1190
        case RESOURCE_REGULAR_FILE:
56✔
1191

1192
                switch (t->target.type) { /* Target */
56✔
1193

1194
                case RESOURCE_REGULAR_FILE:
32✔
1195

1196
                        /* regular file → regular file (why fork off systemd-import for such a simple file
1197
                         * copy case? implicit decompression mostly, and thus also sandboxing. Also, the
1198
                         * importer has some tricks up its sleeve, such as sparse file generation, which we
1199
                         * want to take benefit of, too.) */
1200

1201
                        r = run_callout("(sd-import-raw)",
64✔
1202
                                        STRV_MAKE(
32✔
1203
                                               SYSTEMD_IMPORT_PATH,
1204
                                               "raw",
1205
                                               "--direct",          /* just copy/unpack the specified file, don't do anything else */
1206
                                               arg_sync ? "--sync=yes" : "--sync=no",
1207
                                               i->path,
1208
                                               t->temporary_path),
1209
                                        t, i, cb, userdata);
1210
                        break;
56✔
1211

1212
                case RESOURCE_PARTITION:
24✔
1213

1214
                        /* regular file → partition */
1215

1216
                        r = run_callout("(sd-import-raw)",
48✔
1217
                                        STRV_MAKE(
24✔
1218
                                               SYSTEMD_IMPORT_PATH,
1219
                                               "raw",
1220
                                               "--direct",          /* just copy/unpack the specified file, don't do anything else */
1221
                                               "--offset", offset,
1222
                                               "--size-max", max_size,
1223
                                               arg_sync ? "--sync=yes" : "--sync=no",
1224
                                               i->path,
1225
                                               t->target.path),
1226
                                        t, i, cb, userdata);
1227
                        break;
1228

UNCOV
1229
                default:
×
1230
                        assert_not_reached();
×
1231
                }
1232

1233
                break;
56✔
1234

1235
        case RESOURCE_DIRECTORY:
10✔
1236
        case RESOURCE_SUBVOLUME:
1237
                assert(IN_SET(t->target.type, RESOURCE_DIRECTORY, RESOURCE_SUBVOLUME));
10✔
1238

1239
                /* directory/subvolume → directory/subvolume */
1240

1241
                r = run_callout("(sd-import-fs)",
20✔
1242
                                STRV_MAKE(
20✔
1243
                                       SYSTEMD_IMPORT_FS_PATH,
1244
                                       "run",
1245
                                       "--direct",          /* just untar the specified file, don't do anything else */
1246
                                       arg_sync ? "--sync=yes" : "--sync=no",
1247
                                       t->target.type == RESOURCE_SUBVOLUME ? "--btrfs-subvol=yes" : "--btrfs-subvol=no",
1248
                                       i->path,
1249
                                       t->temporary_path),
1250
                                t, i, cb, userdata);
1251
                break;
1252

UNCOV
1253
        case RESOURCE_TAR:
×
1254
                assert(IN_SET(t->target.type, RESOURCE_DIRECTORY, RESOURCE_SUBVOLUME));
×
1255

1256
                /* tar → directory/subvolume */
1257

UNCOV
1258
                r = run_callout("(sd-import-tar)",
×
1259
                                STRV_MAKE(
×
1260
                                       SYSTEMD_IMPORT_PATH,
1261
                                       "tar",
1262
                                       "--direct",          /* just untar the specified file, don't do anything else */
1263
                                       arg_sync ? "--sync=yes" : "--sync=no",
1264
                                       t->target.type == RESOURCE_SUBVOLUME ? "--btrfs-subvol=yes" : "--btrfs-subvol=no",
1265
                                       i->path,
1266
                                       t->temporary_path),
1267
                                t, i, cb, userdata);
1268
                break;
1269

1270
        case RESOURCE_URL_FILE:
4✔
1271

1272
                switch (t->target.type) {
4✔
1273

UNCOV
1274
                case RESOURCE_REGULAR_FILE:
×
1275

1276
                        /* url file → regular file */
1277

UNCOV
1278
                        r = run_callout("(sd-pull-raw)",
×
1279
                                       STRV_MAKE(
×
1280
                                               SYSTEMD_PULL_PATH,
1281
                                               "raw",
1282
                                               "--direct",          /* just download the specified URL, don't download anything else */
1283
                                               "--verify", digest,  /* validate by explicit SHA256 sum */
1284
                                               arg_sync ? "--sync=yes" : "--sync=no",
1285
                                               i->path,
1286
                                               t->temporary_path),
1287
                                        t, i, cb, userdata);
1288
                        break;
4✔
1289

1290
                case RESOURCE_PARTITION:
4✔
1291

1292
                        /* url file → partition */
1293

1294
                        r = run_callout("(sd-pull-raw)",
8✔
1295
                                        STRV_MAKE(
4✔
1296
                                               SYSTEMD_PULL_PATH,
1297
                                               "raw",
1298
                                               "--direct",              /* just download the specified URL, don't download anything else */
1299
                                               "--verify", digest,      /* validate by explicit SHA256 sum */
1300
                                               "--offset", offset,
1301
                                               "--size-max", max_size,
1302
                                               arg_sync ? "--sync=yes" : "--sync=no",
1303
                                               i->path,
1304
                                               t->target.path),
1305
                                        t, i, cb, userdata);
1306
                        break;
1307

UNCOV
1308
                default:
×
1309
                        assert_not_reached();
×
1310
                }
1311

1312
                break;
4✔
1313

1314
        case RESOURCE_URL_TAR:
4✔
1315
                assert(IN_SET(t->target.type, RESOURCE_DIRECTORY, RESOURCE_SUBVOLUME));
4✔
1316

1317
                r = run_callout("(sd-pull-tar)",
8✔
1318
                                STRV_MAKE(
8✔
1319
                                       SYSTEMD_PULL_PATH,
1320
                                       "tar",
1321
                                       "--direct",          /* just download the specified URL, don't download anything else */
1322
                                       "--verify", digest,  /* validate by explicit SHA256 sum */
1323
                                       t->target.type == RESOURCE_SUBVOLUME ? "--btrfs-subvol=yes" : "--btrfs-subvol=no",
1324
                                       arg_sync ? "--sync=yes" : "--sync=no",
1325
                                       i->path,
1326
                                       t->temporary_path),
1327
                                t, i, cb, userdata);
1328
                break;
1329

UNCOV
1330
        default:
×
1331
                assert_not_reached();
×
1332
        }
1333
        if (r < 0)
74✔
1334
                return r;
1335

1336
        if (RESOURCE_IS_FILESYSTEM(t->target.type)) {
74✔
1337
                bool need_sync = false;
46✔
1338
                assert(t->temporary_path);
46✔
1339

1340
                /* Apply file attributes if set */
1341
                if (f.mtime != USEC_INFINITY) {
46✔
1342
                        struct timespec ts;
42✔
1343

1344
                        timespec_store(&ts, f.mtime);
42✔
1345

1346
                        if (utimensat(AT_FDCWD, t->temporary_path, (struct timespec[2]) { ts, ts }, AT_SYMLINK_NOFOLLOW) < 0)
42✔
UNCOV
1347
                                return log_error_errno(errno, "Failed to adjust mtime of '%s': %m", t->temporary_path);
×
1348

1349
                        need_sync = true;
42✔
1350
                }
1351

1352
                if (f.mode != MODE_INVALID) {
46✔
1353
                        /* Try with AT_SYMLINK_NOFOLLOW first, because it's the safe thing to do. Older
1354
                         * kernels don't support that however, in that case we fall back to chmod(). Not as
1355
                         * safe, but shouldn't be a problem, given that we don't create symlinks here. */
1356
                        if (fchmodat(AT_FDCWD, t->temporary_path, f.mode, AT_SYMLINK_NOFOLLOW) < 0 &&
42✔
UNCOV
1357
                            (!ERRNO_IS_NOT_SUPPORTED(errno) || chmod(t->temporary_path, f.mode) < 0))
×
1358
                                return log_error_errno(errno, "Failed to adjust mode of '%s': %m", t->temporary_path);
×
1359

1360
                        need_sync = true;
1361
                }
1362

1363
                /* Synchronize */
1364
                if (arg_sync && need_sync) {
46✔
1365
                        if (t->target.type == RESOURCE_REGULAR_FILE)
42✔
1366
                                r = fsync_path_and_parent_at(AT_FDCWD, t->temporary_path);
32✔
1367
                        else {
1368
                                assert(IN_SET(t->target.type, RESOURCE_DIRECTORY, RESOURCE_SUBVOLUME));
10✔
1369
                                r = syncfs_path(AT_FDCWD, t->temporary_path);
10✔
1370
                        }
1371
                        if (r < 0)
42✔
UNCOV
1372
                                return log_error_errno(r, "Failed to synchronize file system backing '%s': %m", t->temporary_path);
×
1373
                }
1374

1375
                t->install_read_only = f.read_only;
46✔
1376
        }
1377

1378
        if (t->target.type == RESOURCE_PARTITION) {
74✔
1379
                free_and_replace(t->partition_info.label, formatted_pattern);
28✔
1380
                t->partition_change = PARTITION_LABEL;
28✔
1381

1382
                if (f.partition_uuid_set) {
28✔
UNCOV
1383
                        t->partition_info.uuid = f.partition_uuid;
×
1384
                        t->partition_change |= PARTITION_UUID;
×
1385
                }
1386

1387
                if (f.partition_flags_set) {
28✔
UNCOV
1388
                        t->partition_info.flags = f.partition_flags;
×
1389
                        t->partition_change |= PARTITION_FLAGS;
×
1390
                }
1391

1392
                if (f.no_auto >= 0) {
28✔
UNCOV
1393
                        t->partition_info.no_auto = f.no_auto;
×
1394
                        t->partition_change |= PARTITION_NO_AUTO;
×
1395
                }
1396

1397
                if (f.read_only >= 0) {
28✔
UNCOV
1398
                        t->partition_info.read_only = f.read_only;
×
1399
                        t->partition_change |= PARTITION_READ_ONLY;
×
1400
                }
1401

1402
                if (f.growfs >= 0) {
28✔
UNCOV
1403
                        t->partition_info.growfs = f.growfs;
×
1404
                        t->partition_change |= PARTITION_GROWFS;
×
1405
                }
1406
        }
1407

1408
        /* For regular file cases the only step left is to install the file in place, which install_file()
1409
         * will do via rename(). For partition cases the only step left is to update the partition table,
1410
         * which is done at the same place. */
1411

1412
        log_info("Successfully acquired '%s'.", i->path);
74✔
1413
        return 0;
1414
}
1415

1416
int transfer_install_instance(
74✔
1417
                Transfer *t,
1418
                Instance *i,
1419
                const char *root) {
1420

1421
        int r;
74✔
1422

1423
        assert(t);
74✔
1424
        assert(i);
74✔
1425
        assert(i->resource);
74✔
1426
        assert(t == container_of(i->resource, Transfer, source));
74✔
1427

1428
        if (t->temporary_path) {
74✔
1429
                assert(RESOURCE_IS_FILESYSTEM(t->target.type));
46✔
1430
                assert(t->final_path);
46✔
1431

1432
                r = install_file(AT_FDCWD, t->temporary_path,
138✔
1433
                                 AT_FDCWD, t->final_path,
1434
                                 INSTALL_REPLACE|
46✔
1435
                                 (t->install_read_only > 0 ? INSTALL_READ_ONLY : 0)|
92✔
1436
                                 (t->target.type == RESOURCE_REGULAR_FILE ? INSTALL_FSYNC_FULL : INSTALL_SYNCFS));
46✔
1437
                if (r < 0)
46✔
UNCOV
1438
                        return log_error_errno(r, "Failed to move '%s' into place: %m", t->final_path);
×
1439

1440
                log_info("Successfully installed '%s' (%s) as '%s' (%s).",
46✔
1441
                         i->path,
1442
                         resource_type_to_string(i->resource->type),
1443
                         t->final_path,
1444
                         resource_type_to_string(t->target.type));
1445

1446
                t->temporary_path = mfree(t->temporary_path);
46✔
1447
        }
1448

1449
        if (t->partition_change != 0) {
74✔
1450
                assert(t->target.type == RESOURCE_PARTITION);
28✔
1451

1452
                r = patch_partition(
56✔
1453
                                t->target.path,
28✔
1454
                                &t->partition_info,
28✔
1455
                                t->partition_change);
1456
                if (r < 0)
28✔
1457
                        return r;
1458

1459
                log_info("Successfully installed '%s' (%s) as '%s' (%s).",
28✔
1460
                         i->path,
1461
                         resource_type_to_string(i->resource->type),
1462
                         t->partition_info.device,
1463
                         resource_type_to_string(t->target.type));
1464
        }
1465

1466
        if (t->current_symlink) {
74✔
1467
                _cleanup_free_ char *buf = NULL, *parent = NULL, *relative = NULL, *resolved = NULL;
14✔
1468
                const char *link_path, *link_target;
14✔
1469
                bool resolve_link_path = false;
14✔
1470

1471
                if (RESOURCE_IS_FILESYSTEM(t->target.type)) {
14✔
1472

1473
                        assert(t->target.path);
14✔
1474

1475
                        if (path_is_absolute(t->current_symlink)) {
14✔
1476
                                link_path = t->current_symlink;
1477
                                resolve_link_path = true;
1478
                        } else {
UNCOV
1479
                                buf = path_make_absolute(t->current_symlink, t->target.path);
×
1480
                                if (!buf)
×
1481
                                        return log_oom();
×
1482

1483
                                link_path = buf;
1484
                        }
1485

1486
                        link_target = t->final_path;
14✔
1487

UNCOV
1488
                } else if (t->target.type == RESOURCE_PARTITION) {
×
1489

UNCOV
1490
                        assert(path_is_absolute(t->current_symlink));
×
1491

UNCOV
1492
                        link_path = t->current_symlink;
×
1493
                        link_target = t->partition_info.device;
×
1494

UNCOV
1495
                        resolve_link_path = true;
×
1496
                } else
UNCOV
1497
                        assert_not_reached();
×
1498

1499
                if (resolve_link_path && root) {
14✔
UNCOV
1500
                        r = chase(link_path, root, CHASE_PREFIX_ROOT|CHASE_NONEXISTENT, &resolved, NULL);
×
1501
                        if (r < 0)
×
1502
                                return log_error_errno(r, "Failed to resolve current symlink path '%s': %m", link_path);
×
1503

UNCOV
1504
                        link_path = resolved;
×
1505
                }
1506

1507
                if (link_target) {
14✔
1508
                        r = path_extract_directory(link_path, &parent);
14✔
1509
                        if (r < 0)
14✔
UNCOV
1510
                                return log_error_errno(r, "Failed to extract directory of target path '%s': %m", link_path);
×
1511

1512
                        r = path_make_relative(parent, link_target, &relative);
14✔
1513
                        if (r < 0)
14✔
UNCOV
1514
                                return log_error_errno(r, "Failed to make symlink path '%s' relative to '%s': %m", link_target, parent);
×
1515

1516
                        r = symlink_atomic(relative, link_path);
14✔
1517
                        if (r < 0)
14✔
UNCOV
1518
                                return log_error_errno(r, "Failed to update current symlink '%s' %s '%s': %m",
×
1519
                                                       link_path,
1520
                                                       glyph(GLYPH_ARROW_RIGHT),
1521
                                                       relative);
1522

1523
                        log_info("Updated symlink '%s' %s '%s'.",
14✔
1524
                                 link_path, glyph(GLYPH_ARROW_RIGHT), relative);
1525
                }
1526
        }
1527

1528
        return 0;
1529
}
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