File: HTTP.pm

package info (click to toggle)
libpoe-component-client-http-perl 0.949-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 468 kB
  • sloc: perl: 3,566; makefile: 10
file content (1599 lines) | stat: -rw-r--r-- 49,581 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
package POE::Component::Client::HTTP;
# vim: ts=2 sw=2 expandtab
$POE::Component::Client::HTTP::VERSION = '0.949';
use strict;
#use bytes; # for utf8 compatibility

use constant DEBUG      => 0;
use constant DEBUG_DATA => 0;

use Carp qw(croak carp);
use HTTP::Response;
use Net::HTTP::Methods;
use Socket qw(
  sockaddr_in inet_ntoa
  getnameinfo NI_NUMERICHOST NI_NUMERICSERV
);

use POE::Component::Client::HTTP::RequestFactory;
use POE::Component::Client::HTTP::Request qw(:states :fields);

BEGIN {
  local $SIG{'__DIE__'} = 'DEFAULT';

  #TODO: move this to Client::Keepalive?
  # Allow more finely grained timeouts if Time::HiRes is available.
  eval {
    require Time::HiRes;
    Time::HiRes->import("time");
  };
}

use POE qw(
  Driver::SysRW Filter::Stream
  Filter::HTTPHead Filter::HTTPChunk
  Component::Client::Keepalive
);

# The Internet Assigned Numbers Authority (IANA) acts as a registry
# for transfer-coding value tokens. Initially, the registry contains
# the following tokens: "chunked" (section 3.6.1), "identity" (section
# 3.6.2), "gzip" (section 3.5), "compress" (section 3.5), and
# "deflate" (section 3.5).

# FIXME - Haven't been able to test the compression options.
# Comments for each filter are what HTTP::Message use.  Methods
# without packages are from Compress::Zlib.

# FIXME - Is it okay to be mixing content and transfer encodings in
# this one table?

my %te_possible_filters = (
  'chunked'  => 'POE::Filter::HTTPChunk',
  'identity' => 'POE::Filter::Stream',
#  'gzip'     => 'POE::Filter::Zlib::Stream',  # Zlib: memGunzip
#  'x-gzip'   => 'POE::Filter::Zlib::Stream',  # Zlib: memGunzip
#  'x-bzip2'  => 'POE::Filter::Bzip2',         # Compress::BZip2::decompress
#  'deflate'  => 'POE::Filter::Zlib::Stream',  # Zlib: uncompress / inflate
#  'compress' => 'POE::Filter::LZW',           # unsupported
  # FIXME - base64 = MIME::Base64::decode
  # FIXME - quoted-printable = Mime::QuotedPrint::decode
);

my %te_filters;

while (my ($encoding, $filter) = each %te_possible_filters) {
  eval "use $filter";
  next if $@;
  $te_filters{$encoding} = $filter;
}

# The following defaults to 'chunked,identity' which is technically
# correct but arguably useless.  It also stomps on gzip'd transport
# because in the World Wild Web, Accept-Encoding is used to indicate
# gzip readiness, but the server responds with 'Content-Encoding:
# gzip', completely outside of TE encoding.
#
# Done this way so they appear in order of preference.
# FIXME - Is the order important here?

#my $accept_encoding = join(
#  ",",
#  grep { exists $te_filters{$_} }
#  qw(x-bzip2 gzip x-gzip deflate compress chunked identity)
#);

my %supported_schemes = (
  http  => 1,
  https => 1,
);


#------------------------------------------------------------------------------
# Spawn a new PoCo::Client::HTTP session.  This basically is a
# constructor, but it isn't named "new" because it doesn't create a
# usable object.  Instead, it spawns the object off as a separate
# session.

sub spawn {
  my $type = shift;

  croak "$type requires an even number of parameters" if @_ % 2;

  my %params = @_;

  my $alias = delete $params{Alias};
  $alias = 'weeble' unless defined $alias and length $alias;

  my $bind_addr = delete $params{BindAddr};
  my $cm = delete $params{ConnectionManager};

  my $request_factory = POE::Component::Client::HTTP::RequestFactory->new(
    \%params
  );

  croak(
    "$type doesn't know these parameters: ",
    join(', ', sort keys %params)
  ) if scalar keys %params;

  POE::Session->create(
    inline_states => {
      _start  => \&_poco_weeble_start,
      _stop   => \&_poco_weeble_stop,
      _child  => sub { },

      # Public interface.
      request                => \&_poco_weeble_request,
      pending_requests_count => \&_poco_weeble_pending_requests_count,
      'shutdown'             => \&_poco_weeble_shutdown,
      cancel                 => \&_poco_weeble_cancel,

      # Client::Keepalive interface.
      got_connect_done  => \&_poco_weeble_connect_done,

      # ReadWrite interface.
      got_socket_input  => \&_poco_weeble_io_read,
      got_socket_flush  => \&_poco_weeble_io_flushed,
      got_socket_error  => \&_poco_weeble_io_error,

      # I/O timeout.
      got_timeout       => \&_poco_weeble_timeout,
      remove_request    => \&_poco_weeble_remove_request,
    },
    heap => {
      alias        => $alias,
      factory      => $request_factory,
      cm           => $cm,
      is_shut_down => 0,
      bind_addr    => $bind_addr,
    },
  );

  undef;
}


sub _poco_weeble_start {
  my ($kernel, $heap) = @_[KERNEL, HEAP];

  $kernel->alias_set($heap->{alias});

  # have to do this here because it wants a current_session
  $heap->{cm} = POE::Component::Client::Keepalive->new(
    timeout => $heap->{factory}->timeout,
    ($heap->{bind_addr} ? (bind_address => $heap->{bind_addr}) : ()),
  ) unless ($heap->{cm});
}


sub _poco_weeble_stop {
  my $heap = $_[HEAP];
  my $request = delete $heap->{request};

  foreach my $request_rec (values %$request) {
    $request_rec->remove_timeout();
    delete $heap->{ext_request_to_int_id}->{$request_rec->[REQ_HTTP_REQUEST]};
  }

  DEBUG and warn "Client::HTTP (alias=$heap->{alias}) stopped.";
}


sub _poco_weeble_pending_requests_count {
  my ($heap) = $_[HEAP];
  my $r = $heap->{request} || {};
  return scalar keys %$r;
}


