summaryrefslogtreecommitdiffstats
path: root/src/coredump/coredump.c
blob: a67d425c14ee90ad84366ec767db7638d966d93e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
/* SPDX-License-Identifier: LGPL-2.1-or-later */

#include <errno.h>
#include <stdio.h>
#include <sys/prctl.h>
#include <sys/statvfs.h>
#include <sys/auxv.h>
#include <sys/xattr.h>
#include <unistd.h>

#include "sd-daemon.h"
#include "sd-journal.h"
#include "sd-login.h"
#include "sd-messages.h"

#include "acl-util.h"
#include "alloc-util.h"
#include "bus-error.h"
#include "capability-util.h"
#include "cgroup-util.h"
#include "compress.h"
#include "conf-parser.h"
#include "copy.h"
#include "coredump-util.h"
#include "coredump-vacuum.h"
#include "dirent-util.h"
#include "elf-util.h"
#include "escape.h"
#include "fd-util.h"
#include "fileio.h"
#include "fs-util.h"
#include "iovec-util.h"
#include "journal-importer.h"
#include "journal-send.h"
#include "log.h"
#include "macro.h"
#include "main-func.h"
#include "memory-util.h"
#include "memstream-util.h"
#include "mkdir-label.h"
#include "namespace-util.h"
#include "parse-util.h"
#include "path-util.h"
#include "process-util.h"
#include "signal-util.h"
#include "socket-util.h"
#include "special.h"
#include "stat-util.h"
#include "string-table.h"
#include "string-util.h"
#include "strv.h"
#include "sync-util.h"
#include "tmpfile-util.h"
#include "uid-alloc-range.h"
#include "user-util.h"

/* The maximum size up to which we process coredumps. We use 1G on 32-bit systems, and 32G on 64-bit systems */
#if __SIZEOF_POINTER__ == 4
#define PROCESS_SIZE_MAX ((uint64_t) (1LLU*1024LLU*1024LLU*1024LLU))
#elif __SIZEOF_POINTER__ == 8
#define PROCESS_SIZE_MAX ((uint64_t) (32LLU*1024LLU*1024LLU*1024LLU))
#else
#error "Unexpected pointer size"
#endif

/* The maximum size up to which we leave the coredump around on disk */
#define EXTERNAL_SIZE_MAX PROCESS_SIZE_MAX

/* The maximum size up to which we store the coredump in the journal */
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
#define JOURNAL_SIZE_MAX ((size_t) (767LU*1024LU*1024LU))
#else
/* oss-fuzz limits memory usage. */
#define JOURNAL_SIZE_MAX ((size_t) (10LU*1024LU*1024LU))
#endif

/* When checking for available memory and setting lower limits, don't
 * go below 4MB for writing core files to storage. */
#define PROCESS_SIZE_MIN (4U*1024U*1024U)

/* Make sure to not make this larger than the maximum journal entry
 * size. See DATA_SIZE_MAX in journal-importer.h. */
assert_cc(JOURNAL_SIZE_MAX <= DATA_SIZE_MAX);

enum {
        /* We use these as array indexes for our process metadata cache.
         *
         * The first indices of the cache stores the same metadata as the ones passed by
         * the kernel via argv[], ie the strings array passed by the kernel according to
         * our pattern defined in /proc/sys/kernel/core_pattern (see man:core(5)). */

        META_ARGV_PID,          /* %P: as seen in the initial pid namespace */
        META_ARGV_UID,          /* %u: as seen in the initial user namespace */
        META_ARGV_GID,          /* %g: as seen in the initial user namespace */
        META_ARGV_SIGNAL,       /* %s: number of signal causing dump */
        META_ARGV_TIMESTAMP,    /* %t: time of dump, expressed as seconds since the Epoch (we expand this to μs granularity) */
        META_ARGV_RLIMIT,       /* %c: core file size soft resource limit */
        META_ARGV_HOSTNAME,     /* %h: hostname */
        _META_ARGV_MAX,

        /* The following indexes are cached for a couple of special fields we use (and
         * thereby need to be retrieved quickly) for naming coredump files, and attaching
         * xattrs. Unlike the previous ones they are retrieved from the runtime
         * environment. */

        META_COMM = _META_ARGV_MAX,
        _META_MANDATORY_MAX,

        /* The rest are similar to the previous ones except that we won't fail if one of
         * them is missing. */

        META_EXE = _META_MANDATORY_MAX,
        META_UNIT,
        META_PROC_AUXV,
        _META_MAX
};

static const char * const meta_field_names[_META_MAX] = {
        [META_ARGV_PID]       = "COREDUMP_PID=",
        [META_ARGV_UID]       = "COREDUMP_UID=",
        [META_ARGV_GID]       = "COREDUMP_GID=",
        [META_ARGV_SIGNAL]    = "COREDUMP_SIGNAL=",
        [META_ARGV_TIMESTAMP] = "COREDUMP_TIMESTAMP=",
        [META_ARGV_RLIMIT]    = "COREDUMP_RLIMIT=",
        [META_ARGV_HOSTNAME]  = "COREDUMP_HOSTNAME=",
        [META_COMM]           = "COREDUMP_COMM=",
        [META_EXE]            = "COREDUMP_EXE=",
        [META_UNIT]           = "COREDUMP_UNIT=",
        [META_PROC_AUXV]      = "COREDUMP_PROC_AUXV=",
};

typedef struct Context {
        const char *meta[_META_MAX];
        size_t meta_size[_META_MAX];
        pid_t pid;
        uid_t uid;
        gid_t gid;
        bool is_pid1;
        bool is_journald;
} Context;

typedef enum CoredumpStorage {
        COREDUMP_STORAGE_NONE,
        COREDUMP_STORAGE_EXTERNAL,
        COREDUMP_STORAGE_JOURNAL,
        _COREDUMP_STORAGE_MAX,
        _COREDUMP_STORAGE_INVALID = -EINVAL,
} CoredumpStorage;

static const char* const coredump_storage_table[_COREDUMP_STORAGE_MAX] = {
        [COREDUMP_STORAGE_NONE]     = "none",
        [COREDUMP_STORAGE_EXTERNAL] = "external",
        [COREDUMP_STORAGE_JOURNAL]  = "journal",
};

DEFINE_PRIVATE_STRING_TABLE_LOOKUP(coredump_storage, CoredumpStorage);
static DEFINE_CONFIG_PARSE_ENUM(config_parse_coredump_storage, coredump_storage, CoredumpStorage, "Failed to parse storage setting");

static CoredumpStorage arg_storage = COREDUMP_STORAGE_EXTERNAL;
static bool arg_compress = true;
static uint64_t arg_process_size_max = PROCESS_SIZE_MAX;
static uint64_t arg_external_size_max = EXTERNAL_SIZE_MAX;
static uint64_t arg_journal_size_max = JOURNAL_SIZE_MAX;
static uint64_t arg_keep_free = UINT64_MAX;
static uint64_t arg_max_use = UINT64_MAX;

static int parse_config(void) {
        static const ConfigTableItem items[] = {
                { "Coredump", "Storage",          config_parse_coredump_storage,     0, &arg_storage           },
                { "Coredump", "Compress",         config_parse_bool,                 0, &arg_compress          },
                { "Coredump", "ProcessSizeMax",   config_parse_iec_uint64,           0, &arg_process_size_max  },
                { "Coredump", "ExternalSizeMax",  config_parse_iec_uint64_infinity,  0, &arg_external_size_max },
                { "Coredump", "JournalSizeMax",   config_parse_iec_size,             0, &arg_journal_size_max  },
                { "Coredump", "KeepFree",         config_parse_iec_uint64,           0, &arg_keep_free         },
                { "Coredump", "MaxUse",           config_parse_iec_uint64,           0, &arg_max_use           },
                {}
        };

        int r;

        r = config_parse_config_file(
                        "coredump.conf",
                        "Coredump\0",
                        config_item_table_lookup,
                        items,
                        CONFIG_PARSE_WARN,
                        /* userdata= */ NULL);
        if (r < 0)
                return r;

        /* Let's make sure we fix up the maximum size we send to the journal here on the client side, for
         * efficiency reasons. journald wouldn't accept anything larger anyway. */
        if (arg_journal_size_max > JOURNAL_SIZE_MAX) {
                log_warning("JournalSizeMax= set to larger value (%s) than journald would accept (%s), lowering automatically.",
                            FORMAT_BYTES(arg_journal_size_max), FORMAT_BYTES(JOURNAL_SIZE_MAX));
                arg_journal_size_max = JOURNAL_SIZE_MAX;
        }

        return 0;
}

