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

systemd / systemd / 19979552133

05 Dec 2025 05:29PM UTC coverage: 72.765% (-0.2%) from 72.917%
19979552133

push

github

yuwata
udev-rules: use the right variable

We carefully prepare a copy of a local buffer to save in device cache
and then save the buffer there instead... This leads to abort in free()
on exit (also, copied is leaked).

Reproducer:
 # udevadm test /sys/block/sr0

Follow-up-for: a9559ebcb

Fixes: https://bugzilla.redhat.com/show_bug.cgi?id=2406118

0 of 1 new or added line in 1 file covered. (0.0%)

1564 existing lines in 65 files now uncovered.

309707 of 425625 relevant lines covered (72.77%)

1149816.14 hits per line

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

66.19
/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
#include <unistd.h>
6

7
#include "sd-id128.h"
8

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

101
                .partition_info = PARTITION_INFO_NULL,
102

103
                .context = ctx,
104
        };
105

106
        return t;
556✔
107
}
108

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

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

125
        assert(rvalue);
×
126

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

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

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

144
        return 0;
145
}
146

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

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

163
        assert(rvalue);
×
164

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

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

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

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

196
        assert(rvalue);
×
197

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

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

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

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

220
        return 0;
221
}
222

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

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

239
        assert(rvalue);
92✔
240

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

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

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

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

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

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

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

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

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

292
        return 0;
293
}
294

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

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

310
        assert(rvalue);
1,112✔
311

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

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

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

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

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

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

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

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

364
        assert(rvalue);
1,112✔
365

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

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

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

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

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

389
static DEFINE_CONFIG_PARSE_ENUM_WITH_DEFAULT(config_parse_resource_path_relto, path_relative_to, PathRelativeTo,
276✔
390
                                             PATH_RELATIVE_TO_ROOT);
391

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

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

407
        assert(rvalue);
188✔
408

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

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

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

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

435
        assert(rvalue);
×
436

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

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

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

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

463
        assert(rvalue);
×
464

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

665
        return 0;
666
}
667

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

673
        int r;
556✔
674

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

680
        assert(t);
556✔
681

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

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

690
        return 0;
691
}
692

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

697
        assert(t);
102✔
698

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

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

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

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

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

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

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

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

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

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

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

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

750
        assert(t);
102✔
751

752
        transfer_remove_temporary(t);
102✔
753

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

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

771
        if (t->target.type == RESOURCE_PARTITION && space != UINT64_MAX) {
102✔
772
                _cleanup_free_ char *patterns = NULL;
32✔
773
                uint64_t rm, remain;
32✔
774

775
                patterns = strv_join(t->target.patterns, "|");
32✔
776
                if (!patterns)
32✔
UNCOV
777
                        (void) log_oom_debug();
×
778

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

782
                if (t->target.n_empty + t->target.n_instances < 2)
32✔
783
                        return log_error_errno(SYNTHETIC_ERRNO(ENOSPC),
×
784
                                               "Partition table has less than two partition slots of the right type " SD_ID128_UUID_FORMAT_STR " (%s)%s%s%s, refusing.",
785
                                               SD_ID128_FORMAT_VAL(t->target.partition_type.uuid),
786
                                               gpt_partition_type_uuid_to_string(t->target.partition_type.uuid),
787
                                               !isempty(patterns) ? " and matching the expected pattern '" : "",
788
                                               strempty(patterns),
789
                                               !isempty(patterns) ? "'" : "");
790
                if (space > t->target.n_empty + t->target.n_instances)
32✔
UNCOV
791
                        return log_error_errno(SYNTHETIC_ERRNO(ENOSPC),
×
792
                                               "Partition table does not have enough partition slots of right type " SD_ID128_UUID_FORMAT_STR " (%s)%s%s%s for operation.",
793
                                               SD_ID128_FORMAT_VAL(t->target.partition_type.uuid),
794
                                               gpt_partition_type_uuid_to_string(t->target.partition_type.uuid),
795
                                               !isempty(patterns) ? " and matching the expected pattern '" : "",
796
                                               strempty(patterns),
797
                                               !isempty(patterns) ? "'" : "");
798
                if (space == t->target.n_empty + t->target.n_instances)
32✔
UNCOV
799
                        return log_error_errno(SYNTHETIC_ERRNO(ENOSPC),
×
800
                                               "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.",
801
                                               SD_ID128_FORMAT_VAL(t->target.partition_type.uuid),
802
                                               gpt_partition_type_uuid_to_string(t->target.partition_type.uuid));
803

804
                rm = LESS_BY(space, t->target.n_empty);
32✔
805
                remain = LESS_BY(t->target.n_instances, rm);
32✔
806
                limit = MIN(limit, remain);
32✔
807
        }
