zhao
2021-06-04 c7ec496f9e41c2227103b3ef776e4a3f91bce6b2
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
/* ====================================================================
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for Additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at
 
       http://www.apache.org/licenses/LICENSE-2.0
 
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
==================================================================== */
namespace HH.WMS.Utils.NPOI.HSSF.Record
{
    using System;
    using System.Collections.Generic;
    using HH.WMS.Utils.NPOI.HSSF.EventUserModel;
    using HH.WMS.Utils.NPOI;
    using System.IO;
    using HH.WMS.Utils.NPOI.HSSF.Record.Crypto;
    using HH.WMS.Utils.NPOI.Util;
    /**
     * A stream based way to get at complete records, with
     * as low a memory footprint as possible.
     * This handles Reading from a RecordInputStream, turning
     * the data into full records, processing continue records
     * etc.
     * Most users should use {@link HSSFEventFactory} /
     * {@link HSSFListener} and have new records pushed to
     * them, but this does allow for a "pull" style of coding.
     */
    public class RecordFactoryInputStream
    {
 
        /**
         * Keeps track of the sizes of the Initial records up to and including {@link FilePassRecord}
         * Needed for protected files because each byte is encrypted with respect to its absolute
         * position from the start of the stream.
         */
        private class StreamEncryptionInfo
        {
            private int _InitialRecordsSize;
            private FilePassRecord _filePassRec;
            private Record _lastRecord;
            private bool _hasBOFRecord;
 
            public StreamEncryptionInfo(RecordInputStream rs, List<Record> outputRecs)
            {
                Record rec;
                rs.NextRecord();
                int recSize = 4 + rs.Remaining;
                rec = RecordFactory.CreateSingleRecord(rs);
                outputRecs.Add(rec);
                FilePassRecord fpr = null;
                if (rec is BOFRecord)
                {
                    _hasBOFRecord = true;
                    if (rs.HasNextRecord)
                    {
                        rs.NextRecord();
                        rec = RecordFactory.CreateSingleRecord(rs);
                        recSize += rec.RecordSize;
                        outputRecs.Add(rec);
                        if (rec is FilePassRecord)
                        {
                            fpr = (FilePassRecord)rec;
                            outputRecs.RemoveAt(outputRecs.Count - 1);
                            // TODO - add fpr not Added to outPutRecs
                            rec = outputRecs[0];
                        }
                        else
                        {
                            // workbook not encrypted (typical case)
                            if (rec is EOFRecord)
                            {
                                // A workbook stream is never empty, so crash instead
                                // of trying to keep track of nesting level
                                throw new InvalidOperationException("Nothing between BOF and EOF");
                            }
                        }
                    }
                }
                else
                {
                    // Invalid in a normal workbook stream.
                    // However, some test cases work on sub-sections of
                    // the workbook stream that do not begin with BOF
                    _hasBOFRecord = false;
                }
                _InitialRecordsSize = recSize;
                _filePassRec = fpr;
                _lastRecord = rec;
            }
 
            public RecordInputStream CreateDecryptingStream(Stream original)
            {
                FilePassRecord fpr = _filePassRec;
                String userPassword = Biff8EncryptionKey.CurrentUserPassword;
 
                Biff8EncryptionKey key;
                if (userPassword == null)
                {
                    key = Biff8EncryptionKey.Create(fpr.DocId);
                }
                else
                {
                    key = Biff8EncryptionKey.Create(userPassword, fpr.DocId);
                }
                if (!key.Validate(fpr.SaltData, fpr.SaltHash))
                {
                    throw new EncryptedDocumentException(
                            (userPassword == null ? "Default" : "Supplied")
                            + " password is invalid for docId/saltData/saltHash");
                }
                return new RecordInputStream(original, key, _InitialRecordsSize);
            }
 
            public bool HasEncryption
            {
                get
                {
                    return _filePassRec != null;
                }
            }
 
            /**
             * @return last record scanned while looking for encryption info.
             * This will typically be the first or second record Read. Possibly <code>null</code>
             * if stream was empty
             */
            public Record LastRecord
            {
                get
                {
                    return _lastRecord;
                }
            }
 