static uint64_t storage_size_max(void) {
        if (arg_storage == COREDUMP_STORAGE_EXTERNAL)
                return arg_external_size_max;
        if (arg_storage == COREDUMP_STORAGE_JOURNAL)
                return arg_journal_size_max;
        assert(arg_storage == COREDUMP_STORAGE_NONE);
        return 0;
}

static int fix_acl(int fd, uid_t uid, bool allow_user) {
        assert(fd >= 0);
        assert(uid_is_valid(uid));

#if HAVE_ACL
        int r;

        /* We don't allow users to read coredumps if the uid or capabilities were changed. */
        if (!allow_user)
                return 0;

        if (uid_is_system(uid) || uid_is_dynamic(uid) || uid == UID_NOBODY)
                return 0;

        /* Make sure normal users can read (but not write or delete) their own coredumps */
        r = fd_add_uid_acl_permission(fd, uid, ACL_READ);
        if (r < 0)
                return log_error_errno(r, "Failed to adjust ACL of the coredump: %m");
#endif

        return 0;
}

static int fix_xattr(int fd, const Context *context) {

        static const char * const xattrs[_META_MAX] = {
                [META_ARGV_PID]       = "user.coredump.pid",
                [META_ARGV_UID]       = "user.coredump.uid",
                [META_ARGV_GID]       = "user.coredump.gid",
                [META_ARGV_SIGNAL]    = "user.coredump.signal",
                [META_ARGV_TIMESTAMP] = "user.coredump.timestamp",
                [META_ARGV_RLIMIT]    = "user.coredump.rlimit",
                [META_ARGV_HOSTNAME]  = "user.coredump.hostname",
                [META_COMM]           = "user.coredump.comm",
                [META_EXE]            = "user.coredump.exe",
        };

        int r = 0;

        assert(fd >= 0);

        /* Attach some metadata to coredumps via extended attributes. Just because we can. */

        for (unsigned i = 0; i < _META_MAX; i++) {
                int k;

                if (isempty(context->meta[i]) || !xattrs[i])
                        continue;

                k = RET_NERRNO(fsetxattr(fd, xattrs[i], context->meta[i], strlen(context->meta[i]), XATTR_CREATE));
                RET_GATHER(r, k);
        }

        return r;
}

#define filename_escape(s) xescape((s), "./ ")

static const char *coredump_tmpfile_name(const char *s) {
        return s ?: "(unnamed temporary file)";
}

static int fix_permissions(
                int fd,
                const char *filename,
                const char *target,
                const Context *context,
                bool allow_user) {

        int r;

        assert(fd >= 0);
        assert(target);
        assert(context);

        /* Ignore errors on these */
        (void) fchmod(fd, 0640);
        (void) fix_acl(fd, context->uid, allow_user);
        (void) fix_xattr(fd, context);

        r = link_tmpfile(fd, filename, target, LINK_TMPFILE_SYNC);
        if (r < 0)
                return log_error_errno(r, "Failed to move coredump %s into place: %m", target);

        return 0;
}

static int maybe_remove_external_coredump(const char *filename, uint64_t size) {

        /* Returns 1 if might remove, 0 if will not remove, < 0 on error. */

        if (arg_storage == COREDUMP_STORAGE_EXTERNAL &&
            size <= arg_external_size_max)
                return 0;

        if (!filename)
                return 1;

        if (unlink(filename) < 0 && errno != ENOENT)
                return log_error_errno(errno, "Failed to unlink %s: %m", filename);

        return 1;
}

static int make_filename(const Context *context, char **ret) {
        _cleanup_free_ char *c = NULL, *u = NULL, *p = NULL, *t = NULL;
        sd_id128_t boot = {};
        int r;

        assert(context);

        c = filename_escape(context->meta[META_COMM]);
        if (!c)
                return -ENOMEM;

        u = filename_escape(context->meta[META_ARGV_UID]);
        if (!u)
                return -ENOMEM;

        r = sd_id128_get_boot(&boot);
        if (r < 0)
                return r;

        p = filename_escape(context->meta[META_ARGV_PID]);
        if (!p)
                return -ENOMEM;

        t = filename_escape(context->meta[META_ARGV_TIMESTAMP]);
        if (!t)
                return -ENOMEM;

        if (asprintf(ret,
                     "/var/lib/systemd/coredump/core.%s.%s." SD_ID128_FORMAT_STR ".%s.%s",
                     c,
                     u,
                     SD_ID128_FORMAT_VAL(boot),
                     p,
                     t) < 0)
                return -ENOMEM;

        return 0;
}

static int grant_user_access(int core_fd, const Context *context) {
        int at_secure = -1;
        uid_t uid = UID_INVALID, euid = UID_INVALID;
        uid_t gid = GID_INVALID, egid = GID_INVALID;
        int r;

        assert(core_fd >= 0);
        assert(context);

        if (!context->meta[META_PROC_AUXV])
                return log_warning_errno(SYNTHETIC_ERRNO(ENODATA), "No auxv data, not adjusting permissions.");

        uint8_t elf[EI_NIDENT];
        errno = 0;
        if (pread(core_fd, &elf, sizeof(elf), 0) != sizeof(elf))
                return log_warning_errno(errno_or_else(EIO),
                                         "Failed to pread from coredump fd: %s", STRERROR_OR_EOF(errno));

        if (elf[EI_MAG0] != ELFMAG0 ||
            elf[EI_MAG1] != ELFMAG1 ||
            elf[EI_MAG2] != ELFMAG2 ||
            elf[EI_MAG3] != ELFMAG3 ||
            elf[EI_VERSION] != EV_CURRENT)
                return log_info_errno(SYNTHETIC_ERRNO(EUCLEAN),
                                      "Core file does not have ELF header, not adjusting permissions.");
        if (!IN_SET(elf[EI_CLASS], ELFCLASS32, ELFCLASS64) ||
            !IN_SET(elf[EI_DATA], ELFDATA2LSB, ELFDATA2MSB))
                return log_info_errno(SYNTHETIC_ERRNO(EUCLEAN),
                                      "Core file has strange ELF class, not adjusting permissions.");

        if ((elf[EI_DATA] == ELFDATA2LSB) != (__BYTE_ORDER == __LITTLE_ENDIAN))
                return log_info_errno(SYNTHETIC_ERRNO(EUCLEAN),
                                      "Core file has non-native endianness, not adjusting permissions.");

        r = parse_auxv(LOG_WARNING,
                       /* elf_class= */ elf[EI_CLASS],
                       context->meta[META_PROC_AUXV],
                       context->meta_size[META_PROC_AUXV],
                       &at_secure, &uid, &euid, &gid, &egid);
        if (r < 0)
                return r;

        /* We allow access if we got all the data and at_secure is not set and
         * the uid/gid matches euid/egid. */
        bool ret =
                at_secure == 0 &&
                uid != UID_INVALID && euid != UID_INVALID && uid == euid &&
                gid != GID_INVALID && egid != GID_INVALID && gid == egid;
        log_debug("Will %s access (uid="UID_FMT " euid="UID_FMT " gid="GID_FMT " egid="GID_FMT " at_secure=%s)",
                  ret ? "permit" : "restrict",
                  uid, euid, gid, egid, yes_no(at_secure));
        return ret;
}

