aboutsummaryrefslogtreecommitdiffstats
path: root/libarchive/archive_write_set_format_7zip.c
blob: f63a2266a85ede17a747a7c7796992fcf431c937 (plain) (blame)
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
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
/*-
 * Copyright (c) 2011-2012 Michihiro NAKAJIMA
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "archive_platform.h"
__FBSDID("$FreeBSD$");

#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#include <stdlib.h>
#ifdef HAVE_BZLIB_H
#include <bzlib.h>
#endif
#if HAVE_LZMA_H
#include <lzma.h>
#endif
#ifdef HAVE_ZLIB_H
#include <zlib.h>
#endif

#include "archive.h"
#ifndef HAVE_ZLIB_H
#include "archive_crc32.h"
#endif
#include "archive_endian.h"
#include "archive_entry.h"
#include "archive_entry_locale.h"
#include "archive_ppmd7_private.h"
#include "archive_private.h"
#include "archive_rb.h"
#include "archive_string.h"
#include "archive_write_private.h"

/*
 * Codec ID
 */
#define _7Z_COPY	0
#define _7Z_LZMA1	0x030101
#define _7Z_LZMA2	0x21
#define _7Z_DEFLATE	0x040108
#define _7Z_BZIP2	0x040202
#define _7Z_PPMD	0x030401

/*
 * 7-Zip header property IDs.
 */
#define kEnd			0x00
#define kHeader			0x01
#define kArchiveProperties	0x02
#define kAdditionalStreamsInfo	0x03
#define kMainStreamsInfo	0x04
#define kFilesInfo		0x05
#define kPackInfo		0x06
#define kUnPackInfo		0x07
#define kSubStreamsInfo		0x08
#define kSize			0x09
#define kCRC			0x0A
#define kFolder			0x0B
#define kCodersUnPackSize	0x0C
#define kNumUnPackStream	0x0D
#define kEmptyStream		0x0E
#define kEmptyFile		0x0F
#define kAnti			0x10
#define kName			0x11
#define kCTime			0x12
#define kATime			0x13
#define kMTime			0x14
#define kAttributes		0x15
#define kEncodedHeader		0x17

enum la_zaction {
	ARCHIVE_Z_FINISH,
	ARCHIVE_Z_RUN
};

/*
 * A stream object of universal compressor.
 */
struct la_zstream {
	const uint8_t		*next_in;
	size_t			 avail_in;
	uint64_t		 total_in;

	uint8_t			*next_out;
	size_t			 avail_out;
	uint64_t		 total_out;

	uint32_t		 prop_size;
	uint8_t			*props;

	int			 valid;
	void			*real_stream;
	int			 (*code) (struct archive *a,
				    struct la_zstream *lastrm,
				    enum la_zaction action);
	int			 (*end)(struct archive *a,
				    struct la_zstream *lastrm);
};

#define PPMD7_DEFAULT_ORDER	6
#define PPMD7_DEFAULT_MEM_SIZE	(1 << 24)

struct ppmd_stream {
	int			 stat;
	CPpmd7			 ppmd7_context;
	CPpmd7z_RangeEnc	 range_enc;
	IByteOut		 byteout;
	uint8_t			*buff;
	uint8_t			*buff_ptr;
	uint8_t			*buff_end;
	size_t			 buff_bytes;
};

struct coder {
	unsigned		 codec;
	size_t			 prop_size;
	uint8_t			*props;
};

struct file {
	struct archive_rb_node	 rbnode;

	struct file		*next;
	unsigned		 name_len;
	uint8_t			*utf16name;/* UTF16-LE name. */
	uint64_t		 size;
	unsigned		 flg;
#define MTIME_IS_SET	(1<<0)
#define ATIME_IS_SET	(1<<1)
#define CTIME_IS_SET	(1<<2)
#define CRC32_IS_SET	(1<<3)
#define HAS_STREAM	(1<<4)

	struct {
		time_t		 time;
		long		 time_ns;
	}			 times[3];
#define MTIME 0
#define ATIME 1
#define CTIME 2

	mode_t			 mode;
	uint32_t		 crc32;

	int			 dir:1;
};

struct _7zip {
	int			 temp_fd;
	uint64_t		 temp_offset;

	struct file		*cur_file;
	size_t			 total_number_entry;
	size_t			 total_number_nonempty_entry;
	size_t			 total_number_empty_entry;
	size_t			 total_number_dir_entry;
	size_t			 total_bytes_entry_name;
	size_t			 total_number_time_defined[3];
	uint64_t		 total_bytes_compressed;
	uint64_t		 total_bytes_uncompressed;
	uint64_t		 entry_bytes_remaining;
	uint32_t		 entry_crc32;
	uint32_t		 precode_crc32;
	uint32_t		 encoded_crc32;
	int			 crc32flg;
#define	PRECODE_CRC32	1
#define	ENCODED_CRC32	2

	unsigned		 opt_compression;
	int			 opt_compression_level;

	struct la_zstream	 stream;
	struct coder		 coder;

	struct archive_string_conv *sconv;

	/*
	 * Compressed data buffer.
	 */
	unsigned char		 wbuff[512 * 20 * 6];
	size_t			 wbuff_remaining;

	/*
	 * The list of the file entries which has its contents is used to
	 * manage struct file objects.
	 * We use 'next' (a member of struct file) to chain.
	 */
	struct {
		struct file	*first;
		struct file	**last;
	}			 file_list, empty_list;
	struct archive_rb_tree	 rbtree;/* for empty files */
};

static int	_7z_options(struct archive_write *,
		    const char *, const char *);
static int	_7z_write_header(struct archive_write *,
		    struct archive_entry *);
static ssize_t	_7z_write_data(struct archive_write *,
		    const void *, size_t);
static int	_7z_finish_entry(struct archive_write *);
static int	_7z_close(struct archive_write *);
static int	_7z_free(struct archive_write *);
static int	file_cmp_node(const struct archive_rb_node *,
		    const struct archive_rb_node *);
static int	file_cmp_key(const struct archive_rb_node *, const void *);
static int	file_new(struct archive_write *a, struct archive_entry *,
		    struct file **);
static void	file_free(struct file *);
static void	file_register(struct _7zip *, struct file *);
static void	file_register_empty(struct _7zip *, struct file *);
static void	file_init_register(struct _7zip *);
static void	file_init_register_empty(struct _7zip *);
static void	file_free_register(struct _7zip *);
static ssize_t	compress_out(struct archive_write *, const void *, size_t ,
		    enum la_zaction);
static int	compression_init_encoder_copy(struct archive *,
		    struct la_zstream *);
static int	compression_code_copy(struct archive *,
		    struct la_zstream *, enum la_zaction);
static int	compression_end_copy(struct archive *, struct la_zstream *);
static int	compression_init_encoder_deflate(struct archive *,
		    struct la_zstream *, int, int);
#ifdef HAVE_ZLIB_H
static int	compression_code_deflate(struct archive *,
		    struct la_zstream *, enum la_zaction);
static int	compression_end_deflate(struct archive *, struct la_zstream *);
#endif
static int	compression_init_encoder_bzip2(struct archive *,
		    struct la_zstream *, int);
#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR)
static int	compression_code_bzip2(struct archive *,
		    struct la_zstream *, enum la_zaction);
static int	compression_end_bzip2(struct archive *, struct la_zstream *);
#endif
static int	compression_init_encoder_lzma1(struct archive *,
		    struct la_zstream *, int);
static int	compression_init_encoder_lzma2(struct archive *,
		    struct la_zstream *, int);
#if defined(HAVE_LZMA_H)
static int	compression_code_lzma(struct archive *,
		    struct la_zstream *, enum la_zaction);
static int	compression_end_lzma(struct archive *, struct la_zstream *);
#endif
static int	compression_init_encoder_ppmd(struct archive *,
		    struct la_zstream *, unsigned, uint32_t);
static int	compression_code_ppmd(struct archive *,
		    struct la_zstream *, enum la_zaction);
static int	compression_end_ppmd(struct archive *, struct la_zstream *);
static int	_7z_compression_init_encoder(struct archive_write *, unsigned,
		    int);
static int	compression_code(struct archive *,
		    struct la_zstream *, enum la_zaction);
static int	compression_end(struct archive *,
		    struct la_zstream *);
static int	enc_uint64(struct archive_write *, uint64_t);
static int	make_header(struct archive_write *, uint64_t, uint64_t,
		    uint64_t, int, struct coder *);
static int	make_streamsInfo(struct archive_write *, uint64_t, uint64_t,
		    	uint64_t, int, struct coder *, int, uint32_t);

