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

systemd / systemd / 15057632786

15 May 2025 09:01PM UTC coverage: 72.267% (+0.02%) from 72.244%
15057632786

push

github

bluca
man: document how to hook stuff into system wakeup

Fixes: #6364

298523 of 413084 relevant lines covered (72.27%)

738132.88 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 "sd-id128.h"
4

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

42
/* Default value for InstancesMax= for fs object targets */
43
#define DEFAULT_FILE_INSTANCES_MAX 3
44

45
Transfer* transfer_free(Transfer *t) {
556✔
46
        if (!t)
556✔
47
                return NULL;
48

49
        t->temporary_path = rm_rf_subvolume_and_free(t->temporary_path);
556✔
50

51
        free(t->id);
556✔
52

53
        free(t->min_version);
556✔
54
        strv_free(t->protected_versions);
556✔
55
        free(t->current_symlink);
556✔
56
        free(t->final_path);
556✔
57

58
        strv_free(t->features);
556✔
59
        strv_free(t->requisite_features);
556✔
60

61
        strv_free(t->changelog);
556✔
62
        strv_free(t->appstream);
556✔
63

64
        partition_info_destroy(&t->partition_info);
556✔
65

66
        resource_destroy(&t->source);
556✔
67
        resource_destroy(&t->target);
556✔
68

69
        return mfree(t);
556✔
70
}
71

72
Transfer* transfer_new(Context *ctx) {
556✔
73
        Transfer *t;
556✔
74

75
        t = new(Transfer, 1);
556✔
76
        if (!t)
556✔
77
                return NULL;
78

79
        *t = (Transfer) {
556✔
80
                .source.type = _RESOURCE_TYPE_INVALID,
81
                .target.type = _RESOURCE_TYPE_INVALID,
82
                .remove_temporary = true,
83
                .mode = MODE_INVALID,
84
                .tries_left = UINT64_MAX,
85
                .tries_done = UINT64_MAX,
86
                .verify = true,
87

88
                /* the three flags, as configured by the user */
89
                .no_auto = -1,
90
                .read_only = -1,
91
                .growfs = -1,
92

93
                /* the read only flag, as ultimately determined */
94
                .install_read_only = -1,
95

96
                .partition_info = PARTITION_INFO_NULL,
97

98
                .context = ctx,
99
        };
100

101
        return t;
556✔
102
}
103

104
static int config_parse_protect_version(
×
105
                const char *unit,
106
                const char *filename,
107
                unsigned line,
108
                const char *section,
109
                unsigned section_line,
110
                const char *lvalue,
111
                int ltype,
112
                const char *rvalue,
113
                void *data,
114
                void *userdata) {
115

116
        _cleanup_free_ char *resolved = NULL;
×
117
        char ***protected_versions = ASSERT_PTR(data);
×
118
        int r;
×
119

120
        assert(rvalue);
×
121

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

129
        if (!version_is_valid(resolved))  {
×
130
                log_syntax(unit, LOG_WARNING, filename, line, 0,
×
131
                           "ProtectVersion= string is not valid, ignoring: %s", resolved);
132
                return 0;
×
133
        }
134

135
        r = strv_extend(protected_versions, resolved);
×
136
        if (r < 0)
×
137
                return log_oom();
×
138

139
        return 0;
140
}
141

142
static int config_parse_min_version(
×
143
                const char *unit,
144
                const char *filename,
145
                unsigned line,
146
                const char *section,
147
                unsigned section_line,
148
                const char *lvalue,
149
                int ltype,
150
                const char *rvalue,
151
                void *data,
152
                void *userdata) {
153

154
        _cleanup_free_ char *resolved = NULL;
×
155
        char **version = ASSERT_PTR(data);
×
156
        int r;
×
157

158
        assert(rvalue);
×
159

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

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

173
        return free_and_replace(*version, resolved);
×
174
}
175

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

191
        assert(rvalue);
×
192

193
        if (isempty(rvalue)) {
×
194
                *s = strv_free(*s);
×
195
                return 0;
×
196
        }
