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
use std::collections::{BTreeMap, BTreeSet};
use std::convert::TryInto;
use std::fs;
#[cfg(feature = "signature-meta")]
use std::io;
use std::io::{Read, Write};
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use std::fmt::Debug;
use std::path::{Path, PathBuf};
use digest::Digest;
use super::compressor::Compressor;
use super::headers::*;
use super::Lead;
use crate::errors::*;
use crate::{constants::*, Timestamp};
#[cfg(feature = "signature-meta")]
use crate::signature;
use crate::Package;
use crate::PackageMetadata;
use crate::{CompressionType, CompressionWithLevel, Digests};
#[cfg(unix)]
fn file_mode(file: &fs::File) -> Result<u32, Error> {
Ok(file.metadata()?.permissions().mode())
}
#[cfg(windows)]
fn file_mode(_file: &fs::File) -> Result<u32, Error> {
Ok(0)
}
/// Create an RPM file by specifying metadata and files using the builder pattern.
#[derive(Default)]
pub struct PackageBuilder {
name: String,
epoch: u32,
version: String,
license: String,
arch: String,
uid: Option<u32>, // @todo: nothing is actually setting these or allowing setting them, they fall back to default
gid: Option<u32>,
desc: String,
release: String,
// File entries need to be sorted. The entries need to be in the same order as they come
// in the cpio payload. Otherwise rpm will not be able to resolve those paths.
// key is the directory, values are complete paths
files: BTreeMap<String, PackageFileEntry>,
directories: BTreeSet<String>,
requires: Vec<Dependency>,
obsoletes: Vec<Dependency>,
provides: Vec<Dependency>,
conflicts: Vec<Dependency>,
recommends: Vec<Dependency>,
suggests: Vec<Dependency>,
enhances: Vec<Dependency>,
supplements: Vec<Dependency>,
pre_inst_script: Option<String>,
post_inst_script: Option<String>,
pre_uninst_script: Option<String>,
post_uninst_script: Option<String>,
/// The author name with email followed by a dash with the version
/// `Max Mustermann <max@example.com> - 0.1-1`
changelog_names: Vec<String>,
changelog_entries: Vec<String>,
changelog_times: Vec<Timestamp>,
compression: CompressionWithLevel,
vendor: Option<String>,
url: Option<String>,
vcs: Option<String>,
cookie: Option<String>,
source_date: Option<Timestamp>,
build_host: Option<String>,
}
impl PackageBuilder {
/// Create a new package, providing the required metadata.
///
/// Additional metadata is added using the builder pattern. However `name`, `version`, `license`,
/// `arch`, and `description` are mandatory and must be provided.
///
/// `name` - The name of the software being packaged. It should not contain any whitespace.
/// `version` - The version of the software being packaged. It should be as close as possible to
/// the format of the original software's version.
/// `license` - The license terms applicable to the software being packaged (preferably using SPDX)
/// `arch` - The architecture that the package was built for, or "noarch" if not architecture specific
/// `description` - A detailed description of what the packaged software does.
///
/// ```
/// # fn foo() -> Result<(), Box<dyn std::error::Error>> {
/// let pkg = rpm::PackageBuilder::new("foo", "1.0.0", "Apache-2.0", "x86_64", "some baz package").build();
/// # Ok(())
/// # }
/// ```
pub fn new(name: &str, version: &str, license: &str, arch: &str, desc: &str) -> Self {
Self {
name: name.to_string(),
epoch: 0,
version: version.to_string(),
license: license.to_string(),
arch: arch.to_string(),
desc: desc.to_string(),
release: "1".to_string(),
..Default::default()
}
}
pub fn vendor(mut self, content: impl Into<String>) -> Self {
self.vendor = Some(content.into());
self
}
pub fn url(mut self, content: impl Into<String>) -> Self {
self.url = Some(content.into());
self
}
pub fn vcs(mut self, content: impl Into<String>) -> Self {
self.vcs = Some(content.into());
self
}
pub fn epoch(mut self, epoch: u32) -> Self {
self.epoch = epoch;
self
}
/// Define the name of the build host.
///
/// Commonly used in conjunction with the `gethostname` crate.
///
/// ```
/// # fn foo() -> Result<(), Box<dyn std::error::Error>> {
/// let pkg = rpm::PackageBuilder::new("foo", "1.0.0", "MPL-2.0", "x86_64", "some bar package")
/// .build_host(gethostname::gethostname().to_str().ok_or("Funny hostname")?)
/// .build()?;
/// # Ok(())
/// # }
/// ```
pub fn build_host(mut self, build_host: impl AsRef<str>) -> Self {
self.build_host = Some(build_host.as_ref().to_owned());
self
}
/// Set source date (usually the date of the latest commit in VCS) used
/// to clamp modification time of included files and build time of the package.
///
/// `dt` is number of seconds since the UNIX Epoch.
///
/// ```
/// # fn foo() -> Result<(), Box<dyn std::error::Error>> {
/// // It's recommended to use timestamp of last commit in your VCS
/// let source_date = 1_600_000_000;
/// // Do not forget
/// let pkg = rpm::PackageBuilder::new("foo", "1.0.0", "MPL-2.0", "x86_64", "some bar package")
/// .source_date(source_date)
/// .build()?;
/// # Ok(())
/// # }
/// ```
pub fn source_date(mut self, t: impl TryInto<Timestamp, Error = impl Debug>) -> Self {
self.source_date = Some(t.try_into().unwrap());
self
}
/// Define a value that can be used for associating several package builds as being part of one operation
///
/// You can use any value, but the standard format is "${build_host} ${build_time}"
pub fn cookie(mut self, cookie: impl AsRef<str>) -> Self {
self.cookie = Some(cookie.as_ref().to_owned());
self
}
/// Set the compression type and/or level to be used for the payload of the built package
///
/// Passing a `CompressionType` value will use a default compression level which has been
/// optimized for package size over compression time.
///
/// ```
/// # fn foo() -> Result<(), Box<dyn std::error::Error>> {
///
/// let pkg = rpm::PackageBuilder::new("foo", "1.0.0", "MIT", "x86_64", "some baz package")
/// .compression(rpm::CompressionType::Gzip)
/// .build()?;
/// # Ok(())
/// # }
/// ```
/// If you would like to specify a custom compression level (for faster package builds, at the
/// expense of package size), pass a `CompressionWithLevel` value instead.
///
/// ```
/// # fn foo() -> Result<(), Box<dyn std::error::Error>> {
///
/// let pkg = rpm::PackageBuilder::new("foo", "1.0.0", "MIT", "x86_64", "some baz package")
/// .compression(rpm::CompressionWithLevel::Zstd(3))
/// .build()?;
/// # Ok(())
/// # }
/// ```
///
/// For Gzip compression, the expected range is 0 to 9, with a default value of 9.
/// For Xz compression, the expected range is 0 to 9, with a default value of 9.
/// For Zstd compression, the expected range is 1 to 22, with a default value of 19.
///
/// If this method is not called, the payload will be Gzip compressed by default. This may change
/// in future versions of the library.
pub fn compression(mut self, comp: impl Into<CompressionWithLevel>) -> Self {
self.compression = comp.into();
self
}
/// Add an entry to the package changelog.
///
/// The a changelog entry consists of an entry name (which includes author, email followed by
/// a dash followed by a version number), description, and the date and time of the change.
/// ```
/// # #[cfg(feature = "chrono")]
/// # || -> Result<(), Box<dyn std::error::Error>> {
///
/// let pkg = rpm::PackageBuilder::new("foo", "1.0.0", "Apache-2.0", "x86_64", "some baz package")
/// .add_changelog_entry(
/// "Alfred J. Quack <quack@example.com> - 0.1-27",
/// r#" - Obsolete `fn foo`, in favor of `fn bar`.
/// - Secondly."#,
/// 1_681_411_811,
/// )
/// .add_changelog_entry(
/// "Gambl B. Xen <gbx@example.com> - 0.1-26",
/// " - Add enumerator.",
/// rpm::chrono::DateTime::parse_from_rfc3339("1996-12-19T16:39:57-08:00").unwrap(),
/// )
/// .build()?;
/// # Ok(())
/// # }();
/// ```
pub fn add_changelog_entry(
mut self,
name: impl AsRef<str>,
entry: impl AsRef<str>,
timestamp: impl TryInto<Timestamp, Error = impl Debug>,
) -> Self {
self.changelog_names.push(name.as_ref().to_owned());
self.changelog_entries.push(entry.as_ref().to_owned());
self.changelog_times.push(timestamp.try_into().unwrap());
self
}
/// Add a file to the package.
///
/// ```
/// # fn foo() -> Result<(), Box<dyn std::error::Error>> {
///
/// let pkg = rpm::PackageBuilder::new("foo", "1.0.0", "Apache-2.0", "x86_64", "some baz package")
/// .with_file(
/// "./awesome-config.toml",
/// rpm::FileOptions::new("/etc/awesome/config.toml").is_config(),
/// )?
/// // file mode is inherited from source file
/// .with_file(
/// "./awesome-bin",
/// rpm::FileOptions::new("/usr/bin/awesome"),
/// )?
/// .with_file(
/// "./awesome-config.toml",
/// // you can set a custom mode and custom user too
/// rpm::FileOptions::new("/etc/awesome/second.toml").mode(0o100744).user("hugo"),
/// )?
/// .build()?;
/// # Ok(())
/// # }
/// ```
pub fn with_file(
mut self,
source: impl AsRef<Path>,
options: impl Into<FileOptions>,
) -> Result<Self, Error> {
let mut input = fs::File::open(source)?;
let mut content = Vec::new();
input.read_to_end(&mut content)?;
let mut options = options.into();
if options.inherit_permissions {
options.mode = (file_mode(&input)? as i32).into();
}
let modified_at = input.metadata()?.modified()?.try_into()?;
self.add_data(content, modified_at, options)?;
Ok(self)
}
fn add_data(
&mut self,
content: Vec<u8>,
modified_at: Timestamp,
options: FileOptions,
) -> Result<(), Error> {
let dest = options.destination;
if !dest.starts_with("./") && !dest.starts_with('/') {
return Err(Error::InvalidDestinationPath {
path: dest,
desc: "invalid start, expected / or ./",
});
}
let pb = PathBuf::from(dest.clone());
let parent = pb.parent().ok_or_else(|| Error::InvalidDestinationPath {
path: dest.clone(),
desc: "no parent directory found",
})?;
let (cpio_path, dir) = if dest.starts_with('.') {
(
dest.to_string(),
// strip_prefix() should never fail because we've checked the special cases already
format!("/{}/", parent.strip_prefix(".").unwrap().to_string_lossy()),
)
} else {
(
format!(".{}", dest),
format!("{}/", parent.to_string_lossy()),
)
};
let mut hasher = sha2::Sha256::default();
hasher.update(&content);
let hash_result = hasher.finalize();
let sha_checksum = hex::encode(hash_result); // encode as string
let entry = PackageFileEntry {
// file_name() should never fail because we've checked the special cases already
base_name: pb.file_name().unwrap().to_string_lossy().to_string(),
size: content.len() as u64,
content,
flags: options.flag,
user: options.user,
group: options.group,
mode: options.mode,
link: options.symlink,
modified_at,
dir: dir.clone(),
sha_checksum,
};
self.directories.insert(dir);
self.files.entry(cpio_path).or_insert(entry);
Ok(())
}
pub fn pre_install_script(mut self, content: impl Into<String>) -> Self {
self.pre_inst_script = Some(content.into());
self
}
pub fn post_install_script(mut self, content: impl Into<String>) -> Self {
self.post_inst_script = Some(content.into());
self
}
pub fn pre_uninstall_script(mut self, content: impl Into<String>) -> Self {
self.pre_uninst_script = Some(content.into());
self
}
pub fn post_uninstall_script(mut self, content: impl Into<String>) -> Self {
self.post_uninst_script = Some(content.into());
self
}
pub fn release(mut self, release: impl Into<String>) -> Self {
self.release = release.into();
self
}
/// Add a "provides" dependency
///
/// These are aliases or capabilities provided by this package which other packages can reference.
pub fn provides(mut self, dep: Dependency) -> Self {
self.provides.push(dep);
self
}
/// Add a "requires" dependency
///
/// These are packages or capabilities which must be present in order for the package to be
/// installed.
pub fn requires(mut self, dep: Dependency) -> Self {
self.requires.push(dep);
self
}
/// Add a "conflicts" dependency
///
/// These are packages which must not be present in order for the package to be installed.
pub fn conflicts(mut self, dep: Dependency) -> Self {
self.conflicts.push(dep);
self
}
/// Add an "obsoletes" dependency
///
/// These are packages this package supercedes - if this package is installed, packages
/// listed as "obsoletes" will be be automatically removed (if they are present).
pub fn obsoletes(mut self, dep: Dependency) -> Self {
self.obsoletes.push(dep);
self
}
/// Get a list of dependencies which this package "recommends"
///
/// "rpm" itself will ignore such dependencies, but a dependency solver may elect to treat them
/// as though they were "requires". Unlike "requires" however, if installing a package listed
/// as a "recommends" would cause errors, it may be ignored without error.
pub fn recommends(mut self, dep: Dependency) -> Self {
self.recommends.push(dep);
self
}
/// Get a list of dependencies which this package "suggests"
///
/// "rpm" itself will ignore such dependencies, but a dependency solver may elect to display
/// them to the user to be optionally installed.
pub fn suggests(mut self, dep: Dependency) -> Self {
self.suggests.push(dep);
self
}
/// Get a list of reverse-dependencies which this package "enhances"
///
/// "rpm" itself will ignore such dependencies, but a dependency solver may elect to display
/// this package to the user to be optionally installed when a package matching the "enhances"
/// dependency is installed.
pub fn enhances(mut self, dep: Dependency) -> Self {
self.enhances.push(dep);
self
}
/// Get a list of reverse-dependencies which this package "supplements"
///
/// "rpm" itself will ignore such dependencies, but a dependency solver may elect to treat this
/// package as if it were a "requires" when the matching package is installed. Unlike a
/// "requires" however, if installing it would cause errors, it can be ignored ignored
/// without error.
pub fn supplements(mut self, dep: Dependency) -> Self {
self.supplements.push(dep);
self
}
/// build without a signature
///
/// ignores a present key, if any
pub fn build(self) -> Result<Package, Error> {
let (lead, header_idx_tag, content) = self.prepare_data()?;
let mut header = Vec::with_capacity(128);
header_idx_tag.write(&mut header)?;
let digest_header = {
let header = header;
let header_and_content_len = header.len() + content.len();
let Digests {
header_and_content_digest: header_and_content_digest_md5,
header_digest_sha1,
header_digest_sha256,
} = Package::create_sig_header_digests(header.as_slice(), content.as_slice())?;
Header::<IndexSignatureTag>::builder()
.add_digest(
header_digest_sha1.as_str(),
header_digest_sha256.as_str(),
header_and_content_digest_md5.as_slice(),
)
.build(header_and_content_len)
};
let metadata = PackageMetadata {
lead,
signature: digest_header,
header: header_idx_tag,
};
let pkg = Package { metadata, content };
Ok(pkg)
}
/// use an external signer to sing and build
///
/// See `signature::Signing` for more details.
#[cfg(feature = "signature-meta")]
pub fn build_and_sign<S>(self, signer: S) -> Result<Package, Error>
where
S: signature::Signing,
{
let source_date = self.source_date;
let (lead, header_idx_tag, content) = self.prepare_data()?;
let mut header = Vec::with_capacity(128);
header_idx_tag.write(&mut header)?;
let header = header;
let header_and_content_len = header.len() + content.len();
let Digests {
header_and_content_digest: header_and_content_digest_md5,
header_digest_sha1,
header_digest_sha256,
} = Package::create_sig_header_digests(header.as_slice(), content.as_slice())?;
let now = Timestamp::now();
let signature_timestamp = match source_date {
Some(source_date_epoch) if source_date_epoch < now => source_date_epoch,
_ => now,
};
let builder = Header::<IndexSignatureTag>::builder().add_digest(
header_digest_sha1.as_str(),
header_digest_sha256.as_str(),
header_and_content_digest_md5.as_slice(),
);
let sig_header_only = signer.sign(header.as_slice(), signature_timestamp)?;
let builder = match signer.algorithm() {
signature::AlgorithmType::RSA => {
let mut header_and_content_cursor =
io::Cursor::new(header.as_slice()).chain(io::Cursor::new(content.as_slice()));
let sig_header_and_archive =
signer.sign(&mut header_and_content_cursor, signature_timestamp)?;
builder.add_rsa_signature_legacy(sig_header_only.as_ref(), sig_header_and_archive.as_ref())
}
signature::AlgorithmType::EdDSA => {
builder.add_eddsa_signature(sig_header_only.as_ref())
}
};
let signature_header = builder.build(header_and_content_len);
let metadata = PackageMetadata {
lead,
signature: signature_header,
header: header_idx_tag,
};
let pkg = Package { metadata, content };
Ok(pkg)
}
/// prepare all rpm headers including content
///
/// @todo split this into multiple `fn`s, one per `IndexTag`-group.
fn prepare_data(mut self) -> Result<(Lead, Header<IndexTag>, Vec<u8>), Error> {
// signature depends on header and payload. So we build these two first.
// then the signature. Then we stitch all together.
// Lead is not important. just build it here
let lead = Lead::new(&self.name);
// Calculate the sha256 of the archive as we write it into the compressor, so that we don't
// need to keep two copies in memory simultaneously.
let mut compressor: Compressor = self.compression.try_into()?;
let mut archive = Sha256Writer::new(&mut compressor);
let mut ino_index = 1;
let files_len = self.files.len();
let mut file_sizes = Vec::with_capacity(files_len);
let mut file_modes = Vec::with_capacity(files_len);
let mut file_rdevs = Vec::with_capacity(files_len);
let mut file_mtimes = Vec::with_capacity(files_len);
let mut file_hashes = Vec::with_capacity(files_len);
let mut file_linktos = Vec::with_capacity(files_len);
let mut file_flags = Vec::with_capacity(files_len);
let mut file_usernames = Vec::with_capacity(files_len);
let mut file_groupnames = Vec::with_capacity(files_len);
let mut file_devices = Vec::with_capacity(files_len);
let mut file_inodes = Vec::with_capacity(files_len);
let mut file_langs = Vec::with_capacity(files_len);
let mut file_verify_flags = Vec::with_capacity(files_len);
let mut dir_indixes = Vec::with_capacity(files_len);
let mut base_names = Vec::with_capacity(files_len);
let mut combined_file_sizes: u64 = 0;
for (cpio_path, entry) in self.files.iter() {
combined_file_sizes += entry.size;
file_sizes.push(entry.size);
file_modes.push(entry.mode.into());
// I really do not know the difference. It seems like file_rdevice is always 0 and file_device number always 1.
// Who knows, who cares.
file_rdevs.push(0);
file_devices.push(1);
let mtime = match self.source_date {
Some(d) if d < entry.modified_at => d,
_ => entry.modified_at,
};
file_mtimes.push(mtime.into());
file_hashes.push(entry.sha_checksum.to_owned());
file_linktos.push(entry.link.to_owned());
file_flags.push(entry.flags.bits());
file_usernames.push(entry.user.to_owned());
file_groupnames.push(entry.group.to_owned());
file_inodes.push(ino_index);
file_langs.push("".to_string());
// safe because indexes cannot change after this as the RpmBuilder is consumed
// the dir is guaranteed to be there - or else there is a logic error
let index = self
.directories
.iter()
.position(|d| d == &entry.dir)
.unwrap();
dir_indixes.push(index as u32);
base_names.push(entry.base_name.to_owned());
// @todo: is there a use case for not performing all verifications? and are we performing those verifications currently anyway?
file_verify_flags.push(FileVerifyFlags::all().bits());
let content = entry.content.to_owned();
let mut writer = cpio::newc::Builder::new(cpio_path)
.mode(entry.mode.into())
.ino(ino_index)
.uid(self.uid.unwrap_or(0))
.gid(self.gid.unwrap_or(0))
.write(&mut archive, content.len() as u32);
writer.write_all(&content)?;
writer.finish()?;
ino_index += 1;
}
cpio::newc::trailer(&mut archive)?;
self.provides
.push(Dependency::eq(self.name.clone(), self.version.clone()));
self.provides.push(Dependency::eq(
format!("{}({})", self.name.clone(), self.arch.clone()),
self.version.clone(),
));
self.requires.push(Dependency::rpmlib(
"rpmlib(CompressedFileNames)".to_string(),
"3.0.4-1".to_string(),
));
self.requires.push(Dependency::rpmlib(
"rpmlib(FileDigests)".to_string(),
"4.6.0-1".to_string(),
));
self.requires.push(Dependency::rpmlib(
"rpmlib(PayloadFilesHavePrefix)".to_string(),
"4.0-1".to_string(),
));
if self.compression.compression_type() == CompressionType::Zstd {
self.requires.push(Dependency::rpmlib(
"rpmlib(PayloadIsZstd)".to_string(),
"5.4.18-1".to_string(),
));
}
let mut provide_names = Vec::new();
let mut provide_flags = Vec::new();
let mut provide_versions = Vec::new();
for d in self.provides.into_iter() {
provide_names.push(d.name);
provide_flags.push(d.flags.bits());
provide_versions.push(d.version);
}
let mut obsolete_names = Vec::new();
let mut obsolete_flags = Vec::new();
let mut obsolete_versions = Vec::new();
for d in self.obsoletes.into_iter() {
obsolete_names.push(d.name);
obsolete_flags.push(d.flags.bits());
obsolete_versions.push(d.version);
}
let mut require_names = Vec::new();
let mut require_flags = Vec::new();
let mut require_versions = Vec::new();
for d in self.requires.into_iter() {
require_names.push(d.name);
require_flags.push(d.flags.bits());
require_versions.push(d.version);
}
let mut conflicts_names = Vec::new();
let mut conflicts_flags = Vec::new();
let mut conflicts_versions = Vec::new();
for d in self.conflicts.into_iter() {
conflicts_names.push(d.name);
conflicts_flags.push(d.flags.bits());
conflicts_versions.push(d.version);
}
let mut recommends_names = Vec::new();
let mut recommends_flags = Vec::new();
let mut recommends_versions = Vec::new();
for d in self.recommends.into_iter() {
recommends_names.push(d.name);
recommends_flags.push(d.flags.bits());
recommends_versions.push(d.version);
}
let mut suggests_names = Vec::new();
let mut suggests_flags = Vec::new();
let mut suggests_versions = Vec::new();
for d in self.suggests.into_iter() {
suggests_names.push(d.name);
suggests_flags.push(d.flags.bits());
suggests_versions.push(d.version);
}
let mut enhances_names = Vec::new();
let mut enhances_flags = Vec::new();
let mut enhances_versions = Vec::new();
for d in self.enhances.into_iter() {
enhances_names.push(d.name);
enhances_flags.push(d.flags.bits());
enhances_versions.push(d.version);
}
let mut supplements_names = Vec::new();
let mut supplements_flags = Vec::new();
let mut supplements_versions = Vec::new();
for d in self.supplements.into_iter() {
supplements_names.push(d.name);
supplements_flags.push(d.flags.bits());
supplements_versions.push(d.version);
}
let offset = 0;
let small_package = combined_file_sizes <= u32::MAX.into();
let mut actual_records = vec![
IndexEntry::new(
IndexTag::RPMTAG_SOURCERPM,
offset,
IndexData::StringTag("(none)".to_string()),
),
IndexEntry::new(
IndexTag::RPMTAG_HEADERI18NTABLE,
offset,
IndexData::StringArray(vec!["C".to_string()]),
),
IndexEntry::new(
IndexTag::RPMTAG_NAME,
offset,
IndexData::StringTag(self.name),
),
IndexEntry::new(
IndexTag::RPMTAG_EPOCH,
offset,
IndexData::Int32(vec![self.epoch]),
),
IndexEntry::new(
IndexTag::RPMTAG_RPMVERSION,
offset,
IndexData::StringTag(format!("rpm-rs {}", env!("CARGO_PKG_VERSION"))),
),
// @todo: write RPMTAG_PLATFORM?
IndexEntry::new(
IndexTag::RPMTAG_VERSION,
offset,
IndexData::StringTag(self.version),
),
IndexEntry::new(
IndexTag::RPMTAG_RELEASE,
offset,
IndexData::StringTag(self.release),
),
IndexEntry::new(
IndexTag::RPMTAG_DESCRIPTION,
offset,
IndexData::I18NString(vec![self.desc.clone()]),
),
IndexEntry::new(
IndexTag::RPMTAG_SUMMARY,
offset,
IndexData::I18NString(vec![self.desc]),
),
if small_package {
let combined_file_sizes = combined_file_sizes
.try_into()
.expect("combined_file_sizes should be smaller than 4 GiB");
IndexEntry::new(
IndexTag::RPMTAG_SIZE,
offset,
IndexData::Int32(vec![combined_file_sizes]),
)
} else {
IndexEntry::new(
IndexTag::RPMTAG_LONGSIZE,
offset,
IndexData::Int64(vec![combined_file_sizes]),
)
},
IndexEntry::new(
IndexTag::RPMTAG_LICENSE,
offset,
IndexData::StringTag(self.license),
),
IndexEntry::new(
IndexTag::RPMTAG_OS,
offset,
IndexData::StringTag("linux".to_string()),
),
// @todo: Fedora packaging guidelines recommend against using %group <https://fedoraproject.org/wiki/RPMGroups>
// If it's legacy and safe to drop entirely let's do so. rpmbuild still writes it in the header though.
IndexEntry::new(
IndexTag::RPMTAG_GROUP,
offset,
IndexData::I18NString(vec!["Unspecified".to_string()]),
),
IndexEntry::new(
IndexTag::RPMTAG_ARCH,
offset,
IndexData::StringTag(self.arch),
),
IndexEntry::new(
IndexTag::RPMTAG_ENCODING,
offset,
IndexData::StringTag("utf-8".to_string()),
),
IndexEntry::new(
IndexTag::RPMTAG_PAYLOADFORMAT,
offset,
IndexData::StringTag("cpio".to_string()),
),
];
let now = Timestamp::now();
let build_time = match self.source_date {
Some(t) if t < now => t,
_ => now,
};
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_BUILDTIME,
offset,
IndexData::Int32(vec![build_time.into()]),
));
if let Some(build_host) = self.build_host {
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_BUILDHOST,
offset,
IndexData::StringTag(build_host),
));
}
// if we have an empty RPM, we have to leave out all file related index entries.
if !self.files.is_empty() {
let size_entry = if small_package {
let file_sizes = file_sizes
.into_iter()
.map(u32::try_from)
.collect::<Result<_, _>>()
.expect(
"combined_file_sizes and thus all file sizes \
should be smaller than 4 GiB",
);
IndexEntry::new(
IndexTag::RPMTAG_FILESIZES,
offset,
IndexData::Int32(file_sizes),
)
} else {
IndexEntry::new(
IndexTag::RPMTAG_LONGFILESIZES,
offset,
IndexData::Int64(file_sizes),
)
};
actual_records.extend([
size_entry,
IndexEntry::new(
IndexTag::RPMTAG_FILEMODES,
offset,
IndexData::Int16(file_modes),
),
IndexEntry::new(
IndexTag::RPMTAG_FILERDEVS,
offset,
IndexData::Int16(file_rdevs),
),
IndexEntry::new(
IndexTag::RPMTAG_FILEMTIMES,
offset,
IndexData::Int32(file_mtimes),
),
IndexEntry::new(
IndexTag::RPMTAG_FILEDIGESTS,
offset,
IndexData::StringArray(file_hashes),
),
IndexEntry::new(
IndexTag::RPMTAG_FILELINKTOS,
offset,
IndexData::StringArray(file_linktos),
),
IndexEntry::new(
IndexTag::RPMTAG_FILEFLAGS,
offset,
IndexData::Int32(file_flags),
),
IndexEntry::new(
IndexTag::RPMTAG_FILEUSERNAME,
offset,
IndexData::StringArray(file_usernames),
),
IndexEntry::new(
IndexTag::RPMTAG_FILEGROUPNAME,
offset,
IndexData::StringArray(file_groupnames),
),
IndexEntry::new(
IndexTag::RPMTAG_FILEDEVICES,
offset,
IndexData::Int32(file_devices),
),
IndexEntry::new(
IndexTag::RPMTAG_FILEINODES,
offset,
IndexData::Int32(file_inodes),
),
IndexEntry::new(
IndexTag::RPMTAG_DIRINDEXES,
offset,
IndexData::Int32(dir_indixes),
),
IndexEntry::new(
IndexTag::RPMTAG_FILELANGS,
offset,
IndexData::StringArray(file_langs),
),
IndexEntry::new(
IndexTag::RPMTAG_FILEDIGESTALGO,
offset,
IndexData::Int32(vec![DigestAlgorithm::Sha2_256 as u32]),
),
IndexEntry::new(
IndexTag::RPMTAG_FILEVERIFYFLAGS,
offset,
IndexData::Int32(file_verify_flags),
),
IndexEntry::new(
IndexTag::RPMTAG_BASENAMES,
offset,
IndexData::StringArray(base_names),
),
IndexEntry::new(
IndexTag::RPMTAG_DIRNAMES,
offset,
IndexData::StringArray(self.directories.into_iter().collect()),
),
]);
}
actual_records.extend([
IndexEntry::new(
IndexTag::RPMTAG_PROVIDENAME,
offset,
IndexData::StringArray(provide_names),
),
IndexEntry::new(
IndexTag::RPMTAG_PROVIDEVERSION,
offset,
IndexData::StringArray(provide_versions),
),
IndexEntry::new(
IndexTag::RPMTAG_PROVIDEFLAGS,
offset,
IndexData::Int32(provide_flags),
),
]);
// digest of the uncompressed raw archive calculated on the inner writer
let raw_archive_digest_sha256 = hex::encode(archive.into_digest());
let payload = compressor.finish_compression()?;
// digest of the post-compression archive (payload)
let payload_digest_sha256 = {
let mut hasher = sha2::Sha256::default();
hasher.update(payload.as_slice());
hex::encode(hasher.finalize())
};
actual_records.extend([
IndexEntry::new(
IndexTag::RPMTAG_PAYLOADDIGEST,
offset,
IndexData::StringArray(vec![payload_digest_sha256]),
),
IndexEntry::new(
IndexTag::RPMTAG_PAYLOADDIGESTALGO,
offset,
IndexData::Int32(vec![DigestAlgorithm::Sha2_256 as u32]),
),
IndexEntry::new(
IndexTag::RPMTAG_PAYLOADDIGESTALT,
offset,
IndexData::StringArray(vec![raw_archive_digest_sha256]),
),
]);
let compression_details = match self.compression {
CompressionWithLevel::None => None,
CompressionWithLevel::Gzip(level) => Some(("gzip".to_owned(), level.to_string())),
CompressionWithLevel::Zstd(level) => Some(("zstd".to_owned(), level.to_string())),
CompressionWithLevel::Xz(level) => Some(("xz".to_owned(), level.to_string())),
};
if let Some((compression_name, compression_level)) = compression_details {
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_PAYLOADCOMPRESSOR,
offset,
IndexData::StringTag(compression_name),
));
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_PAYLOADFLAGS,
offset,
IndexData::StringTag(compression_level),
));
}
if !self.changelog_names.is_empty() {
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_CHANGELOGNAME,
offset,
IndexData::StringArray(self.changelog_names),
));
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_CHANGELOGTEXT,
offset,
IndexData::StringArray(self.changelog_entries),
));
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_CHANGELOGTIME,
offset,
IndexData::Int32(self.changelog_times.into_iter().map(Into::into).collect()),
));
}
if !obsolete_flags.is_empty() {
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_OBSOLETENAME,
offset,
IndexData::StringArray(obsolete_names),
));
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_OBSOLETEVERSION,
offset,
IndexData::StringArray(obsolete_versions),
));
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_OBSOLETEFLAGS,
offset,
IndexData::Int32(obsolete_flags),
));
}
if !require_flags.is_empty() {
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_REQUIRENAME,
offset,
IndexData::StringArray(require_names),
));
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_REQUIREVERSION,
offset,
IndexData::StringArray(require_versions),
));
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_REQUIREFLAGS,
offset,
IndexData::Int32(require_flags),
));
}
if !conflicts_flags.is_empty() {
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_CONFLICTNAME,
offset,
IndexData::StringArray(conflicts_names),
));
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_CONFLICTVERSION,
offset,
IndexData::StringArray(conflicts_versions),
));
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_CONFLICTFLAGS,
offset,
IndexData::Int32(conflicts_flags),
));
}
if !recommends_flags.is_empty() {
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_RECOMMENDNAME,
offset,
IndexData::StringArray(recommends_names),
));
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_RECOMMENDVERSION,
offset,
IndexData::StringArray(recommends_versions),
));
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_RECOMMENDFLAGS,
offset,
IndexData::Int32(recommends_flags),
));
}
if !suggests_flags.is_empty() {
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_SUGGESTNAME,
offset,
IndexData::StringArray(suggests_names),
));
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_SUGGESTVERSION,
offset,
IndexData::StringArray(suggests_versions),
));
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_SUGGESTFLAGS,
offset,
IndexData::Int32(suggests_flags),
));
}
if !enhances_flags.is_empty() {
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_ENHANCENAME,
offset,
IndexData::StringArray(enhances_names),
));
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_ENHANCEVERSION,
offset,
IndexData::StringArray(enhances_versions),
));
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_ENHANCEFLAGS,
offset,
IndexData::Int32(enhances_flags),
));
}
if !supplements_flags.is_empty() {
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_SUPPLEMENTNAME,
offset,
IndexData::StringArray(supplements_names),
));
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_SUPPLEMENTVERSION,
offset,
IndexData::StringArray(supplements_versions),
));
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_SUPPLEMENTFLAGS,
offset,
IndexData::Int32(supplements_flags),
));
}
if let Some(pre_inst_script) = self.pre_inst_script {
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_PREIN,
offset,
IndexData::StringTag(pre_inst_script),
));
}
if let Some(post_inst_script) = self.post_inst_script {
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_POSTIN,
offset,
IndexData::StringTag(post_inst_script),
));
}
if let Some(pre_uninst_script) = self.pre_uninst_script {
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_PREUN,
offset,
IndexData::StringTag(pre_uninst_script),
));
}
if let Some(post_uninst_script) = self.post_uninst_script {
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_POSTUN,
offset,
IndexData::StringTag(post_uninst_script),
));
}
if let Some(vendor) = self.vendor {
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_VENDOR,
offset,
IndexData::StringTag(vendor),
));
}
if let Some(url) = self.url {
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_URL,
offset,
IndexData::StringTag(url),
));
}
if let Some(vcs) = self.vcs {
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_VCS,
offset,
IndexData::StringTag(vcs),
));
}
if let Some(cookie) = self.cookie {
actual_records.push(IndexEntry::new(
IndexTag::RPMTAG_COOKIE,
offset,
IndexData::StringTag(cookie),
));
}
let header = Header::from_entries(actual_records, IndexTag::RPMTAG_HEADERIMMUTABLE);
Ok((lead, header, payload))
}
}