sub _poco_weeble_request {
  my (
    $kernel, $heap, $sender,
    $response_event, $http_request, $tag, $progress_event,
    $proxy_override
  ) = @_[KERNEL, HEAP, SENDER, ARG0, ARG1, ARG2, ARG3, ARG4];

  my $scheme = $http_request->uri->scheme;
  unless (
    defined($scheme) and
    exists $supported_schemes{$scheme}
  ) {
    my $rsp = HTTP::Response->new(
       400 => 'Bad Request', [],
       "<html>\n"
       . "<HEAD><TITLE>Error: Bad Request</TITLE></HEAD>\n"
       . "<BODY>\n"
       . "<H1>Error: Bad Request</H1>\n"
       . "Unsupported URI scheme: '$scheme'\n"
       . "</BODY>\n"
       . "</HTML>\n"
    );
    $rsp->request($http_request);
    if (ref($response_event) eq 'POE::Component::Client::HTTP::Request') {
      # This happens during redirect.
      $response_event->postback->($rsp);
    } else {
      $kernel->post($sender, $response_event, [$http_request, $tag], [$rsp]);
    }
    return;
  }

  my $host = $http_request->uri->host;
  unless (defined $host and length $host) {
    my $rsp = HTTP::Response->new(
       400 => 'Bad Request', [],
       "<html>\n"
       . "<HEAD><TITLE>Error: Bad Request</TITLE></HEAD>\n"
       . "<BODY>\n"
       . "<H1>Error: Bad Request</H1>\n"
       . "URI contains no discernable host.\n"
       . "</BODY>\n"
       . "</HTML>\n"
    );
    $rsp->request($http_request);
    if (ref($response_event) eq 'POE::Component::Client::HTTP::Request') {
      $response_event->postback->($rsp);
    } else {
      $kernel->post($sender, $response_event, [$http_request, $tag], [$rsp]);
    }
    return;
  }

  if ($heap->{is_shut_down}) {
    my $rsp = HTTP::Response->new(
       408 => 'Request timed out (component shut down)', [],
       "<html>\n"
       . "<HEAD><TITLE>Error: Request timed out (component shut down)"
       . "</TITLE></HEAD>\n"
       . "<BODY>\n"
       . "<H1>Error: Request Timeout</H1>\n"
       . "Request timed out (component shut down)\n"
       . "</BODY>\n"
       . "</HTML>\n"
      );
    $rsp->request($http_request);
    if (ref($response_event) eq 'POE::Component::Client::HTTP::Request') {
      $response_event->postback->($rsp);
    } else {
      $kernel->post($sender, $response_event, [$http_request, $tag], [$rsp]);
    }
    return;
  }

  if (defined $proxy_override) {
    POE::Component::Client::HTTP::RequestFactory->parse_proxy($proxy_override);
  }

  my $request = $heap->{factory}->create_request(
    $http_request, $response_event, $tag, $progress_event,
    $proxy_override, $sender
  );
  $heap->{request}->{$request->ID} = $request;
  $heap->{ext_request_to_int_id}->{$http_request} = $request->ID;

  my @timeout;
  if ($heap->{factory}->timeout()) {
    @timeout = (
      timeout => $heap->{factory}->timeout()
    );
  }

  eval {
    # get a connection from Client::Keepalive
    #
    # TODO CONNECT - We must ask PCC::Keepalive to establish an http
    # socket, not https.  The initial proxy interactin is plaintext?

    $request->[REQ_CONN_ID] = $heap->{cm}->allocate(
      scheme  => $request->scheme,
      addr    => $request->host,
      port    => $request->port,
      context => $request->ID,
      event   => 'got_connect_done',
      @timeout,
    );
  };
  if ($@) {
    delete $heap->{request}->{$request->ID};
    delete $heap->{ext_request_to_int_id}->{$http_request};

    # we can reach here for things like host being invalid.
    $request->error(400, $@);
  }
}


sub _poco_weeble_connect_done {
  my ($heap, $response) = @_[HEAP, ARG0];

  my $connection = $response->{'connection'};
  my $request_id = $response->{'context'};

  # Can't handle connections if we're shut down.
  # TODO - How do we still get these?  Were they previously queued or
  # something?
  if ($heap->{is_shut_down}) {
    _internal_cancel(
      $heap, $request_id, 408, "Request timed out (request canceled)"
    );
    return;
  }

  if (defined $connection) {
    DEBUG and warn "CON: request $request_id connected ok...";

    my $request = $heap->{request}->{$request_id};
    unless (defined $request) {
      DEBUG and warn "CON: ignoring connection for canceled request";
      return;
    }

    my $block_size = $heap->{factory}->block_size;

    # get wheel from the connection
    my $new_wheel = $connection->start(
      Driver       => POE::Driver::SysRW->new(BlockSize => $block_size),
      InputFilter  => POE::Filter::HTTPHead->new(),
      OutputFilter => POE::Filter::Stream->new(),
      InputEvent   => 'got_socket_input',
      FlushedEvent => 'got_socket_flush',
      ErrorEvent   => 'got_socket_error',
    );

    DEBUG and warn "CON: request $request_id uses wheel ", $new_wheel->ID;

    # Add the new wheel ID to the lookup table.
    $heap->{wheel_to_request}->{ $new_wheel->ID() } = $request_id;

    $request->[REQ_CONNECTION] = $connection;

    # SSLify needs us to call it's function to get the "real" socket
    my $peer_addr;
    if ( $request->scheme eq 'http' ) {
      $peer_addr = getpeername($new_wheel->get_input_handle());
    } else {
      my $socket = $new_wheel->get_input_handle();
      $peer_addr = getpeername(POE::Component::SSLify::SSLify_GetSocket($socket));
    }

    if (defined $peer_addr) {
      my ($error, $address, $port) = getnameinfo(
        $peer_addr, NI_NUMERICHOST | NI_NUMERICSERV
      );

      if ($error) {
        $request->[REQ_PEERNAME] = "error: $error";
      }
      else {
        $request->[REQ_PEERNAME] = "$address.$port";
      }
    }
    else {
      $request->[REQ_PEERNAME] = "error: $!";
    }

    $request->create_timer($heap->{factory}->timeout);
    $request->send_to_wheel;
  }
  else {
    DEBUG and warn(
      "CON: Error connecting for request $request_id --- ", $_[SENDER]->ID
    );

    my ($operation, $errnum, $errstr) = (
      $response->{function},
      $response->{error_num} || '??',
      $response->{error_str}
    );

    DEBUG and warn(
      "CON: request $request_id encountered $operation error " .
      "$errnum: $errstr"
    );

    DEBUG and warn "I/O: removing request $request_id";
    my $request = delete $heap->{request}->{$request_id};
    $request->remove_timeout();
    delete $heap->{ext_request_to_int_id}->{$request->[REQ_HTTP_REQUEST]};

    # Post an error response back to the requesting session.
    $request->connect_error($operation, $errnum, $errstr);
  }
}