            /**
             * <c>false</c> in some test cases
             */
            public bool HasBOFRecord
            {
                get
                {
                    return _hasBOFRecord;
                }
            }
        }
 
 
        private RecordInputStream _recStream;
        private bool _shouldIncludeContinueRecords;
 
        /**
         * Temporarily stores a group of {@link Record}s, for future return by {@link #nextRecord()}.
         * This is used at the start of the workbook stream, and also when the most recently read
         * underlying record is a {@link MulRKRecord}
         */
        private Record[] _unreadRecordBuffer;
 
        /**
         * used to help iterating over the unread records
         */
        private int _unreadRecordIndex = -1;
 
        /**
         * The most recent record that we gave to the user
         */
        private Record _lastRecord = null;
        /**
         * The most recent DrawingRecord seen
         */
        private DrawingRecord _lastDrawingRecord = new DrawingRecord();
 
        private int _bofDepth;
 
        private bool _lastRecordWasEOFLevelZero;
 
 
        /**
         * @param shouldIncludeContinueRecords caller can pass <c>false</c> if loose
         * {@link ContinueRecord}s should be skipped (this is sometimes useful in event based
         * processing).
         */
        public RecordFactoryInputStream(Stream in1, bool shouldIncludeContinueRecords)
        {
            RecordInputStream rs = new RecordInputStream(in1);
            List<Record> records = new List<Record>();
            StreamEncryptionInfo sei = new StreamEncryptionInfo(rs, records);
            if (sei.HasEncryption)
            {
                rs = sei.CreateDecryptingStream(in1);
            }
            else
            {
                // typical case - non-encrypted stream
            }
 
            if (records.Count != 0)
            {
                _unreadRecordBuffer = new Record[records.Count];
                _unreadRecordBuffer = records.ToArray();
                _unreadRecordIndex = 0;
            }
            _recStream = rs;
            _shouldIncludeContinueRecords = shouldIncludeContinueRecords;
            _lastRecord = sei.LastRecord;
 
            /*
            * How to recognise end of stream?
            * In the best case, the underlying input stream (in) ends just after the last EOF record
            * Usually however, the stream is pAdded with an arbitrary byte count.  Excel and most apps
            * reliably use zeros for pAdding and if this were always the case, this code could just
            * skip all the (zero sized) records with sid==0.  However, bug 46987 Shows a file with
            * non-zero pAdding that is read OK by Excel (Excel also fixes the pAdding).
            *
            * So to properly detect the workbook end of stream, this code has to identify the last
            * EOF record.  This is not so easy because the worbook bof+eof pair do not bracket the
            * whole stream.  The worksheets follow the workbook, but it is not easy to tell how many
            * sheet sub-streams should be present.  Hence we are looking for an EOF record that is not
            * immediately followed by a BOF record.  One extra complication is that bof+eof sub-
            * streams can be nested within worksheet streams and it's not clear in these cases what
            * record might follow any EOF record.  So we also need to keep track of the bof/eof
            * nesting level.
            */
            _bofDepth = sei.HasBOFRecord ? 1 : 0;
            _lastRecordWasEOFLevelZero = false;
        }
 
        /**
         * Returns the next (complete) record from the
         * stream, or null if there are no more.
         */
        public Record NextRecord()
        {
            Record r;
            r = GetNextUnreadRecord();
            if (r != null)
            {
                // found an unread record
                return r;
            }
            while (true)
            {
                if (!_recStream.HasNextRecord)
                {
                    // recStream is exhausted;
                    return null;
                }
 
                // step underlying RecordInputStream to the next record
                _recStream.NextRecord();
 
                if (_lastRecordWasEOFLevelZero)
                {
                    // Potential place for ending the workbook stream
                    // Check that the next record is not BOFRecord(0x0809)
                    // Normally the input stream Contains only zero pAdding after the last EOFRecord,
                    // but bug 46987 and 48068 suggests that the padding may be garbage.
                    // This code relies on the pAdding bytes not starting with BOFRecord.sid
                    if (_recStream.Sid != BOFRecord.sid)
                    {
                        return null;
                    }
                    // else - another sheet substream starting here
                }
 
                r = ReadNextRecord();
                if (r == null)
                {
                    // some record types may get skipped (e.g. DBCellRecord and ContinueRecord)
                    continue;
                }
                return r;
            }
        }
 
