File: install.c

package info (click to toggle)
rauc 1.15.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 6,348 kB
  • sloc: ansic: 37,058; python: 3,354; sh: 1,393; xml: 53; makefile: 41
file content (1784 lines) | stat: -rw-r--r-- 57,497 bytes parent folder | download
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
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
#include <errno.h>
#include <fcntl.h>
#include <gio/gfiledescriptorbased.h>
#include <gio/gio.h>
#include <gio/gunixmounts.h>
#include <gio/gunixoutputstream.h>
#include <glib.h>
#include <glib/gstdio.h>
#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>

#include "artifacts.h"
#include "bootchooser.h"
#include "bundle.h"
#include "context.h"
#include "event_log.h"
#include "install.h"
#include "manifest.h"
#include "mark.h"
#include "mount.h"
#include "service.h"
#include "shell.h"
#include "signature.h"
#include "slot.h"
#include "status_file.h"
#include "update_handler.h"
#include "utils.h"

/* All exit codes of hook script above this mean 'rejected' */
#define INSTALL_HOOK_REJECT_CODE 10

#define R_INSTALL_ERROR r_install_error_quark()

GQuark r_install_error_quark(void)
{
	return g_quark_from_static_string("r_install_error_quark");
}

__attribute__((__format__(__printf__, 2, 3)))
static void install_args_update(RaucInstallArgs *args, const gchar *msg, ...)
{
	va_list list;
	gchar *formatted = NULL;

	g_return_if_fail(args);
	g_return_if_fail(msg);

	va_start(list, msg);
	formatted = g_strdup_vprintf(msg, list);
	va_end(list);

	g_mutex_lock(&args->status_mutex);
	g_queue_push_tail(&args->status_messages, formatted);
	g_mutex_unlock(&args->status_mutex);
	g_main_context_invoke(NULL, args->notify, args);
}

static gchar *resolve_loop_device(const gchar *devicepath, GError **error)
{
	g_autoptr(GRegex) regex = NULL;
	g_autoptr(GMatchInfo) match_info = NULL;
	g_autofree gchar *devicename = NULL;
	g_autofree gchar *syspath = NULL;
	gchar *content = NULL;
	GError *ierror = NULL;

	regex = g_regex_new("/dev/(loop\\d+)(p\\d+)?", 0, 0, NULL);
	g_assert_nonnull(regex);

	g_regex_match(regex, devicepath, 0, &match_info);
	if (!g_match_info_matches(match_info))
		return g_strdup(devicepath);

	devicename = g_match_info_fetch(match_info, 1);
	syspath = g_build_filename("/sys/block", devicename, "loop/backing_file", NULL);

	content = read_file_str(syspath, &ierror);
	if (!content) {
		g_propagate_prefixed_error(
				error,
				ierror,
				"Error getting loop backing_file for '%s': ", devicepath);
		return NULL;
	}

	/* g_strchomp modifies the string and returns it */
	return g_strchomp(content);
}

gboolean update_external_mount_points(GError **error)
{
	g_autolist(GUnixMountEntry) mountlist = NULL;
	GHashTableIter iter;
	RaucSlot *slot;
	GError *ierror = NULL;

	/* Clear all previously detected external mount points as we will
	 * re-deterrmine them. */
	g_hash_table_iter_init(&iter, r_context()->config->slots);
	while (g_hash_table_iter_next(&iter, NULL, (gpointer*) &slot)) {
		g_clear_pointer(&slot->ext_mount_point, g_free);
	}

	/* Determine active slot mount points */
	mountlist = g_unix_mounts_get(NULL);
	for (GList *l = mountlist; l != NULL; l = l->next) {
		GUnixMountEntry *m = (GUnixMountEntry*)l->data;
		g_autofree gchar *devicepath = NULL;
		RaucSlot *s;
		devicepath = resolve_loop_device(g_unix_mount_get_device_path(m), &ierror);
		if (!devicepath) {
			g_propagate_error(error, ierror);
			return FALSE;
		}
		s = find_config_slot_by_device(r_context()->config,
				devicepath);
		if (s) {
			/* We might have multiple mount entries matching the same device and thus the same slot.
			 * To avoid leaking the string returned by g_unix_mount_get_mount_path() here, we skip all further matches
			 */
			if (s->ext_mount_point) {
				continue;
			}
			s->ext_mount_point = g_strdup(g_unix_mount_get_mount_path(m));
			g_debug("Found external mountpoint for slot '%s' at '%s'", s->name, s->ext_mount_point);
		}
	}

	return TRUE;
}

/*
 * Based on the 'bootslot' information (derived from /proc/cmdline during
 * context setup), this determines 'booted', 'active' and 'inactive' states for
 * each slot and stores this in the 'state' member of each slot.
 *
 * First, the booted slot is determined by comparing the 'bootslot' against the
 * slot's 'bootname', 'name', or device path. Then, the other states are
 * determined based on the slot hierarchies.
 *
 * If 'bootslot' is '/dev/nfs' or '_external_', all slots are considered
 * 'inactive'.
 *
 * @param error Return location for a GError, or NULL
 *
 * @return TRUE if succeeded, FALSE if failed
 */
gboolean determine_slot_states(GError **error)
{
	g_autoptr(GList) slotlist = NULL;
	RaucSlot *booted = NULL;

	g_assert_nonnull(r_context()->config);

	if (r_context()->config->slots == NULL) {
		g_set_error_literal(
				error,
				R_SLOT_ERROR,
				R_SLOT_ERROR_NO_CONFIG,
				"No slot configuration found");
		return FALSE;
	}

	if (r_context()->bootslot == NULL) {
		g_set_error_literal(
				error,
				R_SLOT_ERROR,
				R_SLOT_ERROR_NO_BOOTSLOT,
				"Could not find any root device or rauc slot information in /proc/cmdline");
		return FALSE;
	}

	slotlist = g_hash_table_get_keys(r_context()->config->slots);

	for (GList *l = slotlist; l != NULL; l = l->next) {
		g_autofree gchar *realdev = NULL;
		RaucSlot *s = g_hash_table_lookup(r_context()->config->slots, l->data);
		g_assert_nonnull(s);

		if (g_strcmp0(s->bootname, r_context()->bootslot) == 0) {
			booted = s;
			break;
		}

		if (g_strcmp0(s->name, r_context()->bootslot) == 0) {
			booted = s;
			break;
		}

		realdev = r_realpath(s->device);
		if (realdev == NULL) {
			g_message("Failed to resolve realpath for '%s'", s->device);
			realdev = g_strdup(s->device);
		}

		if (g_strcmp0(realdev, r_context()->bootslot) == 0) {
			booted = s;
			break;
		}
	}

	if (!booted) {
		if (g_strcmp0(r_context()->bootslot, "_external_") == 0) {
			/* mark all as inactive */
			g_debug("Marking all slots as 'inactive'");
			for (GList *l = slotlist; l != NULL; l = l->next) {
				RaucSlot *s = g_hash_table_lookup(r_context()->config->slots, l->data);
				g_assert_nonnull(s);

				s->state = ST_INACTIVE;
			}

			r_context()->config->slot_states_determined = TRUE;

			return TRUE;
		}

		g_set_error(
				error,
				R_SLOT_ERROR,
				R_SLOT_ERROR_NO_SLOT_WITH_STATE_BOOTED,
				"Did not find booted slot (matching '%s')", r_context()->bootslot);
		return FALSE;
	}

	/* Determine active group members */
	for (GList *l = slotlist; l != NULL; l = l->next) {
		RaucSlot *s = g_hash_table_lookup(r_context()->config->slots, l->data);
		g_assert_nonnull(s);

		if (s == booted) {
			s->state = ST_BOOTED;
			g_debug("Found booted slot: '%s' on '%s'", s->name, s->device);
		} else if (s->parent && s->parent == booted) {
			s->state = ST_ACTIVE;
		} else {
			s->state = ST_INACTIVE;
		}
	}

	r_context()->config->slot_states_determined = TRUE;

	return TRUE;
}