static int save_external_coredump(
                const Context *context,
                int input_fd,
                char **ret_filename,
                int *ret_node_fd,
                int *ret_data_fd,
                uint64_t *ret_size,
                uint64_t *ret_compressed_size,
                bool *ret_truncated) {

        _cleanup_(unlink_and_freep) char *tmp = NULL;
        _cleanup_free_ char *fn = NULL;
        _cleanup_close_ int fd = -EBADF;
        uint64_t rlimit, process_limit, max_size;
        bool truncated, storage_on_tmpfs;
        struct stat st;
        int r;

        assert(context);
        assert(ret_filename);
        assert(ret_node_fd);
        assert(ret_data_fd);
        assert(ret_size);
        assert(ret_compressed_size);
        assert(ret_truncated);

        r = safe_atou64(context->meta[META_ARGV_RLIMIT], &rlimit);
        if (r < 0)
                return log_error_errno(r, "Failed to parse resource limit '%s': %m",
                                       context->meta[META_ARGV_RLIMIT]);
        if (rlimit < page_size())
                /* Is coredumping disabled? Then don't bother saving/processing the
                 * coredump. Anything below PAGE_SIZE cannot give a readable coredump
                 * (the kernel uses ELF_EXEC_PAGESIZE which is not easily accessible, but
                 * is usually the same as PAGE_SIZE. */
                return log_info_errno(SYNTHETIC_ERRNO(EBADSLT),
                                      "Resource limits disable core dumping for process %s (%s).",
                                      context->meta[META_ARGV_PID], context->meta[META_COMM]);

        process_limit = MAX(arg_process_size_max, storage_size_max());
        if (process_limit == 0)
                return log_debug_errno(SYNTHETIC_ERRNO(EBADSLT),
                                       "Limits for coredump processing and storage are both 0, not dumping core.");

        /* Never store more than the process configured, or than we actually shall keep or process */
        max_size = MIN(rlimit, process_limit);

        r = make_filename(context, &fn);
        if (r < 0)
                return log_error_errno(r, "Failed to determine coredump file name: %m");

        (void) mkdir_parents_label(fn, 0755);

        fd = open_tmpfile_linkable(fn, O_RDWR|O_CLOEXEC, &tmp);
        if (fd < 0)
                return log_error_errno(fd, "Failed to create temporary file for coredump %s: %m", fn);

        /* If storage is on tmpfs, the kernel oomd might kill us if there's MemoryMax set on
         * the service or the slice it belongs to. This is common on low-resources systems,
         * to avoid crashing processes to take away too many system resources.
         * Check the cgroup settings, and set max_size to a bit less than half of the
         * available memory left to the process.
         * Then, attempt to write the core file uncompressed first - if the write gets
         * interrupted, we know we won't be able to write it all, so instead compress what
         * was written so far, delete the uncompressed truncated core, and then continue
         * compressing from STDIN. Given the compressed core cannot be larger than the
         * uncompressed one, and 1KB for metadata is accounted for in the calculation, we
         * should be able to at least store the full compressed core file. */

        storage_on_tmpfs = fd_is_temporary_fs(fd) > 0;
        if (storage_on_tmpfs && arg_compress) {
                _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
                uint64_t cgroup_limit = UINT64_MAX;
                struct statvfs sv;

                /* If we can't get the cgroup limit, just ignore it, but don't fail,
                 * try anyway with the config settings. */
                r = sd_bus_default_system(&bus);
                if (r < 0)
                        log_info_errno(r, "Failed to connect to system bus, skipping MemoryAvailable check: %m");
                else {
                        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;

                        r = sd_bus_get_property_trivial(
                                        bus,
                                        "org.freedesktop.systemd1",
                                        "/org/freedesktop/systemd1/unit/self",
                                        "org.freedesktop.systemd1.Service",
                                        "MemoryAvailable",
                                        &error,
                                        't', &cgroup_limit);
                        if (r < 0)
                                log_warning_errno(r,
                                                  "Failed to query MemoryAvailable for current unit, "
                                                  "falling back to static config settings: %s",
                                                  bus_error_message(&error, r));
                }

                max_size = MIN(cgroup_limit, max_size);
                max_size = LESS_BY(max_size, 1024U) / 2; /* Account for 1KB metadata overhead for compressing */
                max_size = MAX(PROCESS_SIZE_MIN, max_size); /* Impose a lower minimum */

                /* tmpfs might get full quickly, so check the available space too.
                 * But don't worry about errors here, failing to access the storage
                 * location will be better logged when writing to it. */
                if (fstatvfs(fd, &sv) >= 0)
                        max_size = MIN((uint64_t)sv.f_frsize * (uint64_t)sv.f_bfree, max_size);

                log_debug("Limiting core file size to %" PRIu64 " bytes due to cgroup memory limits.", max_size);
        }

        r = copy_bytes(input_fd, fd, max_size, 0);
        if (r < 0)
                return log_error_errno(r, "Cannot store coredump of %s (%s): %m",
                                context->meta[META_ARGV_PID], context->meta[META_COMM]);
        truncated = r == 1;

        bool allow_user = grant_user_access(fd, context) > 0;

#if HAVE_COMPRESSION
        if (arg_compress) {
                _cleanup_(unlink_and_freep) char *tmp_compressed = NULL;
                _cleanup_free_ char *fn_compressed = NULL;
                _cleanup_close_ int fd_compressed = -EBADF;
                uint64_t uncompressed_size = 0;

                if (lseek(fd, 0, SEEK_SET) < 0)
                        return log_error_errno(errno, "Failed to seek on coredump %s: %m", fn);

                fn_compressed = strjoin(fn, default_compression_extension());
                if (!fn_compressed)
                        return log_oom();

                fd_compressed = open_tmpfile_linkable(fn_compressed, O_RDWR|O_CLOEXEC, &tmp_compressed);
                if (fd_compressed < 0)
                        return log_error_errno(fd_compressed, "Failed to create temporary file for coredump %s: %m", fn_compressed);

                r = compress_stream(fd, fd_compressed, max_size, &uncompressed_size);
                if (r < 0)
                        return log_error_errno(r, "Failed to compress %s: %m", coredump_tmpfile_name(tmp_compressed));

                if (truncated && storage_on_tmpfs) {
                        uint64_t partial_uncompressed_size = 0;

                        /* Uncompressed write was truncated and we are writing to tmpfs: delete
                         * the uncompressed core, and compress the remaining part from STDIN. */

                        tmp = unlink_and_free(tmp);
                        fd = safe_close(fd);

                        r = compress_stream(input_fd, fd_compressed, max_size, &partial_uncompressed_size);
                        if (r < 0)
                                return log_error_errno(r, "Failed to compress %s: %m", coredump_tmpfile_name(tmp_compressed));
                        uncompressed_size += partial_uncompressed_size;
                }

                r = fix_permissions(fd_compressed, tmp_compressed, fn_compressed, context, allow_user);
                if (r < 0)
                        return r;

                if (fstat(fd_compressed, &st) < 0)
                        return log_error_errno(errno,
                                        "Failed to fstat core file %s: %m",
                                        coredump_tmpfile_name(tmp_compressed));

                *ret_filename = TAKE_PTR(fn_compressed);       /* compressed */
                *ret_node_fd = TAKE_FD(fd_compressed);         /* compressed */
                *ret_compressed_size = (uint64_t) st.st_size;  /* compressed */
                *ret_data_fd = TAKE_FD(fd);
                *ret_size = uncompressed_size;
                *ret_truncated = truncated;
                tmp_compressed = mfree(tmp_compressed);

                return 0;
        }
#endif

        if (truncated)
                log_struct(LOG_INFO,
                           LOG_MESSAGE("Core file was truncated to %"PRIu64" bytes.", max_size),
                           "SIZE_LIMIT=%"PRIu64, max_size,
                           "MESSAGE_ID=" SD_MESSAGE_TRUNCATED_CORE_STR);

        r = fix_permissions(fd, tmp, fn, context, allow_user);
        if (r < 0)
                return log_error_errno(r, "Failed to fix permissions and finalize coredump %s into %s: %m", coredump_tmpfile_name(tmp), fn);

        if (fstat(fd, &st) < 0)
                return log_error_errno(errno, "Failed to fstat core file %s: %m", coredump_tmpfile_name(tmp));

        if (lseek(fd, 0, SEEK_SET) < 0)
                return log_error_errno(errno, "Failed to seek on coredump %s: %m", fn);

        *ret_filename = TAKE_PTR(fn);
        *ret_data_fd = TAKE_FD(fd);
        *ret_size = (uint64_t) st.st_size;
        *ret_truncated = truncated;

        return 0;
}