197

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

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

211
        r = strv_push(s, TAKE_PTR(resolved));
×
212
        if (r < 0)
×
213
                return log_oom();
×
214

215
        return 0;
216
}
217

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

230
        _cleanup_free_ char *resolved = NULL;
92✔
231
        char **current_symlink = ASSERT_PTR(data);
92✔
232
        int r;
92✔
233

234
        assert(rvalue);
92✔
235

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

243
        r = path_simplify_and_warn(resolved, 0, unit, filename, line, lvalue);
92✔
244
        if (r < 0)
92✔
245
                return 0;
246

247
        return free_and_replace(*current_symlink, resolved);
92✔
248
}
249

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

262
        uint64_t *instances_max = data, i;
368✔
263
        int r;
368✔
264

265
        assert(rvalue);
368✔
266
        assert(data);
368✔
267

268
        if (isempty(rvalue)) {
368✔
269
                *instances_max = 0; /* Revert to default logic, see transfer_read_definition() */
×
270
                return 0;
×
271
        }
272

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

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

287
        return 0;
288
}
289

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

302
        char ***patterns = ASSERT_PTR(data);
1,112✔
303
        int r;
1,112✔
304

305
        assert(rvalue);
1,112✔
306

307
        if (isempty(rvalue)) {
1,112✔
308
                *patterns = strv_free(*patterns);
×
309
                return 0;
×
310
        }
311

312
        for (;;) {
3,704✔
313
                _cleanup_free_ char *word = NULL, *resolved = NULL;
1,296✔
314

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

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

331
                if (!pattern_valid(resolved))
1,296✔
332
                        return log_syntax(unit, LOG_ERR, filename, line, SYNTHETIC_ERRNO(EINVAL),
×
333
                                          "MatchPattern= string is not valid, refusing: %s", resolved);
334

335
                r = strv_consume(patterns, TAKE_PTR(resolved));
1,296✔
336
                if (r < 0)
1,296✔
337
                        return log_oom();
×
338
        }
339

340
        strv_uniq(*patterns);
1,112✔
341
        return 0;
1,112✔
342
}
343

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

359
        assert(rvalue);
1,112✔
360

361
        if (streq(rvalue, "auto")) {
1,112✔
362
                rr->path_auto = true;
×
363
                rr->path = mfree(rr->path);
×
364
                return 0;
×
365
        }
366

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

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

378
        rr->path_auto = false;
1,112✔
379
        return free_and_replace(rr->path, resolved);
1,112✔
380
}
381

382
static DEFINE_CONFIG_PARSE_ENUM(config_parse_resource_type, resource_type, ResourceType);
1,112✔
383

384
static DEFINE_CONFIG_PARSE_ENUM_WITH_DEFAULT(config_parse_resource_path_relto, path_relative_to, PathRelativeTo,
552✔
385
                                             PATH_RELATIVE_TO_ROOT);
386

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

399
        Resource *rr = ASSERT_PTR(data);
188✔
400
        int r;
188✔
401

402
        assert(rvalue);
188✔
403

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

411
        rr->partition_type_set = true;
188✔
412
        return 0;
188✔
413
}
414

415
static int config_parse_partition_uuid(
×
416
                const char *unit,
417
                const char *filename,
418
                unsigned line,
419
                const char *section,
420
                unsigned section_line,
421
                const char *lvalue,
422
                int ltype,
423
                const char *rvalue,
424
                void *data,
425
                void *userdata) {
426

427
        Transfer *t = ASSERT_PTR(data);
×
428
        int r;
×
429

430
        assert(rvalue);
×
431

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

439
        t->partition_uuid_set = true;
×
440
        return 0;
×
441
}
442

443
static int config_parse_partition_flags(
×
444
                const char *unit,
445
                const char *filename,
446
                unsigned line,
447
                const char *section,
448
                unsigned section_line,
449
                const char *lvalue,
450
                int ltype,
451
                const char *rvalue,
452
                void *data,
453
                void *userdata) {
454

455
        Transfer *t = ASSERT_PTR(data);
×
456
        int r;
×
457

458
        assert(rvalue);
×
459

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

467
        t->partition_flags_set = true;
×
468
        return 0;
×
469
}
470

