Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

fix(media-proxy): bound media processing and storage reads (#3878)

Hampusf9b4691495f4
diff --git a/fluxer_media_proxy/src/media_process/animated_transform.rs b/fluxer_media_proxy/src/media_process/animated_transform.rs
index 912ee32bf..bbf6e2010 100644
--- a/fluxer_media_proxy/src/media_process/animated_transform.rs
+++ b/fluxer_media_proxy/src/media_process/animated_transform.rs
@@ -4,7 +4,8 @@ use super::image_probe::animated_probe_from_image;
use super::loaded_image::validate_dimensions;
use super::native_runtime::{clear_vips_error, vips_runtime};
use super::{
- MediaError, native_animated_frame_limit, native_buffer_to_media_bytes, native_status_error,
+ MediaError, native_animated_frame_limit, native_buffer_to_media_bytes,
+ native_optional_deadline, native_status_error,
};
use crate::{
constants,
@@ -31,6 +32,7 @@ pub(super) fn try_decode_heif_primary_still(
input: &[u8],
media_limits: &MediaLimits,
metrics: &TransformMetrics,
+ deadline_ms: Option<i64>,
) -> Result<Option<DecodedHEIFPrimaryStill>, MediaError> {
let mut raw = ptr::null_mut();
let mut facts = native::FluxerHEIFPrimaryStillDecodeFacts::empty();
@@ -38,7 +40,7 @@ pub(super) fn try_decode_heif_primary_still(
native::fluxer_heif_decode_primary_still(
input.as_ptr().cast(),
input.len(),
- 0,
+ native_optional_deadline(deadline_ms),
&mut raw,
media_limits.image_pixels(),
c_int::try_from(media_limits.image_dimension())
@@ -54,6 +56,10 @@ pub(super) fn try_decode_heif_primary_still(
metrics.avif_libheif_decode_failures.inc();
return Ok(None);
}
+ NativeStatus::DeadlineExceeded => {
+ clear_vips_error();
+ return Err(MediaError::RequestTimeout);
+ }
status => {
clear_vips_error();
metrics.avif_libheif_decode_failures.inc();
@@ -76,6 +82,7 @@ pub(super) fn try_decode_apng(
input: &[u8],
animated: bool,
media_limits: &MediaLimits,
+ deadline_ms: Option<i64>,
) -> Result<Option<DecodedAnimation>, MediaError> {
let runtime = vips_runtime()?;
let mut raw = ptr::null_mut();
@@ -85,7 +92,7 @@ pub(super) fn try_decode_apng(
input.as_ptr().cast(),
input.len(),
runtime.config().ffmpeg_decoder_threads(),
- 0,
+ native_optional_deadline(deadline_ms),
&mut raw,
if animated {
native_animated_frame_limit(media_limits)
@@ -125,6 +132,7 @@ pub(super) fn try_decode_apng(
pub(super) fn decode_heif_sequence(
input: &[u8],
media_limits: &MediaLimits,
+ deadline_ms: Option<i64>,
) -> Result<Option<DecodedAnimation>, MediaError> {
let runtime = vips_runtime()?;
let mut raw = ptr::null_mut();
@@ -134,7 +142,7 @@ pub(super) fn decode_heif_sequence(
input.as_ptr().cast(),
input.len(),
runtime.config().ffmpeg_decoder_threads(),
- 0,
+ native_optional_deadline(deadline_ms),
&mut raw,
native_animated_frame_limit(media_limits),
media_limits.animated_total_pixels(),
diff --git a/fluxer_media_proxy/src/media_process/metadata.rs b/fluxer_media_proxy/src/media_process/metadata.rs
index 592800860..d8b9fc7ca 100644
--- a/fluxer_media_proxy/src/media_process/metadata.rs
+++ b/fluxer_media_proxy/src/media_process/metadata.rs
@@ -11,6 +11,7 @@ use super::placeholder::{encode_thumbhash, encoded_placeholder, optional_thumbha
use crate::{
constants,
media_limits::MediaLimits,
+ media_type::MediaType,
metrics::transform::TransformMetrics,
mime,
nsfw::{NSFWClassification, NSFWClient, NSFWPolicy},
@@ -123,10 +124,11 @@ fn validate_metadata_image_dimensions(
fn probe_av_metadata_without_requiring_a_frame(
input: &[u8],
media_limits: &MediaLimits,
+ deadline_ms: Option<i64>,
) -> Result<AVMetadata, MediaError> {
- match probe_av_metadata(input, NSFW_PREVIEW_MAX_DIMENSION, media_limits, None) {
+ match probe_av_metadata(input, NSFW_PREVIEW_MAX_DIMENSION, media_limits, deadline_ms) {
Ok(metadata) => Ok(metadata),
- Err(error) => probe_av_metadata(input, 0, media_limits, None).map_err(|_| error),
+ Err(error) => probe_av_metadata(input, 0, media_limits, deadline_ms).map_err(|_| error),
}
}
@@ -167,6 +169,7 @@ fn metadata_blocking(request: MetadataBlockingRequest<'_>) -> Result<PreparedMet
Some(probe_av_metadata_without_requiring_a_frame(
input,
media_limits,
+ options.deadline_ms,
)?)
} else {
None
@@ -210,15 +213,18 @@ fn metadata_blocking(request: MetadataBlockingRequest<'_>) -> Result<PreparedMet
None
};
- let scan_eligible = is_image
- || (category == mime::Category::Video
- && av_probe.as_ref().is_some_and(|probe| probe.has_video));
+ let probe_has_video = av_probe.as_ref().is_some_and(|probe| probe.has_video);
+ let scan_eligible = is_image || probe_has_video;
let nsfw_scan = if let Some(threshold) = options.nsfw.scan_threshold(scan_eligible) {
nsfw_scan_buffers(NSFWScanSource {
media_limits,
metrics,
threshold,
- content_type: sniffed.mime,
+ content_type: if probe_has_video {
+ MediaType::MP4Video.mime()
+ } else {
+ sniffed.mime
+ },
animated,
frame_count: frames_count.max(sniffed.frames),
input,
diff --git a/fluxer_media_proxy/src/media_process/native_cost.rs b/fluxer_media_proxy/src/media_process/native_cost.rs
index 891183efe..f7b9f4003 100644
--- a/fluxer_media_proxy/src/media_process/native_cost.rs
+++ b/fluxer_media_proxy/src/media_process/native_cost.rs
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
use super::image_probe::probe_image_dims;
-use super::loaded_image::static_output_pixels;
+use super::loaded_image::{static_output_pixels, validate_dimensions_u32};
use super::native_runtime::ensure_vips_init;
use super::{ImageDimensions, MediaError};
use crate::{
@@ -46,7 +46,7 @@ pub fn image_transform_cost(
) -> Result<NativeCost, MediaError> {
ensure_vips_init()?;
let sniffed_mime = mime::sniff(input).mime;
- let dims = probe_image_dims(media_limits, input)?;
+ let dims = cost_image_dims(media_limits, input, sniffed_mime)?;
let source_pixels = dims.width as usize * dims.height as usize;
let options =
fit_static_output_to_budget(input.len(), sniffed_mime, options, dims, media_limits);
@@ -61,6 +61,42 @@ pub fn image_transform_cost(
Ok(NativeCost::Bytes(input.len().saturating_add(pixel_cost)))
}
+fn cost_image_dims(
+ media_limits: &MediaLimits,
+ input: &[u8],
+ sniffed_mime: &str,
+) -> Result<ImageDimensions, MediaError> {
+ if sniffed_mime == "image/bmp"
+ && let Some((width, height)) = bmp_header_dims(input)
+ {
+ validate_dimensions_u32(media_limits, width, height)?;
+ return Ok(ImageDimensions {
+ width,
+ height,
+ pages: 1,
+ bands: 4,
+ eight_bit: true,
+ });
+ }
+ probe_image_dims(media_limits, input)
+}
+
+fn bmp_header_dims(input: &[u8]) -> Option<(u32, u32)> {
+ let read = |offset: usize, len: usize| input.get(offset..offset + len);
+ let header_size = u32::from_le_bytes(read(14, 4)?.try_into().ok()?);
+ if header_size == 12 {
+ let width = u16::from_le_bytes(read(18, 2)?.try_into().ok()?);
+ let height = u16::from_le_bytes(read(20, 2)?.try_into().ok()?);
+ return Some((u32::from(width), u32::from(height)));
+ }
+ if header_size < 16 {
+ return None;
+ }
+ let width = i32::from_le_bytes(read(18, 4)?.try_into().ok()?);
+ let height = i32::from_le_bytes(read(22, 4)?.try_into().ok()?);
+ Some((u32::try_from(width).ok()?, height.unsigned_abs()))
+}
+
pub(super) fn fit_static_output_to_budget(
input_len: usize,
sniffed_mime: &str,
@@ -106,7 +142,7 @@ pub fn metadata_cost(input: &[u8], media_limits: &MediaLimits) -> Result<NativeC
match mime::category(sniffed_mime) {
Some(mime::Category::Image) => {
ensure_vips_init()?;
- let dims = probe_image_dims(media_limits, input)?;
+ let dims = cost_image_dims(media_limits, input, sniffed_mime)?;
let source_pixels = dims.width as usize * dims.height as usize;
Ok(NativeCost::Bytes(input.len().saturating_add(
source_pixels * decode_bytes_per_pixel(sniffed_mime),
diff --git a/fluxer_media_proxy/src/media_process/nsfw_processing/mod.rs b/fluxer_media_proxy/src/media_process/nsfw_processing/mod.rs
index 4469955c1..f6882c004 100644
--- a/fluxer_media_proxy/src/media_process/nsfw_processing/mod.rs
+++ b/fluxer_media_proxy/src/media_process/nsfw_processing/mod.rs
@@ -122,13 +122,18 @@ fn extract_animated_image_frames_for_nsfw(
) -> Result<Vec<Vec<u8>>, MediaError> {
let media_type = MediaType::from_mime(source.content_type);
if let Some(media_type @ (MediaType::APNG | MediaType::GIF | MediaType::WebP)) = media_type {
- return extract_native_animated_frames_for_nsfw(
+ match extract_native_animated_frames_for_nsfw(
source.media_limits,
source.input,
source.frame_count,
media_type,
source.deadline_ms,
- );
+ ) {
+ Ok(frames) => return Ok(frames),
+ Err(err) => tracing::warn!(
+ "nsfw native animated frame extract failed: {err:?} - retrying with vips"
+ ),
+ }
}
extract_vips_animation_frames_for_nsfw(source.media_limits, source.input, source.deadline_ms)
}
@@ -321,39 +326,45 @@ pub(super) fn compute_frame_sample_timestamps(
duration_seconds: Option<f64>,
prng: &mut rand_chacha::ChaCha8Rng,
) -> [f64; MAX_NSFW_SAMPLE_FRAMES] {
- const DEFAULT_SAMPLING_WINDOW_SECONDS: f64 = 1.0;
+ const UNKNOWN_DURATION_MIDDLE_POSITION: f64 = 0.5;
+ const UNKNOWN_DURATION_END_POSITION: f64 = 0.85;
use rand::RngExt;
- let valid: Option<f64> = duration_seconds.filter(|d| d.is_finite() && *d > 0.0);
- let sampling_window_seconds = valid.unwrap_or(DEFAULT_SAMPLING_WINDOW_SECONDS);
-
- let clamp = |v: f64| -> f64 {
+ let clamp = |v: f64, max_v: f64| -> f64 {
if !v.is_finite() {
return 0.0;
}
- match valid {
- Some(max_v) => v.clamp(0.0, max_v),
- None => v.max(0.0),
- }
+ v.clamp(0.0, max_v)
+ };
+ let mut jitter = |v: f64, max_v: f64| -> f64 {
+ let radius = (v.abs() * 0.1).max(0.05);
+ let r: f64 = prng.random();
+ clamp(v + (r * 2.0 - 1.0) * radius, max_v)
};
- let start_base = clamp((sampling_window_seconds * 0.1 + 0.5).clamp(1.0, 2.0));
- let middle_base = clamp(sampling_window_seconds / 2.0);
- let end_candidate = if sampling_window_seconds > 2.0 {
- sampling_window_seconds - 1.0
- } else {
- sampling_window_seconds * 0.95
+ let Some(duration) = duration_seconds.filter(|d| d.is_finite() && *d > 0.0) else {
+ return [
+ 0.0,
+ jitter(UNKNOWN_DURATION_MIDDLE_POSITION, 1.0),
+ jitter(UNKNOWN_DURATION_END_POSITION, 1.0),
+ ];
};
- let min_end = start_base + 0.5;
- let end_base = clamp(end_candidate.max(min_end));
- let mut jitter = |v: f64| -> f64 {
- let radius = (v.abs() * 0.1).max(0.05);
- let r: f64 = prng.random();
- clamp(v + (r * 2.0 - 1.0) * radius)
+ let start_base = clamp((duration * 0.1 + 0.5).clamp(1.0, 2.0), duration);
+ let middle_base = clamp(duration / 2.0, duration);
+ let end_candidate = if duration > 2.0 {
+ duration - 1.0
+ } else {
+ duration * 0.95
};
+ let min_end = start_base + 0.5;
+ let end_base = clamp(end_candidate.max(min_end), duration);
- [jitter(start_base), jitter(middle_base), jitter(end_base)]
+ [
+ jitter(start_base, duration),
+ jitter(middle_base, duration),
+ jitter(end_base, duration),
+ ]
}
pub(super) fn nsfw_frame_seed(input: &[u8]) -> u64 {
diff --git a/fluxer_media_proxy/src/media_process/strip/av.rs b/fluxer_media_proxy/src/media_process/strip/av.rs
index 83b089436..687d2ea37 100644
--- a/fluxer_media_proxy/src/media_process/strip/av.rs
+++ b/fluxer_media_proxy/src/media_process/strip/av.rs
@@ -2,11 +2,17 @@
use super::super::native_runtime::ensure_vips_init;
use super::super::{MediaError, native_optional_deadline, native_status_error};
-use crate::native::{self, FluxerAVAudioDurationOut, NativeStatus};
+use super::strip_image_metadata;
+use crate::{
+ media_limits::MediaLimits,
+ native::{self, FluxerAVAudioDurationOut, NativeStatus},
+};
+use libc::{c_int, c_void, size_t};
use std::{
ffi::{CStr, CString},
os::unix::ffi::OsStrExt,
path::Path,
+ slice,
};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
@@ -67,10 +73,57 @@ pub fn av_container(content_type: &str) -> Option<AvContainer> {
})
}
+struct PictureStrip<'a> {
+ media_limits: &'a MediaLimits,
+ deadline_ms: Option<i64>,
+ stripped: Vec<u8>,
+}
+
+unsafe extern "C" fn strip_attached_picture(
+ user_data: *mut c_void,
+ data: *const c_void,
+ len: size_t,
+ out_data: *mut *const c_void,
+ out_len: *mut size_t,
+ out_width: *mut c_int,
+ out_height: *mut c_int,
+) -> c_int {
+ if user_data.is_null()
+ || data.is_null()
+ || out_data.is_null()
+ || out_len.is_null()
+ || out_width.is_null()
+ || out_height.is_null()
+ {
+ return -1;
+ }
+ let context = unsafe { &mut *user_data.cast::<PictureStrip<'_>>() };
+ let input = unsafe { slice::from_raw_parts(data.cast::<u8>(), len) };
+ let Ok(stripped) = strip_image_metadata(input, context.media_limits, context.deadline_ms)
+ else {
+ return -1;
+ };
+ let (Ok(width), Ok(height)) = (
+ c_int::try_from(stripped.width),
+ c_int::try_from(stripped.height),
+ ) else {
+ return -1;
+ };
+ context.stripped = stripped.bytes;
+ unsafe {
+ *out_data = context.stripped.as_ptr().cast();
+ *out_len = context.stripped.len();
+ *out_width = width;
+ *out_height = height;
+ }
+ 0
+}
+
pub fn strip_av_metadata(
input: &[u8],
container: AvContainer,
output: &Path,
+ media_limits: &MediaLimits,
deadline_ms: Option<i64>,
) -> Result<(), MediaError> {
ensure_vips_init()?;
@@ -79,6 +132,11 @@ pub fn strip_av_metadata(
}
let output =
CString::new(output.as_os_str().as_bytes()).map_err(|_| MediaError::MediaEncodeFailed)?;
+ let mut pictures = PictureStrip {
+ media_limits,
+ deadline_ms,
+ stripped: Vec::new(),
+ };
let rc = unsafe {
native::fluxer_av_strip_metadata(
input.as_ptr().cast(),
@@ -88,6 +146,8 @@ pub fn strip_av_metadata(
i32::from(container.faststart),
output.as_ptr(),
native_optional_deadline(deadline_ms),
+ strip_attached_picture,
+ (&raw mut pictures).cast(),
)
};
match native_status_error(NativeStatus::from_code(rc), MediaError::MediaDecodeFailed) {
diff --git a/fluxer_media_proxy/src/media_process/strip/heif.rs b/fluxer_media_proxy/src/media_process/strip/heif.rs
index f07e6566d..b8b0e5c4a 100644
--- a/fluxer_media_proxy/src/media_process/strip/heif.rs
+++ b/fluxer_media_proxy/src/media_process/strip/heif.rs
@@ -5,11 +5,11 @@ use std::{collections::HashSet, ops::Range};
const FREE_BOX_HEADER: usize = 8;
-struct BoxSpan {
- kind: [u8; 4],
- start: usize,
- body: usize,
- end: usize,
+pub(super) struct BoxSpan {
+ pub(super) kind: [u8; 4],
+ pub(super) start: usize,
+ pub(super) body: usize,
+ pub(super) end: usize,
}
fn read_uint(input: &[u8], offset: usize, size: usize) -> Result<u64, MediaError> {
@@ -21,7 +21,7 @@ fn read_uint(input: &[u8], offset: usize, size: usize) -> Result<u64, MediaError
.fold(0u64, |value, &byte| (value << 8) | u64::from(byte)))
}
-fn read_box(input: &[u8], start: usize, limit: usize) -> Result<BoxSpan, MediaError> {
+pub(super) fn read_box(input: &[u8], start: usize, limit: usize) -> Result<BoxSpan, MediaError> {
let size = read_uint(input, start, 4)? as usize;
let kind: [u8; 4] = input
.get(start + 4..start + 8)
@@ -323,41 +323,58 @@ fn rewrite_meta(
}
pub(super) fn strip_items(input: &[u8]) -> Result<Vec<u8>, MediaError> {
- let top = children(input, 0, input.len())?;
- let meta = top
- .iter()
- .find(|span| &span.kind == b"meta")
- .ok_or(MediaError::MediaDecodeFailed)?;
- let mut removal = Removal {
- items: HashSet::new(),
- file_ranges: Vec::new(),
- idat_ranges: Vec::new(),
- };
- let mut rewritten = rewrite_meta(input, meta, &mut removal)?;
- if removal.items.is_empty() {
- return Ok(input.to_vec());
+ let mut found_meta = false;
+ let mut edits: Vec<(Range<usize>, Vec<u8>)> = Vec::new();
+ let mut file_ranges = Vec::new();
+ let mut offset = 0;
+ while offset < input.len() {
+ let meta = read_box(input, offset, input.len())?;
+ offset = meta.end;
+ if &meta.kind != b"meta" {
+ continue;
+ }
+ found_meta = true;
+ let mut removal = Removal {
+ items: HashSet::new(),
+ file_ranges: Vec::new(),
+ idat_ranges: Vec::new(),
+ };
+ let mut rewritten = rewrite_meta(input, &meta, &mut removal)?;
+ if removal.items.is_empty() {
+ continue;
+ }
+ if !removal.idat_ranges.is_empty() {
+ zero_idat(&mut rewritten, &removal.idat_ranges)?;
+ }
+ let original_len = meta.end - meta.start;
+ let padding = original_len
+ .checked_sub(rewritten.len())
+ .filter(|padding| *padding >= FREE_BOX_HEADER)
+ .ok_or(MediaError::UnsupportedMediaType)?;
+ push_box(&mut rewritten, b"free", &vec![0; padding - FREE_BOX_HEADER])?;
+ file_ranges.extend(removal.file_ranges);
+ edits.push((meta.start..meta.end, rewritten));
+ }
+ if !found_meta {
+ return Err(MediaError::MediaDecodeFailed);
}
- if !removal.idat_ranges.is_empty() {
- zero_idat(&mut rewritten, &removal.idat_ranges)?;
+ if edits.is_empty() {
+ return Ok(input.to_vec());
}
- let original_len = meta.end - meta.start;
- let padding = original_len
- .checked_sub(rewritten.len())
- .filter(|padding| *padding >= FREE_BOX_HEADER)
- .ok_or(MediaError::UnsupportedMediaType)?;
- if removal
- .file_ranges
- .iter()
- .any(|range| range.start < meta.end && range.end > meta.start)
- {
+ let overlaps_edit = |range: &Range<usize>| {
+ let index = edits.partition_point(|(span, _)| span.end <= range.start);
+ edits
+ .get(index)
+ .is_some_and(|(span, _)| span.start < range.end)
+ };
+ if file_ranges.iter().any(overlaps_edit) {
return Err(MediaError::UnsupportedMediaType);
}
- let mut output = Vec::with_capacity(input.len());
- output.extend_from_slice(&input[..meta.start]);
- output.extend_from_slice(&rewritten);
- push_box(&mut output, b"free", &vec![0; padding - FREE_BOX_HEADER])?;
- output.extend_from_slice(&input[meta.end..]);
- zero_ranges(&mut output, &removal.file_ranges)?;
+ let mut output = input.to_vec();
+ for (span, rewritten) in &edits {
+ output[span.clone()].copy_from_slice(rewritten);
+ }
+ zero_ranges(&mut output, &file_ranges)?;
Ok(output)
}
@@ -370,3 +387,64 @@ fn zero_idat(meta: &mut [u8], ranges: &[Range<usize>]) -> Result<(), MediaError>
let (body, end) = (idat.body, idat.end);
zero_ranges(&mut meta[body..end], ranges)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn boxed(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
+ let mut output = Vec::new();
+ push_box(&mut output, kind, body).unwrap();
+ output
+ }
+
+ fn infe(id: u16, item_type: &[u8; 4]) -> Vec<u8> {
+ let mut body = vec![2, 0, 0, 0];
+ body.extend_from_slice(&id.to_be_bytes());
+ body.extend_from_slice(&[0, 0]);
+ body.extend_from_slice(item_type);
+ body.push(0);
+ boxed(b"infe", &body)
+ }
+
+ fn meta(items: &[(u16, &[u8; 4], u32, u32)]) -> Vec<u8> {
+ let mut iinf = vec![0, 0, 0, 0];
+ iinf.extend_from_slice(&(items.len() as u16).to_be_bytes());
+ let mut iloc = vec![0, 0, 0, 0, 0x44, 0x00];
+ iloc.extend_from_slice(&(items.len() as u16).to_be_bytes());
+ for &(id, item_type, offset, length) in items {
+ iinf.extend_from_slice(&infe(id, item_type));
+ iloc.extend_from_slice(&id.to_be_bytes());
+ iloc.extend_from_slice(&[0, 0, 0, 1]);
+ iloc.extend_from_slice(&offset.to_be_bytes());
+ iloc.extend_from_slice(&length.to_be_bytes());
+ }
+ let mut body = vec![0, 0, 0, 0];
+ body.extend_from_slice(&boxed(b"iinf", &iinf));
+ body.extend_from_slice(&boxed(b"iloc", &iloc));
+ boxed(b"meta", &body)
+ }
+
+ #[test]
+ fn strips_exif_from_every_meta_box() {
+ let ftyp = boxed(b"ftyp", b"heic\0\0\0\0");
+ let first = meta(&[(1, b"hvc1", 0, 0)]);
+ let header_len = ftyp.len() + first.len();
+ let second_len = meta(&[(1, b"hvc1", 0, 0), (2, b"Exif", 0, 0)]).len();
+ let image_offset = (header_len + second_len + 8) as u32;
+ let first = meta(&[(1, b"hvc1", image_offset, 8)]);
+ let second = meta(&[
+ (1, b"hvc1", image_offset, 8),
+ (2, b"Exif", image_offset + 8, 8),
+ ]);
+ let mdat = boxed(b"mdat", b"IMAGEDATGPS59.33");
+ let input = [ftyp, first, second, mdat].concat();
+
+ let output = strip_items(&input).unwrap();
+
+ assert_eq!(output.len(), input.len());
+ assert!(!output.windows(4).any(|window| window == b"Exif"));
+ assert!(!output.windows(8).any(|window| window == b"GPS59.33"));
+ assert!(output.windows(8).any(|window| window == b"IMAGEDAT"));
+ }
+}
diff --git a/fluxer_media_proxy/src/media_process/strip/jpeg.rs b/fluxer_media_proxy/src/media_process/strip/jpeg.rs
index 0a4184599..823fef65e 100644
--- a/fluxer_media_proxy/src/media_process/strip/jpeg.rs
+++ b/fluxer_media_proxy/src/media_process/strip/jpeg.rs
@@ -22,6 +22,7 @@ const APP14: u8 = 0xEE;
const APP15: u8 = 0xEF;
const COM: u8 = 0xFE;
const DEFAULT_REENCODE_QUALITY: u8 = 95;
+const MAX_HEADER_SEGMENTS: usize = 4096;
struct Segment<'a> {
marker: u8,
@@ -111,6 +112,9 @@ fn parse_layout(input: &[u8]) -> Result<JpegLayout<'_>, MediaError> {
scan_end,
});
}
+ if header.len() >= MAX_HEADER_SEGMENTS {
+ return Err(MediaError::MediaDecodeFailed);
+ }
let segment = read_segment(input, offset)?;
offset += segment.bytes.len();
header.push(segment);
diff --git a/fluxer_media_proxy/src/media_process/strip/jxl.rs b/fluxer_media_proxy/src/media_process/strip/jxl.rs
new file mode 100644
index 000000000..8d65c9b7f
--- /dev/null
+++ b/fluxer_media_proxy/src/media_process/strip/jxl.rs
@@ -0,0 +1,63 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+use super::super::MediaError;
+use super::heif::read_box;
+
+const CODESTREAM_SIGNATURE: &[u8] = b"\xff\x0a";
+
+fn is_metadata(kind: &[u8]) -> bool {
+ matches!(kind, b"Exif" | b"xml " | b"jumb")
+}
+
+pub(super) fn strip_boxes(input: &[u8]) -> Result<Vec<u8>, MediaError> {
+ if input.starts_with(CODESTREAM_SIGNATURE) {
+ return Ok(input.to_vec());
+ }
+ let mut output = Vec::with_capacity(input.len());
+ let mut offset = 0;
+ while offset < input.len() {
+ let span = read_box(input, offset, input.len())?;
+ offset = span.end;
+ let removed = match &span.kind {
+ b"jbrd" => true,
+ b"brob" => input[span.body..span.end].get(..4).is_some_and(is_metadata),
+ kind => is_metadata(kind),
+ };
+ if !removed {
+ output.extend_from_slice(&input[span.start..span.end]);
+ }
+ }
+ Ok(output)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn boxed(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
+ let mut output = ((body.len() + 8) as u32).to_be_bytes().to_vec();
+ output.extend_from_slice(kind);
+ output.extend_from_slice(body);
+ output
+ }
+
+ #[test]
+ fn removes_plain_and_compressed_metadata_boxes() {
+ let signature = boxed(b"JXL ", b"\r\n\x87\n");
+ let ftyp = boxed(b"ftyp", b"jxl \0\0\0\0jxl ");
+ let codestream = boxed(b"jxlc", b"\xff\x0aCODESTREAM");
+ let input = [
+ signature.clone(),
+ ftyp.clone(),
+ boxed(b"Exif", b"\0\0\0\0GPS59.33"),
+ boxed(b"brob", b"xml COMPRESSED"),
+ boxed(b"jbrd", b"RECONSTRUCT"),
+ codestream.clone(),
+ ]
+ .concat();
+
+ let output = strip_boxes(&input).unwrap();
+
+ assert_eq!(output, [signature, ftyp, codestream].concat());
+ }
+}
diff --git a/fluxer_media_proxy/src/media_process/strip/mod.rs b/fluxer_media_proxy/src/media_process/strip/mod.rs
index 8ef9e22d4..c94283e48 100644
--- a/fluxer_media_proxy/src/media_process/strip/mod.rs
+++ b/fluxer_media_proxy/src/media_process/strip/mod.rs
@@ -4,6 +4,7 @@ mod av;
mod gif;
mod heif;
mod jpeg;
+mod jxl;
mod png;
mod webp;
@@ -75,6 +76,7 @@ pub fn strips_image(sniffed_mime: &str) -> bool {
| "image/heic"
| "image/heif"
| "image/tiff"
+ | "image/jxl"
)
}
@@ -102,6 +104,7 @@ pub fn strip_image_metadata(
"image/webp" => webp::strip_chunks(input)?,
"image/gif" => gif::strip_blocks(input)?,
"image/avif" | "image/heic" | "image/heif" => heif::strip_items(input)?,
+ "image/jxl" => jxl::strip_boxes(input)?,
_ => reencode_tiff(input, media_limits, deadline_ms)?,
};
Ok(StrippedImage {
diff --git a/fluxer_media_proxy/src/media_process/strip/png.rs b/fluxer_media_proxy/src/media_process/strip/png.rs
index b79fef3ad..06d090f1d 100644
--- a/fluxer_media_proxy/src/media_process/strip/png.rs
+++ b/fluxer_media_proxy/src/media_process/strip/png.rs
@@ -22,11 +22,7 @@ pub(super) fn strip_chunks(input: &[u8]) -> Result<Vec<u8>, MediaError> {
let kind = &header[4..8];
let end = offset.saturating_add(12).saturating_add(length);
if keeps_chunk(kind) {
- output.extend_from_slice(
- input
- .get(offset..end)
- .ok_or(MediaError::MediaDecodeFailed)?,
- );
+ output.extend_from_slice(&input[offset..end.min(input.len())]);
}
offset = end;
if kind == b"IEND" {
diff --git a/fluxer_media_proxy/src/media_process/transform.rs b/fluxer_media_proxy/src/media_process/transform.rs
index 023cb71c1..b7bd61ff4 100644
--- a/fluxer_media_proxy/src/media_process/transform.rs
+++ b/fluxer_media_proxy/src/media_process/transform.rs
@@ -244,9 +244,9 @@ pub fn transform_image(
}
let heif_source = is_heif_source(sniffed.mime);
let decoded_animation = if sniffed.mime == "image/apng" {
- try_decode_apng(input, animated, media_limits)?
+ try_decode_apng(input, animated, media_limits, options.deadline_ms)?
} else if animated && heif_source_may_be_a_sequence(sniffed) {
- decode_heif_sequence(input, media_limits)?
+ decode_heif_sequence(input, media_limits, options.deadline_ms)?
} else {
None
};
@@ -274,7 +274,8 @@ pub fn transform_image(
&& decoded_animation.is_none()
&& (animated || requires_heif_sdr_decode);
if use_heif_primary_still_path
- && let Some(decoded) = try_decode_heif_primary_still(input, media_limits, metrics)?
+ && let Some(decoded) =
+ try_decode_heif_primary_still(input, media_limits, metrics, options.deadline_ms)?
{
let mut image = decoded.image;
validate_vips_image(media_limits, &image)?;
diff --git a/fluxer_media_proxy/src/media_process/video_thumbnail.rs b/fluxer_media_proxy/src/media_process/video_thumbnail.rs
index 65f8ecafe..d66c24ab4 100644
--- a/fluxer_media_proxy/src/media_process/video_thumbnail.rs
+++ b/fluxer_media_proxy/src/media_process/video_thumbnail.rs
@@ -25,6 +25,7 @@ pub struct VideoThumbnailOptions {
pub fn extract_video_thumbnail(
input: &[u8],
format: OutputFormat,
+ deadline_ms: Option<i64>,
media_limits: &MediaLimits,
) -> Result<ProcessedMedia, MediaError> {
extract_video_thumbnail_with_options(
@@ -34,7 +35,7 @@ pub fn extract_video_thumbnail(
width: None,
height: None,
quality: ResolvedImageQuality::High,
- deadline_ms: None,
+ deadline_ms,
},
media_limits,
)
diff --git a/fluxer_media_proxy/src/mime/iso_bmff.rs b/fluxer_media_proxy/src/mime/iso_bmff.rs
index 62d8593da..6503dd2c7 100644
--- a/fluxer_media_proxy/src/mime/iso_bmff.rs
+++ b/fluxer_media_proxy/src/mime/iso_bmff.rs
@@ -159,10 +159,10 @@ fn ftyp_layout(data: &[u8]) -> Option<FTYPLayout> {
return None;
}
let major_brand_end = header_bytes.checked_add(4)?;
- let scan_end = match declared_box_size {
- Some(declared) if declared <= data.len() => declared,
- _ => data.len().min(ISO_BMFF_BRAND_SCAN_BYTES),
- };
+ let scan_end = declared_box_size
+ .unwrap_or(usize::MAX)
+ .min(data.len())
+ .min(ISO_BMFF_BRAND_SCAN_BYTES);
if major_brand_end > scan_end {
return None;
}
diff --git a/fluxer_media_proxy/src/native/mod.rs b/fluxer_media_proxy/src/native/mod.rs
index 8466325e2..bb896e12c 100644
--- a/fluxer_media_proxy/src/native/mod.rs
+++ b/fluxer_media_proxy/src/native/mod.rs
@@ -123,6 +123,15 @@ impl FluxerNSFWFrameOut {
}
pub type VipsWriteCb = unsafe extern "C" fn(*mut c_void, *const c_void, size_t) -> c_int;
+pub type AvPictureStripCb = unsafe extern "C" fn(
+ *mut c_void,
+ *const c_void,
+ size_t,
+ *mut *const c_void,
+ *mut size_t,
+ *mut c_int,
+ *mut c_int,
+) -> c_int;
unsafe extern "C" {
pub static fluxer_vips_format_uchar: c_int;
@@ -317,6 +326,8 @@ unsafe extern "C" {
faststart: c_int,
output_path: *const c_char,
deadline_monotonic_ms: c_longlong,
+ strip_picture: AvPictureStripCb,
+ user_data: *mut c_void,
) -> c_int;
pub fn fluxer_av_audio_duration(
media_data: *const c_void,
diff --git a/fluxer_media_proxy/src/native_shim/av_input.c b/fluxer_media_proxy/src/native_shim/av_input.c
index fc7e58847..8b696d31a 100644
--- a/fluxer_media_proxy/src/native_shim/av_input.c
+++ b/fluxer_media_proxy/src/native_shim/av_input.c
@@ -218,12 +218,21 @@ int fluxer_find_stream_info_bounded(AVFormatContext *format) {
AVDictionary **options = av_calloc(stream_count, sizeof(*options));
if (options == NULL) return AVERROR(ENOMEM);
+ size_t video_count = 0;
+ for (unsigned int i = 0; i < stream_count; i++) {
+ const AVStream *stream = format->streams[i];
+ if (stream != NULL && stream->codecpar != NULL &&
+ stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
+ stream->discard < AVDISCARD_ALL) {
+ video_count++;
+ }
+ }
+ int64_t max_pixels = (int64_t)(FLUXER_MAX_VIDEO_PIXELS / (video_count > 0 ? video_count : 1));
int rc = 0;
for (unsigned int i = 0; i < stream_count; i++) {
const AVStream *stream = format->streams[i];
if (stream == NULL || stream->codecpar == NULL) continue;
- if (av_dict_set_int(&options[i], "max_pixels",
- (int64_t)FLUXER_MAX_VIDEO_PIXELS, 0) < 0 ||
+ if (av_dict_set_int(&options[i], "max_pixels", max_pixels, 0) < 0 ||
av_dict_set(&options[i], "threads", "1", 0) < 0) {
rc = AVERROR(ENOMEM);
break;
diff --git a/fluxer_media_proxy/src/native_shim/av_strip.c b/fluxer_media_proxy/src/native_shim/av_strip.c
index d8e0a2778..d9c092342 100644
--- a/fluxer_media_proxy/src/native_shim/av_strip.c
+++ b/fluxer_media_proxy/src/native_shim/av_strip.c
@@ -79,12 +79,156 @@ static int fluxer_av_strip_input_open(
return FLUXER_NATIVE_STATUS_OK;
}
+static const uint8_t fluxer_av_vorbis_empty_comment[] = {
+ 0x03, 'v', 'o', 'r', 'b', 'i', 's', 0, 0, 0, 0, 0, 0, 0, 0, 0x01,
+};
+
+static const uint8_t fluxer_av_theora_empty_comment[] = {
+ 0x81, 't', 'h', 'e', 'o', 'r', 'a', 0, 0, 0, 0, 0, 0, 0, 0,
+};
+
+static int fluxer_av_split_xiph_headers(
+ const uint8_t *data,
+ size_t size,
+ size_t first_header_size,
+ const uint8_t **start,
+ size_t *len,
+ int *length_prefixed
+) {
+ if (size >= 2 && (((size_t)data[0] << 8) | data[1]) == first_header_size) {
+ size_t offset = 0;
+ for (int i = 0; i < 3; i++) {
+ if (size - offset < 2) return AVERROR_INVALIDDATA;
+ len[i] = ((size_t)data[offset] << 8) | data[offset + 1];
+ offset += 2;
+ if (size - offset < len[i]) return AVERROR_INVALIDDATA;
+ start[i] = data + offset;
+ offset += len[i];
+ }
+ *length_prefixed = 1;
+ return 0;
+ }
+ if (size < 3 || data[0] != 2) return AVERROR_INVALIDDATA;
+ size_t offset = 1;
+ for (int i = 0; i < 2; i++) {
+ len[i] = 0;
+ while (offset < size && data[offset] == 0xff) {
+ len[i] += 0xff;
+ offset++;
+ }
+ if (offset >= size) return AVERROR_INVALIDDATA;
+ len[i] += data[offset++];
+ }
+ if (size - offset < len[0] || size - offset - len[0] < len[1]) return AVERROR_INVALIDDATA;
+ start[0] = data + offset;
+ start[1] = start[0] + len[0];
+ start[2] = start[1] + len[1];
+ len[2] = size - offset - len[0] - len[1];
+ *length_prefixed = 0;
+ return 0;
+}
+
+static uint8_t *fluxer_av_write_xiph_lace(uint8_t *out, size_t len) {
+ for (; len >= 0xff; len -= 0xff) *out++ = 0xff;
+ *out++ = (uint8_t)len;
+ return out;
+}
+
+static int fluxer_av_strip_xiph_comment(AVCodecParameters *par) {
+ const uint8_t *comment;
+ size_t comment_len;
+ size_t first_header_size;
+ if (par->codec_id == AV_CODEC_ID_VORBIS) {
+ comment = fluxer_av_vorbis_empty_comment;
+ comment_len = sizeof(fluxer_av_vorbis_empty_comment);
+ first_header_size = 30;
+ } else if (par->codec_id == AV_CODEC_ID_THEORA) {
+ comment = fluxer_av_theora_empty_comment;
+ comment_len = sizeof(fluxer_av_theora_empty_comment);
+ first_header_size = 42;
+ } else {
+ return 0;
+ }
+ if (par->extradata == NULL || par->extradata_size <= 0) return 0;
+ const uint8_t *start[3];
+ size_t len[3];
+ int length_prefixed = 0;
+ int rc = fluxer_av_split_xiph_headers(
+ par->extradata, (size_t)par->extradata_size, first_header_size, start, len,
+ &length_prefixed);
+ if (rc < 0) return rc;
+ start[1] = comment;
+ len[1] = comment_len;
+ size_t size = len[0] + len[1] + len[2] +
+ (length_prefixed ? 6 : 1 + len[0] / 0xff + 1 + len[1] / 0xff + 1);
+ if (size > (size_t)INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE) return AVERROR_INVALIDDATA;
+ uint8_t *data = av_mallocz(size + AV_INPUT_BUFFER_PADDING_SIZE);
+ if (data == NULL) return AVERROR(ENOMEM);
+ uint8_t *out = data;
+ if (!length_prefixed) {
+ *out++ = 2;
+ out = fluxer_av_write_xiph_lace(out, len[0]);
+ out = fluxer_av_write_xiph_lace(out, len[1]);
+ }
+ for (int i = 0; i < 3; i++) {
+ if (length_prefixed) {
+ *out++ = (uint8_t)(len[i] >> 8);
+ *out++ = (uint8_t)len[i];
+ }
+ memcpy(out, start[i], len[i]);
+ out += len[i];
+ }
+ av_free(par->extradata);
+ par->extradata = data;
+ par->extradata_size = (int)size;
+ return 0;
+}
+
+static int fluxer_av_strip_picture(
+ const AVStream *source,
+ fluxer_av_picture_strip_cb strip_picture,
+ void *user_data,
+ AVPacket **out,
+ int *width,
+ int *height
+) {
+ const AVPacket *picture = &source->attached_pic;
+ const void *data = NULL;
+ size_t len = 0;
+ if (strip_picture == NULL || picture->data == NULL || picture->size <= 0 ||
+ strip_picture(user_data, picture->data, (size_t)picture->size, &data, &len,
+ width, height) != 0 ||
+ data == NULL || len == 0 || len > (size_t)INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE) {
+ return 0;
+ }
+ AVPacket *packet = av_packet_alloc();
+ if (packet == NULL || av_new_packet(packet, (int)len) < 0) {
+ av_packet_free(&packet);
+ return AVERROR(ENOMEM);
+ }
+ memcpy(packet->data, data, len);
+ *out = packet;
+ return 0;
+}
+
+static int fluxer_av_strip_use_picture(AVPacket *packet, const AVPacket *picture) {
+ AVBufferRef *buffer = av_buffer_ref(picture->buf);
+ if (buffer == NULL) return AVERROR(ENOMEM);
+ av_buffer_unref(&packet->buf);
+ packet->buf = buffer;
+ packet->data = picture->data;
+ packet->size = picture->size;
+ return 0;
+}
+
static int fluxer_av_strip_copy_stream(AVFormatContext *output, const AVStream *source) {
AVStream *stream = avformat_new_stream(output, NULL);
if (stream == NULL) return AVERROR(ENOMEM);
int rc = avcodec_parameters_copy(stream->codecpar, source->codecpar);
if (rc < 0) return rc;
AVCodecParameters *par = stream->codecpar;
+ rc = fluxer_av_strip_xiph_comment(par);
+ if (rc < 0) return rc;
const struct AVCodecTag *const *tags = output->oformat->codec_tag;
unsigned int tag = 0;
if (tags != NULL && av_codec_get_id(tags, par->codec_tag) != par->codec_id &&
@@ -111,7 +255,14 @@ static int fluxer_av_strip_copy_stream(AVFormatContext *output, const AVStream *
return 0;
}
-static int fluxer_av_strip_map_streams(AVFormatContext *input, AVFormatContext *output, int *map) {
+static int fluxer_av_strip_map_streams(
+ AVFormatContext *input,
+ AVFormatContext *output,
+ int *map,
+ AVPacket **pictures,
+ fluxer_av_picture_strip_cb strip_picture,
+ void *user_data
+) {
static const enum AVMediaType order[] = {
AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_SUBTITLE,
};
@@ -123,9 +274,21 @@ static int fluxer_av_strip_map_streams(AVFormatContext *input, AVFormatContext *
stream->codecpar->codec_type != order[t]) {
continue;
}
+ int width = 0;
+ int height = 0;
+ if (stream->disposition & AV_DISPOSITION_ATTACHED_PIC) {
+ int rc = fluxer_av_strip_picture(
+ stream, strip_picture, user_data, &pictures[i], &width, &height);
+ if (rc < 0) return rc;
+ if (pictures[i] == NULL) continue;
+ }
int rc = fluxer_av_strip_copy_stream(output, stream);
if (rc < 0) return rc;
map[i] = (int)output->nb_streams - 1;
+ if (width > 0 && height > 0) {
+ output->streams[map[i]]->codecpar->width = width;
+ output->streams[map[i]]->codecpar->height = height;
+ }
}
}
return output->nb_streams > 0 ? 0 : AVERROR_STREAM_NOT_FOUND;
@@ -209,16 +372,23 @@ static void fluxer_av_strip_retime(
static int fluxer_av_strip_remux(
fluxer_av_strip_input *input,
AVFormatContext *output,
- int faststart
+ int faststart,
+ fluxer_av_picture_strip_cb strip_picture,
+ void *user_data
) {
AVFormatContext *source = input->format;
unsigned int mapped_streams = source->nb_streams;
int *map = av_calloc(mapped_streams, sizeof(*map));
+ AVPacket **pictures = av_calloc(mapped_streams, sizeof(*pictures));
fluxer_av_strip_track *tracks = av_calloc(mapped_streams, sizeof(*tracks));
AVPacket *packet = av_packet_alloc();
AVDictionary *options = NULL;
- int rc = map == NULL || tracks == NULL || packet == NULL ? AVERROR(ENOMEM) : 0;
- if (rc == 0) rc = fluxer_av_strip_map_streams(source, output, map);
+ int rc = map == NULL || pictures == NULL || tracks == NULL || packet == NULL
+ ? AVERROR(ENOMEM)
+ : 0;
+ if (rc == 0) {
+ rc = fluxer_av_strip_map_streams(source, output, map, pictures, strip_picture, user_data);
+ }
if (rc == 0 && faststart) rc = av_dict_set(&options, "movflags", "+faststart", 0);
if (rc == 0) rc = avio_open2(&output->pb, output->url, AVIO_FLAG_WRITE,
&output->interrupt_callback, NULL);
@@ -246,6 +416,13 @@ static int fluxer_av_strip_remux(
av_packet_unref(packet);
continue;
}
+ if (pictures[index] != NULL) {
+ rc = fluxer_av_strip_use_picture(packet, pictures[index]);
+ if (rc < 0) {
+ av_packet_unref(packet);
+ break;
+ }
+ }
track->started = 1;
const AVStream *destination = output->streams[map[index]];
fluxer_av_strip_retime(packet, source->streams[index], destination,
@@ -266,6 +443,10 @@ static int fluxer_av_strip_remux(
av_dict_free(&options);
av_packet_free(&packet);
av_free(tracks);
+ for (unsigned int i = 0; pictures != NULL && i < mapped_streams; i++) {
+ av_packet_free(&pictures[i]);
+ }
+ av_free(pictures);
av_free(map);
return rc;
}
@@ -277,7 +458,9 @@ int fluxer_av_strip_metadata(
const char *muxer,
int faststart,
const char *output_path,
- long long deadline_monotonic_ms
+ long long deadline_monotonic_ms,
+ fluxer_av_picture_strip_cb strip_picture,
+ void *user_data
) {
if (demuxer == NULL || muxer == NULL || output_path == NULL ||
(faststart != 0 && faststart != 1)) {
@@ -298,7 +481,7 @@ int fluxer_av_strip_metadata(
output->protocol_whitelist = av_strdup("file");
rc = output->protocol_whitelist == NULL
? AVERROR(ENOMEM)
- : fluxer_av_strip_remux(&input, output, faststart);
+ : fluxer_av_strip_remux(&input, output, faststart, strip_picture, user_data);
} else if (rc >= 0) {
rc = AVERROR(ENOMEM);
}
diff --git a/fluxer_media_proxy/src/native_shim/nsfw_frame.c b/fluxer_media_proxy/src/native_shim/nsfw_frame.c
index ea90992aa..998afd9ab 100644
--- a/fluxer_media_proxy/src/native_shim/nsfw_frame.c
+++ b/fluxer_media_proxy/src/native_shim/nsfw_frame.c
@@ -379,6 +379,61 @@ static int fluxer_nsfw_uses_byte_seek(const AVFormatContext *format) {
strcmp(name, "mpegvideo") == 0;
}
+static int fluxer_nsfw_positions_are_fractions(const AVFormatContext *format) {
+ return format != NULL && format->duration <= 0;
+}
+
+static int fluxer_nsfw_allows_byte_seek(const AVFormatContext *format) {
+ if (format == NULL || format->iformat == NULL) return 0;
+ return (format->iformat->flags & AVFMT_NO_BYTE_SEEK) == 0;
+}
+
+static int fluxer_nsfw_stream_end_seconds(AVStream *stream, double *out_seconds) {
+ assert(stream != NULL);
+ assert(out_seconds != NULL);
+ if (stream->time_base.num <= 0 || stream->time_base.den <= 0) return 0;
+ int64_t end = 0;
+ if (stream->duration > 0 && stream->duration != AV_NOPTS_VALUE) {
+ end = stream->duration;
+ } else {
+ int entries = avformat_index_get_entries_count(stream);
+ if (entries <= 0) return 0;
+ const AVIndexEntry *last = avformat_index_get_entry(stream, entries - 1);
+ if (last == NULL || last->timestamp == AV_NOPTS_VALUE) return 0;
+ int64_t start = stream->start_time == AV_NOPTS_VALUE ? 0 : stream->start_time;
+ if (start > 0 && last->timestamp < INT64_MIN + start) return 0;
+ if (start < 0 && last->timestamp > INT64_MAX + start) return 0;
+ end = last->timestamp - start;
+ }
+ if (end <= 0) return 0;
+ double seconds = (double)end * av_q2d(stream->time_base);
+ if (!isfinite(seconds) || seconds <= 0.0) return 0;
+ *out_seconds = seconds;
+ return 1;
+}
+
+static int fluxer_nsfw_seek_file_fraction(
+ AVFormatContext *format,
+ double fraction,
+ size_t media_len,
+ long long deadline_monotonic_ms
+) {
+ int deadline_status = fluxer_native_deadline_status(
+ deadline_monotonic_ms);
+ if (deadline_status != FLUXER_NATIVE_STATUS_OK) return deadline_status;
+ double ratio = fmax(0.0, fmin(1.0, fraction));
+ long double projected_offset =
+ floorl((long double)media_len * (long double)ratio);
+ size_t offset = media_len > 0 ? media_len - 1 : 0;
+ if (projected_offset < (long double)offset) {
+ offset = (size_t)projected_offset;
+ }
+ int rc = av_seek_frame(format, -1, (int64_t)offset, AVSEEK_FLAG_BYTE);
+ if (rc >= 0) return fluxer_native_deadline_status(deadline_monotonic_ms);
+ return fluxer_native_status_from_av_error_with_deadline(
+ rc, deadline_monotonic_ms);
+}
+
static int fluxer_nsfw_seek(
AVFormatContext *format,
int stream_index,
@@ -435,6 +490,7 @@ struct fluxer_nsfw_target {
int64_t keyframe_position;
int64_t keyframe_pts;
int has_indexed_keyframe;
+ int file_fraction;
};
static int fluxer_nsfw_target_pts(
@@ -472,7 +528,12 @@ static int fluxer_nsfw_targets_init(
assert(timestamps != NULL);
assert(targets != NULL);
assert(count <= FLUXER_MAX_NSFW_SAMPLES);
- int indexed_seek = !fluxer_nsfw_uses_byte_seek(format);
+ int fractions = fluxer_nsfw_positions_are_fractions(format);
+ int file_fraction = fractions && fluxer_nsfw_allows_byte_seek(format);
+ double end_seconds = 0.0;
+ int scale_to_end = fractions && !file_fraction &&
+ fluxer_nsfw_stream_end_seconds(stream, &end_seconds);
+ int indexed_seek = !file_fraction && !fluxer_nsfw_uses_byte_seek(format);
for (size_t i = 0; i < count; i++) {
int deadline_status = fluxer_native_deadline_status(
deadline_monotonic_ms);
@@ -482,13 +543,19 @@ static int fluxer_nsfw_targets_init(
double seconds = timestamps[i];
assert(isfinite(seconds));
assert(seconds >= 0.0);
+ if (scale_to_end) seconds = fmin(1.0, seconds) * end_seconds;
targets[i].seconds = seconds;
- if (fluxer_nsfw_target_pts(stream, seconds, &targets[i].pts) != 0) {
- return FLUXER_NATIVE_STATUS_CODEC_FAILURE;
- }
targets[i].keyframe_position = -1;
targets[i].keyframe_pts = AV_NOPTS_VALUE;
targets[i].has_indexed_keyframe = 0;
+ targets[i].file_fraction = file_fraction;
+ if (file_fraction) {
+ targets[i].pts = INT64_MIN;
+ continue;
+ }
+ if (fluxer_nsfw_target_pts(stream, seconds, &targets[i].pts) != 0) {
+ return FLUXER_NATIVE_STATUS_CODEC_FAILURE;
+ }
if (!indexed_seek) continue;
const AVIndexEntry *entry = avformat_index_get_entry_from_timestamp(
stream, targets[i].pts, AVSEEK_FLAG_BACKWARD);
@@ -865,13 +932,19 @@ static int fluxer_nsfw_decode_targets(
.limit = limit,
.max_frame_output_size = max_frame_output_size,
};
- int status = fluxer_nsfw_seek(
- context->format,
- context->stream_index,
- targets[next].pts,
- targets[next].seconds,
- media_len,
- deadline_monotonic_ms);
+ int status = targets[next].file_fraction
+ ? fluxer_nsfw_seek_file_fraction(
+ context->format,
+ targets[next].seconds,
+ media_len,
+ deadline_monotonic_ms)
+ : fluxer_nsfw_seek(
+ context->format,
+ context->stream_index,
+ targets[next].pts,
+ targets[next].seconds,
+ media_len,
+ deadline_monotonic_ms);
if (status == FLUXER_NATIVE_STATUS_OK) {
avcodec_flush_buffers(context->decoder);
status = fluxer_native_deadline_status(deadline_monotonic_ms);
diff --git a/fluxer_media_proxy/src/request_log/mod.rs b/fluxer_media_proxy/src/request_log/mod.rs
index ec5b33540..bcf527e4c 100644
--- a/fluxer_media_proxy/src/request_log/mod.rs
+++ b/fluxer_media_proxy/src/request_log/mod.rs
@@ -20,7 +20,10 @@ use axum::{
middleware::Next,
response::Response,
};
-use fluxer_common::attachment_url_signature::is_signature_parameter_name;
+use fluxer_common::{
+ attachment_url_signature::is_signature_parameter_name,
+ external_media_path::{percent_decode, reconstruct_original_url},
+};
use rand::RngExt;
use stage::{StageTimingSnapshot, StageTimings};
use std::{future::Future, sync::Arc, time::Instant};
@@ -31,6 +34,8 @@ const ID_LEN: usize = 12;
const TARGET_LOG_BYTES_MAX: usize = 512;
pub(crate) const HEADER_LOG_BYTES_MAX: usize = 256;
const REDACTED_VALUE: &str = "[redacted]";
+const EXTERNAL_PATH_PREFIX: &str = "/external/";
+const RELAY_TOKEN_PARAMETER: &[u8] = b"t";
#[derive(Clone, Debug)]
pub struct RequestId(pub String);
@@ -71,7 +76,7 @@ impl RequestObservation {
) -> Self {
Self {
kind: classify_route(path),
- path: clip(path, TARGET_LOG_BYTES_MAX),
+ path: clip(&path_for_log(path), TARGET_LOG_BYTES_MAX),
query: query
.map(|query| clip(&redact_signature_values(query), TARGET_LOG_BYTES_MAX))
.unwrap_or_default(),
@@ -100,7 +105,7 @@ pub fn classify_route(path: &str) -> RequestKind {
if path.starts_with("/v1/relay/") {
return RequestKind::Upload;
}
- if path.starts_with("/external/") {
+ if path.starts_with(EXTERNAL_PATH_PREFIX) {
return RequestKind::External;
}
if path.starts_with("/attachments/") {
@@ -263,6 +268,22 @@ fn log_reason(reason: Option<ErrorReason>, status: StatusCode) -> (&'static str,
}
}
+fn path_for_log(path: &str) -> String {
+ let Some(rest) = path.strip_prefix(EXTERNAL_PATH_PREFIX) else {
+ return path.to_owned();
+ };
+ let target = rest
+ .split_once('/')
+ .and_then(|(_, proxy_path)| reconstruct_original_url(proxy_path).ok())
+ .map(|url| external_url_for_log(&url))
+ .unwrap_or_else(|| REDACTED_VALUE.to_owned());
+ format!("{EXTERNAL_PATH_PREFIX}{target}")
+}
+
+fn is_logged_secret_name(name: &str) -> bool {
+ is_signature_parameter_name(name) || percent_decode(name, true) == RELAY_TOKEN_PARAMETER
+}
+
fn redact_signature_values(query: &str) -> String {
if !query.contains('=') {
return query.to_owned();
@@ -273,7 +294,7 @@ fn redact_signature_values(query: &str) -> String {
out.push('&');
}
match field.split_once('=') {
- Some((name, _)) if is_signature_parameter_name(name) => {
+ Some((name, _)) if is_logged_secret_name(name) => {
out.push_str(name);
out.push('=');
out.push_str(REDACTED_VALUE);
@@ -327,6 +348,8 @@ mod tests {
format!("ex=0&is=6a9920b1&hm={signature}&uc=dp"),
format!("ex=0&is=6a9920b1&hm={signature}&uc=dp&"),
format!("width=64&%75c=dp&hm={signature}&ex=6a9a7231&is=6a9920b1"),
+ format!("t={signature}&uploadId=2~upload"),
+ format!("partNumber=1&%74={signature}"),
] {
let observation = RequestObservation::new(
RequestId::generate(),
@@ -346,6 +369,26 @@ mod tests {
}
}
+ #[test]
+ fn an_external_target_query_never_reaches_the_log() {
+ for path in [
+ "/external/c2lnbmF0dXJl/%3Ftoken%3Dhunter2/https/cdn.example.com/rooms/hunter2.png",
+ "/external/c2lnbmF0dXJl/v2/aHR0cHM6Ly9jZG4uZXhhbXBsZS5jb20vYS5wbmc_dG9rZW49aHVudGVyMg",
+ "/external/c2lnbmF0dXJl/%3Ftoken%3Dhunter2",
+ ] {
+ let observation = RequestObservation::new(
+ RequestId::generate(),
+ Method::GET,
+ path,
+ None,
+ &HeaderMap::new(),
+ );
+ assert!(!observation.path.contains("hunter2"), "{path}");
+ assert!(!observation.path.contains("c2lnbmF0dXJl"), "{path}");
+ assert!(observation.path.starts_with("/external/"), "{path}");
+ }
+ }
+
#[test]
fn credentialed_referer_is_redacted_before_it_reaches_the_log() {
let mut headers = HeaderMap::new();
diff --git a/fluxer_media_proxy/src/server/external/fetch.rs b/fluxer_media_proxy/src/server/external/fetch.rs
index 01c0bed62..872a3a734 100644
--- a/fluxer_media_proxy/src/server/external/fetch.rs
+++ b/fluxer_media_proxy/src/server/external/fetch.rs
@@ -70,12 +70,12 @@ async fn send_external_request(
.map_err(|_| ExternalFetchError::BufferAllocationFailed)?;
for _ in 0..=EXTERNAL_FETCH_REDIRECT_LIMIT {
if visited.iter().any(|seen| seen == &current_url) {
- warn!(url = %current_url, "redirect loop detected");
+ warn!(url = %public_net_policy::external_url_for_log(&current_url), "redirect loop detected");
return Err(ExternalFetchError::TooManyRedirects);
}
visited.push(current_url.clone());
if let Err(err) = public_net_policy::validate_url(&current_url) {
- warn!(?err, url = %current_url, "blocked external fetch");
+ warn!(?err, url = %public_net_policy::external_url_for_log(&current_url), "blocked external fetch");
external_metrics.blocked_url_attempts.inc();
return Err(ExternalFetchError::BlockedUrl);
}
@@ -87,12 +87,13 @@ async fn send_external_request(
outbound = outbound.header(header::RANGE, range.header_value());
}
let response = outbound.send().await.map_err(|err| {
+ let err = err.without_url();
if public_net_policy::is_pinned_dns_failure(&err) {
- warn!(?err, url = %current_url, "blocked external fetch");
+ warn!(?err, url = %public_net_policy::external_url_for_log(&current_url), "blocked external fetch");
external_metrics.blocked_url_attempts.inc();
return ExternalFetchError::BlockedUrl;
}
- warn!(url = %current_url, %err, "external send failed");
+ warn!(url = %public_net_policy::external_url_for_log(&current_url), %err, "external send failed");
external_metrics.fetch_failures.inc();
ExternalFetchError::FetchFailed
})?;
@@ -104,14 +105,14 @@ async fn send_external_request(
) {
Some(location) if !location.is_empty() => location,
Some(_) | None => {
- warn!(url = %current_url, status = status.as_u16(), "redirect has an invalid Location");
+ warn!(url = %public_net_policy::external_url_for_log(&current_url), status = status.as_u16(), "redirect has an invalid Location");
external_metrics.fetch_failures.inc();
return Err(ExternalFetchError::FetchFailed);
}
};
current_url =
public_net_policy::resolve_redirect(&current_url, location).map_err(|err| {
- warn!(url = %current_url, %location, ?err, "redirect target blocked");
+ warn!(url = %public_net_policy::external_url_for_log(&current_url), location = %public_net_policy::external_url_for_log(location), ?err, "redirect target blocked");
external_metrics.blocked_url_attempts.inc();
ExternalFetchError::BlockedUrl
})?;
@@ -170,7 +171,7 @@ async fn fetch_external_inner(
if let Some(len) = declared_length
&& len > constants::MAX_MEDIA_PROXY_BYTES as u64
{
- warn!(url = %current_url, len, "external payload too large");
+ warn!(url = %public_net_policy::external_url_for_log(&current_url), len, "external payload too large");
return Err(ExternalFetchError::PayloadTooLarge);
}
let status = if response.status() == StatusCode::PARTIAL_CONTENT {
@@ -182,7 +183,7 @@ async fn fetch_external_inner(
declared_length,
constants::MAX_MEDIA_PROXY_BYTES,
) else {
- warn!(url = %current_url, "invalid upstream partial response");
+ warn!(url = %public_net_policy::external_url_for_log(&current_url), "invalid upstream partial response");
external_metrics.fetch_failures.inc();
return Err(ExternalFetchError::FetchFailed);
};
@@ -225,7 +226,7 @@ async fn fetch_external_inner(
.and_then(|partial| partial.content_length())
.is_some_and(|expected| data.len() as u64 != expected)
{
- warn!(url = %current_url, "upstream partial response body length mismatch");
+ warn!(url = %public_net_policy::external_url_for_log(&current_url), "upstream partial response body length mismatch");
external_metrics.fetch_failures.inc();
return Err(ExternalFetchError::FetchFailed);
}
@@ -257,7 +258,8 @@ async fn external_body_prefix(
response_body_limit::response_body_chunk_limit(constants::MAX_MEDIA_PROXY_BYTES as u64);
while prefix.len() < EXTERNAL_SNIFF_PREFIX_BYTES {
let Some(chunk) = response.chunk().await.map_err(|err| {
- warn!(url = %url, %err, "external body read failed");
+ let err = err.without_url();
+ warn!(url = %public_net_policy::external_url_for_log(url), %err, "external body read failed");
metrics.fetch_failures.inc();
ExternalFetchError::FetchFailed
})?
@@ -266,7 +268,7 @@ async fn external_body_prefix(
};
if chunk.is_empty() {
empty_chunks_remaining = empty_chunks_remaining.checked_sub(1).ok_or_else(|| {
- warn!(url = %url, "external sniff prefix exceeded its empty chunk limit");
+ warn!(url = %public_net_policy::external_url_for_log(url), "external sniff prefix exceeded its empty chunk limit");
ExternalFetchError::PayloadTooLarge
})?;
continue;
@@ -344,7 +346,7 @@ pub(super) async fn buffer_external_response(
} = request;
let declared_length = match content_length {
Some(length) if length > limit as u64 => {
- warn!(url = %url, length, "external payload too large");
+ warn!(url = %public_net_policy::external_url_for_log(url), length, "external payload too large");
return Err(ExternalFetchError::PayloadTooLarge);
}
Some(length) => {
@@ -367,13 +369,14 @@ pub(super) async fn buffer_external_response(
buf.extend_from_slice(&prefix);
let mut empty_chunks_remaining = response_body_limit::response_body_chunk_limit(limit as u64);
while let Some(chunk) = response.chunk().await.map_err(|err| {
- warn!(url = %url, %err, "external body read failed");
+ let err = err.without_url();
+ warn!(url = %public_net_policy::external_url_for_log(url), %err, "external body read failed");
metrics.fetch_failures.inc();
ExternalFetchError::FetchFailed
})? {
if chunk.is_empty() {
empty_chunks_remaining = empty_chunks_remaining.checked_sub(1).ok_or_else(|| {
- warn!(url = %url, "external payload exceeded its empty chunk limit");
+ warn!(url = %public_net_policy::external_url_for_log(url), "external payload exceeded its empty chunk limit");
ExternalFetchError::PayloadTooLarge
})?;
continue;
@@ -383,7 +386,7 @@ pub(super) async fn buffer_external_response(
.checked_add(chunk.len())
.filter(|len| *len <= limit)
else {
- warn!(url = %url, "external payload too large");
+ warn!(url = %public_net_policy::external_url_for_log(url), "external payload too large");
return Err(ExternalFetchError::PayloadTooLarge);
};
if next_len > buf.capacity() {
@@ -412,7 +415,7 @@ pub(super) async fn buffer_external_response(
&& buf.len() != expected_length
{
warn!(
- url = %url,
+ url = %public_net_policy::external_url_for_log(url),
expected_length,
actual_length = buf.len(),
"external buffered body length did not match Content-Length"
diff --git a/fluxer_media_proxy/src/server/external/mod.rs b/fluxer_media_proxy/src/server/external/mod.rs
index 339d5849c..96ec06713 100644
--- a/fluxer_media_proxy/src/server/external/mod.rs
+++ b/fluxer_media_proxy/src/server/external/mod.rs
@@ -9,6 +9,7 @@ use crate::{
config::Config,
constants::{self, AssetExtension},
mime,
+ public_net_policy::external_url_for_log,
server::{
download_stream::DownloadStreamPolicy,
external::{
@@ -30,6 +31,7 @@ use crate::{
response::{
content_disposition_header,
error::{text, text_with_source},
+ retained_response_bytes,
},
state::AppState,
stored::response::passthrough_head_response,
@@ -412,7 +414,7 @@ async fn serve_fetched_external(
app.media.transforms(),
ServeBytesRequest {
method,
- data: data.as_bytes().clone(),
+ data: retained_response_bytes(data),
content_type,
cache_identity: &fetched_url,
filename: &filename,
@@ -441,6 +443,7 @@ pub(in crate::server) async fn fetch_external(
}
fn external_fetch_error_response(url: &str, err: ExternalFetchError) -> Response {
+ let url = external_url_for_log(url);
match err {
ExternalFetchError::BlockedUrl => text_with_source(
StatusCode::BAD_REQUEST,
diff --git a/fluxer_media_proxy/src/server/media_operations/input.rs b/fluxer_media_proxy/src/server/media_operations/input.rs
index 05dfaa280..0908d1003 100644
--- a/fluxer_media_proxy/src/server/media_operations/input.rs
+++ b/fluxer_media_proxy/src/server/media_operations/input.rs
@@ -5,6 +5,7 @@ use crate::{
byte_budget::BudgetedBytes,
constants::{self, AssetExtension},
mime,
+ public_net_policy::external_url_for_log,
server::{
external::fetch_external,
params::url_filename,
@@ -162,7 +163,7 @@ async fn load_external_url(
) -> Result<LoadedMediaInput, MediaFailure> {
let (fetched_url, data) = fetch_external(app, url).await.map_err(|err| {
let failure = MediaFailure::from(err);
- warn!(reason = failure.code(), url, ?err);
+ warn!(reason = failure.code(), url = %external_url_for_log(url), ?err);
failure
})?;
Ok(LoadedMediaInput {
diff --git a/fluxer_media_proxy/src/server/media_operations/mod.rs b/fluxer_media_proxy/src/server/media_operations/mod.rs
index 6a6ab7b4a..f434c9eae 100644
--- a/fluxer_media_proxy/src/server/media_operations/mod.rs
+++ b/fluxer_media_proxy/src/server/media_operations/mod.rs
@@ -32,6 +32,7 @@ use axum::{
http::{HeaderMap, Method, StatusCode},
};
use bytes::Bytes;
+use http_body::Body as _;
use input::LoadedMediaInput;
use std::{sync::Arc, time::Duration};
@@ -66,6 +67,7 @@ pub(in crate::server) async fn resolve_metadata(
NSFWPolicy::Disabled
};
let mut metadata = extract_metadata(app, &input, true, nsfw).await?;
+ let data = include_data.then_some(input.data);
let is_image = metadata["content_type"]
.as_str()
.is_some_and(|content_type| content_type.starts_with("image/"));
@@ -76,10 +78,7 @@ pub(in crate::server) async fn resolve_metadata(
metadata[field] = served[field].take();
}
}
- Ok(MetadataOutput {
- metadata,
- data: include_data.then_some(input.data),
- })
+ Ok(MetadataOutput { metadata, data })
}
async fn served_variant_metadata(
@@ -103,7 +102,15 @@ async fn served_variant_metadata(
if response.status() != StatusCode::OK {
return None;
}
- let data = to_bytes(response.into_body(), constants::MAX_MEDIA_PROXY_BYTES)
+ let body = response.into_body();
+ let reserved = body
+ .size_hint()
+ .upper()
+ .and_then(|upper| usize::try_from(upper).ok())
+ .unwrap_or(constants::MAX_MEDIA_PROXY_BYTES)
+ .min(constants::MAX_MEDIA_PROXY_BYTES);
+ let _reservation = app.media.external_buffer_bytes().try_reserve(reserved)?;
+ let data = to_bytes(body, constants::MAX_MEDIA_PROXY_BYTES)
.await
.ok()?;
let input = LoadedMediaInput {
diff --git a/fluxer_media_proxy/src/server/media_operations/strip.rs b/fluxer_media_proxy/src/server/media_operations/strip.rs
index 34c972b83..712a69696 100644
--- a/fluxer_media_proxy/src/server/media_operations/strip.rs
+++ b/fluxer_media_proxy/src/server/media_operations/strip.rs
@@ -5,7 +5,7 @@ use crate::{
media_process::{self, MediaError},
metrics, mime,
server::{state::AppState, transform::execution::deadline_instant},
- upload_relay::{release_spool_budget, try_reserve_spool_budget},
+ upload_relay::SpoolReservation,
};
use bytes::Bytes;
use memmap2::Mmap;
@@ -19,20 +19,6 @@ pub(in crate::server) struct StrippedMedia {
pub(in crate::server) dimensions: Option<(u32, u32)>,
}
-struct SpoolReservation(u64);
-
-impl SpoolReservation {
- fn try_new(bytes: u64, ceiling: u64) -> Option<Self> {
- try_reserve_spool_budget(bytes, ceiling).then_some(Self(bytes))
- }
-}
-
-impl Drop for SpoolReservation {
- fn drop(&mut self) {
- release_spool_budget(self.0);
- }
-}
-
struct StrippedFile {
map: Mmap,
_reservation: SpoolReservation,
@@ -119,30 +105,43 @@ async fn strip_av(
) -> Result<StrippedMedia, MediaFailure> {
let container =
media_process::av_container(&content_type).ok_or(MediaFailure::StripUnsupportedType)?;
- let relay = &app.cfg.upload_relay;
- let reservation = SpoolReservation::try_new(data.len() as u64, relay.spool_max_total_bytes)
- .ok_or(MediaFailure::StripSpoolExhausted)?;
- let output = tempfile::NamedTempFile::new_in(&relay.spool_dir).map_err(|error| {
- MediaFailure::StripFailed {
- detail: format!("spool file: {error}"),
- }
- })?;
- let path = output.path().to_owned();
+ let spool_dir = app.cfg.upload_relay.spool_dir.clone();
+ let spool_max_total_bytes = app.cfg.upload_relay.spool_max_total_bytes;
+ let runtime = app.media.transforms();
+ let media_limits = runtime.limits();
let deadline_ms = metrics::now_ms() + AV_STRIP_TIMEOUT_MS;
let cost = media_process::av_native_cost(data.len());
- app.media
- .transforms()
+ let (reservation, output) = runtime
.tasks()
.run_native(
deadline_instant(Some(deadline_ms)),
move || Ok(cost),
move || {
- media_process::strip_av_metadata(&data, container, &path, Some(deadline_ms))?;
- Ok(())
+ let Some(reservation) =
+ SpoolReservation::try_new(data.len() as u64, spool_max_total_bytes)
+ else {
+ return Ok(Err(MediaFailure::StripSpoolExhausted));
+ };
+ let output = match tempfile::NamedTempFile::new_in(&spool_dir) {
+ Ok(output) => output,
+ Err(error) => {
+ return Ok(Err(MediaFailure::StripFailed {
+ detail: format!("spool file: {error}"),
+ }));
+ }
+ };
+ media_process::strip_av_metadata(
+ &data,
+ container,
+ output.path(),
+ &media_limits,
+ Some(deadline_ms),
+ )?;
+ Ok(Ok((reservation, output)))
},
)
.await
- .map_err(|error| strip_failure(&error))?;
+ .map_err(|error| strip_failure(&error))??;
let map =
unsafe { Mmap::map(output.as_file()) }.map_err(|error| MediaFailure::StripFailed {
detail: format!("map stripped output: {error}"),
diff --git a/fluxer_media_proxy/src/server/response/error.rs b/fluxer_media_proxy/src/server/response/error.rs
index 2be83a6ee..2073d3e72 100644
--- a/fluxer_media_proxy/src/server/response/error.rs
+++ b/fluxer_media_proxy/src/server/response/error.rs
@@ -13,6 +13,9 @@ pub(in crate::server) fn storage_status(err: &StorageError) -> StatusCode {
StorageError::ReadOnlyStorage => StatusCode::FORBIDDEN,
StorageError::InvalidBucket | StorageError::InvalidKey => StatusCode::BAD_REQUEST,
StorageError::StreamTooLong => StatusCode::PAYLOAD_TOO_LARGE,
+ StorageError::BufferBudgetExhausted | StorageError::BufferAllocationFailed => {
+ StatusCode::SERVICE_UNAVAILABLE
+ }
_ => StatusCode::BAD_GATEWAY,
}
}
diff --git a/fluxer_media_proxy/src/server/routes/relay.rs b/fluxer_media_proxy/src/server/routes/relay.rs
index 7a1d8708c..6eedb0509 100644
--- a/fluxer_media_proxy/src/server/routes/relay.rs
+++ b/fluxer_media_proxy/src/server/routes/relay.rs
@@ -90,7 +90,7 @@ pub(in crate::server) async fn relay_put(
return relay_error(err);
}
let timeout_ms = relay_upstream_timeout_ms(&app, content_length);
- let (body, body_length, streamed, _buffer_reservation) = match content_length {
+ let (body, body_length, streamed, _buffered_budget, _spooled_budget) = match content_length {
Some(declared) => {
let Some(deadline) =
tokio::time::Instant::now().checked_add(Duration::from_millis(timeout_ms))
@@ -124,6 +124,7 @@ pub(in crate::server) async fn relay_put(
declared,
None,
Some(reservation),
+ None,
)
}
None => (
@@ -131,21 +132,29 @@ pub(in crate::server) async fn relay_put(
declared,
Some(StreamedRelayBody { failure, progress }),
None,
+ None,
),
}
}
None => {
let body_length_limit = token.mb.min(app.cfg.upload_relay.max_body_bytes);
- let spooled = match spool_to_temp(
+ let Some(deadline) = tokio::time::Instant::now().checked_add(Duration::from_millis(
+ relay_upstream_timeout_ms(&app, Some(body_length_limit)),
+ )) else {
+ return relay_error(RelayError::InternalError);
+ };
+ let spool = spool_to_temp(
request.into_body(),
content_length,
body_length_limit,
&app.cfg.upload_relay.spool_dir,
app.cfg.upload_relay.spool_chunk_bytes,
app.cfg.upload_relay.spool_max_total_bytes,
- )
- .await
- {
+ );
+ let Ok(spooled) = tokio::time::timeout_at(deadline, spool).await else {
+ return relay_error(RelayError::ClientUploadFailed);
+ };
+ let spooled = match spooled {
Ok(spooled) => spooled,
Err(SpoolError::PayloadTooLarge) => {
return relay_error(RelayError::PayloadTooLarge);
@@ -162,8 +171,14 @@ pub(in crate::server) async fn relay_put(
return relay_error(RelayError::InternalError);
}
};
- let (file, spooled_length) = spooled.into_parts();
- (RelayBody::Spooled(file), spooled_length, None, None)
+ let (file, spooled_length, spool_reservation) = spooled.into_parts();
+ (
+ RelayBody::Spooled(file),
+ spooled_length,
+ None,
+ None,
+ Some(spool_reservation),
+ )
}
};
let content_type = resolve_relay_content_type(
diff --git a/fluxer_media_proxy/src/server/state.rs b/fluxer_media_proxy/src/server/state.rs
index df9075774..a2cf13897 100644
--- a/fluxer_media_proxy/src/server/state.rs
+++ b/fluxer_media_proxy/src/server/state.rs
@@ -31,6 +31,7 @@ pub(in crate::server) struct MediaRuntime {
nsfw: NSFWClient,
external_client: http_client::HttpClient,
external_buffer_bytes: ByteBudget,
+ stored_buffer_bytes: ByteBudget,
external_hints: ExternalHintCache,
transforms: TransformRuntime,
}
@@ -87,7 +88,8 @@ impl MediaRuntime {
Ok(Self {
nsfw,
external_client,
- external_buffer_bytes: ByteBudget::new(external_buffer_budget_bytes(cfg)),
+ external_buffer_bytes: ByteBudget::new(buffered_input_budget_bytes(cfg)),
+ stored_buffer_bytes: ByteBudget::new(buffered_input_budget_bytes(cfg)),
external_hints: new_external_hint_cache(cfg),
transforms: TransformRuntime::new(cfg, metrics)?,
})
@@ -113,6 +115,10 @@ impl MediaRuntime {
&self.external_buffer_bytes
}
+ pub(in crate::server) fn stored_buffer_bytes(&self) -> &ByteBudget {
+ &self.stored_buffer_bytes
+ }
+
pub(in crate::server) fn external_hints(&self) -> &ExternalHintCache {
&self.external_hints
}
@@ -122,7 +128,7 @@ impl MediaRuntime {
}
}
-fn external_buffer_budget_bytes(cfg: &Config) -> usize {
+fn buffered_input_budget_bytes(cfg: &Config) -> usize {
let concurrent_inputs = cfg
.media
.max_native_transforms
diff --git a/fluxer_media_proxy/src/server/stored/mod.rs b/fluxer_media_proxy/src/server/stored/mod.rs
index ba9d8047f..a6cf7d467 100644
--- a/fluxer_media_proxy/src/server/stored/mod.rs
+++ b/fluxer_media_proxy/src/server/stored/mod.rs
@@ -50,6 +50,7 @@ use axum::{
http::{HeaderMap, Method, StatusCode, header},
response::Response,
};
+use bytes::Bytes;
pub(in crate::server) use passthrough::serve_stored_raw;
use passthrough::{PassthroughDisposition, serve_stored_passthrough_stream};
use std::{collections::HashMap, sync::Arc};
@@ -149,7 +150,7 @@ pub(in crate::server) async fn serve_asset_image(
if let Some(hit) = cached_transform_hit(runtime, &cache_key) {
return generated_media_response(GeneratedMediaResponse {
method,
- data: hit.data.as_bytes().clone().into(),
+ data: hit.data,
content_type: hit.format.mime(),
disposition: Some(content_disposition_header(
hit.format.mime(),
@@ -181,7 +182,7 @@ pub(in crate::server) async fn serve_asset_image(
})
.await
{
- Ok(bytes) => bytes.as_bytes().clone(),
+ Ok(bytes) => bytes,
Err(error) => {
let detail = format!(
"asset key={} src_ct={} out={} size={:?} animated={}",
@@ -204,7 +205,7 @@ pub(in crate::server) async fn serve_asset_image(
};
generated_media_response(GeneratedMediaResponse {
method,
- data: transformed.into(),
+ data: transformed,
content_type: out_ext.mime(),
disposition: Some(content_disposition_header(
out_ext.mime(),
@@ -272,16 +273,16 @@ async fn read_cdn_object_with_fallback(
) -> Result<CdnSourceObject, StorageError> {
let bucket = &app.cfg.storage.bucket_cdn;
let limit = constants::MAX_MEDIA_PROXY_BYTES;
- let budget = storage::unversioned_read_budget(limit);
+ let budget = app.media.stored_buffer_bytes();
let read = match app
.store
- .read_object_limited_with_digest(bucket, key, limit, &budget)
+ .read_object_limited_with_digest(bucket, key, limit, budget)
.await
{
Err(StorageError::NotFound) => {
let fallback_key = format!("{key}.{}", original_ext.name());
app.store
- .read_object_limited_with_digest(bucket, &fallback_key, limit, &budget)
+ .read_object_limited_with_digest(bucket, &fallback_key, limit, budget)
.await?
}
other => other?,
@@ -292,7 +293,7 @@ async fn read_cdn_object_with_fallback(
.expect("a digested read always reports its content digest"),
),
object: storage::Object {
- data: read.data.as_bytes().clone(),
+ data: Bytes::from_owner(read.data),
content_type: read.content_type,
},
})
@@ -338,7 +339,11 @@ async fn read_attachment(
}
let object = match app
.store
- .read_object(&app.cfg.storage.bucket_cdn, key)
+ .read_object_within(
+ &app.cfg.storage.bucket_cdn,
+ key,
+ app.media.stored_buffer_bytes(),
+ )
.await
{
Ok(object) => object,
diff --git a/fluxer_media_proxy/src/server/stored/passthrough.rs b/fluxer_media_proxy/src/server/stored/passthrough.rs
index 605972a41..3575a30be 100644
--- a/fluxer_media_proxy/src/server/stored/passthrough.rs
+++ b/fluxer_media_proxy/src/server/stored/passthrough.rs
@@ -24,8 +24,8 @@ use crate::{
state::AppState,
transform::{
cache::{
- CachedTransformRequest, cached_transform, cached_transform_hit,
- coalescer_failure_response,
+ CachedTransformRequest, cached_transform, cached_transform_failed,
+ cached_transform_hit, coalescer_failure_response, record_cached_transform_failure,
},
cache_key::{TransformCacheKeyInput, transform_cache_key},
execution::{coalesced_work_result, deadline_instant, run_transform},
@@ -39,7 +39,6 @@ use axum::{
http::{HeaderMap, HeaderValue, Method, StatusCode, header},
response::Response,
};
-use bytes::Bytes;
use std::sync::Arc;
pub(in crate::server) enum PassthroughDisposition<'a> {
@@ -86,6 +85,9 @@ pub(in crate::server) async fn serve_stored_passthrough_stream(
if app.cfg.mode == DeploymentMode::Mp
&& image_extension_from_filename(key) == Some(AssetExtension::Svg)
{
+ if let Err(err) = app.store.head_object(bucket, key).await {
+ return storage_error_response(key, err);
+ }
return serve_stored_passthrough_svg(app, method, bucket, key, &disposition).await;
}
let range_header = headers.get(header::RANGE).and_then(|v| v.to_str().ok());
@@ -164,12 +166,89 @@ async fn serve_stored_passthrough_svg(
key: &str,
disposition: &PassthroughDisposition<'_>,
) -> Response {
- let object = match app.store.read_object(bucket, key).await {
- Ok(object) => object,
+ let runtime = app.media.transforms();
+ let cache_identity = format!("{bucket}/{key}");
+ let format = OutputFormat::WebP;
+ let quality = ImageQuality::Lossless;
+ let options = media_process::ImageOptions {
+ width: Some(constants::SVG_RASTER_MAX_DIMENSION),
+ height: Some(constants::SVG_RASTER_MAX_DIMENSION),
+ format,
+ quality,
+ animation: AnimationMode::Static,
+ deadline_ms: runtime.transform_deadline_ms(),
+ ..Default::default()
+ };
+ let cache_key = transform_cache_key(TransformCacheKeyInput {
+ route: TransformRoute::Stored,
+ asset_kind: None,
+ cache_identity: &cache_identity,
+ width: options.width,
+ height: options.height,
+ format,
+ quality: Some(quality),
+ animated: false,
+ effort: None,
+ resize_mode: Some(options.resize_mode),
+ });
+ if let Some(hit) = cached_transform_hit(runtime, &cache_key) {
+ return generated_media_response(GeneratedMediaResponse {
+ method,
+ data: hit.data,
+ content_type: hit.format.mime(),
+ disposition: passthrough_disposition_header(disposition, hit.format.mime()),
+ });
+ }
+ if cached_transform_failed(runtime, &cache_key) {
+ return svg_rasterize_failed_response(&cache_identity);
+ }
+ let data = match app
+ .store
+ .read_object_within(bucket, key, app.media.stored_buffer_bytes())
+ .await
+ {
+ Ok(object) => object.data,
Err(err) => return storage_error_response(key, err),
};
- let cache_identity = format!("{bucket}/{key}");
- serve_stored_svg_rasterized(app, method, object.data, &cache_identity, disposition).await
+ let failure_key = cache_key.clone();
+ let transformed = match cached_transform(CachedTransformRequest {
+ runtime,
+ cache_key,
+ format,
+ deadline: deadline_instant(options.deadline_ms),
+ work: move || async move {
+ coalesced_work_result(run_transform(runtime, data, options).await)
+ .map(|media| media_process::MediaBytes::from(media.bytes))
+ },
+ })
+ .await
+ {
+ Ok(bytes) => bytes,
+ Err(error) => {
+ if let Some(response) =
+ coalescer_failure_response(error, "coalescer_timeout_svg_rasterize")
+ {
+ return response;
+ }
+ record_cached_transform_failure(runtime, failure_key);
+ return svg_rasterize_failed_response(&cache_identity);
+ }
+ };
+ generated_media_response(GeneratedMediaResponse {
+ method,
+ data: transformed,
+ content_type: format.mime(),
+ disposition: passthrough_disposition_header(disposition, format.mime()),
+ })
+}
+
+fn svg_rasterize_failed_response(cache_identity: &str) -> Response {
+ text_with_source(
+ StatusCode::BAD_REQUEST,
+ "Bad Request",
+ "svg_rasterize_failed",
+ cache_identity,
+ )
}
/// Resolves the object's full length, preferring what the store already reported on the streamed
@@ -243,77 +322,3 @@ fn passthrough_disposition_header(
)),
}
}
-
-async fn serve_stored_svg_rasterized(
- app: &Arc<AppState>,
- method: Method,
- data: Bytes,
- cache_identity: &str,
- disposition: &PassthroughDisposition<'_>,
-) -> Response {
- let runtime = app.media.transforms();
- let format = OutputFormat::WebP;
- let quality = ImageQuality::Lossless;
- let options = media_process::ImageOptions {
- width: Some(constants::SVG_RASTER_MAX_DIMENSION),
- height: Some(constants::SVG_RASTER_MAX_DIMENSION),
- format,
- quality,
- animation: AnimationMode::Static,
- deadline_ms: runtime.transform_deadline_ms(),
- ..Default::default()
- };
- let cache_key = transform_cache_key(TransformCacheKeyInput {
- route: TransformRoute::Stored,
- asset_kind: None,
- cache_identity,
- width: options.width,
- height: options.height,
- format,
- quality: Some(quality),
- animated: false,
- effort: None,
- resize_mode: Some(options.resize_mode),
- });
- if let Some(hit) = cached_transform_hit(runtime, &cache_key) {
- return generated_media_response(GeneratedMediaResponse {
- method,
- data: hit.data.as_bytes().clone().into(),
- content_type: hit.format.mime(),
- disposition: passthrough_disposition_header(disposition, hit.format.mime()),
- });
- }
- let transformed = match cached_transform(CachedTransformRequest {
- runtime,
- cache_key,
- format,
- deadline: deadline_instant(options.deadline_ms),
- work: move || async move {
- coalesced_work_result(run_transform(runtime, data, options).await)
- .map(|media| media_process::MediaBytes::from(media.bytes))
- },
- })
- .await
- {
- Ok(bytes) => bytes.as_bytes().clone(),
- Err(error) => {
- if let Some(response) =
- coalescer_failure_response(error, "coalescer_timeout_svg_rasterize")
- {
- return response;
- }
- return text_with_source(
- StatusCode::BAD_REQUEST,
- "Bad Request",
- "svg_rasterize_failed",
- cache_identity,
- );
- }
- };
- generated_media_response(GeneratedMediaResponse {
- method,
- data: transformed.into(),
- content_type: format.mime(),
- disposition: passthrough_disposition_header(disposition, format.mime()),
- })
-}
diff --git a/fluxer_media_proxy/src/server/transform/cache.rs b/fluxer_media_proxy/src/server/transform/cache.rs
index f80dbfb7a..1a8c10298 100644
--- a/fluxer_media_proxy/src/server/transform/cache.rs
+++ b/fluxer_media_proxy/src/server/transform/cache.rs
@@ -28,6 +28,20 @@ pub(in crate::server) fn cached_transform_hit(
runtime.cache().get(cache_key)
}
+pub(in crate::server) fn cached_transform_failed(
+ runtime: &TransformRuntime,
+ cache_key: &str,
+) -> bool {
+ runtime.failed_transforms().contains_key(cache_key)
+}
+
+pub(in crate::server) fn record_cached_transform_failure(
+ runtime: &TransformRuntime,
+ cache_key: String,
+) {
+ runtime.failed_transforms().insert(cache_key, ());
+}
+
pub(in crate::server) async fn cached_transform<F, Fut>(
request: CachedTransformRequest<'_, F>,
) -> Result<BudgetedBytes, CoalescerError>
diff --git a/fluxer_media_proxy/src/server/transform/execution.rs b/fluxer_media_proxy/src/server/transform/execution.rs
index 95d9b2f12..a54486c6d 100644
--- a/fluxer_media_proxy/src/server/transform/execution.rs
+++ b/fluxer_media_proxy/src/server/transform/execution.rs
@@ -90,8 +90,12 @@ pub(in crate::server) async fn run_video_transform(
move || Ok(cost_bytes),
move || {
let started = Instant::now();
- let thumbnail =
- media_process::extract_video_thumbnail(&data, format, &media_limits)?;
+ let thumbnail = media_process::extract_video_thumbnail(
+ &data,
+ format,
+ deadline_ms,
+ &media_limits,
+ )?;
let media = if width.is_none() && height.is_none() {
thumbnail
} else {
diff --git a/fluxer_media_proxy/src/server/transform/mod.rs b/fluxer_media_proxy/src/server/transform/mod.rs
index 834746d5c..ad1720e41 100644
--- a/fluxer_media_proxy/src/server/transform/mod.rs
+++ b/fluxer_media_proxy/src/server/transform/mod.rs
@@ -6,7 +6,7 @@ pub(in crate::server) mod execution;
pub mod parameters;
use crate::{
- byte_budget::ByteBudget,
+ byte_budget::{BudgetedBytes, ByteBudget},
byte_cache::ByteCacheSettings,
coalescer::ByteCoalescer,
config::Config,
@@ -56,7 +56,7 @@ use axum::{
response::Response,
};
use bytes::Bytes;
-use std::{collections::HashMap, sync::Arc};
+use std::{collections::HashMap, sync::Arc, time::Duration};
const NATIVE_MEMORY_HEADROOM_BYTES: usize = 512 << 20;
const NATIVE_MEMORY_FLOOR_BYTES: usize = 128 << 20;
@@ -65,6 +65,7 @@ const CGROUP_MEMORY_LIMIT_PATHS: [&str; 2] = [
"/sys/fs/cgroup/memory/memory.limit_in_bytes",
];
const CONTENT_TYPE_SNIFF_PREFIX_BYTES: usize = 8192;
+const FAILED_TRANSFORM_ENTRIES: u64 = 4096;
pub(in crate::server) struct TransformRuntime {
limits: MediaLimits,
@@ -72,6 +73,7 @@ pub(in crate::server) struct TransformRuntime {
transform_timeout_ms: u64,
tasks: NativeTaskExecutor,
cache: TransformCache,
+ failed_transforms: moka::sync::Cache<String, ()>,
metrics: Arc<TransformMetrics>,
}
@@ -131,6 +133,12 @@ impl TransformRuntime {
cache_metrics: metrics.transform_cache(),
coalescer_metrics: metrics.coalescer(),
}),
+ failed_transforms: moka::sync::Cache::builder()
+ .max_capacity(FAILED_TRANSFORM_ENTRIES)
+ .time_to_live(Duration::from_millis(
+ cfg.media.transform_cache_ttl_ms.max(1),
+ ))
+ .build(),
metrics: metrics.transform(),
})
}
@@ -147,6 +155,10 @@ impl TransformRuntime {
&self.cache
}
+ pub(in crate::server) fn failed_transforms(&self) -> &moka::sync::Cache<String, ()> {
+ &self.failed_transforms
+ }
+
pub(in crate::server) fn tasks(&self) -> &NativeTaskExecutor {
&self.tasks
}
@@ -365,7 +377,7 @@ pub(in crate::server) fn cached_video_transform_response(
let hit = cached_transform_hit(runtime, &plan.cache_key)?;
Some(transformed_response(TransformedBytes {
method: request.method,
- data: hit.data.as_bytes().clone(),
+ data: hit.data,
content_type: hit.format.mime(),
filename: request.filename,
requested_download: transform.requested_download,
@@ -422,7 +434,7 @@ async fn serve_video_transform(
if let Some(hit) = cached_transform_hit(runtime, &cache_key) {
return transformed_response(TransformedBytes {
method,
- data: hit.data.as_bytes().clone(),
+ data: hit.data,
content_type: hit.format.mime(),
filename,
requested_download: transform.requested_download,
@@ -454,7 +466,7 @@ async fn serve_video_transform(
})
.await
{
- Ok(bytes) => bytes.as_bytes().clone(),
+ Ok(bytes) => bytes,
Err(error) => {
if let Some(response) = coalescer_failure_response(error, "coalescer_timeout_video") {
return response;
@@ -559,7 +571,7 @@ async fn serve_image_transform(
if let Some(hit) = cached_transform_hit(runtime, &cache_key) {
return transformed_response(TransformedBytes {
method,
- data: hit.data.as_bytes().clone(),
+ data: hit.data,
content_type: response_content_type,
filename,
requested_download: transform.requested_download,
@@ -591,7 +603,7 @@ async fn serve_image_transform(
})
.await
{
- Ok(bytes) => bytes.as_bytes().clone(),
+ Ok(bytes) => bytes,
Err(error) => {
if let Some(original) = too_large_original {
return original_bytes_response(OriginalBytes {
@@ -627,7 +639,11 @@ async fn serve_image_transform(
format!(
"route={:?} cache_identity={} fmt={} w={:?} h={:?} q={} animated={}",
route,
- cache_identity,
+ if route == TransformRoute::External {
+ crate::public_net_policy::external_url_for_log(cache_identity)
+ } else {
+ cache_identity.to_owned()
+ },
options.format.extension(),
options.width,
options.height,
@@ -787,7 +803,7 @@ pub(in crate::server) fn cached_transform_response(
let hit = cached_transform_hit(runtime, &cache_key)?;
Some(transformed_response(TransformedBytes {
method,
- data: hit.data.as_bytes().clone(),
+ data: hit.data,
content_type: &response_content_type,
filename,
requested_download: transform.requested_download,
@@ -796,7 +812,7 @@ pub(in crate::server) fn cached_transform_response(
struct TransformedBytes<'a> {
method: Method,
- data: Bytes,
+ data: BudgetedBytes,
content_type: &'a str,
filename: &'a str,
requested_download: bool,
@@ -810,7 +826,7 @@ fn transformed_response(request: TransformedBytes<'_>) -> Response {
));
generated_media_response(GeneratedMediaResponse {
method: request.method,
- data: request.data.into(),
+ data: request.data,
content_type: request.content_type,
disposition,
})
diff --git a/fluxer_media_proxy/src/spool.rs b/fluxer_media_proxy/src/spool.rs
index cbc604ded..898bf7bb0 100644
--- a/fluxer_media_proxy/src/spool.rs
+++ b/fluxer_media_proxy/src/spool.rs
@@ -10,7 +10,7 @@ use tokio::{
io::{AsyncSeekExt, AsyncWriteExt, BufWriter},
};
-use crate::upload_relay::{release_spool_budget, try_reserve_spool_budget};
+use crate::upload_relay::SpoolReservation;
#[derive(Debug, Error)]
pub enum SpoolError {
@@ -28,25 +28,18 @@ pub enum SpoolError {
#[derive(Debug)]
pub struct SpooledBody {
- file: Option<File>,
+ file: File,
length: u64,
- budget_reservation: u64,
+ reservation: SpoolReservation,
}
impl SpooledBody {
- pub fn into_parts(mut self) -> (File, u64) {
- let file = self.file.take().expect("SpooledBody already consumed");
- let length = self.length;
- if self.budget_reservation > 0 {
- release_spool_budget(self.budget_reservation);
- self.budget_reservation = 0;
- }
- (file, length)
+ pub fn into_parts(self) -> (File, u64, SpoolReservation) {
+ (self.file, self.length, self.reservation)
}
pub fn into_mapped(self) -> std::io::Result<MappedSpool> {
- let file = self.file.as_ref().expect("SpooledBody already consumed");
- let map = unsafe { Mmap::map(file)? };
+ let map = unsafe { Mmap::map(&self.file)? };
Ok(MappedSpool { map, _spool: self })
}
}
@@ -62,15 +55,6 @@ impl AsRef<[u8]> for MappedSpool {
}
}
-impl Drop for SpooledBody {
- fn drop(&mut self) {
- if self.budget_reservation > 0 {
- release_spool_budget(self.budget_reservation);
- self.budget_reservation = 0;
- }
- }
-}
-
pub async fn spool_to_temp(
body: Body,
declared_length: Option<u64>,
@@ -84,35 +68,32 @@ pub async fn spool_to_temp(
{
return Err(SpoolError::PayloadTooLarge);
}
- let budget_reservation = declared_length.unwrap_or(max_body_bytes);
- if !try_reserve_spool_budget(budget_reservation, spool_total_ceiling) {
- return Err(SpoolError::BudgetExhausted);
- }
- let outcome = spool_body_inner(
+ let mut reservation =
+ SpoolReservation::try_new(declared_length.unwrap_or(0), spool_total_ceiling)
+ .ok_or(SpoolError::BudgetExhausted)?;
+ let (file, length) = spool_body_inner(
body,
declared_length,
max_body_bytes,
+ spool_total_ceiling,
+ &mut reservation,
dir,
write_buffer_bytes,
)
- .await;
- match outcome {
- Ok((file, length)) => Ok(SpooledBody {
- file: Some(file),
- length,
- budget_reservation,
- }),
- Err(err) => {
- release_spool_budget(budget_reservation);
- Err(err)
- }
- }
+ .await?;
+ Ok(SpooledBody {
+ file,
+ length,
+ reservation,
+ })
}
async fn spool_body_inner(
mut body: Body,
declared_length: Option<u64>,
max_body_bytes: u64,
+ spool_total_ceiling: u64,
+ reservation: &mut SpoolReservation,
dir: &Path,
write_buffer_bytes: usize,
) -> Result<(File, u64), SpoolError> {
@@ -131,6 +112,11 @@ async fn spool_body_inner(
if next > max_body_bytes || declared_length.is_some_and(|declared| next > declared) {
return Err(SpoolError::PayloadTooLarge);
}
+ if declared_length.is_none()
+ && !reservation.try_grow(chunk.len() as u64, spool_total_ceiling)
+ {
+ return Err(SpoolError::BudgetExhausted);
+ }
writer.write_all(&chunk).await?;
written = next;
}
diff --git a/fluxer_media_proxy/src/storage/local.rs b/fluxer_media_proxy/src/storage/local.rs
index 76cb04dd8..6f5acdc99 100644
--- a/fluxer_media_proxy/src/storage/local.rs
+++ b/fluxer_media_proxy/src/storage/local.rs
@@ -14,33 +14,59 @@ use futures_util::StreamExt as _;
use http::StatusCode;
use sha2::{Digest as _, Sha256};
use std::{
+ ffi::{CStr, CString},
fs::Metadata,
- path::{Path, PathBuf},
+ os::{
+ fd::{AsRawFd as _, FromRawFd as _, OwnedFd},
+ unix::fs::OpenOptionsExt as _,
+ },
};
use tokio::io::{AsyncReadExt as _, AsyncSeekExt as _, AsyncWriteExt as _};
const LOCAL_OPEN_FLAGS: i32 = libc::O_CLOEXEC | libc::O_NOFOLLOW | libc::O_NONBLOCK;
+const LOCAL_DIR_FLAGS: i32 =
+ libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC;
+const LOCAL_CREATE_FLAGS: i32 =
+ libc::O_WRONLY | libc::O_CREAT | libc::O_TRUNC | libc::O_NOFOLLOW | libc::O_CLOEXEC;
+
+struct LocalEntry {
+ parent: OwnedFd,
+ name: CString,
+}
impl Store {
- pub(super) async fn local_path(
+ fn local_entry(&self, bucket: &str, key: &str) -> Result<LocalEntry, StorageError> {
+ safe_bucket(bucket)?;
+ safe_key(key)?;
+ open_local_entry(&self.cfg.storage.root, bucket, key, false)
+ }
+
+ async fn create_local_file(
&self,
bucket: &str,
key: &str,
- ) -> Result<PathBuf, StorageError> {
+ ) -> Result<(LocalEntry, tokio::fs::File), StorageError> {
safe_bucket(bucket)?;
safe_key(key)?;
- let root = Path::new(&self.cfg.storage.root);
- let path = root.join(bucket).join(key);
- reject_symlink_chain(&path)?;
- Ok(path)
+ let root = self.cfg.storage.root.clone();
+ let bucket = bucket.to_owned();
+ let key = key.to_owned();
+ tokio::task::spawn_blocking(move || {
+ let entry = open_local_entry(&root, &bucket, &key, true)?;
+ let file = open_at(&entry.parent, &entry.name, LOCAL_CREATE_FLAGS, 0o666)
+ .map_err(map_local_open_error)?;
+ Ok((entry, tokio::fs::File::from_std(std::fs::File::from(file))))
+ })
+ .await
+ .map_err(std::io::Error::other)?
}
pub(super) async fn read_local(
&self,
request: BufferedObjectReadRequest<'_>,
) -> Result<BufferedStorageObject, StorageError> {
- let path = self.local_path(request.bucket, request.key).await?;
- let (file, metadata) = open_local_read_file(&path).await?;
+ let entry = self.local_entry(request.bucket, request.key)?;
+ let (file, metadata) = open_local_read_file(entry).await?;
if metadata.len() > request.limit as u64 {
return Err(StorageError::StreamTooLong);
}
@@ -63,15 +89,15 @@ impl Store {
bucket: &str,
key: &str,
) -> Result<HeadResult, StorageError> {
- let path = self.local_path(bucket, key).await?;
- let metadata = tokio::fs::symlink_metadata(&path)
- .await
- .map_err(map_not_found)?;
- if !metadata.is_file() {
- return Err(StorageError::NotFound);
+ let entry = self.local_entry(bucket, key)?;
+ let stat = stat_at(&entry.parent, &entry.name).map_err(map_not_found)?;
+ match stat.st_mode & libc::S_IFMT {
+ libc::S_IFREG => {}
+ libc::S_IFLNK => return Err(StorageError::InvalidKey),
+ _ => return Err(StorageError::NotFound),
}
Ok(HeadResult {
- content_length: metadata.len(),
+ content_length: u64::try_from(stat.st_size).unwrap_or(0),
content_type: local_content_type(key),
})
}
@@ -80,8 +106,8 @@ impl Store {
&self,
plan: ObjectStreamPlan<'_>,
) -> Result<StreamObject, StorageError> {
- let path = self.local_path(plan.bucket, plan.key).await?;
- let (mut file, metadata) = open_local_read_file(&path).await?;
+ let entry = self.local_entry(plan.bucket, plan.key)?;
+ let (mut file, metadata) = open_local_read_file(entry).await?;
let total_len = usize::try_from(metadata.len()).map_err(|_| StorageError::StreamTooLong)?;
let byte_range = match plan.range {
StreamRange::Full => None,
@@ -138,11 +164,9 @@ impl Store {
key: &str,
data: &[u8],
) -> Result<(), StorageError> {
- let path = self.local_path(bucket, key).await?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
- tokio::fs::write(path, data).await?;
+ let (_entry, mut file) = self.create_local_file(bucket, key).await?;
+ file.write_all(data).await?;
+ file.flush().await?;
Ok(())
}
@@ -152,11 +176,7 @@ impl Store {
key: &str,
options: RelayPutOptions,
) -> Result<(), StorageError> {
- let path = self.local_path(bucket, key).await?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
- let mut dest = tokio::fs::File::create(&path).await?;
+ let (entry, mut dest) = self.create_local_file(bucket, key).await?;
let content_length = options.content_length;
let result = async {
match options.body {
@@ -185,7 +205,9 @@ impl Store {
}
.await;
if result.is_err() {
- let _ = tokio::fs::remove_file(&path).await;
+ drop(dest);
+ let _ =
+ tokio::task::spawn_blocking(move || unlink_at(&entry.parent, &entry.name)).await;
}
result
}
@@ -197,15 +219,27 @@ fn local_content_type(key: &str) -> String {
.to_owned()
}
-async fn open_local_read_file(path: &Path) -> Result<(tokio::fs::File, Metadata), StorageError> {
- let mut options = tokio::fs::OpenOptions::new();
- options.read(true).custom_flags(LOCAL_OPEN_FLAGS);
- let file = options.open(path).await.map_err(map_local_open_error)?;
- let metadata = file.metadata().await?;
+async fn open_local_read_file(
+ entry: LocalEntry,
+) -> Result<(tokio::fs::File, Metadata), StorageError> {
+ let (file, metadata) = tokio::task::spawn_blocking(move || {
+ let file = open_at(
+ &entry.parent,
+ &entry.name,
+ libc::O_RDONLY | LOCAL_OPEN_FLAGS,
+ 0,
+ )
+ .map(std::fs::File::from)
+ .map_err(map_local_open_error)?;
+ let metadata = file.metadata()?;
+ Ok::<_, StorageError>((file, metadata))
+ })
+ .await
+ .map_err(std::io::Error::other)??;
if !metadata.is_file() {
return Err(StorageError::NotFound);
}
- Ok((file, metadata))
+ Ok((tokio::fs::File::from_std(file), metadata))
}
fn map_local_open_error(error: std::io::Error) -> StorageError {
@@ -215,25 +249,86 @@ fn map_local_open_error(error: std::io::Error) -> StorageError {
map_not_found(error)
}
-/// Walks the resolved path and refuses any component that is a symlink.
-///
-/// This is deliberately synchronous. It runs once per storage operation and touches one dentry
-/// per path component, which the kernel serves from cache in well under a microsecond. Issuing
-/// each `symlink_metadata` through `tokio::fs` instead turns a handful of cheap syscalls into one
-/// blocking-threadpool round-trip *per component*, which measured as a 2-3x throughput loss on
-/// every storage-backed request.
-fn reject_symlink_chain(path: &Path) -> Result<(), StorageError> {
- let mut current = PathBuf::new();
- for component in path.components() {
- current.push(component.as_os_str());
- match std::fs::symlink_metadata(&current) {
- Ok(metadata) if metadata.file_type().is_symlink() => {
+fn open_local_entry(
+ root: &str,
+ bucket: &str,
+ key: &str,
+ create: bool,
+) -> Result<LocalEntry, StorageError> {
+ if create {
+ std::fs::create_dir_all(root)?;
+ }
+ let mut dir = OwnedFd::from(
+ std::fs::OpenOptions::new()
+ .read(true)
+ .custom_flags(libc::O_DIRECTORY)
+ .open(root)
+ .map_err(map_not_found)?,
+ );
+ let mut components = std::iter::once(bucket).chain(key.split('/')).peekable();
+ while let Some(component) = components.next() {
+ let name = CString::new(component).map_err(|_| StorageError::InvalidKey)?;
+ if components.peek().is_none() {
+ return Ok(LocalEntry { parent: dir, name });
+ }
+ if create {
+ mkdir_at(&dir, &name)?;
+ }
+ dir = match open_at(&dir, &name, LOCAL_DIR_FLAGS, 0) {
+ Ok(next) => next,
+ Err(error)
+ if error.raw_os_error() == Some(libc::ENOTDIR) && is_symlink_at(&dir, &name) =>
+ {
return Err(StorageError::InvalidKey);
}
- Ok(_) => {}
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
- Err(error) => return Err(StorageError::Io(error)),
- }
+ Err(error) => return Err(map_local_open_error(error)),
+ };
+ }
+ Err(StorageError::InvalidKey)
+}
+
+fn open_at(dir: &OwnedFd, name: &CStr, flags: i32, mode: libc::c_uint) -> std::io::Result<OwnedFd> {
+ let fd = unsafe { libc::openat(dir.as_raw_fd(), name.as_ptr(), flags, mode) };
+ if fd < 0 {
+ return Err(std::io::Error::last_os_error());
+ }
+ Ok(unsafe { OwnedFd::from_raw_fd(fd) })
+}
+
+fn mkdir_at(dir: &OwnedFd, name: &CStr) -> std::io::Result<()> {
+ if unsafe { libc::mkdirat(dir.as_raw_fd(), name.as_ptr(), 0o777) } == 0 {
+ return Ok(());
+ }
+ let error = std::io::Error::last_os_error();
+ if error.raw_os_error() == Some(libc::EEXIST) {
+ return Ok(());
+ }
+ Err(error)
+}
+
+fn stat_at(dir: &OwnedFd, name: &CStr) -> std::io::Result<libc::stat> {
+ let mut stat = std::mem::MaybeUninit::<libc::stat>::uninit();
+ let rc = unsafe {
+ libc::fstatat(
+ dir.as_raw_fd(),
+ name.as_ptr(),
+ stat.as_mut_ptr(),
+ libc::AT_SYMLINK_NOFOLLOW,
+ )
+ };
+ if rc != 0 {
+ return Err(std::io::Error::last_os_error());
+ }
+ Ok(unsafe { stat.assume_init() })
+}
+
+fn is_symlink_at(dir: &OwnedFd, name: &CStr) -> bool {
+ stat_at(dir, name).is_ok_and(|stat| stat.st_mode & libc::S_IFMT == libc::S_IFLNK)
+}
+
+fn unlink_at(dir: &OwnedFd, name: &CStr) -> std::io::Result<()> {
+ if unsafe { libc::unlinkat(dir.as_raw_fd(), name.as_ptr(), 0) } != 0 {
+ return Err(std::io::Error::last_os_error());
}
Ok(())
}
diff --git a/fluxer_media_proxy/src/storage/object_read.rs b/fluxer_media_proxy/src/storage/object_read.rs
index a0ce197ce..0189bbfd5 100644
--- a/fluxer_media_proxy/src/storage/object_read.rs
+++ b/fluxer_media_proxy/src/storage/object_read.rs
@@ -5,15 +5,25 @@ use super::{
Store, record_storage_outcome, unversioned_read_budget,
};
use crate::{byte_budget::ByteBudget, config::StorageBackend, constants};
+use bytes::Bytes;
impl Store {
pub async fn read_object(&self, bucket: &str, key: &str) -> Result<Object, StorageError> {
let budget = unversioned_read_budget(constants::MAX_MEDIA_PROXY_BYTES);
+ self.read_object_within(bucket, key, &budget).await
+ }
+
+ pub async fn read_object_within(
+ &self,
+ bucket: &str,
+ key: &str,
+ budget: &ByteBudget,
+ ) -> Result<Object, StorageError> {
let object = self
- .read_object_limited(bucket, key, constants::MAX_MEDIA_PROXY_BYTES, &budget)
+ .read_object_limited(bucket, key, constants::MAX_MEDIA_PROXY_BYTES, budget)
.await?;
Ok(Object {
- data: object.data.as_bytes().clone(),
+ data: Bytes::from_owner(object.data),
content_type: object.content_type,
})
}
diff --git a/fluxer_media_proxy/src/storage/response_body.rs b/fluxer_media_proxy/src/storage/response_body.rs
index fac5aa9df..3062ec2fc 100644
--- a/fluxer_media_proxy/src/storage/response_body.rs
+++ b/fluxer_media_proxy/src/storage/response_body.rs
@@ -99,6 +99,48 @@ pub(super) async fn read_response_bytes(
))
}
+pub(super) async fn read_response_bytes_up_to(
+ mut response: reqwest::Response,
+ limit: usize,
+ budget: &ByteBudget,
+) -> Result<BudgetedBytes, StorageError> {
+ let _transport_chunk_reservation = budget
+ .try_reserve(response_body_limit::RESPONSE_BODY_TRANSPORT_CHUNK_BYTES_MAX)
+ .ok_or(StorageError::BufferBudgetExhausted)?;
+ let mut buffer_budget = ReadBufferBudget::reserve(budget, 0)?;
+ let mut body: Vec<u8> = Vec::new();
+ let mut empty_chunks_remaining = response_body_limit::response_body_chunk_limit(limit as u64);
+ while let Some(chunk) = response.chunk().await? {
+ if chunk.is_empty() {
+ empty_chunks_remaining = empty_chunks_remaining.checked_sub(1).ok_or_else(|| {
+ StorageError::ObjectStorage(anyhow::anyhow!(
+ "object storage response exceeded its empty chunk limit"
+ ))
+ })?;
+ continue;
+ }
+ let next_length = body
+ .len()
+ .checked_add(chunk.len())
+ .filter(|length| *length <= limit)
+ .ok_or(StorageError::StreamTooLong)?;
+ if next_length > body.capacity() {
+ let target_capacity = next_length.max(body.capacity().saturating_mul(2).min(limit));
+ buffer_budget.grow_to(target_capacity)?;
+ body.try_reserve_exact(target_capacity - body.len())
+ .map_err(|_| StorageError::BufferAllocationFailed)?;
+ buffer_budget.grow_to(body.capacity())?;
+ }
+ body.extend_from_slice(&chunk);
+ assert_eq!(body.len(), next_length);
+ }
+ buffer_budget.shrink_to(body.capacity());
+ Ok(BudgetedBytes::budgeted(
+ Bytes::from(body),
+ buffer_budget.into_reservation(),
+ ))
+}
+
pub(super) async fn read_exact_bytes(
reader: impl AsyncRead + Unpin,
expected_length: usize,
diff --git a/fluxer_media_proxy/src/storage/s3.rs b/fluxer_media_proxy/src/storage/s3.rs
index 8c302cd59..13942031b 100644
--- a/fluxer_media_proxy/src/storage/s3.rs
+++ b/fluxer_media_proxy/src/storage/s3.rs
@@ -4,9 +4,9 @@ use super::{
BufferedObjectReadRequest, BufferedStorageObject, ContentDigestRequest, HeadResult,
ObjectStreamPlan, StorageError, Store, StreamObject, StreamRange,
relay_body::{RelayBody, RelayPutOptions, SizedFileBody},
- response_body::{exact_response_stream, read_response_bytes},
+ response_body::{exact_response_stream, read_response_bytes, read_response_bytes_up_to},
};
-use crate::{aws_sigv4, byte_budget::BudgetedBytes, config::Config, http_headers, range};
+use crate::{aws_sigv4, config::Config, http_headers, range};
use axum::body::Body;
use http::{HeaderMap, HeaderName, StatusCode, header};
use percent_encoding::{AsciiSet, CONTROLS, percent_encode};
@@ -17,6 +17,8 @@ use tokio::io::AsyncSeekExt as _;
pub(super) const UNSIGNED_PAYLOAD: &str = "UNSIGNED-PAYLOAD";
+const S3_ERROR_BODY_BYTES_MAX: usize = 2048;
+
const QUERY_ENCODE_SET: &AsciiSet = &CONTROLS
.add(b' ')
.add(b'"')
@@ -60,13 +62,7 @@ impl Store {
usize::try_from(content_length).map_err(|_| StorageError::StreamTooLong)?;
read_response_bytes(response, expected_length, request.budget).await?
}
- None => {
- let data = response.bytes().await?;
- if data.len() > request.limit {
- return Err(StorageError::StreamTooLong);
- }
- BudgetedBytes::unbudgeted(data)
- }
+ None => read_response_bytes_up_to(response, request.limit, request.budget).await?,
};
Ok(BufferedStorageObject {
content_digest: match request.content_digest {
@@ -308,13 +304,18 @@ pub(super) fn signed_headers(
headers
}
-pub(super) async fn s3_error_summary(response: reqwest::Response) -> String {
+pub(super) async fn s3_error_summary(mut response: reqwest::Response) -> String {
let status = response.status();
- let body = response
- .bytes()
- .await
- .map(|b| b.to_vec())
- .unwrap_or_default();
+ let mut body = Vec::new();
+ while body.len() < S3_ERROR_BODY_BYTES_MAX {
+ match response.chunk().await {
+ Ok(Some(chunk)) => {
+ let take = chunk.len().min(S3_ERROR_BODY_BYTES_MAX - body.len());
+ body.extend_from_slice(&chunk[..take]);
+ }
+ Ok(None) | Err(_) => break,
+ }
+ }
let snippet: String = String::from_utf8_lossy(&body)
.chars()
.filter(|c| !c.is_control() || *c == ' ')
diff --git a/fluxer_media_proxy/src/upload_relay/mod.rs b/fluxer_media_proxy/src/upload_relay/mod.rs
index e5d902704..d6b4b76c0 100644
--- a/fluxer_media_proxy/src/upload_relay/mod.rs
+++ b/fluxer_media_proxy/src/upload_relay/mod.rs
@@ -67,12 +67,29 @@ impl Drop for BufferReservation {
}
}
-pub fn try_reserve_spool_budget(needed: u64, ceiling: u64) -> bool {
- try_reserve(&SPOOL_IN_FLIGHT_BYTES, needed, ceiling)
+#[derive(Debug)]
+pub struct SpoolReservation {
+ bytes: u64,
}
-pub fn release_spool_budget(amount: u64) {
- SPOOL_IN_FLIGHT_BYTES.fetch_sub(amount, Ordering::AcqRel);
+impl SpoolReservation {
+ pub fn try_new(bytes: u64, ceiling: u64) -> Option<Self> {
+ try_reserve(&SPOOL_IN_FLIGHT_BYTES, bytes, ceiling).then_some(Self { bytes })
+ }
+
+ pub fn try_grow(&mut self, bytes: u64, ceiling: u64) -> bool {
+ if !try_reserve(&SPOOL_IN_FLIGHT_BYTES, bytes, ceiling) {
+ return false;
+ }
+ self.bytes += bytes;
+ true
+ }
+}
+
+impl Drop for SpoolReservation {
+ fn drop(&mut self) {
+ SPOOL_IN_FLIGHT_BYTES.fetch_sub(self.bytes, Ordering::AcqRel);
+ }
}
fn try_reserve(counter: &AtomicU64, needed: u64, ceiling: u64) -> bool {
diff --git a/fluxer_media_proxy/src/vips_shim.h b/fluxer_media_proxy/src/vips_shim.h
index 4bb828acf..20ccd0ff5 100644
--- a/fluxer_media_proxy/src/vips_shim.h
+++ b/fluxer_media_proxy/src/vips_shim.h
@@ -165,6 +165,9 @@ int fluxer_av_metadata(
struct fluxer_av_metadata_out *out
);
+typedef int (*fluxer_av_picture_strip_cb)(
+ void *user_data, const void *data, size_t len,
+ const void **out_data, size_t *out_len, int *out_width, int *out_height);
int fluxer_av_strip_metadata(
const void *media_data,
size_t media_len,
@@ -172,7 +175,9 @@ int fluxer_av_strip_metadata(
const char *muxer,
int faststart,
const char *output_path,
- long long deadline_monotonic_ms
+ long long deadline_monotonic_ms,
+ fluxer_av_picture_strip_cb strip_picture,
+ void *user_data
);
struct fluxer_av_audio_duration_out {