exifreader 4.47.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "exifreader",
3
- "version": "4.47.0",
3
+ "version": "4.48.0",
4
4
  "description": "Library that parses Exif metadata in images.",
5
5
  "author": "Mattias Wallander <mattias@wallander.eu>",
6
6
  "repository": {
@@ -25,7 +25,7 @@
25
25
  "exifreader": "bin/cli.js"
26
26
  },
27
27
  "optionalDependencies": {
28
- "@xmldom/xmldom": "^0.9.10"
28
+ "@xmldom/xmldom": "^0.9.12"
29
29
  },
30
30
  "devDependencies": {
31
31
  "@babel/core": "^7.29.7",
package/src/composite.js CHANGED
@@ -26,14 +26,13 @@ function get(tags, expanded) {
26
26
  const compositeTags = {};
27
27
  let hasCompositeTags = false;
28
28
 
29
- const focalLength = getTagValue(tags, 'exif', 'FocalLength', expanded);
30
- const focalPlaneXResolution = getTagValue(tags, 'exif', 'FocalPlaneXResolution', expanded);
31
- const focalPlaneYResolution = getTagValue(tags, 'exif', 'FocalPlaneYResolution', expanded);
32
- const focalPlaneResolutionUnit = getTagValue(tags, 'exif', 'FocalPlaneResolutionUnit', expanded);
33
- const imageWidth = getTagValue(tags, 'file', 'Image Width', expanded);
34
- const imageHeight = getTagValue(tags, 'file', 'Image Height', expanded);
35
- const focalLengthIn35mmFilm = getTagValue(tags, 'exif', 'FocalLengthIn35mmFilm', expanded)
36
- || getFocalLengthIn35mmFilmValue(focalPlaneXResolution, focalPlaneYResolution, focalPlaneResolutionUnit, imageWidth, imageHeight, focalLength);
29
+ const focalLength = getPositiveRational(getTagValue(tags, 'exif', 'FocalLength', expanded));
30
+ const focalPlaneXResolution = getPositiveRational(getTagValue(tags, 'exif', 'FocalPlaneXResolution', expanded));
31
+ const focalPlaneYResolution = getPositiveRational(getTagValue(tags, 'exif', 'FocalPlaneYResolution', expanded));
32
+ const focalPlaneResolutionUnit = getPositiveNumber(getTagValue(tags, 'exif', 'FocalPlaneResolutionUnit', expanded));
33
+ const pixelDimensions = getPixelDimensions(tags, expanded);
34
+ const focalLengthIn35mmFilm = getPositiveNumber(getTagValue(tags, 'exif', 'FocalLengthIn35mmFilm', expanded))
35
+ || getFocalLengthIn35mmFilmValue(focalPlaneXResolution, focalPlaneYResolution, focalPlaneResolutionUnit, pixelDimensions.width, pixelDimensions.height, focalLength);
37
36
 
38
37
  if (focalLengthIn35mmFilm) {
39
38
  compositeTags.FocalLength35efl = {
@@ -72,14 +71,70 @@ function getTagValue(tags, group, tagName, expanded) {
72
71
  return undefined;
73
72
  }
74
73
 
74
+ /**
75
+ * Converts an Exif `[numerator, denominator]` array, an XMP `'n/d'` string,
76
+ * or a plain number or numeric string to a number.
77
+ *
78
+ * @returns {number|undefined} The number, or undefined when it, or either part
79
+ * of a rational, is not finite and positive.
80
+ */
81
+ function getPositiveRational(value) {
82
+ if (typeof value === 'string') {
83
+ // The limit keeps a long run of slashes from allocating one part per slash.
84
+ const parts = value.split('/', 3);
85
+ if (parts.length === 1) {
86
+ return getPositiveNumber(value);
87
+ }
88
+ return getPositiveQuotient(parts);
89
+ }
90
+ if (Array.isArray(value)) {
91
+ return getPositiveQuotient(value);
92
+ }
93
+ return getPositiveNumber(value);
94
+ }
95
+
96
+ /**
97
+ * @returns {number|undefined} The value as a number when it is a number or a
98
+ * numeric string that is finite and positive, otherwise undefined.
99
+ */
100
+ function getPositiveNumber(value) {
101
+ let number;
102
+ if (typeof value === 'number') {
103
+ number = value;
104
+ } else if (typeof value === 'string') {
105
+ number = Number(value);
106
+ }
107
+ return number > 0 && number < Infinity ? number : undefined;
108
+ }
109
+
110
+ function getPositiveQuotient(parts) {
111
+ if (parts.length !== 2) {
112
+ return undefined;
113
+ }
114
+ return getPositiveNumber(getPositiveNumber(parts[0]) / getPositiveNumber(parts[1]));
115
+ }
116
+
117
+ function getPixelDimensions(tags, expanded) {
118
+ const pixelXDimension = getPositiveNumber(getTagValue(tags, 'exif', 'PixelXDimension', expanded));
119
+ const pixelYDimension = getPositiveNumber(getTagValue(tags, 'exif', 'PixelYDimension', expanded));
120
+ if (pixelXDimension && pixelYDimension) {
121
+ return {width: pixelXDimension, height: pixelYDimension};
122
+ }
123
+ return {
124
+ width: getPositiveNumber(getTagValue(tags, 'file', 'Image Width', expanded)),
125
+ height: getPositiveNumber(getTagValue(tags, 'file', 'Image Height', expanded))
126
+ };
127
+ }
128
+
75
129
  /**
76
130
  * Calculates the 35mm equivalent focal length from camera sensor data.
77
131
  *
78
132
  * This function determines how the field of view of a camera's sensor compares to a
79
133
  * standard 35mm film frame (36mm × 24mm). The conversion involves:
80
134
  *
81
- * 1. **Sensor dimensions**: Calculated from image pixel count and focal plane
82
- * resolution (pixels per unit area)
135
+ * 1. **Sensor dimensions**: The original image size in pixels (PixelXDimension and
136
+ * PixelYDimension, or the file's size when absent) divided by the focal plane
137
+ * resolution (pixels per unit length)
83
138
  * 2. **Crop factor**: The ratio between the sensor diagonal and the standard
84
139
  * 35mm diagonal (43.27mm)
85
140
  * 3. **Equivalent focal length**: Actual focal length multiplied by the crop factor
@@ -88,53 +143,47 @@ function getTagValue(tags, group, tagName, expanded) {
88
143
  * field of view of a 75mm lens on a 35mm camera. This doesn't change the actual
89
144
  * focal length or depth of field characteristics, only the angle of view.
90
145
  */
91
- function getFocalLengthIn35mmFilmValue(focalPlaneXResolution, focalPlaneYResolution, focalPlaneResolutionUnit, imageWidth, imageHeight, focalLength) {
146
+ function getFocalLengthIn35mmFilmValue(focalPlaneXResolution, focalPlaneYResolution, focalPlaneResolutionUnit, pixelWidth, pixelHeight, focalLength) {
92
147
  // Standard 35mm film diagonal is 43.27mm (calculated from 36mm x 24mm frame)
93
148
  const DIAGONAL_35mm = 43.27;
94
149
 
95
- if (focalPlaneXResolution && focalPlaneYResolution && focalPlaneResolutionUnit && imageWidth && imageHeight && focalLength) {
96
- try {
97
- let resolutionUnitFactor;
98
- switch (focalPlaneResolutionUnit) {
99
- case FOCAL_PLANE_RESOLUTION_UNIT.INCHES:
100
- resolutionUnitFactor = UNIT_FACTORS.INCHES_TO_MM;
101
- break;
102
- case FOCAL_PLANE_RESOLUTION_UNIT.CENTIMETERS:
103
- resolutionUnitFactor = UNIT_FACTORS.CM_TO_MM;
104
- break;
105
- case FOCAL_PLANE_RESOLUTION_UNIT.MILLIMETERS:
106
- resolutionUnitFactor = UNIT_FACTORS.MM_TO_MM;
107
- break;
108
- default:
109
- return undefined;
110
- }
111
-
112
- const focalPlaneXResolutionMm = focalPlaneXResolution[0] / focalPlaneXResolution[1] * resolutionUnitFactor;
113
- const focalPlaneYResolutionMm = focalPlaneYResolution[0] / focalPlaneYResolution[1] * resolutionUnitFactor;
114
-
115
- const sensorWidthMm = imageWidth / focalPlaneXResolutionMm;
116
- const sensorHeightMm = imageHeight / focalPlaneYResolutionMm;
117
-
118
- const sensorDiagonal = Math.sqrt(sensorWidthMm ** 2 + sensorHeightMm ** 2);
119
- const focalLength35mm = (focalLength[0] / focalLength[1]) * (DIAGONAL_35mm / sensorDiagonal);
120
- return focalLength35mm;
121
- } catch (error) {
122
- // Ignore.
150
+ if (focalPlaneXResolution && focalPlaneYResolution && focalPlaneResolutionUnit && pixelWidth && pixelHeight && focalLength) {
151
+ let resolutionUnitFactor;
152
+ switch (focalPlaneResolutionUnit) {
153
+ case FOCAL_PLANE_RESOLUTION_UNIT.INCHES:
154
+ resolutionUnitFactor = UNIT_FACTORS.INCHES_TO_MM;
155
+ break;
156
+ case FOCAL_PLANE_RESOLUTION_UNIT.CENTIMETERS:
157
+ resolutionUnitFactor = UNIT_FACTORS.CM_TO_MM;
158
+ break;
159
+ case FOCAL_PLANE_RESOLUTION_UNIT.MILLIMETERS:
160
+ resolutionUnitFactor = UNIT_FACTORS.MM_TO_MM;
161
+ break;
162
+ default:
163
+ return undefined;
123
164
  }
165
+
166
+ const focalPlaneXResolutionMm = focalPlaneXResolution / resolutionUnitFactor;
167
+ const focalPlaneYResolutionMm = focalPlaneYResolution / resolutionUnitFactor;
168
+
169
+ const sensorWidthMm = pixelWidth / focalPlaneXResolutionMm;
170
+ const sensorHeightMm = pixelHeight / focalPlaneYResolutionMm;
171
+
172
+ const sensorDiagonal = Math.sqrt(sensorWidthMm ** 2 + sensorHeightMm ** 2);
173
+ const focalLength35mm = focalLength * (DIAGONAL_35mm / sensorDiagonal);
174
+ return getPositiveNumber(focalLength35mm);
124
175
  }
125
176
  return undefined;
126
177
  }
127
178
 
128
179
  function getScaleFactorTo35mmEquivalent(focalLength, focalLengthIn35mmFilm) {
129
180
  if (focalLength && focalLengthIn35mmFilm) {
130
- try {
131
- const value = focalLengthIn35mmFilm / (focalLength[0] / focalLength[1]);
181
+ const value = getPositiveNumber(focalLengthIn35mmFilm / focalLength);
182
+ if (value) {
132
183
  return {
133
184
  value,
134
185
  description: value.toFixed(1),
135
186
  };
136
- } catch (error) {
137
- // Ignore.
138
187
  }
139
188
  }
140
189
  return undefined;
@@ -144,14 +193,12 @@ function getFieldOfView(focalLengthIn35mmFilm) {
144
193
  const FULL_FRAME_SENSOR_WIDTH_MM = 36;
145
194
 
146
195
  if (focalLengthIn35mmFilm) {
147
- try {
148
- const value = 2 * Math.atan(FULL_FRAME_SENSOR_WIDTH_MM / (2 * focalLengthIn35mmFilm)) * (180 / Math.PI);
196
+ const value = getPositiveNumber(2 * Math.atan(FULL_FRAME_SENSOR_WIDTH_MM / (2 * focalLengthIn35mmFilm)) * (180 / Math.PI));
197
+ if (value) {
149
198
  return {
150
199
  value,
151
200
  description: value.toFixed(1) + ' deg',
152
201
  };
153
- } catch (error) {
154
- // Ignore.
155
202
  }
156
203
  }
157
204
  return undefined;
@@ -8,7 +8,7 @@
8
8
  */
9
9
  /* global Buffer */
10
10
 
11
- import {objectAssign, decompress, withDecompressBudget, COMPRESSION_METHOD_BROTLI, getDataView, getStringValueFromArray, assertPromiseSupport, setProperty} from './utils.js';
11
+ import {objectAssign, decompress, withDecompressBudget, COMPRESSION_METHOD_BROTLI, getDataView, getByteString, getStringValueFromArray, assertPromiseSupport, setProperty} from './utils.js';
12
12
  import {isFilePathOrURL, isBrowserFileObject, loadFile, loadFileObject} from './file-loaders.js';
13
13
  import {makeLoadAuto, validateAutoOptions} from './load-auto.js';
14
14
  import Constants from './constants.js';
@@ -17,7 +17,7 @@ import ByteOrder from './byte-order.js';
17
17
  import {getTiffHeaderOffset} from './image-header-iso-bmff.js';
18
18
  import ImageHeader from './image-header.js';
19
19
  import Tags from './tags.js';
20
- import {getValueBudget} from './tags-helpers.js';
20
+ import {getValueBudget, addDecompressedValueAllowance} from './tags-helpers.js';
21
21
  import MpfTags from './mpf-tags.js';
22
22
  import FileTags from './file-tags.js';
23
23
  import JxlFileTags from './jxl-file-tags.js';
@@ -39,6 +39,11 @@ import {createTagFilter} from './tag-filter.js';
39
39
  import {buildTagsFromMergeSteps, isThenable} from './loadview-pipeline.js';
40
40
  import exifErrors from './errors.js';
41
41
 
42
+ // Brob XMP is bounded by the file size, as brob Exif is, plus room for one JPEG
43
+ // standard XMP segment so that a small file can still carry a typical packet.
44
+ const BROB_XMP_SIZE_PER_INPUT_SIZE = 4;
45
+ const BROB_XMP_SIZE_ALLOWANCE = 64 * 1024;
46
+
42
47
  export default {
43
48
  load,
44
49
  loadView,
@@ -216,7 +221,8 @@ export function loadView(
216
221
  parsedExifTags['IPTC-NAA'].value,
217
222
  0,
218
223
  includeUnknown,
219
- tagFilter
224
+ tagFilter,
225
+ valueBudget
220
226
  );
221
227
  const parsedIptcTags =
222
228
  filterTagsForParse('iptc', readIptcTags, tagFilter);
@@ -239,7 +245,7 @@ export function loadView(
239
245
  && tagFilter.shouldParseGroup('xmp')
240
246
  ) {
241
247
  const readXmpTags = XmpTags.read(
242
- getStringValueFromArray(parsedExifTags['ApplicationNotes'].value),
248
+ getByteString(parsedExifTags['ApplicationNotes'].value),
243
249
  undefined,
244
250
  domParser
245
251
  );
@@ -385,7 +391,7 @@ export function loadView(
385
391
  && iptcDataOffset !== undefined
386
392
  && tagFilter.shouldParseGroup('iptc')
387
393
  ) {
388
- const readTags = IptcTags.read(dataView, iptcDataOffset, includeUnknown, tagFilter);
394
+ const readTags = IptcTags.read(dataView, iptcDataOffset, includeUnknown, tagFilter, valueBudget);
389
395
  const parsedIptcTags = filterTagsForParse('iptc', readTags, tagFilter);
390
396
  parsedGroups.iptc = parsedIptcTags;
391
397
 
@@ -428,6 +434,7 @@ export function loadView(
428
434
  decompress(compressedExifData, COMPRESSION_METHOD_BROTLI, undefined, 'dataview', decompressConfig)
429
435
  .then((decompressedDataView) => {
430
436
  const brobTiffHeaderOffset = getTiffHeaderOffset(decompressedDataView, 0);
437
+ addDecompressedValueAllowance(valueBudget, decompressedDataView.byteLength);
431
438
  const {tags: readTags} = Tags.read(
432
439
  decompressedDataView,
433
440
  brobTiffHeaderOffset,
@@ -439,6 +446,9 @@ export function loadView(
439
446
  if (readTags.Thumbnail) {
440
447
  delete readTags.Thumbnail;
441
448
  }
449
+ if (readTags.MakerNote) {
450
+ delete readTags.MakerNote.__offset;
451
+ }
442
452
  deferredResults.brobExif = readTags;
443
453
  })
444
454
  .catch(() => {
@@ -463,6 +473,10 @@ export function loadView(
463
473
  deferredPromises.push(
464
474
  decompress(compressedXmpData, COMPRESSION_METHOD_BROTLI, undefined, 'dataview', decompressConfig)
465
475
  .then((decompressedDataView) => {
476
+ if (exceedsBrobXmpSizeBound(decompressedDataView, dataView)) {
477
+ deferredResults.brobXmp = {};
478
+ return;
479
+ }
466
480
  deferredResults.brobXmp = XmpTags.read(
467
481
  decompressedDataView,
468
482
  [{dataOffset: 0, length: decompressedDataView.byteLength}],
@@ -562,7 +576,7 @@ export function loadView(
562
576
  || tagFilter.shouldParseGroup('iptc')
563
577
  )
564
578
  ) {
565
- const {readTags, readTagsPromise} = PngTextTags.read(
579
+ const {readTags, embeddedExifTags, embeddedIptcTags, embeddedExifThumbnail, readTagsPromise} = PngTextTags.read(
566
580
  dataView,
567
581
  pngTextChunks,
568
582
  async,
@@ -570,13 +584,17 @@ export function loadView(
570
584
  computed,
571
585
  tagFilter,
572
586
  decompressConfig,
573
- valueBudget
587
+ valueBudget,
588
+ getPngTextThumbnailReader(tagFilter)
574
589
  );
575
590
  pngTextIsAsync = !!readTagsPromise;
576
591
 
577
592
  mergeSteps.push({
578
593
  type: 'processPngTextReadTags',
579
594
  readTags,
595
+ embeddedExifTags,
596
+ embeddedIptcTags,
597
+ embeddedExifThumbnail,
580
598
  });
581
599
 
582
600
  if (readTagsPromise) {
@@ -779,7 +797,20 @@ function getBrobDataView(dataView, brobChunk) {
779
797
  // than its header, so bound the view by the bytes present. The JXL header
780
798
  // parser never reports a dataOffset past the end of the view.
781
799
  const length = Math.max(0, Math.min(brobChunk.length, dataView.byteLength - brobChunk.dataOffset));
782
- return new DataView(dataView.buffer, dataView.byteOffset + brobChunk.dataOffset, length);
800
+ if (isDataViewLike(dataView)) {
801
+ return new DataView(dataView.buffer, dataView.byteOffset + brobChunk.dataOffset, length);
802
+ }
803
+ // The Node Buffer wrapper has no ArrayBuffer to view, so copy the bytes out.
804
+ const bytes = new Uint8Array(length);
805
+ for (let i = 0; i < length; i++) {
806
+ bytes[i] = dataView.getUint8(brobChunk.dataOffset + i);
807
+ }
808
+ return new DataView(bytes.buffer);
809
+ }
810
+
811
+ function exceedsBrobXmpSizeBound(decompressedDataView, inputDataView) {
812
+ return decompressedDataView.byteLength
813
+ > BROB_XMP_SIZE_PER_INPUT_SIZE * inputDataView.byteLength + BROB_XMP_SIZE_ALLOWANCE;
783
814
  }
784
815
 
785
816
  function readExifTagsSafely(dataView, tiffHeaderOffset, includeUnknown, computed, tagFilter) {
@@ -800,6 +831,21 @@ function readExifTagsSafely(dataView, tiffHeaderOffset, includeUnknown, computed
800
831
  }
801
832
  }
802
833
 
834
+ function getPngTextThumbnailReader(tagFilter) {
835
+ if (
836
+ !Constants.USE_EXIF
837
+ || !Constants.USE_THUMBNAIL
838
+ || !tagFilter.shouldReturnTag('thumbnail', 'Thumbnail')
839
+ ) {
840
+ return undefined;
841
+ }
842
+ return (dataView, thumbnailIfdTags, tiffHeaderOffset) => Thumbnail.get(
843
+ dataView,
844
+ filterTagsForParse('thumbnail', thumbnailIfdTags, tagFilter),
845
+ tiffHeaderOffset
846
+ );
847
+ }
848
+
803
849
  function filterTagsForParse(groupKey, readTags, tagFilter) {
804
850
  if (!tagFilter.isActive) {
805
851
  return readTags;
@@ -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, maxBytes: 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
  /**
@@ -76,15 +97,21 @@ function legacyRange(options) {
76
97
  *
77
98
  * @param {string} url
78
99
  * @param {{start?: number, end?: number, maxBytes?: number}} [range] `end` is exclusive. Omit (or pass `Infinity`)
79
- * to read to EOF. With `maxBytes` (a non-negative integer) at most that many body bytes are kept, for a 2xx
80
- * status and for 416; where the response body is a `ReadableStream` the transfer is stopped once they have
81
- * arrived, otherwise the whole body is read and cut.
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.
82
103
  * @returns {Promise<{buffer: ArrayBuffer, totalSize: number|undefined, status: number|undefined}>}
83
104
  * `totalSize` is taken from the `Content-Range` or `Content-Length` response header when present.
84
105
  * Rejects with `Could not fetch file: <status>` on non-2xx responses, except 416 which the
85
- * `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`.
86
110
  */
87
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
+ }
88
115
  const options = {method: 'GET'};
89
116
  if (start > 0 || (end !== undefined && end !== Infinity)) {
90
117
  options.headers = {range: buildRangeHeader(start, end)};
@@ -92,10 +119,15 @@ export function fetchRange(url, {start = 0, end, maxBytes} = {}) {
92
119
  return fetch(url, options).then((response) => {
93
120
  const status = response && typeof response.status === 'number' ? response.status : undefined;
94
121
  if (status !== undefined && !isAcceptableFetchStatus(status)) {
122
+ cancelQuietly(response.body);
95
123
  const statusText = response.statusText || '';
96
124
  return Promise.reject(new Error(`Could not fetch file: ${status} ${statusText}`.trim()));
97
125
  }
98
126
  const totalSize = totalSizeFromFetchResponse(response);
127
+ if (status === HTTP_STATUS_RANGE_NOT_SATISFIABLE) {
128
+ cancelQuietly(response.body);
129
+ return {buffer: new ArrayBuffer(0), totalSize, status};
130
+ }
99
131
  return readFetchBody(response, maxBytes).then((buffer) => ({buffer, totalSize, status}));
100
132
  });
101
133
  }
@@ -146,8 +178,8 @@ function readStreamUpTo(reader, maxBytes) {
146
178
  });
147
179
  }
148
180
 
149
- function cancelQuietly(reader) {
150
- Promise.resolve().then(() => reader.cancel()).then(undefined, () => undefined);
181
+ function cancelQuietly(cancellable) {
182
+ Promise.resolve().then(() => cancellable.cancel()).then(undefined, () => undefined);
151
183
  }
152
184
 
153
185
  /**
@@ -189,6 +221,10 @@ function createByteCollector(maxBytes) {
189
221
  }
190
222
  }
191
223
 
224
+ function isEmptyRange(start, end) {
225
+ return end !== undefined && end !== Infinity && end <= start;
226
+ }
227
+
192
228
  function buildRangeHeader(start, end) {
193
229
  if (end === undefined || end === Infinity) {
194
230
  return `bytes=${start}-`;
@@ -214,7 +250,9 @@ function isAcceptableFetchStatus(status) {
214
250
 
215
251
  /**
216
252
  * Range-aware Node `http(s).get`. Same contract as `fetchRange`. Rejects
217
- * 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.
218
256
  *
219
257
  * @param {string} url
220
258
  * @param {{start?: number, end?: number, maxBytes?: number}} [range] `end` is exclusive. Omit (or pass `Infinity`)
@@ -223,6 +261,9 @@ function isAcceptableFetchStatus(status) {
223
261
  * @returns {Promise<{buffer: Buffer, totalSize: number|undefined, status: number|undefined}>}
224
262
  */
225
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
+ }
226
267
  return new Promise((resolve, reject) => {
227
268
  const options = {};
228
269
  if (start > 0 || (end !== undefined && end !== Infinity)) {
@@ -252,11 +293,12 @@ export function nodeGetRange(url, {start = 0, end, maxBytes} = {}) {
252
293
  } else if (response.statusCode === HTTP_STATUS_RANGE_NOT_SATISFIABLE) {
253
294
  // Resolve (rather than reject) so the adaptive `length: 'auto'`
254
295
  // loop can fall back to a full read, mirroring the fetch path.
255
- response.resume();
256
- 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});
257
299
  } else {
258
300
  reject(new Error(`Could not fetch file: ${response.statusCode} ${response.statusMessage}`));
259
- response.resume();
301
+ response.destroy();
260
302
  }
261
303
  }).on('error', (error) => reject(error));
262
304
  });
@@ -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 {
@@ -586,18 +590,19 @@ function parseItemInformationBox(dataView, startOffset, version, contentOffset,
586
590
  };
587
591
  }
588
592
 
589
- function parseItemInformationEntryBox(dataView, startOffset, version, contentOffset, length) {
593
+ function parseItemInformationEntryBox(dataView, startOffset, version, contentOffset, length, containerEnd) {
590
594
  const FLAGS_SIZE = 3;
591
595
 
592
596
  contentOffset += FLAGS_SIZE;
593
597
  const entry = {type: 'infe', length};
598
+ const entryEnd = Math.min(startOffset + length, containerEnd);
594
599
 
595
600
  if (version === 0 || version === 1) {
596
601
  entry.itemId = dataView.getUint16(contentOffset);
597
602
  contentOffset += 2;
598
603
  entry.itemProtectionIndex = dataView.getUint16(contentOffset);
599
604
  contentOffset += 2;
600
- entry.itemName = getNullTerminatedStringFromDataView(dataView, contentOffset);
605
+ entry.itemName = readEntryString(dataView, contentOffset, entryEnd).value;
601
606
  contentOffset += entry.itemName.length + 1;
602
607
  // entry.contentType = getNullTerminatedStringFromDataView(dataView, offset);
603
608
  // offset += entry.contentType.length + 1;
@@ -640,19 +645,35 @@ function parseItemInformationEntryBox(dataView, startOffset, version, contentOff
640
645
  contentOffset += 2;
641
646
  entry.itemType = dataView.getUint32(contentOffset);
642
647
  contentOffset += 4;
643
- 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
+ }
644
653
  contentOffset += entry.itemName.length + 1;
645
654
  if (entry.itemType === ITEM_INFO_TYPE_MIME) {
646
- 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
+ }
647
660
  contentOffset += entry.contentType.length + 1;
648
- if (startOffset + length > contentOffset) {
649
- entry.contentEncoding = getNullTerminatedStringFromDataView(dataView, contentOffset);
650
- contentOffset += entry.contentEncoding.length + 1;
661
+ if (entryEnd > contentOffset) {
662
+ entry.contentEncoding = readEntryString(dataView, contentOffset, entryEnd).value;
651
663
  }
652
664
  } else if (entry.itemType === ITEM_INFO_TYPE_URI) {
653
- entry.itemUri = getNullTerminatedStringFromDataView(dataView, contentOffset);
654
- contentOffset += entry.itemUri.length + 1;
665
+ entry.itemUri = readEntryString(dataView, contentOffset, entryEnd).value;
655
666
  }
656
667
  }
657
668
  return entry;
658
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);