gboolean determine_boot_states(GError **error)
{
	GHashTableIter iter;
	RaucSlot *slot;
	gboolean had_errors = FALSE;

	/* get boot state */
	g_hash_table_iter_init(&iter, r_context()->config->slots);
	while (g_hash_table_iter_next(&iter, NULL, (gpointer*) &slot)) {
		g_autoptr(GError) ierror = NULL;

		if (!slot->bootname)
			continue;

		if (!r_boot_get_state(slot, &slot->boot_good, &ierror)) {
			g_message("Failed to get boot state of '%s': %s", slot->name, ierror->message);
			had_errors = TRUE;
		}
	}

	if (had_errors)
		g_set_error_literal(
				error,
				R_SLOT_ERROR,
				R_SLOT_ERROR_NO_SLOT_WITH_STATE_BOOTED,
				"Could not determine all boot states");

	return !had_errors;
}

/* Returns NULL-teminated intern string array of all classes listed in
 * given manifest.
 * Free with g_free */
static gchar** get_all_manifest_slot_classes(const RaucManifest *manifest)
{
	GPtrArray *slotclasses = NULL;

	g_return_val_if_fail(manifest, NULL);

	slotclasses = g_ptr_array_new();

	for (GList *l = manifest->images; l != NULL; l = l->next) {
		const gchar *key = NULL;
		RaucImage *iterimage = l->data;
		g_assert_nonnull(iterimage->slotclass);

		if (iterimage->artifact)
			continue;

		key = g_intern_string(iterimage->slotclass);
		g_ptr_array_remove_fast(slotclasses, (gpointer)key); /* avoid duplicates */
		g_ptr_array_add(slotclasses, (gpointer)key);
	}
	g_ptr_array_add(slotclasses, NULL);

	return (gchar**) g_ptr_array_free(slotclasses, FALSE);
}

/* Selects a single appropriate inactive slot of root slot class
 *
 * If a global status file is used and multiple candidates are available, the
 * one with the oldest 'installed' timestamp will be selected.
 * If a slot with an unset timestamp is found, this one will be preferably
 * instead.
 *
 * @param rootclass name of root slot class
 *
 * @return pointer to appropriate slot in system slot list
 */
static RaucSlot *select_inactive_slot_class_member(const gchar *rootclass)
{
	RaucSlot *iterslot;
	RaucSlot *selectslot = NULL;
	GHashTableIter iter;

	g_return_val_if_fail(rootclass, NULL);

	if (g_strcmp0(r_context()->config->statusfile_path, "per-slot") == 0) {
		g_debug("Selecting inactive slot for class '%s'. Strategy: 'first found'", rootclass);
	} else {
		g_debug("Selecting inactive slot for class '%s'. Strategy: 'oldest timestamp first')", rootclass);
	}

	g_hash_table_iter_init(&iter, r_context()->config->slots);
	while (g_hash_table_iter_next(&iter, NULL, (gpointer*) &iterslot)) {
		if (iterslot->state != ST_INACTIVE)
			continue;

		if (g_strcmp0(iterslot->sclass, rootclass) != 0)
			continue;

		/* For per-slot status, we don't try to access the timestamp information
		 * and just take the first appropriate slot */
		if (g_strcmp0(r_context()->config->statusfile_path, "per-slot") == 0) {
			g_debug("Selected slot '%s'", iterslot->name);
			return iterslot;
		}

		/* For the global slot status, context setup ensures the status is always initialized */
		g_assert_nonnull(iterslot->status);

		/* A slot that is "failed" should be updated preferably */
		if (g_strcmp0(iterslot->status->status, "failed") == 0) {
			g_debug("Slot '%s' has status 'failed'. Select it.", iterslot->name);
			return iterslot;
		}

		/* A slot without a timestamp is always considered out-of-date and updatable */
		if (!iterslot->status->installed_timestamp) {
			g_debug("Slot '%s' has no valid timestamp. Consider outdated and select it.", iterslot->name);
			return iterslot;
		}

		/* First slot found */
		if (!selectslot) {
			g_debug("Consider slot '%s' as first candidate.", iterslot->name);
			selectslot = iterslot;
			continue;
		}

		/* If currently checked slot is older than candidate, use as new candidate */
		gint comp = g_date_time_compare(iterslot->status->installed_timestamp, selectslot->status->installed_timestamp);
		if (comp < 0) {
			g_autofree gchar *found = g_date_time_format(iterslot->status->installed_timestamp, RAUC_FORMAT_ISO_8601);
			g_autofree gchar *current = g_date_time_format(selectslot->status->installed_timestamp, RAUC_FORMAT_ISO_8601);
			g_debug("Slot '%s' has older timestamp (%s) than slot '%s' (%s). Consider as new candidate.", iterslot->name, found, selectslot->name, current);
			selectslot = iterslot;
		}
	}

	if (selectslot)
		g_debug("Selected slot '%s'", selectslot->name);
	else
		g_debug("No slot selected");

	return selectslot;
}

/* Map each slot class available to a potential target slot.
 *
 * Algorithm:
 *
 * - Get all root classes (classes of slots that do not have a parent)
 * - For each root class:
 *     - select 1 (inactive) member (function)
 * -> set of selected root slots
 * -> collect target install group
 *
 * @return Newly allocated HashTable of
 *         slotclass (gchar*) -> target slot (RaucSlot *)
 */
GHashTable* determine_target_install_group(void)
{
	g_autofree gchar **rootclasses = NULL;
	GHashTable *targetgroup = NULL;
	GHashTableIter iter;
	RaucSlot *iterslot = NULL;
	g_autoptr(GList) selected_root_slots = NULL;

	r_context_begin_step("determine_target_install_group", "Determining target install group", 0);

	/* collect all root classes available in system.conf */
	rootclasses = r_slot_get_root_classes(r_context()->config->slots);

	for (gchar **rootslot = rootclasses; *rootslot != NULL; rootslot++) {
		RaucSlot *selected = NULL;

		selected = select_inactive_slot_class_member(*rootslot);

		if (selected == NULL)
			continue;

		selected_root_slots = g_list_append(selected_root_slots, selected);
	}

	targetgroup = g_hash_table_new(g_str_hash, g_str_equal);

	/* Now, iterate over all slots available and add those who's parent are
	 * in the selected root slots */
	g_hash_table_iter_init(&iter, r_context()->config->slots);
	while (g_hash_table_iter_next(&iter, NULL, (gpointer*) &iterslot)) {
		RaucSlot *parent = r_slot_get_parent_root(iterslot);
		g_debug("Checking slot: '%s'", iterslot->name);

		if (r_slot_list_contains(selected_root_slots, parent)) {
			g_debug("\tAdding mapping: '%s' -> '%s'", iterslot->sclass, iterslot->name);
			g_hash_table_insert(targetgroup, (gpointer) iterslot->sclass, iterslot);
		} else {
			g_debug("\tNo mapping found");
		}
	}

	r_context_end_step("determine_target_install_group", TRUE);

	return targetgroup;
}

void r_image_install_plan_free(gpointer value)
{
	RImageInstallPlan *plan = (RImageInstallPlan*)value;

	if (!plan)
		return;

	g_free(plan);
}

G_DEFINE_AUTOPTR_CLEANUP_FUNC(RImageInstallPlan, r_image_install_plan_free);