static int allocate_journal_field(int fd, size_t size, char **ret, size_t *ret_size) {
        _cleanup_free_ char *field = NULL;
        ssize_t n;

        assert(fd >= 0);
        assert(ret);
        assert(ret_size);

        if (lseek(fd, 0, SEEK_SET) < 0)
                return log_warning_errno(errno, "Failed to seek: %m");

        field = malloc(9 + size);
        if (!field)
                return log_warning_errno(SYNTHETIC_ERRNO(ENOMEM),
                                         "Failed to allocate memory for coredump, coredump will not be stored.");

        memcpy(field, "COREDUMP=", 9);

        /* NB: simple read() would fail for overly large coredumps, since read() on Linux can only deal with
         * 0x7ffff000 bytes max. Hence call things in a loop. */
        n = loop_read(fd, field + 9, size, /* do_poll= */ false);
        if (n < 0)
                return log_error_errno((int) n, "Failed to read core data: %m");
        if ((size_t) n < size)
                return log_error_errno(SYNTHETIC_ERRNO(EIO),
                                       "Core data too short.");

        *ret = TAKE_PTR(field);
        *ret_size = size + 9;

        return 0;
}

/* Joins /proc/[pid]/fd/ and /proc/[pid]/fdinfo/ into the following lines:
 * 0:/dev/pts/23
 * pos:    0
 * flags:  0100002
 *
 * 1:/dev/pts/23
 * pos:    0
 * flags:  0100002
 *
 * 2:/dev/pts/23
 * pos:    0
 * flags:  0100002
 * EOF
 */
static int compose_open_fds(pid_t pid, char **ret) {
        _cleanup_(memstream_done) MemStream m = {};
        _cleanup_closedir_ DIR *proc_fd_dir = NULL;
        _cleanup_close_ int proc_fdinfo_fd = -EBADF;
        const char *fddelim = "", *path;
        FILE *stream;
        int r;

        assert(pid >= 0);
        assert(ret);

        path = procfs_file_alloca(pid, "fd");
        proc_fd_dir = opendir(path);
        if (!proc_fd_dir)
                return -errno;

        proc_fdinfo_fd = openat(dirfd(proc_fd_dir), "../fdinfo", O_DIRECTORY|O_NOFOLLOW|O_CLOEXEC|O_PATH);
        if (proc_fdinfo_fd < 0)
                return -errno;

        stream = memstream_init(&m);
        if (!stream)
                return -ENOMEM;

        FOREACH_DIRENT(de, proc_fd_dir, return -errno) {
                _cleanup_fclose_ FILE *fdinfo = NULL;
                _cleanup_free_ char *fdname = NULL;
                _cleanup_close_ int fd = -EBADF;

                r = readlinkat_malloc(dirfd(proc_fd_dir), de->d_name, &fdname);
                if (r < 0)
                        return r;

                fprintf(stream, "%s%s:%s\n", fddelim, de->d_name, fdname);
                fddelim = "\n";

                /* Use the directory entry from /proc/[pid]/fd with /proc/[pid]/fdinfo */
                fd = openat(proc_fdinfo_fd, de->d_name, O_NOFOLLOW|O_CLOEXEC|O_RDONLY);
                if (fd < 0)
                        continue;

                fdinfo = take_fdopen(&fd, "r");
                if (!fdinfo)
                        continue;

                for (;;) {
                        _cleanup_free_ char *line = NULL;

                        r = read_line(fdinfo, LONG_LINE_MAX, &line);
                        if (r < 0)
                                return r;
                        if (r == 0)
                                break;

                        fputs(line, stream);
                        fputc('\n', stream);
                }
        }

        return memstream_finalize(&m, ret, NULL);
}

/* Returns 1 if the parent was found.
 * Returns 0 if there is not a process we can call the pid's
 * container parent (the pid's process isn't 'containerized').
 * Returns a negative number on errors.
 */
static int get_process_container_parent_cmdline(pid_t pid, char** cmdline) {
        pid_t container_pid;
        const char *proc_root_path;
        struct stat root_stat, proc_root_stat;
        int r;

        /* To compare inodes of / and /proc/[pid]/root */
        if (stat("/", &root_stat) < 0)
                return -errno;

        proc_root_path = procfs_file_alloca(pid, "root");
        if (stat(proc_root_path, &proc_root_stat) < 0)
                return -errno;

        /* The process uses system root. */
        if (stat_inode_same(&proc_root_stat, &root_stat)) {
                *cmdline = NULL;
                return 0;
        }

        r = namespace_get_leader(pid, NAMESPACE_MOUNT, &container_pid);
        if (r < 0)
                return r;

        r = pid_get_cmdline(container_pid, SIZE_MAX, PROCESS_CMDLINE_QUOTE_POSIX, cmdline);
        if (r < 0)
                return r;

        return 1;
}

static int change_uid_gid(const Context *context) {
        uid_t uid = context->uid;
        gid_t gid = context->gid;
        int r;

        if (uid_is_system(uid)) {
                const char *user = "systemd-coredump";

                r = get_user_creds(&user, &uid, &gid, NULL, NULL, 0);
                if (r < 0) {
                        log_warning_errno(r, "Cannot resolve %s user. Proceeding to dump core as root: %m", user);
                        uid = gid = 0;
                }
        }

        return drop_privileges(uid, gid, 0);
}