471
static bool transfer_decide_if_enabled(Transfer *t, Hashmap *known_features) {
556✔
472
        assert(t);
556✔
473

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

481
        /* No features defined -> transfer implicitly enabled */
482
        if (strv_isempty(t->features))
556✔
483
                return true;
484

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

492
        /* All listed features disabled -> transfer disabled */
493
        return false;
494
}
495

496
int transfer_read_definition(Transfer *t, const char *path, const char **dirs, Hashmap *known_features) {
556✔
497
        assert(t);
556✔
498

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

530
        _cleanup_free_ char *filename = NULL;
556✔
531
        char *e;
556✔
532
        int r;
556✔
533

534
        assert(path);
556✔
535
        assert(dirs);
556✔
536

537
        r = path_extract_filename(path, &filename);
556✔
538
        if (r < 0)
556✔
539
                return log_error_errno(r, "Failed to extract filename from path '%s': %m", path);
×
540

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

557
        e = ASSERT_PTR(endswith(filename, ".transfer") ?: endswith(filename, ".conf"));
556✔
558
        *e = 0; /* Remove the file extension */
556✔
559
        t->id = TAKE_PTR(filename);
556✔
560

561
        t->enabled = transfer_decide_if_enabled(t, known_features);
556✔
562

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

567
        if (t->target.type < 0) {
556✔
568
                switch (t->source.type) {
×
569

570
                case RESOURCE_URL_FILE:
×
571
                case RESOURCE_REGULAR_FILE:
572
                        t->target.type =
×
573
                                t->target.path && path_startswith(t->target.path, "/dev/") ?
×
574
                                RESOURCE_PARTITION : RESOURCE_REGULAR_FILE;
×
575
                        break;
×
576

577
                case RESOURCE_URL_TAR:
×
578
                case RESOURCE_TAR:
579
                case RESOURCE_DIRECTORY:
580
                        t->target.type = RESOURCE_DIRECTORY;
×
581
                        break;
×
582

583
                case RESOURCE_SUBVOLUME:
×
584
                        t->target.type = RESOURCE_SUBVOLUME;
×
585
                        break;
×
586

587
                default:
×
588
                        assert_not_reached();
×
589
                }
590
        }
591

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

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

604
        if (!t->source.path && !t->source.path_auto)
556✔
605
                return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
×
606
                                  "Source specification lacks Path=.");
607

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

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

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

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

631
        if (strv_isempty(t->source.patterns))
556✔
632
                return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
×
633
                                  "Source specification lacks MatchPattern=.");
634

635
        if (!t->target.path && !t->target.path_auto)
556✔
636
                return log_syntax(NULL, LOG_ERR, path, 1, SYNTHETIC_ERRNO(EINVAL),
×
637
                                  "Target specification lacks Path= field.");
638

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

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

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

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

660
        return 0;
661
}
662

663
int transfer_resolve_paths(
556✔
664
                Transfer *t,
665
                const char *root,
666
                const char *node) {
667

668
        int r;
556✔
669

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

675
        assert(t);
556✔
676

677
        r = resource_resolve_path(&t->source, root, arg_transfer_source, node);
556✔
678
        if (r < 0)
556✔
679
                return r;
680

681
        r = resource_resolve_path(&t->target, root, /*relative_to_directory=*/ NULL, node);
556✔
682
        if (r < 0)
556✔
683
                return r;
×
684

685
        return 0;
686
}
687