int
archive_write_set_format_7zip(struct archive *_a)
{
	static const struct archive_rb_tree_ops rb_ops = {
		file_cmp_node, file_cmp_key
	};
	struct archive_write *a = (struct archive_write *)_a;
	struct _7zip *zip;

	archive_check_magic(_a, ARCHIVE_WRITE_MAGIC,
	    ARCHIVE_STATE_NEW, "archive_write_set_format_7zip");

	/* If another format was already registered, unregister it. */
	if (a->format_free != NULL)
		(a->format_free)(a);

	zip = calloc(1, sizeof(*zip));
	if (zip == NULL) {
		archive_set_error(&a->archive, ENOMEM,
		    "Can't allocate 7-Zip data");
		return (ARCHIVE_FATAL);
	}
	zip->temp_fd = -1;
	__archive_rb_tree_init(&(zip->rbtree), &rb_ops);
	file_init_register(zip);
	file_init_register_empty(zip);

	/* Set default compression type and its level. */
#if HAVE_LZMA_H
	zip->opt_compression = _7Z_LZMA1;
#elif defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR)
	zip->opt_compression = _7Z_BZIP2;
#elif defined(HAVE_ZLIB_H)
	zip->opt_compression = _7Z_DEFLATE;
#else
	zip->opt_compression = _7Z_COPY;
#endif
	zip->opt_compression_level = 6;

	a->format_data = zip;

	a->format_name = "7zip";
	a->format_options = _7z_options;
	a->format_write_header = _7z_write_header;
	a->format_write_data = _7z_write_data;
	a->format_finish_entry = _7z_finish_entry;
	a->format_close = _7z_close;
	a->format_free = _7z_free;
	a->archive.archive_format = ARCHIVE_FORMAT_7ZIP;
	a->archive.archive_format_name = "7zip";

	return (ARCHIVE_OK);
}

static int
_7z_options(struct archive_write *a, const char *key, const char *value)
{
	struct _7zip *zip;

	zip = (struct _7zip *)a->format_data;

	if (strcmp(key, "compression") == 0) {
		const char *name = NULL;

		if (value == NULL || strcmp(value, "copy") == 0 ||
		    strcmp(value, "COPY") == 0 ||
		    strcmp(value, "store") == 0 ||
		    strcmp(value, "STORE") == 0)
			zip->opt_compression = _7Z_COPY;
		else if (strcmp(value, "deflate") == 0 ||
		    strcmp(value, "DEFLATE") == 0)
#if HAVE_ZLIB_H
			zip->opt_compression = _7Z_DEFLATE;
#else
			name = "deflate";
#endif
		else if (strcmp(value, "bzip2") == 0 ||
		    strcmp(value, "BZIP2") == 0)
#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR)
			zip->opt_compression = _7Z_BZIP2;
#else
			name = "bzip2";
#endif
		else if (strcmp(value, "lzma1") == 0 ||
		    strcmp(value, "LZMA1") == 0)
#if HAVE_LZMA_H
			zip->opt_compression = _7Z_LZMA1;
#else
			name = "lzma1";
#endif
		else if (strcmp(value, "lzma2") == 0 ||
		    strcmp(value, "LZMA2") == 0)
#if HAVE_LZMA_H
			zip->opt_compression = _7Z_LZMA2;
#else
			name = "lzma2";
#endif
		else if (strcmp(value, "ppmd") == 0 ||
		    strcmp(value, "PPMD") == 0 ||
		    strcmp(value, "PPMd") == 0)
			zip->opt_compression = _7Z_PPMD;
		else {
			archive_set_error(&(a->archive),
			    ARCHIVE_ERRNO_MISC,
			    "Unknown compression name: `%s'",
			    value);
			return (ARCHIVE_FAILED);
		}
		if (name != NULL) {
			archive_set_error(&(a->archive),
			    ARCHIVE_ERRNO_MISC,
			    "`%s' compression not supported "
			    "on this platform",
			    name);
			return (ARCHIVE_FAILED);
		}
		return (ARCHIVE_OK);
	}
	if (strcmp(key, "compression-level") == 0) {
		if (value == NULL ||
		    !(value[0] >= '0' && value[0] <= '9') ||
		    value[1] != '\0') {
			archive_set_error(&(a->archive),
			    ARCHIVE_ERRNO_MISC,
			    "Illegal value `%s'",
			    value);
			return (ARCHIVE_FAILED);
		}
		zip->opt_compression_level = value[0] - '0';
		return (ARCHIVE_OK);
	}

	/* Note: The "warn" return is just to inform the options
	 * supervisor that we didn't handle it.  It will generate
	 * a suitable error if no one used this option. */
	return (ARCHIVE_WARN);
}

static int
_7z_write_header(struct archive_write *a, struct archive_entry *entry)
{
	struct _7zip *zip;
	struct file *file;
	int r;

	zip = (struct _7zip *)a->format_data;
	zip->cur_file = NULL;
	zip->entry_bytes_remaining = 0;

	if (zip->sconv == NULL) {
		zip->sconv = archive_string_conversion_to_charset(
		    &a->archive, "UTF-16LE", 1);
		if (zip->sconv == NULL)
			return (ARCHIVE_FATAL);
	}

	r = file_new(a, entry, &file);
	if (r < ARCHIVE_WARN) {
		file_free(file);
		return (r);
	}
	if (file->size == 0 && file->dir) {
		if (!__archive_rb_tree_insert_node(&(zip->rbtree),
		    (struct archive_rb_node *)file)) {
			/* We have already had the same file. */
			file_free(file);
			return (ARCHIVE_OK);
		}
	}

	if (file->flg & MTIME_IS_SET)
		zip->total_number_time_defined[MTIME]++;
	if (file->flg & CTIME_IS_SET)
		zip->total_number_time_defined[CTIME]++;
	if (file->flg & ATIME_IS_SET)
		zip->total_number_time_defined[ATIME]++;

	zip->total_number_entry++;
	zip->total_bytes_entry_name += file->name_len + 2;
	if (file->size == 0) {
		/* Count up the number of empty files. */
		zip->total_number_empty_entry++;
		if (file->dir)
			zip->total_number_dir_entry++;
		else
			file_register_empty(zip, file);
		return (r);
	}

	/*
	 * Init compression.
	 */
	if ((zip->total_number_entry - zip->total_number_empty_entry) == 1) {
		r = _7z_compression_init_encoder(a, zip->opt_compression,
			zip->opt_compression_level);
		if (r < 0) {
			file_free(file);
			return (ARCHIVE_FATAL);
		}
	}

	/* Register a non-empty file. */
	file_register(zip, file);

	/*
	 * Set the current file to cur_file to read its contents.
	 */
	zip->cur_file = file;


	/* Save a offset of current file in temporary file. */
	zip->entry_bytes_remaining = file->size;
	zip->entry_crc32 = 0;

	/*
	 * Store a symbolic link name as file contents.
	 */
	if (archive_entry_filetype(entry) == AE_IFLNK) {
		ssize_t bytes;
		const void *p = (const void *)archive_entry_symlink(entry);
		bytes = compress_out(a, p, (size_t)file->size, ARCHIVE_Z_RUN);
		if (bytes < 0)
			return ((int)bytes);
		zip->entry_crc32 = crc32(zip->entry_crc32, p, (unsigned)bytes);
		zip->entry_bytes_remaining -= bytes;
	}

	return (r);
}

/*
 * Write data to a temporary file.
 */
static int
write_to_temp(struct archive_write *a, const void *buff, size_t s)
{
	struct _7zip *zip;
	const unsigned char *p;
	ssize_t ws;

	zip = (struct _7zip *)a->format_data;

	/*
	 * Open a temporary file.
	 */
	if (zip->temp_fd == -1) {
		zip->temp_offset = 0;
		zip->temp_fd = __archive_mktemp(NULL);
		if (zip->temp_fd < 0) {
			archive_set_error(&a->archive, errno,
			    "Couldn't create temporary file");
			return (ARCHIVE_FATAL);
		}
	}

	p = (const unsigned char *)buff;
	while (s) {
		ws = write(zip->temp_fd, p, s);
		if (ws < 0) {
			archive_set_error(&(a->archive), errno,
			    "fwrite function failed");
			return (ARCHIVE_FATAL);
		}
		s -= ws;
		p += ws;
		zip->temp_offset += ws;
	}
	return (ARCHIVE_OK);
}

static ssize_t
compress_out(struct archive_write *a, const void *buff, size_t s,
    enum la_zaction run)
{
	struct _7zip *zip = (struct _7zip *)a->format_data;
	int r;

	if (run == ARCHIVE_Z_FINISH && zip->stream.total_in == 0 && s == 0)
		return (0);