        /**
         * @return the next {@link Record} from the multiple record group as expanded from
         * a recently read {@link MulRKRecord}. <code>null</code> if not present.
         */
        private Record GetNextUnreadRecord()
        {
            if (_unreadRecordBuffer != null)
            {
                int ix = _unreadRecordIndex;
                if (ix < _unreadRecordBuffer.Length)
                {
                    Record result = _unreadRecordBuffer[ix];
                    _unreadRecordIndex = ix + 1;
                    return result;
                }
                _unreadRecordIndex = -1;
                _unreadRecordBuffer = null;
            }
            return null;
        }
 
        /**
         * @return the next available record, or <code>null</code> if
         * this pass didn't return a record that's
         * suitable for returning (eg was a continue record).
         */
        private Record ReadNextRecord()
        {
 
            Record record = RecordFactory.CreateSingleRecord(_recStream);
            _lastRecordWasEOFLevelZero = false;
 
            if (record is BOFRecord)
            {
                _bofDepth++;
                return record;
            }
 
            if (record is EOFRecord)
            {
                _bofDepth--;
                if (_bofDepth < 1)
                {
                    _lastRecordWasEOFLevelZero = true;
                }
 
                return record;
            }
 
            if (record is DBCellRecord)
            {
                // Not needed by POI.  Regenerated from scratch by POI when spreadsheet is written
                return null;
            }
 
            if (record is RKRecord)
            {
                return RecordFactory.ConvertToNumberRecord((RKRecord)record);
            }
 
            if (record is MulRKRecord)
            {
                Record[] records = RecordFactory.ConvertRKRecords((MulRKRecord)record);
 
                _unreadRecordBuffer = records;
                _unreadRecordIndex = 1;
                return records[0];
            }
 
            if (record.Sid == DrawingGroupRecord.sid
                    && _lastRecord is DrawingGroupRecord)
            {
                DrawingGroupRecord lastDGRecord = (DrawingGroupRecord)_lastRecord;
                lastDGRecord.Join((AbstractEscherHolderRecord)record);
                return null;
            }
            if (record.Sid == ContinueRecord.sid)
            {
                ContinueRecord contRec = (ContinueRecord)record;
 
                if (_lastRecord is ObjRecord || _lastRecord is TextObjectRecord)
                {
                    // Drawing records have a very strange continue behaviour.
                    //There can actually be OBJ records mixed between the continues.
                    _lastDrawingRecord.ProcessContinueRecord(contRec.Data);
                    //we must remember the position of the continue record.
                    //in the serialization procedure the original structure of records must be preserved
                    if (_shouldIncludeContinueRecords)
                    {
                        return record;
                    }
                    return null;
                }
                if (_lastRecord is DrawingGroupRecord)
                {
                    ((DrawingGroupRecord)_lastRecord).ProcessContinueRecord(contRec.Data);
                    return null;
                }
                if (_lastRecord is DrawingRecord)
                {
                    ((DrawingRecord)_lastRecord).ProcessContinueRecord(contRec.Data);
                    return null;
                }
                if (_lastRecord is UnknownRecord)
                {
                    //Gracefully handle records that we don't know about,
                    //that happen to be continued
                    return record;
                }
                if (_lastRecord is EOFRecord)
                {
                    // This is really odd, but excel still sometimes
                    //  outPuts a file like this all the same
                    return record;
                }
                //if (_lastRecord is StringRecord)
                //{
                //    ((StringRecord)_lastRecord).ProcessContinueRecord(contRec.Data);
                //    return null;
                //}
                throw new RecordFormatException("Unhandled Continue Record");
            }
            _lastRecord = record;
            if (record is DrawingRecord)
            {
                _lastDrawingRecord = (DrawingRecord)record;
            }
            return record;
        }
    }
}