688
static void transfer_remove_temporary(Transfer *t) {
102✔
689
        _cleanup_closedir_ DIR *d = NULL;
102✔
690
        int r;
102✔
691

692
        assert(t);
102✔
693

694
        if (!t->remove_temporary)
102✔
695
                return;
696

697
        if (!IN_SET(t->target.type, RESOURCE_REGULAR_FILE, RESOURCE_DIRECTORY, RESOURCE_SUBVOLUME))
102✔
698
                return;
699

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

702
        d = opendir(t->target.path);
70✔
703
        if (!d) {
70✔
704
                if (errno == ENOENT)
×
705
                        return;
706

707
                log_debug_errno(errno, "Failed to open target directory '%s', ignoring: %m", t->target.path);
×
708
                return;
×
709
        }
710

711
        for (;;) {
266✔
712
                struct dirent *de;
266✔
713

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

722
                if (!startswith(de->d_name, ".#"))
196✔
723
                        continue;
196✔
724

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

733
                log_debug("Removed temporary resource instance '%s/%s'.", t->target.path, de->d_name);
×
734
        }
735
}
736

737
int transfer_vacuum(
102✔
738
                Transfer *t,
739
                uint64_t space,
740
                const char *extra_protected_version) {
741

742
        uint64_t instances_max, limit;
102✔
743
        int r, count = 0;
102✔
744

745
        assert(t);
102✔
746

747
        transfer_remove_temporary(t);
102✔
748

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

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

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

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

772
                if (t->target.n_empty + t->target.n_instances < 2)
32✔
773
                        return log_error_errno(SYNTHETIC_ERRNO(ENOSPC),
×
774
                                               "Partition table has less than two partition slots of the right type " SD_ID128_UUID_FORMAT_STR " (%s), refusing.",
775
                                               SD_ID128_FORMAT_VAL(t->target.partition_type.uuid),
776
                                               gpt_partition_type_uuid_to_string(t->target.partition_type.uuid));
777
                if (space > t->target.n_empty + t->target.n_instances)
32✔
778
                        return log_error_errno(SYNTHETIC_ERRNO(ENOSPC),
×
779
                                               "Partition table does not have enough partition slots of right type " SD_ID128_UUID_FORMAT_STR " (%s) for operation.",
780
                                               SD_ID128_FORMAT_VAL(t->target.partition_type.uuid),
781
                                               gpt_partition_type_uuid_to_string(t->target.partition_type.uuid));
782
                if (space == t->target.n_empty + t->target.n_instances)
32✔
783
                        return log_error_errno(SYNTHETIC_ERRNO(ENOSPC),
×
784
                                               "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.",
785
                                               SD_ID128_FORMAT_VAL(t->target.partition_type.uuid),
786
                                               gpt_partition_type_uuid_to_string(t->target.partition_type.uuid));
787

788
                rm = LESS_BY(space, t->target.n_empty);
32✔
789
                remain = LESS_BY(t->target.n_instances, rm);
32✔
790
                limit = MIN(limit, remain);
32✔
791
        }
792

793
        while (t->target.n_instances > limit) {
152✔
794
                Instance *oldest;
50✔
795
                size_t p = t->target.n_instances - 1;
50✔
796

797
                for (;;) {
50✔
798
                        oldest = t->target.instances[p];
50✔
799
                        assert(oldest);
50✔
800

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

806
                        log_debug("Version '%s' is protected, not removing.", oldest->metadata.version);
×
807
                        if (p == 0) {
×
808
                                oldest = NULL;
809
                                break;
810
                        }
811

812
                        p--;
×
813
                }
814

815
                if (!oldest) /* Nothing more to remove */
50✔
816
                        break;
817

818
                assert(oldest->resource);
50✔
819

820
                log_info("%s Removing %s '%s' (%s).",
100✔
821
                         glyph(GLYPH_RECYCLING),
822
                         space == UINT64_MAX ? "disabled" : "old",
823
                         oldest->path,
824
                         resource_type_to_string(oldest->resource->type));
825

826
                switch (t->target.type) {
50✔
827

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

835
                        (void) rmdir_parents(oldest->path, t->target.path);
30✔
836

837
                        break;
30✔
838

839
                case RESOURCE_PARTITION: {
20✔
840
                        PartitionInfo pinfo = oldest->partition_info;
20✔
841

842
                        /* label "_empty" means "no contents" for our purposes */
843
                        pinfo.label = (char*) "_empty";
20✔
844

845
                        r = patch_partition(t->target.path, &pinfo, PARTITION_LABEL);
20✔
846
                        if (r < 0)
20✔
847
                                return r;
×
848

849
                        t->target.n_empty++;
20✔
850
                        break;
20✔
851
                }
852

853
                default:
×
854
                        assert_not_reached();
×
855
                }
856

857
                instance_free(oldest);
50✔
858
                memmove(t->target.instances + p, t->target.instances + p + 1, (t->target.n_instances - p - 1) * sizeof(Instance*));
50✔
859
                t->target.n_instances--;
50✔
860

861
                count++;
50✔
862
        }
