exifreader 4.46.0 → 4.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -32,23 +32,30 @@ export function isDataUri(filename) {
32
32
  * in `load()`.
33
33
  *
34
34
  * @param {string} filename URL, data URI, or local file path.
35
- * @param {{length?: number}} [options]
36
- * @returns {Promise<ArrayBuffer|Buffer>} The whole file, or its first `length` bytes if specified.
35
+ * @param {{length?: number}} [options] A fractional `length` is rounded down.
36
+ * @returns {Promise<ArrayBuffer|Buffer>} The whole file, or its first `length` bytes if specified. Rejects when
37
+ * `length` is not `undefined`, `null` or a finite non-negative number, and with the decoder's error when a
38
+ * data URI cannot be decoded.
37
39
  */
38
40
  export function loadFile(filename, options) {
41
+ const range = legacyRange(options);
42
+ if (!range) {
43
+ return rejectInvalidLength();
44
+ }
45
+
39
46
  if (/^\w+:\/\//.test(filename)) {
40
47
  if (typeof fetch !== 'undefined') {
41
- return fetchRange(filename, legacyRange(options)).then((r) => r.buffer);
48
+ return fetchRange(filename, range).then((r) => r.buffer);
42
49
  }
43
50
 
44
- return nodeGetRange(filename, legacyRange(options)).then((r) => r.buffer);
51
+ return nodeGetRange(filename, range).then((r) => r.buffer);
45
52
  }
46
53
 
47
54
  if (isDataUri(filename)) {
48
- return Promise.resolve(dataUriToBuffer(filename));
55
+ return Promise.resolve().then(() => dataUriToBuffer(filename));
49
56
  }
50
57
 
51
- return readLocalFileRange(filename, legacyRange(options)).then((r) => r.buffer);
58
+ return readLocalFileRange(filename, range).then((r) => r.buffer);
52
59
  }
53
60
 
54
61
  /**
@@ -56,18 +63,32 @@ export function loadFile(filename, options) {
56
63
  * code path in `load()`.
57
64
  *
58
65
  * @param {File} file
59
- * @param {{length?: number}} [options]
60
- * @returns {Promise<ArrayBuffer>}
66
+ * @param {{length?: number}} [options] A fractional `length` is rounded down.
67
+ * @returns {Promise<ArrayBuffer>} Rejects when `length` is not `undefined`, `null` or a finite non-negative number.
61
68
  */
62
69
  export function loadFileObject(file, options) {
63
- return readFileObjectRange(file, legacyRange(options)).then((r) => r.buffer);
70
+ const range = legacyRange(options);
71
+ if (!range) {
72
+ return rejectInvalidLength();
73
+ }
74
+
75
+ return readFileObjectRange(file, range).then((r) => r.buffer);
64
76
  }
65
77
 
66
78
  function legacyRange(options) {
67
- if (options && Number.isInteger(options.length) && options.length >= 0) {
68
- return {start: 0, end: options.length};
79
+ const length = options ? options.length : undefined;
80
+ if (length === undefined || length === null) {
81
+ return {start: 0};
69
82
  }
70
- return {start: 0};
83
+ if (Number.isFinite(length) && length >= 0) {
84
+ const end = Math.floor(length);
85
+ return {start: 0, end, maxBytes: end};
86
+ }
87
+ return undefined;
88
+ }
89
+
90
+ function rejectInvalidLength() {
91
+ return Promise.reject(new Error('The length option must be a finite non-negative number or "auto".'));
71
92
  }
72
93
 
73
94
  /**
@@ -75,13 +96,22 @@ function legacyRange(options) {
75
96
  * requested range is not the whole file.
76
97
  *
77
98
  * @param {string} url
78
- * @param {{start?: number, end?: number}} [range] `end` is exclusive. Omit (or pass `Infinity`) to read to EOF.
99
+ * @param {{start?: number, end?: number, maxBytes?: number}} [range] `end` is exclusive. Omit (or pass `Infinity`)
100
+ * to read to EOF. With `maxBytes` (a non-negative integer) at most that many body bytes are kept on a 2xx
101
+ * response; where the response body is a `ReadableStream` the transfer is stopped once they have arrived,
102
+ * otherwise the whole body is read and cut.
79
103
  * @returns {Promise<{buffer: ArrayBuffer, totalSize: number|undefined, status: number|undefined}>}
80
104
  * `totalSize` is taken from the `Content-Range` or `Content-Length` response header when present.
81
105
  * Rejects with `Could not fetch file: <status>` on non-2xx responses, except 416 which the
82
- * `length: 'auto'` loop consumes as a fall-back signal. Mirrors `nodeGetRange`.
106
+ * `length: 'auto'` loop consumes as a fall-back signal and which resolves with an empty buffer.
107
+ * The body of a 416 or a rejected status is never read; a `ReadableStream` body is cancelled.
108
+ * An empty range (`end <= start`) resolves with an empty buffer without a request.
109
+ * Mirrors `nodeGetRange`.
83
110
  */
84
- export function fetchRange(url, {start = 0, end} = {}) {
111
+ export function fetchRange(url, {start = 0, end, maxBytes} = {}) {
112
+ if (isEmptyRange(start, end)) {
113
+ return Promise.resolve({buffer: new ArrayBuffer(0), totalSize: undefined, status: undefined});
114
+ }
85
115
  const options = {method: 'GET'};
86
116
  if (start > 0 || (end !== undefined && end !== Infinity)) {
87
117
  options.headers = {range: buildRangeHeader(start, end)};
@@ -89,14 +119,112 @@ export function fetchRange(url, {start = 0, end} = {}) {
89
119
  return fetch(url, options).then((response) => {
90
120
  const status = response && typeof response.status === 'number' ? response.status : undefined;
91
121
  if (status !== undefined && !isAcceptableFetchStatus(status)) {
122
+ cancelQuietly(response.body);
92
123
  const statusText = response.statusText || '';
93
124
  return Promise.reject(new Error(`Could not fetch file: ${status} ${statusText}`.trim()));
94
125
  }
95
126
  const totalSize = totalSizeFromFetchResponse(response);
96
- return Promise.resolve(response.arrayBuffer()).then((buffer) => ({buffer, totalSize, status}));
127
+ if (status === HTTP_STATUS_RANGE_NOT_SATISFIABLE) {
128
+ cancelQuietly(response.body);
129
+ return {buffer: new ArrayBuffer(0), totalSize, status};
130
+ }
131
+ return readFetchBody(response, maxBytes).then((buffer) => ({buffer, totalSize, status}));
132
+ });
133
+ }
134
+
135
+ function readFetchBody(response, maxBytes) {
136
+ if (!isByteLimit(maxBytes)) {
137
+ return Promise.resolve(response.arrayBuffer());
138
+ }
139
+ if (response.body && typeof response.body.getReader === 'function') {
140
+ return readStreamUpTo(response.body.getReader(), maxBytes);
141
+ }
142
+ return Promise.resolve(response.arrayBuffer()).then((buffer) => buffer.slice(0, maxBytes));
143
+ }
144
+
145
+ function isByteLimit(maxBytes) {
146
+ return Number.isInteger(maxBytes) && maxBytes >= 0;
147
+ }
148
+
149
+ function readStreamUpTo(reader, maxBytes) {
150
+ return new Promise((resolve, reject) => {
151
+ const collector = createByteCollector(maxBytes);
152
+ readNextChunk();
153
+
154
+ // Not returning the inner promise keeps memory constant per chunk;
155
+ // a returned chain would retain every link until the stream ends.
156
+ function readNextChunk() {
157
+ if (collector.isFull()) {
158
+ resolve(collector.toArrayBuffer());
159
+ cancelQuietly(reader);
160
+ return;
161
+ }
162
+ reader.read().then(onChunk).then(undefined, onFailure);
163
+ }
164
+
165
+ function onChunk(result) {
166
+ if (result.done) {
167
+ resolve(collector.toArrayBuffer());
168
+ return;
169
+ }
170
+ collector.add(result.value);
171
+ readNextChunk();
172
+ }
173
+
174
+ function onFailure(error) {
175
+ reject(error);
176
+ cancelQuietly(reader);
177
+ }
97
178
  });
98
179
  }
99
180
 
181
+ function cancelQuietly(cancellable) {
182
+ Promise.resolve().then(() => cancellable.cancel()).then(undefined, () => undefined);
183
+ }
184
+
185
+ /**
186
+ * Collects the first `maxBytes` bytes of a sequence of chunks into one
187
+ * growable array, so memory stays O(maxBytes) however the body is chunked.
188
+ * Capacity grows with the data rather than being preallocated, since a
189
+ * caller may pass a large `length` for a small file.
190
+ */
191
+ function createByteCollector(maxBytes) {
192
+ let bytes = new Uint8Array(0);
193
+ let count = 0;
194
+
195
+ return {
196
+ add(chunk) {
197
+ const size = Math.min(chunk.byteLength, maxBytes - count);
198
+ if (count + size > bytes.length) {
199
+ grow(count + size);
200
+ }
201
+ bytes.set(chunk.subarray(0, size), count);
202
+ count += size;
203
+ },
204
+ isFull() {
205
+ return count >= maxBytes;
206
+ },
207
+ toArrayBuffer() {
208
+ if (bytes.length === count) {
209
+ return bytes.buffer;
210
+ }
211
+ const exact = new Uint8Array(count);
212
+ exact.set(bytes.subarray(0, count));
213
+ return exact.buffer;
214
+ },
215
+ };
216
+
217
+ function grow(needed) {
218
+ const larger = new Uint8Array(Math.min(maxBytes, Math.max(needed, 2 * bytes.length)));
219
+ larger.set(bytes.subarray(0, count));
220
+ bytes = larger;
221
+ }
222
+ }
223
+
224
+ function isEmptyRange(start, end) {
225
+ return end !== undefined && end !== Infinity && end <= start;
226
+ }
227
+
100
228
  function buildRangeHeader(start, end) {
101
229
  if (end === undefined || end === Infinity) {
102
230
  return `bytes=${start}-`;
@@ -122,13 +250,20 @@ function isAcceptableFetchStatus(status) {
122
250
 
123
251
  /**
124
252
  * Range-aware Node `http(s).get`. Same contract as `fetchRange`. Rejects
125
- * on non-2xx responses with the status line in the error message.
253
+ * on non-2xx responses with the status line in the error message, except
254
+ * 416 which resolves with an empty buffer. The body of a 416 or a rejected
255
+ * status is not read: the response is destroyed.
126
256
  *
127
257
  * @param {string} url
128
- * @param {{start?: number, end?: number}} [range] `end` is exclusive. Omit (or pass `Infinity`) to read to EOF.
258
+ * @param {{start?: number, end?: number, maxBytes?: number}} [range] `end` is exclusive. Omit (or pass `Infinity`)
259
+ * to read to EOF. With `maxBytes` (a non-negative integer) at most that many body bytes are read on a 2xx
260
+ * response, 200 or 206, and the transfer is stopped once they have arrived.
129
261
  * @returns {Promise<{buffer: Buffer, totalSize: number|undefined, status: number|undefined}>}
130
262
  */
131
- export function nodeGetRange(url, {start = 0, end} = {}) {
263
+ export function nodeGetRange(url, {start = 0, end, maxBytes} = {}) {
264
+ if (isEmptyRange(start, end)) {
265
+ return Promise.resolve({buffer: Buffer.alloc(0), totalSize: undefined, status: undefined});
266
+ }
132
267
  return new Promise((resolve, reject) => {
133
268
  const options = {};
134
269
  if (start > 0 || (end !== undefined && end !== Infinity)) {
@@ -139,27 +274,66 @@ export function nodeGetRange(url, {start = 0, end} = {}) {
139
274
  get(url, options, (response) => {
140
275
  if ((response.statusCode >= HTTP_STATUS_OK) && (response.statusCode <= HTTP_STATUS_SUCCESS_MAX)) {
141
276
  const totalSize = totalSizeFromNodeResponse(response);
142
- const data = [];
143
- response.on('data', (chunk) => data.push(Buffer.from(chunk)));
144
- response.on('error', (error) => reject(error));
145
- response.on('end', () => resolve({
146
- buffer: Buffer.concat(data),
147
- totalSize,
148
- status: response.statusCode,
149
- }));
277
+ if (isByteLimit(maxBytes)) {
278
+ readNodeResponseUpTo(response, maxBytes, (buffer) => resolve({
279
+ buffer,
280
+ totalSize,
281
+ status: response.statusCode,
282
+ }), reject);
283
+ } else {
284
+ const data = [];
285
+ response.on('data', (chunk) => data.push(Buffer.from(chunk)));
286
+ response.on('error', (error) => reject(error));
287
+ response.on('end', () => resolve({
288
+ buffer: Buffer.concat(data),
289
+ totalSize,
290
+ status: response.statusCode,
291
+ }));
292
+ }
150
293
  } else if (response.statusCode === HTTP_STATUS_RANGE_NOT_SATISFIABLE) {
151
294
  // Resolve (rather than reject) so the adaptive `length: 'auto'`
152
295
  // loop can fall back to a full read, mirroring the fetch path.
153
- response.resume();
154
- resolve({buffer: Buffer.alloc(0), totalSize: totalSizeFromNodeResponse(response), status: response.statusCode});
296
+ const totalSize = totalSizeFromNodeResponse(response);
297
+ response.destroy();
298
+ resolve({buffer: Buffer.alloc(0), totalSize, status: response.statusCode});
155
299
  } else {
156
300
  reject(new Error(`Could not fetch file: ${response.statusCode} ${response.statusMessage}`));
157
- response.resume();
301
+ response.destroy();
158
302
  }
159
303
  }).on('error', (error) => reject(error));
160
304
  });
161
305
  }
162
306
 
307
+ function readNodeResponseUpTo(response, maxBytes, onBuffer, onError) {
308
+ const collector = createByteCollector(maxBytes);
309
+ let finished = false;
310
+
311
+ response.on('error', onError);
312
+ if (collector.isFull()) {
313
+ finish();
314
+ response.destroy();
315
+ } else {
316
+ response.on('data', onData);
317
+ response.on('end', finish);
318
+ }
319
+
320
+ function onData(chunk) {
321
+ if (finished) {
322
+ return;
323
+ }
324
+ collector.add(chunk);
325
+ if (collector.isFull()) {
326
+ finish();
327
+ response.destroy();
328
+ }
329
+ }
330
+
331
+ function finish() {
332
+ finished = true;
333
+ onBuffer(Buffer.from(collector.toArrayBuffer()));
334
+ }
335
+ }
336
+
163
337
  function totalSizeFromNodeResponse(response) {
164
338
  if (!response || !response.headers) {
165
339
  return undefined;
@@ -41,6 +41,7 @@ export function parseItemLocationBox(dataView, startOffset, version, contentOffs
41
41
  return {
42
42
  type: 'iloc',
43
43
  items: getItems(dataView, boxEnd, version, offsets, sizes, offsetSize, lengthSize, indexSize, itemCount),
44
+ uses64BitFields: hasAny64BitField(offsetSize, lengthSize, baseOffsetSize, indexSize),
44
45
  length: boxLength
45
46
  };
46
47
  }
@@ -190,9 +191,11 @@ function getVariableSizedValue(dataView, offset, size) {
190
191
  return dataView.getUint32(offset);
191
192
  }
192
193
  if (size === 8) {
193
- // eslint-disable-next-line no-console
194
- console.warn('This file uses an 8-bit offset which is currently not supported by ExifReader. Contact the maintainer to get it fixed.');
195
194
  return get64BitValue(dataView, offset);
196
195
  }
197
196
  return 0;
198
197
  }
198
+
199
+ function hasAny64BitField(offsetSize, lengthSize, baseOffsetSize, indexSize) {
200
+ return offsetSize === 8 || lengthSize === 8 || baseOffsetSize === 8 || indexSize === 8;
201
+ }
@@ -39,6 +39,10 @@ export const ITEM_INFO_TYPE_EXIF = 0x45786966;
39
39
  export const ITEM_INFO_TYPE_MIME = 0x6d696d65;
40
40
  const ITEM_INFO_TYPE_URI = 0x75726920;
41
41
 
42
+ // The spec sets no maximum for the infe strings; the cap bounds the memory one
43
+ // malformed string can take, far above any real name, MIME type or URI.
44
+ const MAX_INFE_STRING_LENGTH = 65536;
45
+
42
46
  export const BOX_TYPE_OFFSET = 4;
43
47
  export const BOX_MIN_LENGTH = 8;
44
48
 
@@ -103,7 +107,7 @@ export function parseBox(dataView, offset, containerEnd = dataView.byteLength) {
103
107
  return parseItemInformationBox(dataView, offset, version, contentOffset + VERSION_SIZE, length, containerEnd);
104
108
  }
105
109
  if (type === TYPE_INFE) {
106
- return parseItemInformationEntryBox(dataView, offset, version, contentOffset + VERSION_SIZE, length);
110
+ return parseItemInformationEntryBox(dataView, offset, version, contentOffset + VERSION_SIZE, length, containerEnd);
107
111
  }
108
112
 
109
113
  return {
@@ -228,6 +232,8 @@ export function findOffsets(dataView, metadataBlocks) {
228
232
  return {hasAppMarkers: false};
229
233
  }
230
234
 
235
+ warnIfUnsupportedFieldSize(metaBox);
236
+
231
237
  if (Constants.USE_EXIF) {
232
238
  const exif = findExifOffset(dataView, metaBox, metadataBlocks);
233
239
  if (exif !== undefined) {
@@ -279,6 +285,14 @@ function findMetaBox(dataView) {
279
285
  return undefined;
280
286
  }
281
287
 
288
+ function warnIfUnsupportedFieldSize(metaBox) {
289
+ const ilocBox = metaBox.subBoxes.find((box) => box.type === 'iloc');
290
+ if (ilocBox && ilocBox.uses64BitFields) {
291
+ // eslint-disable-next-line no-console
292
+ console.warn('This file uses 8-byte iloc offset, length or index fields which are currently not fully supported by ExifReader. Contact the maintainer to get it fixed.');
293
+ }
294
+ }
295
+
282
296
  function findExifOffset(dataView, metaBox, metadataBlocks) {
283
297
  try {
284
298
  const exifItemId = findIinfExifItemId(metaBox).itemId;
@@ -576,18 +590,19 @@ function parseItemInformationBox(dataView, startOffset, version, contentOffset,
576
590
  };
577
591
  }
578
592
 
579
- function parseItemInformationEntryBox(dataView, startOffset, version, contentOffset, length) {
593
+ function parseItemInformationEntryBox(dataView, startOffset, version, contentOffset, length, containerEnd) {
580
594
  const FLAGS_SIZE = 3;
581
595
 
582
596
  contentOffset += FLAGS_SIZE;
583
597
  const entry = {type: 'infe', length};
598
+ const entryEnd = Math.min(startOffset + length, containerEnd);
584
599
 
585
600
  if (version === 0 || version === 1) {
586
601
  entry.itemId = dataView.getUint16(contentOffset);
587
602
  contentOffset += 2;
588
603
  entry.itemProtectionIndex = dataView.getUint16(contentOffset);
589
604
  contentOffset += 2;
590
- entry.itemName = getNullTerminatedStringFromDataView(dataView, contentOffset);
605
+ entry.itemName = readEntryString(dataView, contentOffset, entryEnd).value;
591
606
  contentOffset += entry.itemName.length + 1;
592
607
  // entry.contentType = getNullTerminatedStringFromDataView(dataView, offset);
593
608
  // offset += entry.contentType.length + 1;
@@ -630,19 +645,35 @@ function parseItemInformationEntryBox(dataView, startOffset, version, contentOff
630
645
  contentOffset += 2;
631
646
  entry.itemType = dataView.getUint32(contentOffset);
632
647
  contentOffset += 4;
633
- entry.itemName = getNullTerminatedStringFromDataView(dataView, contentOffset);
648
+ const itemName = readEntryString(dataView, contentOffset, entryEnd);
649
+ entry.itemName = itemName.value;
650
+ if (!itemName.isTerminated) {
651
+ return entry;
652
+ }
634
653
  contentOffset += entry.itemName.length + 1;
635
654
  if (entry.itemType === ITEM_INFO_TYPE_MIME) {
636
- entry.contentType = getNullTerminatedStringFromDataView(dataView, contentOffset);
655
+ const contentType = readEntryString(dataView, contentOffset, entryEnd);
656
+ entry.contentType = contentType.value;
657
+ if (!contentType.isTerminated) {
658
+ return entry;
659
+ }
637
660
  contentOffset += entry.contentType.length + 1;
638
- if (startOffset + length > contentOffset) {
639
- entry.contentEncoding = getNullTerminatedStringFromDataView(dataView, contentOffset);
640
- contentOffset += entry.contentEncoding.length + 1;
661
+ if (entryEnd > contentOffset) {
662
+ entry.contentEncoding = readEntryString(dataView, contentOffset, entryEnd).value;
641
663
  }
642
664
  } else if (entry.itemType === ITEM_INFO_TYPE_URI) {
643
- entry.itemUri = getNullTerminatedStringFromDataView(dataView, contentOffset);
644
- contentOffset += entry.itemUri.length + 1;
665
+ entry.itemUri = readEntryString(dataView, contentOffset, entryEnd).value;
645
666
  }
646
667
  }
647
668
  return entry;
648
669
  }
670
+
671
+ /**
672
+ * Reads one string of an infe box, bounded by the box end and the length cap.
673
+ * isTerminated is false when the string ran into either bound instead of a NUL.
674
+ */
675
+ function readEntryString(dataView, offset, entryEnd) {
676
+ const limit = Math.min(entryEnd, offset + MAX_INFE_STRING_LENGTH);
677
+ const value = getNullTerminatedStringFromDataView(dataView, offset, limit);
678
+ return {value, isTerminated: offset + value.length < limit};
679
+ }
@@ -40,6 +40,9 @@ const ICC_TOTAL_CHUNKS_OFFSET = ICC_CHUNK_NUMBER_OFFSET + 1;
40
40
  // Guards against memory exhaustion from a crafted file. Both chunk fields are a
41
41
  // single byte, so a longer list could never be assembled into a profile anyway.
42
42
  const MAX_ICC_CHUNKS = 255;
43
+ // Guards against memory exhaustion from a crafted file. An extended XMP segment
44
+ // holds at most about 64 KiB, so this still allows about 64 MiB of XMP.
45
+ const MAX_XMP_CHUNKS = 1024;
43
46
 
44
47
  const APP2_MPF_IDENTIFIER = 'MPF\0';
45
48
 
@@ -168,14 +171,18 @@ function findJpegOffsets(dataView, metadataBlocks) {
168
171
  xmpChunks = [];
169
172
  }
170
173
  fieldLength = dataView.getUint16(appMarkerPosition + APP_MARKER_SIZE);
171
- xmpChunks.push(getXmpChunkDetails(appMarkerPosition, fieldLength));
174
+ if (xmpChunks.length < MAX_XMP_CHUNKS) {
175
+ xmpChunks.push(getXmpChunkDetails(appMarkerPosition, fieldLength));
176
+ }
172
177
  blockType = 'xmp';
173
178
  } else if (Constants.USE_XMP && isApp1ExtendedXmpMarker(dataView, appMarkerPosition)) {
174
179
  if (!xmpChunks) {
175
180
  xmpChunks = [];
176
181
  }
177
182
  fieldLength = dataView.getUint16(appMarkerPosition + APP_MARKER_SIZE);
178
- xmpChunks.push(getExtendedXmpChunkDetails(appMarkerPosition, fieldLength));
183
+ if (xmpChunks.length < MAX_XMP_CHUNKS) {
184
+ xmpChunks.push(getExtendedXmpChunkDetails(appMarkerPosition, fieldLength));
185
+ }
179
186
  blockType = 'xmp';
180
187
  } else if (Constants.USE_IPTC && isApp13PhotoshopMarker(dataView, appMarkerPosition)) {
181
188
  fieldLength = dataView.getUint16(appMarkerPosition + APP_MARKER_SIZE);
@@ -4,7 +4,7 @@
4
4
 
5
5
  // Specification: http://www.libpng.org/pub/png/spec/1.2/
6
6
 
7
- import {getStringFromDataView, getNullTerminatedStringFromDataView, pushMetadataBlock} from './utils.js';
7
+ import {getStringFromDataView, pushMetadataBlock} from './utils.js';
8
8
  import Constants from './constants.js';
9
9
 
10
10
  export default {
@@ -26,6 +26,8 @@ export const TYPE_PHYS = 'pHYs';
26
26
  export const TYPE_TIME = 'tIME';
27
27
  export const TYPE_EXIF = 'eXIf';
28
28
  export const TYPE_ICCP = 'iCCP';
29
+ // PNG spec: an iCCP profile name is at most 79 bytes, like a text keyword.
30
+ const MAX_ICC_PROFILE_NAME_LENGTH = 79;
29
31
 
30
32
  /**
31
33
  * Checks if the provided data view represents a PNG file.
@@ -100,20 +102,20 @@ function findPngOffsets(dataView, async, metadataBlocks) {
100
102
  blockType = 'exif';
101
103
  } else if (Constants.USE_ICC && async && isPngIccpChunk(dataView, offset)) {
102
104
  const iccHeaderOffset = offset + PNG_CHUNK_DATA_OFFSET;
103
- const iccHeader = parseIccHeader(dataView, iccHeaderOffset);
105
+ const iccHeader = parseIccHeader(dataView, iccHeaderOffset, chunkDataLength);
104
106
  if (iccHeader !== undefined) {
105
107
  offsets.hasAppMarkers = true;
108
+ // PNG spec: a file has at most one iCCP chunk, so only the first valid one is kept.
106
109
  if (!offsets.iccChunks) {
107
- offsets.iccChunks = [];
110
+ offsets.iccChunks = [{
111
+ offset: iccHeader.compressedProfileOffset,
112
+ length: chunkDataLength - (iccHeader.compressedProfileOffset - iccHeaderOffset),
113
+ chunkNumber: 1,
114
+ chunksTotal: 1,
115
+ profileName: iccHeader.profileName,
116
+ compressionMethod: iccHeader.compressionMethod
117
+ }];
108
118
  }
109
- offsets.iccChunks.push({
110
- offset: iccHeader.compressedProfileOffset,
111
- length: chunkDataLength - (iccHeader.compressedProfileOffset - iccHeaderOffset),
112
- chunkNumber: 1,
113
- chunksTotal: 1,
114
- profileName: iccHeader.profileName,
115
- compressionMethod: iccHeader.compressionMethod
116
- });
117
119
  blockType = 'icc';
118
120
  }
119
121
  } else if (isPngChunk(dataView, offset)) {
@@ -190,22 +192,32 @@ function getPngXmpDataOffset(dataView, offset) {
190
192
  return offset;
191
193
  }
192
194
 
193
- function parseIccHeader(dataView, offset) {
195
+ function parseIccHeader(dataView, offset, chunkDataLength) {
194
196
  const NULL_SEPARATOR_SIZE = 1;
195
197
  const COMPRESSION_METHOD_SIZE = 1;
198
+ const chunkEnd = Math.min(offset + chunkDataLength, dataView.byteLength);
196
199
 
197
- const profileName = getNullTerminatedStringFromDataView(dataView, offset);
198
- offset += profileName.length + NULL_SEPARATOR_SIZE;
199
-
200
- if (offset + COMPRESSION_METHOD_SIZE > dataView.byteLength) {
200
+ const profileNameLength = getIccProfileNameLength(dataView, offset, chunkEnd);
201
+ if (profileNameLength === undefined) {
202
+ return undefined;
203
+ }
204
+ const compressionMethodOffset = offset + profileNameLength + NULL_SEPARATOR_SIZE;
205
+ if (compressionMethodOffset + COMPRESSION_METHOD_SIZE > chunkEnd) {
201
206
  return undefined;
202
207
  }
203
- const compressionMethod = dataView.getUint8(offset);
204
- offset += COMPRESSION_METHOD_SIZE;
205
208
 
206
209
  return {
207
- profileName,
208
- compressionMethod,
209
- compressedProfileOffset: offset
210
+ profileName: getStringFromDataView(dataView, offset, profileNameLength),
211
+ compressionMethod: dataView.getUint8(compressionMethodOffset),
212
+ compressedProfileOffset: compressionMethodOffset + COMPRESSION_METHOD_SIZE
210
213
  };
211
214
  }
215
+
216
+ function getIccProfileNameLength(dataView, offset, chunkEnd) {
217
+ for (let i = 0; i <= MAX_ICC_PROFILE_NAME_LENGTH && offset + i < chunkEnd; i++) {
218
+ if (dataView.getUint8(offset + i) === 0) {
219
+ return i;
220
+ }
221
+ }
222
+ return undefined;
223
+ }