FU: Some FastCGI fixes; FU::Util: utf8_decode & URI escaping

This commit is contained in:
Yorhel 2025-02-18 10:27:58 +01:00
parent d9fba4e8d8
commit 90cfd66069
6 changed files with 146 additions and 33 deletions

View file

@ -2,13 +2,35 @@ package FU::Util 0.1;
use v5.36;
use FU::XS;
use Carp 'confess';
use Exporter 'import';
our @EXPORT_OK = qw/
json_format json_parse
utf8_decode uri_escape uri_unescape
fdpass_send fdpass_recv
/;
sub utf8_decode :prototype($) {
return if !defined $_[0];
confess 'Invalid UTF-8' if !utf8::decode($_[0]);
confess 'Invalid control character' if $_[0] =~ /[\x00-\x08\x0b\x0c\x0e-\x1f]/;
$_[0]
}
sub uri_escape :prototype($) {
utf8::encode(local $_ = shift);
s/([^A-Za-z0-9._~-])/sprintf '%%%02X', ord $1/eg;
$_;
}
sub uri_unescape :prototype($) {
return if !defined $_[0];
utf8::encode(local $_ = shift);
s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
utf8_decode $_;
}
1;
__END__
@ -155,6 +177,36 @@ L<JSON::PP> and L<Cpanel::JSON::XS> are perfectly fine alternatives.
L<JSON::SIMD> and L<Mojo::JSON> also look like good and maintained candidates.)
=head2 String Utility Functions
=over
=item utf8_decode($bytes)
Convert a (perl-UTF-8 encoded) byte string into a sanitized perl Unicode
string. The conversion is performed in-place, so the C<$bytes> argument is
turned into a Unicode string. Returns the same string for convenience.
This function throws an error if the input is not valid UTF-8 or if it contains
ASCII control characters - that is, any character between C<0x00> and C<0x1f>
except for tab, newline and carriage return.
(This is a tiny wrapper around C<utf8::decode()> with some extra checks)
=item uri_escape($string)
Takes an Unicode string and returns a percent-encoded ASCII string, suitable
for use in a query parameter.
=item uri_unescape($string)
Takes an Unicode string potentially containing percent-encoding and returns a
decoded Unicode string. Also checks for ASCII control characters as per
C<utf8_decode()>.
=back
=head2 File Descriptor Passing
UNIX sockets (see L<IO::Socket::UNIX>) have the fancy property of letting you