808

809
        while (t->target.n_instances > limit) {
152✔
810
                Instance *oldest;
50✔
811
                size_t p = t->target.n_instances - 1;
50✔
812

813
                for (;;) {
50✔
814
                        oldest = t->target.instances[p];
50✔
815
                        assert(oldest);
50✔
816

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

UNCOV
822
                        log_debug("Version '%s' is protected, not removing.", oldest->metadata.version);
×
UNCOV
823
                        if (p == 0) {
×
824
                                oldest = NULL;
825
                                break;
826
                        }
827

UNCOV
828
                        p--;
×
829
                }
830

831
                if (!oldest) /* Nothing more to remove */
50✔
832
                        break;
833

834
                assert(oldest->resource);
50✔
835

836
                log_info("%s Removing %s '%s' (%s).",
100✔
837
                         glyph(GLYPH_RECYCLING),
838
                         space == UINT64_MAX ? "disabled" : "old",
839
                         oldest->path,
840
                         resource_type_to_string(oldest->resource->type));
841

842
                switch (t->target.type) {
50✔
843

844
                case RESOURCE_REGULAR_FILE:
30✔
845
                case RESOURCE_DIRECTORY:
846
                case RESOURCE_SUBVOLUME:
847
                        r = rm_rf(oldest->path, REMOVE_ROOT|REMOVE_PHYSICAL|REMOVE_SUBVOLUME|REMOVE_MISSING_OK|REMOVE_CHMOD);
30✔
848
                        if (r < 0 && r != -ENOENT)
30✔
UNCOV
849
                                return log_error_errno(r, "Failed to make room, deleting '%s' failed: %m", oldest->path);
×
850

851
                        (void) rmdir_parents(oldest->path, t->target.path);
30✔
852

853
                        break;
30✔
854

855
                case RESOURCE_PARTITION: {
20✔
856
                        PartitionInfo pinfo = oldest->partition_info;
20✔
857

858
                        /* label "_empty" means "no contents" for our purposes */
859
                        pinfo.label = (char*) "_empty";
20✔
860

861
                        r = patch_partition(t->target.path, &pinfo, PARTITION_LABEL);
20✔
862
                        if (r < 0)
20✔
UNCOV
863
                                return r;
×
864

865
                        t->target.n_empty++;
20✔
866
                        break;
20✔
867
                }
868

UNCOV
869
                default:
×
UNCOV
870
                        assert_not_reached();
×
871
                }
872

873
                instance_free(oldest);
50✔
874
                memmove(t->target.instances + p, t->target.instances + p + 1, (t->target.n_instances - p - 1) * sizeof(Instance*));
50✔
875
                t->target.n_instances--;
50✔
876

877
                count++;
50✔
878
        }
879

880
        return count;
881
}
882

883
static void compile_pattern_fields(
74✔
884
                const Transfer *t,
885
                const Instance *i,
886
                InstanceMetadata *ret) {
887

888
        assert(t);
74✔
889
        assert(i);
74✔
890
        assert(ret);
74✔
891

892
        *ret = (InstanceMetadata) {
148✔
893
                .version = i->metadata.version,
74✔
894

895
                /* We generally prefer explicitly configured values for the transfer over those automatically
896
                 * derived from the source instance. Also, if the source is a tar archive, then let's not
897
                 * patch mtime/mode and use the one embedded in the tar file */
898
                .partition_uuid = t->partition_uuid_set ? t->partition_uuid : i->metadata.partition_uuid,
74✔
899
                .partition_uuid_set = t->partition_uuid_set || i->metadata.partition_uuid_set,
74✔
900
                .partition_flags = t->partition_flags_set ? t->partition_flags : i->metadata.partition_flags,
74✔
901
                .partition_flags_set = t->partition_flags_set || i->metadata.partition_flags_set,
74✔
902
                .mtime = RESOURCE_IS_TAR(i->resource->type) ? USEC_INFINITY : i->metadata.mtime,
74✔
903
                .mode = t->mode != MODE_INVALID ? t->mode : (RESOURCE_IS_TAR(i->resource->type) ? MODE_INVALID : i->metadata.mode),
74✔
904
                .size = i->metadata.size,
74✔
905
                .tries_done = t->tries_done != UINT64_MAX ? t->tries_done :
74✔
906
                              i->metadata.tries_done != UINT64_MAX ? i->metadata.tries_done : 0,
60✔
907
                .tries_left = t->tries_left != UINT64_MAX ? t->tries_left :
74✔
908
                              i->metadata.tries_left != UINT64_MAX ? i->metadata.tries_left : 3,
60✔
909
                .no_auto = t->no_auto >= 0 ? t->no_auto : i->metadata.no_auto,
74✔
910
                .read_only = t->read_only >= 0 ? t->read_only : i->metadata.read_only,
74✔
911
                .growfs = t->growfs >= 0 ? t->growfs : i->metadata.growfs,
74✔
912
                .sha256sum_set = i->metadata.sha256sum_set,
74✔
913
        };
914

915
        memcpy(ret->sha256sum, i->metadata.sha256sum, sizeof(ret->sha256sum));
74✔
916
}
74✔
917

