SlideShare a Scribd company logo
Apache Hacks

Beth Skwarecki
Pittsburgh Perl Workshop
2007-10-13

Slides and code:
http://BethSkwarecki.com/ppw2007
A Simple Output Filter
A horse walks   A horse walks
into a foo.     into a bar.

The footender   The bartender
says, why the   says, why the
long face?      long face?
Using the Filter
          In your apache2 configuration:

PerlLoadModule Example::RewriteStuff

<Files *.html>
     PerlOutputFilterHandler Example::RewriteStuff
     RewriteWhatToWhat foo bar
</Files>
How Filters Work
Essential Parts of this Filter
package Example::RewriteStuff;

# Register our module
Apache2::Module::add(__PACKAGE__, @directives);

# This processes our custom directive
sub RewriteWhatToWhat { ... }

# This does the filtering
sub handler { ... s/foo/bar/; ...}
Helpful Perl Modules
Apache2::Module lets your perl module
 become an Apache module.

Apache2::Filter provides a filter object ($f)
 and helpful filter management functions.

Apache2::Const - constants
Apache2::CmdParms – $parms
Apache2::RequestRec – request object $r
APR::Table – unset Content-Length
Define your Directives and Add
           your Module
my @directives = (
                     {
                    name => 'RewriteWhatToWhat',
                    args_how => Apache2::Const::TAKE2,
                    errmsg   => 'Args: FROM-STRING TO-STRING',
                  },
                 );

Apache2::Module::add(__PACKAGE__, @directives);




                 (This goes in Example::RewriteStuff)
The Directive
sub RewriteWhatToWhat {

my ($self, $parms, @args) = @_;

my $srv_cfg = Apache2::Module::get_config
 ($self, $parms->server);

# process/store params for later use
($srv_cfg->{from},
 $srv_cfg->{to}) = map quotemeta, @args;

}
            (This goes in Example::RewriteStuff)
The Handler
sub handler{

my $f = shift;
# [unset Content-length here]

while ($f->read(my $buffer, 1024)){
$buffer =~ s/
              $cfg->{from}
             /
              $cfg->{to}
             /gx;
 $f->print($buffer);

}          (This goes in Example::RewriteStuff)
Saving Data


          $f->ctx()
$f->ctx({ somedata => “thing to
save” });
What are Filters Good For?

●   Rewrite links in the page
●   Tidy up code as you send it
●   Screw with PHP (mod_perl cookbook)
●   What nifty filter will YOU write?
What Else can you do with
         Apache2 Filters?
●   Input filters
●   Dynamic filters (decide at request time what
    filters to run)
●   Connection filters (munge headers as well as
    body)
Hacking Apache::Registry
   ( Major Surgery)
 This next example uses Apache 1.3


 (Apache 2 users: go ahead and boo)

(Apache 1 users: you can wake up now)
Actually, It's Really Easy

1. Move & rename Apache/Registry.pm

3. Point apache to your renamed module:

    PerlModule Example::MyRegistry
    PerlHandler Example::MyRegistry

4. Hack away! (this part may be less easy)
Catch a Compile Time Error
     # ...

     compile($eval);
       $r->stash_rgy_endav($script_name);
       if ($@) {
            # your code here
            xlog_error($r, $@);
            return SERVER_ERROR unless $Debug && $Debug &
2;
             return Apache::Debug::dump($r, SERVER_ERROR);
      }
     # ...

                 (This is in Example::MyRegistry)
Catch a Runtime Error
use Example::Purgatory; # catches $SIG{__DIE__}

# ...

 if($errsv) {
       # your code here
     xlog_error($r, $errsv);
     return SERVER_ERROR unless $Debug && $Debug
& 2;
     return Apache::Debug::dump($r, SERVER_ERROR);
   }
 # ...

            (This is in Example::MyRegistry)
Email the Backtrace
use Carp::Heavy;
use Mail::Sendmail;

$SIG{__DIE__} = sub {

    sendmail (
      To => 'developers@yourcompany',
      Subject => “$page died”,
      Body => Carp::longmess_heavy()
    );

}           (This is in Example::Purgatory)
The End!

http://bethskwarecki.com/ppw2007
Apache Hacks

Beth Skwarecki
Pittsburgh Perl Workshop
2007-10-13

Slides and code:
http://BethSkwarecki.com/ppw2007
                                   1
A Simple Output Filter
          A horse walks        A horse walks
          into a foo.          into a bar.

          The footender        The bartender
          says, why the        says, why the
          long face?           long face?




                                               2




Goal the first (there are two): write an Apache filter
 that filters text, for example changing “foo” to
 “bar” on the fly. The box on the left is a file you
 have on disk; the box on the right is what the user
 sees when they request that page. The magical
 cloud in the middle is Apache.

Apache output filters can do more than just replacing
 strings (they're written in perl, so they can do
 anything perl can do) but we've chosen a simple
 replace for our example.
Using the Filter
                 In your apache2 configuration:

       PerlLoadModule Example::RewriteStuff

       <Files *.html>
            PerlOutputFilterHandler Example::RewriteStuff
            RewriteWhatToWhat foo bar
       </Files>




                                                        3




Now, how do you USE an Apache output filter? It's an
 apache module, so you need to tell Apache how to
 use your filter.

We're calling our module Example::RewriteStuff. (real
 creative, huh?) We even let the user – the person
 who's configuring Apache with our module – decide
 what strings they'd like to replace. Same idea as
 arguments in a CLI program.