static int submit_coredump(
                const Context *context,
                struct iovec_wrapper *iovw,
                int input_fd) {

        _cleanup_(json_variant_unrefp) JsonVariant *json_metadata = NULL;
        _cleanup_close_ int coredump_fd = -EBADF, coredump_node_fd = -EBADF;
        _cleanup_free_ char *filename = NULL, *coredump_data = NULL;
        _cleanup_free_ char *stacktrace = NULL;
        char *core_message;
        const char *module_name;
        uint64_t coredump_size = UINT64_MAX, coredump_compressed_size = UINT64_MAX;
        bool truncated = false;
        JsonVariant *module_json;
        int r;

        assert(context);
        assert(iovw);
        assert(input_fd >= 0);

        /* Vacuum before we write anything again */
        (void) coredump_vacuum(-1, arg_keep_free, arg_max_use);

        /* Always stream the coredump to disk, if that's possible */
        r = save_external_coredump(context, input_fd,
                                   &filename, &coredump_node_fd, &coredump_fd,
                                   &coredump_size, &coredump_compressed_size, &truncated);
        if (r < 0)
                /* Skip whole core dumping part */
                goto log;

        /* If we don't want to keep the coredump on disk, remove it now, as later on we
         * will lack the privileges for it. However, we keep the fd to it, so that we can
         * still process it and log it. */
        r = maybe_remove_external_coredump(filename, coredump_node_fd >= 0 ? coredump_compressed_size : coredump_size);
        if (r < 0)
                return r;
        if (r == 0)
                (void) iovw_put_string_field(iovw, "COREDUMP_FILENAME=", filename);
        else if (arg_storage == COREDUMP_STORAGE_EXTERNAL)
                log_info("The core will not be stored: size %"PRIu64" is greater than %"PRIu64" (the configured maximum)",
                         coredump_node_fd >= 0 ? coredump_compressed_size : coredump_size, arg_external_size_max);

        /* Vacuum again, but exclude the coredump we just created */
        (void) coredump_vacuum(coredump_node_fd >= 0 ? coredump_node_fd : coredump_fd, arg_keep_free, arg_max_use);

        /* Now, let's drop privileges to become the user who owns the segfaulted process
         * and allocate the coredump memory under the user's uid. This also ensures that
         * the credentials journald will see are the ones of the coredumping user, thus
         * making sure the user gets access to the core dump. Let's also get rid of all
         * capabilities, if we run as root, we won't need them anymore. */
        r = change_uid_gid(context);
        if (r < 0)
                return log_error_errno(r, "Failed to drop privileges: %m");

        /* Try to get a stack trace if we can */
        if (coredump_size > arg_process_size_max)
                log_debug("Not generating stack trace: core size %"PRIu64" is greater "
                          "than %"PRIu64" (the configured maximum)",
                          coredump_size, arg_process_size_max);
        else if (coredump_fd >= 0) {
                bool skip = startswith(context->meta[META_COMM], "systemd-coredum"); /* COMM is 16 bytes usually */

                (void) parse_elf_object(coredump_fd,
                                        context->meta[META_EXE],
                                        /* fork_disable_dump= */ skip, /* avoid loops */
                                        &stacktrace,
                                        &json_metadata);
        }

log:
        core_message = strjoina("Process ", context->meta[META_ARGV_PID],
                                " (", context->meta[META_COMM], ") of user ",
                                context->meta[META_ARGV_UID], " dumped core.",
                                context->is_journald && filename ? "\nCoredump diverted to " : NULL,
                                context->is_journald && filename ? filename : NULL);

        core_message = strjoina(core_message, stacktrace ? "\n\n" : NULL, stacktrace);

        if (context->is_journald)
                /* We might not be able to log to the journal, so let's always print the message to another
                 * log target. The target was set previously to something safe. */
                log_dispatch(LOG_ERR, 0, core_message);

        (void) iovw_put_string_field(iovw, "MESSAGE=", core_message);

        if (truncated)
                (void) iovw_put_string_field(iovw, "COREDUMP_TRUNCATED=", "1");

        /* If we managed to parse any ELF metadata (build-id, ELF package meta),
         * attach it as journal metadata. */
        if (json_metadata) {
                _cleanup_free_ char *formatted_json = NULL;

                r = json_variant_format(json_metadata, 0, &formatted_json);
                if (r < 0)
                        return log_error_errno(r, "Failed to format JSON package metadata: %m");

                (void) iovw_put_string_field(iovw, "COREDUMP_PACKAGE_JSON=", formatted_json);
        }

        /* In the unlikely scenario that context->meta[META_EXE] is not available,
         * let's avoid guessing the module name and skip the loop. */
        if (context->meta[META_EXE])
                JSON_VARIANT_OBJECT_FOREACH(module_name, module_json, json_metadata) {
                        JsonVariant *t;

                        /* We only add structured fields for the 'main' ELF module, and only if we can identify it. */
                        if (!path_equal_filename(module_name, context->meta[META_EXE]))
                                continue;

                        t = json_variant_by_key(module_json, "name");
                        if (t)
                                (void) iovw_put_string_field(iovw, "COREDUMP_PACKAGE_NAME=", json_variant_string(t));

                        t = json_variant_by_key(module_json, "version");
                        if (t)
                                (void) iovw_put_string_field(iovw, "COREDUMP_PACKAGE_VERSION=", json_variant_string(t));
                }

        /* Optionally store the entire coredump in the journal */
        if (arg_storage == COREDUMP_STORAGE_JOURNAL && coredump_fd >= 0) {
                if (coredump_size <= arg_journal_size_max) {
                        size_t sz = 0;

                        /* Store the coredump itself in the journal */

                        r = allocate_journal_field(coredump_fd, (size_t) coredump_size, &coredump_data, &sz);
                        if (r >= 0) {
                                if (iovw_put(iovw, coredump_data, sz) >= 0)
                                        TAKE_PTR(coredump_data);
                        } else
                                log_warning_errno(r, "Failed to attach the core to the journal entry: %m");
                } else
                        log_info("The core will not be stored: size %"PRIu64" is greater than %"PRIu64" (the configured maximum)",
                                 coredump_size, arg_journal_size_max);
        }

        /* If journald is coredumping, we have to be careful that we don't deadlock when trying to write the
         * coredump to the journal, so we put the journal socket in nonblocking mode before trying to write
         * the coredump to the socket. */

        if (context->is_journald) {
                r = journal_fd_nonblock(true);
                if (r < 0)
                        return log_error_errno(r, "Failed to make journal socket non-blocking: %m");
        }

        r = sd_journal_sendv(iovw->iovec, iovw->count);

        if (context->is_journald) {
                int k;

                k = journal_fd_nonblock(false);
                if (k < 0)
                        return log_error_errno(k, "Failed to make journal socket blocking: %m");
        }

        if (r == -EAGAIN && context->is_journald)
                log_warning_errno(r, "Failed to log journal coredump, ignoring: %m");
        else if (r < 0)
                return log_error_errno(r, "Failed to log coredump: %m");

        return 0;
}

static int save_context(Context *context, const struct iovec_wrapper *iovw) {
        const char *unit;
        int r;

        assert(context);
        assert(iovw);
        assert(iovw->count >= _META_ARGV_MAX);

        /* The context does not allocate any memory on its own */

        for (size_t n = 0; n < iovw->count; n++) {
                struct iovec *iovec = iovw->iovec + n;

                for (size_t i = 0; i < ELEMENTSOF(meta_field_names); i++) {
                        /* Note that these strings are NUL terminated, because we made sure that a
                         * trailing NUL byte is in the buffer, though not included in the iov_len
                         * count (see process_socket() and gather_pid_metadata_*()) */
                        assert(((char*) iovec->iov_base)[iovec->iov_len] == 0);

                        const char *p = startswith(iovec->iov_base, meta_field_names[i]);
                        if (p) {
                                context->meta[i] = p;
                                context->meta_size[i] = iovec->iov_len - strlen(meta_field_names[i]);
                                break;
                        }
                }
        }

        if (!context->meta[META_ARGV_PID])
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Failed to find the PID of crashing process");

        r = parse_pid(context->meta[META_ARGV_PID], &context->pid);
        if (r < 0)
                return log_error_errno(r, "Failed to parse PID \"%s\": %m", context->meta[META_ARGV_PID]);

        r = parse_uid(context->meta[META_ARGV_UID], &context->uid);
        if (r < 0)
                return log_error_errno(r, "Failed to parse UID \"%s\": %m", context->meta[META_ARGV_UID]);

        r = parse_gid(context->meta[META_ARGV_GID], &context->gid);
        if (r < 0)
                return log_error_errno(r, "Failed to parse GID \"%s\": %m", context->meta[META_ARGV_GID]);

        unit = context->meta[META_UNIT];
        context->is_pid1 = streq(context->meta[META_ARGV_PID], "1") || streq_ptr(unit, SPECIAL_INIT_SCOPE);
        context->is_journald = streq_ptr(unit, SPECIAL_JOURNALD_SERVICE);

        return 0;
}

static int process_socket(int fd) {
        _cleanup_close_ int input_fd = -EBADF;
        Context context = {};
        struct iovec_wrapper iovw = {};
        struct iovec iovec;
        int r;

        assert(fd >= 0);

        log_setup();

        log_debug("Processing coredump received on stdin...");

        for (;;) {
                CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control;
                struct msghdr mh = {
                        .msg_control = &control,
                        .msg_controllen = sizeof(control),
                        .msg_iovlen = 1,
                };
                ssize_t n;
                ssize_t l;

                l = next_datagram_size_fd(fd);
                if (l < 0) {
                        r = log_error_errno(l, "Failed to determine datagram size to read: %m");
                        goto finish;
                }

                iovec.iov_len = l;
                iovec.iov_base = malloc(l + 1);
                if (!iovec.iov_base) {
                        r = log_oom();
                        goto finish;
                }

                mh.msg_iov = &iovec;

                n = recvmsg_safe(fd, &mh, MSG_CMSG_CLOEXEC);
                if (n < 0)  {
                        free(iovec.iov_base);
                        r = log_error_errno(n, "Failed to receive datagram: %m");
                        goto finish;
                }

                /* The final zero-length datagram carries the file descriptor and tells us
                 * that we're done. */
                if (n == 0) {
                        struct cmsghdr *found;

                        free(iovec.iov_base);

                        found = cmsg_find(&mh, SOL_SOCKET, SCM_RIGHTS, CMSG_LEN(sizeof(int)));
                        if (!found) {
                                cmsg_close_all(&mh);
                                r = log_error_errno(SYNTHETIC_ERRNO(EBADMSG),
                                                    "Coredump file descriptor missing.");
                                goto finish;
                        }

                        assert(input_fd < 0);
                        input_fd = *CMSG_TYPED_DATA(found, int);
                        break;
                } else
                        cmsg_close_all(&mh);

                /* Add trailing NUL byte, in case these are strings */
                ((char*) iovec.iov_base)[n] = 0;
                iovec.iov_len = (size_t) n;

                r = iovw_put(&iovw, iovec.iov_base, iovec.iov_len);
                if (r < 0)
                        goto finish;
        }

        /* Make sure we got all data we really need */
        assert(input_fd >= 0);

        r = save_context(&context, &iovw);
        if (r < 0)
                goto finish;

        /* Make sure we received at least all fields we need. */
        for (int i = 0; i < _META_MANDATORY_MAX; i++)
                if (!context.meta[i]) {
                        r = log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                            "A mandatory argument (%i) has not been sent, aborting.",
                                            i);
                        goto finish;
                }

        r = submit_coredump(&context, &iovw, input_fd);