918
typedef struct CalloutContext {
919
        const Transfer *transfer;
920
        const Instance *instance;
921
        TransferProgress callback;
922
        PidRef pid;
923
        const char *name;
924
        int helper_errno;
925
        void* userdata;
926
} CalloutContext;
927

928
static CalloutContext *callout_context_free(CalloutContext *ctx) {
74✔
929
        if (!ctx)
74✔
930
                return NULL;
931

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

935
        return mfree(ctx);
74✔
936
}
937

938
DEFINE_TRIVIAL_CLEANUP_FUNC(CalloutContext*, callout_context_free);
148✔
939

940
static int callout_context_new(const Transfer *t, const Instance *i, TransferProgress cb,
74✔
941
                               const char *name, void* userdata, CalloutContext **ret) {
942
        _cleanup_(callout_context_freep) CalloutContext *ctx = NULL;
74✔
943

944
        assert(t);
74✔
945
        assert(i);
74✔
946
        assert(cb);
74✔
947

948
        ctx = new(CalloutContext, 1);
74✔
949
        if (!ctx)
74✔
950
                return -ENOMEM;
951

952
        *ctx = (CalloutContext) {
74✔
953
                .transfer = t,
954
                .instance = i,
955
                .callback = cb,
956
                .pid = PIDREF_NULL,
957
                .name = name,
958
                .userdata = userdata,
959
        };
960

961
        *ret = TAKE_PTR(ctx);
74✔
962
        return 0;
74✔
963
}
964

965
static int helper_on_exit(sd_event_source *s, const siginfo_t *si, void *userdata) {
74✔
966
        CalloutContext *ctx = ASSERT_PTR(userdata);
74✔
967
        int r;
74✔
968

969
        assert(s);
74✔
970
        assert(si);
74✔
971
        assert(ctx);
74✔
972

973
        if (si->si_code == CLD_EXITED) {
74✔
974
                if (si->si_status == EXIT_SUCCESS) {
74✔
975
                        r = 0;
74✔
976
                        log_debug("%s succeeded.", ctx->name);
74✔
UNCOV
977
                } else if (ctx->helper_errno != 0) {
×
978
                        r = -ctx->helper_errno;
×
UNCOV
979
                        log_error_errno(r, "%s failed with exit status %i: %m", ctx->name, si->si_status);
×
980
                } else {
UNCOV
981
                        r = -EPROTO;
×
UNCOV
982
                        log_error("%s failed with exit status %i.", ctx->name, si->si_status);
×
983
                }
984
        } else {
UNCOV
985
                r = -EPROTO;
×
UNCOV
986
                if (IN_SET(si->si_code, CLD_KILLED, CLD_DUMPED))
×
UNCOV
987
                        log_error("%s terminated by signal %s.", ctx->name, signal_to_string(si->si_status));
×
988
                else
UNCOV
989
                        log_error("%s failed due to unknown reason.", ctx->name);
×
990
        }
991

992
        return sd_event_exit(sd_event_source_get_event(s), r);
74✔
993
}
994