863

864
        return count;
865
}
866

867
static void compile_pattern_fields(
74✔
868
                const Transfer *t,
869
                const Instance *i,
870
                InstanceMetadata *ret) {
871

872
        assert(t);
74✔
873
        assert(i);
74✔
874
        assert(ret);
74✔
875

876
        *ret = (InstanceMetadata) {
148✔
877
                .version = i->metadata.version,
74✔
878

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

899
        memcpy(ret->sha256sum, i->metadata.sha256sum, sizeof(ret->sha256sum));
74✔
900
}
74✔
901

902
typedef struct CalloutContext {
903
        const Transfer *transfer;
904
        const Instance *instance;
905
        TransferProgress callback;
906
        PidRef pid;
907
        const char *name;
908
        int helper_errno;
909
        void* userdata;
910
} CalloutContext;
911

912
static CalloutContext *callout_context_free(CalloutContext *ctx) {
74✔
913
        if (!ctx)
74✔
914
                return NULL;
915

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

919
        return mfree(ctx);
74✔
920
}
921

922
DEFINE_TRIVIAL_CLEANUP_FUNC(CalloutContext*, callout_context_free);
148✔
923

924
static int callout_context_new(const Transfer *t, const Instance *i, TransferProgress cb,
74✔
925
                               const char *name, void* userdata, CalloutContext **ret) {
926
        _cleanup_(callout_context_freep) CalloutContext *ctx = NULL;
74✔
927

928
        assert(t);
74✔
929
        assert(i);
74✔
930
        assert(cb);
74✔
931

932
        ctx = new(CalloutContext, 1);
74✔
933
        if (!ctx)
74✔
934
                return -ENOMEM;
935

936
        *ctx = (CalloutContext) {
74✔
937
                .transfer = t,
938
                .instance = i,
939
                .callback = cb,
940
                .pid = PIDREF_NULL,
941
                .name = name,
942
                .userdata = userdata,
943
        };
944

945
        *ret = TAKE_PTR(ctx);
74✔
946
        return 0;
74✔
947
}
948

949
static int helper_on_exit(sd_event_source *s, const siginfo_t *si, void *userdata) {
74✔
950
        CalloutContext *ctx = ASSERT_PTR(userdata);
74✔
951
        int r;
74✔
952

953
        assert(s);
74✔
954
        assert(si);
74✔
955
        assert(ctx);
74✔
956

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

976
        return sd_event_exit(sd_event_source_get_event(s), r);
74✔
977
}
978

979
static int helper_on_notify(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
144✔
980
        CalloutContext *ctx = ASSERT_PTR(userdata);
144✔
981
        int r;
144✔
982

983
        assert(fd >= 0);
144✔
984

985
        _cleanup_free_ char *buf = NULL;
144✔
986
        _cleanup_(pidref_done) PidRef sender_pid = PIDREF_NULL;
144✔
987
        r = notify_recv(fd, &buf, /* ret_ucred= */ NULL, &sender_pid);
144✔
988
        if (r == -EAGAIN)
144✔
989
                return 0;
990
        if (r < 0)
144✔
991
                return r;
992

993
        if (!pidref_equal(&ctx->pid, &sender_pid)) {
144✔
994
                log_warning("Got notification datagram from unexpected peer, ignoring.");
×
995
                return 0;
×
996
        }
997

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

1010
        char *progress_str = find_line_startswith(buf, "X_IMPORT_PROGRESS=");
144✔
1011
        if (progress_str) {
144✔
1012
                truncate_nl(progress_str);
70✔
1013

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

1024
        return 0;
1025
}
1026

1027
static int run_callout(
74✔
1028
                const char *name,
1029
                char *cmdline[],
1030
                const Transfer *transfer,
1031
                const Instance *instance,
1032
                TransferProgress callback,
1033
                void *userdata) {
1034

1035
        int r;
74✔
1036

1037
        assert(name);
74✔
1038
        assert(cmdline);
74✔
1039
        assert(cmdline[0]);
74✔
1040

1041
        _cleanup_(callout_context_freep) CalloutContext *ctx = NULL;
×
1042
        r = callout_context_new(transfer, instance, callback, name, userdata, &ctx);
74✔
1043
        if (r < 0)
74✔
1044
                return log_oom();
×
1045

1046
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
74✔
1047
        r = sd_event_new(&event);
74✔
1048
        if (r < 0)
74✔
1049
                return log_error_errno(r, "Failed to create event: %m");
×
1050

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

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

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

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

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

1094
        /* Process events until the helper quits */
1095
        return sd_event_loop(event);
74✔
1096
}
1097

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

1106
        assert(t);
74✔
1107
        assert(i);
74✔
1108
        assert(i->resource == &t->source);
74✔
1109
        assert(cb);
74✔
1110

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

1118
        assert(!t->final_path);
74✔
1119
        assert(!t->temporary_path);
74✔
1120
        assert(!strv_isempty(t->target.patterns));
74✔
1121

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

1128
        if (RESOURCE_IS_FILESYSTEM(t->target.type)) {
74✔
1129

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

1133
                t->final_path = path_join(t->target.path, formatted_pattern);
46✔
1134
                if (!t->final_path)
46✔
1135
                        return log_oom();
×
1136

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

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

1145
                where = t->final_path;
46✔
1146
        }
1147

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

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

1163
                xsprintf(offset, "%" PRIu64, t->partition_info.start);
28✔
1164
                xsprintf(max_size, "%" PRIu64, t->partition_info.size);
28✔
1165

1166
                where = t->partition_info.device;
28✔
1167
        }
1168

1169
        assert(where);
74✔
1170

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

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

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

1180
                digest = hexmem(i->metadata.sha256sum, sizeof(i->metadata.sha256sum));
8✔
1181
                if (!digest)
8✔
1182
                        return log_oom();
×
1183
        }
