jt
2021-06-10 5d0d028456874576560552f5a5c4e8b801786f11
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
// ZipSegmentedStream.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2009-2011 Dino Chiesa.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// last saved (in emacs):
// Time-stamp: <2011-July-13 22:25:45>
//
// ------------------------------------------------------------------
//
// This module defines logic for zip streams that span disk files.
//
// ------------------------------------------------------------------
 
 
using System;
using System.Collections.Generic;
using System.IO;
 
namespace HH.WMS.Utils.Ionic.Zip
{
    internal class ZipSegmentedStream : System.IO.Stream
    {
        enum RwMode
        {
            None = 0,
            ReadOnly = 1,
            Write = 2,
            //Update = 3
        }
 
        private RwMode rwMode;
        private bool _exceptionPending; // **see note below
        private string _baseName;
        private string _baseDir;
        //private bool _isDisposed;
        private string _currentName;
        private string _currentTempName;
        private uint _currentDiskNumber;
        private uint _maxDiskNumber;
        private int _maxSegmentSize;
        private System.IO.Stream _innerStream;
 
        // **Note regarding exceptions:
        //
        // When ZipSegmentedStream is employed within a using clause,
        // which is the typical scenario, and an exception is thrown
        // within the scope of the using, Dispose() is invoked
        // implicitly before processing the initial exception.  If that
        // happens, this class sets _exceptionPending to true, and then
        // within the Dispose(bool), takes special action as
        // appropriate. Need to be careful: any additional exceptions
        // will mask the original one.
 
        private ZipSegmentedStream() : base()
        {
            _exceptionPending = false;
        }
 
        public static ZipSegmentedStream ForReading(string name,
                                                    uint initialDiskNumber,
                                                    uint maxDiskNumber)
        {
            ZipSegmentedStream zss = new ZipSegmentedStream()
                {
                    rwMode = RwMode.ReadOnly,
                    CurrentSegment = initialDiskNumber,
                    _maxDiskNumber = maxDiskNumber,
                    _baseName = name,
                };
 
            // Console.WriteLine("ZSS: ForReading ({0})",
            //                    Path.GetFileName(zss.CurrentName));
 
            zss._SetReadStream();
 
            return zss;
        }
 
 
        public static ZipSegmentedStream ForWriting(string name, int maxSegmentSize)
        {
            ZipSegmentedStream zss = new ZipSegmentedStream()
                {
                    rwMode = RwMode.Write,
                    CurrentSegment = 0,
                    _baseName = name,
                    _maxSegmentSize = maxSegmentSize,
                    _baseDir = Path.GetDirectoryName(name)
                };
 
            // workitem 9522
            if (zss._baseDir=="") zss._baseDir=".";
 
            zss._SetWriteStream(0);
 
            // Console.WriteLine("ZSS: ForWriting ({0})",
            //                    Path.GetFileName(zss.CurrentName));
 
            return zss;
        }
 
 
        /// <summary>
        ///   Sort-of like a factory method, ForUpdate is used only when
        ///   the application needs to update the zip entry metadata for
        ///   a segmented zip file, when the starting segment is earlier
        ///   than the ending segment, for a particular entry.
        /// </summary>
        /// <remarks>
        ///   <para>
        ///     The update is always contiguous, never rolls over.  As a
        ///     result, this method doesn't need to return a ZSS; it can
        ///     simply return a FileStream.  That's why it's "sort of"
        ///     like a Factory method.
        ///   </para>
        ///   <para>
        ///     Caller must Close/Dispose the stream object returned by
        ///     this method.
        ///   </para>
        /// </remarks>
        public static Stream ForUpdate(string name, uint diskNumber)
        {
            if (diskNumber >= 99)
                throw new ArgumentOutOfRangeException("diskNumber");
 
            string fname =
                String.Format("{0}.z{1:D2}",
                                 Path.Combine(Path.GetDirectoryName(name),
                                              Path.GetFileNameWithoutExtension(name)),
                                 diskNumber + 1);
 
            // Console.WriteLine("ZSS: ForUpdate ({0})",
            //                   Path.GetFileName(fname));
 
            // This class assumes that the update will not expand the
            // size of the segment. Update is used only for an in-place
            // update of zip metadata. It never will try to write beyond
            // the end of a segment.
 
            return File.Open(fname,
                             FileMode.Open,
                             FileAccess.ReadWrite,
                             FileShare.None);
        }
 
        public bool ContiguousWrite
        {
            get;
            set;
        }
 
 
        public UInt32 CurrentSegment
        {
            get
            {
                return _currentDiskNumber;
            }
            private set
            {
                _currentDiskNumber = value;
                _currentName = null; // it will get updated next time referenced
            }
        }
 