sub _poco_weeble_timeout {
  my ($kernel, $heap, $request_id) = @_[KERNEL, HEAP, ARG0];

  DEBUG and warn "T/O: request $request_id timed out";

  # Discard the request.  Keep a copy for a few bits of cleanup.
  DEBUG and warn "I/O: removing request $request_id";
  my $request = delete $heap->{request}->{$request_id};

  unless (defined $request) {
    die(
      "T/O: unexpectedly undefined request for id $request_id\n",
      "T/O: known request IDs: ", join(", ", keys %{$heap->{request}}), "\n",
      "...",
    );
  }

  DEBUG and warn "T/O: request $request_id has timer ", $request->timer;
  $request->remove_timeout();
  delete $heap->{ext_request_to_int_id}->{$request->[REQ_HTTP_REQUEST]};

  # There's a wheel attached to the request.  Shut it down.
  if ($request->wheel) {
    my $wheel_id = $request->wheel->ID();
    DEBUG and warn "T/O: request $request_id is wheel $wheel_id";

    # Shut down the connection so it's not reused.
    $request->wheel->shutdown_input();
    delete $heap->{wheel_to_request}->{$wheel_id};
  }


  DEBUG and do {
    die( "T/O: request $request_id is unexpectedly zero" )
      unless $request->[REQ_STATE];
    warn "T/O: request_state = " . sprintf("%#04x\n", $request->[REQ_STATE]);
  };

  # Hey, we haven't sent back a response yet!
  unless ($request->[REQ_STATE] & (RS_REDIRECTED | RS_POSTED)) {

    # Well, we have a response.  Isn't that nice?  Let's send it.
    if ($request->[REQ_STATE] & (RS_IN_CONTENT | RS_DONE)) {
      _finish_request($heap, $request);
      return;
    }

    # Post an error response back to the requesting session.
    DEBUG and warn "I/O: Disconnect, keepalive timeout or HTTP/1.0.";
    $request->error(408, "Request timed out") if $request->[REQ_STATE];
    return;
  }
}


sub _poco_weeble_io_flushed {
  my ($heap, $wheel_id) = @_[HEAP, ARG0];

  # We sent the request.  Now we're looking for a response.  It may be
  # bad to assume we won't get a response until a request has flushed.
  my $request_id = $heap->{wheel_to_request}->{$wheel_id};
  if (not defined $request_id) {
    DEBUG and warn "!!!: unexpectedly undefined request ID";
    return;
  }

  DEBUG and warn(
    "I/O: wheel $wheel_id (request $request_id) flushed its request..."
  );

  my $request = $heap->{request}->{$request_id};

  # Read content to send from a callback
  if ( ref $request->[REQ_HTTP_REQUEST]->content() eq 'CODE' ) {
    my $callback = $request->[REQ_HTTP_REQUEST]->content();

    my $buf = eval { $callback->() };

    if ( $buf ) {
      $request->wheel->put($buf);

      # reset the timeout
      # Have to also reset REQ_START_TIME or timer ends early
      $request->remove_timeout;
      $request->[REQ_START_TIME] = time();
      $request->create_timer($heap->{factory}->timeout);

      return;
    }
  }

  $request->[REQ_STATE] ^= RS_SENDING;
  $request->[REQ_STATE] = RS_IN_HEAD;

  # XXX - Removed a second time.  The first time was in version 0.53,
  # because the EOF generated by shutdown_output() causes some servers
  # to disconnect rather than send their responses.
  # $request->wheel->shutdown_output();
}


sub _poco_weeble_io_error {
  my ($kernel, $heap, $operation, $errnum, $errstr, $wheel_id) =
    @_[KERNEL, HEAP, ARG0..ARG3];

  DEBUG and warn(
    "I/O: wheel $wheel_id encountered $operation error $errnum: $errstr"
  );

  # Drop the wheel.
  my $request_id = delete $heap->{wheel_to_request}->{$wheel_id};

  # There was no corresponding request?  Nothing left to do here.
  # We might have got here because the server sent EOF after we were done processing
  # the request, and deleted it from our cache. ( notes for RT#50231 )
  return unless $request_id;

  DEBUG and warn "I/O: removing request $request_id";
  my $request = delete $heap->{request}->{$request_id};
  $request->remove_timeout;
  delete $heap->{ext_request_to_int_id}{$request->[REQ_HTTP_REQUEST]};

  # Otherwise the remote end simply closed.  If we've got a pending
  # response, then post it back to the client.
  DEBUG and warn "STATE is ", $request->[REQ_STATE];

  # Except when we're redirected.  In this case, the connection was but
  # one step towards our destination.
  return if ($request->[REQ_STATE] & RS_REDIRECTED);

  # If there was a non-zero error, then something bad happened.  Post
  # an error response back, if we haven't posted anything before.
  if ($errnum) {
    if ($operation eq "connect") {
      $request->connect_error($operation, $errnum, $errstr);
      return;
    }

    unless ($request->[REQ_STATE] & RS_POSTED) {
      $request->error(400, "$operation error $errnum: $errstr");
    }
    return;
  }

  # We seem to have finished with the request.  Send back a response.
  if (
    $request->[REQ_STATE] & (RS_IN_CONTENT | RS_DONE) and
    not $request->[REQ_STATE] & RS_POSTED
  ) {
    _finish_request($heap, $request);
    return;
  }

  # We have already posted a response, so this is a remote keepalive
  # timeout or other delayed socket shutdown.  Nothing left to do.
  if ($request->[REQ_STATE] & RS_POSTED) {
    DEBUG and warn "I/O: Disconnect, remote keepalive timeout or HTTP/1.0.";
    return;
  }

  # We never received a response.
  if (not defined $request->[REQ_RESPONSE]) {
    # Check for pending data indicating a LF-free HTTP 0.9 response.
    my $lines = $request->wheel->get_input_filter()->get_pending();
    my $text = join '' => @$lines;
    DEBUG and warn "Got ", length($text), " bytes of data without LF.";

    # If we have data, build and return a response from it.
    if ($text =~ /\S/) {
      DEBUG and warn(
        "Generating HTTP response for HTTP/0.9 response without LF."
      );
      $request->[REQ_RESPONSE] = HTTP::Response->new(
        200, 'OK', [
          'Content-Type'  => 'text/html',
          'X-PCCH-Peer'   => $request->[REQ_PEERNAME],
        ], $text
      );
      $request->[REQ_RESPONSE]->protocol('HTTP/0.9');
      $request->[REQ_RESPONSE]->request($request->[REQ_HTTP_REQUEST]);
      $request->[REQ_STATE] = RS_DONE;
      $request->return_response;
      return;
    }

    # No data received.  This is an incomplete response.
    $request->error(400, "Incomplete response - $request_id");
    return;
  }

  # We haven't built a proper response, and nothing returned by the
  # server can be turned into a proper response.  Send back an error.
  # Changed to 406 after considering rt.cpan.org 20975.
  #
  # 10.4.7 406 Not Acceptable
  #
  # The resource identified by the request is only capable of
  # generating response entities which have content characteristics
  # not acceptable according to the accept headers sent in the
  # request.

  $request->error(406, "Server response is Not Acceptable - $request_id");
}