1184

1185
        switch (i->resource->type) { /* Source */
74✔
1186

1187
        case RESOURCE_REGULAR_FILE:
56✔
1188

1189
                switch (t->target.type) { /* Target */
56✔
1190

1191
                case RESOURCE_REGULAR_FILE:
32✔
1192

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

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

1209
                case RESOURCE_PARTITION:
24✔
1210

1211
                        /* regular file → partition */
1212

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

1226
                default:
×
1227
                        assert_not_reached();
×
1228
                }
1229

1230
                break;
56✔
1231

1232
        case RESOURCE_DIRECTORY:
10✔
1233
        case RESOURCE_SUBVOLUME:
1234
                assert(IN_SET(t->target.type, RESOURCE_DIRECTORY, RESOURCE_SUBVOLUME));
10✔
1235

1236
                /* directory/subvolume → directory/subvolume */
1237

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

1250
        case RESOURCE_TAR:
×
1251
                assert(IN_SET(t->target.type, RESOURCE_DIRECTORY, RESOURCE_SUBVOLUME));
×
1252

1253
                /* tar → directory/subvolume */
1254

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

1267
        case RESOURCE_URL_FILE:
4✔
1268

1269
                switch (t->target.type) {
4✔
1270

1271
                case RESOURCE_REGULAR_FILE:
×
1272

1273
                        /* url file → regular file */
1274

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

1287
                case RESOURCE_PARTITION:
4✔
1288

1289
                        /* url file → partition */
1290

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

1305
                default:
×
1306
                        assert_not_reached();
×
1307
                }
1308

1309
                break;
4✔
1310

1311
        case RESOURCE_URL_TAR:
4✔
1312
                assert(IN_SET(t->target.type, RESOURCE_DIRECTORY, RESOURCE_SUBVOLUME));
4✔
1313

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

1327
        default:
×
1328
                assert_not_reached();
×
1329
        }