995
static int helper_on_notify(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
139✔
996
        CalloutContext *ctx = ASSERT_PTR(userdata);
139✔
997
        int r;
139✔
998

999
        assert(fd >= 0);
139✔
1000

1001
        _cleanup_free_ char *buf = NULL;
139✔
1002
        _cleanup_(pidref_done) PidRef sender_pid = PIDREF_NULL;
139✔
1003
        r = notify_recv(fd, &buf, /* ret_ucred= */ NULL, &sender_pid);
139✔
1004
        if (r == -EAGAIN)
139✔
1005
                return 0;
1006
        if (r < 0)
139✔
1007
                return r;
1008

1009
        if (!pidref_equal(&ctx->pid, &sender_pid)) {
139✔
1010
                log_warning("Got notification datagram from unexpected peer, ignoring.");
×
1011
                return 0;
×
1012
        }
1013

1014
        char *errno_str = find_line_startswith(buf, "ERRNO=");
139✔
1015
        if (errno_str) {
139✔
UNCOV
1016
                truncate_nl(errno_str);
×
UNCOV
1017
                r = parse_errno(errno_str);
×
UNCOV
1018
                if (r < 0)
×
UNCOV
1019
                        log_warning_errno(r, "Got invalid errno value '%s', ignoring: %m", errno_str);
×
1020
                else {
1021
                        ctx->helper_errno = r;
×
UNCOV
1022
                        log_debug_errno(r, "Got errno from callout: %i (%m)", r);
×
1023
                }
1024
        }
1025

1026
        char *progress_str = find_line_startswith(buf, "X_IMPORT_PROGRESS=");
139✔
1027
        if (progress_str) {
139✔
1028
                truncate_nl(progress_str);
65✔
1029

1030
                int progress = parse_percent(progress_str);
65✔
1031
                if (progress < 0)
65✔
UNCOV
1032
                        log_warning("Got invalid percent value '%s', ignoring.", progress_str);
×
1033
                else {
1034
                        r = ctx->callback(ctx->transfer, ctx->instance, progress);
65✔
1035
                        if (r < 0)
65✔
UNCOV
1036
                                return r;
×
1037
                }
1038
        }
1039

1040
        return 0;
1041
}
1042

1043
static int run_callout(
74✔
1044
                const char *name,
1045
                char *cmdline[],
1046
                const Transfer *transfer,
1047
                const Instance *instance,
1048
                TransferProgress callback,
1049
                void *userdata) {
1050

1051
        int r;
74✔
1052

1053
        assert(name);
74✔
1054
        assert(cmdline);
74✔
1055
        assert(cmdline[0]);
74✔
1056

UNCOV
1057
        _cleanup_(callout_context_freep) CalloutContext *ctx = NULL;
×
1058
        r = callout_context_new(transfer, instance, callback, name, userdata, &ctx);
74✔
1059
        if (r < 0)
74✔
UNCOV
1060
                return log_oom();
×
1061

1062
        _cleanup_(sd_event_unrefp) sd_event *event = NULL;
74✔
1063
        r = sd_event_new(&event);
74✔
1064
        if (r < 0)
74✔
UNCOV
1065
                return log_error_errno(r, "Failed to create event: %m");
×
1066

1067
        /* Kill the helper & return an error if we get interrupted by a signal */
1068
        r = sd_event_add_signal(event, NULL, SIGINT | SD_EVENT_SIGNAL_PROCMASK, NULL, INT_TO_PTR(-ECANCELED));
74✔
1069
        if (r < 0)
74✔
UNCOV
1070
                return log_error_errno(r, "Failed to register signal to event: %m");
×
1071
        r = sd_event_add_signal(event, NULL, SIGTERM | SD_EVENT_SIGNAL_PROCMASK, NULL, INT_TO_PTR(-ECANCELED));
74✔
1072
        if (r < 0)
74✔
UNCOV
1073
                return log_error_errno(r, "Failed to register signal to event: %m");
×
1074

1075
        _cleanup_free_ char *bind_name = NULL;
74✔
1076
        r = notify_socket_prepare(
74✔
1077
                        event,
1078
                        SD_EVENT_PRIORITY_NORMAL - 5,
1079
                        helper_on_notify,
1080
                        ctx,
1081
                        &bind_name);
1082
        if (r < 0)
74✔
UNCOV
1083
                return log_error_errno(r, "Failed to prepare notify socket: %m");
×
1084

1085
        r = pidref_safe_fork(ctx->name, FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGTERM|FORK_LOG, &ctx->pid);
74✔
1086
        if (r < 0)
148✔
UNCOV
1087
                return log_error_errno(r, "Failed to fork process %s: %m", ctx->name);
×
1088
        if (r == 0) {
148✔
1089
                /* Child */
1090
                if (setenv("NOTIFY_SOCKET", bind_name, 1) < 0) {
74✔
UNCOV
1091
                        log_error_errno(errno, "setenv() failed: %m");
×
1092
                        _exit(EXIT_FAILURE);
×
1093
                }
1094
                r = invoke_callout_binary(cmdline[0], (char *const*) cmdline);
74✔
UNCOV
1095
                log_error_errno(r, "Failed to execute %s tool: %m", cmdline[0]);
×
1096
                _exit(EXIT_FAILURE);
×
1097
        }
1098

1099
        /* Quit the loop w/ when child process exits */
1100
        _cleanup_(sd_event_source_unrefp) sd_event_source *exit_source = NULL;
74✔
1101
        r = event_add_child_pidref(event, &exit_source, &ctx->pid, WEXITED, helper_on_exit, ctx);
74✔
1102
        if (r < 0)
74✔
UNCOV
1103
                return log_error_errno(r, "Failed to add child process to event loop: %m");
×
1104

1105
        r = sd_event_source_set_child_process_own(exit_source, true);
74✔
1106
        if (r < 0)
74✔
UNCOV
1107
                return log_error_errno(r, "Failed to take ownership of child process: %m");
×
1108

1109
        /* Process events until the helper quits */
1110
        return sd_event_loop(event);
74✔
1111
}
1112

