ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent-MCP/lib/AnyEvent/MCP/Extension.pm
Revision: 1.1
Committed: Thu Oct 15 09:07:04 2026 UTC (5 weeks, 3 days ago) by root
Branch: MAIN
Log Message:
*** empty log message ***

File Contents

# User Rev Content
1 root 1.1 =head1 NAME
2    
3     AnyEvent::MCP::Extension - authenticated non-HTTP connections on an MCP listener
4    
5     =head1 FUNCTIONS
6    
7     =over
8    
9     =item AnyEvent::MCP::Extension::accept $handle, [$token...], $callback->($handle, $hello), $reject->($handle)
10    
11     Read one bounded newline-terminated JSON array beginning with a protocol name
12     and accepted token. Authenticate before calling the protocol-specific handler.
13     Invalid hellos close the connection. The callback takes ownership of the same
14     handle, including buffered bytes after the hello. Remaining array fields belong
15     to the selected protocol. An optional C<$reject> callback releases any
16     listener ownership on rejection; otherwise the handle is destroyed.
17    
18     =item ($host, $port, $token, $alias) = AnyEvent::MCP::Extension::parse_url $url
19    
20     Parse C<http://host:port/token/alias>, including bracketed IPv6 hosts. The URL
21     names a raw TCP extension endpoint sharing an HTTP listener; no HTTP request
22     is sent. Tokens use the ordinary listener token syntax and aliases use ASCII
23     letters, digits, underscores and hyphens.
24    
25     =back
26    
27     =cut
28    
29     package AnyEvent::MCP::Extension;
30    
31     use common::sense;
32     use JSON::XS ();
33    
34     sub parse_url {
35     my ($url) = @_;
36    
37     my ($host, $port, $token, $alias) =
38     $url =~ m{\Ahttp://(\[[^\]]+\]|[^/:?#]+):([0-9]+)/([A-Za-z0-9_.~-]+)/([A-Za-z0-9_-]+)\z};
39     defined $host && $port > 0 && $port <= 65535
40     or die "Expected extension URL http://host:port/token/alias\n";
41     $host =~ s/\A\[(.*)\]\z/$1/;
42    
43     ($host, 0 + $port, $token, $alias)
44     }
45    
46     sub accept {
47     my ($handle, $tokens, $done, $reject) = @_;
48    
49     my $rbuf_max = $handle->{rbuf_max};
50     $handle->rtimeout (15);
51     $handle->{rbuf_max} = 4096;
52     $handle->push_read (line => sub {
53     my (undef, $line) = @_;
54    
55     my $ok = eval {
56     my $hello = JSON::XS->new->utf8->max_depth (8)->decode ($line);
57     ref $hello eq "ARRAY" && @$hello >= 2
58     && defined $hello->[0] && !ref $hello->[0]
59     && defined $hello->[1] && !ref $hello->[1]
60     && (grep $_ eq $hello->[1], @$tokens)
61     or die "Invalid extension hello\n";
62    
63     $handle->rtimeout (0);
64     $handle->{rbuf_max} = $rbuf_max;
65     $done->($handle, $hello);
66     1
67     };
68     ($reject ? $reject->($handle) : $handle->destroy) unless $ok;
69     });
70     }
71    
72     1;