        /// <summary>
        ///   Name of the filesystem file corresponding to the current segment.
        /// </summary>
        /// <remarks>
        ///   <para>
        ///     The name is not always the name currently being used in the
        ///     filesystem.  When rwMode is RwMode.Write, the filesystem file has a
        ///     temporary name until the stream is closed or until the next segment is
        ///     started.
        ///   </para>
        /// </remarks>
        public String CurrentName
        {
            get
            {
                if (_currentName==null)
                    _currentName = _NameForSegment(CurrentSegment);
 
                return _currentName;
            }
        }
 
 
        public String CurrentTempName
        {
            get
            {
                return _currentTempName;
            }
        }
 
        private string _NameForSegment(uint diskNumber)
        {
            if (diskNumber >= 99)
            {
                _exceptionPending = true;
                throw new OverflowException("The number of zip segments would exceed 99.");
            }
 
            return String.Format("{0}.z{1:D2}",
                                 Path.Combine(Path.GetDirectoryName(_baseName),
                                              Path.GetFileNameWithoutExtension(_baseName)),
                                 diskNumber + 1);
        }
 
 
        // Returns the segment that WILL be current if writing
        // a block of the given length.
        // This isn't exactly true. It could roll over beyond
        // this number.
        public UInt32 ComputeSegment(int length)
        {
            if (_innerStream.Position + length > _maxSegmentSize)
                // the block will go AT LEAST into the next segment
                return CurrentSegment + 1;
 
            // it will fit in the current segment
            return CurrentSegment;
        }
 
 
        public override String ToString()
        {
            return String.Format("{0}[{1}][{2}], pos=0x{3:X})",
                                 "ZipSegmentedStream", CurrentName,
                                 rwMode.ToString(),
                                 this.Position);
        }
 
 
        private void _SetReadStream()
        {
            if (_innerStream != null)
            {
#if NETCF
                _innerStream.Close();
#else
                _innerStream.Dispose();
#endif
            }
 
            if (CurrentSegment + 1 == _maxDiskNumber)
                _currentName = _baseName;
 
            // Console.WriteLine("ZSS: SRS ({0})",
            //                   Path.GetFileName(CurrentName));
 
            _innerStream = File.OpenRead(CurrentName);
        }
 
 
        /// <summary>
        /// Read from the stream
        /// </summary>
        /// <param name="buffer">the buffer to read</param>
        /// <param name="offset">the offset at which to start</param>
        /// <param name="count">the number of bytes to read</param>
        /// <returns>the number of bytes actually read</returns>
        public override int Read(byte[] buffer, int offset, int count)
        {
            if (rwMode != RwMode.ReadOnly)
            {
                _exceptionPending = true;
                throw new InvalidOperationException("Stream Error: Cannot Read.");
            }
 
            int r = _innerStream.Read(buffer, offset, count);
            int r1 = r;
 
            while (r1 != count)
            {
                if (_innerStream.Position != _innerStream.Length)
                {
                    _exceptionPending = true;
                    throw new ZipException(String.Format("Read error in file {0}", CurrentName));
 
                }
 
                if (CurrentSegment + 1 == _maxDiskNumber)
                    return r; // no more to read
 
                CurrentSegment++;
                _SetReadStream();
                offset += r1;
                count -= r1;
                r1 = _innerStream.Read(buffer, offset, count);
                r += r1;
            }
            return r;
        }
 
 
 
