| 1 | |||
| 2 | package TUWF::Response; | ||
| 3 | |||
| 4 | |||
| 5 | use strict; | ||
| 6 | use warnings; | ||
| 7 | use Exporter 'import'; | ||
| 8 | use POSIX 'strftime'; | ||
| 9 | use Carp 'croak', 'carp'; | ||
| 10 | |||
| 11 | |||
| 12 | our $VERSION = '1.6'; | ||
| 13 | our @EXPORT = qw| | ||
| 14 | resInit resHeader resCookie resBuffer resFd resStatus resRedirect | ||
| 15 | resNotFound resJSON resBinary resFile resFinish | ||
| 16 | |; | ||
| 17 | |||
| 18 | |||
| 19 | # try to load PerlIO::gzip, resBuffer will check for its availability | ||
| 20 | eval { require PerlIO::gzip; }; | ||
| 21 | |||
| 22 | |||
| 23 | # Initialises response data and resets all headers and content to their | ||
| 24 | # defaults. This method can be called mutliple times per request to clear | ||
| 25 | # any previous changes and to create a new response. | ||
| 26 | sub resInit { | ||
| 27 | my $self = shift; | ||
| 28 | |||
| 29 | $self->{_TUWF}{Res} = { | ||
| 30 | status => 200, | ||
| 31 | headers => [ | ||
| 32 | 'Content-Type' => 'text/html; charset=UTF-8', | ||
| 33 | ], | ||
| 34 | cookies => {}, | ||
| 35 | content => '', | ||
| 36 | }; | ||
| 37 | |||
| 38 | # open output buffer | ||
| 39 | $self->resBuffer($self->{_TUWF}{content_encoding}||'auto'); | ||
| 40 | |||
| 41 | # (re)initialize TUWF::XML | ||
| 42 | TUWF::XML->new( | ||
| 43 | write => sub { print { $self->resFd } $_ for @_ }, | ||
| 44 | pretty => $self->{_TUWF}{xml_pretty}, | ||
| 45 | default => 1, | ||
| 46 | ); | ||
| 47 | } | ||
| 48 | |||
| 49 | |||
| 50 | # Arguments Action | ||
| 51 | # name returns list of values of the header, first found in scalar context, undef if not exists | ||
| 52 | # name, value sets header, overwrites existing header with same name, removes duplicates | ||
| 53 | # name, undef removes header | ||
| 54 | # name, value, 1 adds header, not checking whether it already exists | ||
| 55 | # Header names are case-insensitive | ||
| 56 | sub resHeader { | ||
| 57 | my($self, $name, $value, $add) = @_; | ||
| 58 | my $h = $self->{_TUWF}{Res}{headers}; | ||
| 59 | |||
| 60 | if($add) { | ||
| 61 | push @$h, $name, $value; | ||
| 62 | return $value; | ||
| 63 | } | ||
| 64 | |||
| 65 | my @h; | ||
| 66 | my @r; | ||
| 67 | for (@$h ? 0..$#$h/2 : ()) { | ||
| 68 | if(lc($h->[$_*2]) eq lc($name)) { | ||
| 69 | push @h, $h->[$_*2+1]; | ||
| 70 | if(@_ == 3 && defined $value) { | ||
| 71 | $h->[$_*2+1] = $value; | ||
| 72 | push @r, $_ if @h > 1 | ||
| 73 | } elsif(@_ == 3) { | ||
| 74 | push @r, $_; | ||
| 75 | } | ||
| 76 | } | ||
| 77 | } | ||
| 78 | |||
| 79 | push @$h, $name, $value if @_ == 3 && defined $value && !@h; | ||
| 80 | |||
| 81 | splice @$h, $r[$_]*2-$_*2, 2 | ||
| 82 | for (@r ? 0..$#r : ()); | ||
| 83 | |||
| 84 | return @_ == 3 || @_ == 2 && !wantarray ? $h[0] : @h; | ||
| 85 | } | ||
| 86 | |||
| 87 | |||
| 88 | # Adds a Set-Cookie header, arguments: | ||
| 89 | # name, value, %options. | ||
| 90 | # value = undef -> remove cookie, | ||
| 91 | # options: | ||
| 92 | # expires, path, domain, secure, httponly, maxage, samesite | ||
| 93 | sub resCookie { | ||
| 94 | my $self = shift; | ||
| 95 | my $name = shift; | ||
| 96 | my $value = shift; | ||
| 97 | my %o = ($self->{_TUWF}{cookie_defaults} ? %{$self->{_TUWF}{cookie_defaults}} : (), @_); | ||
| 98 | |||
| 99 | $name = "$self->{_TUWF}{cookie_prefix}$name" if $self->{_TUWF}{cookie_prefix}; | ||
| 100 | my @attr = (sprintf '%s=%s', $name, defined($value)?$value:''); | ||
| 101 | $o{expires} = 0 if !defined $value; | ||
| 102 | |||
| 103 | push @attr, sprintf 'Expires=%s', strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime $o{expires}) if defined $o{expires}; | ||
| 104 | push @attr, "Max-Age=$o{maxage}" if defined $o{maxage}; | ||
| 105 | push @attr, "Path=$o{path}" if $o{path}; | ||
| 106 | push @attr, "Domain=$o{domain}" if $o{domain}; | ||
| 107 | push @attr, "SameSite=$o{samesite}" if $o{samesite}; | ||
| 108 | push @attr, 'Secure' if $o{secure}; | ||
| 109 | push @attr, 'HttpOnly' if $o{httponly}; | ||
| 110 | $self->{_TUWF}{Res}{cookies}{$name} = join '; ', @attr; | ||
| 111 | } | ||
| 112 | |||
| 113 | |||
| 114 | # Argument Action | ||
| 115 | # none/empty Returns output compression type: none/gzip/deflate | ||
| 116 | # 'clear' Clears the internal buffer, but doesn't change compression method | ||
| 117 | # 'none' Clears buffer and disables output compression | ||
| 118 | # 'gzip' Clears and enables gzip | ||
| 119 | # 'deflate' Clears and enables deflate | ||
| 120 | # 'auto' Clears and autodetects output compression from request header | ||
| 121 | # Enabling compression if PerlIO::gzip isn't installed will result in an error | ||
| 122 | sub resBuffer { | ||
| 123 | my($self, $act, $noutf8) = @_; | ||
| 124 | my $i = $self->{_TUWF}{Res}; | ||
| 125 | |||
| 126 | my $h = $self->resHeader('Content-Encoding'); | ||
| 127 | $h = !$h ? 'none' : $h eq 'gzip' ? 'gzip' : $h eq 'deflate' ? 'deflate' : 'none'; | ||
| 128 | |||
| 129 | if($act) { | ||
| 130 | my $new = $act eq 'clear' ? $h : $act; | ||
| 131 | if($new eq 'auto') { | ||
| 132 | # can we even do output compression? | ||
| 133 | if(!defined $PerlIO::gzip::VERSION) { | ||
| 134 | $new = 'none'; | ||
| 135 | } | ||
| 136 | # seems like we can, figure out which encoding to use | ||
| 137 | else { | ||
| 138 | my $enc = $self->reqHeader('Accept-Encoding')||''; | ||
| 139 | my $gzip = $enc !~ /gzip\s*(?:;\s*q=(\d+(?:\.\d*)?))?/ ? 0 : defined $1 ? $1 : 1; | ||
| 140 | my $deflate = $enc !~ /deflate\s*(?:;\s*q=(\d+(?:\.\d*)?))?/ ? 0 : defined $1 ? $1 : 1; | ||
| 141 | $new = !$gzip && !$deflate ? 'none' : $deflate > $gzip ? 'deflate' : 'gzip'; | ||
| 142 | } | ||
| 143 | } | ||
| 144 | |||
| 145 | # clear buffer | ||
| 146 | close $i->{fd} if defined $i->{fd}; | ||
| 147 | $i->{content} = ''; | ||
| 148 | open $i->{fd}, '>', \$i->{content}; | ||
| 149 | |||
| 150 | # set output compression | ||
| 151 | binmode $i->{fd}, $new eq 'gzip' ? ':gzip' : ':gzip(none)' if $new ne 'none'; | ||
| 152 | binmode $i->{fd}, ':utf8' if !($noutf8 && $noutf8 eq 'noutf8'); | ||
| 153 | $self->resHeader('Content-Encoding', $new eq 'none' ? undef : $new); | ||
| 154 | } | ||
| 155 | |||
| 156 | return $h; | ||
| 157 | } | ||
| 158 | |||
| 159 | |||
| 160 | # Returns the file descriptor where output functions can 'print' to | ||
| 161 | sub resFd { | ||
| 162 | return shift->{_TUWF}{Res}{fd}; | ||
| 163 | } | ||
| 164 | |||
| 165 | |||
| 166 | # Returns or sets the HTTP status | ||
| 167 | sub resStatus { | ||
| 168 | my($self, $new) = @_; | ||
| 169 | $self->{_TUWF}{Res}{status} = $new if $new; | ||
| 170 | return $self->{_TUWF}{Res}{status}; | ||
| 171 | } | ||
| 172 | |||
| 173 | |||
| 174 | # Redirect to an other page, accepts an URL (either relative or absolute) and | ||
| 175 | # an optional type consisting of 'temp' (temporary) or 'post' (after posting a form). | ||
| 176 | # No type argument means a permanent redirect. | ||
| 177 | sub resRedirect { | ||
| 178 | my($self, $url, $type) = @_; | ||
| 179 | |||
| 180 | $self->resBuffer('clear'); | ||
| 181 | my $fd = $self->resFd(); | ||
| 182 | print $fd 'Redirecting...'; | ||
| 183 | $self->resHeader('Content-Type' => 'text/plain'); | ||
| 184 | $self->resHeader('Location' => $url); | ||
| 185 | $self->resStatus(!$type ? 301 : $type eq 'temp' ? 307 : 303); | ||
| 186 | } | ||
| 187 | |||
| 188 | |||
| 189 | sub resNotFound { | ||
| 190 | my $self = shift; | ||
| 191 | $self->resInit; | ||
| 192 | $self->{_TUWF}{error_404_handler}->($self); | ||
| 193 | } | ||
| 194 | |||
| 195 | |||
| 196 | my $_json_codec; | ||
| 197 | sub resJSON { | ||
| 198 | my($self, $obj) = @_; | ||
| 199 | $_json_codec ||= TUWF::Misc::_JSON()->new->convert_blessed->utf8; | ||
| 200 | |||
| 201 | $self->resHeader('Content-Type' => 'application/json; charset=UTF-8'); | ||
| 202 | $self->resBinary($_json_codec->encode($obj), 'clear'); | ||
| 203 | } | ||
| 204 | |||
| 205 | |||
| 206 | sub resBinary { | ||
| 207 | my($self, $data, $buffer) = @_; | ||
| 208 | my $enc = $self->resBuffer($buffer//'none', 'noutf8'); | ||
| 209 | |||
| 210 | if($enc eq 'none') { | ||
| 211 | # Write to the buffer directly if we're not compressing, avoids extra copying. | ||
| 212 | $self->{_TUWF}{Res}{content} = $data; | ||
| 213 | } else { | ||
| 214 | print { $self->{_TUWF}{Res}{fd} } $data; | ||
| 215 | } | ||
| 216 | } | ||
| 217 | |||
| 218 | |||
| 219 | sub resFile { | ||
| 220 | my($self, $path, $fn) = @_; | ||
| 221 | |||
| 222 | # This also catches files with '..' somewhere in the middle of the name. | ||
| 223 | # Let's just disallow that too to simplify this check, I'd err on the side of | ||
| 224 | # caution. | ||
| 225 | if($fn =~ /\.\./) { | ||
| 226 | $self->resNotFound; | ||
| 227 | $self->done; | ||
| 228 | } | ||
| 229 | |||
| 230 | my $ext = $fn =~ m{\.([^/\.]+)$} ? lc $1 : ''; | ||
| 231 | my $ctype = $self->{_TUWF}{mime_types}{$ext} || $self->{_TUWF}{mime_default}; | ||
| 232 | my $compress = $ctype =~ /^text/; | ||
| 233 | |||
| 234 | my $file = "$path/$fn"; | ||
| 235 | return 0 if !-f $file; | ||
| 236 | open my $F, '<', $file or croak "Unable to open '$file': $!"; | ||
| 237 | { | ||
| 238 | local $/=undef; | ||
| 239 | $self->resBinary(scalar <$F>, $compress ? 'auto' : 'none'); | ||
| 240 | } | ||
| 241 | |||
| 242 | $self->resHeader('Content-Type' => "$ctype; charset=UTF-8"); # Adding a charset to binary formats should be safe, too. | ||
| 243 | return 1; | ||
| 244 | } | ||
| 245 | |||
| 246 | |||
| 247 | # Send everything we have buffered to the client | ||
| 248 | sub resFinish { | ||
| 249 | my $self = shift; | ||
| 250 | my $i = $self->{_TUWF}{Res}; | ||
| 251 | |||
| 252 | close $i->{fd}; | ||
| 253 | if($i->{status} == 204) { | ||
| 254 | $self->resHeader('Content-Type' => undef); | ||
| 255 | $self->resHeader('Content-Encoding' => undef); | ||
| 256 | } else { | ||
| 257 | $self->resHeader('Content-Length' => length($i->{content})); | ||
| 258 | } | ||
| 259 | |||
| 260 | if($self->{_TUWF}{http}) { | ||
| 261 | printf "HTTP/1.0 %d Hi, I am a HTTP response.\r\n", $i->{status}; | ||
| 262 | } else { | ||
| 263 | printf "Status: %d\r\n", $i->{status}; | ||
| 264 | } | ||
| 265 | my $hdr = join "\r\n", | ||
| 266 | (map "$i->{headers}[$_*2]: $i->{headers}[$_*2+1]", @{$i->{headers}} ? 0..$#{$i->{headers}}/2 : ()), | ||
| 267 | (map "Set-Cookie: $i->{cookies}{$_}", keys %{$i->{cookies}}); | ||
| 268 | utf8::encode $hdr; | ||
| 269 | print "$hdr\r\n\r\n"; | ||
| 270 | print $i->{content} if $self->reqMethod() ne 'HEAD' && $i->{status} != 204; | ||
| 271 | |||
| 272 | # free the memory used for the reponse data | ||
| 273 | $self->resInit; | ||
| 274 | } | ||
| 275 | |||
| 276 | |||
| 277 | |||
| 278 | |||
| 279 | 1; | ||
| 280 | |||
| 281 |