#------------------------------------------------------------------------------
# Read a chunk of response.  This code is directly adapted from Artur
# Bergman's nifty POE::Filter::HTTPD, which does pretty much the same
# in the other direction.

sub _poco_weeble_io_read {
  my ($kernel, $heap, $input, $wheel_id) = @_[KERNEL, HEAP, ARG0, ARG1];
  my $request_id = $heap->{wheel_to_request}->{$wheel_id};

  DEBUG and warn "I/O: wheel $wheel_id got input...";
  DEBUG_DATA and warn (ref($input) ? $input->as_string : _hexdump($input));

  # There was no corresponding request?  Nothing left to do here.
  #
  # We might have got here because the server sent EOF after we were
  # done processing the request, and deleted it from our cache. (
  # notes for RT#50231 )
  return unless defined $request_id;

  my $request = $heap->{request}->{$request_id};
  return unless defined $request;
  DEBUG and warn(
    "REQUEST $request_id is $request <",
    $request->[REQ_HTTP_REQUEST]->uri(), ">"
  );

  # Reset the timeout if we get data.
  $kernel->delay_adjust($request->timer, $heap->{factory}->timeout);

  if ($request->[REQ_STATE] & RS_REDIRECTED) {
    DEBUG and warn "input for request that was redirected";
    return;
  }


  # The very first line ought to be status.  If it's not, then it's
  # part of the content.
  if ($request->[REQ_STATE] & RS_IN_HEAD) {
    if (defined $input) {
      $input->request ($request->[REQ_HTTP_REQUEST]);
      #warn(
      #  "INPUT for ", $request->[REQ_HTTP_REQUEST]->uri,
      #  " is \n",$input->as_string
      #)
    }
    else {
      #warn "NO INPUT";
    }

    # FIXME: LordVorp gets here without $input being a HTTP::Response.
    # FIXME: This happens when the response is HTTP/0.9 and doesn't
    # include a status line.  See t/53_response_parser.t.
    $request->[REQ_RESPONSE] = $input;
    $input->header("X-PCCH-Peer", $request->[REQ_PEERNAME]);

    # TODO CONNECT - If we've got the headers to a CONNECT request,
    # then we can switch to the actual request.  This is like a faux
    # redirect where the socket gets reused.
    #
    # 1. Switch the socket to SSL.
    # 2. Switch the request from CONNECT mode to regular mode, using
    #    the method proposed in PCCH::Request.
    # 3. Send the original request via PCCH::Request->send_to_wheel().
    #    This puts the client back into the RS_SENDING state.
    # 4. Reset any data/state so it appears we never went through
    #    CONNECT.
    # 5. Make sure that PCC::Keepalive will discard the socket when
    #    we're done with it.
    # 6. Return.  The connection should proceed as normal.
    #
    # I think the normal handling for HTTP errors will cover the case
    # of CONNECT failure.  If not, we can refine the implementation as
    # needed.

    # Some responses are without content by definition
    # FIXME: #12363
    # Make sure we finish even when it isn't one of these, but there
    # is no content.
    if (
      $request->[REQ_HTTP_REQUEST]->method eq 'HEAD'
      or $input->code =~ /^(?:1|[23]04)/
      or (
        defined($input->content_length())
        and $input->content_length() == 0
      )
    ) {
      if (_try_redirect($request_id, $input, $request)) {
        my $old_request = delete $heap->{request}->{$request_id};
        delete $heap->{wheel_to_request}->{$wheel_id};
        if (defined $old_request) {
          DEBUG and warn "I/O: removed request $request_id";
          $old_request->remove_timeout();
          delete $heap->{ext_request_to_int_id}{$old_request->[REQ_HTTP_REQUEST]};
          $old_request->[REQ_CONNECTION] = undef;
        }
        return;
      }
      $request->[REQ_STATE] |= RS_DONE;
      $request->remove_timeout();
      _finish_request($heap, $request);
      return;
    }
    else {
      # If we have content length, and it's more than the maximum we
      # requested, then fail without bothering with the content.
      if (
        defined($heap->{factory}->max_response_size())
        and defined($input->content_length())
        and $input->content_length() > $heap->{factory}->max_response_size()
      ) {
        _internal_cancel(
          $heap, $request_id, 406,
          "Response content length " . $input->content_length() .
          " is greater than specified MaxSize of " .
          $heap->{factory}->max_response_size() .
          ".  Use range requests to retrieve specific amounts of content."
        );
        return;
      }

      $request->[REQ_STATE] |= RS_IN_CONTENT;
      $request->[REQ_STATE] &= ~RS_IN_HEAD;
      #FIXME: probably want to find out when the content from this
      #       request is in, and only then do the new request, so we
      #       can reuse the connection.
      if (_try_redirect($request_id, $input, $request)) {
        my $old_request = delete $heap->{request}->{$request_id};
        delete $heap->{wheel_to_request}->{$wheel_id};
        if (defined $old_request) {
          DEBUG and warn "I/O: removed request $request_id";
          delete $heap->{ext_request_to_int_id}{$old_request->[REQ_HTTP_REQUEST]};
          $old_request->remove_timeout();
          $old_request->close_connection();
        }
        return;
      }

      # RFC 2616 14.41:  If multiple encodings have been applied to an
      # entity, the transfer-codings MUST be listed in the order in
      # which they were applied.

      my ($filter, @filters);

      # Transfer encoding.

      my $te = $input->header('Transfer-Encoding');
      if (defined $te) {
        my @te = split(/\s*,\s*/, lc($te));

        while (@te and exists $te_filters{$te[-1]}) {
          my $encoding = pop @te;
          my $fclass = $te_filters{$encoding};
          push @filters, $fclass->new();
        }

        if (@te) {
          $input->header('Transfer-Encoding', join(', ', @te));
        }
        else {
          $input->header('Transfer-Encoding', undef);
        }
      }

      # Content encoding.

      my $ce = $input->header('Content-Encoding');
      if (defined $ce) {
        my @ce = split(/\s*,\s*/, lc($ce));

        while (@ce and exists $te_filters{$ce[-1]}) {
          my $encoding = pop @ce;
          my $fclass = $te_filters{$encoding};
          push @filters, $fclass->new();
        }

        if (@ce) {
          $input->header('Content-Encoding', join(', ', @ce));
        }
        else {
          $input->header('Content-Encoding', undef);
        }
      }

      if (@filters > 1) {
        $filter = POE::Filter::Stackable->new( Filters => \@filters );
      }
      elsif (@filters) {
        $filter = $filters[0];
      }
      else {
        # Punt if we have no specified filters.
        $filter = POE::Filter::Stream->new;
      }

      # do this last, because it triggers a read
      $request->wheel->set_input_filter($filter);
    }
    return;
  }

  # We're in a content state.
  if ($request->[REQ_STATE] & RS_IN_CONTENT) {
    if (ref($input) and UNIVERSAL::isa($input, 'HTTP::Response')) {
      # there was a problem in the input filter
      # $request->close_connection;
    }
    else {
      $request->add_content($input);
    }
  }

  # POST response without disconnecting
  if (
    $request->[REQ_STATE] & RS_DONE and
    not $request->[REQ_STATE] & RS_POSTED
  ) {
    $request->remove_timeout;
    _finish_request($heap, $request);
  }

}