1113
int transfer_acquire_instance(Transfer *t, Instance *i, TransferProgress cb, void *userdata) {
74✔
1114
        _cleanup_free_ char *formatted_pattern = NULL, *digest = NULL;
74✔
1115
        char offset[DECIMAL_STR_MAX(uint64_t)+1], max_size[DECIMAL_STR_MAX(uint64_t)+1];
74✔
1116
        const char *where = NULL;
74✔
1117
        InstanceMetadata f;
74✔
1118
        Instance *existing;
74✔
1119
        int r;
74✔
1120

1121
        assert(t);
74✔
1122
        assert(i);
74✔
1123
        assert(i->resource == &t->source);
74✔
1124
        assert(cb);
74✔
1125

1126
        /* Does this instance already exist in the target? Then we don't need to acquire anything */
1127
        existing = resource_find_instance(&t->target, i->metadata.version);
74✔
1128
        if (existing) {
74✔
UNCOV
1129
                log_info("No need to acquire '%s', already installed.", i->path);
×
1130
                return 0;
×
1131
        }
1132

1133
        assert(!t->final_path);
74✔
1134
        assert(!t->temporary_path);
74✔
1135
        assert(!strv_isempty(t->target.patterns));
74✔
1136

1137
        /* Format the target name using the first pattern specified */
1138
        compile_pattern_fields(t, i, &f);
74✔
1139
        r = pattern_format(t->target.patterns[0], &f, &formatted_pattern);
74✔
1140
        if (r < 0)
74✔
UNCOV
1141
                return log_error_errno(r, "Failed to format target pattern: %m");
×
1142

1143
        if (RESOURCE_IS_FILESYSTEM(t->target.type)) {
74✔
1144

1145
                if (!path_is_safe(formatted_pattern))
46✔
UNCOV
1146
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Formatted pattern is not suitable as file name, refusing: %s", formatted_pattern);
×
1147

1148
                t->final_path = path_join(t->target.path, formatted_pattern);
46✔
1149
                if (!t->final_path)
46✔
UNCOV
1150
                        return log_oom();
×
1151

1152
                r = mkdir_parents(t->final_path, 0755);
46✔
1153
                if (r < 0)
46✔
UNCOV
1154
                        return log_error_errno(r, "Cannot create target directory: %m");
×
1155

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

1160
                where = t->final_path;
46✔
1161
        }
1162

1163
        if (t->target.type == RESOURCE_PARTITION) {
74✔
1164
                r = gpt_partition_label_valid(formatted_pattern);
28✔
1165
                if (r < 0)
28✔
UNCOV
1166
                        return log_error_errno(r, "Failed to determine if formatted pattern is suitable as GPT partition label: %s", formatted_pattern);
×
1167
                if (!r)
28✔
UNCOV
1168
                        return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Formatted pattern is not suitable as GPT partition label, refusing: %s", formatted_pattern);
×
1169

1170
                r = find_suitable_partition(
28✔
1171
                                t->target.path,
28✔
1172
                                i->metadata.size,
1173
                                t->target.partition_type_set ? &t->target.partition_type.uuid : NULL,
28✔
1174
                                &t->partition_info);
1175
                if (r < 0)
28✔
1176
                        return r;
1177

1178
                xsprintf(offset, "%" PRIu64, t->partition_info.start);
28✔
1179
                xsprintf(max_size, "%" PRIu64, t->partition_info.size);
28✔
1180

1181
                where = t->partition_info.device;
28✔
1182
        }
1183

1184
        assert(where);
74✔
1185

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

1188
        if (RESOURCE_IS_URL(i->resource->type)) {
74✔
1189
                /* For URL sources we require the SHA256 sum to be known so that we can validate the
1190
                 * download. */
1191

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

1195
                digest = hexmem(i->metadata.sha256sum, sizeof(i->metadata.sha256sum));
8✔
1196
                if (!digest)
8✔
UNCOV
1197
                        return log_oom();
×
1198
        }
1199

1200
        switch (i->resource->type) { /* Source */
74✔
1201

1202
        case RESOURCE_REGULAR_FILE:
56✔
1203

1204
                switch (t->target.type) { /* Target */
56✔
1205

1206
                case RESOURCE_REGULAR_FILE:
32✔
1207

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

1213
                        r = run_callout("(sd-import-raw)",
64✔
1214
                                        STRV_MAKE(
32✔
1215
                                               SYSTEMD_IMPORT_PATH,
1216
                                               "raw",
1217
                                               "--direct",          /* just copy/unpack the specified file, don't do anything else */
1218
                                               arg_sync ? "--sync=yes" : "--sync=no",
1219
                                               i->path,
1220
                                               t->temporary_path),
1221
                                        t, i, cb, userdata);
1222
                        break;
56✔
1223

1224
                case RESOURCE_PARTITION:
24✔
1225

1226
                        /* regular file → partition */
1227

1228
                        r = run_callout("(sd-import-raw)",
48✔
1229
                                        STRV_MAKE(
24✔
1230
                                               SYSTEMD_IMPORT_PATH,
1231
                                               "raw",
1232
                                               "--direct",          /* just copy/unpack the specified file, don't do anything else */
1233
                                               "--offset", offset,
1234
                                               "--size-max", max_size,
1235
                                               arg_sync ? "--sync=yes" : "--sync=no",
1236
                                               i->path,
1237
                                               t->target.path),
1238
                                        t, i, cb, userdata);
1239
                        break;
1240

UNCOV
1241
                default:
×
UNCOV
1242
                        assert_not_reached();
×
1243
                }
1244

1245
                break;
56✔
1246

1247
        case RESOURCE_DIRECTORY:
10✔
1248
        case RESOURCE_SUBVOLUME:
1249
                assert(IN_SET(t->target.type, RESOURCE_DIRECTORY, RESOURCE_SUBVOLUME));
10✔
1250

1251
                /* directory/subvolume → directory/subvolume */
1252

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

UNCOV
1265
        case RESOURCE_TAR:
×
UNCOV
1266
                assert(IN_SET(t->target.type, RESOURCE_DIRECTORY, RESOURCE_SUBVOLUME));
×
1267

1268
                /* tar → directory/subvolume */
1269

UNCOV
1270
                r = run_callout("(sd-import-tar)",
×
UNCOV
1271
                                STRV_MAKE(
×
1272
                                       SYSTEMD_IMPORT_PATH,
1273
                                       "tar",
1274
                                       "--direct",          /* just untar the specified file, don't do anything else */
1275
                                       arg_sync ? "--sync=yes" : "--sync=no",
1276
                                       t->target.type == RESOURCE_SUBVOLUME ? "--btrfs-subvol=yes" : "--btrfs-subvol=no",
1277
                                       i->path,
1278
                                       t->temporary_path),
1279
                                t, i, cb, userdata);
1280
                break;
1281

1282
        case RESOURCE_URL_FILE:
4✔
1283

1284
                switch (t->target.type) {
4✔
1285

UNCOV
1286
                case RESOURCE_REGULAR_FILE:
×
1287

1288
                        /* url file → regular file */
1289

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

1302
                case RESOURCE_PARTITION:
4✔
1303

1304
                        /* url file → partition */
1305

1306
                        r = run_callout("(sd-pull-raw)",
8✔
1307
                                        STRV_MAKE(
4✔
1308
                                               SYSTEMD_PULL_PATH,
1309
                                               "raw",
1310
                                               "--direct",              /* just download the specified URL, don't download anything else */
1311
                                               "--verify", digest,      /* validate by explicit SHA256 sum */
1312
                                               "--offset", offset,
1313
                                               "--size-max", max_size,
1314
                                               arg_sync ? "--sync=yes" : "--sync=no",
1315
                                               i->path,
1316
                                               t->target.path),
1317
                                        t, i, cb, userdata);
1318
                        break;
1319

UNCOV
1320
                default:
×
UNCOV
1321
                        assert_not_reached();
×
1322
                }
1323

1324
                break;
4✔
1325

1326
        case RESOURCE_URL_TAR:
4✔
1327
                assert(IN_SET(t->target.type, RESOURCE_DIRECTORY, RESOURCE_SUBVOLUME));
4✔
1328

1329
                r = run_callout("(sd-pull-tar)",
8✔
1330
                                STRV_MAKE(
8✔
1331
                                       SYSTEMD_PULL_PATH,
1332
                                       "tar",
1333
                                       "--direct",          /* just download the specified URL, don't download anything else */
1334
                                       "--verify", digest,  /* validate by explicit SHA256 sum */
1335
                                       t->target.type == RESOURCE_SUBVOLUME ? "--btrfs-subvol=yes" : "--btrfs-subvol=no",
1336
                                       arg_sync ? "--sync=yes" : "--sync=no",
1337
                                       i->path,
1338
                                       t->temporary_path),
1339
                                t, i, cb, userdata);
1340
                break;
1341

UNCOV
1342
        default:
×
UNCOV
1343
                assert_not_reached();
×
1344
        }
1345
        if (r < 0)
74✔
1346
                return r;
1347

1348
        if (RESOURCE_IS_FILESYSTEM(t->target.type)) {
74✔
1349
                bool need_sync = false;
46✔
1350
                assert(t->temporary_path);
46✔
1351

1352
                /* Apply file attributes if set */
1353
                if (f.mtime != USEC_INFINITY) {
46✔
1354
                        struct timespec ts;
42✔
1355

1356
                        timespec_store(&ts, f.mtime);
42✔
1357

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

1361
                        need_sync = true;
42✔
1362
                }
1363

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

1372
                        need_sync = true;
1373
                }
1374

1375
                /* Synchronize */
1376
                if (arg_sync && need_sync) {
46✔
1377
                        if (t->target.type == RESOURCE_REGULAR_FILE)
42✔
1378
                                r = fsync_path_and_parent_at(AT_FDCWD, t->temporary_path);
32✔
1379
                        else {
1380
                                assert(IN_SET(t->target.type, RESOURCE_DIRECTORY, RESOURCE_SUBVOLUME));
10✔
1381
                                r = syncfs_path(AT_FDCWD, t->temporary_path);
10✔
1382
                        }
1383
                        if (r < 0)
42✔
1384
                                return log_error_errno(r, "Failed to synchronize file system backing '%s': %m", t->temporary_path);
×
1385
                }
1386

1387
                t->install_read_only = f.read_only;
46✔
1388
        }