finish:
        iovw_free_contents(&iovw, true);
        return r;
}

static int send_iovec(const struct iovec_wrapper *iovw, int input_fd) {
        _cleanup_close_ int fd = -EBADF;
        int r;

        assert(iovw);
        assert(input_fd >= 0);

        fd = socket(AF_UNIX, SOCK_SEQPACKET|SOCK_CLOEXEC, 0);
        if (fd < 0)
                return log_error_errno(errno, "Failed to create coredump socket: %m");

        r = connect_unix_path(fd, AT_FDCWD, "/run/systemd/coredump");
        if (r < 0)
                return log_error_errno(r, "Failed to connect to coredump service: %m");

        for (size_t i = 0; i < iovw->count; i++) {
                struct msghdr mh = {
                        .msg_iov = iovw->iovec + i,
                        .msg_iovlen = 1,
                };
                struct iovec copy[2];

                for (;;) {
                        if (sendmsg(fd, &mh, MSG_NOSIGNAL) >= 0)
                                break;

                        if (errno == EMSGSIZE && mh.msg_iov[0].iov_len > 0) {
                                /* This field didn't fit? That's a pity. Given that this is
                                 * just metadata, let's truncate the field at half, and try
                                 * again. We append three dots, in order to show that this is
                                 * truncated. */

                                if (mh.msg_iov != copy) {
                                        /* We don't want to modify the caller's iovec, hence
                                         * let's create our own array, consisting of two new
                                         * iovecs, where the first is a (truncated) copy of
                                         * what we want to send, and the second one contains
                                         * the trailing dots. */
                                        copy[0] = iovw->iovec[i];
                                        copy[1] = IOVEC_MAKE(((char[]){'.', '.', '.'}), 3);

                                        mh.msg_iov = copy;
                                        mh.msg_iovlen = 2;
                                }

                                copy[0].iov_len /= 2; /* halve it, and try again */
                                continue;
                        }

                        return log_error_errno(errno, "Failed to send coredump datagram: %m");
                }
        }

        r = send_one_fd(fd, input_fd, 0);
        if (r < 0)
                return log_error_errno(r, "Failed to send coredump fd: %m");

        return 0;
}

static int gather_pid_metadata_from_argv(
                struct iovec_wrapper *iovw,
                Context *context,
                int argc, char **argv) {

        _cleanup_free_ char *free_timestamp = NULL;
        int r, signo;
        char *t;

        assert(iovw);
        assert(context);

        /* We gather all metadata that were passed via argv[] into an array of iovecs that
         * we'll forward to the socket unit */

        if (argc < _META_ARGV_MAX)
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                       "Not enough arguments passed by the kernel (%i, expected %i).",
                                       argc, _META_ARGV_MAX);

        for (int i = 0; i < _META_ARGV_MAX; i++) {

                t = argv[i];

                switch (i) {

                case META_ARGV_TIMESTAMP:
                        /* The journal fields contain the timestamp padded with six
                         * zeroes, so that the kernel-supplied 1s granularity timestamps
                         * becomes 1μs granularity, i.e. the granularity systemd usually
                         * operates in. */
                        t = free_timestamp = strjoin(argv[i], "000000");
                        if (!t)
                                return log_oom();
                        break;

                case META_ARGV_SIGNAL:
                        /* For signal, record its pretty name too */
                        if (safe_atoi(argv[i], &signo) >= 0 && SIGNAL_VALID(signo))
                                (void) iovw_put_string_field(iovw, "COREDUMP_SIGNAL_NAME=SIG",
                                                             signal_to_string(signo));
                        break;

                default:
                        break;
                }

                r = iovw_put_string_field(iovw, meta_field_names[i], t);
                if (r < 0)
                        return r;
        }

        /* Cache some of the process metadata we collected so far and that we'll need to
         * access soon */
        return save_context(context, iovw);
}

static int gather_pid_metadata_from_procfs(struct iovec_wrapper *iovw, Context *context) {
        uid_t owner_uid;
        pid_t pid;
        char *t;
        size_t size;
        const char *p;
        int r;

        assert(iovw);
        assert(context);

        /* Note that if we fail on oom later on, we do not roll-back changes to the iovec
         * structure. (It remains valid, with the first iovec fields initialized.) */

        pid = context->pid;

        /* The following is mandatory */
        r = pid_get_comm(pid, &t);
        if (r < 0)
                return log_error_errno(r, "Failed to get COMM: %m");

        r = iovw_put_string_field_free(iovw, "COREDUMP_COMM=", t);
        if (r < 0)
                return r;

        /* The following are optional, but we use them if present. */
        r = get_process_exe(pid, &t);
        if (r >= 0)
                r = iovw_put_string_field_free(iovw, "COREDUMP_EXE=", t);
        if (r < 0)
                log_warning_errno(r, "Failed to get EXE, ignoring: %m");

        if (cg_pid_get_unit(pid, &t) >= 0)
                (void) iovw_put_string_field_free(iovw, "COREDUMP_UNIT=", t);

        if (cg_pid_get_user_unit(pid, &t) >= 0)
                (void) iovw_put_string_field_free(iovw, "COREDUMP_USER_UNIT=", t);

        if (sd_pid_get_session(pid, &t) >= 0)
                (void) iovw_put_string_field_free(iovw, "COREDUMP_SESSION=", t);

        if (sd_pid_get_owner_uid(pid, &owner_uid) >= 0) {
                r = asprintf(&t, UID_FMT, owner_uid);
                if (r > 0)
                        (void) iovw_put_string_field_free(iovw, "COREDUMP_OWNER_UID=", t);
        }

        if (sd_pid_get_slice(pid, &t) >= 0)
                (void) iovw_put_string_field_free(iovw, "COREDUMP_SLICE=", t);

        if (pid_get_cmdline(pid, SIZE_MAX, PROCESS_CMDLINE_QUOTE_POSIX, &t) >= 0)
                (void) iovw_put_string_field_free(iovw, "COREDUMP_CMDLINE=", t);

        if (cg_pid_get_path_shifted(pid, NULL, &t) >= 0)
                (void) iovw_put_string_field_free(iovw, "COREDUMP_CGROUP=", t);

        if (compose_open_fds(pid, &t) >= 0)
                (void) iovw_put_string_field_free(iovw, "COREDUMP_OPEN_FDS=", t);

        p = procfs_file_alloca(pid, "status");
        if (read_full_virtual_file(p, &t, NULL) >= 0)
                (void) iovw_put_string_field_free(iovw, "COREDUMP_PROC_STATUS=", t);

        p = procfs_file_alloca(pid, "maps");
        if (read_full_virtual_file(p, &t, NULL) >= 0)
                (void) iovw_put_string_field_free(iovw, "COREDUMP_PROC_MAPS=", t);

        p = procfs_file_alloca(pid, "limits");
        if (read_full_virtual_file(p, &t, NULL) >= 0)
                (void) iovw_put_string_field_free(iovw, "COREDUMP_PROC_LIMITS=", t);

        p = procfs_file_alloca(pid, "cgroup");
        if (read_full_virtual_file(p, &t, NULL) >= 0)
                (void) iovw_put_string_field_free(iovw, "COREDUMP_PROC_CGROUP=", t);

        p = procfs_file_alloca(pid, "mountinfo");
        if (read_full_virtual_file(p, &t, NULL) >= 0)
                (void) iovw_put_string_field_free(iovw, "COREDUMP_PROC_MOUNTINFO=", t);

        /* We attach /proc/auxv here. ELF coredumps also contain a note for this (NT_AUXV), see elf(5). */
        p = procfs_file_alloca(pid, "auxv");
        if (read_full_virtual_file(p, &t, &size) >= 0) {
                char *buf = malloc(strlen("COREDUMP_PROC_AUXV=") + size + 1);
                if (buf) {
                        /* Add a dummy terminator to make save_context() happy. */
                        *((uint8_t*) mempcpy(stpcpy(buf, "COREDUMP_PROC_AUXV="), t, size)) = '\0';
                        (void) iovw_consume(iovw, buf, size + strlen("COREDUMP_PROC_AUXV="));
                }

                free(t);
        }

        if (get_process_cwd(pid, &t) >= 0)
                (void) iovw_put_string_field_free(iovw, "COREDUMP_CWD=", t);

        if (get_process_root(pid, &t) >= 0) {
                bool proc_self_root_is_slash;

                proc_self_root_is_slash = strcmp(t, "/") == 0;

                (void) iovw_put_string_field_free(iovw, "COREDUMP_ROOT=", t);

                /* If the process' root is "/", then there is a chance it has
                 * mounted own root and hence being containerized. */
                if (proc_self_root_is_slash && get_process_container_parent_cmdline(pid, &t) > 0)
                        (void) iovw_put_string_field_free(iovw, "COREDUMP_CONTAINER_CMDLINE=", t);
        }

        if (get_process_environ(pid, &t) >= 0)
                (void) iovw_put_string_field_free(iovw, "COREDUMP_ENVIRON=", t);

        /* we successfully acquired all metadata */
        return save_context(context, iovw);
}