#------------------------------------------------------------------------------
# Generate a hex dump of some input. This is not a POE function.

sub _hexdump {
  my $data = shift;

  my $dump;
  my $offset = 0;
  while (length $data) {
    my $line = substr($data, 0, 16);
    substr($data, 0, 16) = '';

    my $hexdump  = unpack 'H*', $line;
    $hexdump =~ s/(..)/$1 /g;

    $line =~ tr[ -~][.]c;
    $dump .= sprintf( "%04x %-47.47s - %s\n", $offset, $hexdump, $line );
    $offset += 16;
  }

  return $dump;
}


# Check for and handle redirect.  Returns true if redirect should
# occur, or false if there's no redirect.

sub _try_redirect {
  my ($request_id, $input, $request) = @_;

  if (my $newrequest = $request->check_redirect) {
    DEBUG and warn(
      "Redirected $request_id ", $input->code, " to <",
      $newrequest->uri, ">"
    );
    my @proxy;
    if ($request->[REQ_USING_PROXY]) {
      push @proxy, (
        'http://' .  $request->host .  ':' .  $request->port .  '/'
      );
    }

    $poe_kernel->yield(
      request =>
      $request,
      $newrequest,
      "_redir_".$request->ID,
      $request->[REQ_PROG_POSTBACK],
      @proxy
    );

    return 1;
  }

  return;
}


# Complete a request. This was moved out of _poco_weeble_io_error(). This is
# not a POE function.

sub _finish_request {
  my ($heap, $request) = @_;

  my $request_id = $request->ID;
  if (DEBUG) {
    carp "XXX: calling _finish_request(request id = $request_id)";
  }

  # XXX What does this do?
  $request->add_eof;

  # KeepAlive: added the RS_POSTED flag
  $request->[REQ_STATE] |= RS_POSTED;

  my $wheel_id = defined $request->wheel ? $request->wheel->ID : "(undef)";
  DEBUG and warn "Wheel from request is ", $wheel_id;
  # clean up the request
  my $address = "$request->[REQ_HOST]:$request->[REQ_PORT]";

  DEBUG and warn "address is $address";

  return _clear_req_cache( $heap, $request_id );
}


sub _poco_weeble_remove_request {
  my ($kernel, $heap, $request_id) = @_[KERNEL, HEAP, ARG0];

  return _clear_req_cache( $heap, $request_id );
}


# helper subroutine to remove a request from our caches

sub _clear_req_cache {
  my ($heap, $request_id) = @_;

  my $request = delete $heap->{request}->{$request_id};
  return unless defined $request;

  DEBUG and warn "I/O: removed request $request_id";

  $request->remove_timeout();
  delete $heap->{ext_request_to_int_id}{$request->[REQ_HTTP_REQUEST]};
  if (my $wheel = $request->wheel) {
    delete $heap->{wheel_to_request}->{$wheel->ID};
  }

  # If the response wants us to close the connection, regrettably do
  # so.  Only matters if the request is defined.
  if ($request->[REQ_CONNECTION]) {
    if (defined(my $response = $request->[REQ_RESPONSE])) {
      my $connection_header = $response->header('Connection');
      if (defined $connection_header and $connection_header =~ /\bclose\b/) {
        DEBUG and warn "I/O: closing connection on server's request";
        $request->close_connection();
      }
    }
  }

  return;
}


# Cancel a single request by HTTP::Request object.

sub _poco_weeble_cancel {
  my ($kernel, $heap, $request) = @_[KERNEL, HEAP, ARG0];
  my $request_id = $heap->{ext_request_to_int_id}{$request};
  return unless defined $request_id;
  _internal_cancel(
    $heap, $request_id, 408, "Request timed out (request canceled)"
  );
}