	if ((zip->crc32flg & PRECODE_CRC32) && s)
		zip->precode_crc32 = crc32(zip->precode_crc32, buff,
		    (unsigned)s);
	zip->stream.next_in = (const unsigned char *)buff;
	zip->stream.avail_in = s;
	for (;;) {
		/* Compress file data. */
		r = compression_code(&(a->archive), &(zip->stream), run);
		if (r != ARCHIVE_OK && r != ARCHIVE_EOF)
			return (ARCHIVE_FATAL);
		if (zip->stream.avail_out == 0) {
			if (write_to_temp(a, zip->wbuff, sizeof(zip->wbuff))
			    != ARCHIVE_OK)
				return (ARCHIVE_FATAL);
			zip->stream.next_out = zip->wbuff;
			zip->stream.avail_out = sizeof(zip->wbuff);
			if (zip->crc32flg & ENCODED_CRC32)
				zip->encoded_crc32 = crc32(zip->encoded_crc32,
				    zip->wbuff, sizeof(zip->wbuff));
			if (run == ARCHIVE_Z_FINISH && r != ARCHIVE_EOF)
				continue;
		}
		if (zip->stream.avail_in == 0)
			break;
	}
	if (run == ARCHIVE_Z_FINISH) {
		uint64_t bytes = sizeof(zip->wbuff) - zip->stream.avail_out;
		if (write_to_temp(a, zip->wbuff, (size_t)bytes) != ARCHIVE_OK)
			return (ARCHIVE_FATAL);
		if ((zip->crc32flg & ENCODED_CRC32) && bytes)
			zip->encoded_crc32 = crc32(zip->encoded_crc32,
			    zip->wbuff, (unsigned)bytes);
	}

	return (s);
}

static ssize_t
_7z_write_data(struct archive_write *a, const void *buff, size_t s)
{
	struct _7zip *zip;
	ssize_t bytes;

	zip = (struct _7zip *)a->format_data;

	if (s > zip->entry_bytes_remaining)
		s = (size_t)zip->entry_bytes_remaining;
	if (s == 0 || zip->cur_file == NULL)
		return (0);
	bytes = compress_out(a, buff, s, ARCHIVE_Z_RUN);
	if (bytes < 0)
		return (bytes);
	zip->entry_crc32 = crc32(zip->entry_crc32, buff, (unsigned)bytes);
	zip->entry_bytes_remaining -= bytes;
	return (bytes);
}

static int
_7z_finish_entry(struct archive_write *a)
{
	struct _7zip *zip;
	size_t s;
	ssize_t r;

	zip = (struct _7zip *)a->format_data;
	if (zip->cur_file == NULL)
		return (ARCHIVE_OK);

	while (zip->entry_bytes_remaining > 0) {
		s = (size_t)zip->entry_bytes_remaining;
		if (s > a->null_length)
			s = a->null_length;
		r = _7z_write_data(a, a->nulls, s);
		if (r < 0)
			return ((int)r);
	}
	zip->total_bytes_compressed += zip->stream.total_in;
	zip->total_bytes_uncompressed += zip->stream.total_out;
	zip->cur_file->crc32 = zip->entry_crc32;
	zip->cur_file = NULL;

	return (ARCHIVE_OK);
}

static int
flush_wbuff(struct archive_write *a)
{
	struct _7zip *zip;
	int r;
	size_t s;

	zip = (struct _7zip *)a->format_data;
	s = sizeof(zip->wbuff) - zip->wbuff_remaining;
	r = __archive_write_output(a, zip->wbuff, s);
	if (r != ARCHIVE_OK)
		return (r);
	zip->wbuff_remaining = sizeof(zip->wbuff);
	return (r);
}

static int
copy_out(struct archive_write *a, uint64_t offset, uint64_t length)
{
	struct _7zip *zip;
	int r;

	zip = (struct _7zip *)a->format_data;
	if (zip->temp_offset > 0 &&
	    lseek(zip->temp_fd, offset, SEEK_SET) < 0) {
		archive_set_error(&(a->archive), errno, "lseek failed");
		return (ARCHIVE_FATAL);
	}
	while (length) {
		size_t rsize;
		ssize_t rs;
		unsigned char *wb;

		if (length > zip->wbuff_remaining)
			rsize = zip->wbuff_remaining;
		else
			rsize = (size_t)length;
		wb = zip->wbuff + (sizeof(zip->wbuff) - zip->wbuff_remaining);
		rs = read(zip->temp_fd, wb, rsize);
		if (rs < 0) {
			archive_set_error(&(a->archive), errno,
			    "Can't read temporary file(%jd)",
			    (intmax_t)rs);
			return (ARCHIVE_FATAL);
		}
		if (rs == 0) {
			archive_set_error(&(a->archive), 0,
			    "Truncated 7-Zip archive");
			return (ARCHIVE_FATAL);
		}
		zip->wbuff_remaining -= rs;
		length -= rs;
		if (zip->wbuff_remaining == 0) {
			r = flush_wbuff(a);
			if (r != ARCHIVE_OK)
				return (r);
		}
	}
	return (ARCHIVE_OK);
}

static int
_7z_close(struct archive_write *a)
{
	struct _7zip *zip;
	unsigned char *wb;
	uint64_t header_offset, header_size, header_unpacksize;
	uint64_t length;
	uint32_t header_crc32;
	int r;

	zip = (struct _7zip *)a->format_data;

	if (zip->total_number_entry > 0) {
		struct archive_rb_node *n;
		uint64_t data_offset, data_size, data_unpacksize;
		unsigned header_compression;

		r = (int)compress_out(a, NULL, 0, ARCHIVE_Z_FINISH);
		if (r < 0)
			return (r);
		data_offset = 0;
		data_size = zip->stream.total_out;
		data_unpacksize = zip->stream.total_in;
		zip->coder.codec = zip->opt_compression;
		zip->coder.prop_size = zip->stream.prop_size;
		zip->coder.props = zip->stream.props;
		zip->stream.prop_size = 0;
		zip->stream.props = NULL;
		zip->total_number_nonempty_entry =
		    zip->total_number_entry - zip->total_number_empty_entry;

		/* Connect an empty file list. */
		if (zip->empty_list.first != NULL) {
			*zip->file_list.last = zip->empty_list.first;
			zip->file_list.last = zip->empty_list.last;
		}
		/* Connect a directory file list. */
		ARCHIVE_RB_TREE_FOREACH(n, &(zip->rbtree)) {
			file_register(zip, (struct file *)n);
		}

		/*
		 * NOTE: 7z command supports just LZMA1, LZMA2 and COPY for
		 * the compression type for encoding the header.
		 */
#if HAVE_LZMA_H
		header_compression = _7Z_LZMA1;
		/* If the stored file is only one, do not encode the header.
		 * This is the same way 7z command does. */
		if (zip->total_number_entry == 1)
			header_compression = _7Z_COPY;
#else
		header_compression = _7Z_COPY;
#endif
		r = _7z_compression_init_encoder(a, header_compression, 6);
		if (r < 0)
			return (r);
		zip->crc32flg = PRECODE_CRC32;
		zip->precode_crc32 = 0;
		r = make_header(a, data_offset, data_size, data_unpacksize,
			1, &(zip->coder));
		if (r < 0)
			return (r);
		r = (int)compress_out(a, NULL, 0, ARCHIVE_Z_FINISH);
		if (r < 0)
			return (r);
		header_offset = data_offset + data_size;
		header_size = zip->stream.total_out;
		header_crc32 = zip->precode_crc32;
		header_unpacksize = zip->stream.total_in;

		if (header_compression != _7Z_COPY) {
			/*
			 * Encode the header in order to reduce the size
			 * of the archive.
			 */
			free(zip->coder.props);
			zip->coder.codec = header_compression;
			zip->coder.prop_size = zip->stream.prop_size;
			zip->coder.props = zip->stream.props;
			zip->stream.prop_size = 0;
			zip->stream.props = NULL;

			r = _7z_compression_init_encoder(a, _7Z_COPY, 0);
			if (r < 0)
				return (r);
			zip->crc32flg = ENCODED_CRC32;
			zip->encoded_crc32 = 0;

			/*
			 * Make EncodedHeader.
			 */
			r = enc_uint64(a, kEncodedHeader);
			if (r < 0)
				return (r);
			r = make_streamsInfo(a, header_offset, header_size,
			      header_unpacksize, 1, &(zip->coder), 0,
			      header_crc32);
			if (r < 0)
				return (r);
			r = (int)compress_out(a, NULL, 0, ARCHIVE_Z_FINISH);
			if (r < 0)
				return (r);
			header_offset = header_offset + header_size;
			header_size = zip->stream.total_out;
			header_crc32 = zip->encoded_crc32;
		}
		zip->crc32flg = 0;
	} else {
		header_offset = header_size = 0;
		header_crc32 = 0;
	}
	
	length = zip->temp_offset;

	/*
	 * Make the zip header on wbuff(write buffer).
	 */
	wb = zip->wbuff;
	zip->wbuff_remaining = sizeof(zip->wbuff);
	memcpy(&wb[0], "7z\xBC\xAF\x27\x1C", 6);
	wb[6] = 0;/* Major version. */
	wb[7] = 3;/* Minor version. */
	archive_le64enc(&wb[12], header_offset);/* Next Header Offset */
	archive_le64enc(&wb[20], header_size);/* Next Header Size */
	archive_le32enc(&wb[28], header_crc32);/* Next Header CRC */
	archive_le32enc(&wb[8], crc32(0, &wb[12], 20));/* Start Header CRC */
	zip->wbuff_remaining -= 32;

	/*
	 * Read all file contents and an encoded header from the temporary
	 * file and write out it.
	 */
	r = copy_out(a, 0, length);
	if (r != ARCHIVE_OK)
		return (r);
	r = flush_wbuff(a);
	return (r);
}

