Phoebe/Gopher.pm untested

filter: Statementstmt 0.0% 0 / 199 Branchbran 0.0% 0 / 50 Conditioncond 0.0% 0 / 20 MC/DCmcdc 0.0% 0 / 11 Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 13 totaltotal 0.0% 0 / 314 CC 26 SCAR 36.1
CC
26
Cov
0%
serve_gopher
110.0
gopher_plain_text
56.0
gopher_startup
20.0
CRAP 36.8
1 # -*- mode: perl -*-
2 # Copyright (C) 2017–2021 Alex Schroeder <alex@gnu.org>
3  
4 # This program is free software: you can redistribute it and/or modify it under
5 # the terms of the GNU Affero General Public License as published by the Free
6 # Software Foundation, either version 3 of the License, or (at your option) any
7 # later version.
8 #
9 # This program is distributed in the hope that it will be useful, but WITHOUT
10 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11 # FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
12 # details.
13 #
14 # You should have received a copy of the GNU Affero General Public License along
15 # with this program. If not, see <https://www.gnu.org/licenses/>.
16  
17 =encoding utf8
18  
19 =head1 NAME
20  
21 App::Phoebe::Gopher - serving a Phoebe wiki via the Gopher protocol
22  
23 =head1 DESCRIPTION
24  
25 This extension serves your Gemini pages via Gopher and generates a few automatic
26 pages for you, such as the main page.
27  
28 To configure, you need to specify the Gopher port(s) in your Phoebe F<config> file.
29 The default port is 70. This is a priviledge port. Thus, you either need to
30 grant Perl the permission to listen on a priviledged port, or you need to run
31 Phoebe as a super user. Both are potential security risk, but the first option
32 is much less of a problem, I think.
33  
34 If you want to try this, run the following as root:
35  
36 setcap 'cap_net_bind_service=+ep' $(which perl)
37  
38 Verify it:
39  
40 getcap $(which perl)
41  
42 If you want to undo this:
43  
44 setcap -r $(which perl)
45  
46 The alternative is to use a port number above 1024.
47  
48 If you don't do any of the above, you'll get a permission error on startup:
49 "Mojo::Reactor::Poll: Timer failed: Can't create listen socket: Permission
50 denied…"
51  
52 If you are virtual hosting note that the Gopher protocol is incapable of doing
53 that: the server does not know what hostname the client used to look up the IP
54 number it eventually contacted. This works for HTTP and Gemini because HTTP/1.0
55 and later added a Host header to pass this information along, and because Gemini
56 uses a URL including a hostname in its request. It does not work for Gopher.
57 This is why you need to specify the hostname via C<$gopher_host>.
58  
59 You can set the normal Gopher via C<$gopher_port> and the encrypted Gopher ports
60 via C<$gophers_port> (note the extra s). The values either be a single port, or
61 an array of ports. See the example below.
62  
63 In this example we first switch to the package namespace, set some variables,
64 and then we I<use> the package. At this point the ports are specified and the
65 server processes it starts go up, one for ever IP number serving the hostname.
66  
67 package App::Phoebe::Gopher;
68 our $gopher_host = "alexschroeder.ch";
69 our $gopher_port = [70,79]; # listen on the finger port as well
70 our $gophers_port = 7443; # listen on port 7443 using TLS
71 our $gopher_main_page = "Gopher_Welcome";
72 use App::Phoebe::Gopher;
73  
74 Note the C<finger> port in the example. This works, but it's awkward since you
75 have to finger C<page/alex> instead of C<alex>. In order to make that work, we
76 need some more code.
77  
78 package App::Phoebe::Gopher;
79 use App::Phoebe qw(@extensions port $log);
80 use Modern::Perl;
81 our $gopher_host = "alexschroeder.ch";
82 our $gopher_port = [70,79]; # listen on the finger port as well
83 our $gophers_port = 7443; # listen on port 7443 using TLS
84 our $gopher_main_page = "Gopher_Welcome";
85 our @extensions;
86 push(@extensions, \&finger);
87 sub finger {
88 my $stream = shift;
89 my $selector = shift;
90 my $port = port($stream);
91 if ($port == 79 and $selector =~ m!^[^/]+$!) {
92 $log->debug("Serving $selector via finger");
93 gopher_serve_page($stream, $gopher_host, undef, decode_utf8(uri_unescape($selector)));
94 return 1;
95 }
96 return 0;
97 }
98 use App::Phoebe::Gopher;
99  
100 =cut
101  
102 package App::Phoebe::Gopher;
103 use App::Phoebe qw(get_ip_numbers $log $server @extensions port space pages blog_pages
104 space_regex reserved_regex run_extensions text search);
105 use Modern::Perl;
106 use URI::Escape;
107 use List::Util qw(min);
108 use Encode qw(encode_utf8 decode_utf8);
109 use Text::Wrapper;
110 use utf8;
111  
112 our $gopher_header = "iPhlog:\n"; # must start with 'i'
113 our $gopher_port ||= 70;
114 our $gophers_port = [];
115 our $gopher_host;
116 our $gopher_main_page;
117 our ($server, $log, @main_menu);
118  
119 use Mojo::IOLoop;
120  
121 # start the loop after configuration (so that the user can change $gopher_port)
122 Mojo::IOLoop->next_tick(\&gopher_startup);
123  
124 sub gopher_startup {
125 $gopher_host ||= (keys %{$server->{host}})[0];
126 for my $address (get_ip_numbers($gopher_host)) {
127 my @ports = ref $gopher_port ? @$gopher_port : ($gopher_port);
128 my %tls = map { push(@ports, $_); $_ => 1 } ref $gophers_port ? @$gophers_port : ($gophers_port);
129 for my $port (@ports) {
130 $log->info("$gopher_host: listening on $address:$port (Gopher)");
131 Mojo::IOLoop->server({
132 address => $address,
133 port => $port,
134 tls => $tls{$port},
135 tls_cert => $server->{cert_file}->{"$gopher_host:$port"},
136 tls_key => $server->{key_file}->{"$gopher_host:$port"},
137 } => sub {
138 my ($loop, $stream) = @_;
139 my $buffer;
140 $stream->on(read => sub {
141 my ($stream, $bytes) = @_;
142 $log->debug("Received " . length($bytes) . " bytes via Gopher");
143 $buffer .= $bytes;
144 if ($buffer =~ /^(.*)\r\n/) {
145 $log->debug("Looking at " . ($1 || "an empty selector"));
146 serve_gopher($stream, $1);
147 } else {
148 $log->debug("Waiting for more bytes...");
149 }
150 });
151 });
152 }
153 }
154 }
155  
156 sub serve_gopher {
157 my ($stream, $selector) = @_;
158 eval {
159 local $SIG{'ALRM'} = sub {
160 $log->error("Timeout processing $selector via Gopher");
161 };
162 alarm(10); # timeout
163 my $port = port($stream);
164 my $host = $gopher_host;
165 my $spaces = space_regex();
166 my $reserved = reserved_regex($stream);
167 my $query;
168 $log->debug("Serving Gopher on $host for spaces $spaces");
169 $log->info("Looking at " . ($selector || "an empty selector"));
170 my ($space, $id, $n, $style, $filter);
171 if (run_extensions($stream, $selector)) {
172 # config file goes first
173 } elsif (($space) = $selector =~ m!^($spaces)?(?:/page)?/?$!) {
174 # "up" from page/Alex gives us page or page/ → show main menu
175 gopher_main_menu($stream, $host, space($stream, $host, $space));
176 } elsif (($space, $n) = $selector =~ m!^(?:($spaces)/)?do/more(?:/(\d+))?$!) {
177 gopher_serve_blog($stream, $host, space($stream, $host, $space), $n);
178 } elsif (($space) = $selector =~ m!^(?:($spaces)/)?do/index$!) {
179 gopher_serve_index($stream, $host, space($stream, $host, $space));
180 } elsif ($selector =~ m!^do/source$!) {
181 seek DATA, 0, 0;
182 local $/ = undef; # slurp
183 $stream->write(encode_utf8 <DATA>);
184 } elsif (($space, $query) = $selector =~ m!^(?:($spaces)/)?do/match\t(.+)!) {
185 gopher_serve_match($stream, $host, space($stream, $host, $space), decode_utf8(uri_unescape($query)));
186 } elsif (($space, $query) = $selector =~ m!^(?:($spaces)/)?do/search\t(.+)!) {
187 gopher_serve_search($stream, $host, space($stream, $host, $space), decode_utf8(uri_unescape($query)));
188 } elsif (($space, $id, $n) = $selector =~ m!^(?:($spaces)/)?(?:page/)?([^/]+)(?:/(\d+))?$!) {
189 # the /page is optional: makes finger possible
190 gopher_serve_page($stream, $host, space($stream, $host, $space), decode_utf8(uri_unescape($id)), $n);
191 } else {
192 $log->info("No handler for $selector via gopher");
193 $stream->write("Don't know how to handle $selector\r\n");
194 }
195 $log->debug("Done");
196 };
197 $log->error("Error: $@") if $@;
198 alarm(0);
199 $stream->close_gracefully();
200 }
201  
202 sub gopher_link {
203 my $stream = shift;
204 my $host = shift;
205 my $space = shift;
206 my $title = shift;
207 my $id = shift || "page/$title";
208 my $type = shift || 0;
209 my $port = port($stream);
210 $stream->write(encode_utf8 join("\t", $type . $title, $id, $host, $port) . "\n");
211 }
212  
213 sub gopher_menu_link {
214 my $stream = shift;
215 my $host = shift;
216 my $space = shift;
217 my $title = shift;
218 my $selector = shift;
219 my $port = port($stream);
220 $stream->write(encode_utf8 join("\t", "1" . $title, $selector, $host, $port) . "\n");
221 }
222  
223 sub gopher_main_menu {
224 my $stream = shift;
225 my $host = shift;
226 my $space = shift||"";
227 $log->info("Serving main menu via Gopher");
228 my $page = $gopher_main_page || $server->{wiki_main_page};
229 if ($page) {
230 my $text = gopher_plain_text(text($stream, $host, $space, $page)) . "\n\n";
231 $stream->write(encode_utf8 gopher_menu($text));
232 } else {
233 $stream->write("iWelcome to Phoebe!\n");
234 $stream->write("i\n");
235 }
236 gopher_blog($stream, $host, $space, 10);
237 for my $id (@{$server->{wiki_page}}) {
238 gopher_link($stream, $host, $space, $id);
239 }
240 for my $line (@main_menu) {
241 $stream->write(encode_utf8 join("\n", map { "i$_" } split(/\n/, gopher_plain_text($line))) . "\ni\n");
242 }
243 # gopher_link($stream, $host, $space, "Changes", "do/changes");
244 gopher_link($stream, $host, $space, "Search matching page names", "do/match", "7");
245 gopher_link($stream, $host, $space, "Search matching page content", "do/search", "7");
246 $stream->write("i\n");
247 gopher_menu_link($stream, $host, $space, "Index of all pages", "do/index");
248 # gopher_link($stream, $host, $space, "Index of all files", "do/files");
249 # gopher_link($stream, $host, undef, "Index of all spaces", "do/spaces")
250 # if @{$server->{wiki_space}} or keys %{$server->{host}} > 1;
251 # gopher_link($stream, $host, $space, "Download data", "do/data");
252 # a requirement of the GNU Affero General Public License
253 gopher_link($stream, $host, undef, "Source code", "do/source");
254 $stream->write("i\n");
255 }
256  
257 sub gopher_blog {
258 my $stream = shift;
259 my $host = shift;
260 my $space = shift;
261 my $n = shift || 10;
262 my @blog = blog_pages($stream, $host, $space, $n + 1); # for More...
263 return unless @blog;
264 $stream->write($gopher_header);
265 # we should check for pages marked for deletion!
266 for my $id (@blog[0 .. min($#blog, $n - 1)]) {
267 gopher_link($stream, $host, $space, $id);
268 }
269 gopher_menu_link($stream, $host, $space, "More...", "do/more/" . ($n * 10)) if @blog > $n;
270 $stream->write("i\n");
271 return @blog;
272 }
273  
274 sub gopher_serve_page {
275 my $stream = shift;
276 my $host = shift;
277 my $space = shift;
278 my $id = shift;
279 my $revision = shift;
280 $log->info("Serve Gopher page $id");
281 $stream->write(encode_utf8 gopher_plain_text("# $id\n" . text($stream, $host, $space, $id, $revision)));
282 }
283  
284 sub gopher_plain_text {
285 $_ = shift;
286 my $text_wrapper = Text::Wrapper->new;
287 my $bullet_wrapper = Text::Wrapper->new(par_start => "• ", body_start => " ");
288 my $quote_wrapper = Text::Wrapper->new(par_start => "> ", body_start => "> ");
289 s/^=> .*\n//gm;
290 my @lines = grep { !/^```/ } split(/\n/);
291 for (@lines) {
292 next if /^\s*$/;
293 next if s/^\* (.*)/$bullet_wrapper->wrap($1)/e;
294 next if s/^> (.*)/$quote_wrapper->wrap($1)/e;
295 next if s/^## (.*)/"$1\n" . '-' x length($1) . "\n\n"/e;
296 next if s/^### (.*)/"$1\n" . '·' x length($1) . "\n\n"/e;
297 next if s/^# (.*)/"$1\n" . '=' x length($1) . "\n\n"/e;
298 $_ = $text_wrapper->wrap($_);
299 }
300 # drop trailing newlines added to paragraphs by the Text::Wrapper code, except for the last one
301 my $text = join("\n", map { s/\n+$//; $_ } @lines) . "\n";
302 # drop extra empty lines: one empty line is enough
303 $text =~ s/\n\n\n+/\n\n/gm;
304 return $text;
305 }
306  
307 sub gopher_menu {
308 my $text = shift;
309 $text =~ s/^/i/gm;
310 return $text;
311 }
312  
313 sub gopher_serve_index {
314 my $stream = shift;
315 my $host = shift;
316 my $space = shift;
317 $log->info("Serving index of all pages via Gopher");
318 my @pages = pages($stream, $host, $space);
319 $stream->write("iThere are no pages.\n") unless @pages;
320 for my $id (@pages) {
321 gopher_link($stream, $host, $space, $id);
322 }
323 }
324  
325 sub gopher_serve_blog {
326 my $stream = shift;
327 my $host = shift;
328 my $space = shift;
329 my $n = shift;
330 $log->info("Serving blog via Gopher");
331 return if gopher_blog($stream, $host, $space, 10);
332 $stream->write("iThere are no blog pages.\n");
333 }
334  
335 sub gopher_serve_match {
336 my $stream = shift;
337 my $host = shift;
338 my $space = shift;
339 my $query = shift;
340 $log->info("Serving index of all pages matching $query via Gopher");
341 my @pages = pages($stream, $host, $space, $query);
342 $stream->write("iThere are no pages matching $query.\n") unless @pages;
343 for my $id (@pages) {
344 gopher_link($stream, $host, $space, $id);
345 }
346 }
347  
348 sub gopher_serve_search {
349 my $stream = shift;
350 my $host = shift;
351 my $space = shift;
352 my $query = shift;
353 $log->info("Serving search for $query via Gopher");
354 my @pages = search($stream, $host, $space, $query, sub { gopher_link($stream, @_[0..2]) });
355 $stream->write("iThere are no pages containing $query.\n") unless @pages;
356 }
357  
358 1;