sub _internal_cancel {
  my ($heap, $request_id, $code, $message) = @_;

  my $request = delete $heap->{request}{$request_id};
  return unless defined $request;

  DEBUG and warn "CXL: canceling request $request_id";
  $request->remove_timeout();
  delete $heap->{ext_request_to_int_id}{$request->[REQ_HTTP_REQUEST]};

  if ($request->wheel) {
    my $wheel_id = $request->wheel->ID;
    DEBUG and warn "CXL: Request $request_id canceling wheel $wheel_id";
    delete $heap->{wheel_to_request}{$wheel_id};
  }

  if ($request->[REQ_CONNECTION]) {
    DEBUG and warn "I/O: Closing connection during internal cancel";
    $request->close_connection();
  }
  else {
    # Didn't connect yet; inform connection manager to cancel
    # connection request.

    $heap->{cm}->deallocate($request->[REQ_CONN_ID]);
  }

  unless ($request->[REQ_STATE] & RS_POSTED) {
    $request->error($code, $message);
  }
}


# Shut down the entire component.
sub _poco_weeble_shutdown {
  my ($kernel, $heap) = @_[KERNEL, HEAP];

  $heap->{is_shut_down} = 1;

  my @request_ids = keys %{$heap->{request}};
  foreach my $request_id (@request_ids) {
    _internal_cancel(
      $heap, $request_id, 408, "Request timed out (component shut down)"
    );
  }

  # Shut down the connection manager subcomponent.
  if (defined $heap->{cm}) {
    DEBUG and warn "CXL: Client::HTTP shutting down Client::Keepalive";
    $heap->{cm}->shutdown();
    delete $heap->{cm};
  }

  # Final cleanup of this component.
  $kernel->alias_remove($heap->{alias});
}

1;

__END__

=head1 NAME

POE::Component::Client::HTTP - a HTTP user-agent component

=head1 VERSION

version 0.949

=head1 SYNOPSIS

  use POE qw(Component::Client::HTTP);

  POE::Component::Client::HTTP->spawn(
    Agent     => 'SpiffCrawler/0.90',   # defaults to something long
    Alias     => 'ua',                  # defaults to 'weeble'
    From      => 'spiffster@perl.org',  # defaults to undef (no header)
    Protocol  => 'HTTP/0.9',            # defaults to 'HTTP/1.1'
    Timeout   => 60,                    # defaults to 180 seconds
    MaxSize   => 16384,                 # defaults to entire response
    Streaming => 4096,                  # defaults to 0 (off)
    FollowRedirects => 2,               # defaults to 0 (off)
    Proxy     => "http://localhost:80", # defaults to HTTP_PROXY env. variable
    NoProxy   => [ "localhost", "127.0.0.1" ], # defs to NO_PROXY env. variable
    BindAddr  => "12.34.56.78",         # defaults to INADDR_ANY
  );

  $kernel->post(
    'ua',        # posts to the 'ua' alias
    'request',   # posts to ua's 'request' state
    'response',  # which of our states will receive the response
    $request,    # an HTTP::Request object
  );

  # This is the sub which is called when the session receives a
  # 'response' event.
  sub response_handler {
    my ($request_packet, $response_packet) = @_[ARG0, ARG1];

    # HTTP::Request
    my $request_object  = $request_packet->[0];

    # HTTP::Response
    my $response_object = $response_packet->[0];

    my $stream_chunk;
    if (! defined($response_object->content)) {
      $stream_chunk = $response_packet->[1];
    }

    print(
      "*" x 78, "\n",
      "*** my request:\n",
      "-" x 78, "\n",
      $request_object->as_string(),
      "*" x 78, "\n",
      "*** their response:\n",
      "-" x 78, "\n",
      $response_object->as_string(),
    );

    if (defined $stream_chunk) {
      print "-" x 40, "\n", $stream_chunk, "\n";
    }

    print "*" x 78, "\n";
  }

=head1 DESCRIPTION

POE::Component::Client::HTTP is an HTTP user-agent for POE.  It lets
other sessions run while HTTP transactions are being processed, and it
lets several HTTP transactions be processed in parallel.

It supports keep-alive through POE::Component::Client::Keepalive,
which in turn uses POE::Component::Resolver for asynchronous IPv4 and
IPv6 name resolution.

HTTP client components are not proper objects.  Instead of being
created, as most objects are, they are "spawned" as separate sessions.
To avoid confusion (and hopefully not cause other confusion), they
must be spawned with a C<spawn> method, not created anew with a C<new>
one.

=head1 CONSTRUCTOR

=head2 spawn

PoCo::Client::HTTP's C<spawn> method takes a few named parameters:

=over 2

=item Agent => $user_agent_string

=item Agent => \@list_of_agents

If a UserAgent header is not present in the HTTP::Request, a random
one will be used from those specified by the C<Agent> parameter.  If
none are supplied, POE::Component::Client::HTTP will advertise itself
to the server.

C<Agent> may contain a reference to a list of user agents.  If this is
the case, PoCo::Client::HTTP will choose one of them at random for
each request.

=item Alias => $session_alias

C<Alias> sets the name by which the session will be known.  If no
alias is given, the component defaults to "weeble".  The alias lets
several sessions interact with HTTP components without keeping (or
even knowing) hard references to them.  It's possible to spawn several
HTTP components with different names.

=item ConnectionManager => $poco_client_keepalive

C<ConnectionManager> sets this component's connection pool manager.
It expects the connection manager to be a reference to a
POE::Component::Client::Keepalive object.  The HTTP client component
will call C<allocate()> on the connection manager itself so you should
not have done this already.

  my $pool = POE::Component::Client::Keepalive->new(
    keep_alive    => 10, # seconds to keep connections alive
    max_open      => 100, # max concurrent connections - total
    max_per_host  => 20, # max concurrent connections - per host
    timeout       => 30, # max time (seconds) to establish a new connection
  );

  POE::Component::Client::HTTP->spawn(
    # ...
    ConnectionManager => $pool,
    # ...
  );

See L<POE::Component::Client::Keepalive> for more information,
including how to alter the connection manager's resolver
configuration (for example, to force IPv6 or prefer it before IPv4).

=item CookieJar => $cookie_jar

C<CookieJar> sets the component's cookie jar.  It expects the cookie
jar to be a reference to a HTTP::Cookies object.

=item From => $admin_address

C<From> holds an e-mail address where the client's administrator
and/or maintainer may be reached.  It defaults to undef, which means
no From header will be included in requests.

=item MaxSize => OCTETS

C<MaxSize> specifies the largest response to accept from a server.
The content of larger responses will be truncated to OCTET octets.
This has been used to return the <head></head> section of web pages
without the need to wade through <body></body>.

=item NoProxy => [ $host_1, $host_2, ..., $host_N ]

=item NoProxy => "host1,host2,hostN"