1389

1390
        if (t->target.type == RESOURCE_PARTITION) {
74✔
1391
                free_and_replace(t->partition_info.label, formatted_pattern);
28✔
1392
                t->partition_change = PARTITION_LABEL;
28✔
1393

1394
                if (f.partition_uuid_set) {
28✔
1395
                        t->partition_info.uuid = f.partition_uuid;
×
UNCOV
1396
                        t->partition_change |= PARTITION_UUID;
×
1397
                }
1398

1399
                if (f.partition_flags_set) {
28✔
1400
                        t->partition_info.flags = f.partition_flags;
×
UNCOV
1401
                        t->partition_change |= PARTITION_FLAGS;
×
1402
                }
1403

1404
                if (f.no_auto >= 0) {
28✔
1405
                        t->partition_info.no_auto = f.no_auto;
×
UNCOV
1406
                        t->partition_change |= PARTITION_NO_AUTO;
×
1407
                }
1408

1409
                if (f.read_only >= 0) {
28✔
UNCOV
1410
                        t->partition_info.read_only = f.read_only;
×
UNCOV
1411
                        t->partition_change |= PARTITION_READ_ONLY;
×
1412
                }
1413

1414
                if (f.growfs >= 0) {
28✔
UNCOV
1415
                        t->partition_info.growfs = f.growfs;
×
UNCOV
1416
                        t->partition_change |= PARTITION_GROWFS;
×
1417
                }
1418
        }