1330
        if (r < 0)
74✔
1331
                return r;
1332

1333
        if (RESOURCE_IS_FILESYSTEM(t->target.type)) {
74✔
1334
                bool need_sync = false;
46✔
1335
                assert(t->temporary_path);
46✔
1336

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

1341
                        timespec_store(&ts, f.mtime);
42✔
1342

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

1346
                        need_sync = true;
42✔
1347
                }
1348

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

1357
                        need_sync = true;
1358
                }
1359

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

1372
                t->install_read_only = f.read_only;
46✔
1373
        }
1374

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

1379
                if (f.partition_uuid_set) {
28✔
1380
                        t->partition_info.uuid = f.partition_uuid;
×
1381
                        t->partition_change |= PARTITION_UUID;
×
1382
                }
1383

1384
                if (f.partition_flags_set) {
28✔
1385
                        t->partition_info.flags = f.partition_flags;
×
1386
                        t->partition_change |= PARTITION_FLAGS;
×
1387
                }
1388

1389
                if (f.no_auto >= 0) {
28✔
1390
                        t->partition_info.no_auto = f.no_auto;
×
1391
                        t->partition_change |= PARTITION_NO_AUTO;
×
1392
                }
1393

1394
                if (f.read_only >= 0) {
28✔
1395
                        t->partition_info.read_only = f.read_only;
×
1396
                        t->partition_change |= PARTITION_READ_ONLY;
×
1397
                }
1398

1399
                if (f.growfs >= 0) {
28✔
1400
                        t->partition_info.growfs = f.growfs;
×
1401
                        t->partition_change |= PARTITION_GROWFS;
×
1402
                }
1403
        }
1404

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

1409
        log_info("Successfully acquired '%s'.", i->path);
74✔
1410
        return 0;
1411
}
1412

1413
int transfer_install_instance(
74✔
1414
                Transfer *t,
1415
                Instance *i,
1416
                const char *root) {
1417

1418
        int r;
74✔
1419

1420
        assert(t);
74✔
1421
        assert(i);
74✔
1422
        assert(i->resource);
74✔
1423
        assert(t == container_of(i->resource, Transfer, source));
74✔
1424

1425
        if (t->temporary_path) {
74✔
1426
                assert(RESOURCE_IS_FILESYSTEM(t->target.type));
46✔
1427
                assert(t->final_path);
46✔
1428

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

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

1443
                t->temporary_path = mfree(t->temporary_path);
46✔
1444
        }
1445

1446
        if (t->partition_change != 0) {
74✔
1447
                assert(t->target.type == RESOURCE_PARTITION);
28✔
1448

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

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

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

1468
                if (RESOURCE_IS_FILESYSTEM(t->target.type)) {
14✔
1469

1470
                        assert(t->target.path);
14✔
1471

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

1480
                                link_path = buf;
1481
                        }
1482

1483
                        link_target = t->final_path;
14✔
1484

1485
                } else if (t->target.type == RESOURCE_PARTITION) {
×
1486

1487
                        assert(path_is_absolute(t->current_symlink));
×
1488

1489
                        link_path = t->current_symlink;
×
1490
                        link_target = t->partition_info.device;
×
1491

1492
                        resolve_link_path = true;
×
1493
                } else
1494
                        assert_not_reached();
×
1495

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

1501
                        link_path = resolved;
×
1502
                }
1503

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

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

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

1520
                        log_info("Updated symlink '%s' %s '%s'.",
14✔
1521
                                 link_path, glyph(GLYPH_ARROW_RIGHT), relative);
1522
                }
1523
        }
1524

1525
        return 0;
1526
}
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