GPtrArray* r_install_make_plans(const RaucManifest *manifest, GHashTable *target_group, GError **error)
{
	GError *ierror = NULL;
	g_autofree gchar **slotclasses = NULL;
	g_autoptr(GPtrArray) install_plans = g_ptr_array_new_with_free_func(r_image_install_plan_free);

	g_return_val_if_fail(manifest != NULL, NULL);
	g_return_val_if_fail(target_group != NULL, NULL);
	g_return_val_if_fail(error == NULL || *error == NULL, NULL);

	slotclasses = get_all_manifest_slot_classes(manifest);

	/* Find exactly 1 image for each slot class listed in manifest */
	for (gchar **cls = slotclasses; *cls != NULL; cls++) {
		RaucImage *matching_img = NULL;
		g_autoptr(RImageInstallPlan) plan = g_new0(RImageInstallPlan, 1);

		for (GList *l = manifest->images; l != NULL; l = l->next) {
			RaucImage *lookup_image = l->data;

			/* Not interested in slots of other classes */
			if (g_strcmp0(lookup_image->slotclass, *cls) != 0)
				continue;

			/* If this is a default variant and we have no better
			 * match yet, use it and continue scanning.
			 * Otherwise test if it is our variant and directly use
			 * it if so */
			if (lookup_image->variant == NULL) {
				if (!matching_img)
					matching_img = lookup_image;
			} else if (g_strcmp0(lookup_image->variant, r_context()->config->system_variant) == 0) {
				g_debug("Using variant '%s' image '%s' for '%s'", lookup_image->variant, lookup_image->filename, lookup_image->slotclass);
				matching_img = lookup_image;
				break;
			}
		}

		/* If we have an image for a class in the manifest but none
		 * that matches our variant, we assume this to be a failure */
		if (!matching_img) {
			g_set_error(error,
					R_INSTALL_ERROR,
					R_INSTALL_ERROR_FAILED,
					"Failed to find matching variant of image for slot class '%s'", *cls);
			return NULL;
		}

		g_debug("Found image mapping: '%s' -> '%s'", matching_img->filename, matching_img->slotclass);
		plan->image = matching_img;

		/* Check if target_group contains an appropriate slot for this image */
		plan->target_slot = g_hash_table_lookup(target_group, matching_img->slotclass);
		if (!plan->target_slot) {
			g_set_error(error,
					R_INSTALL_ERROR,
					R_INSTALL_ERROR_FAILED,
					"No target slot for class '%s' of image '%s' found", matching_img->slotclass, matching_img->filename);
			return NULL;
		}
		if (plan->target_slot->readonly) {
			g_set_error(error,
					R_INSTALL_ERROR,
					R_INSTALL_ERROR_FAILED,
					"Target slot for class '%s' of image '%s' is readonly", matching_img->slotclass, matching_img->filename);
			return NULL;
		}

		/* determine whether update image type is compatible with destination slot type */
		plan->slot_handler = get_update_handler(plan->image, plan->target_slot, &ierror);
		if (plan->slot_handler == NULL) {
			g_propagate_error(error, ierror);
			return NULL;
		}

		g_ptr_array_add(install_plans, g_steal_pointer(&plan));
	}

	/* Make plans for artifact installation */
	if (!r_artifacts_init(&ierror)) {
		g_propagate_error(error, ierror);
		return NULL;
	}
	/* TODO: This may remove objects for a composefs image we are about to install. */
	if (!r_artifacts_prune(&ierror)) {
		g_propagate_error(error, ierror);
		return NULL;
	}

	for (GList *l = manifest->images; l != NULL; l = l->next) {
		RaucImage *iter_image = l->data;

		if (!iter_image->artifact)
			continue;

		g_autoptr(RImageInstallPlan) plan = g_new0(RImageInstallPlan, 1);
		plan->image = l->data;
		plan->target_repo = g_hash_table_lookup(r_context()->config->artifact_repos, iter_image->slotclass);
		if (!plan->target_repo) {
			g_set_error(error,
					R_INSTALL_ERROR,
					R_INSTALL_ERROR_FAILED,
					"No target repo '%s' for artifact image '%s' found", iter_image->slotclass, iter_image->artifact);
			return NULL;
		}

		g_ptr_array_add(install_plans, g_steal_pointer(&plan));
	}

	if (install_plans->len == 0) {
		g_set_error_literal(error,
				R_INSTALL_ERROR,
				R_INSTALL_ERROR_FAILED,
				"No installable image found");
		return NULL;
	}

	return g_steal_pointer(&install_plans);
}

static gchar* parse_handler_output(gchar* line)
{
	gchar *message = NULL;
	g_auto(GStrv) split = NULL;

	g_assert_nonnull(line);

	if (!g_str_has_prefix(line, "<< ")) {
		g_print("# %s\n", line);
		return NULL;
	}

	split = g_strsplit(line, " ", 5);

	if (!split[1])
		return NULL;

	if (g_strcmp0(split[1], "handler") == 0) {
		message = g_strdup_printf("Handler status: %s", split[2]);
	} else if (g_strcmp0(split[1], "image") == 0) {
		message = g_strdup_printf("Image '%s' status: %s", split[2], split[3]);
	} else if (g_strcmp0(split[1], "bootloader") == 0) {
		message = g_strdup_printf("Bootloader status: %s", split[2]);
	} else if (g_strcmp0(split[1], "error") == 0) {
		g_autofree gchar *joined = g_strjoinv(" ", &split[2]);
		message = g_strdup_printf("Error: %s", joined);
	} else if (g_strcmp0(split[1], "debug") == 0) {
		g_autofree gchar *joined = g_strjoinv(" ", &split[2]);
		message = g_strdup_printf("Debug: %s", joined);
	} else {
		message = g_strdup_printf("Unknown handler output: %s", line);
	}

	return message;
}

static gboolean verify_compatible(RaucInstallArgs *args, RaucManifest *manifest, GError **error)
{
	if (args->ignore_compatible) {
		return TRUE;
	} else if (g_strcmp0(r_context()->config->system_compatible,
			manifest->update_compatible) == 0) {
		return TRUE;
	} else {
		g_set_error(error, R_INSTALL_ERROR, R_INSTALL_ERROR_COMPAT_MISMATCH,
				"Compatible mismatch: Expected '%s' but bundle manifest has '%s'",
				r_context()->config->system_compatible,
				manifest->update_compatible);
		return FALSE;
	}
}

static gboolean check_version_limits(RaucInstallArgs *args, RaucManifest *manifest, GError **error)
{
	GError *ierror = NULL;

	g_return_val_if_fail(args, FALSE);
	g_return_val_if_fail(manifest, FALSE);
	g_return_val_if_fail(error == NULL || *error == NULL, FALSE);

	if (!r_context()->config->system_min_bundle_version) {
		g_debug("No min-bundle-version configured in the system.conf. Version-limit check does nothing.");
		return TRUE;
	}

	if (args->ignore_version_limit) {
		g_message("Explicitly ignoring bundle version limit check.");
		return TRUE;
	}

	if (!manifest->update_version) {
		g_set_error(error, R_INSTALL_ERROR, R_INSTALL_ERROR_VERSION_MISMATCH,
				"Version mismatch: Expected at least '%s' but bundle manifest has no version",
				r_context()->config->system_min_bundle_version);
		return FALSE;
	}

	if (!r_semver_less_equal(
			r_context()->config->system_min_bundle_version,
			manifest->update_version,
			&ierror)) {
		if (ierror) {
			g_propagate_error(error, ierror);
			return FALSE;
		} else {
			g_set_error(error, R_INSTALL_ERROR, R_INSTALL_ERROR_VERSION_MISMATCH,
					"Version mismatch: Expected at least '%s' but bundle manifest has '%s'",
					r_context()->config->system_min_bundle_version,
					manifest->update_version);
			return FALSE;
		}
	}
	return TRUE;
}

static gchar **add_system_environment(gchar **envp)
{
	GHashTableIter iter;
	const gchar *key;
	const gchar *value;

	g_return_val_if_fail(envp, NULL);

	envp = g_environ_setenv(envp, "RAUC_SYSTEM_CONFIG", r_context()->configpath, TRUE);
	envp = g_environ_setenv(envp, "RAUC_SYSTEM_VARIANT", r_context()->config->system_variant ?: "", TRUE);
	envp = g_environ_setenv(envp, "RAUC_CURRENT_BOOTNAME", r_context()->bootslot, TRUE);
	envp = g_environ_setenv(envp, "RAUC_MOUNT_PREFIX", r_context()->config->mount_prefix, TRUE);

	g_assert_nonnull(r_context()->system_info);
	g_hash_table_iter_init(&iter, r_context()->system_info);
	/* Allow defining new env variables based on system-info
	 * handler, but do not override existing ones. */
	while (g_hash_table_iter_next(&iter, (gpointer*) &key, (gpointer*) &value)) {
		envp = g_environ_setenv(envp, key, value, FALSE);
	}

	return envp;
}

/**
 * Sets up an environment containing RAUC information, ready to be passed to e.g. handlers
 *
 * Extends the system environment so that the result is safe to be used with
 * g_subprocess_launcher_set_environ().
 *
 * @param update_source Path to the current bundle mount point
 * @param manifest Currently used manifest
 * @param transaction Current transaction identifier
 * @param target_group Determined target group
 *
 * @return A newly allocated List of environment variables
 */
