Debian Codegraph @

README

raw
1 NAME
2
3 POE::Component::Server::SimpleHTTP - Perl extension to serve HTTP
4 requests in POE.
5
6 VERSION
7
8 version 2.30
9
10 SYNOPSIS
11
12 use POE;
13 use POE::Component::Server::SimpleHTTP;
14
15 # Start the server!
16 POE::Component::Server::SimpleHTTP->new(
17 'ALIAS' => 'HTTPD',
18 'PORT' => 11111,
19 'HOSTNAME' => 'MySite.com',
20 'HANDLERS' => [
21 {
22 'DIR' => '^/bar/.*',
23 'SESSION' => 'HTTP_GET',
24 'EVENT' => 'GOT_BAR',
25 },
26 {
27 'DIR' => '^/$',
28 'SESSION' => 'HTTP_GET',
29 'EVENT' => 'GOT_MAIN',
30 },
31 {
32 'DIR' => '^/foo/.*',
33 'SESSION' => 'HTTP_GET',
34 'EVENT' => 'GOT_NULL',
35 },
36 {
37 'DIR' => '.*',
38 'SESSION' => 'HTTP_GET',
39 'EVENT' => 'GOT_ERROR',
40 },
41 ],
42
43 'LOGHANDLER' => { 'SESSION' => 'HTTP_GET',
44 'EVENT' => 'GOT_LOG',
45 },
46
47 'LOG2HANDLER' => { 'SESSION' => 'HTTP_GET',
48 'EVENT' => 'POSTLOG',
49 },
50
51 # In the testing phase...
52 'SSLKEYCERT' => [ 'private-key.pem', 'public-cert.pem' ],
53 'SSLINTERMEDIATECACERT' => 'intermediate-ca-cert.pem',
54 ) or die 'Unable to create the HTTP Server';
55
56 # Create our own session to receive events from SimpleHTTP
57 POE::Session->create(
58 inline_states => {
59 '_start' => sub { $_[KERNEL]->alias_set( 'HTTP_GET' );
60 $_[KERNEL]->post( 'HTTPD', 'GETHANDLERS', $_[SESSION], 'GOT_HANDLERS' );
61 },
62
63 'GOT_BAR' => \&GOT_REQ,
64 'GOT_MAIN' => \&GOT_REQ,
65 'GOT_ERROR' => \&GOT_ERR,
66 'GOT_NULL' => \&GOT_NULL,
67 'GOT_HANDLERS' => \&GOT_HANDLERS,
68 'GOT_LOG' => \&GOT_LOG,
69 },
70 );
71
72 # Start POE!
73 POE::Kernel->run();
74
75 sub GOT_HANDLERS {
76 # ARG0 = HANDLERS array
77 my $handlers = $_[ ARG0 ];
78
79 # Move the first handler to the last one
80 push( @$handlers, shift( @$handlers ) );
81
82 # Send it off!
83 $_[KERNEL]->post( 'HTTPD', 'SETHANDLERS', $handlers );
84 }
85
86 sub GOT_NULL {
87 # ARG0 = HTTP::Request object, ARG1 = HTTP::Response object, ARG2 = the DIR that matched
88 my( $request, $response, $dirmatch ) = @_[ ARG0 .. ARG2 ];
89
90 # Kill this!
91 $_[KERNEL]->post( 'HTTPD', 'CLOSE', $response );
92 }
93
94 sub GOT_REQ {
95 # ARG0 = HTTP::Request object, ARG1 = HTTP::Response object, ARG2 = the DIR that matched
96 my( $request, $response, $dirmatch ) = @_[ ARG0 .. ARG2 ];
97
98 # Do our stuff to HTTP::Response
99 $response->code( 200 );
100 $response->content( 'Some funky HTML here' );
101
102 # We are done!
103 # For speed, you could use $_[KERNEL]->call( ... )
104 $_[KERNEL]->post( 'HTTPD', 'DONE', $response );
105 }
106
107 sub GOT_ERR {
108 # ARG0 = HTTP::Request object, ARG1 = HTTP::Response object, ARG2 = the DIR that matched
109 my( $request, $response, $dirmatch ) = @_[ ARG0 .. ARG2 ];
110
111 # Check for errors
112 if ( ! defined $request ) {
113 $_[KERNEL]->post( 'HTTPD', 'DONE', $response );
114 return;
115 }
116
117 # Do our stuff to HTTP::Response
118 $response->code( 404 );
119 $response->content( "Hi visitor from " . $response->connection->remote_ip . ", Page not found -> '" . $request->uri->path . "'" );
120
121 # We are done!
122 # For speed, you could use $_[KERNEL]->call( ... )
123 $_[KERNEL]->post( 'HTTPD', 'DONE', $response );
124 }
125
126 sub GOT_LOG {
127 # ARG0 = HTTP::Request object, ARG1 = remote IP
128 my ($request, $remote_ip) = @_[ARG0,ARG1];
129
130 # Do some sort of logging activity.
131 # If the request was malformed, $request = undef
132 # CHECK FOR A REQUEST OBJECT BEFORE USING IT.
133 if( $request ) {
134 {
135 warn join(' ', time(), $remote_ip, $request->uri ), "\n";
136 } else {
137 warn join(' ', time(), $remote_ip, 'Bad request' ), "\n";
138 }
139
140 return;
141 }
142
143 DESCRIPTION
144
145 This module makes serving up HTTP requests a breeze in POE.
146
147 The hardest thing to understand in this module is the HANDLERS. That's
148 it!
149
150 The standard way to use this module is to do this:
151
152 use POE;
153 use POE::Component::Server::SimpleHTTP;
154
155 POE::Component::Server::SimpleHTTP->new( ... );
156
157 POE::Session->create( ... );
158
159 POE::Kernel->run();
160
161 Starting SimpleHTTP
162
163 To start SimpleHTTP, just call it's new method:
164
165 POE::Component::Server::SimpleHTTP->new(
166 'ALIAS' => 'HTTPD',
167 'ADDRESS' => '192.168.1.1',
168 'PORT' => 11111,
169 'HOSTNAME' => 'MySite.com',
170 'HEADERS' => {},
171 'HANDLERS' => [ ],
172 );
173
174 This method will die on error or return success.
175
176 This constructor accepts only 7 options.
177
178 ALIAS
179
180 This will set the alias SimpleHTTP uses in the POE Kernel. This will
181 default to "SimpleHTTP"
182
183 ADDRESS
184
185 This value will be passed to POE::Wheel::SocketFactory to bind to,
186 will use INADDR_ANY if it is nothing is provided (or IN6ADDR_ANY if
187 DOMAIN is AF_INET6). For UNIX domain sockets, it should be a path
188 describing the socket's filename.
189
190 If neither DOMAIN nor ADDRESS are specified, it will use IN6ADDR_ANY
191 and AF_INET6.
192
193 PORT
194
195 This value will be passed to POE::Wheel::SocketFactory to bind to.
196
197 DOMAIN
198
199 This value will be passed to POE::Wheel::SocketFactory to define the
200 socket domain used (AF_INET, AF_INET6, AF_UNIX).
201
202 HOSTNAME
203
204 This value is for the HTTP::Request's URI to point to. If this is not
205 supplied, SimpleHTTP will use Sys::Hostname to find it.
206
207 HEADERS
208
209 This should be a hashref, that will become the default headers on all
210 HTTP::Response objects. You can override this in individual requests
211 by setting it via $request->header( ... )
212
213 For more information, consult the HTTP::Headers module.
214
215 HANDLERS
216
217 This is the hardest part of SimpleHTTP :)
218
219 You supply an array, with each element being a hash. All the hashes
220 should contain those 3 keys:
221
222 DIR -> The regexp that will be used, more later.
223
224 SESSION -> The session to send the input
225
226 EVENT -> The event to trigger
227
228 The DIR key should be a valid regexp. This will be matched against
229 the current request path. Pseudocode is: if ( $path =~ /$DIR/ )
230
231 NOTE: The path is UNIX style, not MSWIN style ( /blah/foo not
232 \blah\foo )
233
234 Now, if you supply 100 handlers, how will SimpleHTTP know what to do?
235 Simple! By passing in an array in the first place, you have already
236 told SimpleHTTP the order of your handlers. They will be tried in
237 order, and if a match is not found, SimpleHTTP will return a 404
238 response.
239
240 This allows some cool things like specifying 3 handlers with DIR of:
241 '^/foo/.*', '^/$', '.*'
242
243 Now, if the request is not in /foo or not root, your 3rd handler will
244 catch it, becoming the "404 not found" handler!
245
246 NOTE: You might get weird Session/Events, make sure your handlers are
247 in order, for example: '^/', '^/foo/.*' The 2nd handler will NEVER
248 get any requests, as the first one will match ( no $ in the regex )
249
250 Now, here's what a handler receives:
251
252 ARG0 -> HTTP::Request object
253
254 ARG1 -> POE::Component::Server::SimpleHTTP::Response object
255
256 ARG2 -> The exact DIR that matched, so you can see what triggered
257 what
258
259 NOTE: If ARG0 is undef, that means POE::Filter::HTTPD encountered an
260 error parsing the client request, simply modify the HTTP::Response
261 object and send some sort of generic error. SimpleHTTP will set the
262 path used in matching the DIR regexes to an empty string, so if there
263 is a "catch-all" DIR regex like '.*', it will catch the errors, and
264 only that one.
265
266 NOTE: The only way SimpleHTTP will leak memory ( hopefully heh ) is
267 if you discard the SimpleHTTP::Response object without sending it
268 back to SimpleHTTP via the DONE/CLOSE events, so never do that!
269
270 KEEPALIVE
271
272 Set to true to enable HTTP keep-alive support. Connections will be
273 kept alive until the client closes the connection. All HTTP/1.1
274 connections are kept-open, unless you set the response Connection
275 header to close.
276
277 $response->header( Connection => 'close' );
278
279 If you want more control, use
280 POE::Component::Server::HTTP::KeepAlive.
281
282 LOGHANDLER
283
284 Expects a hashref with the following key, values:
285
286 SESSION -> The session to send the input
287
288 EVENT -> The event to trigger
289
290 You will receive an event for each request to the server from
291 clients. Malformed client requests will not be passed into the
292 handler. Instead undef will be passed. Event is called before ANY
293 content handler is called.
294
295 The event will have the following parameters:
296
297 ARG0 -> HTTP::Request object/undef if client request was malformed.
298
299 ARG1 -> the IP address of the client
300
301 LOG2HANDLER
302
303 Expect a hashref with the following key, values:
304
305 SESSION -> The session to send the input
306
307 EVENT -> The event to trigger
308
309 You will receive an event for each response that hit DONE call.
310 Malformed client requests will not be passed into the handler. Event
311 is after processing all content handlers.
312
313 The event will have the following parameters:
314
315 ARG0 -> HTTP::Request object
316
317 ARG1 -> HTTP::Response object
318
319 That makes possible following code:
320
321 my ($login, $password) = $request->authorization_basic();
322 printf STDERR "%s - %s [%s] \"%s %s %s\" %d %d\n",
323 $response->connection->remote_ip, $login||'-', POSIX::strftime("%d/%b/%Y:%T %z",localtime(time())),
324 $request->method(), $request->uri()->path(), $request->protocol(),
325 $response->code(), length($response->content());
326
327 Emulate apache-like logs for PoCo::Server::SimpleHTTP
328
329 SETUPHANDLER
330
331 Expects a hashref with the following key, values:
332
333 SESSION -> The session to send the input
334
335 EVENT -> The event to trigger
336
337 You will receive an event when the listener wheel has been setup.
338
339 Currently there are no parameters returned.
340
341 SSLKEYCERT
342
343 This should be an arrayref of only 2 elements - the private key and
344 public certificate locations. Now, this is still in the experimental
345 stage, and testing is greatly welcome!
346
347 Again, this will automatically turn every incoming connection into a
348 SSL socket. Once enough testing has been done, this option will be
349 augmented with more SSL stuff!
350
351 SSLINTERMEDIATECACERT
352
353 This option is needed in case the SSL certificate references an
354 intermediate certification authority certificate.
355
356 PROXYMODE
357
358 Set this to a true value to enable the server to act as a proxy
359 server, ie. it won't mangle the HTTP::Request URI.
360
361 Events
362
363 SimpleHTTP is so simple, there are only 8 events available.
364
365 DONE
366
367 This event accepts only one argument: the HTTP::Response object we sent to the handler.
368
369 Calling this event implies that this particular request is done, and will proceed to close the socket.
370
371 NOTE: This method automatically sets those 3 headers if they are not already set:
372 Date -> Current date stringified via HTTP::Date->time2str
373 Content-Type -> text/html
374 Content-Length -> length( $response->content )
375
376 To get greater throughput and response time, do not post() to the DONE event, call() it!
377 However, this will force your program to block while servicing web requests...
378
379 CLOSE
380
381 This event accepts only one argument: the HTTP::Response object we sent to the handler.
382
383 Calling this event will close the socket, not sending any output
384
385 GETHANDLERS
386
387 This event accepts 2 arguments: The session + event to send the response to
388
389 This event will send back the current HANDLERS array ( deep-cloned via Storable::dclone )
390
391 The resulting array can be played around to your tastes, then once you are done...
392
393 SETHANDLERS
394
395 This event accepts only one argument: pointer to HANDLERS array
396
397 BEWARE: if there is an error in the HANDLERS, SimpleHTTP will die!
398
399 SETCLOSEHANDLER
400
401 $_[KERNEL]->call( $_[SENDER], 'SETCLOSEHANDLER', $connection,
402 $event, @args );
403
404 Calls $event in the current session when $connection is closed. You
405 could use for persistent connection handling.
406
407 Multiple session may register close handlers.
408
409 Calling SETCLOSEHANDLER without $event to remove the current
410 session's handler:
411
412 $_[KERNEL]->call( $_[SENDER], 'SETCLOSEHANDLER', $connection );
413
414 You must make sure that @args doesn't cause a circular reference.
415 Ideally, use $connection-ID> or some other unique value associated
416 with this $connection.
417
418 STARTLISTEN
419
420 Starts the listening socket, if it was shut down
421
422 STOPLISTEN
423
424 Simply a wrapper for SHUTDOWN GRACEFUL, but will not shutdown SimpleHTTP if there is no more requests
425
426 SHUTDOWN
427
428 Without arguments, SimpleHTTP does this:
429 Close the listening socket
430 Kills all pending requests by closing their sockets
431 Removes it's alias
432
433 With an argument of 'GRACEFUL', SimpleHTTP does this:
434 Close the listening socket
435 Waits for all pending requests to come in via DONE/CLOSE, then removes it's alias
436
437 STREAM
438
439 With a $response argument it streams the content and calls back the streaming event
440 of the user's session (or with the dont_flush option you're responsible for calling
441 back your session's streaming event).
442
443 To use the streaming feature see below.
444
445 Streaming with SimpleHTTP
446
447 It's possible to send data as a stream to clients (unbuffered and
448 integrated in the POE loop).
449
450 Just create your session to receive events from SimpleHTTP as usually
451 and add a streaming event, this event will be triggered over and over
452 each time you set the $response to a streaming state and once you
453 trigger it:
454
455 # sets the response as streamed within our session which alias is HTTP_GET
456 # with the event GOT_STREAM
457 $response->stream(
458 session => 'HTTP_GET',
459 event => 'GOT_STREAM',
460 dont_flush => 1
461 );
462
463 # then you can simply yield your streaming event, once the GOT_STREAM event
464 # has reached its end it will be triggered again and again, until you
465 # send a CLOSE event to the kernel with the appropriate response as parameter
466 $kernel->yield('GOT_STREAM', $response);
467
468 The optional dont_flush option gives the user the ability to control
469 the callback to the streaming event, which means once your stream event
470 has reached its end it won't be called, you have to call it back.
471
472 You can now send data by chunks and either call yourself back (via POE)
473 or shutdown when your streaming is done (EOF for example).
474
475 sub GOT_STREAM {
476 my ( $kernel, $heap, $response ) = @_[KERNEL, HEAP, ARG0];
477
478 # sets the content of the response
479 $response->content("Hello World\n");
480
481 # send it to the client
482 POE::Kernel->post('HTTPD', 'STREAM', $response);
483
484 # if we have previously set the dont_flush option
485 # we have to trigger our event back until the end of
486 # the stream like this (that can be a yield, of course):
487 #
488 # $kernel->delay('GOT_STREAM', 1, $stream );
489
490 # otherwise the GOT_STREAM event is triggered continuously until
491 # we call the CLOSE event on the response like that :
492 #
493 if ($heap{'streaming_is_done'}) {
494 # close the socket and end the stream
495 POE::Kernel->post('HTTPD', 'CLOSE', $response );
496 }
497 }
498
499 The dont_flush option is there to be able to control the frequency of
500 flushes to the client.
501
502 SimpleHTTP Notes
503
504 You can enable debugging mode by doing this:
505
506 sub POE::Component::Server::SimpleHTTP::DEBUG () { 1 }
507 use POE::Component::Server::SimpleHTTP;
508
509 Also, this module will try to keep the Listening socket alive. if it
510 dies, it will open it again for a max of 5 retries.
511
512 You can override this behavior by doing this:
513
514 sub POE::Component::Server::SimpleHTTP::MAX_RETRIES () { 10 }
515 use POE::Component::Server::SimpleHTTP;
516
517 For those who are pondering about basic-authentication, here's a tiny
518 snippet to put in the Event handler
519
520 # Contributed by Rocco Caputo
521 sub Got_Request {
522 # ARG0 = HTTP::Request, ARG1 = HTTP::Response
523 my( $request, $response ) = @_[ ARG0, ARG1 ];
524
525 # Get the login
526 my ( $login, $password ) = $request->authorization_basic();
527
528 # Decide what to do
529 if ( ! defined $login or ! defined $password ) {
530 # Set the authorization
531 $response->header( 'WWW-Authenticate' => 'Basic realm="MyRealm"' );
532 $response->code( 401 );
533 $response->content( 'FORBIDDEN.' );
534
535 # Send it off!
536 $_[KERNEL]->post( 'SimpleHTTP', 'DONE', $response );
537 } else {
538 # Authenticate the user and move on
539 }
540 }
541
542 EXPORT
543
544 Nothing.
545
546 ABSTRACT
547
548 An easy to use HTTP daemon for POE-enabled programs
549
550 SEE ALSO
551
552 L<POE>
553
554 L<POE::Filter::HTTPD>
555
556 L<HTTP::Request>
557
558 L<HTTP::Response>
559
560 L<POE::Component::Server::SimpleHTTP::Connection>
561
562 L<POE::Component::Server::SimpleHTTP::Response>
563
564 L<POE::Component::Server::SimpleHTTP::PreFork>
565
566 L<POE::Component::SSLify>
567
568 AUTHOR
569
570 Apocalypse <[email protected]>
571
572 COPYRIGHT AND LICENSE
573
574 This software is copyright (c) 2023 by Apocalypse, Chris Williams,
575 Eriam Schaffter, Marlon Bailey and Philip Gwyn.
576
577 This is free software; you can redistribute it and/or modify it under
578 the same terms as the Perl 5 programming language system itself.
579