/*
 * Encode 64 bits value into 7-Zip's encoded UINT64 value.
 */
static int
enc_uint64(struct archive_write *a, uint64_t val)
{
	unsigned mask = 0x80;
	uint8_t numdata[9];
	int i;

	numdata[0] = 0;
	for (i = 1; i < (int)sizeof(numdata); i++) {
		if (val < mask) {
			numdata[0] |= (uint8_t)val;
			break;
		}
		numdata[i] = (uint8_t)val;
		val >>= 8;
		numdata[0] |= mask;
		mask >>= 1;
	}
	return ((int)compress_out(a, numdata, i, ARCHIVE_Z_RUN));
}

static int
make_substreamsInfo(struct archive_write *a, struct coder *coders)
{
	struct _7zip *zip = (struct _7zip *)a->format_data;
	struct file *file;
	int r;

	/*
	 * Make SubStreamsInfo.
	 */
	r = enc_uint64(a, kSubStreamsInfo);
	if (r < 0)
		return (r);

	if (zip->total_number_nonempty_entry > 1 && coders->codec != _7Z_COPY) {
		/*
		 * Make NumUnPackStream.
		 */
		r = enc_uint64(a, kNumUnPackStream);
		if (r < 0)
			return (r);

		/* Write numUnpackStreams */
		r = enc_uint64(a, zip->total_number_nonempty_entry);
		if (r < 0)
			return (r);

		/*
		 * Make kSize.
		 */
		r = enc_uint64(a, kSize);
		if (r < 0)
			return (r);
		file = zip->file_list.first;
		for (;file != NULL; file = file->next) {
			if (file->next == NULL ||
			    file->next->size == 0)
				break;
			r = enc_uint64(a, file->size);
			if (r < 0)
				return (r);
		}
	}

	/*
	 * Make CRC.
	 */
	r = enc_uint64(a, kCRC);
	if (r < 0)
		return (r);


	/* All are defined */
	r = enc_uint64(a, 1);
	if (r < 0)
		return (r);
	file = zip->file_list.first;
	for (;file != NULL; file = file->next) {
		uint8_t crc[4];
		if (file->size == 0)
			break;
		archive_le32enc(crc, file->crc32);
		r = (int)compress_out(a, crc, 4, ARCHIVE_Z_RUN);
		if (r < 0)
			return (r);
	}

	/* Write End. */
	r = enc_uint64(a, kEnd);
	if (r < 0)
		return (r);
	return (ARCHIVE_OK);
}

static int
make_streamsInfo(struct archive_write *a, uint64_t offset, uint64_t pack_size,
    uint64_t unpack_size, int num_coder, struct coder *coders, int substrm,
    uint32_t header_crc)
{
	struct _7zip *zip = (struct _7zip *)a->format_data;
	uint8_t codec_buff[8];
	int numFolders, fi;
	int codec_size;
	int i, r;

	if (coders->codec == _7Z_COPY)
		numFolders = (int)zip->total_number_nonempty_entry;
	else
		numFolders = 1;

	/*
	 * Make PackInfo.
	 */
	r = enc_uint64(a, kPackInfo);
	if (r < 0)
		return (r);

	/* Write PackPos. */
	r = enc_uint64(a, offset);
	if (r < 0)
		return (r);

	/* Write NumPackStreams. */
	r = enc_uint64(a, numFolders);
	if (r < 0)
		return (r);

	/* Make Size. */
	r = enc_uint64(a, kSize);
	if (r < 0)
		return (r);

	if (numFolders > 1) {
		struct file *file = zip->file_list.first;
		for (;file != NULL; file = file->next) {
			if (file->size == 0)
				break;
			r = enc_uint64(a, file->size);
			if (r < 0)
				return (r);
		}
	} else {
		/* Write size. */
		r = enc_uint64(a, pack_size);
		if (r < 0)
			return (r);
	}

	r = enc_uint64(a, kEnd);
	if (r < 0)
		return (r);

	/*
	 * Make UnPackInfo.
	 */
	r = enc_uint64(a, kUnPackInfo);
	if (r < 0)
		return (r);

	/*
	 * Make Folder.
	 */
	r = enc_uint64(a, kFolder);
	if (r < 0)
		return (r);

	/* Write NumFolders. */
	r = enc_uint64(a, numFolders);
	if (r < 0)
		return (r);

	/* Write External. */
	r = enc_uint64(a, 0);
	if (r < 0)
		return (r);

	for (fi = 0; fi < numFolders; fi++) {
		/* Write NumCoders. */
		r = enc_uint64(a, num_coder);
		if (r < 0)
			return (r);

		for (i = 0; i < num_coder; i++) {
			unsigned codec_id = coders[i].codec;

			/* Write Codec flag. */
			archive_be64enc(codec_buff, codec_id);
			for (codec_size = 8; codec_size > 0; codec_size--) {
				if (codec_buff[8 - codec_size])
					break;
			}
			if (codec_size == 0)
				codec_size = 1;
			if (coders[i].prop_size)
				r = enc_uint64(a, codec_size | 0x20);
			else
				r = enc_uint64(a, codec_size);
			if (r < 0)
				return (r);

			/* Write Codec ID. */
			codec_size &= 0x0f;
			r = (int)compress_out(a, &codec_buff[8-codec_size],
				codec_size, ARCHIVE_Z_RUN);
			if (r < 0)
				return (r);

			if (coders[i].prop_size) {
				/* Write Codec property size. */
				r = enc_uint64(a, coders[i].prop_size);
				if (r < 0)
					return (r);

				/* Write Codec properties. */
				r = (int)compress_out(a, coders[i].props,
					coders[i].prop_size, ARCHIVE_Z_RUN);
				if (r < 0)
					return (r);
			}
		}
	}

	/*
	 * Make CodersUnPackSize.
	 */
	r = enc_uint64(a, kCodersUnPackSize);
	if (r < 0)
		return (r);

	if (numFolders > 1) {
		struct file *file = zip->file_list.first;
		for (;file != NULL; file = file->next) {
			if (file->size == 0)
				break;
			r = enc_uint64(a, file->size);
			if (r < 0)
				return (r);
		}

	} else {
		/* Write UnPackSize. */
		r = enc_uint64(a, unpack_size);
		if (r < 0)
			return (r);
	}

	if (!substrm) {
		uint8_t crc[4];
		/*
		 * Make CRC.
		 */
		r = enc_uint64(a, kCRC);
		if (r < 0)
			return (r);

		/* All are defined */
		r = enc_uint64(a, 1);
		if (r < 0)
			return (r);
		archive_le32enc(crc, header_crc);
		r = (int)compress_out(a, crc, 4, ARCHIVE_Z_RUN);
		if (r < 0)
			return (r);
	}

	/* Write End. */
	r = enc_uint64(a, kEnd);
	if (r < 0)
		return (r);

	if (substrm) {
		/*
		 * Make SubStreamsInfo.
		 */
		r = make_substreamsInfo(a, coders);
		if (r < 0)
			return (r);
	}


	/* Write End. */
	r = enc_uint64(a, kEnd);
	if (r < 0)
		return (r);

	return (ARCHIVE_OK);
}


#define EPOC_TIME ARCHIVE_LITERAL_ULL(116444736000000000)
static uint64_t
utcToFiletime(time_t t, long ns)
{
	uint64_t fileTime;

	fileTime = t;
	fileTime *= 10000000;
	fileTime += ns / 100;
	fileTime += EPOC_TIME;
	return (fileTime);
}