static int send_ucred(int transport_fd, struct ucred *ucred) {
        CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred))) control = {};
        struct msghdr mh = {
                .msg_control = &control,
                .msg_controllen = sizeof(control),
        };
        struct cmsghdr *cmsg;

        assert(transport_fd >= 0);

        cmsg = CMSG_FIRSTHDR(&mh);
        *cmsg = (struct cmsghdr) {
                .cmsg_level = SOL_SOCKET,
                .cmsg_type = SCM_CREDENTIALS,
                .cmsg_len = CMSG_LEN(sizeof(struct ucred)),
        };
        memcpy(CMSG_DATA(cmsg), ucred, sizeof(struct ucred));

        return RET_NERRNO(sendmsg(transport_fd, &mh, MSG_NOSIGNAL));
}

static int receive_ucred(int transport_fd, struct ucred *ret_ucred) {
        CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred))) control = {};
        struct msghdr mh = {
                .msg_control = &control,
                .msg_controllen = sizeof(control),
        };
        struct cmsghdr *cmsg = NULL;
        struct ucred *ucred = NULL;
        ssize_t n;

        assert(ret_ucred);

        n = recvmsg_safe(transport_fd, &mh, 0);
        if (n < 0)
                return n;

        CMSG_FOREACH(cmsg, &mh)
                if (cmsg->cmsg_level == SOL_SOCKET &&
                    cmsg->cmsg_type == SCM_CREDENTIALS &&
                    cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred))) {

                        assert(!ucred);
                        ucred = CMSG_TYPED_DATA(cmsg, struct ucred);
                }

        if (!ucred)
                return -EIO;

        *ret_ucred = *ucred;

        return 0;
}

static int can_forward_coredump(pid_t pid) {
        _cleanup_free_ char *cgroup = NULL, *path = NULL, *unit = NULL;
        int r;

        r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &cgroup);
        if (r < 0)
                return r;

        r = path_extract_directory(cgroup, &path);
        if (r < 0)
                return r;

        r = cg_path_get_unit_path(path, &unit);
        if (r == -ENOMEM)
                return log_oom();
        if (r == -ENXIO)
                /* No valid units in this path. */
                return false;
        if (r < 0)
                return r;

        /* We require that this process belongs to a delegated cgroup
         * (i.e. Delegate=yes), with CoredumpReceive=yes also. */
        r = cg_is_delegated(unit);
        if (r <= 0)
                return r;

        return cg_has_coredump_receive(unit);
}

static int forward_coredump_to_container(Context *context) {
        _cleanup_close_ int pidnsfd = -EBADF, mntnsfd = -EBADF, netnsfd = -EBADF, usernsfd = -EBADF, rootfd = -EBADF;
        _cleanup_close_pair_ int pair[2] = EBADF_PAIR;
        pid_t pid, child;
        struct ucred ucred = {
                .pid = context->pid,
                .uid = context->uid,
                .gid = context->gid,
        };
        int r;

        r = namespace_get_leader(context->pid, NAMESPACE_PID, &pid);
        if (r < 0)
                return log_debug_errno(r, "Failed to get namespace leader: %m");

        r = can_forward_coredump(pid);
        if (r < 0)
                return log_debug_errno(r, "Failed to check if coredump can be forwarded: %m");
        if (r == 0)
                return log_debug_errno(SYNTHETIC_ERRNO(ENOENT),
                                       "Coredump will not be forwarded because no target cgroup was found.");

        r = RET_NERRNO(socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, pair));
        if (r < 0)
                return log_debug_errno(r, "Failed to create socket pair: %m");

        r = setsockopt_int(pair[1], SOL_SOCKET, SO_PASSCRED, true);
        if (r < 0)
                return log_debug_errno(r, "Failed to set SO_PASSCRED: %m");

        r = namespace_open(pid, &pidnsfd, &mntnsfd, &netnsfd, &usernsfd, &rootfd);
        if (r < 0)
                return log_debug_errno(r, "Failed to join namespaces of PID " PID_FMT ": %m", pid);

        r = namespace_fork("(sd-coredumpns)", "(sd-coredump)", NULL, 0,
                           FORK_RESET_SIGNALS|FORK_DEATHSIG,
                           pidnsfd, mntnsfd, netnsfd, usernsfd, rootfd, &child);
        if (r < 0)
                return log_debug_errno(r, "Failed to fork into namespaces of PID " PID_FMT ": %m", pid);
        if (r == 0) {
                _cleanup_(iovw_free_freep) struct iovec_wrapper *iovw = NULL;
                Context child_context = {};

                pair[0] = safe_close(pair[0]);

                if (laccess("/run/systemd/coredump", W_OK) < 0) {
                        log_debug_errno(errno, "Cannot find coredump socket, exiting: %m");
                        _exit(EXIT_FAILURE);
                }

                r = receive_ucred(pair[1], &ucred);
                if (r < 0) {
                        log_debug_errno(r, "Failed to receive ucred and fd: %m");
                        _exit(EXIT_FAILURE);
                }

                iovw = iovw_new();
                if (!iovw) {
                        log_oom();
                        _exit(EXIT_FAILURE);
                }

                (void) iovw_put_string_field(iovw, "MESSAGE_ID=", SD_MESSAGE_COREDUMP_STR);
                (void) iovw_put_string_field(iovw, "PRIORITY=", STRINGIFY(LOG_CRIT));
                (void) iovw_put_string_field(iovw, "COREDUMP_FORWARDED=", "1");

                for (int i = 0; i < _META_ARGV_MAX; i++) {
                        int signo;
                        char buf[DECIMAL_STR_MAX(pid_t)];
                        const char *t = context->meta[i];

                        switch(i) {

                        case META_ARGV_PID:
                                xsprintf(buf, PID_FMT, ucred.pid);
                                t = buf;

                                break;

                        case META_ARGV_UID:
                                xsprintf(buf, UID_FMT, ucred.uid);
                                t = buf;
                                break;

                        case META_ARGV_GID:
                                xsprintf(buf, GID_FMT, ucred.gid);
                                t = buf;
                                break;

                        case META_ARGV_SIGNAL:
                                if (safe_atoi(t, &signo) >= 0 && SIGNAL_VALID(signo))
                                        (void) iovw_put_string_field(iovw,
                                                                     "COREDUMP_SIGNAL_NAME=SIG",
                                                                     signal_to_string(signo));
                                break;

                        default:
                                break;
                        }

                        r = iovw_put_string_field(iovw, meta_field_names[i], t);
                        if (r < 0) {
                                log_debug_errno(r, "Failed to construct iovec: %m");
                                _exit(EXIT_FAILURE);
                        }
                }

                r = save_context(&child_context, iovw);
                if (r < 0) {
                        log_debug_errno(r, "Failed to save context: %m");
                        _exit(EXIT_FAILURE);
                }

                r = gather_pid_metadata_from_procfs(iovw, &child_context);
                if (r < 0) {
                        log_debug_errno(r, "Failed to gather metadata from procfs: %m");
                        _exit(EXIT_FAILURE);
                }

                r = send_iovec(iovw, STDIN_FILENO);
                if (r < 0) {
                        log_debug_errno(r, "Failed to send iovec to coredump socket: %m");
                        _exit(EXIT_FAILURE);
                }

                _exit(EXIT_SUCCESS);
        }

        pair[1] = safe_close(pair[1]);

        /* We need to translate the PID, UID, and GID of the crashing process
         * to the container's namespaces. Do this by sending an SCM_CREDENTIALS
         * message on a socket pair, and read the result when we join the
         * container. The kernel will perform the translation for us. */
        r = send_ucred(pair[0], &ucred);
        if (r < 0)
                return log_debug_errno(r, "Failed to send metadata to container: %m");

        r = wait_for_terminate_and_check("(sd-coredumpns)", child, 0);
        if (r < 0)
                return log_debug_errno(r, "Failed to wait for child to terminate: %m");
        if (r != EXIT_SUCCESS)
                return log_debug_errno(SYNTHETIC_ERRNO(EPROTO), "Failed to process coredump in container: %m");

        return 0;
}