        private void _SetWriteStream(uint increment)
        {
            if (_innerStream != null)
            {
#if NETCF
                _innerStream.Close();
#else
                _innerStream.Dispose();
#endif
                if (File.Exists(CurrentName))
                    File.Delete(CurrentName);
                File.Move(_currentTempName, CurrentName);
                // Console.WriteLine("ZSS: SWS close ({0})",
                //                   Path.GetFileName(CurrentName));
            }
 
            if (increment > 0)
                CurrentSegment += increment;
 
            SharedUtilities.CreateAndOpenUniqueTempFile(_baseDir,
                                                        out _innerStream,
                                                        out _currentTempName);
 
            // Console.WriteLine("ZSS: SWS open ({0})",
            //                   Path.GetFileName(_currentTempName));
 
            if (CurrentSegment == 0)
                _innerStream.Write(BitConverter.GetBytes(ZipConstants.SplitArchiveSignature), 0, 4);
        }
 
 
        /// <summary>
        /// Write to the stream.
        /// </summary>
        /// <param name="buffer">the buffer from which to write</param>
        /// <param name="offset">the offset at which to start writing</param>
        /// <param name="count">the number of bytes to write</param>
        public override void Write(byte[] buffer, int offset, int count)
        {
            if (rwMode != RwMode.Write)
            {
                _exceptionPending = true;
                throw new InvalidOperationException("Stream Error: Cannot Write.");
            }
 
 
            if (ContiguousWrite)
            {
                // enough space for a contiguous write?
                if (_innerStream.Position + count > _maxSegmentSize)
                    _SetWriteStream(1);
            }
            else
            {
                while (_innerStream.Position + count > _maxSegmentSize)
                {
                    int c = unchecked(_maxSegmentSize - (int)_innerStream.Position);
                    _innerStream.Write(buffer, offset, c);
                    _SetWriteStream(1);
                    count -= c;
                    offset += c;
                }
            }
 
            _innerStream.Write(buffer, offset, count);
        }
 
 
        public long TruncateBackward(uint diskNumber, long offset)
        {
            // Console.WriteLine("***ZSS.Trunc to disk {0}", diskNumber);
            // Console.WriteLine("***ZSS.Trunc:  current disk {0}", CurrentSegment);
            if (diskNumber >= 99)
                throw new ArgumentOutOfRangeException("diskNumber");
 
            if (rwMode != RwMode.Write)
            {
                _exceptionPending = true;
                throw new ZipException("bad state.");
            }
 
            // Seek back in the segmented stream to a (maybe) prior segment.
 
            // Check if it is the same segment.  If it is, very simple.
            if (diskNumber == CurrentSegment)
            {
                var x =_innerStream.Seek(offset, SeekOrigin.Begin);
                // workitem 10178
                HH.WMS.Utils.Ionic.Zip.SharedUtilities.Workaround_Ladybug318918(_innerStream);
                return x;
            }
 
            // Seeking back to a prior segment.
            // The current segment and any intervening segments must be removed.
            // First, close the current segment, and then remove it.
            if (_innerStream != null)
            {
#if NETCF
                _innerStream.Close();
#else
                _innerStream.Dispose();
#endif
                if (File.Exists(_currentTempName))
                    File.Delete(_currentTempName);
            }
 
            // Now, remove intervening segments.
            for (uint j= CurrentSegment-1; j > diskNumber; j--)
            {
                string s = _NameForSegment(j);
                // Console.WriteLine("***ZSS.Trunc:  removing file {0}", s);
                if (File.Exists(s))
                    File.Delete(s);
            }
 
            // now, open the desired segment.  It must exist.
            CurrentSegment = diskNumber;
 
            // get a new temp file, try 3 times:
            for (int i = 0; i < 3; i++)
            {
                try
                {
                    _currentTempName = SharedUtilities.InternalGetTempFileName();
                    // move the .z0x file back to a temp name
                    File.Move(CurrentName, _currentTempName);
                    break; // workitem 12403
                }
                catch(IOException)
                {
                    if (i == 2) throw;
                }
            }
 
            // open it
            _innerStream = new FileStream(_currentTempName, FileMode.Open);
 
            var r =  _innerStream.Seek(offset, SeekOrigin.Begin);
 
            // workitem 10178
            HH.WMS.Utils.Ionic.Zip.SharedUtilities.Workaround_Ladybug318918(_innerStream);
 
            return r;
        }
 
 
 
        public override bool CanRead
        {
            get
            {
                return (rwMode == RwMode.ReadOnly &&
                        (_innerStream != null) &&
                        _innerStream.CanRead);
            }
        }
 
 
        public override bool CanSeek
        {
            get
            {
                return (_innerStream != null) &&
                        _innerStream.CanSeek;
            }
        }
 
 
        public override bool CanWrite
        {
            get
            {
                return (rwMode == RwMode.Write) &&
                        (_innerStream != null) &&
                        _innerStream.CanWrite;
            }
        }
 
        public override void Flush()
        {
            _innerStream.Flush();
        }
 
        public override long Length
        {
            get
            {
                return _innerStream.Length;
            }
        }
 
        public override long Position
        {
            get { return _innerStream.Position; }
            set { _innerStream.Position = value; }
        }
 
        public override long Seek(long offset, System.IO.SeekOrigin origin)
        {
            var x = _innerStream.Seek(offset, origin);
            // workitem 10178
            HH.WMS.Utils.Ionic.Zip.SharedUtilities.Workaround_Ladybug318918(_innerStream);
            return x;
        }
 
        public override void SetLength(long value)
        {
            if (rwMode != RwMode.Write)
            {
                _exceptionPending = true;
                throw new InvalidOperationException();
            }
            _innerStream.SetLength(value);
        }
 
 
        protected override void Dispose(bool disposing)
        {
            // this gets called by Stream.Close()
 
            // if (_isDisposed) return;
            // _isDisposed = true;
            //Console.WriteLine("Dispose (mode={0})\n", rwMode.ToString());
 
            try
            {
                if (_innerStream != null)
                {
#if NETCF
                    _innerStream.Close();
#else
                    _innerStream.Dispose();
#endif
                    //_innerStream = null;
                    if (rwMode == RwMode.Write)
                    {
                        if (_exceptionPending)
                        {
                            // possibly could try to clean up all the
                            // temp files created so far...
                        }
                        else
                        {
                            // // move the final temp file to the .zNN name
                            // if (File.Exists(CurrentName))
                            //     File.Delete(CurrentName);
                            // if (File.Exists(_currentTempName))
                            //     File.Move(_currentTempName, CurrentName);
                        }
                    }
                }
            }
            finally
            {
                base.Dispose(disposing);
            }
        }
 
    }
 
}