static gchar **prepare_environment(gchar *update_source, RaucManifest *manifest, gchar *transaction, GHashTable *target_group)
{
	GHashTableIter iter;
	RaucSlot *slot;
	gint slotcnt = 0;
	g_autoptr(GString) slots = g_string_sized_new(128);
	g_autoptr(GString) target_slots = g_string_sized_new(128);

	/* get current process environment to use as base for appending */
	gchar **envp = g_get_environ();

	envp = add_system_environment(envp);
	envp = g_environ_setenv(envp, "RAUC_BUNDLE_MOUNT_POINT", update_source, TRUE);
	/* Deprecated, included for backwards compatibility: */
	envp = g_environ_setenv(envp, "RAUC_UPDATE_SOURCE", update_source, TRUE);
	envp = g_environ_setenv(envp, "RAUC_TRANSACTION_ID", transaction, TRUE);

	g_hash_table_iter_init(&iter, r_context()->config->slots);
	while (g_hash_table_iter_next(&iter, NULL, (gpointer*) &slot)) {
		gchar *varname;
		GHashTableIter iiter;
		gpointer member;

		slotcnt++;

		if (slots->len)
			g_string_append_c(slots, ' ');
		g_string_append_printf(slots, "%i", slotcnt);

		g_hash_table_iter_init(&iiter, target_group);
		while (g_hash_table_iter_next(&iiter, NULL, &member)) {
			if (slot != member) {
				continue;
			}

			/* for target slots, get image name and add number to list */
			for (GList *l = manifest->images; l != NULL; l = l->next) {
				RaucImage *img = l->data;
				if (g_str_equal(slot->sclass, img->slotclass)) {
					varname = g_strdup_printf("RAUC_IMAGE_NAME_%i", slotcnt);
					envp = g_environ_setenv(envp, varname, img->filename ?: "", TRUE);
					g_clear_pointer(&varname, g_free);

					varname = g_strdup_printf("RAUC_IMAGE_DIGEST_%i", slotcnt);
					envp = g_environ_setenv(envp, varname, img->checksum.digest ?: "", TRUE);
					g_clear_pointer(&varname, g_free);

					varname = g_strdup_printf("RAUC_IMAGE_CLASS_%i", slotcnt);
					envp = g_environ_setenv(envp, varname, img->slotclass, TRUE);
					g_clear_pointer(&varname, g_free);

					break;
				}
			}

			if (target_slots->len)
				g_string_append_c(target_slots, ' ');
			g_string_append_printf(target_slots, "%i", slotcnt);
		}

		varname = g_strdup_printf("RAUC_SLOT_NAME_%i", slotcnt);
		envp = g_environ_setenv(envp, varname, slot->name, TRUE);
		g_clear_pointer(&varname, g_free);

		varname = g_strdup_printf("RAUC_SLOT_CLASS_%i", slotcnt);
		envp = g_environ_setenv(envp, varname, slot->sclass, TRUE);
		g_clear_pointer(&varname, g_free);

		varname = g_strdup_printf("RAUC_SLOT_TYPE_%i", slotcnt);
		envp = g_environ_setenv(envp, varname, slot->type, TRUE);
		g_clear_pointer(&varname, g_free);

		varname = g_strdup_printf("RAUC_SLOT_DEVICE_%i", slotcnt);
		envp = g_environ_setenv(envp, varname, slot->device, TRUE);
		g_clear_pointer(&varname, g_free);

		varname = g_strdup_printf("RAUC_SLOT_BOOTNAME_%i", slotcnt);
		envp = g_environ_setenv(envp, varname, slot->bootname ? slot->bootname : "", TRUE);
		g_clear_pointer(&varname, g_free);

		varname = g_strdup_printf("RAUC_SLOT_PARENT_%i", slotcnt);
		envp = g_environ_setenv(envp, varname, slot->parent ? slot->parent->name : "", TRUE);
		g_clear_pointer(&varname, g_free);
	}

	envp = g_environ_setenv(envp, "RAUC_SLOTS", slots->str, TRUE);
	envp = g_environ_setenv(envp, "RAUC_TARGET_SLOTS", target_slots->str, TRUE);

	g_autoptr(GPtrArray) shell_vars = g_ptr_array_new_with_free_func(g_free);
	r_shell_from_manifest_meta(shell_vars, manifest);
	envp = r_environ_setenv_ptr_array(envp, shell_vars, FALSE);

	return envp;
}

/**
 * Launches a handler using g_subprocess and waits for it to finish.
 *
 * Messages printed by the handler to stdout or stderr are parsed and can be
 * used for generating high-level user output in RAUC.
 * See parse_handler_output().
 *
 * @param args Install args, required for user output
 * @param handler_name Path to the handler script/binary
 * @param handler_argv Argument list passed to the handler call, or NULL
 * @param override_env Environment to set for the handler call, or NULL
 * @param[out] error Return location for a GError, or NULL
 *
 * @return TRUE on success, FALSE otherwise
 */
static gboolean launch_and_wait_handler(RaucInstallArgs *args, gchar *handler_name, gchar **handler_argv, gchar **override_env, GError **error)
{
	g_autoptr(GSubprocessLauncher) handlelaunch = NULL;
	g_autoptr(GSubprocess) handleproc = NULL;
	GError *ierror = NULL;
	gboolean res = FALSE;
	g_autoptr(GPtrArray) args_array = NULL;
	GInputStream *instream = NULL;
	g_autoptr(GDataInputStream) datainstream = NULL;
	gchar *outline;

	g_return_val_if_fail(args, FALSE);
	g_return_val_if_fail(handler_name, FALSE);
	g_return_val_if_fail(error == NULL || *error == NULL, FALSE);

	handlelaunch = g_subprocess_launcher_new(G_SUBPROCESS_FLAGS_STDOUT_PIPE | G_SUBPROCESS_FLAGS_STDERR_MERGE);

	if (override_env)
		g_subprocess_launcher_set_environ(handlelaunch, override_env);

	args_array = g_ptr_array_new();
	g_ptr_array_add(args_array, handler_name);
	if (handler_argv) {
		r_ptr_array_addv(args_array, handler_argv, FALSE);
	}
	g_ptr_array_add(args_array, NULL);

	handleproc = r_subprocess_launcher_spawnv(
			handlelaunch, args_array, &ierror);
	if (handleproc == NULL) {
		g_propagate_error(error, ierror);
		goto out;
	}

	instream = g_subprocess_get_stdout_pipe(handleproc);
	datainstream = g_data_input_stream_new(instream);

	do {
		g_autofree gchar *handler_message = NULL;
		outline = g_data_input_stream_read_line(datainstream, NULL, NULL, NULL);
		if (!outline)
			continue;

		handler_message = parse_handler_output(outline);
		if (handler_message != NULL)
			install_args_update(args, "%s", handler_message);

		g_free(outline);
	} while (outline);

	res = g_subprocess_wait_check(handleproc, NULL, &ierror);
	if (!res) {
		g_propagate_error(error, ierror);
		goto out;
	}

	res = TRUE;

out:
	return res;
}