C<NoProxy> specifies a list of server hosts that will not be proxied.
It is useful for local hosts and hosts that do not properly support
proxying.  If NoProxy is not specified, a list will be taken from the
NO_PROXY environment variable.

  NoProxy => [ "localhost", "127.0.0.1" ],
  NoProxy => "localhost,127.0.0.1",

=item BindAddr => $local_ip

Specify C<BindAddr> to bind all client sockets to a particular local
address.  The value of BindAddr will be passed through
POE::Component::Client::Keepalive to POE::Wheel::SocketFactory (as
C<bind_address>).  See that module's documentation for implementation
details.

  BindAddr => "12.34.56.78"

=item Protocol => $http_protocol_string

C<Protocol> advertises the protocol that the client wishes to see.
Under normal circumstances, it should be left to its default value:
"HTTP/1.1".

=item Proxy => [ $proxy_host, $proxy_port ]

=item Proxy => $proxy_url

=item Proxy => $proxy_url,$proxy_url,...

C<Proxy> specifies one or more proxy hosts that requests will be
passed through.  If not specified, proxy servers will be taken from
the HTTP_PROXY (or http_proxy) environment variable.  No proxying will
occur unless Proxy is set or one of the environment variables exists.

The proxy can be specified either as a host and port, or as one or
more URLs.  Proxy URLs must specify the proxy port, even if it is 80.

  Proxy => [ "127.0.0.1", 80 ],
  Proxy => "http://127.0.0.1:80/",

C<Proxy> may specify multiple proxies separated by commas.
PoCo::Client::HTTP will choose proxies from this list at random.  This
is useful for load balancing requests through multiple gateways.

  Proxy => "http://127.0.0.1:80/,http://127.0.0.1:81/",

=item Streaming => OCTETS

C<Streaming> changes allows Client::HTTP to return large content in
chunks (of OCTETS octets each) rather than combine the entire content
into a single HTTP::Response object.

By default, Client::HTTP reads the entire content for a response into
memory before returning an HTTP::Response object.  This is obviously
bad for applications like streaming MP3 clients, because they often
fetch songs that never end.  Yes, they go on and on, my friend.

When C<Streaming> is set to nonzero, however, the response handler
receives chunks of up to OCTETS octets apiece.  The response handler
accepts slightly different parameters in this case.  ARG0 is also an
HTTP::Response object but it does not contain response content,
and ARG1 contains a a chunk of raw response
content, or undef if the stream has ended.

  sub streaming_response_handler {
    my $response_packet = $_[ARG1];
    my ($response, $data) = @$response_packet;
    print SAVED_STREAM $data if defined $data;
  }

=item FollowRedirects => $number_of_hops_to_follow

C<FollowRedirects> specifies how many redirects (e.g. 302 Moved) to
follow.  If not specified defaults to 0, and thus no redirection is
followed.  This maintains compatibility with the previous behavior,
which was not to follow redirects at all.

If redirects are followed, a response chain should be built, and can
be accessed through $response_object->previous(). See HTTP::Response
for details here.

=item Timeout => $query_timeout

C<Timeout> sets how long POE::Component::Client::HTTP has to process
an application's request, in seconds.  C<Timeout> defaults to 180
(three minutes) if not specified.

It's important to note that the timeout begins when the component
receives an application's request, not when it attempts to connect to
the web server.

Timeouts may result from sending the component too many requests at
once.  Each request would need to be received and tracked in order.
Consider this:

  $_[KERNEL]->post(component => request => ...) for (1..15_000);

15,000 requests are queued together in one enormous bolus.  The
component would receive and initialize them in order.  The first
socket activity wouldn't arrive until the 15,000th request was set up.
If that took longer than C<Timeout>, then the requests that have
waited too long would fail.

C<ConnectionManager>'s own timeout and concurrency limits also affect
how many requests may be processed at once.  For example, most of the
15,000 requests would wait in the connection manager's pool until
sockets become available.  Meanwhile, the C<Timeout> would be counting
down.

Applications may elect to control concurrency outside the component's
C<Timeout>.  They may do so in a few ways.

The easiest way is to limit the initial number of requests to
something more manageable.  As responses arrive, the application
should handle them and start new requests.  This limits concurrency to
the initial request count.

An application may also outsource job throttling to another module,
such as POE::Component::JobQueue.

In any case, C<Timeout> and C<ConnectionManager> may be tuned to
maximize timeouts and concurrency limits.  This may help in some
cases.  Developers should be aware that doing so will increase memory
usage.  POE::Component::Client::HTTP and KeepAlive track requests in
memory, while applications are free to keep pending requests on disk.

=back

=head1 ACCEPTED EVENTS

Sessions communicate asynchronously with PoCo::Client::HTTP.  They
post requests to it, and it posts responses back.

=head2 request

Requests are posted to the component's "request" state.  They include
an HTTP::Request object which defines the request.  For example:

  $kernel->post(
    'ua', 'request',            # http session alias & state
    'response',                 # my state to receive responses
    GET('http://poe.perl.org'), # a simple HTTP request
    'unique id',                # a tag to identify the request
    'progress',                 # an event to indicate progress
    'http://1.2.3.4:80/'        # proxy to use for this request
  );

Requests include the state to which responses will be posted.  In the
previous example, the handler for a 'response' state will be called
with each HTTP response.  The "progress" handler is optional and if
installed, the component will provide progress metrics (see sample
handler below).  The "proxy" parameter is optional and if not defined,
a default proxy will be used if configured.  No proxy will be used if
neither a default one nor a "proxy" parameter is defined.

=head2 pending_requests_count

There's also a pending_requests_count state that returns the number of
requests currently being processed.  To receive the return value, it
must be invoked with $kernel->call().

  my $count = $kernel->call('ua' => 'pending_requests_count');

NOTE: Sometimes the count might not be what you expected, because responses
are currently in POE's queue and you haven't processed them. This could happen
if you configure the C<ConnectionManager>'s concurrency to a high enough value.

=head2 cancel

Cancel a specific HTTP request.  Requires a reference to the original
request (blessed or stringified) so it knows which one to cancel.  See
L<progress handler> below for notes on canceling streaming requests.

To cancel a request based on its blessed HTTP::Request object:

  $kernel->post( component => cancel => $http_request );

To cancel a request based on its stringified HTTP::Request object:

  $kernel->post( component => cancel => "$http_request" );

=head2 shutdown

