-
-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathMessage.rakumod
356 lines (270 loc) · 8.45 KB
/
Message.rakumod
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
unit class HTTP::Message;
use HTTP::Header;
use HTTP::MediaType;
use Encode;
has HTTP::Header $.header = HTTP::Header.new;
has $.content is rw;
has $.protocol is rw = 'HTTP/1.1';
has Bool $.binary = False;
has Str @.text-types;
my $CRLF = "\r\n";
method new($content?, *%fields) {
my $header = HTTP::Header.new(|%fields);
self.bless(:$header, :$content);
}
method add-content($content) {
$.content ~= $content;
}
class X::Decoding is Exception {
has HTTP::Message $.response;
has Blob $.content;
method message() {
"Problem decoding content";
}
}
method content-type() returns Str {
$!header.field('Content-Type').values[0] || '';
}
has HTTP::MediaType $!media-type;
method media-type() returns HTTP::MediaType {
if not $!media-type.defined {
if self.content-type() -> $ct {
$!media-type = HTTP::MediaType.parse($ct);
}
}
$!media-type;
}
# Don't want to put the heuristic in the HTTP::MediaType
# Also moving this here makes it much more easy to test
method charset() returns Str {
if self.media-type -> $mt {
$mt.charset || ( $mt.major-type eq 'text' ?? $mt.sub-type eq 'html' ?? 'utf-8' !! 'iso-8859-1' !! 'utf-8');
}
else {
# At this point we're probably screwed anyway
'iso-8859-1'
}
}
# This is already a candidate for refactoring
# Just want to get it working
method is-text() returns Bool {
my Bool $ret = do {
if $!binary {
False;
}
else {
if self.media-type -> $mt {
if $mt.type ~~ any(@!text-types) {
True;
}
else {
given $mt.major-type {
when 'text' {
True;
}
when any(<image audio video>) {
False;
}
when 'application' {
given $mt.sub-type {
when /xml|javascript|json/ {
True;
}
default {
False;
}
}
}
default {
# Not sure about this
True;
}
}
}
}
else {
# No content type, try and blow up
True;
}
}
}
$ret;
}
method is-binary() returns Bool {
!self.is-text;
}
method content-encoding() {
$!header.field('Content-Encoding');
}
class X::Deflate is Exception {
has Str $.message;
}
method inflate-content() returns Blob {
if self.content-encoding -> $v is copy {
# This is a guess
$v = 'zlib' if $v eq 'compress' ;
$v = 'zlib' if $v eq 'deflate';
try require ::('Compress::Zlib');
if ::('Compress::Zlib::Stream') ~~ Failure {
X::Deflate.new(message => "Please install 'Compress::Zlib' to uncompress '$v' encoded content").throw;
}
else {
my $z = ::('Compress::Zlib::Stream').new( |{ $v => True });
$z.inflate($!content);
}
}
else {
$!content;
}
}
method decoded-content(:$bin) {
return $!content if $!content ~~ Str || $!content.bytes == 0;
my $content = self.inflate-content;
# [todo]
# If charset is missing from Content-Type, then before defaulting
# to anything it should attempt to extract it from $.content like (for HTML):
# <meta charset="UTF-8">
# <meta http-equiv="content-type" content="text/html; charset=UTF-8">
my $decoded_content;
if !$bin && self.is-text {
my $charset = self.charset;
$decoded_content = try {
Encode::decode($charset, $content);
} || try {
$content.decode('iso-8859-1');
} || try {
$content.unpack("A*")
} || X::Decoding.new(content => $content, response => self).throw;
}
else {
$decoded_content = $content;
}
$decoded_content
}
multi method field(Str $f) {
$.header.field($f);
}
multi method field(*%fields) {
$.header.field(|%fields);
}
method push-field(*%fields) {
$.header.push-field(|%fields);
}
method remove-field(Str $field) {
$.header.remove-field($field);
}
method clear {
$.header.clear;
$.content = '';
}
method parse($raw_message) {
my @lines = $raw_message.split(/$CRLF/);
my ($first, $second, $third);
($first, $second, $third) = @lines.shift.split(/\s+/);
if $third.index('/') { # is a request
$.protocol = $third;
} else { # is a response
$.protocol = $first;
}
loop {
last until @lines;
my $line = @lines.shift;
if $line {
my ($k, $v) = $line.split(/\:\s*/, 2);
if $k and $v {
if $.header.field($k) {
$.header.push-field: |($k => $v.split(',')>>.trim);
} else {
$.header.field: |($k => $v.split(',')>>.trim);
}
}
} else {
$.content = @lines.grep({ $_ }).join("\n");
last;
}
}
self;
}
method Str($eol = "\n", :$debug, Bool :$bin) {
my constant $max_size = 300;
my $s = $.header.Str($eol);
$s ~= $eol if $.content;
# The :bin will be passed from the H::UA
if not $bin {
$s ~= $.content ~ $eol if $.content and !$debug;
}
if $.content and $debug {
if $bin || self.is-binary {
$s ~= $eol ~ "=Content size : " ~ $.content.elems ~ " bytes ";
$s ~= "$eol ** Not showing binary content ** $eol";
}
else {
$s ~= $eol ~ "=Content size: "~$.content.Str.chars~" chars";
$s ~= "- Displaying only $max_size" if $.content.Str.chars > $max_size;
$s ~= $eol ~ $.content.Str.substr(0, $max_size) ~ $eol;
}
}
return $s;
}
=begin pod
=head1 NAME
HTTP::Message - class encapsulating HTTP message
=head1 SYNOPSIS
use HTTP::Message;
my $raw_msg = "GET / HTTP/1.1\r\nHost: somehost\r\n\r\n";
my $mess = HTTP::Message.new.parse($raw_msg);
say $mess;
=head1 DESCRIPTION
This module provides a bunch of methods to easily manage HTTP message.
=head1 METHODS
=head2 method new
method new($content?, *%fields)
A constructor, takes following parameters:
=item content : content of the message (optional)
=item fields : fields of the header section
my $msg = HTTP::Message.new('content', :field<value>);
=head2 method add-content
method add-content(HTTP::Message:, Str $content)
Adds HTTP message content. It does not remove the existing value,
it concats to the existing content.
my $msg = HTTP::Message.new('content', :field<value>);
$msg.add-content: 's';
say $msg.content; # says 'contents'
=head2 method decoded-content
method decoded-content(HTTP::Message:)
Returns decoded content of the message (using L<Encode> module to decode).
my $msg = HTTP::Message.new();
say $msg.decoded-content;
=head2 method field
multi method field(HTTP::Message:, Str $s) returns HTTP::Header::Field
multi method field(HTTP::Message:, *%fields)
See L<HTTP::Header>.
=head2 method init-field
method init-field(HTTP::Message:, *%fields)
See L<HTTP::Header>.
=head2 method push-field
method push-field(HTTP::Message:, HTTP::Header::Field $field)
See L<HTTP::Header>.
=head2 method remove-field
method remove-field(HTTP::Message:, Str $field)
See L<HTTP::Header>.
=head2 method clear
method clear(HTTP::Message:)
Removes the whole message, both header and content section.
my $msg = HTTP::Message.new('content', :field<value>);
$msg.clear;
say ~$msg; # says nothing
=head2 method parse
method parse(HTTP::Message:, Str $raw_message) returns HTTP::Message
Parses the whole HTTP message.
It takes the HTTP message (with \r\n as a line separator)
and obtain the header and content section, creates a HTTP::Header
object.
my $msg = HTTP::Message.new.parse("GET / HTTP/1.1\r\nHost: example\r\ncontent\r\n");
say $msg.perl;
=head2 method Str
method Str(HTTP::Message:, Str $eol = "\n") returns Str
Returns HTTP message in a readable form.
=head1 SEE ALSO
L<HTTP::Request>, L<HTTP::Response>, L<Encode>
=end pod