static gboolean run_bundle_hook(RaucManifest *manifest, gchar* bundledir, const gchar *hook_cmd, GError **error)
{
	g_autofree gchar *hook_name = NULL;
	g_autoptr(GSubprocessLauncher) launcher = NULL;
	g_autoptr(GSubprocess) sproc = NULL;
	GError *ierror = NULL;
	GInputStream *instream = NULL;
	g_autoptr(GDataInputStream) datainstream = NULL;
	gboolean res = FALSE;
	gchar *outline = NULL;
	g_autofree gchar *hookreturnmsg = NULL;

	g_assert_nonnull(manifest->hook_name);

	hook_name = g_build_filename(bundledir, manifest->hook_name, NULL);

	g_message("Running bundle hook '%s'", hook_cmd);

	launcher = g_subprocess_launcher_new(G_SUBPROCESS_FLAGS_STDERR_PIPE);

	g_subprocess_launcher_setenv(launcher, "RAUC_SYSTEM_COMPATIBLE", r_context()->config->system_compatible, TRUE);
	g_subprocess_launcher_setenv(launcher, "RAUC_SYSTEM_VARIANT", r_context()->config->system_variant ?: "", TRUE);

	g_subprocess_launcher_setenv(launcher, "RAUC_MF_COMPATIBLE", manifest->update_compatible, TRUE);
	g_subprocess_launcher_setenv(launcher, "RAUC_MF_VERSION", manifest->update_version ?: "", TRUE);
	g_subprocess_launcher_setenv(launcher, "RAUC_MF_BUILD", manifest->update_build ?: "", TRUE);
	g_subprocess_launcher_setenv(launcher, "RAUC_MOUNT_PREFIX", r_context()->config->mount_prefix, TRUE);

	g_autoptr(GPtrArray) shell_vars = g_ptr_array_new_with_free_func(g_free);
	r_shell_from_manifest_meta(shell_vars, manifest);
	r_subprocess_launcher_setenv_ptr_array(launcher, shell_vars, TRUE);

	sproc = g_subprocess_launcher_spawn(
			launcher, &ierror,
			hook_name,
			hook_cmd,
			NULL);
	if (sproc == NULL) {
		g_propagate_prefixed_error(
				error,
				ierror,
				"failed to start bundle hook: ");
		goto out;
	}

	/* Read scripts stderr output */
	instream = g_subprocess_get_stderr_pipe(sproc);
	datainstream = g_data_input_stream_new(instream);

	do {
		outline = g_data_input_stream_read_line(datainstream, NULL, NULL, NULL);
		if (outline) {
			g_clear_pointer(&hookreturnmsg, g_free);
			hookreturnmsg = outline;
		}
	} while (outline);

	res = g_subprocess_wait_check(sproc, NULL, &ierror);
	if (!res) {
		/* Subprocess exited with code 1 */
		if ((ierror->domain == G_SPAWN_EXIT_ERROR) && (ierror->code >= INSTALL_HOOK_REJECT_CODE)) {
			if (hookreturnmsg) {
				g_clear_error(&ierror);
				g_set_error(error, R_INSTALL_ERROR, R_INSTALL_ERROR_REJECTED,
						"Hook returned: '%s'", hookreturnmsg);
			} else {
				g_propagate_prefixed_error(
						error,
						ierror,
						"Hook returned with exit code %d: ", ierror->code);
			}
		} else {
			g_propagate_prefixed_error(
					error,
					ierror,
					"failed to run bundle hook: ");
		}
		goto out;
	}

out:
	return res;
}

static gboolean launch_and_wait_custom_handler(RaucInstallArgs *args, gchar* bundledir, RaucManifest *manifest, GHashTable *target_group, gchar **env, GError **error)
{
	GError *ierror = NULL;
	g_autofree gchar* handler_name = NULL;
	g_autoptr(GPtrArray) handler_args = NULL;
	gboolean res = FALSE;

	r_context_begin_step_weighted("launch_and_wait_custom_handler", "Launching update handler", 0, 6);

	handler_name = g_build_filename(bundledir, manifest->handler_name, NULL);
	handler_args = g_ptr_array_new_full(0, g_free);
	if (manifest->handler_args) {
		g_auto(GStrv) handler_argvp = NULL;
		res = g_shell_parse_argv(manifest->handler_args, NULL, &handler_argvp, &ierror);
		if (!res) {
			g_propagate_error(error, ierror);
			goto out;
		}
		r_ptr_array_addv(handler_args, handler_argvp, TRUE);
	}
	if (r_context()->handlerextra) {
		g_auto(GStrv) extra_argvp = NULL;
		res = g_shell_parse_argv(r_context()->handlerextra, NULL, &extra_argvp, &ierror);
		if (!res) {
			g_propagate_error(error, ierror);
			goto out;
		}
		r_ptr_array_addv(handler_args, extra_argvp, TRUE);
	}
	g_ptr_array_add(handler_args, NULL);

	res = launch_and_wait_handler(args, handler_name, (gchar**) handler_args->pdata, env, error);

out:
	r_context_end_step("launch_and_wait_custom_handler", res);
	return res;
}

static gboolean pre_install_check_slot_mount_status(RaucSlot *slot, RaucImage *mfimage, GError **error)
{
	/* OK if the slot is not mounted at all. */
	if (!(slot->mount_point || slot->ext_mount_point))
		return TRUE;

	/* OK if the configuration says it may already be mounted and the
	 * bundle has a custom install hook. */
	if (slot->allow_mounted && mfimage->hooks.install)
		return TRUE;

	if (slot->allow_mounted)
		g_set_error(error, R_INSTALL_ERROR, R_INSTALL_ERROR_MOUNTED,
				"Mounted device '%s' may only be updated by a custom install hook", slot->device);
	else
		g_set_error(error, R_INSTALL_ERROR, R_INSTALL_ERROR_MOUNTED,
				"Destination device '%s' already mounted", slot->device);

	return FALSE;
}

static gboolean pre_install_checks(gchar* bundledir, GPtrArray *install_plans, GHashTable *target_group, GError **error)
{
	for (guint i = 0; i < install_plans->len; i++) {
		const RImageInstallPlan *plan = g_ptr_array_index(install_plans, i);

		if (!plan->image->filename) {
			/* having no filename is valid for install hook only */
			if (plan->image->hooks.install)
				goto skip_filename_checks;
			else
				/* Should not be reached as the pre-conditions for optional 'filename' are already
				 * checked during manifest parsing in manifest.c: parse_image() */
				g_assert_not_reached();
		}

		/* if image filename is relative, make it absolute */
		if (!g_path_is_absolute(plan->image->filename)) {
			gchar *filename = g_build_filename(bundledir, plan->image->filename, NULL);
			g_free(plan->image->filename);
			plan->image->filename = filename;
		}

		if (!g_file_test(plan->image->filename, G_FILE_TEST_EXISTS)) {
			if (!plan->image->converted || plan->image->converted->len == 0) {
				g_set_error(error, G_FILE_ERROR, G_FILE_ERROR_NOENT,
						"Source image '%s' not found in bundle", plan->image->filename);
				return FALSE;
			} else {
				g_debug("Have converted images, ignoring missing source image '%s'", plan->image->filename);
			}
		}

		/* handle converted images as well */
		if (plan->image->converted)
			for (guint j = 0; j < plan->image->converted->len; j++) {
				gchar **converted = (gchar**)&plan->image->converted->pdata[j];
				if (!g_path_is_absolute(*converted)) {
					gchar *filename = g_build_filename(bundledir, *converted, NULL);
					g_free(*converted);
					*converted = filename;
				}

				if (!g_file_test(*converted, G_FILE_TEST_EXISTS)) {
					g_set_error(error, G_FILE_ERROR, G_FILE_ERROR_NOENT,
							"Converted source image '%s' not found in bundle", *converted);
					return FALSE;
				}
			}

skip_filename_checks:
		if (plan->target_slot) {
			g_assert(plan->target_repo == NULL);

			if (!g_file_test(plan->target_slot->device, G_FILE_TEST_EXISTS)) {
				g_set_error(error, G_FILE_ERROR, G_FILE_ERROR_NOENT,
						"Destination device '%s' for slot '%s' not found", plan->target_slot->device, plan->target_slot->name);
				return FALSE;
			}

			if (!pre_install_check_slot_mount_status(plan->target_slot, plan->image, error)) {
				/* error is already set */
				return FALSE;
			}
		} else if (plan->target_repo) {
			g_assert(plan->target_slot == NULL);

			if (!g_file_test(plan->target_repo->path, G_FILE_TEST_EXISTS)) {
				g_set_error(error, G_FILE_ERROR, G_FILE_ERROR_NOENT,
						"Destination path '%s' not found for artifact repo '%s'", plan->target_repo->path, plan->target_repo->name);
				return FALSE;
			}
		} else {
			g_error("Inconsistency detected: image install plan has no target");
			return FALSE;
		}
	}

	return TRUE;
}

static void update_slot_status(RaucSlotStatus *slot_state, const gchar* status, const RaucManifest *manifest, const RImageInstallPlan *plan, const RaucInstallArgs *args)
{
	r_slot_clear_status(slot_state);

	slot_state->bundle_compatible = g_strdup(manifest->update_compatible);
	slot_state->bundle_version = g_strdup(manifest->update_version);
	slot_state->bundle_description = g_strdup(manifest->update_description);
	slot_state->bundle_build = g_strdup(manifest->update_build);
	slot_state->bundle_hash = g_strdup(manifest->hash);
	slot_state->status = g_strdup(status);
	slot_state->checksum.type = plan->image->checksum.type;
	slot_state->checksum.digest = g_strdup(plan->image->checksum.digest);
	slot_state->checksum.size = plan->image->checksum.size;
	slot_state->installed_txn = g_strdup(args->transaction);
	slot_state->installed_timestamp = g_date_time_new_now_utc();
	slot_state->installed_count++;
}

