Cleaned up demos, various build fixes
[urisagit/Stem.git] / bin / cgi2stem.pl
CommitLineData
4536f655 1#!/usr/local/bin/perl -wT
2
3# This is a CGI script that interfaces to stem. it collects all the
4# CGI data and sends it to a Stem::SockMsg cell as a single
5# Stem::Packet. It reads a single Stem::Packet back from the socket
6# and uses the data in there to generate a response page.
7
8$|++ ;
9
10use strict ;
11use lib '/wrk/stem/src/stem/lib/' ;
12
13use CGI ;
14use CGI::Carp qw(fatalsToBrowser) ;
15use IO::Socket ;
16
17use Stem::Packet ;
18
19my $cgi = CGI->new() ;
20
21my %cgi_data ;
22
23# get all the cgi data we can
24
25$cgi_data{ 'params' } = get_cgi_data( 'param' ) ;
26$cgi_data{ 'cookies' } = get_cgi_data( 'cookie' ) ;
27#$cgi_data{ 'env' } = { %ENV } ;
28#$cgi_data{ 'self_url' } = $cgi->self_url() ;
29$cgi_data{ 'url' } = $cgi->url() ;
30#$cgi_data{ 'cgi' } = $cgi ;
31
32# todo: handle default host:port here
33
34my $data = send_and_get_packet( \%cgi_data ) ;
35
36# use Data::Dumper ;
37
38# print $cgi->header() ;
39# # print "<PRE>\n", Dumper( \%cgi_data ), "\n</PRE>\n" ;
40# print "<PRE>\n", Dumper( $data ), "\n</PRE>\n" ;
41
42# exit ;
43
44if ( ref $data eq 'SCALAR' ) {
45
46 print $$data ;
47 exit ;
48}
49
50print $cgi->header(), <<HTML ;
51<HTML>
52cgi2stem error: $data
53</HTML>
54HTML
55
56
57
58# this works for both cookies and params as their APIs are the same
59
60sub get_cgi_data {
61
62 my( $type ) = @_ ;
63
64 my %cgi_info ;
65
66 foreach my $name ( $cgi->$type() ) { ;
67
68 my @values = $cgi->$type( $name ) ;
69
70 if ( @values > 1 ) {
71 $cgi_info{ $type } = \@values ;
72 next ;
73 }
74
75 $cgi_info{ $name } = shift @values ;
76 }
77
78 return \%cgi_info ;
79}
80
81sub send_and_get_packet {
82
83 my( $in_data, $host, $port ) = @_ ;
84
85 $port ||= 9999 ;
86 $host ||= 'localhost' ;
87
88 my $sock = IO::Socket::INET->new( "$host:$port" ) ;
89
90 $sock or return "can't connect to $host:$port\n" ;
91
92 my $packet = Stem::Packet->new( codec => 'Storable' ) ;
93
94 my $write_buf = $packet->to_packet($in_data) ;
95
96 syswrite( $sock, $$write_buf ) ;
97
98 my $read_buf ;
99
100 while( 1 ) {
101
102 my $bytes_read = sysread( $sock, $read_buf, 8192 ) ;
103
104 return "sysread error $!" unless defined $bytes_read ;
105 return "sysread closed" if $bytes_read == 0 ;
106
107 my $result = $packet->to_data( $read_buf ) ;
108
109 return $result if $result ;
110 }
111}