static int
make_time(struct archive_write *a, uint8_t type, unsigned flg, int ti)
{
	uint8_t filetime[8];
	struct _7zip *zip = (struct _7zip *)a->format_data;
	struct file *file;
	int r;
	uint8_t b, mask;

	/*
	 * Make Time Bools.
	 */
	if (zip->total_number_time_defined[ti] == zip->total_number_entry) {
		/* Write Time Type. */
		r = enc_uint64(a, type);
		if (r < 0)
			return (r);
		/* Write EmptyStream Size. */
		r = enc_uint64(a, 2 + zip->total_number_entry * 8);
		if (r < 0)
			return (r);
		/* All are defined. */
		r = enc_uint64(a, 1);
		if (r < 0)
			return (r);
	} else {
		if (zip->total_number_time_defined[ti] == 0)
			return (ARCHIVE_OK);

		/* Write Time Type. */
		r = enc_uint64(a, type);
		if (r < 0)
			return (r);
		/* Write EmptyStream Size. */
		r = enc_uint64(a, 2 + ((zip->total_number_entry + 7) >> 3)
			+ zip->total_number_time_defined[ti] * 8);
		if (r < 0)
			return (r);

		/* All are not defined. */
		r = enc_uint64(a, 0);
		if (r < 0)
			return (r);

		b = 0;
		mask = 0x80;
		file = zip->file_list.first;
		for (;file != NULL; file = file->next) {
			if (file->flg & flg)
				b |= mask;
			mask >>= 1;
			if (mask == 0) {
				r = (int)compress_out(a, &b, 1, ARCHIVE_Z_RUN);
				if (r < 0)
					return (r);
				mask = 0x80;
				b = 0;
			}
		}
		if (mask != 0x80) {
			r = (int)compress_out(a, &b, 1, ARCHIVE_Z_RUN);
			if (r < 0)
				return (r);
		}
	}

	/* External. */
	r = enc_uint64(a, 0);
	if (r < 0)
		return (r);


	/*
	 * Make Times.
	 */
	file = zip->file_list.first;
	for (;file != NULL; file = file->next) {
		if ((file->flg & flg) == 0)
			continue;
		archive_le64enc(filetime, utcToFiletime(file->times[ti].time,
			file->times[ti].time_ns));
		r = (int)compress_out(a, filetime, 8, ARCHIVE_Z_RUN);
		if (r < 0)
			return (r);
	}

	return (ARCHIVE_OK);
}

static int
make_header(struct archive_write *a, uint64_t offset, uint64_t pack_size,
    uint64_t unpack_size, int codernum, struct coder *coders)
{
	struct _7zip *zip = (struct _7zip *)a->format_data;
	struct file *file;
	int r;
	uint8_t b, mask;

	/*
	 * Make FilesInfo.
	 */
	r = enc_uint64(a, kHeader);
	if (r < 0)
		return (r);

	/*
	 * If there are empty files only, do not write MainStreamInfo.
	 */
	if (zip->total_number_nonempty_entry) {
		/*
		 * Make MainStreamInfo.
		 */
		r = enc_uint64(a, kMainStreamsInfo);
		if (r < 0)
			return (r);
		r = make_streamsInfo(a, offset, pack_size, unpack_size,
		      codernum, coders, 1, 0);
		if (r < 0)
			return (r);
	}

	/*
	 * Make FilesInfo.
	 */
	r = enc_uint64(a, kFilesInfo);
	if (r < 0)
		return (r);

	/* Write numFiles. */
	r = enc_uint64(a, zip->total_number_entry);
	if (r < 0)
		return (r);

	if (zip->total_number_empty_entry > 0) {
		/* Make EmptyStream. */
		r = enc_uint64(a, kEmptyStream);
		if (r < 0)
			return (r);

		/* Write EmptyStream Size. */
		r = enc_uint64(a, (zip->total_number_entry+7)>>3);
		if (r < 0)
			return (r);

		b = 0;
		mask = 0x80;
		file = zip->file_list.first;
		for (;file != NULL; file = file->next) {
			if (file->size == 0)
				b |= mask;
			mask >>= 1;
			if (mask == 0) {
				r = (int)compress_out(a, &b, 1, ARCHIVE_Z_RUN);
				if (r < 0)
					return (r);
				mask = 0x80;
				b = 0;
			}
		}
		if (mask != 0x80) {
			r = (int)compress_out(a, &b, 1, ARCHIVE_Z_RUN);
			if (r < 0)
				return (r);
		}
	}

	if (zip->total_number_empty_entry > zip->total_number_dir_entry) {
		/* Make EmptyFile. */
		r = enc_uint64(a, kEmptyFile);
		if (r < 0)
			return (r);

		/* Write EmptyFile Size. */
		r = enc_uint64(a, (zip->total_number_empty_entry + 7) >> 3);
		if (r < 0)
			return (r);

		b = 0;
		mask = 0x80;
		file = zip->file_list.first;
		for (;file != NULL; file = file->next) {
			if (file->size)
				continue;
			if (!file->dir)
				b |= mask;
			mask >>= 1;
			if (mask == 0) {
				r = (int)compress_out(a, &b, 1, ARCHIVE_Z_RUN);
				if (r < 0)
					return (r);
				mask = 0x80;
				b = 0;
			}
		}
		if (mask != 0x80) {
			r = (int)compress_out(a, &b, 1, ARCHIVE_Z_RUN);
			if (r < 0)
				return (r);
		}
	}

	/* Make Name. */
	r = enc_uint64(a, kName);
	if (r < 0)
		return (r);

	/* Write Name size. */
	r = enc_uint64(a, zip->total_bytes_entry_name+1);
	if (r < 0)
		return (r);

	/* Write dmy byte. */
	r = enc_uint64(a, 0);
	if (r < 0)
		return (r);

	file = zip->file_list.first;
	for (;file != NULL; file = file->next) {
		r = (int)compress_out(a, file->utf16name, file->name_len+2,
			ARCHIVE_Z_RUN);
		if (r < 0)
			return (r);
	}

	/* Make MTime. */
	r = make_time(a, kMTime, MTIME_IS_SET, MTIME);
	if (r < 0)
		return (r);

	/* Make CTime. */
	r = make_time(a, kCTime, CTIME_IS_SET, CTIME);
	if (r < 0)
		return (r);

	/* Make ATime. */
	r = make_time(a, kATime, ATIME_IS_SET, ATIME);
	if (r < 0)
		return (r);

	/* Make Attributes. */
	r = enc_uint64(a, kAttributes);
	if (r < 0)
		return (r);

	/* Write Attributes size. */
	r = enc_uint64(a, 2 + zip->total_number_entry * 4);
	if (r < 0)
		return (r);

	/* Write "All Are Defined". */
	r = enc_uint64(a, 1);
	if (r < 0)
		return (r);

	/* Write dmy byte. */
	r = enc_uint64(a, 0);
	if (r < 0)
		return (r);

	file = zip->file_list.first;
	for (;file != NULL; file = file->next) {
		/*
		 * High 16bits is unix mode.
		 * Low 16bits is Windows attributes.
		 */
		uint32_t encattr, attr;
		if (file->dir)
			attr = 0x8010;
		else
			attr = 0x8020;
		if ((file->mode & 0222) == 0)
			attr |= 1;/* Read Only. */
		attr |= ((uint32_t)file->mode) << 16;
		archive_le32enc(&encattr, attr);
		r = (int)compress_out(a, &encattr, 4, ARCHIVE_Z_RUN);
		if (r < 0)
			return (r);
	}

	/* Write End. */
	r = enc_uint64(a, kEnd);
	if (r < 0)
		return (r);

	/* Write End. */
	r = enc_uint64(a, kEnd);
	if (r < 0)
		return (r);

	return (ARCHIVE_OK);
}


static int
_7z_free(struct archive_write *a)
{
	struct _7zip *zip = (struct _7zip *)a->format_data;

	/* Close the temporary file. */
	if (zip->temp_fd >= 0)
		close(zip->temp_fd);

	file_free_register(zip);
	compression_end(&(a->archive), &(zip->stream));
	free(zip->coder.props);
	free(zip);

	return (ARCHIVE_OK);
}

static int
file_cmp_node(const struct archive_rb_node *n1,
    const struct archive_rb_node *n2)
{
	const struct file *f1 = (const struct file *)n1;
	const struct file *f2 = (const struct file *)n2;

	if (f1->name_len == f2->name_len)
		return (memcmp(f1->utf16name, f2->utf16name, f1->name_len));
	return (f1->name_len > f2->name_len)?1:-1;
}
        
static int
file_cmp_key(const struct archive_rb_node *n, const void *key)
{
	const struct file *f = (const struct file *)n;

	return (f->name_len - *(const char *)key);
}

static int
file_new(struct archive_write *a, struct archive_entry *entry,
    struct file **newfile)
{
	struct _7zip *zip;
	struct file *file;
	const char *u16;
	size_t u16len;
	int ret = ARCHIVE_OK;

	zip = (struct _7zip *)a->format_data;
	*newfile = NULL;

	file = calloc(1, sizeof(*file));
	if (file == NULL) {
		archive_set_error(&a->archive, ENOMEM,
		    "Can't allocate memory");
		return (ARCHIVE_FATAL);
	}