static gboolean handle_slot_install_plan(const RaucManifest *manifest, const RImageInstallPlan *plan, RaucInstallArgs *args, const char *hook_name, GError **error)
{
	GError *ierror = NULL;
	RaucSlotStatus *slot_state = NULL;

	install_args_update(args, "Checking slot %s", plan->target_slot->name);

	r_context_begin_step_weighted_formatted("check_slot", 0, 1, "Checking slot %s%s%s%s",
			plan->target_slot->name,
			plan->target_slot->bootname ? " (" : "",
			plan->target_slot->bootname ? plan->target_slot->bootname : "",
			plan->target_slot->bootname ? ")" : "");

	r_slot_status_load(plan->target_slot);
	slot_state = plan->target_slot->status;

	/* In case we failed unmounting while reading per-slot status
	 * file, abort here */
	if (plan->target_slot->mount_point) {
		g_set_error(error, R_INSTALL_ERROR, R_INSTALL_ERROR_MOUNTED,
				"Slot '%s' still mounted", plan->target_slot->device);
		r_context_end_step("check_slot", FALSE);
		return FALSE;
	}

	/* if explicitly enabled, skip update of up-to-date slots */
	if (!plan->target_slot->install_same && g_strcmp0(slot_state->status, "ok") == 0 && g_strcmp0(plan->image->checksum.digest, slot_state->checksum.digest) == 0) {
		install_args_update(args, "Skipping update for correct image '%s'", plan->image->filename);
		g_message("Skipping update for correct image '%s'", plan->image->filename);
		r_context_end_step("check_slot", TRUE);

		/* Dummy step to indicate slot was skipped and complete required 'update_slots' substeps */
		r_context_begin_step_weighted_formatted("skip_image", 0, 9, "Copying image skipped");

		/* Update the status also for skipped slots */
		g_message("Updating slot %s status", plan->target_slot->name);
		update_slot_status(slot_state, "ok", manifest, plan, args);
		if (!r_slot_status_save(plan->target_slot, &ierror)) {
			g_propagate_prefixed_error(error, ierror, "Error while writing status file: ");
			r_context_end_step("skip_image", FALSE);
			return FALSE;
		}

		r_context_end_step("skip_image", TRUE);

		install_args_update(args, "Updating slot %s done", plan->target_slot->name);
		return TRUE;
	}

	/* For global slot status: Clear checksum info and make status
	 * 'pending' to prevent the slot status from looking valid later in
	 * case we crash while installing. */
	if (g_strcmp0(r_context()->config->statusfile_path, "per-slot") != 0) {
		g_clear_pointer(&slot_state->status, g_free);
		slot_state->status = g_strdup("pending");

		g_autofree gchar *old_digest = g_steal_pointer(&slot_state->checksum.digest);
		slot_state->checksum.size = 0;

		if (!r_slot_move_checksum_data_directory(plan->target_slot, old_digest, NULL, &ierror)) {
			g_warning("Failed to move slot data directory, but will try to continue: %s", ierror->message);
			g_clear_error(&ierror);
		}

		if (!r_slot_status_save(plan->target_slot, &ierror)) {
			g_propagate_prefixed_error(error, ierror, "Error while writing status file: ");
			r_context_end_step("check_slot", FALSE);
			return FALSE;
		}
	}

	g_free(slot_state->status);
	slot_state->status = g_strdup("update");

	r_context_end_step("check_slot", TRUE);

	install_args_update(args, "Updating slot %s", plan->target_slot->name);
	r_event_log_message(R_EVENT_LOG_TYPE_WRITE_SLOT, "Updating slot %s", plan->target_slot->name);

	/* update slot */
	if (plan->image->hooks.install) {
		g_message("Updating %s with 'install' slot hook", plan->target_slot->device);
	} else {
		if (plan->image->variant)
			g_message("Updating %s with %s (variant: %s)", plan->target_slot->device, plan->image->filename, plan->image->variant);
		else
			g_message("Updating %s with %s", plan->target_slot->device, plan->image->filename);
	}

	r_context_begin_step_weighted_formatted("copy_image", 0, 9, "Copying image to %s", plan->target_slot->name);

	if (!plan->slot_handler(plan->image, plan->target_slot, hook_name, &ierror)) {
		g_autoptr(GError) ierror_status = NULL;

		g_propagate_prefixed_error(error, ierror,
				"Failed updating slot %s: ", plan->target_slot->name);
		r_context_end_step("copy_image", FALSE);

		g_message("Updating slot %s status", plan->target_slot->name);
		update_slot_status(slot_state, "failed", manifest, plan, args);
		if (!r_slot_status_save(plan->target_slot, &ierror_status)) {
			g_warning("Error while writing status file after slot update failure: %s", ierror_status->message);
		}

		return FALSE;
	}

	r_context_end_step("copy_image", TRUE);

	g_message("Updating slot %s status", plan->target_slot->name);
	update_slot_status(slot_state, "ok", manifest, plan, args);
	if (!r_slot_status_save(plan->target_slot, &ierror)) {
		g_propagate_prefixed_error(error, ierror, "Error while writing status file: ");
		return FALSE;
	}

	install_args_update(args, "Updating slot %s done", plan->target_slot->name);
	return TRUE;
}

/* For each installation plan list, there should be one slot that we need to
 * mark bad and active for the bootloader.
 * In cases where we have only images for slots that are not part of the
 * redundancy scheme (e.g. bootloader-only updates), having no such slot at all
 * is also valid */
static RaucSlot* get_boot_mark_slot(const GPtrArray *install_plans)
{
	RaucSlot *bootslot = NULL;

	g_return_val_if_fail(install_plans, NULL);

	for (guint i = 0; i < install_plans->len; i++) {
		const RImageInstallPlan *plan = g_ptr_array_index(install_plans, i);

		if (!plan->target_slot) {
			continue;
		}

		if (plan->target_slot->parent || !plan->target_slot->bootname) {
			continue;
		}

		if (bootslot) {
			g_error("Inconsistency detected: "
					"Would need to activate more than one slot."
					"At least %s and %s have a bootname set and are about to be updated",
					bootslot->name, plan->target_slot->name);
		}

		bootslot = plan->target_slot;
	}

	return bootslot;
}

#define MESSAGE_ID_INSTALLATION_STARTED   "b05410e8a93345389cd061aab1e9516d"
#define MESSAGE_ID_INSTALLATION_SUCCEEDED "0163db5468ac4237b090d28490c301ed"
#define MESSAGE_ID_INSTALLATION_FAILED    "c48141f7fd49443aafff862b4809168f"
#define MESSAGE_ID_INSTALLATION_REJECTED  "60bea7e4fea549ccad68af457308b13a"

static void log_event_installation_started(RaucInstallArgs *args)
{
	g_log_structured(R_EVENT_LOG_DOMAIN, G_LOG_LEVEL_MESSAGE,
			"RAUC_EVENT_TYPE", "install",
			"MESSAGE_ID", MESSAGE_ID_INSTALLATION_STARTED,
			"TRANSACTION_ID", args->transaction,
			"MESSAGE", "Installation %.8s started", args->transaction // truncate ID for readability
			);
}

/**
 * @param args RaucInstallArgs
 * @param manifest Manifest
 * @param GError Error or NULL
 */
static void log_event_installation_done(RaucInstallArgs *args, RaucManifest *manifest, const GError *error)
{
	g_autofree gchar *formatted = NULL;
	GLogField fields[] = {
		{"MESSAGE", NULL, -1},
		{"MESSAGE_ID", NULL, -1},
		{"PRIORITY", r_event_log_level_to_priority(G_LOG_LEVEL_MESSAGE), -1},
		{"GLIB_DOMAIN", R_EVENT_LOG_DOMAIN, -1},
		{"RAUC_EVENT_TYPE", "install", -1},
		{"BUNDLE_HASH", "", -1},
		{"BUNDLE_DESCRIPTION", "", -1},
		{"BUNDLE_VERSION", "", -1},
		{"TRANSACTION_ID", args->transaction, -1},
	};

	g_return_if_fail(args);

	if (error) {
		if (g_error_matches(error, R_INSTALL_ERROR, R_INSTALL_ERROR_REJECTED) ||
		    g_error_matches(error, R_INSTALL_ERROR, R_INSTALL_ERROR_COMPAT_MISMATCH)) {
			formatted = g_strdup_printf("Installation %.8s rejected: %s", args->transaction, error->message);
			fields[1].value = MESSAGE_ID_INSTALLATION_REJECTED;
		} else {
			formatted = g_strdup_printf("Installation %.8s failed: %s", args->transaction, error->message);
			fields[1].value = MESSAGE_ID_INSTALLATION_FAILED;
		}
	} else {
		formatted = g_strdup_printf("Installation %.8s succeeded", args->transaction);
		fields[1].value = MESSAGE_ID_INSTALLATION_SUCCEEDED;
	}

	fields[0].value = formatted;
	if (manifest) {
		fields[5].value = manifest->hash ?: "";
		fields[6].value = manifest->update_description ?: "";
		fields[7].value = manifest->update_version ?: "";
	}

	g_log_structured_array(G_LOG_LEVEL_MESSAGE, fields, G_N_ELEMENTS(fields));
}