Responds to all pending requests with 408 (request timeout), and then
shuts down the component and all subcomponents.

=head1 SENT EVENTS

=head2 response handler

In addition to all the usual POE parameters, HTTP responses come with
two list references:

  my ($request_packet, $response_packet) = @_[ARG0, ARG1];

C<$request_packet> contains a reference to the original HTTP::Request
object.  This is useful for matching responses back to the requests
that generated them.

  my $http_request_object = $request_packet->[0];
  my $http_request_tag    = $request_packet->[1]; # from the 'request' post

C<$response_packet> contains a reference to the resulting
HTTP::Response object.

  my $http_response_object = $response_packet->[0];

Please see the HTTP::Request and HTTP::Response manpages for more
information.

=head2 progress handler

The example progress handler shows how to calculate a percentage of
download completion.

  sub progress_handler {
    my $gen_args  = $_[ARG0];    # args passed to all calls
    my $call_args = $_[ARG1];    # args specific to the call

    my $req = $gen_args->[0];    # HTTP::Request object being serviced
    my $tag = $gen_args->[1];    # Request ID tag from.
    my $got = $call_args->[0];   # Number of bytes retrieved so far.
    my $tot = $call_args->[1];   # Total bytes to be retrieved.
    my $oct = $call_args->[2];   # Chunk of raw octets received this time.

    my $percent = $got / $tot * 100;

    printf(
      "-- %.0f%% [%d/%d]: %s\n", $percent, $got, $tot, $req->uri()
    );

    # To cancel the request:
    # $_[KERNEL]->post( component => cancel => $req );
  }

=head3 DEPRECATION WARNING

The third return argument (the raw octets received) has been deprecated.
Instead of it, use the Streaming parameter to get chunks of content
in the response handler.

=head1 REQUEST CALLBACKS

The HTTP::Request object passed to the request event can contain a
CODE reference as C<content>.  This allows for sending large files
without wasting memory.  Your callback should return a chunk of data
each time it is called, and an empty string when done.  Don't forget
to set the Content-Length header correctly.  Example:

  my $request = HTTP::Request->new( PUT => 'http://...' );

  my $file = '/path/to/large_file';

  open my $fh, '<', $file;

  my $upload_cb = sub {
    if ( sysread $fh, my $buf, 4096 ) {
      return $buf;
    }
    else {
      close $fh;
      return '';
    }
  };

  $request->content_length( -s $file );

  $request->content( $upload_cb );

  $kernel->post( ua => request, 'response', $request );

=head1 CONTENT ENCODING AND COMPRESSION

Transparent content decoding has been disabled as of version 0.84.
This also removes support for transparent gzip requesting and
decompression.

To re-enable gzip compression, specify the gzip Content-Encoding and
use HTTP::Response's decoded_content() method rather than content():

  my $request = HTTP::Request->new(
    GET => "http://www.yahoo.com/", [
      'Accept-Encoding' => 'gzip'
    ]
  );

  # ... time passes ...

  my $content = $response->decoded_content();

The change in POE::Component::Client::HTTP behavior was prompted by
changes in HTTP::Response that surfaced a bug in the component's
transparent gzip handling.

Allowing the application to specify and handle content encodings seems
to be the most reliable and flexible resolution.

For more information about the problem and discussions regarding the
solution, see:
L<http://www.perlmonks.org/?node_id=683833> and
L<http://rt.cpan.org/Ticket/Display.html?id=35538>

=head1 CLIENT HEADERS

POE::Component::Client::HTTP sets its own response headers with
additional information.  All of its headers begin with "X-PCCH".

=head2 X-PCCH-Errmsg

POE::Component::Client::HTTP may fail because of an internal client
error rather than an HTTP protocol error.  X-PCCH-Errmsg will contain a
human readable reason for client failures, should they occur.

The text of X-PCCH-Errmsg may also be repeated in the response's
content.

=head2 X-PCCH-Peer

X-PCCH-Peer contains the remote IPv4 address and port, separated by a
period.  For example, "127.0.0.1.8675" represents port 8675 on
localhost.

Proxying will render X-PCCH-Peer nearly useless, since the socket will
be connected to a proxy rather than the server itself.

This feature was added at Doreen Grey's request.  Doreen wanted a
means to find the remote server's address without having to make an
additional request.

=head1 ENVIRONMENT

POE::Component::Client::HTTP uses two standard environment variables:
HTTP_PROXY and NO_PROXY.

HTTP_PROXY sets the proxy server that Client::HTTP will forward
requests through.  NO_PROXY sets a list of hosts that will not be
forwarded through a proxy.

See the Proxy and NoProxy constructor parameters for more information
about these variables.

=head1 SEE ALSO

This component is built upon HTTP::Request, HTTP::Response, and POE.
Please see its source code and the documentation for its foundation
modules to learn more.  If you want to use cookies, you'll need to
read about HTTP::Cookies as well.

Also see the test program, t/01_request.t, in the PoCo::Client::HTTP
distribution.

=head1 BUGS

There is no support for CGI_PROXY or CgiProxy.

Secure HTTP (https) proxying is not supported at this time.

There is no object oriented interface.  See
L<POE::Component::Client::Keepalive> and
L<POE::Component::Resolver> for examples of a decent OO interface.

=head1 AUTHOR, COPYRIGHT, & LICENSE

POE::Component::Client::HTTP is

=over 2

=item

Copyright 1999-2009 Rocco Caputo

=item

Copyright 2004 Rob Bloodgood

=item

Copyright 2004-2005 Martijn van Beers

=back

All rights are reserved.  POE::Component::Client::HTTP is free
software; you may redistribute it and/or modify it under the same
terms as Perl itself.

=head1 CONTRIBUTORS

Joel Bernstein solved some nasty race conditions.  Portugal Telecom
L<http://www.sapo.pt/> was kind enough to support his contributions.

Jeff Bisbee added POD tests and documentation to pass several of them
to version 0.79.  He's a kwalitee-increasing machine!

=head1 BUG TRACKER

https://rt.cpan.org/Dist/Display.html?Queue=POE-Component-Client-HTTP

=head1 REPOSITORY

Github: L<http://github.com/rcaputo/poe-component-client-http> .

Gitorious: L<http://gitorious.org/poe-component-client-http> .

=head1 OTHER RESOURCES

L<http://search.cpan.org/dist/POE-Component-Client-HTTP/>

=cut