	if (0 > archive_entry_pathname_l(entry, &u16, &u16len, zip->sconv)) {
		if (errno == ENOMEM) {
			free(file);
			archive_set_error(&a->archive, ENOMEM,
			    "Can't allocate memory for UTF-16LE");
			return (ARCHIVE_FATAL);
		}
		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
		    "A filename cannot be converted to UTF-16LE;"
		    "You should disable making Joliet extension");
		ret = ARCHIVE_WARN;
	}
	file->utf16name = malloc(u16len + 2);
	if (file->utf16name == NULL) {
		free(file);
		archive_set_error(&a->archive, ENOMEM,
		    "Can't allocate memory for Name");
		return (ARCHIVE_FATAL);
	}
	memcpy(file->utf16name, u16, u16len);
	file->utf16name[u16len+0] = 0;
	file->utf16name[u16len+1] = 0;
	file->name_len = (unsigned)u16len;
	file->mode = archive_entry_mode(entry);
	if (archive_entry_filetype(entry) == AE_IFREG)
		file->size = archive_entry_size(entry);
	else
		archive_entry_set_size(entry, 0);
	if (archive_entry_filetype(entry) == AE_IFDIR)
		file->dir = 1;
	else if (archive_entry_filetype(entry) == AE_IFLNK)
		file->size = strlen(archive_entry_symlink(entry));
	if (archive_entry_mtime_is_set(entry)) {
		file->flg |= MTIME_IS_SET;
		file->times[MTIME].time = archive_entry_mtime(entry);
		file->times[MTIME].time_ns = archive_entry_mtime_nsec(entry);
	}
	if (archive_entry_atime_is_set(entry)) {
		file->flg |= ATIME_IS_SET;
		file->times[ATIME].time = archive_entry_atime(entry);
		file->times[ATIME].time_ns = archive_entry_atime_nsec(entry);
	}
	if (archive_entry_ctime_is_set(entry)) {
		file->flg |= CTIME_IS_SET;
		file->times[CTIME].time = archive_entry_ctime(entry);
		file->times[CTIME].time_ns = archive_entry_ctime_nsec(entry);
	}

	*newfile = file;
	return (ret);
}

static void
file_free(struct file *file)
{
	free(file->utf16name);
	free(file);
}

static void
file_register(struct _7zip *zip, struct file *file)
{
	file->next = NULL;
	*zip->file_list.last = file;
	zip->file_list.last = &(file->next);
}

static void
file_init_register(struct _7zip *zip)
{
	zip->file_list.first = NULL;
	zip->file_list.last = &(zip->file_list.first);
}

static void
file_free_register(struct _7zip *zip)
{
	struct file *file, *file_next;

	file = zip->file_list.first;
	while (file != NULL) {
		file_next = file->next;
		file_free(file);
		file = file_next;
	}
}

static void
file_register_empty(struct _7zip *zip, struct file *file)
{
	file->next = NULL;
	*zip->empty_list.last = file;
	zip->empty_list.last = &(file->next);
}

static void
file_init_register_empty(struct _7zip *zip)
{
	zip->empty_list.first = NULL;
	zip->empty_list.last = &(zip->empty_list.first);
}

#if !defined(HAVE_ZLIB_H) || !defined(HAVE_BZLIB_H) ||\
	 !defined(BZ_CONFIG_ERROR) || !defined(HAVE_LZMA_H)
static int
compression_unsupported_encoder(struct archive *a,
    struct la_zstream *lastrm, const char *name)
{

	archive_set_error(a, ARCHIVE_ERRNO_MISC,
	    "%s compression not supported on this platform", name);
	lastrm->valid = 0;
	lastrm->real_stream = NULL;
	return (ARCHIVE_FAILED);
}
#endif

/*
 * _7_COPY compressor.
 */
static int
compression_init_encoder_copy(struct archive *a, struct la_zstream *lastrm)
{

	if (lastrm->valid)
		compression_end(a, lastrm);
	lastrm->valid = 1;
	lastrm->code = compression_code_copy;
	lastrm->end = compression_end_copy;
	return (ARCHIVE_OK);
}

static int
compression_code_copy(struct archive *a,
    struct la_zstream *lastrm, enum la_zaction action)
{
	size_t bytes;

	(void)a; /* UNUSED */
	if (lastrm->avail_out > lastrm->avail_in)
		bytes = lastrm->avail_in;
	else
		bytes = lastrm->avail_out;
	if (bytes) {
		memcpy(lastrm->next_out, lastrm->next_in, bytes);
		lastrm->next_in += bytes;
		lastrm->avail_in -= bytes;
		lastrm->total_in += bytes;
		lastrm->next_out += bytes;
		lastrm->avail_out -= bytes;
		lastrm->total_out += bytes;
	}
	if (action == ARCHIVE_Z_FINISH && lastrm->avail_in == 0)
		return (ARCHIVE_EOF);
	return (ARCHIVE_OK);
}

static int
compression_end_copy(struct archive *a, struct la_zstream *lastrm)
{
	(void)a; /* UNUSED */
	lastrm->valid = 0;
	return (ARCHIVE_OK);
}

/*
 * _7_DEFLATE compressor.
 */
#ifdef HAVE_ZLIB_H
static int
compression_init_encoder_deflate(struct archive *a,
    struct la_zstream *lastrm, int level, int withheader)
{
	z_stream *strm;

	if (lastrm->valid)
		compression_end(a, lastrm);
	strm = calloc(1, sizeof(*strm));
	if (strm == NULL) {
		archive_set_error(a, ENOMEM,
		    "Can't allocate memory for gzip stream");
		return (ARCHIVE_FATAL);
	}
	/* zlib.h is not const-correct, so we need this one bit
	 * of ugly hackery to convert a const * pointer to
	 * a non-const pointer. */
	strm->next_in = (Bytef *)(uintptr_t)(const void *)lastrm->next_in;
	strm->avail_in = (uInt)lastrm->avail_in;
	strm->total_in = (uLong)lastrm->total_in;
	strm->next_out = lastrm->next_out;
	strm->avail_out = (uInt)lastrm->avail_out;
	strm->total_out = (uLong)lastrm->total_out;
	if (deflateInit2(strm, level, Z_DEFLATED,
	    (withheader)?15:-15,
	    8, Z_DEFAULT_STRATEGY) != Z_OK) {
		free(strm);
		lastrm->real_stream = NULL;
		archive_set_error(a, ARCHIVE_ERRNO_MISC,
		    "Internal error initializing compression library");
		return (ARCHIVE_FATAL);
	}
	lastrm->real_stream = strm;
	lastrm->valid = 1;
	lastrm->code = compression_code_deflate;
	lastrm->end = compression_end_deflate;
	return (ARCHIVE_OK);
}

static int
compression_code_deflate(struct archive *a,
    struct la_zstream *lastrm, enum la_zaction action)
{
	z_stream *strm;
	int r;

	strm = (z_stream *)lastrm->real_stream;
	/* zlib.h is not const-correct, so we need this one bit
	 * of ugly hackery to convert a const * pointer to
	 * a non-const pointer. */
	strm->next_in = (Bytef *)(uintptr_t)(const void *)lastrm->next_in;
	strm->avail_in = (uInt)lastrm->avail_in;
	strm->total_in = (uLong)lastrm->total_in;
	strm->next_out = lastrm->next_out;
	strm->avail_out = (uInt)lastrm->avail_out;
	strm->total_out = (uLong)lastrm->total_out;
	r = deflate(strm,
	    (action == ARCHIVE_Z_FINISH)? Z_FINISH: Z_NO_FLUSH);
	lastrm->next_in = strm->next_in;
	lastrm->avail_in = strm->avail_in;
	lastrm->total_in = strm->total_in;
	lastrm->next_out = strm->next_out;
	lastrm->avail_out = strm->avail_out;
	lastrm->total_out = strm->total_out;
	switch (r) {
	case Z_OK:
		return (ARCHIVE_OK);
	case Z_STREAM_END:
		return (ARCHIVE_EOF);
	default:
		archive_set_error(a, ARCHIVE_ERRNO_MISC,
		    "GZip compression failed:"
		    " deflate() call returned status %d", r);
		return (ARCHIVE_FATAL);
	}
}

static int
compression_end_deflate(struct archive *a, struct la_zstream *lastrm)
{
	z_stream *strm;
	int r;

	strm = (z_stream *)lastrm->real_stream;
	r = deflateEnd(strm);
	free(strm);
	lastrm->real_stream = NULL;
	lastrm->valid = 0;
	if (r != Z_OK) {
		archive_set_error(a, ARCHIVE_ERRNO_MISC,
		    "Failed to clean up compressor");
		return (ARCHIVE_FATAL);
	}
	return (ARCHIVE_OK);
}
#else
static int
compression_init_encoder_deflate(struct archive *a,
    struct la_zstream *lastrm, int level, int withheader)
{

	(void) level; /* UNUSED */
	(void) withheader; /* UNUSED */
	if (lastrm->valid)
		compression_end(a, lastrm);
	return (compression_unsupported_encoder(a, lastrm, "deflate"));
}
#endif

/*
 * _7_BZIP2 compressor.
 */
#if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR)
static int
compression_init_encoder_bzip2(struct archive *a,
    struct la_zstream *lastrm, int level)
{
	bz_stream *strm;