static gboolean remove_old_artifacts(const RaucManifest *manifest, RArtifactRepo *repo, GError **error)
{
	GError *ierror = NULL;

	g_return_val_if_fail(manifest, FALSE);
	g_return_val_if_fail(repo, FALSE);
	g_return_val_if_fail(error == NULL || *error == NULL, FALSE);

	/* Remove references to old artifacts in this repo which are not in the manifest. */
	/* The symlinks and data will be removed later when pruning. */
	GHashTableIter iter;
	g_hash_table_iter_init(&iter, repo->artifacts);
	const gchar *a_name = NULL;
	GHashTable *inner = NULL;
	while (g_hash_table_iter_next(&iter, (gpointer*)&a_name, (gpointer*)&inner)) {
		if (r_manifest_has_artifact_image(manifest, repo->name, a_name)) {
			/* The manifest has an image for this artifact. */
			continue;
		}

		GHashTableIter inner_iter;
		g_hash_table_iter_init(&inner_iter, inner);
		RArtifact *artifact = NULL;
		while (g_hash_table_iter_next(&inner_iter, NULL, (gpointer*)&artifact)) {
			g_assert(artifact->references != NULL);

			g_message("Deactivating artifact '%s' in repo '%s', because it is not in the new manifest", a_name, repo->name);

			/* TODO support repos with multiple parents, perhaps with r_artifact_deactivate */
			g_ptr_array_set_size(artifact->references, 0);
		}
	}

	if (!r_artifact_repo_commit(repo, &ierror)) {
		g_propagate_error(error, ierror);
		return FALSE;
	}

	return TRUE;
}

static gboolean handle_artifact_install_plan(const RaucManifest *manifest, const RImageInstallPlan *plan, RaucInstallArgs *args, const char *hook_name, GError **error)
{
	GError *ierror = NULL;

	g_return_val_if_fail(manifest, FALSE);
	g_return_val_if_fail(plan, FALSE);
	g_return_val_if_fail(args, FALSE);
	g_return_val_if_fail(error == NULL || *error == NULL, FALSE);

	r_context_begin_step_weighted_formatted("check_repo", 0, 1, "Checking repo '%s'", plan->target_repo->name);
	if (!remove_old_artifacts(manifest, plan->target_repo, &ierror)) {
		g_propagate_error(error, ierror);
		r_context_end_step("check_repo", FALSE);
		return FALSE;
	}

	/* check for existing artifact */
	RArtifact *artifact = r_artifact_find(plan->target_repo, plan->image->artifact, plan->image->checksum.digest);
	gboolean need_install = FALSE;
	if (!artifact) {
		/* create artifact */
		g_autoptr(RArtifact) artifact_owned = g_new0(RArtifact, 1);
		artifact = artifact_owned;

		artifact->name = g_intern_string(plan->image->artifact);
		artifact->bundle_compatible = g_strdup(manifest->update_compatible);
		artifact->bundle_version = g_strdup(manifest->update_version);
		artifact->bundle_description = g_strdup(manifest->update_description);
		artifact->bundle_build = g_strdup(manifest->update_build);
		artifact->bundle_hash = g_strdup(manifest->hash);
		artifact->checksum.digest = g_strdup(plan->image->checksum.digest);
		artifact->checksum.size = plan->image->checksum.size;
		artifact->checksum.type = plan->image->checksum.type;
		artifact->references = g_ptr_array_new();

		/* find target name */
		if (!r_artifact_repo_insert(plan->target_repo, artifact, &ierror)) {
			g_propagate_error(error, ierror);
			r_context_end_step("check_repo", FALSE);
			return FALSE;
		}
		artifact_owned = NULL; /* it now belongs to the repo */
		need_install = TRUE;
	}
	r_context_end_step("check_repo", TRUE);

	r_event_log_message(R_EVENT_LOG_TYPE_WRITE_SLOT, "Updating artifact '%s' in repo '%s'", artifact->name, plan->target_repo->name);

	if (need_install) {
		r_context_begin_step_weighted_formatted("copy_image", 0, 9, "Copying artifact image to repo '%s'", plan->target_repo->name);

		if (!r_artifact_install(artifact, plan->image, &ierror)) {
			g_propagate_error(error, ierror);
			r_context_end_step("copy_image", FALSE);
			return FALSE;
		}
	} else {
		r_context_begin_step_weighted_formatted("copy_image", 0, 9, "Reusing artifact image in repo '%s'", plan->target_repo->name);
	}

	/* update links (commit) */
	g_assert(artifact->repo->parent_class == NULL); /* TODO handle repos with parents */
	r_artifact_activate(artifact, (gpointer)g_intern_static_string(""));
	if (!r_artifact_repo_commit(plan->target_repo, &ierror)) {
		g_propagate_error(error, ierror);
		r_context_end_step("copy_image", FALSE);
		return FALSE;
	}

	r_context_end_step("copy_image", TRUE);

	install_args_update(args, "Updating artifact '%s' in repo '%s' done", plan->image->artifact, plan->target_repo->name);
	return TRUE;
}

static gboolean launch_and_wait_default_handler(RaucInstallArgs *args, gchar* bundledir, RaucManifest *manifest, GHashTable *target_group, GError **error)
{
	g_autofree gchar *hook_name = NULL;
	GError *ierror = NULL;
	g_autoptr(GPtrArray) install_plans = NULL;
	RaucSlot *boot_mark_slot = NULL;

	install_plans = r_install_make_plans(manifest, target_group, &ierror);
	if (install_plans == NULL) {
		g_propagate_error(error, ierror);
		return FALSE;
	}

	boot_mark_slot = get_boot_mark_slot(install_plans);

	if (!pre_install_checks(bundledir, install_plans, target_group, &ierror)) {
		g_propagate_error(error, ierror);
		return FALSE;
	}

	if (boot_mark_slot) {
		/* Mark boot slot non-bootable */
		g_message("Marking target slot %s as non-bootable (bad)...", boot_mark_slot->name);
		if (!r_mark_bad(boot_mark_slot, &ierror)) {
			g_set_error(error, R_INSTALL_ERROR, R_INSTALL_ERROR_MARK_NONBOOTABLE,
					"Failed marking slot %s non-bootable (bad): %s", boot_mark_slot->name, ierror->message);
			g_clear_error(&ierror);
			return FALSE;
		}
	}

	if (manifest->hook_name)
		hook_name = g_build_filename(bundledir, manifest->hook_name, NULL);

	r_context_begin_step_weighted("update_slots", "Updating slots", install_plans->len * 10, 6);
	install_args_update(args, "Updating slots...");

	for (guint i = 0; i < install_plans->len; i++) {
		const RImageInstallPlan *plan = g_ptr_array_index(install_plans, i);

		if (plan->target_slot) {
			if (!handle_slot_install_plan(manifest, plan, args, hook_name, &ierror)) {
				g_propagate_error(error, ierror);
				r_context_end_step("update_slots", FALSE);
				return FALSE;
			}
		} else if (plan->target_repo) {
			if (!handle_artifact_install_plan(manifest, plan, args, hook_name, &ierror)) {
				g_propagate_error(error, ierror);
				r_context_end_step("update_slots", FALSE);
				return FALSE;
			}
		}
	}

	/* Remove unused artifacts if we were successful so far. */
	if (!r_artifacts_prune(&ierror)) {
		g_propagate_error(error, ierror);
		return FALSE;
	}

	r_context_end_step("update_slots", TRUE);
	install_args_update(args, "All slots updated");

	if (boot_mark_slot) {
		if (r_context()->config->activate_installed) {
			/* Mark boot slot bootable */
			g_message("Marking target slot %s as bootable (active/primary)...", boot_mark_slot->name);
			if (!r_mark_active(boot_mark_slot, &ierror)) {
				g_propagate_prefixed_error(error, ierror,
						"Failed marking slot %s bootable (active/primary): ", boot_mark_slot->name);
				return FALSE;
			}
		} else {
			g_message("Leaving target slot non-bootable as requested by activate_installed == false.");
		}
	}

	return TRUE;
}

