SlideShare une entreprise Scribd logo
1  sur  36
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Oliver hookins puppetcamp2011
Oliver hookins puppetcamp2011Oliver hookins puppetcamp2011
Oliver hookins puppetcamp2011Puppet
 
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 tek11Elizabeth 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.0Tim Bunce
 
Spl to the Rescue - Zendcon 09
Spl to the Rescue - Zendcon 09Spl to the Rescue - Zendcon 09
Spl to the Rescue - Zendcon 09Elizabeth 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 infrastructurePuppet
 
SPL to the Rescue - Tek 09
SPL to the Rescue - Tek 09SPL to the Rescue - Tek 09
SPL to the Rescue - Tek 09Elizabeth Smith
 
Apache mod_rewrite
Apache mod_rewriteApache mod_rewrite
Apache mod_rewriteDave Ross
 
Perl at SkyCon'12
Perl at SkyCon'12Perl at SkyCon'12
Perl at SkyCon'12Tim 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 Aboutjoshua.mcadams
 
vfsStream - effective filesystem mocking
vfsStream - effective filesystem mocking vfsStream - effective filesystem mocking
vfsStream - effective filesystem mocking Sebastian Marek
 
Smolder @Silex
Smolder @SilexSmolder @Silex
Smolder @SilexJeen Lee
 

Tendances (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
 

En vedette (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)
 

Similaire à Apache Hacks

Tips
TipsTips
Tipsmclee
 
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 thingsMarcus Deglos
 
Building apache modules
Building apache modulesBuilding apache modules
Building apache modulesMarian Marinov
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest UpdatesIftekhar Eather
 
Deploy Rails Application by Capistrano
Deploy Rails Application by CapistranoDeploy Rails Application by Capistrano
Deploy Rails Application by CapistranoTasawr Interactive
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalystdwm042
 
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_ToolGordon Forsythe
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functionsmussawir20
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applicationschartjes
 
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.3Jeremy Coates
 
AWS Hadoop and PIG and overview
AWS Hadoop and PIG and overviewAWS Hadoop and PIG and overview
AWS Hadoop and PIG and overviewDan Morrill
 
TYPO3 Flow 2.0 Workshop T3BOARD13
TYPO3 Flow 2.0 Workshop T3BOARD13TYPO3 Flow 2.0 Workshop T3BOARD13
TYPO3 Flow 2.0 Workshop T3BOARD13Robert Lemke
 
Ch ch-changes cake php2
Ch ch-changes cake php2Ch ch-changes cake php2
Ch ch-changes cake php2markstory
 
Hadoop spark performance comparison
Hadoop spark performance comparisonHadoop spark performance comparison
Hadoop spark performance comparisonarunkumar sadhasivam
 

Similaire à Apache Hacks (20)

Tips
TipsTips
Tips
 
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)
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
 
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
 

Dernier

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 

Dernier (20)

"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 

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