blib/lib/Langertha/Content/Image.pm

filter: Statementstmt 98.8% 329 / 333 Branchbran 84.7% 183 / 216 Conditioncond 76.8% 106 / 138 MC/DCmcdc 56.2% 45 / 80 Subroutinesub 96.6% 58 / 60 Podpod 93.7% 15 / 16 totaltotal 87.3% 736 / 843 CC 162 SCAR 21.5
CC
162
Cov
90%
_inline_fetched
23.5
_is_private_v4
18.0
_is_private_address
16.0
CRAP 8.6
« blib/lib/Langertha/Runtime/Knobs.pm ↑ Summary blib/lib/Langertha/ServerTool.pm »
1 package Langertha::Content::Image;
2 # ABSTRACT: Canonical image content block with cross-provider conversion
3 17 our $VERSION = '0.503';
4 17 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 17 ▶use Moose::Util::TypeConstraints qw( subtype as where message );
Subroutine BEGIN: called CC=1 SCAR=0.0
6 17 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 17 ▶use MIME::Base64 qw( encode_base64 decode_base64 );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 17 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 17 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 17 ▶use Scalar::Util qw( blessed );
Subroutine BEGIN: called CC=1 SCAR=0.0
11 17 ▶use Socket qw( getaddrinfo getnameinfo inet_pton AF_INET AF_INET6 SOCK_STREAM
Subroutine BEGIN: called CC=1 SCAR=0.0
12 17 NI_NUMERICHOST NIx_NOSERV );
13  
14 17 with 'Langertha::Content';
15  
16 # The only schemes the inline fetch talks to (karr k325). data: URLs are
17 # decoded locally, everything else croaks before any I/O.
18 17 my @FETCH_SCHEMES = qw( http https );
19  
20 # The download cap when the caller passes none (karr k337): provider inline
21 # image limits sit around 20 MB, and the body is held in memory.
22 17 ▶use constant DEFAULT_MAX_BYTES => 20_971_520;
Subroutine BEGIN: called CC=1 SCAR=0.0
23  
24 # Redirect hops the Net::Async::HTTP fetch follows itself, the LWP default.
25 17 my $MAX_REDIRECTS = 7;
26  
27  
28 17 has url => (
29 is => 'ro',
30 isa => 'Maybe[Str]',
31 predicate => 'has_url',
32 );
33  
34  
35 17 has base64 => (
36 is => 'rw',
37 isa => 'Maybe[Str]',
38 predicate => 'has_base64',
39 );
40  
41  
42 17 has media_type => (
43 is => 'rw',
44 isa => 'Maybe[Str]',
45 predicate => 'has_media_type',
46 );
47  
48  
49 # Open value, not an enum: the provider judges it (normalize, don't gatekeep;
50 # a model family may add values before Langertha knows them).
51 14 ▶subtype 'Langertha::Content::Image::Detail', as 'Str', where { length },
Subroutine __ANON__: called CC=1 SCAR=0.0
52 1 ▶ message { 'detail must be a non-empty string' };
Subroutine __ANON__: called CC=1 SCAR=0.0
53  
54 17 has detail => (
55 is => 'ro',
56 isa => 'Langertha::Content::Image::Detail',
57 predicate => 'has_detail',
58 );
59  
60  
61 229 ▶sub BUILD {
Subroutine BUILD: called CC=3 SCAR=11.7
Pod undocumented
62 229 my ($self) = @_;
63 229 ▶ croak "Langertha::Content::Image requires url, base64, or data"
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_url or $self->has_base64 0 229 229
Condition66%2/3
$self->has_url or $self->has_base64
l!l&&r!l&&!r
177520
MC/DC0%0/2
$self->has_url or $self->has_base64
$self->has_url $self->has_base64
Truth table66%2/3
A or B
A= $self->has_urlB= $self->has_base64
ABresult
1X1
011
000
64 unless $self->has_url || $self->has_base64;
65 }
66  
67 # --- Constructors ---
68  
69 179 ▶sub from_url {
Subroutine from_url: called CC=6 SCAR=18.2
Pod documented
70 179 my ( $class, $url, %extra ) = @_;
71 179 ▶ croak "from_url requires a URL" unless defined $url && length $url;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $url and length $url 0 179 179
Condition33%1/3
defined $url and length $url
!ll&&!rl&&r
00179
MC/DC0%0/2
defined $url and length $url
defined $url length $url
Truth table33%1/3
A and B
A= defined $urlB= length $url
ABresult
0X0
100
111
72 179 ▶ $class->_check_fetch_scheme($url) unless _is_data_url($url);
Branch: 1 branch
BranchTrueFalseTotal
unless _is_data_url($url) 177 2 179
73 172 ▶ my $media_type = $extra{media_type} // _sniff_media_type($url);
Condition100%3/3
$extra{"media_type"} // _sniff_media_type($url)
l!l&&r!l&&!r
11647
MC/DC100%2/2
$extra{"media_type"} // _sniff_media_type($url)
$extra{"media_type"} _sniff_media_type($url)
Truth table100%3/3
A // B
A= $extra{"media_type"}B= _sniff_media_type($url)
ABresult
1X1
011
000
74 172 ▶ return $class->new(
Branch: 1 branch
BranchTrueFalseTotal
defined $media_type ? : 165 7 172
75 url => $url,
76 ( defined $media_type ? ( media_type => $media_type ) : () ),
77 _detail_arg(%extra),
78 );
79 }
80  
81  
82 1 ▶sub from_file {
Subroutine from_file: called CC=7 SCAR=21.5
Pod documented
83 1 my ( $class, $path, %extra ) = @_;
84 1 ▶ croak "from_file requires a path" unless defined $path && length $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path and length $path 0 1 1
Condition33%1/3
defined $path and length $path
!ll&&!rl&&r
001
MC/DC0%0/2
defined $path and length $path
defined $path length $path
Truth table33%1/3
A and B
A= defined $pathB= length $path
ABresult
0X0
100
111
85 1 ▶ croak "from_file: $path not found" unless -f $path;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $path 0 1 1
86 1 ▶ open my $fh, '<:raw', $path or croak "open $path: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $path or croak("open ${path}: $!") 1 0 1
87 1 my $bytes = do { local $/; <$fh> };
88 1 close $fh;
89 1 ▶ my $media_type = $extra{media_type} // _sniff_media_type($path);
Condition33%1/3
$extra{"media_type"} // _sniff_media_type($path)
l!l&&r!l&&!r
010
MC/DC0%0/2
$extra{"media_type"} // _sniff_media_type($path)
$extra{"media_type"} _sniff_media_type($path)
Truth table33%1/3
A // B
A= $extra{"media_type"}B= _sniff_media_type($path)
ABresult
1X1
011
000
90 1 ▶ croak "from_file: cannot determine media_type for $path"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $media_type 0 1 1
91 unless defined $media_type;
92 1 return $class->new(
93 base64 => encode_base64($bytes, ''),
94 media_type => $media_type,
95 _detail_arg(%extra),
96 );
97 }
98  
99  
100 3 ▶sub from_data {
Subroutine from_data: called CC=3 SCAR=11.4
Pod documented
101 3 my ( $class, $bytes, %extra ) = @_;
102 3 ▶ croak "from_data requires bytes" unless defined $bytes;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes 0 3 3
103 3 ▶ croak "from_data requires media_type" unless defined $extra{media_type};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $extra{"media_type"} 0 3 3
104 return $class->new(
105 base64 => encode_base64($bytes, ''),
106 media_type => $extra{media_type},
107 3 _detail_arg(%extra),
108 );
109 }
110  
111  
112 47 ▶sub from_base64 {
Subroutine from_base64: called CC=4 SCAR=15.6
Pod documented
113 47 my ( $class, $b64, %extra ) = @_;
114 47 ▶ croak "from_base64 requires a base64 string" unless defined $b64 && length $b64;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $b64 and length $b64 0 47 47
Condition33%1/3
defined $b64 and length $b64
!ll&&!rl&&r
0047
MC/DC0%0/2
defined $b64 and length $b64
defined $b64 length $b64
Truth table33%1/3
A and B
A= defined $b64B= length $b64
ABresult
0X0
100
111
115 47 ▶ croak "from_base64 requires media_type" unless defined $extra{media_type};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $extra{"media_type"} 0 47 47
116 return $class->new(
117 base64 => $b64,
118 media_type => $extra{media_type},
119 47 _detail_arg(%extra),
120 );
121 }
122  
123  
124 # --- Base64 materialization ---
125  
126 # timeout => N comes from the engine's inline_image_fetch_timeout on the
127 # request-build paths (karr k279). LWP cannot run without a timeout, so 0
128 # leaves LWP's own default (180s) in place. max_bytes / url_filter come from
129 # inline_image_max_bytes / inline_image_url_filter (karr k337).
130 115 ▶sub ensure_base64 {
Subroutine ensure_base64: called CC=6 SCAR=17.9
Pod documented
131 115 my ( $self, %opt ) = @_;
132 115 ▶ return $self->base64 if $self->has_base64;
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_base64 63 52 115
133 52 ▶ croak "ensure_base64: no url to fetch" unless $self->has_url;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_url 0 52 52
134 52 ▶ return $self->_inline_data_url if _is_data_url($self->url);
Branch: 1 branch
BranchTrueFalseTotal
if _is_data_url($self->url) 1 51 52
135 51 $self->_check_fetch_scheme($self->url);
136 49 my %limit = _fetch_limits(%opt);
137 49 $self->_check_url_filter( $self->url, $limit{url_filter} );
138  
139 46 ▶ my $secs = $opt{timeout} // 30;
Condition100%2/2
$opt{"timeout"} // 30
l!l
2125
MC/DC100%1/1
$opt{"timeout"} // 30
$opt{"timeout"}
Truth table100%2/2
A
A= $opt{"timeout"}
Aresult
11
00
140 46 require LWP::UserAgent;
141 46 my %state = ( checked => { _uri_key( $self->url ) => 1 } ); # vetted above
142 46 ▶ my $ua = $self->_guard_ua( LWP::UserAgent->new(
Branch: 1 branch
BranchTrueFalseTotal
$secs ? : 45 1 46
143 agent => 'Langertha-Content-Image/'.$VERSION,
144 ( $secs ? ( timeout => $secs ) : () ),
145 ), \%limit, \%state );
146 46 return $self->_inline_fetched( $ua->get($self->url), \%limit, \%state );
147 }
148  
149 # Async twin of ensure_base64 (karr k274): the GET goes through $http, any
150 # client with the async do_request contract (ADR 0027) -- the engine's
151 # _async_http on the _f paths, so a URL image never blocks the event loop on
152 # LWP. A transport failure and an error status fail the Future with the text
153 # ensure_base64 croaks.
154 100 ▶async sub ensure_base64_f {
Subroutine ensure_base64_f: called CC=10 SCAR=23.6
Pod documented
155 100 my ( $self, $http, %opt ) = @_;
156 100 ▶ return $self->base64 if $self->has_base64;
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_base64 0 100 100
157 100 ▶ croak "ensure_base64_f: no url to fetch" unless $self->has_url;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_url 0 100 100
158 100 ▶ return $self->_inline_data_url if _is_data_url($self->url);
Branch: 1 branch
BranchTrueFalseTotal
if _is_data_url($self->url) 1 99 100
159 99 $self->_check_fetch_scheme($self->url);
160 96 ▶ croak "ensure_base64_f requires a client with do_request"
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($http) and $http->can("do_request") 0 96 96
Condition33%1/3
builtin::blessed($http) and $http->can("do_request")
!ll&&!rl&&r
0096
MC/DC0%0/2
builtin::blessed($http) and $http->can("do_request")
builtin::blessed($http) $http->can("do_request")
Truth table33%1/3
A and B
A= builtin::blessed($http)B= $http->can("do_request")
ABresult
0X0
100
111
161 unless blessed($http) && $http->can('do_request');
162 96 my %limit = _fetch_limits(%opt);
163 96 $self->_check_url_filter( $self->url, $limit{url_filter} );
164  
165 88 my %state = ( checked => { _uri_key( $self->url ) => 1 } ); # vetted above
166 88 ▶ if ( $http->isa('Net::Async::HTTP') ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($http->isa("Net::Async::HTTP")) 33 55 88
167 33 my $response = await $self->_fetch_net_async_f( $http, \%limit );
168 19 return $self->_inline_fetched( $response, \%limit, \%state );
169 }
170 # The sync LWP shim runs the engine's own user_agent, which allows every
171 # scheme LWP knows and has no size cap: fetch through a copy guarded like
172 # ensure_base64's agent (karr k325, k337).
173 55 ▶ if ( $http->isa('Langertha::Request::SyncHTTP')
Branch: 1 branch
BranchTrueFalseTotal
if ($http->isa('Langertha::Request::SyncHTTP') and builtin::blessed($http->user_agent) and $http->user_agent->isa('LWP::UserAgent')) { } 27 28 55
Condition66%4/6
$http->isa("Langertha::Request::SyncHTTP") and builtin::blessed($http->user_agent) and $http->user_agent->isa("LWP::UserAgent")
!ll&&!rl&&r
28027
$http->isa("Langertha::Request::SyncHTTP") and builtin::blessed($http->user_agent)
!ll&&!rl&&r
28027
MC/DC33%1/3
$http->isa("Langertha::Request::SyncHTTP") and builtin::blessed($http->user_agent) and $http->user_agent->isa("LWP::UserAgent")
$http->isa("Langertha::Request::SyncHTTP") builtin::blessed($http->user_agent) $http->user_agent->isa("LWP::UserAgent")
Truth table50%2/4
A and B and C
A= $http->isa("Langertha::Request::SyncHTTP")B= builtin::blessed($http->user_agent)C= $http->user_agent->isa("LWP::UserAgent")
ABCresult
0XX0
10X0
1100
1111
174 && blessed( $http->user_agent ) && $http->user_agent->isa('LWP::UserAgent') ) {
175 27 $http = Langertha::Request::SyncHTTP->new(
176 user_agent => $self->_guard_ua( $http->user_agent->clone, \%limit, \%state ) );
177 }
178 else {
179 # Any other client follows redirects on its own terms: its chain is
180 # checked after the fact, and nothing from a refused hop is stored.
181 28 $state{check_chain} = 1;
182 }
183  
184 55 my $response = await $self->_fetch_one_f( $http, $self->url );
185 54 return $self->_inline_fetched( $response, \%limit, \%state );
186 17 }
187  
188 # One GET through the async contract; a transport failure fails with the text
189 # ensure_base64 croaks.
190 90 ▶sub _fetch_one_f {
Subroutine _fetch_one_f: called CC=3 SCAR=11.0
191 90 my ( $self, $http, $url, %args ) = @_;
192 90 require HTTP::Request;
193 90 my $request = HTTP::Request->new( GET => $url,
194 [ 'User-Agent' => 'Langertha-Content-Image/'.$VERSION ] );
195 90 my $orig = $self->url;
196 # The Net::Async::HTTP connect-module check of Role::AsyncHTTP: a module that
197 # fails to load at connect time would wedge the host's slot (karr k353).
198 90 ▶ if ( $http->isa('Net::Async::HTTP') ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($http->isa("Net::Async::HTTP")) 35 55 90
199 35 require Langertha::HTTP::ConnectCheck;
200 35 my $error = Langertha::HTTP::ConnectCheck::connect_error($url);
201 35 ▶ return Future->fail("ensure_base64: failed to fetch $orig: $error\n") if $error;
Branch: 1 branch
BranchTrueFalseTotal
if $error 1 34 35
202 }
203 2 ▶ return $http->do_request( request => $request, %args )->else( sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
204 2 my ($err) = @_;
205 2 $err =~ s/\s+\z//;
206 2 Future->fail("ensure_base64: failed to fetch $orig: $err\n");
207 89 } );
208 }
209  
210 # Net::Async::HTTP (karr k337). Redirects are followed here, one hop at a
211 # time with max_redirects => 0, so the scheme rule and the url filter see
212 # every hop before it is requested. The body streams through on_header and is
213 # counted; past the cap the request is abandoned: wait_any cancels it, which
214 # closes the connection. That abort waits for the loop's next tick, because
215 # the chunk callback runs inside the connection's read handler, where closing
216 # the connection is not safe; a response that completes within the same read
217 # is refused by the flag instead.
218 33 ▶async sub _fetch_net_async_f {
Subroutine _fetch_net_async_f: called CC=8 SCAR=20.8
219 33 my ( $self, $http, $limit ) = @_;
220 33 require URI;
221 33 my $max = $limit->{max_bytes};
222 33 my $uri = URI->new( $self->url );
223 33 my $previous;
224 33 for my $hop ( 0 .. $MAX_REDIRECTS ) {
225 35 my $too_big;
226 35 my $abort = Future->new;
227 31 ▶ my %stream = $max ? ( on_header => sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
228 31 my ($header) = @_;
229 7 ▶ my $trip = sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
230 7 ▶ return if $too_big++;
Branch: 1 branch
BranchTrueFalseTotal
if $too_big++ 0 7 7
231 7 ▶ $http->loop->later( sub { $abort->done unless $abort->is_ready } );
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
unless $abort->is_ready 2 5 7
232 31 };
233 31 my $length = $header->content_length;
234 31 ▶ $trip->() if $header->is_success && defined $length && $length > $max;
Branch: 1 branch
BranchTrueFalseTotal
if $header->is_success and defined $length and $length > $max 3 28 31
Condition100%6/6
$header->is_success and defined $length and $length > $max
!ll&&!rl&&r
9193
$header->is_success and defined $length
!ll&&!rl&&r
7222
MC/DC100%3/3
$header->is_success and defined $length and $length > $max
$header->is_success defined $length $length > $max
Truth table100%4/4
A and B and C
A= $header->is_successB= defined $lengthC= $length > $max
ABCresult
0XX0
10X0
1100
1111
235 76 ▶ return sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
236 76 ▶ return $header unless @_;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 28 48 76
237 48 ▶ return if $too_big;
Branch: 1 branch
BranchTrueFalseTotal
if $too_big 16 32 48
238 32 ▶ $header->add_content( $_[0] ) if defined $_[0];
Branch: 1 branch
BranchTrueFalseTotal
if defined $_[0] 32 0 32
239 32 ▶ $trip->() if length( ${ $header->content_ref } ) > $max;
Branch: 1 branch
BranchTrueFalseTotal
if length ${$header->content_ref;} > $max 4 28 32
240 32 return;
241 31 };
242 35 ▶ } ) : ();
Branch: 1 branch
BranchTrueFalseTotal
$max ? : 33 2 35
243 # Over the cap, whatever ends the fetch (the abort, or the server closing
244 # the connection first) ends in the size error.
245 my $response = await Future->wait_any(
246 $self->_fetch_one_f( $http, "$uri", max_redirects => 0, %stream ), $abort,
247 35 ▶ )->else( sub { $too_big ? Future->done : Future->fail(@_) } );
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
$too_big ? : 0 2 2
248 32 ▶ $self->_croak_too_big($max) if $too_big;
Branch: 1 branch
BranchTrueFalseTotal
if $too_big 7 25 32
249 25 ▶ $response->previous($previous) if $previous;
Branch: 1 branch
BranchTrueFalseTotal
if $previous 2 23 25
250 25 ▶ my $location = $response->is_redirect && $response->header('Location');
Condition66%2/3
$response->is_redirect && $response->header('Location')
!ll&&!rl&&r
1906
MC/DC50%1/2
$response->is_redirect && $response->header('Location')
$response->is_redirect $response->header('Location')
Truth table66%2/3
A && B
A= $response->is_redirectB= $response->header('Location')
ABresult
0X0
100
111
251 25 ▶ return $response unless $location && $hop < $MAX_REDIRECTS;
Branch: 1 branch
BranchTrueFalseTotal
unless $location and $hop < $MAX_REDIRECTS 19 6 25
Condition66%2/3
$location and $hop < $MAX_REDIRECTS
!ll&&!rl&&r
1906
MC/DC50%1/2
$location and $hop < $MAX_REDIRECTS
$location $hop < $MAX_REDIRECTS
Truth table66%2/3
A and B
A= $locationB= $hop < $MAX_REDIRECTS
ABresult
0X0
100
111
252 6 $uri = URI->new_abs( $location, $uri );
253 6 $self->_check_fetch_scheme("$uri");
254 4 $self->_check_url_filter( "$uri", $limit->{url_filter} );
255 2 $previous = $response;
256 }
257 0 return; # not reached: the last hop returns above
258 17 }
259  
260 # Stores a fetched HTTP::Response as the inline payload (both doors above).
261 119 ▶sub _inline_fetched {
Subroutine _inline_fetched: called CC=23 SCAR=31.6
262 119 my ( $self, $response, $limit, $state ) = @_;
263 119 ▶ $self->_refuse_url( @{$state}{qw( refused filter_error )} ) if $state->{refused};
Branch: 1 branch
BranchTrueFalseTotal
if $state->{"refused"} 4 115 119
264 115 ▶ croak "ensure_base64: failed to fetch ".$self->url.": ".$response->status_line
Branch: 1 branch
BranchTrueFalseTotal
unless $response->is_success 13 102 115
265 unless $response->is_success;
266 # LWP stops at max_size (Client-Aborted) or at the Content-Length check of
267 # _guard_ua (X-Died); a body from any other client is measured here (k337).
268 102 my $max = $limit->{max_bytes};
269 102 my $died = $response->header('X-Died');
270 $self->_croak_too_big($max) if $max && ( $state->{too_big}
271 || ( $response->header('Client-Aborted') // '' ) eq 'max_size'
272 || ( $response->content_length // 0 ) > $max
273 102 ▶ || length( ${ $response->content_ref } ) > $max );
Branch: 1 branch
BranchTrueFalseTotal
if $max and $state->{"too_big"} || ($response->header("Client-Aborted") // "") eq "max_size" || ($response->content_length // 0) > $max || length ${$response->content_ref;} > $max 14 88 102
Condition100%16/16
$max and $state->{"too_big"} || ($response->header("Client-Aborted") // "") eq "max_size" || ($response->content_length // 0) > $max || length ${$response->content_ref;} > $max
!ll&&!rl&&r
88014
$state->{"too_big"} or ($response->header("Client-Aborted") // "") eq "max_size" or ($response->content_length // 0) > $max or length ${$response->content_ref;} > $max
l!l&&r!l&&!r
12280
$state->{"too_big"} or ($response->header("Client-Aborted") // "") eq "max_size" or ($response->content_length // 0) > $max
l!l&&r!l&&!r
10282
$state->{"too_big"} or ($response->header("Client-Aborted") // "") eq "max_size"
l!l&&r!l&&!r
6484
$response->header("Client-Aborted") // ""
l!l
484
$response->content_length // 0
l!l
6618
MC/DC100%5/5
$max and $state->{"too_big"} || ($response->header("Client-Aborted") // "") eq "max_size" || ($response->content_length // 0) > $max || length ${$response->content_ref;} > $max
$max $state->{"too_big"} $response->header("Client-Aborted") $response->content_length length ${$response->content_ref;} > $max
Truth table100%6/6
A and B or C or D or E
A= $maxB= $state->{"too_big"}C= $response->header("Client-Aborted")D= $response->content_lengthE= length ${$response->content_ref;} > $max
ABCDEresult
0XXXX0
100000
11XXX1
101XX1
1001X1
100011
274 88 ▶ croak "ensure_base64: failed to fetch ".$self->url.": $died" if defined $died;
Branch: 1 branch
BranchTrueFalseTotal
if defined $died 0 88 88
275 # Whatever client ran the fetch, a body that came from another scheme (a
276 # redirect it followed) is never stored (karr k325).
277 88 ▶ my $final = $response->request && $response->request->uri;
Condition66%2/3
$response->request && $response->request->uri
!ll&&!rl&&r
16072
MC/DC50%1/2
$response->request && $response->request->uri
$response->request $response->request->uri
Truth table66%2/3
A && B
A= $response->requestB= $response->request->uri
ABresult
0X0
100
111
278 88 ▶ $self->_check_fetch_scheme("$final") if defined $final;
Branch: 1 branch
BranchTrueFalseTotal
if defined $final 72 16 88
279 # A client that followed redirects on its own: every hop it took must pass
280 # the url filter too, or nothing is stored (karr k337).
281 88 ▶ if ( $limit->{url_filter} && $state->{check_chain} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($limit->{"url_filter"} and $state->{"check_chain"}) 2 86 88
Condition100%3/3
$limit->{"url_filter"} and $state->{"check_chain"}
!ll&&!rl&&r
8062
MC/DC100%2/2
$limit->{"url_filter"} and $state->{"check_chain"}
$limit->{"url_filter"} $state->{"check_chain"}
Truth table100%3/3
A and B
A= $limit->{"url_filter"}B= $state->{"check_chain"}
ABresult
0X0
100
111
282 2 my @chain;
283 2 ▶ for ( my $hop = $response; $hop; $hop = $hop->previous ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hop) 4 2 6
284 4 ▶ unshift @chain, $hop->request->uri if $hop->request && $hop->request->uri;
Branch: 1 branch
BranchTrueFalseTotal
if $hop->request and $hop->request->uri 4 0 4
Condition33%1/3
$hop->request and $hop->request->uri
!ll&&!rl&&r
004
MC/DC0%0/2
$hop->request and $hop->request->uri
$hop->request $hop->request->uri
Truth table33%1/3
A and B
A= $hop->requestB= $hop->request->uri
ABresult
0X0
100
111
285 }
286 2 for my $hop (@chain) {
287 $self->_check_url_filter( "$hop", $limit->{url_filter} )
288 4 ▶ unless $state->{checked}{ _uri_key($hop) }++;
Branch: 1 branch
BranchTrueFalseTotal
unless $state->{"checked"}{_uri_key($hop)}++ 2 2 4
289 }
290 }
291  
292 87 $self->base64( encode_base64( $self->_decoded_body( $response, $max ), '' ) );
293 66 ▶ unless ($self->has_media_type) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->has_media_type) 5 61 66
294 5 ▶ my $ct = $response->header('Content-Type') // '';
Condition50%1/2
$response->header("Content-Type") // ""
l!l
50
MC/DC0%0/1
$response->header("Content-Type") // ""
$response->header("Content-Type")
Truth table50%1/2
A
A= $response->header("Content-Type")
Aresult
11
00
295 5 $ct =~ s/;.*$//;
296 5 $ct =~ s/^\s+|\s+$//g;
297 5 ▶ $self->media_type($ct) if length $ct;
Branch: 1 branch
BranchTrueFalseTotal
if length $ct 5 0 5
298 }
299 66 return $self->base64;
300 }
301  
302 # The body with its Content-Encoding undone (karr k342). The cap above counts
303 # the bytes on the wire; a compressed body is inflated in blocks and refused as
304 # soon as its decoded size passes the cap, so a small gzip body cannot expand to
305 # gigabytes in memory. No backend is trusted to have decoded it: Net::Async::HTTP
306 # decodes (and counts) only the encodings it knows and leaves the rest here.
307 # Without a cap, HTTP::Message decodes as before. The bounded inflate itself is
308 # shared with the provider/metrics decoders (Langertha::HTTP::BoundedDecode,
309 # karr k346); the image-flavoured error text stays here through the handlers.
310 87 ▶sub _decoded_body {
Subroutine _decoded_body: called CC=2 SCAR=7.0
311 87 my ( $self, $response, $max ) = @_;
312 87 ▶ return $response->decoded_content( charset => 'none' ) unless $max;
Branch: 1 branch
BranchTrueFalseTotal
unless $max 8 79 87
313 79 require Langertha::HTTP::BoundedDecode;
314 return Langertha::HTTP::BoundedDecode::decode_within(
315 $response->content, scalar $response->header('Content-Encoding'), $max, {
316 17 ▶ too_big => sub { $self->_croak_too_big( $_[0] ) },
Subroutine __ANON__: called CC=1 SCAR=0.0
317 0 ▶ undecodable => sub { $self->_undecodable( $_[0] ) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
318 4 ▶ unbounded_encoding => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
319 4 croak "ensure_base64: failed to fetch ".$self->url
320 . ": cannot decode Content-Encoding '$_[0]' within inline_image_max_bytes";
321 },
322 79 } );
323 }
324  
325 0 ▶sub _undecodable {
Subroutine _undecodable: not called CC=1 SCAR=6.9
326 0 my ( $self, $encoding ) = @_;
327 0 croak "ensure_base64: failed to fetch ".$self->url.": cannot decode Content-Encoding '$encoding'";
328 }
329  
330 # max_bytes (undef: the default cap, 0: none) and url_filter out of the
331 # ensure_base64(_f) options.
332 145 ▶sub _fetch_limits {
Subroutine _fetch_limits: called CC=4 SCAR=14.1
333 145 my (%opt) = @_;
334 145 my $filter = $opt{url_filter};
335 145 ▶ croak "url_filter must be a CODE reference" if defined $filter && ref $filter ne 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if defined $filter and ref $filter ne "CODE" 0 145 145
Condition66%2/3
defined $filter and ref $filter ne "CODE"
!ll&&!rl&&r
120250
MC/DC0%0/2
defined $filter and ref $filter ne "CODE"
defined $filter ref $filter ne "CODE"
Truth table66%2/3
A and B
A= defined $filterB= ref $filter ne "CODE"
ABresult
0X0
100
111
336 145 ▶ return ( max_bytes => $opt{max_bytes} // DEFAULT_MAX_BYTES, url_filter => $filter );
Condition100%2/2
$opt{"max_bytes"} // 20971520
l!l
10540
MC/DC100%1/1
$opt{"max_bytes"} // 20971520
$opt{"max_bytes"}
Truth table100%2/2
A
A= $opt{"max_bytes"}
Aresult
11
00
337 }
338  
339 # The LWP agent of a fetch, guarded (karr k325, k337): only http/https, also
340 # on redirects; max_size stops reading past the cap, and a Content-Length over
341 # it stops before the body; request_prepare runs for the first request and for
342 # every redirect hop before it connects, so a hop the url filter refuses is
343 # never requested. LWP turns a die in either handler into a response (X-Died,
344 # or a 400), so the verdict is kept in $state for _inline_fetched. A handler
345 # rather than a redirect_ok override: that would mean reblessing the clone of
346 # the engine's user_agent into a generated subclass.
347 73 ▶sub _guard_ua {
Subroutine _guard_ua: called CC=3 SCAR=11.0
348 73 my ( $self, $ua, $limit, $state ) = @_;
349 73 $ua->protocols_allowed([@FETCH_SCHEMES]);
350 73 ▶ if ( my $max = $limit->{max_bytes} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $max = $limit->{"max_bytes"}) 69 4 73
351 69 $ua->max_size($max);
352 45 ▶ $ua->add_handler( response_header => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
353 45 my ($response) = @_;
354 45 my $length = $response->content_length;
355 45 ▶ return unless defined $length && $length > $max;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $length and $length > $max 39 6 45
Condition100%3/3
defined $length and $length > $max
!ll&&!rl&&r
4356
MC/DC100%2/2
defined $length and $length > $max
defined $length $length > $max
Truth table100%3/3
A and B
A= defined $lengthB= $length > $max
ABresult
0X0
100
111
356 6 $state->{too_big} = 1;
357 6 die "inline_image_max_bytes exceeded\n";
358 69 }, m_code => 2 );
359 }
360 73 ▶ if ( my $filter = $limit->{url_filter} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $filter = $limit->{"url_filter"}) 8 65 73
361 14 ▶ $ua->add_handler( request_prepare => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
362 14 my ($request) = @_;
363 14 ▶ return if $state->{checked}{ _uri_key( $request->uri ) }++;
Branch: 1 branch
BranchTrueFalseTotal
if $state->{"checked"}{_uri_key($request->uri)}++ 8 6 14
364 6 my ( $ok, $error ) = _filter_verdict( $filter, $request->uri );
365 6 ▶ return if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 2 4 6
366 4 @{$state}{qw( refused filter_error )} = ( $request->uri->as_string, $error );
367 4 die "refused by inline_image_url_filter\n";
368 8 } );
369 }
370 73 return $ua;
371 }
372  
373 # (allowed, error) for one URL: the filter gets a URI object and returns true
374 # to allow; a filter that dies refuses, and its error is reported.
375 36 ▶sub _filter_verdict {
Subroutine _filter_verdict: called CC=3 SCAR=11.0
376 36 my ( $filter, $url ) = @_;
377 36 require URI;
378 36 my $ok;
379 36 ▶ return ( 0, $@ =~ s/\s+\z//r ) unless eval { $ok = $filter->( URI->new("$url") ); 1 };
Branch: 1 branch
BranchTrueFalseTotal
unless eval { do { $ok = &$filter("URI"->new("$url")); 1 } } 4 32 36
380 32 ▶ return ( $ok ? 1 : 0, undef );
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 18 14 32
381 }
382  
383 # A URL's canonical string, so a URL the filter already passed is not asked
384 # (and resolved) twice.
385 152 ▶sub _uri_key {
Subroutine _uri_key: called CC=1 SCAR=0.0
386 152 require URI;
387 152 return URI->new("$_[0]")->canonical->as_string;
388 }
389  
390 151 ▶sub _check_url_filter {
Subroutine _check_url_filter: called CC=3 SCAR=11.0
391 151 my ( $self, $url, $filter ) = @_;
392 151 ▶ return unless $filter;
Branch: 1 branch
BranchTrueFalseTotal
unless $filter 121 30 151
393 30 my ( $ok, $error ) = _filter_verdict( $filter, $url );
394 30 ▶ $self->_refuse_url( $url, $error ) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 14 16 30
395 16 return;
396 }
397  
398 18 ▶sub _refuse_url {
Subroutine _refuse_url: called CC=3 SCAR=11.4
399 18 my ( $self, $url, $error ) = @_;
400 18 ▶ my $class = ref $self || $self;
Condition33%1/3
ref $self || $self
l!l&&r!l&&!r
1800
MC/DC0%0/2
ref $self || $self
ref $self $self
Truth table33%1/3
A || B
A= ref $selfB= $self
ABresult
1X1
011
000
401 18 ▶ croak "$class refuses to fetch image URL $url: "
Branch: 1 branch
BranchTrueFalseTotal
defined $error ? : 4 14 18
402 . ( defined $error ? "inline_image_url_filter died: $error" : 'rejected by inline_image_url_filter' );
403 }
404  
405 38 ▶sub _croak_too_big {
Subroutine _croak_too_big: called CC=2 SCAR=7.6
406 38 my ( $self, $max ) = @_;
407 38 ▶ my $class = ref $self || $self;
Condition33%1/3
ref $self || $self
l!l&&r!l&&!r
3800
MC/DC0%0/2
ref $self || $self
ref $self $self
Truth table33%1/3
A || B
A= ref $selfB= $self
ABresult
1X1
011
000
408 38 croak "$class image at ".$self->url." exceeds inline_image_max_bytes ($max)";
409 }
410  
411  
412  
413 # --- SSRF filter (karr k337) ---
414  
415 6 ▶sub deny_private_hosts {
Subroutine deny_private_hosts: called CC=3 SCAR=11.1
Pod documented
416 6 my ( $class, %opt ) = @_;
417 6 ▶ my $resolver = $opt{resolver} // \&_resolve_host;
Condition100%2/2
$opt{"resolver"} // \&Langertha::Content::Image::_resolve_host
l!l
24
MC/DC100%1/1
$opt{"resolver"} // \&Langertha::Content::Image::_resolve_host
$opt{"resolver"}
Truth table100%2/2
A
A= $opt{"resolver"}
Aresult
11
00
418 6 ▶ croak "deny_private_hosts: resolver must be a CODE reference" unless ref $resolver eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $resolver eq "CODE" 0 6 6
419 88 ▶ return sub {
Subroutine __ANON__: called CC=6 SCAR=18.2
420 88 my ($uri) = @_;
421 88 my $host = eval { $uri->host };
422 88 ▶ return 0 unless defined $host && length $host;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $host and length $host 0 88 88
Condition33%1/3
defined $host and length $host
!ll&&!rl&&r
0088
MC/DC0%0/2
defined $host and length $host
defined $host length $host
Truth table33%1/3
A and B
A= defined $hostB= length $host
ABresult
0X0
100
111
423 88 my @addresses = $resolver->($host);
424 88 ▶ return 0 unless @addresses;
Branch: 1 branch
BranchTrueFalseTotal
unless @addresses 1 87 88
425 87 for my $address (@addresses) {
426 88 ▶ return 0 if _is_private_address($address);
Branch: 1 branch
BranchTrueFalseTotal
if _is_private_address($address) 59 29 88
427 }
428 28 return 1;
429 6 };
430 }
431  
432  
433 7 ▶sub _resolve_host {
Subroutine _resolve_host: called CC=4 SCAR=14.0
434 7 my ($host) = @_;
435 7 my ( $err, @found ) = getaddrinfo( $host, undef, { socktype => SOCK_STREAM } );
436 7 ▶ return () if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 7 7
437 7 my @addresses;
438 7 for my $entry (@found) {
439 7 my ( $name_err, $ip ) = getnameinfo( $entry->{addr}, NI_NUMERICHOST, NIx_NOSERV );
440 7 ▶ push @addresses, $ip unless $name_err;
Branch: 1 branch
BranchTrueFalseTotal
unless $name_err 7 0 7
441 }
442 7 return @addresses;
443 }
444  
445 # True for an address on an internal network (the deny_private_hosts list),
446 # and for anything that does not parse as an IP address.
447 88 ▶sub _is_private_address {
Subroutine _is_private_address: called CC=16 SCAR=27.8
448 88 my ($address) = @_;
449 88 ▶ ( my $ip = $address // '' ) =~ s/%.*\z//s; # IPv6 zone index
Condition50%1/2
$address // ""
l!l
880
MC/DC0%0/1
$address // ""
$address
Truth table50%1/2
A
A= $address
Aresult
11
00
450 88 $ip =~ s/\A\[(.*)\]\z/$1/;
451 88 ▶ if ( defined( my $v4 = inet_pton( AF_INET, $ip ) ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $v4 = inet_pton(2, $ip))) 48 40 88
452 48 return _is_private_v4($v4);
453 }
454 40 my $v6 = inet_pton( AF_INET6, $ip );
455 40 ▶ return 1 unless defined $v6;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v6 0 40 40
456 40 my $head = substr $v6, 0, 12;
457 40 ▶ return _is_private_v4( substr $v6, 12 ) if $head eq ( "\0" x 10 ) . "\xff\xff";
Branch: 1 branch
BranchTrueFalseTotal
if $head eq "\0\0\0\0\0\0\0\0\0\0\377\377" 3 37 40
458 37 ▶ return 1 if $head eq "\0" x 12;
Branch: 1 branch
BranchTrueFalseTotal
if $head eq "\0\0\0\0\0\0\0\0\0\0\0\0" 4 33 37
459 # IPv4 addresses a gateway translates to (karr k343): SIIT ::ffff:0:0:0/96,
460 # NAT64 64:ff9b::/96 and the local-use 64:ff9b:1::/48 (RFC 8215), and 6to4
461 # 2002::/16. A local NAT64 address outside the /96 layout does not say where
462 # its IPv4 address sits, so it is refused outright.
463 33 ▶ return _is_private_v4( substr $v6, 12 )
Branch: 1 branch
BranchTrueFalseTotal
if $head eq "\0\0\0\0\0\0\0\0\377\377\0\0" or $head eq "\0d\377\233\0\0\0\0\0\0\0\0" 9 24 33
Condition100%3/3
$head eq "\0\0\0\0\0\0\0\0\377\377\0\0" or $head eq "\0d\377\233\0\0\0\0\0\0\0\0"
l!l&&r!l&&!r
4524
MC/DC100%2/2
$head eq "\0\0\0\0\0\0\0\0\377\377\0\0" or $head eq "\0d\377\233\0\0\0\0\0\0\0\0"
$head eq "\0\0\0\0\0\0\0\0\377\377\0\0" $head eq "\0d\377\233\0\0\0\0\0\0\0\0"
Truth table100%3/3
A or B
A= $head eq "\0\0\0\0\0\0\0\0\377\377\0\0"B= $head eq "\0d\377\233\0\0\0\0\0\0\0\0"
ABresult
1X1
011
000
464 if $head eq ( "\0" x 8 ) . "\xff\xff\0\0"
465 || $head eq "\0\x64\xff\x9b" . ( "\0" x 8 );
466 24 ▶ if ( substr( $v6, 0, 6 ) eq "\0\x64\xff\x9b\0\x01" ) {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($v6, 0, 6) eq "\0d\377\233\0\1") 5 19 24
467 5 ▶ return 1 unless substr( $v6, 6, 6 ) eq "\0" x 6;
Branch: 1 branch
BranchTrueFalseTotal
unless substr($v6, 6, 6) eq "\0\0\0\0\0\0" 2 3 5
468 3 return _is_private_v4( substr $v6, 12 );
469 }
470 19 ▶ return _is_private_v4( substr $v6, 2, 4 ) if substr( $v6, 0, 2 ) eq "\x20\x02";
Branch: 1 branch
BranchTrueFalseTotal
if substr($v6, 0, 2) eq " \2" 5 14 19
471 # Teredo 2001:0000::/32 (RFC 4380, karr k346): the client's IPv4 sits in the
472 # last 32 bits, obfuscated (bit-inverted), so it cannot be re-checked like
473 # 6to4 or NAT64 above -- refuse the whole prefix outright. A non-Teredo
474 # 2001::/16 address (2001:db8::, 2001:4860::, ...) does not match and passes.
475 14 ▶ return 1 if substr( $v6, 0, 4 ) eq "\x20\x01\0\0";
Branch: 1 branch
BranchTrueFalseTotal
if substr($v6, 0, 4) eq " \1\0\0" 4 10 14
476 10 my ( $first, $second ) = unpack 'C2', $v6;
477 10 ▶ return 1 if ( $first & 0xfe ) == 0xfc; # fc00::/7
Branch: 1 branch
BranchTrueFalseTotal
if ($first & 254) == 252 2 8 10
478 8 ▶ return 1 if $first == 0xfe && ( $second & 0x80 ) == 0x80; # fe80::/10, fec0::/10
Branch: 1 branch
BranchTrueFalseTotal
if $first == 254 and ($second & 128) == 128 2 6 8
Condition66%2/3
$first == 254 and ($second & 128) == 128
!ll&&!rl&&r
602
MC/DC50%1/2
$first == 254 and ($second & 128) == 128
$first == 254 ($second & 128) == 128
Truth table66%2/3
A and B
A= $first == 254B= ($second & 128) == 128
ABresult
0X0
100
111
479 6 ▶ return 1 if $first == 0xff; # ff00::/8
Branch: 1 branch
BranchTrueFalseTotal
if $first == 255 1 5 6
480 5 return 0;
481 }
482  
483 68 ▶sub _is_private_v4 {
Subroutine _is_private_v4: called CC=18 SCAR=28.9
484 68 my ($packed) = @_;
485 68 my ( $first, $second ) = unpack 'C2', $packed;
486 68 ▶ return 1 if $first == 0 || $first == 10 || $first == 127;
Branch: 1 branch
BranchTrueFalseTotal
if $first == 0 or $first == 10 or $first == 127 21 47 68
Condition100%6/6
$first == 0 or $first == 10 or $first == 127
l!l&&r!l&&!r
81347
$first == 0 or $first == 10
l!l&&r!l&&!r
1760
MC/DC100%3/3
$first == 0 or $first == 10 or $first == 127
$first == 0 $first == 10 $first == 127
Truth table100%4/4
A or B or C
A= $first == 0B= $first == 10C= $first == 127
ABCresult
1XX1
01X1
0011
0000
487 47 ▶ return 1 if $first == 169 && $second == 254;
Branch: 1 branch
BranchTrueFalseTotal
if $first == 169 and $second == 254 7 40 47
Condition66%2/3
$first == 169 and $second == 254
!ll&&!rl&&r
4007
MC/DC50%1/2
$first == 169 and $second == 254
$first == 169 $second == 254
Truth table66%2/3
A and B
A= $first == 169B= $second == 254
ABresult
0X0
100
111
488 40 ▶ return 1 if $first == 172 && ( $second & 0xf0 ) == 16;
Branch: 1 branch
BranchTrueFalseTotal
if $first == 172 and ($second & 240) == 16 2 38 40
Condition100%3/3
$first == 172 and ($second & 240) == 16
!ll&&!rl&&r
3622
MC/DC100%2/2
$first == 172 and ($second & 240) == 16
$first == 172 ($second & 240) == 16
Truth table100%3/3
A and B
A= $first == 172B= ($second & 240) == 16
ABresult
0X0
100
111
489 38 ▶ return 1 if $first == 192 && $second == 168;
Branch: 1 branch
BranchTrueFalseTotal
if $first == 192 and $second == 168 3 35 38
Condition100%3/3
$first == 192 and $second == 168
!ll&&!rl&&r
3053
MC/DC100%2/2
$first == 192 and $second == 168
$first == 192 $second == 168
Truth table100%3/3
A and B
A= $first == 192B= $second == 168
ABresult
0X0
100
111
490 35 ▶ return 1 if $first == 192 && $second == 0 && unpack( 'x2 C', $packed ) == 0; # 192.0.0.0/24
Branch: 1 branch
BranchTrueFalseTotal
if $first == 192 and $second == 0 and unpack("x2 C", $packed) == 0 3 32 35
Condition100%6/6
$first == 192 and $second == 0 and unpack("x2 C", $packed) == 0
!ll&&!rl&&r
3113
$first == 192 and $second == 0
!ll&&!rl&&r
3014
MC/DC100%3/3
$first == 192 and $second == 0 and unpack("x2 C", $packed) == 0
$first == 192 $second == 0 unpack("x2 C", $packed) == 0
Truth table100%4/4
A and B and C
A= $first == 192B= $second == 0C= unpack("x2 C", $packed) == 0
ABCresult
0XX0
10X0
1100
1111
491 32 ▶ return 1 if $first == 198 && ( $second & 0xfe ) == 18; # 198.18.0.0/15
Branch: 1 branch
BranchTrueFalseTotal
if $first == 198 and ($second & 254) == 18 2 30 32
Condition100%3/3
$first == 198 and ($second & 254) == 18
!ll&&!rl&&r
2822
MC/DC100%2/2
$first == 198 and ($second & 254) == 18
$first == 198 ($second & 254) == 18
Truth table100%3/3
A and B
A= $first == 198B= ($second & 254) == 18
ABresult
0X0
100
111
492 30 ▶ return 1 if $first == 100 && ( $second & 0xc0 ) == 64;
Branch: 1 branch
BranchTrueFalseTotal
if $first == 100 and ($second & 192) == 64 2 28 30
Condition100%3/3
$first == 100 and ($second & 192) == 64
!ll&&!rl&&r
2622
MC/DC100%2/2
$first == 100 and ($second & 192) == 64
$first == 100 ($second & 192) == 64
Truth table100%3/3
A and B
A= $first == 100B= ($second & 192) == 64
ABresult
0X0
100
111
493 28 ▶ return 1 if $first >= 224;
Branch: 1 branch
BranchTrueFalseTotal
if $first >= 224 4 24 28
494 24 return 0;
495 }
496  
497 # --- Serializers ---
498  
499 37 ▶sub data_url {
Subroutine data_url: called CC=2 SCAR=7.1
Pod documented
500 37 my ($self) = @_;
501 37 $self->ensure_base64;
502 37 ▶ return sprintf('data:%s;base64,%s',
Condition50%1/2
$self->media_type // "application/octet-stream"
l!l
370
MC/DC0%0/1
$self->media_type // "application/octet-stream"
$self->media_type
Truth table50%1/2
A
A= $self->media_type
Aresult
11
00
503 ($self->media_type // 'application/octet-stream'),
504 $self->base64,
505 );
506 }
507  
508  
509 # The image as one string for wires that take "URL or data URL" in one field.
510 # inline => 1 forces the data URL (fetching a URL-only image first, like
511 # to_gemini) for endpoints that reject remote image URLs (karr k267).
512 47 ▶sub _url_or_data_url {
Subroutine _url_or_data_url: called CC=3 SCAR=11.0
513 47 my ( $self, %opt ) = @_;
514 47 ▶ return $self->url if $self->has_url && !$opt{inline};
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_url and not $opt{"inline"} 17 30 47
Condition100%3/3
$self->has_url and not $opt{"inline"}
!ll&&!rl&&r
151517
MC/DC100%2/2
$self->has_url and not $opt{"inline"}
$self->has_url not $opt{"inline"}
Truth table100%3/3
A and not(B)
A= $self->has_urlB= not $opt{"inline"}
ABresult
0X0
100
111
515 30 return $self->data_url;
516 }
517  
518 36 ▶sub to_openai {
Subroutine to_openai: called CC=2 SCAR=6.9
Pod documented
519 36 my ( $self, %opt ) = @_;
520 36 ▶ return { type => 'image_url', image_url => {
Branch: 1 branch
BranchTrueFalseTotal
$self->has_detail ? : 2 34 36
521 url => $self->_url_or_data_url(%opt),
522 ( $self->has_detail ? ( detail => $self->detail ) : () ),
523 } };
524 }
525  
526  
527 11 ▶sub to_responses {
Subroutine to_responses: called CC=2 SCAR=6.9
Pod documented
528 11 my ( $self, %opt ) = @_;
529 return {
530 11 ▶ type => 'input_image',
Branch: 1 branch
BranchTrueFalseTotal
$self->has_detail ? : 2 9 11
531 image_url => $self->_url_or_data_url(%opt),
532 ( $self->has_detail ? ( detail => $self->detail ) : () ),
533 };
534 }
535  
536  
537 8 ▶sub to_ollama {
Subroutine to_ollama: called CC=1 SCAR=0.0
Pod documented
538 8 my ($self) = @_;
539 8 return $self->ensure_base64;
540 }
541  
542  
543 7 ▶sub to_lmstudio {
Subroutine to_lmstudio: called CC=1 SCAR=0.0
Pod documented
544 7 my ($self) = @_;
545 7 return { type => 'image', data_url => $self->data_url };
546 }
547  
548  
549 10 ▶sub to_anthropic {
Subroutine to_anthropic: called CC=3 SCAR=11.0
Pod documented
550 10 my ($self) = @_;
551 10 ▶ if ($self->has_url) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_url) 3 7 10
552 return {
553 3 type => 'image',
554 source => { type => 'url', url => $self->url },
555 };
556 }
557 7 ▶ croak "to_anthropic: base64 image requires media_type"
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_media_type 1 6 7
558 unless $self->has_media_type;
559 return {
560 6 type => 'image',
561 source => {
562 type => 'base64',
563 media_type => $self->media_type,
564 data => $self->base64,
565 },
566 };
567 }
568  
569  
570 18 ▶sub to_gemini {
Subroutine to_gemini: called CC=2 SCAR=7.0
Pod documented
571 18 my ($self) = @_;
572 18 $self->ensure_base64;
573 18 ▶ croak "to_gemini: image requires media_type"
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_media_type 0 18 18
574 unless $self->has_media_type;
575 return {
576 18 inline_data => {
577 mime_type => $self->media_type,
578 data => $self->base64,
579 },
580 };
581 }
582  
583  
584 # --- JSON ---
585  
586 # Compact on purpose: TO_JSON fires implicitly wherever a message array holding
587 # the image is encoded (a trace, a log line), and the base64 payload would blow
588 # those up (karr k273). The payload is described by its decoded size instead.
589 6 ▶sub TO_JSON {
Subroutine TO_JSON: called CC=10 SCAR=23.0
Pod documented
590 6 my ($self) = @_;
591 6 ▶ my $url = $self->has_url ? $self->url : undef;
Branch: 1 branch
BranchTrueFalseTotal
$self->has_url ? : 3 3 6
592 6 ▶ $url = undef if defined $url && $url =~ /\Adata:/i;
Branch: 1 branch
BranchTrueFalseTotal
if defined $url and $url =~ /\Adata:/i 1 5 6
Condition100%3/3
defined $url and $url =~ /\Adata:/i
!ll&&!rl&&r
321
MC/DC100%2/2
defined $url and $url =~ /\Adata:/i
defined $url $url =~ /\Adata:/i
Truth table100%3/3
A and B
A= defined $urlB= $url =~ /\Adata:/i
ABresult
0X0
100
111
593 6 ▶ my %out = (
Branch: 4 branches
BranchTrueFalseTotal
defined $url ? : 2 4 6
defined $url ? : 2 4 6
defined $self->media_type ? : 6 0 6
$self->has_detail ? : 2 4 6
594 type => 'image',
595 source => ( defined $url ? 'url' : 'base64' ),
596 ( defined $url ? ( url => $url ) : () ),
597 ( defined $self->media_type ? ( media_type => $self->media_type ) : () ),
598 ( $self->has_detail ? ( detail => $self->detail ) : () ),
599 );
600 6 ▶ if ( defined $self->base64 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->base64) 3 3 6
601 3 ( my $b64 = $self->base64 ) =~ s/\s+//g;
602 3 ▶ my $pad = $b64 =~ /(=+)\z/ ? length $1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$b64 =~ /(=+)\z/ ? : 2 1 3
603 3 $out{bytes} = int( length($b64) * 3 / 4 ) - $pad;
604 }
605 6 return \%out;
606 }
607  
608  
609 # --- Helpers ---
610  
611 331 ▶sub _is_data_url { defined $_[0] && $_[0] =~ /\Adata:/i }
Subroutine _is_data_url: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] and $_[0] =~ /\Adata:/i 331 0 331
612  
613 405 ▶sub _check_fetch_scheme {
Subroutine _check_fetch_scheme: called CC=5 SCAR=16.1
614 405 my ( $self, $url ) = @_;
615 405 my ($scheme) = $url =~ /\A([a-zA-Z][a-zA-Z0-9+.\-]*):/;
616 405 ▶ return if defined $scheme && grep { lc $scheme eq $_ } @FETCH_SCHEMES;
Branch: 1 branch
BranchTrueFalseTotal
if defined $scheme and grep {lc $scheme eq $_;} @FETCH_SCHEMES 391 14 405
Condition100%3/3
defined $scheme and grep {lc $scheme eq $_;} @FETCH_SCHEMES
!ll&&!rl&&r
113391
MC/DC100%2/2
defined $scheme and grep {lc $scheme eq $_;} @FETCH_SCHEMES
defined $scheme grep {lc $scheme eq $_;} @FETCH_SCHEMES
Truth table100%3/3
A and B
A= defined $schemeB= grep {lc $scheme eq $_;} @FETCH_SCHEMES
ABresult
0X0
100
111
617 14 ▶ my $class = ref $self || $self;
Condition66%2/3
ref $self || $self
l!l&&r!l&&!r
770
MC/DC0%0/2
ref $self || $self
ref $self $self
Truth table66%2/3
A || B
A= ref $selfB= $self
ABresult
1X1
011
000
618 14 ▶ croak "$class refuses to fetch image URL "
Branch: 1 branch
BranchTrueFalseTotal
defined $scheme ? : 13 1 14
619 . ( defined $scheme ? "with scheme '$scheme'" : 'without a scheme' )
620 . " (only http/https; use Content::Image->from_file for local files)";
621 }
622  
623 # Decodes a data: URL image in process, no I/O.
624 2 ▶sub _inline_data_url {
Subroutine _inline_data_url: called CC=5 SCAR=16.6
625 2 my ($self) = @_;
626 2 require URI;
627 2 my $uri = URI->new( $self->url );
628 2 my $bytes = $uri->data;
629 2 ▶ croak "ensure_base64: cannot decode data: URL" unless defined $bytes;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes 0 2 2
630 2 $self->base64( encode_base64( $bytes, '' ) );
631 2 ▶ unless ( $self->has_media_type ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->has_media_type) 2 0 2
632 2 ▶ ( my $ct = $uri->media_type // '' ) =~ s/;.*$//;
Condition50%1/2
$uri->media_type // ""
l!l
20
MC/DC0%0/1
$uri->media_type // ""
$uri->media_type
Truth table50%1/2
A
A= $uri->media_type
Aresult
11
00
633 2 ▶ $self->media_type($ct) if length $ct;
Branch: 1 branch
BranchTrueFalseTotal
if length $ct 2 0 2
634 }
635 2 return $self->base64;
636 }
637  
638 # detail => ... out of a from_* constructor's %extra; undef means unset.
639 223 ▶sub _detail_arg {
Subroutine _detail_arg: called CC=2 SCAR=6.9
640 223 my (%extra) = @_;
641 223 ▶ return defined $extra{detail} ? ( detail => $extra{detail} ) : ();
Branch: 1 branch
BranchTrueFalseTotal
defined $extra{'detail'} ? : 13 210 223
642 }
643  
644 17 my %EXT_MAP = (
645 jpg => 'image/jpeg',
646 jpeg => 'image/jpeg',
647 png => 'image/png',
648 gif => 'image/gif',
649 webp => 'image/webp',
650 bmp => 'image/bmp',
651 svg => 'image/svg+xml',
652 heic => 'image/heic',
653 heif => 'image/heif',
654 );
655  
656 172 ▶sub _sniff_media_type {
Subroutine _sniff_media_type: called CC=3 SCAR=11.0
657 172 my ($path) = @_;
658 172 ▶ return undef unless defined $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 0 172 172
659 172 ( my $clean = $path ) =~ s/[?#].*$//;
660 172 ▶ if ( $clean =~ /\.([a-zA-Z0-9]+)$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($clean =~ /\.([a-zA-Z0-9]+)$/) 165 7 172
661 165 return $EXT_MAP{ lc $1 };
662 }
663 7 return undef;
664 }
665  
666 17 __PACKAGE__->meta->make_immutable;
667  
668  
669 17 1;
670  
671 __END__
672  
673 =pod
674  
675 =encoding UTF-8
676  
677 =head1 NAME
678  
679 Langertha::Content::Image - Canonical image content block with cross-provider conversion
680  
681 =head1 VERSION
682  
683 version 0.503
684  
685 =head1 SYNOPSIS
686  
687 use Langertha::Content::Image;
688  
689 # From a remote URL
690 my $img = Langertha::Content::Image->from_url('https://example.com/cat.jpg');
691  
692 # From a local file (media_type sniffed from extension)
693 my $img = Langertha::Content::Image->from_file('/tmp/cat.png');
694  
695 # From raw bytes
696 my $img = Langertha::Content::Image->from_data($bytes, media_type => 'image/jpeg');
697  
698 # From an existing base64 string
699 my $img = Langertha::Content::Image->from_base64($b64, media_type => 'image/png');
700  
701 # Embed in a chat message — Langertha::Role::Chat converts per engine
702 my $response = $engine->simple_chat_f({
703 role => 'user',
704 content => [ 'What is in this image?', $img ],
705 });
706  
707 =head1 DESCRIPTION
708  
709 Provider-neutral image block. Carries either a remote URL, a base64 payload,
710 or both, plus an IANA C<media_type>. Serializes to these vision-chat wire
711 formats:
712  
713 =over
714  
715 =item * OpenAI chat completions — C<{ type => 'image_url', image_url => { url => ... } }>
716  
717 =item * Anthropic messages — C<{ type => 'image', source => { type => 'url' | 'base64', ... } }>
718  
719 =item * Google Gemini — C<{ inline_data => { mime_type => ..., data => <base64> } }>
720  
721 =item * Open-Responses — C<{ type => 'input_image', image_url => <url or data: URL> }>
722  
723 =item * Ollama native — the raw base64 string, for the message C<images> array
724  
725 =item * LM Studio native — C<{ type => 'image', data_url => <data: URL> }>
726  
727 =back
728  
729 The optional L</detail> hint goes out only on the two wires that have the
730 field (OpenAI chat completions and Open-Responses) and is ignored elsewhere.
731 L</TO_JSON> gives a compact description for logs and traces, never the
732 payload.
733  
734 Gemini, Ollama native and LM Studio native require inline data, so their
735 serializers transparently download a remote URL on first call (cached on the
736 object). Engines whose OpenAI-compatible endpoint rejects remote image URLs
737 get the same treatment through C<< to_openai( inline => 1 ) >>. On the C<_f>
738 methods of L<Langertha::Role::Chat> the download happens earlier, through the
739 engine's async HTTP backend (L</ensure_base64_f>), so the serializers find the
740 payload cached and do not block the event loop.
741  
742 =head2 url
743  
744 Remote HTTP(S) URL of the image. May be passed through directly (OpenAI,
745 Anthropic) or auto-downloaded and base64-encoded (Gemini).
746  
747 =head2 base64
748  
749 The base64-encoded image payload (no C<data:> URL prefix). Can be supplied
750 at construction, or populated lazily when a provider that requires inline
751 data (Gemini) is targeted.
752  
753 =head2 media_type
754  
755 IANA media type (C<image/jpeg>, C<image/png>, C<image/gif>, C<image/webp>).
756 Required for base64 payloads on Anthropic and Gemini. Sniffed from the file
757 extension by C<from_file> and from the URL path by C<from_url>.
758  
759 =head2 detail
760  
761 Optional image-detail hint, a non-empty string. The known values are C<low>,
762 C<high> and C<auto>; any other value is sent unchanged, and the provider
763 decides whether it takes it. Unset by default, and
764 then no C<detail> field goes on any wire. When set, L</to_openai> sends it as
765 C<image_url.detail> and L</to_responses> as C<input_image.detail>; the other
766 serializers ignore it, because their wires have no such field. Every C<from_*>
767 constructor takes it:
768  
769 my $img = Langertha::Content::Image->from_url($url, detail => 'low');
770  
771 =head2 from_url
772  
773 my $img = Langertha::Content::Image->from_url($url);
774 my $img = Langertha::Content::Image->from_url($url, media_type => 'image/jpeg');
775  
776 Builds an image block referencing a remote URL. Media type is sniffed from
777 the URL extension when not provided.
778  
779 Only C<http>, C<https> and C<data:> URLs are accepted. Any other scheme
780 (C<file>, C<ftp>, C<gopher>, ...) croaks here, before any I/O, because the
781 engines that have to inline images would otherwise read it (a C<file:> URL
782 from a caller's message would send a server-local file to the provider). For
783 a local file use L</from_file>. See L</ensure_base64> for what the fetch does
784 not protect against.
785  
786 =head2 from_file
787  
788 my $img = Langertha::Content::Image->from_file('/tmp/cat.png');
789  
790 Reads a local file, base64-encodes it, and sniffs the media type from the
791 extension (unless C<media_type> is passed).
792  
793 =head2 from_data
794  
795 my $img = Langertha::Content::Image->from_data($bytes, media_type => 'image/jpeg');
796  
797 Builds an image block from raw bytes. C<media_type> is required.
798  
799 =head2 from_base64
800  
801 my $img = Langertha::Content::Image->from_base64($b64, media_type => 'image/png');
802  
803 Builds an image block from an existing base64 string.
804  
805 =head2 ensure_base64
806  
807 my $b64 = $img->ensure_base64;
808 my $b64 = $img->ensure_base64( timeout => 5 );
809 my $b64 = $img->ensure_base64(
810 max_bytes => 5_000_000,
811 url_filter => Langertha::Content::Image->deny_private_hosts,
812 );
813  
814 Returns the base64 payload, fetching the URL over HTTP if necessary.
815 Populates C<media_type> from the response C<Content-Type> header when the
816 image was URL-only. Caches the result on the object.
817  
818 Only C<http> and C<https> URLs are fetched; a C<data:> URL is decoded locally.
819 Any other scheme croaks before any I/O:
820  
821 Langertha::Content::Image refuses to fetch image URL with scheme 'file'
822 (only http/https; use Content::Image->from_file for local files)
823  
824 A redirect to another scheme is not followed, and a fetch that ended on one
825 anyway is not stored.
826  
827 C<max_bytes> caps the download, C<20971520> (20 MiB) by default; C<0> means no
828 cap. A C<Content-Length> over the cap stops the fetch before the body, and a
829 body that grows past it stops reading there. The cap holds for the decoded
830 size too: a body sent with a C<Content-Encoding> (C<gzip>, C<deflate>,
831 C<bzip2>) is inflated in blocks and refused once it passes the cap, and one in
832 any other encoding is refused as undecodable while a cap is set. Nothing is
833 stored, and the call croaks:
834  
835 Langertha::Content::Image image at https://... exceeds inline_image_max_bytes (20971520)
836  
837 C<url_filter> is a code reference that decides which URLs may be fetched,
838 against server-side request forgery (SSRF) through image URLs from untrusted
839 input. It gets each URL as a L<URI> object and returns true to allow it. It
840 runs on the image URL before any I/O, and again on every redirect hop before
841 that hop is requested. Without it, the default, every C<http> and C<https> host
842 is fetched. A refused URL, or a filter that dies, croaks:
843  
844 Langertha::Content::Image refuses to fetch image URL http://10.0.0.5/x.png:
845 rejected by inline_image_url_filter
846  
847 L</deny_private_hosts> builds a ready-made filter.
848 L<Langertha::Role::Chat> passes the engine's
849 L<Langertha::Role::Chat/inline_image_max_bytes> and
850 L<Langertha::Role::Chat/inline_image_url_filter> as these two options.
851  
852 The fetch is a blocking L<LWP::UserAgent> GET that gives up after
853 C<timeout> seconds of inactivity, C<30> by default. When
854 L<Langertha::Role::Chat> builds a request it passes the engine's
855 L<Langertha::Role::Chat/inline_image_fetch_timeout>. C<< timeout => 0 >> leaves
856 LWP's own default (180 seconds) in place, because LWP cannot run without a
857 timeout.
858  
859 =head2 ensure_base64_f
860  
861 my $b64 = await $img->ensure_base64_f($http);
862 my $b64 = await $img->ensure_base64_f( $http, max_bytes => ..., url_filter => ... );
863  
864 The async L</ensure_base64>: returns a L<Future> of the base64 payload and
865 fetches the URL through C<$http>, any client that answers the async
866 C<do_request> contract (L<Langertha::Role::AsyncHTTP>), instead of a blocking
867 L<LWP::UserAgent>. A transport error or a non-success status fails the Future.
868 The scheme rules of L</ensure_base64> apply unchanged: a non-HTTP(S) URL fails
869 the Future before any request, a C<data:> URL is decoded locally, and on the
870 synchronous LWP fallback (L<Langertha::Request::SyncHTTP>) the fetch runs over
871 a copy of its user agent restricted to C<http> and C<https>.
872  
873 C<max_bytes> and C<url_filter> work as on L</ensure_base64> and fail the
874 Future with the same text. On L<Net::Async::HTTP> the body is counted as it
875 arrives and the request is abandoned (its connection closed) once it passes
876 the cap, and redirects (up to 7) are followed one hop at a time, so the filter
877 sees each hop before it is requested. On the LWP fallback the copy of its user
878 agent carries the cap and the filter. Any other client follows redirects on its
879 own: there the filter sees the hops only after the fetch, and the payload of a
880 fetch with a refused hop is not stored; the cap is checked on the finished
881 body.
882 The C<_f> methods of L<Langertha::Role::Chat> call it with the engine's backend
883 for every URL image the engine has to inline, before the request is built.
884  
885 =head2 deny_private_hosts
886  
887 my $engine = Langertha::Engine::Gemini->new(
888 api_key => $key,
889 inline_image_url_filter => Langertha::Content::Image->deny_private_hosts,
890 );
891  
892 # With a resolver of your own (tests, a caching resolver):
893 my $filter = Langertha::Content::Image->deny_private_hosts(
894 resolver => sub { my ($host) = @_; return @ip_addresses },
895 );
896  
897 Returns a URL filter for L</ensure_base64>'s C<url_filter> (and the engine's
898 L<Langertha::Role::Chat/inline_image_url_filter>) that refuses hosts on
899 internal networks. It resolves the URL's host and refuses it when any address
900 it resolves to is one of:
901  
902 =over
903  
904 =item * IPv4 C<0.0.0.0/8> (this host), C<127.0.0.0/8> (loopback), C<10.0.0.0/8>,
905 C<172.16.0.0/12>, C<192.168.0.0/16> (RFC 1918), C<100.64.0.0/10> (carrier-grade
906 NAT), C<169.254.0.0/16> (link-local, including the cloud metadata address
907 C<169.254.169.254>), C<192.0.0.0/24> (IETF protocol assignments, including the
908 NAT64 discovery addresses), C<198.18.0.0/15> (benchmarking), C<224.0.0.0/3>
909 (multicast, C<240.0.0.0/4> reserved, C<255.255.255.255> broadcast)
910  
911 =item * IPv6 C<::/96> (unspecified, loopback C<::1>, IPv4-compatible),
912 C<fe80::/10> (link-local), C<fec0::/10> (site-local), C<fc00::/7> (unique local,
913 including the AWS metadata address C<fd00:ec2::254>), C<ff00::/8> (multicast)
914  
915 =item * an IPv6 address that carries an IPv4 address in the list above:
916 IPv4-mapped C<::ffff:a.b.c.d>, SIIT C<::ffff:0:a.b.c.d>, NAT64 C<64:ff9b::a.b.c.d>
917 and C<64:ff9b:1::a.b.c.d>, and 6to4 C<2002:AABB:CCDD::/48>. Any other address in
918 the local-use NAT64 prefix C<64:ff9b:1::/48> is refused, since it does not say
919 where its IPv4 address sits.
920  
921 =item * Teredo C<2001:0000::/32> (RFC 4380): its client IPv4 is embedded
922 I<obfuscated> (bit-inverted) in the low 32 bits, so unlike 6to4 and NAT64 it
923 cannot be re-checked as a plain address — the whole prefix is refused outright.
924 A non-Teredo C<2001::/16> address (C<2001:db8::>, C<2001:4860::>, ...) is not
925 matched and passes.
926  
927 =back
928  
929 A host that does not resolve, and a URL without a host, are refused too.
930  
931 The default resolver is the system's C<getaddrinfo> (L<Socket>); an IP literal
932 is not looked up. The lookup blocks, also on the C<_f> paths, where it holds
933 the event loop for its duration. C<resolver> replaces it: a code reference
934 that gets the host name and returns its addresses as strings.
935  
936 B<DNS rebinding:> the host is resolved here, before the HTTP client connects,
937 and the client resolves it again on its own. A name whose DNS answer changes
938 between the two lookups (a short TTL pointing first at a public address, then
939 at C<127.0.0.1>) passes the filter and still reaches the internal address.
940 The filter stops URLs that name or resolve to an internal address; for a
941 guarantee against rebinding, fetch through an egress proxy or firewall that
942 enforces the same rule on the connection itself.
943  
944 =head2 data_url
945  
946 my $uri = $img->data_url; # data:image/png;base64,...
947  
948 Returns the image as a C<data:> URL, fetching a URL-only image first (see
949 L</ensure_base64>). The media type falls back to C<application/octet-stream>.
950  
951 =head2 to_openai
952  
953 my $block = $img->to_openai;
954 # { type => 'image_url', image_url => { url => ... } }
955 my $block = $img->to_openai( inline => 1 ); # always a data: URL
956  
957 Serializes to the OpenAI chat-completions image block. Uses the URL when
958 available, otherwise emits a C<data:> URL from the base64 payload. With
959 C<< inline => 1 >> it always emits the C<data:> URL, fetching a URL-only image
960 first; L<Langertha::Role::Chat> passes it for engines whose endpoint rejects
961 remote image URLs. A set L</detail> goes out as C<image_url.detail>.
962  
963 =head2 to_responses
964  
965 my $block = $img->to_responses;
966 # { type => 'input_image', image_url => 'https://...' } (or a data: URL)
967  
968 Serializes to the Open-Responses C<input_image> part (OpenAI C</v1/responses>,
969 Perplexity C</v1/agent>). C<image_url> is a plain string, not an object: the
970 URL when available, otherwise a C<data:> URL. Takes C<< inline => 1 >> like
971 L</to_openai>. A set L</detail> goes out as the part's C<detail> field.
972  
973 =head2 to_ollama
974  
975 my $b64 = $img->to_ollama;
976  
977 Returns the raw base64 payload (no C<data:> prefix) for one entry of the
978 Ollama native C</api/chat> message C<images> array. Fetches a URL-only image
979 first, because that wire takes no image URLs.
980  
981 =head2 to_lmstudio
982  
983 my $item = $img->to_lmstudio;
984 # { type => 'image', data_url => 'data:image/png;base64,...' }
985  
986 Serializes to an LM Studio native C</api/v1/chat> C<input> image item. That
987 wire takes only base64 data URLs, so a URL-only image is fetched first.
988  
989 =head2 to_anthropic
990  
991 my $block = $img->to_anthropic;
992 # { type => 'image', source => { type => 'url', url => ... } }
993 # or
994 # { type => 'image', source => { type => 'base64', media_type => ..., data => ... } }
995  
996 Serializes to the Anthropic messages image block. Prefers a URL source
997 when available; otherwise emits an inline base64 source (C<media_type>
998 required).
999  
1000 =head2 to_gemini
1001  
1002 my $block = $img->to_gemini;
1003 # { inline_data => { mime_type => ..., data => <base64> } }
1004  
1005 Serializes to the Gemini C<inlineData> part. Auto-downloads URL-only
1006 images because Gemini has no URL-fetching equivalent.
1007  
1008 =head2 TO_JSON
1009  
1010 my $json = JSON::MaybeXS->new( convert_blessed => 1 )
1011 ->encode([ { role => 'user', content => [ 'What is this?', $img ] } ]);
1012 # ... {"bytes":48213,"media_type":"image/png","source":"base64","type":"image"} ...
1013  
1014 Serialization hook for JSON encoders configured with C<convert_blessed> (the
1015 engine's own L<Langertha::Role::JSON/json> is one), so a message array holding
1016 images can be written to a log or a trace. Returns a compact description,
1017 B<never the image data>:
1018  
1019 { type => 'image',
1020 source => 'url' | 'base64',
1021 url => ..., # only for a URL image
1022 media_type => ..., # when known
1023 detail => ..., # when set
1024 bytes => ... } # decoded payload size, when base64 is present
1025  
1026 C<source> is C<url> for an image built from a URL (even after
1027 L</ensure_base64> has fetched it; C<bytes> then gives the fetched size), and
1028 C<base64> otherwise. A C<data:> URL passed as C<url> is reported as
1029 C<base64> without the URL, because it I<is> the payload. This is not a wire
1030 format: request bodies are built by the C<to_*> serializers, never through
1031 C<TO_JSON>.
1032  
1033 =head1 SEE ALSO
1034  
1035 =over
1036  
1037 =item * L<Langertha::Content> - Base role this class implements
1038  
1039 =item * L<Langertha::Role::Chat> - Normalizes content blocks per engine during C<chat_messages>
1040  
1041 =item * L<Langertha::ToolChoice> - Sibling value object for tool_choice normalization
1042  
1043 =back
1044  
1045 =head1 SUPPORT
1046  
1047 =head2 Issues
1048  
1049 Please report bugs and feature requests on GitHub at
1050 L<https://github.com/Getty/langertha/issues>.
1051  
1052 =head2 IRC
1053  
1054 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
1055  
1056 =head1 CONTRIBUTING
1057  
1058 Contributions are welcome! Please fork the repository and submit a pull request.
1059  
1060 =head1 AUTHOR
1061  
1062 Torsten Raudssus <getty@cpan.org>
1063  
1064 =head1 COPYRIGHT AND LICENSE
1065  
1066 This software is copyright (c) 2026 by Torsten Raudssus L<https://raudssus.de/>.
1067  
1068 This is free software; you can redistribute it and/or modify it under
1069 the same terms as the Perl 5 programming language system itself.
1070  
1071 =cut
« blib/lib/Langertha/Runtime/Knobs.pm ↑ Summary blib/lib/Langertha/ServerTool.pm »