1419

1420
        /* For regular file cases the only step left is to install the file in place, which install_file()
1421
         * will do via rename(). For partition cases the only step left is to update the partition table,
1422
         * which is done at the same place. */
1423

1424
        log_info("Successfully acquired '%s'.", i->path);
74✔
1425
        return 0;
1426
}
1427

1428
int transfer_install_instance(
74✔
1429
                Transfer *t,
1430
                Instance *i,
1431
                const char *root) {
1432

1433
        int r;
74✔
1434

1435
        assert(t);
74✔
1436
        assert(i);
74✔
1437
        assert(i->resource);
74✔
1438
        assert(t == container_of(i->resource, Transfer, source));
74✔
1439

1440
        if (t->temporary_path) {
74✔
1441
                assert(RESOURCE_IS_FILESYSTEM(t->target.type));
46✔
1442
                assert(t->final_path);
46✔
1443

1444
                r = install_file(AT_FDCWD, t->temporary_path,
138✔
1445
                                 AT_FDCWD, t->final_path,
1446
                                 INSTALL_REPLACE|
46✔
1447
                                 (t->install_read_only > 0 ? INSTALL_READ_ONLY : 0)|
92✔
1448
                                 (t->target.type == RESOURCE_REGULAR_FILE ? INSTALL_FSYNC_FULL : INSTALL_SYNCFS));
46✔
1449
                if (r < 0)
46✔
UNCOV
1450
                        return log_error_errno(r, "Failed to move '%s' into place: %m", t->final_path);
×
1451

1452
                log_info("Successfully installed '%s' (%s) as '%s' (%s).",
46✔
1453
                         i->path,
1454
                         resource_type_to_string(i->resource->type),
1455
                         t->final_path,
1456
                         resource_type_to_string(t->target.type));
1457

1458
                t->temporary_path = mfree(t->temporary_path);
46✔
1459
        }
1460

1461
        if (t->partition_change != 0) {
74✔
1462
                assert(t->target.type == RESOURCE_PARTITION);
28✔
1463

1464
                r = patch_partition(
56✔
1465
                                t->target.path,
28✔
1466
                                &t->partition_info,
28✔
1467
                                t->partition_change);
1468
                if (r < 0)
28✔
1469
                        return r;
1470

1471
                log_info("Successfully installed '%s' (%s) as '%s' (%s).",
28✔
1472
                         i->path,
1473
                         resource_type_to_string(i->resource->type),
1474
                         t->partition_info.device,
1475
                         resource_type_to_string(t->target.type));
1476
        }
1477

1478
        if (t->current_symlink) {
74✔
1479
                _cleanup_free_ char *buf = NULL, *parent = NULL, *relative = NULL, *resolved = NULL;
14✔
1480
                const char *link_path, *link_target;
14✔
1481
                bool resolve_link_path = false;
14✔
1482

1483
                if (RESOURCE_IS_FILESYSTEM(t->target.type)) {
14✔
1484

1485
                        assert(t->target.path);
14✔
1486

1487
                        if (path_is_absolute(t->current_symlink)) {
14✔
1488
                                link_path = t->current_symlink;
1489
                                resolve_link_path = true;
1490
                        } else {
1491
                                buf = path_make_absolute(t->current_symlink, t->target.path);
×
UNCOV
1492
                                if (!buf)
×
1493
                                        return log_oom();
×
1494

1495
                                link_path = buf;
1496
                        }
1497

1498
                        link_target = t->final_path;
14✔
1499

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

1502
                        assert(path_is_absolute(t->current_symlink));
×
1503

UNCOV
1504
                        link_path = t->current_symlink;
×
1505
                        link_target = t->partition_info.device;
×
1506

UNCOV
1507
                        resolve_link_path = true;
×
1508
                } else
UNCOV
1509
                        assert_not_reached();
×
1510

1511
                if (resolve_link_path && root) {
14✔
UNCOV
1512
                        r = chase(link_path, root, CHASE_PREFIX_ROOT|CHASE_NONEXISTENT|CHASE_TRIGGER_AUTOFS, &resolved, NULL);
×
UNCOV
1513
                        if (r < 0)
×
UNCOV
1514
                                return log_error_errno(r, "Failed to resolve current symlink path '%s': %m", link_path);
×
1515

UNCOV
1516
                        link_path = resolved;
×
1517
                }
1518

1519
                if (link_target) {
14✔
1520
                        r = path_extract_directory(link_path, &parent);
14✔
1521
                        if (r < 0)
14✔
UNCOV
1522
                                return log_error_errno(r, "Failed to extract directory of target path '%s': %m", link_path);
×
1523

1524
                        r = path_make_relative(parent, link_target, &relative);
14✔
1525
                        if (r < 0)
14✔
UNCOV
1526
                                return log_error_errno(r, "Failed to make symlink path '%s' relative to '%s': %m", link_target, parent);
×
1527

1528
                        r = symlink_atomic(relative, link_path);
14✔
1529
                        if (r < 0)
14✔
UNCOV
1530
                                return log_error_errno(r, "Failed to update current symlink '%s' %s '%s': %m",
×
1531
                                                       link_path,
1532
                                                       glyph(GLYPH_ARROW_RIGHT),
1533
                                                       relative);
1534

1535
                        log_info("Updated symlink '%s' %s '%s'.",
14✔
1536
                                 link_path, glyph(GLYPH_ARROW_RIGHT), relative);
1537
                }
1538
        }
1539

1540
        return 0;
1541
}
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