	if (lastrm->valid)
		compression_end(a, lastrm);
	strm = calloc(1, sizeof(*strm));
	if (strm == NULL) {
		archive_set_error(a, ENOMEM,
		    "Can't allocate memory for bzip2 stream");
		return (ARCHIVE_FATAL);
	}
	/* bzlib.h is not const-correct, so we need this one bit
	 * of ugly hackery to convert a const * pointer to
	 * a non-const pointer. */
	strm->next_in = (char *)(uintptr_t)(const void *)lastrm->next_in;
	strm->avail_in = lastrm->avail_in;
	strm->total_in_lo32 = (uint32_t)(lastrm->total_in & 0xffffffff);
	strm->total_in_hi32 = (uint32_t)(lastrm->total_in >> 32);
	strm->next_out = (char *)lastrm->next_out;
	strm->avail_out = lastrm->avail_out;
	strm->total_out_lo32 = (uint32_t)(lastrm->total_out & 0xffffffff);
	strm->total_out_hi32 = (uint32_t)(lastrm->total_out >> 32);
	if (BZ2_bzCompressInit(strm, level, 0, 30) != BZ_OK) {
		free(strm);
		lastrm->real_stream = NULL;
		archive_set_error(a, ARCHIVE_ERRNO_MISC,
		    "Internal error initializing compression library");
		return (ARCHIVE_FATAL);
	}
	lastrm->real_stream = strm;
	lastrm->valid = 1;
	lastrm->code = compression_code_bzip2;
	lastrm->end = compression_end_bzip2;
	return (ARCHIVE_OK);
}

static int
compression_code_bzip2(struct archive *a,
    struct la_zstream *lastrm, enum la_zaction action)
{
	bz_stream *strm;
	int r;

	strm = (bz_stream *)lastrm->real_stream;
	/* bzlib.h is not const-correct, so we need this one bit
	 * of ugly hackery to convert a const * pointer to
	 * a non-const pointer. */
	strm->next_in = (char *)(uintptr_t)(const void *)lastrm->next_in;
	strm->avail_in = lastrm->avail_in;
	strm->total_in_lo32 = (uint32_t)(lastrm->total_in & 0xffffffff);
	strm->total_in_hi32 = (uint32_t)(lastrm->total_in >> 32);
	strm->next_out = (char *)lastrm->next_out;
	strm->avail_out = lastrm->avail_out;
	strm->total_out_lo32 = (uint32_t)(lastrm->total_out & 0xffffffff);
	strm->total_out_hi32 = (uint32_t)(lastrm->total_out >> 32);
	r = BZ2_bzCompress(strm,
	    (action == ARCHIVE_Z_FINISH)? BZ_FINISH: BZ_RUN);
	lastrm->next_in = (const unsigned char *)strm->next_in;
	lastrm->avail_in = strm->avail_in;
	lastrm->total_in =
	    (((uint64_t)(uint32_t)strm->total_in_hi32) << 32)
	    + (uint64_t)(uint32_t)strm->total_in_lo32;
	lastrm->next_out = (unsigned char *)strm->next_out;
	lastrm->avail_out = strm->avail_out;
	lastrm->total_out =
	    (((uint64_t)(uint32_t)strm->total_out_hi32) << 32)
	    + (uint64_t)(uint32_t)strm->total_out_lo32;
	switch (r) {
	case BZ_RUN_OK:     /* Non-finishing */
	case BZ_FINISH_OK:  /* Finishing: There's more work to do */
		return (ARCHIVE_OK);
	case BZ_STREAM_END: /* Finishing: all done */
		/* Only occurs in finishing case */
		return (ARCHIVE_EOF);
	default:
		/* Any other return value indicates an error */
		archive_set_error(a, ARCHIVE_ERRNO_MISC,
		    "Bzip2 compression failed:"
		    " BZ2_bzCompress() call returned status %d", r);
		return (ARCHIVE_FATAL);
	}
}

static int
compression_end_bzip2(struct archive *a, struct la_zstream *lastrm)
{
	bz_stream *strm;
	int r;

	strm = (bz_stream *)lastrm->real_stream;
	r = BZ2_bzCompressEnd(strm);
	free(strm);
	lastrm->real_stream = NULL;
	lastrm->valid = 0;
	if (r != BZ_OK) {
		archive_set_error(a, ARCHIVE_ERRNO_MISC,
		    "Failed to clean up compressor");
		return (ARCHIVE_FATAL);
	}
	return (ARCHIVE_OK);
}

#else
static int
compression_init_encoder_bzip2(struct archive *a,
    struct la_zstream *lastrm, int level)
{

	(void) level; /* UNUSED */
	if (lastrm->valid)
		compression_end(a, lastrm);
	return (compression_unsupported_encoder(a, lastrm, "bzip2"));
}
#endif

/*
 * _7_LZMA1, _7_LZMA2 compressor.
 */
#if defined(HAVE_LZMA_H)
static int
compression_init_encoder_lzma(struct archive *a,
    struct la_zstream *lastrm, int level, uint64_t filter_id)
{
	static const lzma_stream lzma_init_data = LZMA_STREAM_INIT;
	lzma_stream *strm;
	lzma_filter *lzmafilters;
	lzma_options_lzma lzma_opt;
	int r;

	if (lastrm->valid)
		compression_end(a, lastrm);
	strm = calloc(1, sizeof(*strm) + sizeof(*lzmafilters) * 2);
	if (strm == NULL) {
		archive_set_error(a, ENOMEM,
		    "Can't allocate memory for lzma stream");
		return (ARCHIVE_FATAL);
	}
	lzmafilters = (lzma_filter *)(strm+1);
	if (level > 6)
		level = 6;
	if (lzma_lzma_preset(&lzma_opt, level)) {
		free(strm);
		lastrm->real_stream = NULL;
		archive_set_error(a, ENOMEM,
		    "Internal error initializing compression library");
		return (ARCHIVE_FATAL);
	}
	lzmafilters[0].id = filter_id;
	lzmafilters[0].options = &lzma_opt;
	lzmafilters[1].id = LZMA_VLI_UNKNOWN;/* Terminate */

	r = lzma_properties_size(&(lastrm->prop_size), lzmafilters);
	if (r != LZMA_OK) {
		free(strm);
		lastrm->real_stream = NULL;
		archive_set_error(a, ARCHIVE_ERRNO_MISC,
		    "lzma_properties_size failed");
		return (ARCHIVE_FATAL);
	}
	if (lastrm->prop_size) {
		lastrm->props = malloc(lastrm->prop_size);
		if (lastrm->props == NULL) {
			free(strm);
			lastrm->real_stream = NULL;
			archive_set_error(a, ENOMEM,
			    "Cannot allocate memory");
			return (ARCHIVE_FATAL);
		}
		r = lzma_properties_encode(lzmafilters,  lastrm->props);
		if (r != LZMA_OK) {
			free(strm);
			lastrm->real_stream = NULL;
			archive_set_error(a, ARCHIVE_ERRNO_MISC,
			    "lzma_properties_encode failed");
			return (ARCHIVE_FATAL);
		}
	}

	*strm = lzma_init_data;
	r = lzma_raw_encoder(strm, lzmafilters);
	switch (r) {
	case LZMA_OK:
		lastrm->real_stream = strm;
		lastrm->valid = 1;
		lastrm->code = compression_code_lzma;
		lastrm->end = compression_end_lzma;
		r = ARCHIVE_OK;
		break;
	case LZMA_MEM_ERROR:
		free(strm);
		lastrm->real_stream = NULL;
		archive_set_error(a, ENOMEM,
		    "Internal error initializing compression library: "
		    "Cannot allocate memory");
		r =  ARCHIVE_FATAL;
		break;
        default:
		free(strm);
		lastrm->real_stream = NULL;
		archive_set_error(a, ARCHIVE_ERRNO_MISC,
		    "Internal error initializing compression library: "
		    "It's a bug in liblzma");
		r =  ARCHIVE_FATAL;
		break;
	}
	return (r);
}

static int
compression_init_encoder_lzma1(struct archive *a,
    struct la_zstream *lastrm, int level)
{
	return compression_init_encoder_lzma(a, lastrm, level,
		    LZMA_FILTER_LZMA1);
}

static int
compression_init_encoder_lzma2(struct archive *a,
    struct la_zstream *lastrm, int level)
{
	return compression_init_encoder_lzma(a, lastrm, level,
		    LZMA_FILTER_LZMA2);
}

static int
compression_code_lzma(struct archive *a,
    struct la_zstream *lastrm, enum la_zaction action)
{
	lzma_stream *strm;
	int r;

