aboutsummaryrefslogtreecommitdiff
path: root/src/dtf/WixToolset.Dtf.Compression.Cab/CabPacker.cs
blob: ec6e3bda7edb959525ce8cdf312f09650eac6194 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
// Copyright (c) .NET Foundation and contributors. All rights reserved. Licensed under the Microsoft Reciprocal License. See LICENSE.TXT file in the project root for full license information.

namespace WixToolset.Dtf.Compression.Cab
{
    using System;
    using System.IO;
    using System.Text;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Runtime.InteropServices;
    using System.Diagnostics.CodeAnalysis;

    internal class CabPacker : CabWorker
    {
        private const string TempStreamName = "%%TEMP%%";

        private NativeMethods.FCI.Handle fciHandle;

        // These delegates need to be saved as member variables
        // so that they don't get GC'd.
        private NativeMethods.FCI.PFNALLOC fciAllocMemHandler;
        private NativeMethods.FCI.PFNFREE fciFreeMemHandler;
        private NativeMethods.FCI.PFNOPEN fciOpenStreamHandler;
        private NativeMethods.FCI.PFNREAD fciReadStreamHandler;
        private NativeMethods.FCI.PFNWRITE fciWriteStreamHandler;
        private NativeMethods.FCI.PFNCLOSE fciCloseStreamHandler;
        private NativeMethods.FCI.PFNSEEK fciSeekStreamHandler;
        private NativeMethods.FCI.PFNFILEPLACED fciFilePlacedHandler;
        private NativeMethods.FCI.PFNDELETE fciDeleteFileHandler;
        private NativeMethods.FCI.PFNGETTEMPFILE fciGetTempFileHandler;

        private NativeMethods.FCI.PFNGETNEXTCABINET fciGetNextCabinet;
        private NativeMethods.FCI.PFNSTATUS fciCreateStatus;
        private NativeMethods.FCI.PFNGETOPENINFO fciGetOpenInfo;

        private IPackStreamContext context;

        private FileAttributes fileAttributes;
        private DateTime fileLastWriteTime;

        private int maxCabBytes;

        private long totalFolderBytesProcessedInCurrentCab;

        private CompressionLevel compressionLevel;
        private bool dontUseTempFiles;
        private IList<Stream> tempStreams;

        public CabPacker(CabEngine cabEngine)
            : base(cabEngine)
        {
            this.fciAllocMemHandler    = this.CabAllocMem;
            this.fciFreeMemHandler     = this.CabFreeMem;
            this.fciOpenStreamHandler  = this.CabOpenStreamEx;
            this.fciReadStreamHandler  = this.CabReadStreamEx;
            this.fciWriteStreamHandler = this.CabWriteStreamEx;
            this.fciCloseStreamHandler = this.CabCloseStreamEx;
            this.fciSeekStreamHandler  = this.CabSeekStreamEx;
            this.fciFilePlacedHandler  = this.CabFilePlaced;
            this.fciDeleteFileHandler  = this.CabDeleteFile;
            this.fciGetTempFileHandler = this.CabGetTempFile;
            this.fciGetNextCabinet     = this.CabGetNextCabinet;
            this.fciCreateStatus       = this.CabCreateStatus;
            this.fciGetOpenInfo        = this.CabGetOpenInfo;
            this.tempStreams = new List<Stream>();
            this.compressionLevel = CompressionLevel.Normal;
        }

        public bool UseTempFiles
        {
            get
            {
                return !this.dontUseTempFiles;
            }

            set
            {
                this.dontUseTempFiles = !value;
            }
        }

        public CompressionLevel CompressionLevel
        {
            get
            {
                return this.compressionLevel;
            }

            set
            {
                this.compressionLevel = value;
            }
        }

