| 1 | package Perlbal::Plugin::NotModified; |
|---|
| 2 | |
|---|
| 3 | use Perlbal; |
|---|
| 4 | use strict; |
|---|
| 5 | use warnings; |
|---|
| 6 | |
|---|
| 7 | # Takes settings in perlbal like: |
|---|
| 8 | # SET ss.notmodified.host_pattern = ^example\.com |
|---|
| 9 | # |
|---|
| 10 | # The value is a regular expression to match against the Host: header on the incoming request. |
|---|
| 11 | |
|---|
| 12 | sub load { |
|---|
| 13 | my $class = shift; |
|---|
| 14 | return 1; |
|---|
| 15 | } |
|---|
| 16 | |
|---|
| 17 | sub unload { |
|---|
| 18 | my $class = shift; |
|---|
| 19 | return 1; |
|---|
| 20 | } |
|---|
| 21 | |
|---|
| 22 | # called when we're being added to a service |
|---|
| 23 | sub register { |
|---|
| 24 | my ($class, $svc) = @_; |
|---|
| 25 | |
|---|
| 26 | my $host_check_regex = undef; |
|---|
| 27 | |
|---|
| 28 | my $start_http_request_hook = sub { |
|---|
| 29 | my Perlbal::ClientHTTPBase $client = shift; |
|---|
| 30 | my Perlbal::HTTPHeaders $hds = $client->{req_headers}; |
|---|
| 31 | return 0 unless $hds; |
|---|
| 32 | |
|---|
| 33 | my $uri = $hds->request_uri; |
|---|
| 34 | |
|---|
| 35 | return 0 unless $uri; |
|---|
| 36 | |
|---|
| 37 | my $host = $hds->header("Host"); |
|---|
| 38 | |
|---|
| 39 | return 0 unless $host; |
|---|
| 40 | return 0 unless $host =~ $host_check_regex; |
|---|
| 41 | |
|---|
| 42 | my $ims = $hds->header("If-Modified-Since"); |
|---|
| 43 | |
|---|
| 44 | return 0 unless $ims; |
|---|
| 45 | |
|---|
| 46 | $client->send_response(304, "Not Modified"); |
|---|
| 47 | |
|---|
| 48 | return 1; |
|---|
| 49 | }; |
|---|
| 50 | |
|---|
| 51 | # register things to take in configuration regular expressions |
|---|
| 52 | $svc->register_setter('NotModified', 'host_pattern', sub { |
|---|
| 53 | my ($out, $what, $val) = @_; |
|---|
| 54 | return 0 unless $what && $val; |
|---|
| 55 | |
|---|
| 56 | my $err = sub { |
|---|
| 57 | $out->("ERROR: $_[0]") if $out; |
|---|
| 58 | return 0; |
|---|
| 59 | }; |
|---|
| 60 | |
|---|
| 61 | unless (length $val) { |
|---|
| 62 | $host_check_regex = undef; |
|---|
| 63 | $svc->unregister_hooks('NotModified'); |
|---|
| 64 | return 1; |
|---|
| 65 | } |
|---|
| 66 | |
|---|
| 67 | $host_check_regex = qr/$val/; |
|---|
| 68 | $svc->register_hook('NotModified', 'start_http_request', $start_http_request_hook); |
|---|
| 69 | |
|---|
| 70 | return 1; |
|---|
| 71 | }); |
|---|
| 72 | |
|---|
| 73 | return 1; |
|---|
| 74 | } |
|---|
| 75 | |
|---|
| 76 | # called when we're no longer active on a service |
|---|
| 77 | sub unregister { |
|---|
| 78 | my ($class, $svc) = @_; |
|---|
| 79 | $svc->unregister_hooks('NotModified'); |
|---|
| 80 | $svc->unregister_setters('NotModified'); |
|---|
| 81 | return 1; |
|---|
| 82 | } |
|---|
| 83 | |
|---|
| 84 | 1; |
|---|