gboolean do_install_bundle(RaucInstallArgs *args, GError **error)
{
	const gchar* bundlefile = args->name;
	GError *ierror = NULL;
	gboolean res = FALSE;
	g_autoptr(RaucBundle) bundle = NULL;
	g_autoptr(GHashTable) target_group = NULL;
	g_auto(GStrv) handler_env = NULL;

	g_assert_nonnull(bundlefile);
	g_assert_null(r_context()->install_info->mounted_bundle);
	g_assert_true(r_context()->config->slot_states_determined);

	if (!args->transaction)
		args->transaction = g_uuid_string_random();

	r_context_begin_step("do_install_bundle", "Installing", 10);

	log_event_installation_started(args);

	r_context_begin_step("determine_slot_states", "Determining slot states", 0);
	res = update_external_mount_points(&ierror);
	r_context_end_step("determine_slot_states", res);
	if (!res) {
		g_propagate_error(error, ierror);
		goto out;
	}

	// TODO: mount info in context ?
	install_args_update(args, "Checking and mounting bundle...");

	args->access_args.http_info_headers = assemble_info_headers(args->transaction);

	res = check_bundle(bundlefile, &bundle, CHECK_BUNDLE_DEFAULT, &args->access_args, &ierror);
	if (!res) {
		g_propagate_error(error, ierror);
		goto out;
	}

	if (args->require_manifest_hash) {
		if (!bundle->manifest) {
			/* only plain bundles have no manifest at this point */
			g_set_error(error, R_INSTALL_ERROR, R_INSTALL_ERROR_REJECTED, "Refusing to install plain bundle when using require-manifest-hash");
			res = FALSE;
			goto out;
		}
		if (g_strcmp0(args->require_manifest_hash, bundle->manifest->hash) != 0) {
			g_set_error(error, R_INSTALL_ERROR, R_INSTALL_ERROR_REJECTED, "Refusing to install bundle with unexpected hash (expected %s, got %s)",
					args->require_manifest_hash, bundle->manifest->hash);
			res = FALSE;
			goto out;
		}
	}

	if (bundle->manifest && bundle->manifest->bundle_format == R_MANIFEST_FORMAT_CRYPT && !bundle->was_encrypted) {
		g_set_error(error, R_INSTALL_ERROR, R_INSTALL_ERROR_REJECTED, "Refusing to install unencrypted crypt bundles");
		res = FALSE;
		goto out;
	}

	res = mount_bundle(bundle, &ierror);
	if (!res) {
		g_propagate_prefixed_error(
				error,
				ierror,
				"Failed mounting bundle: ");
		goto umount;
	}

	r_context()->install_info->mounted_bundle = bundle;

	target_group = determine_target_install_group();
	if (!target_group) {
		g_set_error_literal(error, R_INSTALL_ERROR, R_INSTALL_ERROR_TARGET_GROUP, "Could not determine target group");
		res = FALSE;
		goto umount;
	}

	handler_env = prepare_environment(bundle->mount_point, bundle->manifest, args->transaction, target_group);

	if (r_context()->config->preinstall_handler) {
		g_message("Starting pre install handler: %s", r_context()->config->preinstall_handler);
		res = launch_and_wait_handler(args, r_context()->config->preinstall_handler, NULL, handler_env, &ierror);
		if (!res) {
			g_propagate_prefixed_error(error, ierror, "Pre-install handler error: ");
			goto umount;
		}
	}

	/* Allow overriding compatible check by hook */
	if (bundle->manifest->hooks.install_check) {
		run_bundle_hook(bundle->manifest, bundle->mount_point, "install-check", &ierror);
		if (ierror) {
			res = FALSE;
			if (g_error_matches(ierror, R_INSTALL_ERROR, R_INSTALL_ERROR_REJECTED)) {
				g_propagate_prefixed_error(
						error,
						ierror,
						"Bundle rejected: ");
			} else {
				g_propagate_prefixed_error(
						error,
						ierror,
						"Install-check hook failed: ");
			}
			goto umount;
		}
	} else if (!verify_compatible(args, bundle->manifest, &ierror)) {
		res = FALSE;
		g_propagate_error(error, ierror);
		goto umount;
	}

	if (!check_version_limits(args, bundle->manifest, &ierror)) {
		res = FALSE;
		g_propagate_error(error, ierror);
		goto umount;
	}

	if (bundle->manifest->handler_name) {
		g_message("Using custom handler: %s", bundle->manifest->handler_name);
		res = launch_and_wait_custom_handler(args, bundle->mount_point, bundle->manifest, target_group, handler_env, &ierror);
	} else {
		g_debug("Using default installation handler");
		res = launch_and_wait_default_handler(args, bundle->mount_point, bundle->manifest, target_group, &ierror);
	}

	if (!res) {
		g_propagate_prefixed_error(error, ierror, "Installation error: ");
		goto umount;
	}

	if (r_context()->config->postinstall_handler) {
		g_message("Starting post install handler: %s", r_context()->config->postinstall_handler);
		res = launch_and_wait_handler(args, r_context()->config->postinstall_handler, NULL, handler_env, &ierror);
		if (!res) {
			g_propagate_prefixed_error(error, ierror, "Post-install handler error: ");
			goto umount;
		}
	}

	res = TRUE;

umount:
	if (bundle->mount_point) {
		umount_bundle(bundle, NULL);
	}
	r_context()->install_info->mounted_bundle = NULL;

out:
	log_event_installation_done(args, bundle ? bundle->manifest : NULL, error ? *error : NULL);

	r_context_end_step("do_install_bundle", res);

	return res;
}

static gboolean install_done(gpointer data)
{
	RaucInstallArgs *args = data;

	args->cleanup(args);

	r_context_set_busy(FALSE);

	return G_SOURCE_REMOVE;
}

static gpointer install_thread(gpointer data)
{
	GError *ierror = NULL;
	RaucInstallArgs *args = data;
	gint result;

	/* clear LastError property */
	set_last_error("");

	g_debug("thread started for %s", args->name);
	install_args_update(args, "started");

	result = !do_install_bundle(args, &ierror);

	if (result != 0) {
		g_warning("%s", ierror->message);
		install_args_update(args, "%s", ierror->message);
		set_last_error(ierror->message);
		g_clear_error(&ierror);
	}

	g_mutex_lock(&args->status_mutex);
	args->status_result = result;
	g_mutex_unlock(&args->status_mutex);
	install_args_update(args, "finished");
	g_debug("thread finished for %s", args->name);

	g_main_context_invoke(NULL, install_done, args);
	return NULL;
}

RaucInstallArgs *install_args_new(void)
{
	RaucInstallArgs *args = g_new0(RaucInstallArgs, 1);

	g_mutex_init(&args->status_mutex);
	g_queue_init(&args->status_messages);
	args->status_result = -2;

	return args;
}

void install_args_free(RaucInstallArgs *args)
{
	g_free(args->name);
	g_free(args->transaction);
	g_mutex_clear(&args->status_mutex);
	g_assert_cmpint(args->status_result, >=, 0);
	g_assert_true(g_queue_is_empty(&args->status_messages));
	g_free(args->require_manifest_hash);
	clear_bundle_access_args(&args->access_args);
	g_free(args);
}

void install_run(RaucInstallArgs *args)
{
	r_context_set_busy(TRUE);

	g_message("Active slot bootname: '%s'", r_context()->bootslot);

	/* g_thread_new aborts if the thread cannot be created. */
	GThread *thread = g_thread_new("installer", install_thread, args);
	/* we don't need to keep a reference to this thread */
	g_thread_unref(thread);
}

static const gchar *supported_http_headers[] = {
	"boot-id",
	"transaction-id",
	"machine-id",
	"system-version",
	"serial",
	"variant",
	"uptime",
	NULL
};

gboolean r_install_is_supported_http_header(const gchar *header)
{
	return g_strv_contains(supported_http_headers, header);
}