        [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
        private void CreateFci(long maxArchiveSize)
        {
            NativeMethods.FCI.CCAB ccab = new NativeMethods.FCI.CCAB();
            if (maxArchiveSize > 0 && maxArchiveSize < ccab.cb)
            {
                ccab.cb = Math.Max(
                    NativeMethods.FCI.MIN_DISK, (int) maxArchiveSize);
            }

            object maxFolderSizeOption = this.context.GetOption(
                "maxFolderSize", null);
            if (maxFolderSizeOption != null)
            {
                long maxFolderSize = Convert.ToInt64(
                    maxFolderSizeOption, CultureInfo.InvariantCulture);
                if (maxFolderSize > 0 && maxFolderSize < ccab.cbFolderThresh)
                {
                    ccab.cbFolderThresh = (int) maxFolderSize;
                }
            }

            this.maxCabBytes = ccab.cb;
            ccab.szCab = this.context.GetArchiveName(0);
            if (ccab.szCab == null)
            {
                throw new FileNotFoundException(
                    "Cabinet name not provided by stream context.");
            }
            ccab.setID = (short) new Random().Next(
                Int16.MinValue, Int16.MaxValue + 1);
            this.CabNumbers[ccab.szCab] = 0;
            this.currentArchiveName = ccab.szCab;
            this.totalArchives = 1;
            this.CabStream = null;

            this.Erf.Clear();
            this.fciHandle = NativeMethods.FCI.Create(
                this.ErfHandle.AddrOfPinnedObject(),
                this.fciFilePlacedHandler,
                this.fciAllocMemHandler,
                this.fciFreeMemHandler,
                this.fciOpenStreamHandler,
                this.fciReadStreamHandler,
                this.fciWriteStreamHandler,
                this.fciCloseStreamHandler,
                this.fciSeekStreamHandler,
                this.fciDeleteFileHandler,
                this.fciGetTempFileHandler,
                ccab,
                IntPtr.Zero);
            this.CheckError(false);
        }

        public void Pack(
            IPackStreamContext streamContext,
            IEnumerable<string> files,
            long maxArchiveSize)
        {
            if (streamContext == null)
            {
                throw new ArgumentNullException("streamContext");
            }

            if (files == null)
            {
                throw new ArgumentNullException("files");
            }

            lock (this)
            {
                try
                {
                    this.context = streamContext;

                    this.ResetProgressData();

                    this.CreateFci(maxArchiveSize);

                    foreach (string file in files)
                    {
                        FileAttributes attributes;
                        DateTime lastWriteTime;
                        Stream fileStream = this.context.OpenFileReadStream(
                            file,
                            out attributes,
                            out lastWriteTime);
                        if (fileStream != null)
                        {
                            this.totalFileBytes += fileStream.Length;
                            this.totalFiles++;
                            this.context.CloseFileReadStream(file, fileStream);
                        }
                    }

                    long uncompressedBytesInFolder = 0;
                    this.currentFileNumber = -1;

                    foreach (string file in files)
                    {
                        FileAttributes attributes;
                        DateTime lastWriteTime;
                        Stream fileStream = this.context.OpenFileReadStream(
                            file, out attributes, out lastWriteTime);
                        if (fileStream == null)
                        {
                            continue;
                        }

                        if (fileStream.Length >= (long) NativeMethods.FCI.MAX_FOLDER)
                        {
                            throw new NotSupportedException(String.Format(
                                CultureInfo.InvariantCulture,
                                "File {0} exceeds maximum file size " +
                                "for cabinet format.",
                                file));
                        }

                        if (uncompressedBytesInFolder > 0)
                        {
                            // Automatically create a new folder if this file
                            // won't fit in the current folder.
                            bool nextFolder = uncompressedBytesInFolder
                                + fileStream.Length >= (long) NativeMethods.FCI.MAX_FOLDER;

                            // Otherwise ask the client if it wants to
                            // move to the next folder.
                            if (!nextFolder)
                            {
                                object nextFolderOption = streamContext.GetOption(
                                    "nextFolder",
                                    new object[] { file, this.currentFolderNumber });
                                nextFolder = Convert.ToBoolean(
                                    nextFolderOption, CultureInfo.InvariantCulture);
                            }

                            if (nextFolder)
                            {
                                this.FlushFolder();
                                uncompressedBytesInFolder = 0;
                            }
                        }

                        if (this.currentFolderTotalBytes > 0)
                        {
                            this.currentFolderTotalBytes = 0;
                            this.currentFolderNumber++;
                            uncompressedBytesInFolder = 0;
                        }

                        this.currentFileName = file;
                        this.currentFileNumber++;

                        this.currentFileTotalBytes = fileStream.Length;
                        this.currentFileBytesProcessed = 0;
                        this.OnProgress(ArchiveProgressType.StartFile);

                        uncompressedBytesInFolder += fileStream.Length;

                        this.AddFile(
                            file,
                            fileStream,
                            attributes,
                            lastWriteTime,
                            false,
                            this.CompressionLevel);
                    }

                    this.FlushFolder();
                    this.FlushCabinet();
                }
                finally
                {
                    if (this.CabStream != null)
                    {
                        this.context.CloseArchiveWriteStream(
                            this.currentArchiveNumber,
                            this.currentArchiveName,
                            this.CabStream);
                        this.CabStream = null;
                    }

                    if (this.FileStream != null)
                    {
                        this.context.CloseFileReadStream(
                            this.currentFileName, this.FileStream);
                        this.FileStream = null;
                    }
                    this.context = null;

                    if (this.fciHandle != null)
                    {
                        this.fciHandle.Dispose();
                        this.fciHandle = null;
                    }
                }
            }
        }

        internal override int CabOpenStreamEx(string path, int openFlags, int shareMode, out int err, IntPtr pv)
        {
            if (this.CabNumbers.ContainsKey(path))
            {
                Stream stream = this.CabStream;
                if (stream == null)
                {
                    short cabNumber = this.CabNumbers[path];

                    this.currentFolderTotalBytes = 0;

                    stream = this.context.OpenArchiveWriteStream(cabNumber, path, true, this.CabEngine);
                    if (stream == null)
                    {
                        throw new FileNotFoundException(
                            String.Format(CultureInfo.InvariantCulture, "Cabinet {0} not provided.", cabNumber));
                    }
                    this.currentArchiveName = path;

                    this.currentArchiveTotalBytes = Math.Min(
                        this.totalFolderBytesProcessedInCurrentCab, this.maxCabBytes);
                    this.currentArchiveBytesProcessed = 0;

                    this.OnProgress(ArchiveProgressType.StartArchive);
                    this.CabStream = stream;
                }
                path = CabWorker.CabStreamName;
            }
            else if (path == CabPacker.TempStreamName)
            {
                // Opening memory stream for a temp file.
                Stream stream = new MemoryStream();
                this.tempStreams.Add(stream);
                int streamHandle = this.StreamHandles.AllocHandle(stream);
                err = 0;
                return streamHandle;
            }
            else if (path != CabWorker.CabStreamName)
            {
                // Opening a file on disk for a temp file.
                path = Path.Combine(Path.GetTempPath(), path);
                Stream stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
                this.tempStreams.Add(stream);
                stream = new DuplicateStream(stream);
                int streamHandle = this.StreamHandles.AllocHandle(stream);
                err = 0;
                return streamHandle;
            }
            return base.CabOpenStreamEx(path, openFlags, shareMode, out err, pv);
        }

        internal override int CabWriteStreamEx(int streamHandle, IntPtr memory, int cb, out int err, IntPtr pv)
        {
            int count = base.CabWriteStreamEx(streamHandle, memory, cb, out err, pv);
            if (count > 0 && err == 0)
            {
                Stream stream = this.StreamHandles[streamHandle];
                if (DuplicateStream.OriginalStream(stream) ==
                    DuplicateStream.OriginalStream(this.CabStream))
                {
                    this.currentArchiveBytesProcessed += cb;
                    if (this.currentArchiveBytesProcessed > this.currentArchiveTotalBytes)
                    {
                        this.currentArchiveBytesProcessed = this.currentArchiveTotalBytes;
                    }
                }
            }
            return count;
        }

        internal override int CabCloseStreamEx(int streamHandle, out int err, IntPtr pv)
        {
            Stream stream = DuplicateStream.OriginalStream(this.StreamHandles[streamHandle]);

            if (stream == DuplicateStream.OriginalStream(this.FileStream))
            {
                this.context.CloseFileReadStream(this.currentFileName, stream);
                this.FileStream = null;
                long remainder = this.currentFileTotalBytes - this.currentFileBytesProcessed;
                this.currentFileBytesProcessed += remainder;
                this.fileBytesProcessed += remainder;
                this.OnProgress(ArchiveProgressType.FinishFile);

                this.currentFileTotalBytes = 0;
                this.currentFileBytesProcessed = 0;
                this.currentFileName = null;
            }
            else if (stream == DuplicateStream.OriginalStream(this.CabStream))
            {
                if (stream.CanWrite)
                {
                    stream.Flush();
                }

                this.currentArchiveBytesProcessed = this.currentArchiveTotalBytes;
                this.OnProgress(ArchiveProgressType.FinishArchive);
                this.currentArchiveNumber++;
                this.totalArchives++;

                this.context.CloseArchiveWriteStream(
                    this.currentArchiveNumber,
                    this.currentArchiveName,
                    stream);

                this.currentArchiveName = this.NextCabinetName;
                this.currentArchiveBytesProcessed = this.currentArchiveTotalBytes = 0;
                this.totalFolderBytesProcessedInCurrentCab = 0;

                this.CabStream = null;
            }
            else  // Must be a temp stream
            {
                stream.Close();
                this.tempStreams.Remove(stream);
            }
            return base.CabCloseStreamEx(streamHandle, out err, pv);
        }

        /// <summary>
        /// Disposes of resources allocated by the cabinet engine.
        /// </summary>
        /// <param name="disposing">If true, the method has been called directly or indirectly by a user's code,
        /// so managed and unmanaged resources will be disposed. If false, the method has been called by the 
        /// runtime from inside the finalizer, and only unmanaged resources will be disposed.</param>
        [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
        protected override void Dispose(bool disposing) 
        {
            try
            {
                if (disposing)
                {
                    if (this.fciHandle != null)
                    {
                        this.fciHandle.Dispose();
                        this.fciHandle = null;
                    }
                }
            }
            finally
            {
                base.Dispose(disposing);
            }
        }

        private static NativeMethods.FCI.TCOMP GetCompressionType(CompressionLevel compLevel)
        {
            if (compLevel < CompressionLevel.Min)
            {
                return NativeMethods.FCI.TCOMP.TYPE_NONE;
            }
            else
            {
                if (compLevel > CompressionLevel.Max)
                {
                    compLevel = CompressionLevel.Max;
                }

                int lzxWindowMax =
                    ((int) NativeMethods.FCI.TCOMP.LZX_WINDOW_HI >> (int) NativeMethods.FCI.TCOMP.SHIFT_LZX_WINDOW) -
                    ((int) NativeMethods.FCI.TCOMP.LZX_WINDOW_LO >> (int) NativeMethods.FCI.TCOMP.SHIFT_LZX_WINDOW);
                int lzxWindow = lzxWindowMax *
                    (compLevel - CompressionLevel.Min) / (CompressionLevel.Max - CompressionLevel.Min);

                return (NativeMethods.FCI.TCOMP) ((int) NativeMethods.FCI.TCOMP.TYPE_LZX |
                    ((int) NativeMethods.FCI.TCOMP.LZX_WINDOW_LO +
                    (lzxWindow << (int) NativeMethods.FCI.TCOMP.SHIFT_LZX_WINDOW)));
            }
        }

        [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
        private void AddFile(
            string name,
            Stream stream,
            FileAttributes attributes,
            DateTime lastWriteTime,
            bool execute,
            CompressionLevel compLevel)
        {
            this.FileStream = stream;
            this.fileAttributes = attributes &
                (FileAttributes.Archive | FileAttributes.Hidden | FileAttributes.ReadOnly | FileAttributes.System);
            this.fileLastWriteTime = lastWriteTime;
            this.currentFileName = name;

            NativeMethods.FCI.TCOMP tcomp = CabPacker.GetCompressionType(compLevel);

            IntPtr namePtr = IntPtr.Zero;
            try
            {
                Encoding nameEncoding = Encoding.ASCII;
                if (Encoding.UTF8.GetByteCount(name) > name.Length)
                {
                    nameEncoding = Encoding.UTF8;
                    this.fileAttributes |= FileAttributes.Normal;  // _A_NAME_IS_UTF
                }

                byte[] nameBytes = nameEncoding.GetBytes(name);
                namePtr = Marshal.AllocHGlobal(nameBytes.Length + 1);
                Marshal.Copy(nameBytes, 0, namePtr, nameBytes.Length);
                Marshal.WriteByte(namePtr, nameBytes.Length, 0);

                this.Erf.Clear();
                NativeMethods.FCI.AddFile(
                    this.fciHandle,
                    String.Empty,
                    namePtr,
                    execute,
                    this.fciGetNextCabinet,
                    this.fciCreateStatus,
                    this.fciGetOpenInfo,
                    tcomp);
            }
            finally
            {
                if (namePtr != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(namePtr);
                }
            }

            this.CheckError(false);
            this.FileStream = null;
            this.currentFileName = null;
        }

        private void FlushFolder()
        {
            this.Erf.Clear();
            NativeMethods.FCI.FlushFolder(this.fciHandle, this.fciGetNextCabinet, this.fciCreateStatus);
            this.CheckError(false);
        }

        private void FlushCabinet()
        {
            this.Erf.Clear();
            NativeMethods.FCI.FlushCabinet(this.fciHandle, false, this.fciGetNextCabinet, this.fciCreateStatus);
            this.CheckError(false);
        }

        private int CabGetOpenInfo(
            string path,
            out short date,
            out short time,
            out short attribs,
            out int err,
            IntPtr pv)
        {
            CompressionEngine.DateTimeToDosDateAndTime(this.fileLastWriteTime, out date, out time);
            attribs = (short) this.fileAttributes;

            Stream stream = this.FileStream;
            this.FileStream = new DuplicateStream(stream);
            int streamHandle = this.StreamHandles.AllocHandle(stream);
            err = 0;
            return streamHandle;
        }

        private int CabFilePlaced(
            IntPtr pccab,
            string filePath,
            long fileSize,
            int continuation,
            IntPtr pv)
        {
            return 0;
        }

        private int CabGetNextCabinet(IntPtr pccab, uint prevCabSize, IntPtr pv)
        {
            NativeMethods.FCI.CCAB nextCcab = new NativeMethods.FCI.CCAB();
            Marshal.PtrToStructure(pccab, nextCcab);

            nextCcab.szDisk = String.Empty;
            nextCcab.szCab = this.context.GetArchiveName(nextCcab.iCab);
            this.CabNumbers[nextCcab.szCab] = (short) nextCcab.iCab;
            this.NextCabinetName = nextCcab.szCab;

            Marshal.StructureToPtr(nextCcab, pccab, false);
            return 1;
        }

        private int CabCreateStatus(NativeMethods.FCI.STATUS typeStatus, uint cb1, uint cb2, IntPtr pv)
        {
            switch (typeStatus)
            {
                case NativeMethods.FCI.STATUS.FILE:
                    if (cb2 > 0 && this.currentFileBytesProcessed < this.currentFileTotalBytes)
                    {
                        if (this.currentFileBytesProcessed + cb2 > this.currentFileTotalBytes)
                        {
                            cb2 = (uint) this.currentFileTotalBytes - (uint) this.currentFileBytesProcessed;
                        }
                        this.currentFileBytesProcessed += cb2;
                        this.fileBytesProcessed += cb2;

                        this.OnProgress(ArchiveProgressType.PartialFile);
                    }
                    break;

                case NativeMethods.FCI.STATUS.FOLDER:
                    if (cb1 == 0)
                    {
                        this.currentFolderTotalBytes = cb2 - this.totalFolderBytesProcessedInCurrentCab;
                        this.totalFolderBytesProcessedInCurrentCab = cb2;
                    }
                    else if (this.currentFolderTotalBytes == 0)
                    {
                        this.OnProgress(ArchiveProgressType.PartialArchive);
                    }
                    break;

                case NativeMethods.FCI.STATUS.CABINET:
                    break;
            }
            return 0;
        }

        private int CabGetTempFile(IntPtr tempNamePtr, int tempNameSize, IntPtr pv)
        {
            string tempFileName;
            if (this.UseTempFiles)
            {
                tempFileName = Path.GetFileName(Path.GetTempFileName());
            }
            else
            {
                tempFileName = CabPacker.TempStreamName;
            }

            byte[] tempNameBytes = Encoding.ASCII.GetBytes(tempFileName);
            if (tempNameBytes.Length >= tempNameSize)
            {
                return -1;
            }

            Marshal.Copy(tempNameBytes, 0, tempNamePtr, tempNameBytes.Length);
            Marshal.WriteByte(tempNamePtr, tempNameBytes.Length, 0);  // null-terminator
            return 1;
        }

        private int CabDeleteFile(string path, out int err, IntPtr pv)
        {
            try
            {
                // Deleting a temp file - don't bother if it is only a memory stream.
                if (path != CabPacker.TempStreamName)
                {
                    path = Path.Combine(Path.GetTempPath(), path);
                    File.Delete(path);
                }
            }
            catch (IOException)
            {
                // Failure to delete a temp file is not fatal.
            }
            err = 0;
            return 1;
        }
    }
}