	strm = (lzma_stream *)lastrm->real_stream;
	strm->next_in = lastrm->next_in;
	strm->avail_in = lastrm->avail_in;
	strm->total_in = lastrm->total_in;
	strm->next_out = lastrm->next_out;
	strm->avail_out = lastrm->avail_out;
	strm->total_out = lastrm->total_out;
	r = lzma_code(strm,
	    (action == ARCHIVE_Z_FINISH)? LZMA_FINISH: LZMA_RUN);
	lastrm->next_in = strm->next_in;
	lastrm->avail_in = strm->avail_in;
	lastrm->total_in = strm->total_in;
	lastrm->next_out = strm->next_out;
	lastrm->avail_out = strm->avail_out;
	lastrm->total_out = strm->total_out;
	switch (r) {
	case LZMA_OK:
		/* Non-finishing case */
		return (ARCHIVE_OK);
	case LZMA_STREAM_END:
		/* This return can only occur in finishing case. */
		return (ARCHIVE_EOF);
	case LZMA_MEMLIMIT_ERROR:
		archive_set_error(a, ENOMEM,
		    "lzma compression error:"
		    " %ju MiB would have been needed",
		    (uintmax_t)((lzma_memusage(strm) + 1024 * 1024 -1)
			/ (1024 * 1024)));
		return (ARCHIVE_FATAL);
	default:
		/* Any other return value indicates an error */
		archive_set_error(a, ARCHIVE_ERRNO_MISC,
		    "lzma compression failed:"
		    " lzma_code() call returned status %d", r);
		return (ARCHIVE_FATAL);
	}
}

static int
compression_end_lzma(struct archive *a, struct la_zstream *lastrm)
{
	lzma_stream *strm;

	(void)a; /* UNUSED */
	strm = (lzma_stream *)lastrm->real_stream;
	lzma_end(strm);
	free(strm);
	lastrm->valid = 0;
	lastrm->real_stream = NULL;
	return (ARCHIVE_OK);
}
#else
static int
compression_init_encoder_lzma1(struct archive *a,
    struct la_zstream *lastrm, int level)
{

	(void) level; /* UNUSED */
	if (lastrm->valid)
		compression_end(a, lastrm);
	return (compression_unsupported_encoder(a, lastrm, "lzma"));
}
static int
compression_init_encoder_lzma2(struct archive *a,
    struct la_zstream *lastrm, int level)
{

	(void) level; /* UNUSED */
	if (lastrm->valid)
		compression_end(a, lastrm);
	return (compression_unsupported_encoder(a, lastrm, "lzma"));
}
#endif

/*
 * _7_PPMD compressor.
 */
static void
ppmd_write(void *p, Byte b)
{
	struct archive_write *a = ((IByteOut *)p)->a;
	struct _7zip *zip = (struct _7zip *)(a->format_data);
	struct la_zstream *lastrm = &(zip->stream);
	struct ppmd_stream *strm;

	if (lastrm->avail_out) {
		*lastrm->next_out++ = b;
		lastrm->avail_out--;
		lastrm->total_out++;
		return;
	}
	strm = (struct ppmd_stream *)lastrm->real_stream;
	if (strm->buff_ptr < strm->buff_end) {
		*strm->buff_ptr++ = b;
		strm->buff_bytes++;
	}
}

static int
compression_init_encoder_ppmd(struct archive *a,
    struct la_zstream *lastrm, unsigned maxOrder, uint32_t msize)
{
	struct ppmd_stream *strm;
	uint8_t *props;
	int r;

	if (lastrm->valid)
		compression_end(a, lastrm);
	strm = calloc(1, sizeof(*strm));
	if (strm == NULL) {
		archive_set_error(a, ENOMEM,
		    "Can't allocate memory for PPMd");
		return (ARCHIVE_FATAL);
	}
	strm->buff = malloc(32);
	if (strm->buff == NULL) {
		free(strm);
		archive_set_error(a, ENOMEM,
		    "Can't allocate memory for PPMd");
		return (ARCHIVE_FATAL);
	}
	strm->buff_ptr = strm->buff;
	strm->buff_end = strm->buff + 32;

	props = malloc(1+4);
	if (props == NULL) {
		free(strm->buff);
		free(strm);
		archive_set_error(a, ENOMEM,
		    "Coludn't allocate memory for PPMd");
		return (ARCHIVE_FATAL);
	}
	props[0] = maxOrder;
	archive_le32enc(props+1, msize);
	__archive_ppmd7_functions.Ppmd7_Construct(&strm->ppmd7_context);
	r = __archive_ppmd7_functions.Ppmd7_Alloc(
		&strm->ppmd7_context, msize);
	if (r == 0) {
		free(strm->buff);
		free(strm);
		free(props);
		archive_set_error(a, ENOMEM,
		    "Coludn't allocate memory for PPMd");
		return (ARCHIVE_FATAL);
	}
	__archive_ppmd7_functions.Ppmd7_Init(&(strm->ppmd7_context), maxOrder);
	strm->byteout.a = (struct archive_write *)a;
	strm->byteout.Write = ppmd_write;
	strm->range_enc.Stream = &(strm->byteout);
	__archive_ppmd7_functions.Ppmd7z_RangeEnc_Init(&(strm->range_enc));
	strm->stat = 0;

	lastrm->real_stream = strm;
	lastrm->valid = 1;
	lastrm->code = compression_code_ppmd;
	lastrm->end = compression_end_ppmd;
	lastrm->prop_size = 5;
	lastrm->props = props;
	return (ARCHIVE_OK);
}

static int
compression_code_ppmd(struct archive *a,
    struct la_zstream *lastrm, enum la_zaction action)
{
	struct ppmd_stream *strm;

	(void)a; /* UNUSED */

	strm = (struct ppmd_stream *)lastrm->real_stream;

	/* Copy encoded data if there are remaining bytes from previous call. */
	if (strm->buff_bytes) {
		uint8_t *p = strm->buff_ptr - strm->buff_bytes;
		while (lastrm->avail_out && strm->buff_bytes) {
			*lastrm->next_out++ = *p++;
			lastrm->avail_out--;
			lastrm->total_out++;
			strm->buff_bytes--;
		}
		if (strm->buff_bytes)
			return (ARCHIVE_OK);
		if (strm->stat == 1)
			return (ARCHIVE_EOF);
		strm->buff_ptr = strm->buff;
	}
	while (lastrm->avail_in && lastrm->avail_out) {
		__archive_ppmd7_functions.Ppmd7_EncodeSymbol(
			&(strm->ppmd7_context), &(strm->range_enc),
			*lastrm->next_in++);
		lastrm->avail_in--;
		lastrm->total_in++;
	}
	if (lastrm->avail_in == 0 && action == ARCHIVE_Z_FINISH) {
		__archive_ppmd7_functions.Ppmd7z_RangeEnc_FlushData(
			&(strm->range_enc));
		strm->stat = 1;
		/* Return EOF if there are no remaining bytes. */
		if (strm->buff_bytes == 0)
			return (ARCHIVE_EOF);
	}
	return (ARCHIVE_OK);
}

static int
compression_end_ppmd(struct archive *a, struct la_zstream *lastrm)
{
	struct ppmd_stream *strm;

	(void)a; /* UNUSED */

	strm = (struct ppmd_stream *)lastrm->real_stream;
	__archive_ppmd7_functions.Ppmd7_Free(&strm->ppmd7_context);
	free(strm->buff);
	free(strm);
	lastrm->real_stream = NULL;
	lastrm->valid = 0;
	return (ARCHIVE_OK);
}

/*
 * Universal compressor initializer.
 */
static int
_7z_compression_init_encoder(struct archive_write *a, unsigned compression,
    int compression_level)
{
	struct _7zip *zip;
	int r;

	zip = (struct _7zip *)a->format_data;
	switch (compression) {
	case _7Z_DEFLATE:
		r = compression_init_encoder_deflate(
		    &(a->archive), &(zip->stream),
		    compression_level, 0);
		break;
	case _7Z_BZIP2:
		r = compression_init_encoder_bzip2(
		    &(a->archive), &(zip->stream),
		    compression_level);
		break;
	case _7Z_LZMA1:
		r = compression_init_encoder_lzma1(
		    &(a->archive), &(zip->stream),
		    compression_level);
		break;
	case _7Z_LZMA2:
		r = compression_init_encoder_lzma2(
		    &(a->archive), &(zip->stream),
		    compression_level);
		break;
	case _7Z_PPMD:
		r = compression_init_encoder_ppmd(
		    &(a->archive), &(zip->stream),
		    PPMD7_DEFAULT_ORDER, PPMD7_DEFAULT_MEM_SIZE);
		break;
	case _7Z_COPY:
	default:
		r = compression_init_encoder_copy(
		    &(a->archive), &(zip->stream));
		break;
	}
	if (r == ARCHIVE_OK) {
		zip->stream.total_in = 0;
		zip->stream.next_out = zip->wbuff;
		zip->stream.avail_out = sizeof(zip->wbuff);
		zip->stream.total_out = 0;
	}

	return (r);
}

static int
compression_code(struct archive *a, struct la_zstream *lastrm,
    enum la_zaction action)
{
	if (lastrm->valid)
		return (lastrm->code(a, lastrm, action));
	return (ARCHIVE_OK);
}

static int
compression_end(struct archive *a, struct la_zstream *lastrm)
{
	if (lastrm->valid) {
		lastrm->prop_size = 0;
		free(lastrm->props);
		lastrm->props = NULL;
		return (lastrm->end(a, lastrm));
	}
	return (ARCHIVE_OK);
}