-
Notifications
You must be signed in to change notification settings - Fork 7
/
Moxy.pm
322 lines (268 loc) · 8.65 KB
/
Moxy.pm
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
package Moxy;
use strict;
use warnings;
use Class::Component 0.16;
our $VERSION = '0.41';
use Carp;
use Encode;
use File::Spec::Functions;
use FindBin;
use HTML::Entities;
use HTML::Parser;
use HTML::TreeBuilder::XPath;
use HTML::TreeBuilder;
use LWP::UserAgent;
use MIME::Base64;
use Moxy::Util;
use Params::Validate ':all';
use Path::Class;
use Scalar::Util qw/blessed/;
use UNIVERSAL::require;
use URI::Escape;
use URI::Heuristic qw(uf_uristr);
use URI;
use YAML;
use HTTP::MobileAttribute plugins => [
qw/CarrierLetter IS/,
{
module => 'Display',
config => {
DoCoMoMap => YAML::LoadFile(
catfile( 'assets', 'common', 'docomo-display-map.yaml' )
)
}
},
];
__PACKAGE__->load_components(qw/Plaggerize Autocall::InjectMethod Context/);
__PACKAGE__->load_plugins(qw/DisplayWidth ControlPanel LocationBar Pictogram/);
sub new {
my ($class, $config) = @_;
my $self = $class->NEXT( 'new' => { config => $config } );
$self->conf->{global}->{log}->{fh} ||= \*STDERR;
$self->_init_storage;
return $self;
}
sub assets_path {
my $self = shift;
return $self->{__assets_path} ||= do {
$self->conf->{global}->{assets_path}
|| dir( $FindBin::RealBin, 'assets' )->stringify;
};
}
# -------------------------------------------------------------------------
sub _init_storage {
my ($self, ) = @_;
my $mod = $self->{config}->{global}->{storage}->{module};
$mod = $mod ? "Moxy::Storage::$mod" : 'Moxy::Storage::DBM_File';
$mod->use or die $@;
$self->{storage} = $mod->new($self, $self->conf->{global}->{storage} || {});
}
sub storage { shift->{storage} }
# -------------------------------------------------------------------------
sub run_hook_and_get_response {
my ($self, $hook, @args) = @_;
$self->log(debug => "Run hook and get response: $hook");
for my $action (@{$self->class_component_hooks->{$hook}}) {
my $code = $action->{plugin}->can($action->{method});
my $response = $code->($action->{plugin}, $self, @args);
return $response if blessed $response && $response->isa('HTTP::Response');
}
return; # not finished yet
}
sub rewrite {
my ($base, $html, $url) = @_;
my $base_url = URI->new($url);
# parse.
my $tree = HTML::TreeBuilder::XPath->new;
$tree->implicit_tags(0);
$tree->no_space_compacting(1);
$tree->ignore_ignorable_whitespace(0);
$tree->store_comments(1);
$tree->ignore_unknown(0);
$tree->parse($html);
$tree->eof;
# define replacer.
my $replace = sub {
my ( $tag, $attr_name ) = @_;
for my $node ( $tree->findnodes("//$tag") ) {
if ( my $attr = $node->attr($attr_name) ) {
$node->attr(
$attr_name => sprintf( qq{%s%s%s},
$base,
($base =~ m{/$} ? '' : '/'),
uri_escape( URI->new($attr)->abs($base_url) ) )
);
}
}
};
# replace.
$replace->( 'img' => 'src' );
$replace->( 'script' => 'src' );
$replace->( 'form' => 'action' );
$replace->( 'a' => 'href' );
$replace->( 'link' => 'href' );
# dump.
my $result = $tree->as_HTML(q{<>"&'});
$tree = $tree->delete; # cleanup :-) HTML::TreeBuilder needs this.
# return result.
return $result;
}
sub render_start_page {
my $base = shift;
return sprintf(<<"...");
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="ja" xml:lang="ja" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-script-type" content="text/javascript" />
<script type="text/javascript">
window.onload = function () {
document.getElementById('moxy_url').focus();
};
</script>
</head>
<body>
<form method="get" action="$base" onsubmit="location.href=location.href+encodeURIComponent(document.getElementById('moxy_url').value);return false;">
<input type="text" size="40" id="moxy_url" />
<input type="submit" value="go" />
</form>
</body>
</html>
...
}
sub handle_request {
my ($self, $c) = @_;
my $session_id = join ',', $c->req->headers->authorization_basic;
$self->log(debug => "Authorization header: $session_id");
if ($session_id) {
$self->_make_response(
c => $c,
user_id => $session_id,
);
} else {
$c->res->status(401);
$c->res->headers->www_authenticate(qq{Basic realm="Moxy needs basic auth.Only for identification.Password is dummy."});
$c->res->body('authentication required');
}
}
sub _make_response {
my $self = shift;
my %args = validate(
@_ => +{
c => { isa => 'HTTP::Engine::Context', },
user_id => { type => SCALAR },
}
);
my $c = $args{c};
my $base = $c->req->uri->clone;
$base->path('');
$base->query_form({});
(my $url = $c->req->uri->path_query) =~ s!^/!!;
$url = uf_uristr(uri_unescape $url);
if ($url) {
# do proxy
my $res = $self->_do_request(
url => $url,
request => $c->req->as_http_request,
user_id => $args{user_id},
);
$self->log(debug => '-- response status: ' . $res->code);
if ($res->code == 302) {
# rewrite redirect
my $location = URI->new($res->header('Location'));
$self->log(debug => "redirect to $location");
my $uri = URI->new($url);
if ($uri->port != 80 && $location->port != $uri->port) {
$location->port($uri->port);
}
$res->header( 'Location' => $base . '/' . uri_escape( $location ) );
$self->log(debug => "redirect to " . $res->header('Location'));
} else {
my $content_type = $res->header('Content-Type');
$self->log("Content-Type: $content_type");
if ($content_type =~ /html/i) {
$res->content( encode($res->charset, rewrite($base, decode($res->charset, $res->content), $url)) );
}
use bytes;
$res->header('Content-Length' => bytes::length($res->content));
}
$c->res->set_http_response($res);
} else {
# please input url.
$c->res->status(200);
$c->res->content_type('text/html; charset=utf8');
$c->res->body( render_start_page($base) );
}
}
sub _do_request {
my $self = shift;
my %args = validate(
@_ => +{
url => qr{^https?://},
request => { isa => 'HTTP::Request' },
user_id => { type => SCALAR },
}
);
# make request
my $req = $args{request}->clone;
$req->uri($args{url});
$req->header('Host' => URI->new($args{url})->host);
$self->run_hook(
'request_filter_process_agent',
{ request => $req, # HTTP::Request object
user => $args{user_id},
}
);
my $mobile_attribute = HTTP::MobileAttribute->new($req->headers);
my $carrier = $mobile_attribute->carrier;
for my $hook ('request_filter', "request_filter_$carrier") {
my $response = $self->run_hook_and_get_response(
$hook,
+{
request => $req, # HTTP::Request object
mobile_attribute => $mobile_attribute,
user => $args{user_id},
}
);
if ($response) {
return $response; # finished
}
}
# do request
my $ua = LWP::UserAgent->new(
timeout => $self->conf->{global}->{timeout} || 10,
max_redirects => 0,
protocols_allowed => [qw/http https/],
parse_head => 0,
);
my $response = $ua->request($req);
for my $hook ( 'response_filter', "response_filter_$carrier", 'render_location_bar' ) {
$self->run_hook(
$hook,
{
response => $response, # HTTP::Response object
mobile_attribute => $mobile_attribute,
user => $args{user_id},
}
);
}
$response;
}
1;
__END__
=for stopwords nyarla-net
=head1 NAME
Moxy - Mobile web development proxy
=head1 DESCRIPTION
Moxy is a mobile web development proxy.
=head1 AUTHOR
Kan Fushihara
Tokuhiro Matsuno
=head1 THANKS TO
Kazuhiro Osawa
nyarla-net
=head1 LICENSE
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
=head1 SEE ALSO
L<http://coderepos.org/share/wiki/ssb>