static int process_kernel(int argc, char* argv[]) {
        _cleanup_(iovw_free_freep) struct iovec_wrapper *iovw = NULL;
        Context context = {};
        int r;

        /* When we're invoked by the kernel, stdout/stderr are closed which is dangerous because the fds
         * could get reallocated. To avoid hard to debug issues, let's instead bind stdout/stderr to
         * /dev/null. */
        r = rearrange_stdio(STDIN_FILENO, -EBADF, -EBADF);
        if (r < 0)
                return log_error_errno(r, "Failed to connect stdout/stderr to /dev/null: %m");

        log_debug("Processing coredump received from the kernel...");

        iovw = iovw_new();
        if (!iovw)
                return log_oom();

        /* Collect all process metadata passed by the kernel through argv[] */
        r = gather_pid_metadata_from_argv(iovw, &context, argc - 1, argv + 1);
        if (r < 0)
                return r;

        /* Collect the rest of the process metadata retrieved from the runtime */
        r = gather_pid_metadata_from_procfs(iovw, &context);
        if (r < 0)
                return r;

        if (!context.is_journald)
                /* OK, now we know it's not the journal, hence we can make use of it now. */
                log_set_target_and_open(LOG_TARGET_JOURNAL_OR_KMSG);

        r = in_same_namespace(getpid_cached(), context.pid, NAMESPACE_PID);
        if (r < 0)
                log_debug_errno(r, "Failed to check pidns of crashing process, ignoring: %m");
        if (r == 0) {
                /* If this fails, fallback to the old behavior so that
                 * there is still some record of the crash. */
                r = forward_coredump_to_container(&context);
                if (r >= 0)
                        return 0;
        }

        /* If this is PID 1 disable coredump collection, we'll unlikely be able to process
         * it later on.
         *
         * FIXME: maybe we should disable coredumps generation from the beginning and
         * re-enable it only when we know it's either safe (ie we're not running OOM) or
         * it's not pid1 ? */
        if (context.is_pid1) {
                log_notice("Due to PID 1 having crashed coredump collection will now be turned off.");
                disable_coredumps();
        }

        (void) iovw_put_string_field(iovw, "MESSAGE_ID=", SD_MESSAGE_COREDUMP_STR);
        (void) iovw_put_string_field(iovw, "PRIORITY=", STRINGIFY(LOG_CRIT));

        if (context.is_journald || context.is_pid1)
                return submit_coredump(&context, iovw, STDIN_FILENO);

        return send_iovec(iovw, STDIN_FILENO);
}

static int process_backtrace(int argc, char *argv[]) {
        _cleanup_(journal_importer_cleanup) JournalImporter importer = JOURNAL_IMPORTER_INIT(STDIN_FILENO);
        _cleanup_(iovw_free_freep) struct iovec_wrapper *iovw = NULL;
        Context context = {};
        char *message;
        int r;

        log_debug("Processing backtrace on stdin...");

        iovw = iovw_new();
        if (!iovw)
                return log_oom();

        (void) iovw_put_string_field(iovw, "MESSAGE_ID=", SD_MESSAGE_BACKTRACE_STR);
        (void) iovw_put_string_field(iovw, "PRIORITY=", STRINGIFY(LOG_CRIT));

        /* Collect all process metadata from argv[] by making sure to skip the
         * '--backtrace' option */
        r = gather_pid_metadata_from_argv(iovw, &context, argc - 2, argv + 2);
        if (r < 0)
                return r;

        /* Collect the rest of the process metadata retrieved from the runtime */
        r = gather_pid_metadata_from_procfs(iovw, &context);
        if (r < 0)
                return r;

        for (;;) {
                r = journal_importer_process_data(&importer);
                if (r < 0)
                        return log_error_errno(r, "Failed to parse journal entry on stdin: %m");
                if (r == 1 ||                        /* complete entry */
                    journal_importer_eof(&importer)) /* end of data */
                        break;
        }

        if (journal_importer_eof(&importer)) {
                log_warning("Did not receive a full journal entry on stdin, ignoring message sent by reporter");

                message = strjoina("Process ", context.meta[META_ARGV_PID],
                                  " (", context.meta[META_COMM], ")"
                                  " of user ", context.meta[META_ARGV_UID],
                                  " failed with ", context.meta[META_ARGV_SIGNAL]);

                r = iovw_put_string_field(iovw, "MESSAGE=", message);
                if (r < 0)
                        return r;
        } else {
                /* The imported iovecs are not supposed to be freed by us so let's copy and merge them at the
                 * end of the array. */
                r = iovw_append(iovw, &importer.iovw);
                if (r < 0)
                        return r;
        }

        r = sd_journal_sendv(iovw->iovec, iovw->count);
        if (r < 0)
                return log_error_errno(r, "Failed to log backtrace: %m");

        return 0;
}

static int run(int argc, char *argv[]) {
        int r;

        /* First, log to a safe place, since we don't know what crashed and it might
         * be journald which we'd rather not log to then. */

        log_set_target_and_open(LOG_TARGET_KMSG);

        /* Make sure we never enter a loop */
        (void) prctl(PR_SET_DUMPABLE, 0);

        /* Ignore all parse errors */
        (void) parse_config();

        log_debug("Selected storage '%s'.", coredump_storage_to_string(arg_storage));
        log_debug("Selected compression %s.", yes_no(arg_compress));

        r = sd_listen_fds(false);
        if (r < 0)
                return log_error_errno(r, "Failed to determine the number of file descriptors: %m");

        /* If we got an fd passed, we are running in coredumpd mode. Otherwise we
         * are invoked from the kernel as coredump handler. */
        if (r == 0) {
                if (streq_ptr(argv[1], "--backtrace"))
                        return process_backtrace(argc, argv);
                else
                        return process_kernel(argc, argv);
        } else if (r == 1)
                return process_socket(SD_LISTEN_FDS_START);

        return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                               "Received unexpected number of file descriptors.");
}

DEFINE_MAIN_FUNCTION(run);