This goes in your httpd.conf or, for me, the
  appropriate file in sites-enabled.

(Yes, apache2. This kind of filtering doesn't work with
  earlier Apaches.)
How Filters Work




                                                4




Apache2 filters can stack; after one filter is done with
 its portion of data, the data goes to the next filter.

Data comes in “buckets”, and when you read up on
 Apache filters, you'll hear a lot about bucket
 brigades. [Details are elided here. My examples use
 the stream-oriented API, so buckets are behind the
 scenes.]

User-defined filters are processed in the same order
 as their configuration: the first-defined filter goes
 first. [By the time your filters are invoked, the
 INCLUDES filter has already been run.]

Pictured: a 3-bucket water filter that removes arsenic
  from water. Invented by Abul Hussam for use in his
  native Bangladesh.
Essential Parts of this Filter
         package Example::RewriteStuff;

         # Register our module
         Apache2::Module::add(__PACKAGE__, @directives);

         # This processes our custom directive
         sub RewriteWhatToWhat { ... }

         # This does the filtering
         sub handler { ... s/foo/bar/; ...}



                                                            5




This is not a working filter; lots of stuff is missing.
  (See the example code for the rest, at
  http://bethskwarecki.com/ppw2007)

But the basics are here: we register the module (this
  mainly includes defining our directives like
  RewriteWhatToWhat).
We have a sub that the directive executes upon
  parsing (so it runs each time Apache reads its
  config file)
and we have the handler sub that does the hard work
  (in our case, the regex that substitutes “bar” for
  “foo”.
Helpful Perl Modules
        Apache2::Module lets your perl module
         become an Apache module.

        Apache2::Filter provides a filter object ($f)
         and helpful filter management functions.

        Apache2::Const - constants
        Apache2::CmdParms – $parms
        Apache2::RequestRec – request object $r
        APR::Table – unset Content-Length
                                                        6




Speaks for itself, I think. Perldoc for more info.

APR::Table provides unset() for content-length
Define your Directives and Add
                  your Module
       my @directives = (
                         {
                           name => 'RewriteWhatToWhat',
                           args_how => Apache2::Const::TAKE2,
                           errmsg   => 'Args: FROM-STRING TO-STRING',
                         },
                        );

       Apache2::Module::add(__PACKAGE__, @directives);




                        (This goes in Example::RewriteStuff)      7




req_override says where the directive can legally
  appear. OR_ALL means it can be just about
  anywhere.

args_how describes the arguments. In this case, we
  take 2 arguments (the from-string and to-string)

errmsg will be used if you invoke the directive
  incorrectly (for example, wrong number of
  arguments)

The name is the name of the directive, and func is
  the function that it maps to. They don't need to
  have the same name.

More info on those funky Apache constants here:
http://perl.apache.org/docs/2.0/user/config/custom.ht
  ml
The Directive
sub RewriteWhatToWhat {

my ($self, $parms, @args) = @_;

my $srv_cfg = Apache2::Module::get_config
 ($self, $parms->server);

# process/store params for later use
($srv_cfg->{from},
 $srv_cfg->{to}) = map quotemeta, @args;

}
            (This goes in Example::RewriteStuff)   8
The Handler
       sub handler{

        my $f = shift;
        # [unset Content-length here]

        while ($f->read(my $buffer, 1024)){
        $buffer =~ s/
                      $cfg->{from}
                     /
                      $cfg->{to}
                     /gx;
         $f->print($buffer);

       }          (This goes in Example::RewriteStuff)   9




where does $cfg come from?

what happens if $from crosses a 1024-byte
 boundary?
Saving Data


          $f->ctx()
$f->ctx({ somedata => “thing to
save” });


                                  10
What are Filters Good For?

        ●   Rewrite links in the page
        ●   Tidy up code as you send it
        ●   Screw with PHP (mod_perl cookbook)
        ●   What nifty filter will YOU write?



                                                 11




What filter will YOU write?

I wrote a filter to munge URLs in a reverse proxy.
   (mod_proxy_html rewrites links in HTML but I
   needed to also rewrite URLs in CSS and
   javascript.)
Two filters by Graham TerMarsch “minify” code –
   they remove whitespace. Apache::Clean by
   Geoffrey Young tidies HTML on the fly.
Screw with PHP (mod_perl cookbook)
[Your name here!]
What Else can you do with
         Apache2 Filters?
●   Input filters
●   Dynamic filters (decide at request time what
    filters to run)
●   Connection filters (munge headers as well as
    body)



                                                   12
Hacking Apache::Registry
   ( Major Surgery)
 This next example uses Apache 1.3


 (Apache 2 users: go ahead and boo)

(Apache 1 users: you can wake up now)

                                        13
Actually, It's Really Easy

        1. Move & rename Apache/Registry.pm

        3. Point apache to your renamed module:

            PerlModule Example::MyRegistry
            PerlHandler Example::MyRegistry

        4. Hack away! (this part may be less easy)

                                                     14




Example: mv /usr/lib/perl5/Apache/Registry.pm
  /usr/local/lib/site_perl/Example/MyRegistry.pm

Remember to change the “package” line to match
 (it's the first line in that file).
Catch a Compile Time Error
     # ...

     compile($eval);
       $r->stash_rgy_endav($script_name);
       if ($@) {
            # your code here
            xlog_error($r, $@);
            return SERVER_ERROR unless $Debug && $Debug &
2;
             return Apache::Debug::dump($r, SERVER_ERROR);
      }
     # ...

                 (This is in Example::MyRegistry)
                                                             15
Catch a Runtime Error
         use Example::Purgatory; # catches $SIG{__DIE__}

         # ...

          if($errsv) {
                # your code here
              xlog_error($r, $errsv);
              return SERVER_ERROR unless $Debug && $Debug
         & 2;
              return Apache::Debug::dump($r, SERVER_ERROR);
            }
          # ...

                     (This is in Example::MyRegistry)
                                                              16




runtime_error just displays a helpful message for the
  user.

Example::Purgatory catches the die signal.
Email the Backtrace
use Carp::Heavy;
use Mail::Sendmail;

$SIG{__DIE__} = sub {

    sendmail (
      To => 'developers@yourcompany',
      Subject => “$page died”,
      Body => Carp::longmess_heavy()
    );

}           (This is in Example::Purgatory)   17
The End!

http://bethskwarecki.com/ppw2007



                                   18

More Related Content

What's hot

Puppet modules for Fun and Profit
Puppet modules for Fun and ProfitPuppet modules for Fun and Profit
Puppet modules for Fun and Profit
Alessandro Franceschi
 
Training on php by cyber security infotech (csi)
Training on  php by cyber security infotech (csi)Training on  php by cyber security infotech (csi)
Training on php by cyber security infotech (csi)
Cyber Security Infotech Pvt. Ltd.
 
Oliver hookins puppetcamp2011
Oliver hookins puppetcamp2011Oliver hookins puppetcamp2011
Oliver hookins puppetcamp2011
Puppet
 
Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...
Puppet
 
Writing and using php streams and sockets tek11
Writing and using php streams and sockets   tek11Writing and using php streams and sockets   tek11
Writing and using php streams and sockets tek11
Elizabeth Smith
 
PL/Perl - New Features in PostgreSQL 9.0
PL/Perl - New Features in PostgreSQL 9.0PL/Perl - New Features in PostgreSQL 9.0
PL/Perl - New Features in PostgreSQL 9.0
Tim Bunce
 
Spl to the Rescue - Zendcon 09
Spl to the Rescue - Zendcon 09Spl to the Rescue - Zendcon 09
Spl to the Rescue - Zendcon 09
Elizabeth Smith
 
Spl in the wild
Spl in the wildSpl in the wild
Spl in the wild
Elizabeth Smith
 
Puppet Camp Berlin 2014: Manageable puppet infrastructure
Puppet Camp Berlin 2014: Manageable puppet infrastructurePuppet Camp Berlin 2014: Manageable puppet infrastructure
Puppet Camp Berlin 2014: Manageable puppet infrastructure
Puppet
 
TRunner
TRunnerTRunner
TRunner
Jeen Lee
 
SPL to the Rescue - Tek 09
SPL to the Rescue - Tek 09SPL to the Rescue - Tek 09
SPL to the Rescue - Tek 09
Elizabeth Smith
 
ReUse Your (Puppet) Modules!
ReUse Your (Puppet) Modules!ReUse Your (Puppet) Modules!
ReUse Your (Puppet) Modules!
Alessandro Franceschi
 
Apache mod_rewrite
Apache mod_rewriteApache mod_rewrite
Apache mod_rewrite
Dave Ross
 
Anatomy of a reusable module
Anatomy of a reusable moduleAnatomy of a reusable module
Anatomy of a reusable module
Alessandro Franceschi
 
Perl at SkyCon'12
Perl at SkyCon'12Perl at SkyCon'12
Perl at SkyCon'12
Tim Bunce
 
Codeigniter4の比較と検証
Codeigniter4の比較と検証Codeigniter4の比較と検証
Codeigniter4の比較と検証
ME iBotch
 
Utility Modules That You Should Know About
Utility Modules That You Should Know AboutUtility Modules That You Should Know About
Utility Modules That You Should Know About
joshua.mcadams
 
Puppi. Puppet strings to the shell
Puppi. Puppet strings to the shellPuppi. Puppet strings to the shell
Puppi. Puppet strings to the shell
Alessandro Franceschi
 
vfsStream - effective filesystem mocking
vfsStream - effective filesystem mocking vfsStream - effective filesystem mocking
vfsStream - effective filesystem mocking
Sebastian Marek
 
Smolder @Silex
Smolder @SilexSmolder @Silex
Smolder @Silex
Jeen Lee
 

What's hot (20)

Puppet modules for Fun and Profit
Puppet modules for Fun and ProfitPuppet modules for Fun and Profit
Puppet modules for Fun and Profit
 
Training on php by cyber security infotech (csi)
Training on  php by cyber security infotech (csi)Training on  php by cyber security infotech (csi)
Training on php by cyber security infotech (csi)
 
Oliver hookins puppetcamp2011
Oliver hookins puppetcamp2011Oliver hookins puppetcamp2011
Oliver hookins puppetcamp2011
 
Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...
 
Writing and using php streams and sockets tek11
Writing and using php streams and sockets   tek11Writing and using php streams and sockets   tek11
Writing and using php streams and sockets tek11
 
PL/Perl - New Features in PostgreSQL 9.0
PL/Perl - New Features in PostgreSQL 9.0PL/Perl - New Features in PostgreSQL 9.0
PL/Perl - New Features in PostgreSQL 9.0
 
Spl to the Rescue - Zendcon 09
Spl to the Rescue - Zendcon 09Spl to the Rescue - Zendcon 09
Spl to the Rescue - Zendcon 09
 
Spl in the wild
Spl in the wildSpl in the wild
Spl in the wild
 
Puppet Camp Berlin 2014: Manageable puppet infrastructure
Puppet Camp Berlin 2014: Manageable puppet infrastructurePuppet Camp Berlin 2014: Manageable puppet infrastructure
Puppet Camp Berlin 2014: Manageable puppet infrastructure
 
TRunner
TRunnerTRunner
TRunner
 
SPL to the Rescue - Tek 09
SPL to the Rescue - Tek 09SPL to the Rescue - Tek 09
SPL to the Rescue - Tek 09
 
ReUse Your (Puppet) Modules!
ReUse Your (Puppet) Modules!ReUse Your (Puppet) Modules!
ReUse Your (Puppet) Modules!
 
Apache mod_rewrite
Apache mod_rewriteApache mod_rewrite
Apache mod_rewrite
 
Anatomy of a reusable module
Anatomy of a reusable moduleAnatomy of a reusable module
Anatomy of a reusable module
 
Perl at SkyCon'12
Perl at SkyCon'12Perl at SkyCon'12
Perl at SkyCon'12
 
Codeigniter4の比較と検証
Codeigniter4の比較と検証Codeigniter4の比較と検証
Codeigniter4の比較と検証
 
Utility Modules That You Should Know About
Utility Modules That You Should Know AboutUtility Modules That You Should Know About
Utility Modules That You Should Know About
 
Puppi. Puppet strings to the shell
Puppi. Puppet strings to the shellPuppi. Puppet strings to the shell
Puppi. Puppet strings to the shell
 
vfsStream - effective filesystem mocking
vfsStream - effective filesystem mocking vfsStream - effective filesystem mocking
vfsStream - effective filesystem mocking
 
Smolder @Silex
Smolder @SilexSmolder @Silex
Smolder @Silex
 

Viewers also liked

Rad 2
Rad 2Rad 2
Rad 2
casataboca
 
Pp nc-kh-tdtt
Pp nc-kh-tdttPp nc-kh-tdtt
Pp nc-kh-tdtt
DV Thế Nam
 
Sindhi Screen Play (نوڪر تابعدار ) By: Abdul Razzaque Memon
Sindhi Screen Play (نوڪر تابعدار ) By: Abdul Razzaque MemonSindhi Screen Play (نوڪر تابعدار ) By: Abdul Razzaque Memon
Sindhi Screen Play (نوڪر تابعدار ) By: Abdul Razzaque Memon
Sollywood Production Publication research center New Saidabad Sindh
 
Content Beyond Bet.com
Content Beyond Bet.comContent Beyond Bet.com
Content Beyond Bet.com
Siddiq Bello
 
Like Write
Like WriteLike Write
Like Write
guestdaef4b
 
Apt apresentacao-01
Apt apresentacao-01Apt apresentacao-01
Apt apresentacao-01
Daebul University
 
Aula 04 Microbiologia
Aula 04 Microbiologia Aula 04 Microbiologia
Aula 04 Microbiologia
Tiago da Silva
 
Nbr 11682 1991 - estabilidade de taludes
Nbr 11682   1991 - estabilidade de taludesNbr 11682   1991 - estabilidade de taludes
Nbr 11682 1991 - estabilidade de taludes
Fernando Boff
 
Fungos e Bactérias
Fungos e BactériasFungos e Bactérias
Fungos e Bactérias
Mariolina Rodrigues Oliveira
 
(Modelo de apr análise preliminar de risco - 2)
(Modelo de apr   análise preliminar de risco - 2)(Modelo de apr   análise preliminar de risco - 2)
(Modelo de apr análise preliminar de risco - 2)
Luis Araujo
 

Viewers also liked (10)

Rad 2
Rad 2Rad 2
Rad 2
 
Pp nc-kh-tdtt
Pp nc-kh-tdttPp nc-kh-tdtt
Pp nc-kh-tdtt
 
Sindhi Screen Play (نوڪر تابعدار ) By: Abdul Razzaque Memon
Sindhi Screen Play (نوڪر تابعدار ) By: Abdul Razzaque MemonSindhi Screen Play (نوڪر تابعدار ) By: Abdul Razzaque Memon
Sindhi Screen Play (نوڪر تابعدار ) By: Abdul Razzaque Memon
 
Content Beyond Bet.com
Content Beyond Bet.comContent Beyond Bet.com
Content Beyond Bet.com
 
Like Write
Like WriteLike Write
Like Write
 
Apt apresentacao-01
Apt apresentacao-01Apt apresentacao-01
Apt apresentacao-01
 
Aula 04 Microbiologia
Aula 04 Microbiologia Aula 04 Microbiologia
Aula 04 Microbiologia
 
Nbr 11682 1991 - estabilidade de taludes
Nbr 11682   1991 - estabilidade de taludesNbr 11682   1991 - estabilidade de taludes
Nbr 11682 1991 - estabilidade de taludes
 
Fungos e Bactérias
Fungos e BactériasFungos e Bactérias
Fungos e Bactérias
 
(Modelo de apr análise preliminar de risco - 2)
(Modelo de apr   análise preliminar de risco - 2)(Modelo de apr   análise preliminar de risco - 2)
(Modelo de apr análise preliminar de risco - 2)
 

Similar to Apache Hacks

Tips
TipsTips
Tips
mclee
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
Muhamad Al Imran
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Muhamad Al Imran
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Muhamad Al Imran
 
Performance all teh things
Performance all teh thingsPerformance all teh things
Performance all teh things
Marcus Deglos
 
Building apache modules
Building apache modulesBuilding apache modules
Building apache modules
Marian Marinov
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
Iftekhar Eather
 
Deploy Rails Application by Capistrano
Deploy Rails Application by CapistranoDeploy Rails Application by Capistrano
Deploy Rails Application by Capistrano
Tasawr Interactive
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
dwm042
 
Catalyst MVC
Catalyst MVCCatalyst MVC
Catalyst MVC
Sheeju Alex
 
Zend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_ToolZend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_Tool
Gordon Forsythe
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functions
mussawir20
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
chartjes
 
What's new, what's hot in PHP 5.3
What's new, what's hot in PHP 5.3What's new, what's hot in PHP 5.3
What's new, what's hot in PHP 5.3
Jeremy Coates
 
AWS Hadoop and PIG and overview
AWS Hadoop and PIG and overviewAWS Hadoop and PIG and overview
AWS Hadoop and PIG and overview
Dan Morrill
 
lab4_php
lab4_phplab4_php
lab4_php
tutorialsruby
 
lab4_php
lab4_phplab4_php
lab4_php
tutorialsruby
 
TYPO3 Flow 2.0 Workshop T3BOARD13
TYPO3 Flow 2.0 Workshop T3BOARD13TYPO3 Flow 2.0 Workshop T3BOARD13
TYPO3 Flow 2.0 Workshop T3BOARD13
Robert Lemke
 
Ch ch-changes cake php2
Ch ch-changes cake php2Ch ch-changes cake php2
Ch ch-changes cake php2
markstory
 
Hadoop spark performance comparison
Hadoop spark performance comparisonHadoop spark performance comparison
Hadoop spark performance comparison
arunkumar sadhasivam
 

Similar to Apache Hacks (20)

Tips
TipsTips
Tips
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
 
Performance all teh things
Performance all teh thingsPerformance all teh things
Performance all teh things
 
Building apache modules
Building apache modulesBuilding apache modules
Building apache modules
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
 
Deploy Rails Application by Capistrano
Deploy Rails Application by CapistranoDeploy Rails Application by Capistrano
Deploy Rails Application by Capistrano
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
 
Catalyst MVC
Catalyst MVCCatalyst MVC
Catalyst MVC
 
Zend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_ToolZend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_Tool
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functions
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
What's new, what's hot in PHP 5.3
What's new, what's hot in PHP 5.3What's new, what's hot in PHP 5.3
What's new, what's hot in PHP 5.3
 
AWS Hadoop and PIG and overview
AWS Hadoop and PIG and overviewAWS Hadoop and PIG and overview
AWS Hadoop and PIG and overview
 
lab4_php
lab4_phplab4_php
lab4_php
 
lab4_php
lab4_phplab4_php
lab4_php
 
TYPO3 Flow 2.0 Workshop T3BOARD13
TYPO3 Flow 2.0 Workshop T3BOARD13TYPO3 Flow 2.0 Workshop T3BOARD13
TYPO3 Flow 2.0 Workshop T3BOARD13
 
Ch ch-changes cake php2
Ch ch-changes cake php2Ch ch-changes cake php2
Ch ch-changes cake php2
 
Hadoop spark performance comparison
Hadoop spark performance comparisonHadoop spark performance comparison
Hadoop spark performance comparison
 

Recently uploaded

Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
ScyllaDB
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
Javier Junquera
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
SAP S/4 HANA sourcing and procurement to Public cloud
SAP S/4 HANA sourcing and procurement to Public cloudSAP S/4 HANA sourcing and procurement to Public cloud
SAP S/4 HANA sourcing and procurement to Public cloud
maazsz111
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Jeffrey Haguewood
 
dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
Shinana2
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - HiikeSystem Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
Hiike
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 

Recently uploaded (20)

Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
SAP S/4 HANA sourcing and procurement to Public cloud
SAP S/4 HANA sourcing and procurement to Public cloudSAP S/4 HANA sourcing and procurement to Public cloud
SAP S/4 HANA sourcing and procurement to Public cloud
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
 
dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - HiikeSystem Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 

Apache Hacks

  • 1. Apache Hacks Beth Skwarecki Pittsburgh Perl Workshop 2007-10-13 Slides and code: http://BethSkwarecki.com/ppw2007
  • 2. A Simple Output Filter A horse walks A horse walks into a foo. into a bar. The footender The bartender says, why the says, why the long face? long face?
  • 3. Using the Filter In your apache2 configuration: PerlLoadModule Example::RewriteStuff <Files *.html> PerlOutputFilterHandler Example::RewriteStuff RewriteWhatToWhat foo bar </Files>
  • 5. Essential Parts of this Filter package Example::RewriteStuff; # Register our module Apache2::Module::add(__PACKAGE__, @directives); # This processes our custom directive sub RewriteWhatToWhat { ... } # This does the filtering sub handler { ... s/foo/bar/; ...}
  • 6. Helpful Perl Modules Apache2::Module lets your perl module become an Apache module. Apache2::Filter provides a filter object ($f) and helpful filter management functions. Apache2::Const - constants Apache2::CmdParms – $parms Apache2::RequestRec – request object $r APR::Table – unset Content-Length
  • 7. Define your Directives and Add your Module my @directives = ( { name => 'RewriteWhatToWhat', args_how => Apache2::Const::TAKE2, errmsg => 'Args: FROM-STRING TO-STRING', }, ); Apache2::Module::add(__PACKAGE__, @directives); (This goes in Example::RewriteStuff)
  • 8. The Directive sub RewriteWhatToWhat { my ($self, $parms, @args) = @_; my $srv_cfg = Apache2::Module::get_config ($self, $parms->server); # process/store params for later use ($srv_cfg->{from}, $srv_cfg->{to}) = map quotemeta, @args; } (This goes in Example::RewriteStuff)
  • 9. The Handler sub handler{ my $f = shift; # [unset Content-length here] while ($f->read(my $buffer, 1024)){ $buffer =~ s/ $cfg->{from} / $cfg->{to} /gx; $f->print($buffer); } (This goes in Example::RewriteStuff)
  • 10. Saving Data $f->ctx() $f->ctx({ somedata => “thing to save” });
  • 11. What are Filters Good For? ● Rewrite links in the page ● Tidy up code as you send it ● Screw with PHP (mod_perl cookbook) ● What nifty filter will YOU write?
  • 12. What Else can you do with Apache2 Filters? ● Input filters ● Dynamic filters (decide at request time what filters to run) ● Connection filters (munge headers as well as body)
  • 13. Hacking Apache::Registry ( Major Surgery) This next example uses Apache 1.3 (Apache 2 users: go ahead and boo) (Apache 1 users: you can wake up now)
  • 14. Actually, It's Really Easy 1. Move & rename Apache/Registry.pm 3. Point apache to your renamed module: PerlModule Example::MyRegistry PerlHandler Example::MyRegistry 4. Hack away! (this part may be less easy)
  • 15. Catch a Compile Time Error # ... compile($eval); $r->stash_rgy_endav($script_name); if ($@) { # your code here xlog_error($r, $@); return SERVER_ERROR unless $Debug && $Debug & 2; return Apache::Debug::dump($r, SERVER_ERROR); } # ... (This is in Example::MyRegistry)
  • 16. Catch a Runtime Error use Example::Purgatory; # catches $SIG{__DIE__} # ... if($errsv) { # your code here xlog_error($r, $errsv); return SERVER_ERROR unless $Debug && $Debug & 2; return Apache::Debug::dump($r, SERVER_ERROR); } # ... (This is in Example::MyRegistry)
  • 17. Email the Backtrace use Carp::Heavy; use Mail::Sendmail; $SIG{__DIE__} = sub { sendmail ( To => 'developers@yourcompany', Subject => “$page died”, Body => Carp::longmess_heavy() ); } (This is in Example::Purgatory)
  • 19. Apache Hacks Beth Skwarecki Pittsburgh Perl Workshop 2007-10-13 Slides and code: http://BethSkwarecki.com/ppw2007 1
  • 20. A Simple Output Filter A horse walks A horse walks into a foo. into a bar. The footender The bartender says, why the says, why the long face? long face? 2 Goal the first (there are two): write an Apache filter that filters text, for example changing “foo” to “bar” on the fly. The box on the left is a file you have on disk; the box on the right is what the user sees when they request that page. The magical cloud in the middle is Apache. Apache output filters can do more than just replacing strings (they're written in perl, so they can do anything perl can do) but we've chosen a simple replace for our example.
  • 21. Using the Filter In your apache2 configuration: PerlLoadModule Example::RewriteStuff <Files *.html> PerlOutputFilterHandler Example::RewriteStuff RewriteWhatToWhat foo bar </Files> 3 Now, how do you USE an Apache output filter? It's an apache module, so you need to tell Apache how to use your filter. We're calling our module Example::RewriteStuff. (real creative, huh?) We even let the user – the person who's configuring Apache with our module – decide what strings they'd like to replace. Same idea as arguments in a CLI program. This goes in your httpd.conf or, for me, the appropriate file in sites-enabled. (Yes, apache2. This kind of filtering doesn't work with earlier Apaches.)
  • 22. How Filters Work 4 Apache2 filters can stack; after one filter is done with its portion of data, the data goes to the next filter. Data comes in “buckets”, and when you read up on Apache filters, you'll hear a lot about bucket brigades. [Details are elided here. My examples use the stream-oriented API, so buckets are behind the scenes.] User-defined filters are processed in the same order as their configuration: the first-defined filter goes first. [By the time your filters are invoked, the INCLUDES filter has already been run.] Pictured: a 3-bucket water filter that removes arsenic from water. Invented by Abul Hussam for use in his native Bangladesh.
  • 23. Essential Parts of this Filter package Example::RewriteStuff; # Register our module Apache2::Module::add(__PACKAGE__, @directives); # This processes our custom directive sub RewriteWhatToWhat { ... } # This does the filtering sub handler { ... s/foo/bar/; ...} 5 This is not a working filter; lots of stuff is missing. (See the example code for the rest, at http://bethskwarecki.com/ppw2007) But the basics are here: we register the module (this mainly includes defining our directives like RewriteWhatToWhat). We have a sub that the directive executes upon parsing (so it runs each time Apache reads its config file) and we have the handler sub that does the hard work (in our case, the regex that substitutes “bar” for “foo”.
  • 24. Helpful Perl Modules Apache2::Module lets your perl module become an Apache module. Apache2::Filter provides a filter object ($f) and helpful filter management functions. Apache2::Const - constants Apache2::CmdParms – $parms Apache2::RequestRec – request object $r APR::Table – unset Content-Length 6 Speaks for itself, I think. Perldoc for more info. APR::Table provides unset() for content-length
  • 25. Define your Directives and Add your Module my @directives = ( { name => 'RewriteWhatToWhat', args_how => Apache2::Const::TAKE2, errmsg => 'Args: FROM-STRING TO-STRING', }, ); Apache2::Module::add(__PACKAGE__, @directives); (This goes in Example::RewriteStuff) 7 req_override says where the directive can legally appear. OR_ALL means it can be just about anywhere. args_how describes the arguments. In this case, we take 2 arguments (the from-string and to-string) errmsg will be used if you invoke the directive incorrectly (for example, wrong number of arguments) The name is the name of the directive, and func is the function that it maps to. They don't need to have the same name. More info on those funky Apache constants here: http://perl.apache.org/docs/2.0/user/config/custom.ht ml
  • 26. The Directive sub RewriteWhatToWhat { my ($self, $parms, @args) = @_; my $srv_cfg = Apache2::Module::get_config ($self, $parms->server); # process/store params for later use ($srv_cfg->{from}, $srv_cfg->{to}) = map quotemeta, @args; } (This goes in Example::RewriteStuff) 8
  • 27. The Handler sub handler{ my $f = shift; # [unset Content-length here] while ($f->read(my $buffer, 1024)){ $buffer =~ s/ $cfg->{from} / $cfg->{to} /gx; $f->print($buffer); } (This goes in Example::RewriteStuff) 9 where does $cfg come from? what happens if $from crosses a 1024-byte boundary?
  • 28. Saving Data $f->ctx() $f->ctx({ somedata => “thing to save” }); 10
  • 29. What are Filters Good For? ● Rewrite links in the page ● Tidy up code as you send it ● Screw with PHP (mod_perl cookbook) ● What nifty filter will YOU write? 11 What filter will YOU write? I wrote a filter to munge URLs in a reverse proxy. (mod_proxy_html rewrites links in HTML but I needed to also rewrite URLs in CSS and javascript.) Two filters by Graham TerMarsch “minify” code – they remove whitespace. Apache::Clean by Geoffrey Young tidies HTML on the fly. Screw with PHP (mod_perl cookbook) [Your name here!]
  • 30. What Else can you do with Apache2 Filters? ● Input filters ● Dynamic filters (decide at request time what filters to run) ● Connection filters (munge headers as well as body) 12
  • 31. Hacking Apache::Registry ( Major Surgery) This next example uses Apache 1.3 (Apache 2 users: go ahead and boo) (Apache 1 users: you can wake up now) 13
  • 32. Actually, It's Really Easy 1. Move & rename Apache/Registry.pm 3. Point apache to your renamed module: PerlModule Example::MyRegistry PerlHandler Example::MyRegistry 4. Hack away! (this part may be less easy) 14 Example: mv /usr/lib/perl5/Apache/Registry.pm /usr/local/lib/site_perl/Example/MyRegistry.pm Remember to change the “package” line to match (it's the first line in that file).
  • 33. Catch a Compile Time Error # ... compile($eval); $r->stash_rgy_endav($script_name); if ($@) { # your code here xlog_error($r, $@); return SERVER_ERROR unless $Debug && $Debug & 2; return Apache::Debug::dump($r, SERVER_ERROR); } # ... (This is in Example::MyRegistry) 15
  • 34. Catch a Runtime Error use Example::Purgatory; # catches $SIG{__DIE__} # ... if($errsv) { # your code here xlog_error($r, $errsv); return SERVER_ERROR unless $Debug && $Debug & 2; return Apache::Debug::dump($r, SERVER_ERROR); } # ... (This is in Example::MyRegistry) 16 runtime_error just displays a helpful message for the user. Example::Purgatory catches the die signal.
  • 35. Email the Backtrace use Carp::Heavy; use Mail::Sendmail; $SIG{__DIE__} = sub { sendmail ( To => 'developers@yourcompany', Subject => “$page died”, Body => Carp::longmess_heavy() ); } (This is in Example::Purgatory) 17