ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/Net-FCP/FCP.pm
(Generate patch)

Comparing Net-FCP/FCP.pm (file contents):
Revision 1.2 by root, Sun Sep 7 23:20:20 2003 UTC vs.
Revision 1.30 by root, Fri May 14 16:12:26 2004 UTC

17of what the messages do. I am too lazy to document all this here. 17of what the messages do. I am too lazy to document all this here.
18 18
19=head1 WARNING 19=head1 WARNING
20 20
21This module is alpha. While it probably won't destroy (much :) of your 21This module is alpha. While it probably won't destroy (much :) of your
22data, it currently works only with the Event module (alkthough the event 22data, it currently falls short of what it should provide (intelligent uri
23mechanism is fully pluggable). 23following, splitfile downloads, healing...)
24
25=head2 IMPORT TAGS
26
27Nothing much can be "imported" from this module right now. There are,
28however, certain "import tags" that can be used to select the event model
29to be used.
30
31Event models are implemented as modules under the C<Net::FCP::Event::xyz>
32class, where C<xyz> is the event model to use. The default is C<Event> (or
33later C<Auto>).
34
35The import tag to use is named C<event=xyz>, e.g. C<event=Event>,
36C<event=Glib> etc.
37
38You should specify the event module to use only in the main program.
39
40If no event model has been specified, FCP tries to autodetect it on first
41use (e.g. first transaction), in this order: Coro, Event, Glib, Tk.
42
43=head2 FREENET BASICS
44
45Ok, this section will not explain any freenet basics to you, just some
46problems I found that you might want to avoid:
47
48=over 4
49
50=item freenet URIs are _NOT_ URIs
51
52Whenever a "uri" is required by the protocol, freenet expects a kind of
53URI prefixed with the "freenet:" scheme, e.g. "freenet:CHK...". However,
54these are not URIs, as freeent fails to parse them correctly, that is, you
55must unescape an escaped characters ("%2c" => ",") yourself. Maybe in the
56future this library will do it for you, so watch out for this incompatible
57change.
58
59=item Numbers are in HEX
60
61Virtually every number in the FCP protocol is in hex. Be sure to use
62C<hex()> on all such numbers, as the module (currently) does nothing to
63convert these for you.
64
65=back
24 66
25=head2 THE Net::FCP CLASS 67=head2 THE Net::FCP CLASS
26 68
27=over 4 69=over 4
28 70
29=cut 71=cut
30 72
31package Net::FCP; 73package Net::FCP;
32 74
33use Carp; 75use Carp;
34use IO::Socket::INET;
35 76
36$VERSION = 0.01; 77$VERSION = 0.7;
37 78
38sub event_reg_cb { 79no warnings;
39 my ($obj) = @_;
40 require Event;
41 80
42 $obj->{eventdata} = Event->io ( 81use Net::FCP::Metadata;
43 fd => $obj->{fh}, 82
44 poll => 'r', 83our $EVENT = Net::FCP::Event::Auto::;
45 cb => sub { 84
46 $obj->fh_ready; 85sub import {
86 shift;
87
88 for (@_) {
89 if (/^event=(\w+)$/) {
90 $EVENT = "Net::FCP::Event::$1";
91 eval "require $EVENT";
47 }, 92 }
48 ); 93 }
94 die $@ if $@;
49} 95}
50
51sub event_unreg_cb {
52 $_[0]{eventdata}
53 and (delete $_[0]{eventdata})->cancel;
54}
55
56sub event_wait_cb {
57 Event::one_event();
58}
59
60$regcb = \&event_reg_cb;
61$unregcb = \&event_unreg_cb;
62$waitcb = \&event_wait_cb;
63 96
64sub touc($) { 97sub touc($) {
65 local $_ = shift; 98 local $_ = shift;
66 1 while s/((?:^|_)(?:svk|chk|uri)(?:_|$))/\U$1/; 99 1 while s/((?:^|_)(?:svk|chk|uri)(?:_|$))/\U$1/;
67 s/(?:^|_)(.)/\U$1/g; 100 s/(?:^|_)(.)/\U$1/g;
68 $_; 101 $_;
69} 102}
70 103
71sub tolc($) { 104sub tolc($) {
72 local $_ = shift; 105 local $_ = shift;
106 1 while s/(SVK|CHK|URI)([^_])/$1\_$2/i;
107 1 while s/([^_])(SVK|CHK|URI)/$1\_$2/i;
73 s/(?<=[a-z])(?=[A-Z])/_/g; 108 s/(?<=[a-z])(?=[A-Z])/_/g;
74 lc $_; 109 lc $_;
75} 110}
76 111
112# the opposite of hex
113sub xeh($) {
114 sprintf "%x", $_[0];
115}
116
77=item $fcp = new Net::FCP [host => $host][, port => $port] 117=item $fcp = new Net::FCP [host => $host][, port => $port][, progress => \&cb]
78 118
79Create a new virtual FCP connection to the given host and port (default 119Create a new virtual FCP connection to the given host and port (default
80127.0.0.1:8481). 120127.0.0.1:8481, or the environment variables C<FREDHOST> and C<FREDPORT>).
81 121
82Connections are virtual because no persistent physical connection is 122Connections are virtual because no persistent physical connection is
83established. However, the existance of the node is checked by executing a 123established.
84C<ClientHello> transaction. 124
125You can install a progress callback that is being called with the Net::FCP
126object, a txn object, the type of the transaction and the attributes. Use
127it like this:
128
129 sub progress_cb {
130 my ($self, $txn, $type, $attr) = @_;
131
132 warn "progress<$txn,$type," . (join ":", %$attr) . ">\n";
133 }
85 134
86=cut 135=cut
87 136
88sub new { 137sub new {
89 my $class = shift; 138 my $class = shift;
90 my $self = bless { @_ }, $class; 139 my $self = bless { @_ }, $class;
91 140
92 $self->{host} ||= "127.0.0.1"; 141 $self->{host} ||= $ENV{FREDHOST} || "127.0.0.1";
93 $self->{port} ||= 8481; 142 $self->{port} ||= $ENV{FREDPORT} || 8481;
94
95 $self->{nodehello} = $self->txn("ClientHello")->result
96 or croak "unable to get nodehello from node\n";
97 143
98 $self; 144 $self;
99} 145}
100 146
147sub progress {
148 my ($self, $txn, $type, $attr) = @_;
149
150 $self->{progress}->($self, $txn, $type, $attr)
151 if $self->{progress};
152}
153
101=item $txn = $fcp->txn(type => attr => val,...) 154=item $txn = $fcp->txn (type => attr => val,...)
102 155
103The low-level interface to transactions. Don't use it. 156The low-level interface to transactions. Don't use it unless you have
157"special needs". Instead, use predefiend transactions like this:
158
159The blocking case, no (visible) transactions involved:
160
161 my $nodehello = $fcp->client_hello;
162
163A transaction used in a blocking fashion:
164
165 my $txn = $fcp->txn_client_hello;
166 ...
167 my $nodehello = $txn->result;
168
169Or shorter:
170
171 my $nodehello = $fcp->txn_client_hello->result;
172
173Setting callbacks:
174
175 $fcp->txn_client_hello->cb(
176 sub { my $nodehello => $_[0]->result }
177 );
104 178
105=cut 179=cut
106 180
107sub txn { 181sub txn {
108 my ($self, $type, %attr) = @_; 182 my ($self, $type, %attr) = @_;
109 183
110 $type = touc $type; 184 $type = touc $type;
111 185
112 my $txn = "Net::FCP::Txn::$type"->new(fcp => $self, type => tolc $type, attr => \%attr); 186 my $txn = "Net::FCP::Txn::$type"->new (fcp => $self, type => tolc $type, attr => \%attr);
113 187
114 $txn; 188 $txn;
115} 189}
116 190
117sub _txn($&) { 191{ # transactions
192
193my $txn = sub {
118 my ($name, $sub) = @_; 194 my ($name, $sub) = @_;
119 *{"$name\_txn"} = $sub; 195 *{"txn_$name"} = $sub;
120 *{$name} = sub { $sub->(@_)->result }; 196 *{$name} = sub { $sub->(@_)->result };
121} 197};
122 198
123=item $txn = $fcp->txn_client_hello 199=item $txn = $fcp->txn_client_hello
124 200
125=item $nodehello = $fcp->client_hello 201=item $nodehello = $fcp->client_hello
126 202
127Executes a ClientHello request and returns it's results. 203Executes a ClientHello request and returns it's results.
128 204
129 { 205 {
130 max_file_size => "5f5e100", 206 max_file_size => "5f5e100",
207 node => "Fred,0.6,1.46,7050"
131 protocol => "1.2", 208 protocol => "1.2",
132 node => "Fred,0.6,1.46,7050"
133 } 209 }
134 210
135=cut 211=cut
136 212
137_txn client_hello => sub { 213$txn->(client_hello => sub {
138 my ($self) = @_; 214 my ($self) = @_;
139 215
140 $self->txn ("client_hello"); 216 $self->txn ("client_hello");
141}; 217});
142 218
143=item $txn = $fcp->txn_client_info 219=item $txn = $fcp->txn_client_info
144 220
145=item $nodeinfo = $fcp->client_info 221=item $nodeinfo = $fcp->client_info
146 222
147Executes a ClientInfo request and returns it's results. 223Executes a ClientInfo request and returns it's results.
148 224
149 { 225 {
150 max_file_size => "5f5e100",
151 datastore_max => "2540be400",
152 node_port => 369,
153 java_name => "Java HotSpot(_T_M) Server VM",
154 operating_system_version => "2.4.20",
155 estimated_load => 52,
156 free_memory => "5cc0148",
157 datastore_free => "5ce03400",
158 node_address => "1.2.3.4",
159 active_jobs => "1f", 226 active_jobs => "1f",
160 allocated_memory => "bde0000", 227 allocated_memory => "bde0000",
161 architecture => "i386", 228 architecture => "i386",
229 available_threads => 17,
230 datastore_free => "5ce03400",
231 datastore_max => "2540be400",
232 datastore_used => "1f72bb000",
233 estimated_load => 52,
234 free_memory => "5cc0148",
235 is_transient => "false",
236 java_name => "Java HotSpot(_T_M) Server VM",
237 java_vendor => "http://www.blackdown.org/",
238 java_version => "Blackdown-1.4.1-01",
239 least_recent_timestamp => "f41538b878",
240 max_file_size => "5f5e100",
241 most_recent_timestamp => "f77e2cc520"
242 node_address => "1.2.3.4",
243 node_port => 369,
244 operating_system => "Linux",
245 operating_system_version => "2.4.20",
162 routing_time => "a5", 246 routing_time => "a5",
163 least_recent_timestamp => "f41538b878",
164 available_threads => 17,
165 datastore_used => "1f72bb000",
166 java_version => "Blackdown-1.4.1-01",
167 is_transient => "false",
168 operating_system => "Linux",
169 java_vendor => "http://www.blackdown.org/",
170 most_recent_timestamp => "f77e2cc520"
171 } 247 }
172 248
173=cut 249=cut
174 250
175_txn client_info => sub { 251$txn->(client_info => sub {
176 my ($self) = @_; 252 my ($self) = @_;
177 253
178 $self->txn ("client_info"); 254 $self->txn ("client_info");
179}; 255});
180 256
181=item $txn = $fcp->txn_generate_chk ($metadata, $data) 257=item $txn = $fcp->txn_generate_chk ($metadata, $data[, $cipher])
182 258
183=item $uri = $fcp->generate_chk ($metadata, $data) 259=item $uri = $fcp->generate_chk ($metadata, $data[, $cipher])
184 260
185Creates a new CHK, given the metadata and data. UNTESTED. 261Calculates a CHK, given the metadata and data. C<$cipher> is either
262C<Rijndael> or C<Twofish>, with the latter being the default.
186 263
187=cut 264=cut
188 265
189_txn generate_chk => sub { 266$txn->(generate_chk => sub {
190 my ($self, $metadata, $data) = @_; 267 my ($self, $metadata, $data, $cipher) = @_;
191 268
192 $self->txn (generate_chk => data => "$data$metadata", meta_data_length => length $metadata); 269 $metadata = Net::FCP::Metadata::build_metadata $metadata;
270
271 $self->txn (generate_chk =>
272 data => "$metadata$data",
273 metadata_length => xeh length $metadata,
274 cipher => $cipher || "Twofish");
193}; 275});
194 276
195=item $txn = $fcp->txn_generate_svk_pair 277=item $txn = $fcp->txn_generate_svk_pair
196 278
197=item ($public, $private) = @{ $fcp->generate_svk_pair } 279=item ($public, $private) = @{ $fcp->generate_svk_pair }
198 280
199Creates a new SVK pair. Returns an arrayref. 281Creates a new SVK pair. Returns an arrayref with the public key, the
282private key and a crypto key, which is just additional entropy.
200 283
201 [ 284 [
202 "hKs0-WDQA4pVZyMPKNFsK1zapWY", 285 "acLx4dux9fvvABH15Gk6~d3I-yw",
203 "ZnmvMITaTXBMFGl4~jrjuyWxOWg" 286 "cPoDkDMXDGSMM32plaPZDhJDxSs",
287 "BH7LXCov0w51-y9i~BoB3g",
204 ] 288 ]
205 289
206=cut 290A private key (for inserting) can be constructed like this:
207 291
292 SSK@<private_key>,<crypto_key>/<name>
293
294It can be used to insert data. The corresponding public key looks like this:
295
296 SSK@<public_key>PAgM,<crypto_key>/<name>
297
298Watch out for the C<PAgM>-part!
299
300=cut
301
208_txn generate_svk_pair => sub { 302$txn->(generate_svk_pair => sub {
209 my ($self) = @_; 303 my ($self) = @_;
210 304
211 $self->txn ("generate_svk_pair"); 305 $self->txn ("generate_svk_pair");
212}; 306});
213 307
214=item $txn = $fcp->txn_insert_private_key ($private) 308=item $txn = $fcp->txn_invert_private_key ($private)
215 309
216=item $uri = $fcp->insert_private_key ($private) 310=item $public = $fcp->invert_private_key ($private)
217 311
218Inserts a private key. $private can be either an insert URI (must start 312Inverts a private key (returns the public key). C<$private> can be either
219with freenet:SSK@) or a raw private key (i.e. the private value you get back 313an insert URI (must start with C<freenet:SSK@>) or a raw private key (i.e.
220from C<generate_svk_pair>). 314the private value you get back from C<generate_svk_pair>).
221 315
222Returns the public key. 316Returns the public key.
223 317
224UNTESTED.
225
226=cut 318=cut
227 319
228_txn insert_private_key => sub { 320$txn->(invert_private_key => sub {
229 my ($self, $privkey) = @_; 321 my ($self, $privkey) = @_;
230 322
231 $self->txn (invert_private_key => private => $privkey); 323 $self->txn (invert_private_key => private => $privkey);
232}; 324});
233 325
234=item $txn = $fcp->txn_get_size ($uri) 326=item $txn = $fcp->txn_get_size ($uri)
235 327
236=item $length = $fcp->get_size ($uri) 328=item $length = $fcp->get_size ($uri)
237 329
238Finds and returns the size (rounded up to the nearest power of two) of the 330Finds and returns the size (rounded up to the nearest power of two) of the
239given document. 331given document.
240 332
241UNTESTED.
242
243=cut 333=cut
244 334
245_txn get_size => sub { 335$txn->(get_size => sub {
246 my ($self, $uri) = @_; 336 my ($self, $uri) = @_;
247 337
248 $self->txn (get_size => URI => $uri); 338 $self->txn (get_size => URI => $uri);
249}; 339});
250 340
251=item MISSING: ClientGet, ClientPut 341=item $txn = $fcp->txn_client_get ($uri [, $htl = 15 [, $removelocal = 0]])
342
343=item ($metadata, $data) = @{ $fcp->client_get ($uri, $htl, $removelocal)
344
345Fetches a (small, as it should fit into memory) key content block from
346freenet. C<$meta> is a C<Net::FCP::Metadata> object or C<undef>).
347
348The C<$uri> should begin with C<freenet:>, but the scheme is currently
349added, if missing.
350
351 my ($meta, $data) = @{
352 $fcp->client_get (
353 "freenet:CHK@hdXaxkwZ9rA8-SidT0AN-bniQlgPAwI,XdCDmBuGsd-ulqbLnZ8v~w"
354 )
355 };
356
357=cut
358
359$txn->(client_get => sub {
360 my ($self, $uri, $htl, $removelocal) = @_;
361
362 $uri =~ s/^freenet://; $uri = "freenet:$uri";
363
364 $self->txn (client_get => URI => $uri, hops_to_live => xeh (defined $htl ? $htl : 15),
365 remove_local_key => $removelocal ? "true" : "false");
366});
367
368=item $txn = $fcp->txn_client_put ($uri, $metadata, $data, $htl, $removelocal)
369
370=item my $uri = $fcp->client_put ($uri, $metadata, $data, $htl, $removelocal);
371
372Insert a new key. If the client is inserting a CHK, the URI may be
373abbreviated as just CHK@. In this case, the node will calculate the
374CHK. If the key is a private SSK key, the node will calculcate the public
375key and the resulting public URI.
376
377C<$meta> can be a hash reference (same format as returned by
378C<Net::FCP::parse_metadata>) or a string.
379
380The result is an arrayref with the keys C<uri>, C<public_key> and C<private_key>.
381
382=cut
383
384$txn->(client_put => sub {
385 my ($self, $uri, $metadata, $data, $htl, $removelocal) = @_;
386
387 $metadata = Net::FCP::Metadata::build_metadata $metadata;
388 $uri =~ s/^freenet://; $uri = "freenet:$uri";
389
390 $self->txn (client_put => URI => $uri,
391 hops_to_live => xeh (defined $htl ? $htl : 15),
392 remove_local_key => $removelocal ? "true" : "false",
393 data => "$metadata$data", metadata_length => xeh length $metadata);
394});
395
396} # transactions
252 397
253=back 398=back
254 399
255=head2 THE Net::FCP::Txn CLASS 400=head2 THE Net::FCP::Txn CLASS
256 401
257All requests (or transactions) are executed in a asynchroneous way (LIE: 402All requests (or transactions) are executed in a asynchronous way. For
258uploads are blocking). For each request, a C<Net::FCP::Txn> object is 403each request, a C<Net::FCP::Txn> object is created (worse: a tcp
259created (worse: a tcp connection is created, too). 404connection is created, too).
260 405
261For each request there is actually a different subclass (and it's possible 406For each request there is actually a different subclass (and it's possible
262to subclass these, although of course not documented). 407to subclass these, although of course not documented).
263 408
264The most interesting method is C<result>. 409The most interesting method is C<result>.
266=over 4 411=over 4
267 412
268=cut 413=cut
269 414
270package Net::FCP::Txn; 415package Net::FCP::Txn;
416
417use Fcntl;
418use Socket;
271 419
272=item new arg => val,... 420=item new arg => val,...
273 421
274Creates a new C<Net::FCP::Txn> object. Not normally used. 422Creates a new C<Net::FCP::Txn> object. Not normally used.
275 423
277 425
278sub new { 426sub new {
279 my $class = shift; 427 my $class = shift;
280 my $self = bless { @_ }, $class; 428 my $self = bless { @_ }, $class;
281 429
430 $self->{signal} = $EVENT->new_signal;
431
432 $self->{fcp}{txn}{$self} = $self;
433
282 my $attr = ""; 434 my $attr = "";
283 my $data = delete $self->{attr}{data}; 435 my $data = delete $self->{attr}{data};
284 436
285 while (my ($k, $v) = each %{$self->{attr}}) { 437 while (my ($k, $v) = each %{$self->{attr}}) {
286 $attr .= (Net::FCP::touc $k) . "=$v\012" 438 $attr .= (Net::FCP::touc $k) . "=$v\012"
287 } 439 }
288 440
289 if (defined $data) { 441 if (defined $data) {
290 $attr .= "DataLength=" . (length $data) . "\012"; 442 $attr .= sprintf "DataLength=%x\012", length $data;
291 $data = "Data\012$data"; 443 $data = "Data\012$data";
292 } else { 444 } else {
293 $data = "EndMessage\012"; 445 $data = "EndMessage\012";
294 } 446 }
295 447
296 my $fh = new IO::Socket::INET 448 socket my $fh, PF_INET, SOCK_STREAM, 0
297 PeerHost => $self->{fcp}{host}, 449 or Carp::croak "unable to create new tcp socket: $!";
298 PeerPort => $self->{fcp}{port}
299 or Carp::croak "FCP::txn: unable to connect to $self->{fcp}{host}:$self->{fcp}{port}: $!\n";
300
301 binmode $fh, ":raw"; 450 binmode $fh, ":raw";
451 fcntl $fh, F_SETFL, O_NONBLOCK;
452 connect $fh, (sockaddr_in $self->{fcp}{port}, inet_aton $self->{fcp}{host})
453 and !$!{EWOULDBLOCK}
454 and !$!{EINPROGRESS}
455 and Carp::croak "FCP::txn: unable to connect to $self->{fcp}{host}:$self->{fcp}{port}: $!\n";
302 456
303 if (0) { 457 $self->{sbuf} =
304 print 458 "\x00\x00\x00\x02"
305 Net::FCP::touc $self->{type}, "\012",
306 $attr,
307 $data, "\012";
308 }
309
310 print $fh
311 "\x00\x00", "\x00\x02", # SESSID, PRESID
312 Net::FCP::touc $self->{type}, "\012", 459 . (Net::FCP::touc $self->{type})
313 $attr, 460 . "\012$attr$data";
314 $data;
315 461
316 #$fh->shutdown (1); # freenet buggy?, well, it's java... 462 #shutdown $fh, 1; # freenet buggy?, well, it's java...
317 463
318 $self->{fh} = $fh; 464 $self->{fh} = $fh;
319 465
320 $Net::FCP::regcb->($self); 466 $self->{w} = $EVENT->new_from_fh ($fh)->cb(sub { $self->fh_ready_w })->poll(0, 1, 1);
321 467
322 $self; 468 $self;
323} 469}
324 470
471=item $txn = $txn->cb ($coderef)
472
473Sets a callback to be called when the request is finished. The coderef
474will be called with the txn as it's sole argument, so it has to call
475C<result> itself.
476
477Returns the txn object, useful for chaining.
478
479Example:
480
481 $fcp->txn_client_get ("freenet:CHK....")
482 ->userdata ("ehrm")
483 ->cb(sub {
484 my $data = shift->result;
485 });
486
487=cut
488
489sub cb($$) {
490 my ($self, $cb) = @_;
491 $self->{cb} = $cb;
492 $self;
493}
494
495=item $txn = $txn->userdata ([$userdata])
496
497Set user-specific data. This is useful in progress callbacks. The data can be accessed
498using C<< $txn->{userdata} >>.
499
500Returns the txn object, useful for chaining.
501
502=cut
503
504sub userdata($$) {
505 my ($self, $data) = @_;
506 $self->{userdata} = $data;
507 $self;
508}
509
510=item $txn->cancel (%attr)
511
512Cancels the operation with a C<cancel> exception anf the given attributes
513(consider at least giving the attribute C<reason>).
514
515UNTESTED.
516
517=cut
518
519sub cancel {
520 my ($self, %attr) = @_;
521 $self->throw (Net::FCP::Exception->new (cancel => { %attr }));
522 $self->set_result;
523 $self->eof;
524}
525
325sub fh_ready { 526sub fh_ready_w {
527 my ($self) = @_;
528
529 my $len = syswrite $self->{fh}, $self->{sbuf};
530
531 if ($len > 0) {
532 substr $self->{sbuf}, 0, $len, "";
533 unless (length $self->{sbuf}) {
534 fcntl $self->{fh}, F_SETFL, 0;
535 $self->{w}->cb(sub { $self->fh_ready_r })->poll (1, 0, 1);
536 }
537 } elsif (defined $len) {
538 $self->throw (Net::FCP::Exception->new (network_error => { reason => "unexpected end of file while writing" }));
539 } else {
540 $self->throw (Net::FCP::Exception->new (network_error => { reason => "$!" }));
541 }
542}
543
544sub fh_ready_r {
326 my ($self) = @_; 545 my ($self) = @_;
327 546
328 if (sysread $self->{fh}, $self->{buf}, 65536, length $self->{buf}) { 547 if (sysread $self->{fh}, $self->{buf}, 65536, length $self->{buf}) {
329 for (;;) { 548 for (;;) {
330 if ($self->{datalen}) { 549 if ($self->{datalen}) {
550 #warn "expecting new datachunk $self->{datalen}, got ".(length $self->{buf})."\n";#d#
331 if (length $self->{buf} >= $self->{datalen}) { 551 if (length $self->{buf} >= $self->{datalen}) {
332 $self->recv_data (substr $self->{buf}, 0, $self->{datalen}, ""); 552 $self->rcv_data (substr $self->{buf}, 0, delete $self->{datalen}, "");
333 } else { 553 } else {
334 last; 554 last;
335 } 555 }
336 } elsif ($self->{buf} =~ s/^DataChunk\015?\012Length=(\d+)\015?\012Data\015?\012//) { 556 } elsif ($self->{buf} =~ s/^DataChunk\015?\012Length=([0-9a-fA-F]+)\015?\012Data\015?\012//) {
337 $self->{datalen} = $1; 557 $self->{datalen} = hex $1;
558 #warn "expecting new datachunk $self->{datalen}\n";#d#
338 } elsif ($self->{buf} =~ s/^([a-zA-Z]+)\015?\012(.*?)\015?\012EndMessage\015?\012//s) { 559 } elsif ($self->{buf} =~ s/^([a-zA-Z]+)\015?\012(?:(.+?)\015?\012)?EndMessage\015?\012//s) {
339 $self->rcv ($1, { 560 $self->rcv ($1, {
340 map { my ($a, $b) = split /=/, $_, 2; ((Net::FCP::tolc $a), $b) } 561 map { my ($a, $b) = split /=/, $_, 2; ((Net::FCP::tolc $a), $b) }
341 split /\015?\012/, $2 562 split /\015?\012/, $2
342 }); 563 });
343 } else { 564 } else {
344 last; 565 last;
345 } 566 }
346 } 567 }
347 } else { 568 } else {
348 $Net::FCP::unregcb->($self);
349 delete $self->{fh};
350 $self->eof; 569 $self->eof;
351 } 570 }
352}
353
354sub rcv_data {
355 my ($self, $chunk) = @_;
356} 571}
357 572
358sub rcv { 573sub rcv {
359 my ($self, $type, $attr) = @_; 574 my ($self, $type, $attr) = @_;
360 575
361 $type = Net::FCP::tolc $type; 576 $type = Net::FCP::tolc $type;
577
578 #use PApp::Util; warn PApp::Util::dumpval [$type, $attr];
362 579
363 if (my $method = $self->can("rcv_$type")) { 580 if (my $method = $self->can("rcv_$type")) {
364 $method->($self, $attr, $type); 581 $method->($self, $attr, $type);
365 } else { 582 } else {
366 warn "received unexpected reply type '$type' for '$self->{type}', ignoring\n"; 583 warn "received unexpected reply type '$type' for '$self->{type}', ignoring\n";
367 $self->eof; 584 }
585}
586
587# used as a default exception thrower
588sub rcv_throw_exception {
589 my ($self, $attr, $type) = @_;
590 $self->throw (Net::FCP::Exception->new ($type, $attr));
591}
592
593*rcv_failed = \&Net::FCP::Txn::rcv_throw_exception;
594*rcv_format_error = \&Net::FCP::Txn::rcv_throw_exception;
595
596sub throw {
597 my ($self, $exc) = @_;
598
599 $self->{exception} = $exc;
600 $self->set_result;
601 $self->eof; # must be last to avoid loops
602}
603
604sub set_result {
605 my ($self, $result) = @_;
606
607 unless (exists $self->{result}) {
608 $self->{result} = $result;
609 $self->{cb}->($self) if exists $self->{cb};
610 $self->{signal}->send;
368 } 611 }
369} 612}
370 613
371sub eof { 614sub eof {
372 my ($self, $result) = @_; 615 my ($self) = @_;
373 616
374 $self->{result} = $result unless exists $self->{result}; 617 delete $self->{w};
618 delete $self->{fh};
619
620 delete $self->{fcp}{txn}{$self};
621
622 unless (exists $self->{result}) {
623 $self->throw (Net::FCP::Exception->new (short_data => {
624 reason => "unexpected eof or internal node error",
625 }));
626 }
627}
628
629sub progress {
630 my ($self, $type, $attr) = @_;
631
632 $self->{fcp}->progress ($self, $type, $attr);
375} 633}
376 634
377=item $result = $txn->result 635=item $result = $txn->result
378 636
379Waits until a result is available and then returns it. 637Waits until a result is available and then returns it.
380 638
381This waiting is (depending on your event modul) not very efficient, as it 639This waiting is (depending on your event model) not very efficient, as it
382is done outside the "mainloop". 640is done outside the "mainloop". The biggest problem, however, is that it's
641blocking one thread of execution. Try to use the callback mechanism, if
642possible, and call result from within the callback (or after is has been
643run), as then no waiting is necessary.
383 644
384=cut 645=cut
385 646
386sub result { 647sub result {
387 my ($self) = @_; 648 my ($self) = @_;
388 649
389 $Net::FCP::waitcb->() while !exists $self->{result}; 650 $self->{signal}->wait while !exists $self->{result};
651
652 die $self->{exception} if $self->{exception};
390 653
391 return $self->{result}; 654 return $self->{result};
392}
393
394sub DESTROY {
395 $Net::FCP::unregcb->($_[0]);
396} 655}
397 656
398package Net::FCP::Txn::ClientHello; 657package Net::FCP::Txn::ClientHello;
399 658
400use base Net::FCP::Txn; 659use base Net::FCP::Txn;
401 660
402sub rcv_node_hello { 661sub rcv_node_hello {
403 my ($self, $attr) = @_; 662 my ($self, $attr) = @_;
404 663
405 $self->eof ($attr); 664 $self->set_result ($attr);
406} 665}
407 666
408package Net::FCP::Txn::ClientInfo; 667package Net::FCP::Txn::ClientInfo;
409 668
410use base Net::FCP::Txn; 669use base Net::FCP::Txn;
411 670
412sub rcv_node_info { 671sub rcv_node_info {
413 my ($self, $attr) = @_; 672 my ($self, $attr) = @_;
414 673
415 $self->eof ($attr); 674 $self->set_result ($attr);
416} 675}
417 676
418package Net::FCP::Txn::GenerateCHK; 677package Net::FCP::Txn::GenerateCHK;
419 678
420use base Net::FCP::Txn; 679use base Net::FCP::Txn;
421 680
422sub rcv_success { 681sub rcv_success {
423 my ($self, $attr) = @_; 682 my ($self, $attr) = @_;
424 683
425 $self->eof ($attr); 684 $self->set_result ($attr->{uri});
426} 685}
427 686
428package Net::FCP::Txn::GenerateSVKPair; 687package Net::FCP::Txn::GenerateSVKPair;
429 688
430use base Net::FCP::Txn; 689use base Net::FCP::Txn;
431 690
432sub rcv_success { 691sub rcv_success {
433 my ($self, $attr) = @_; 692 my ($self, $attr) = @_;
434 693 $self->set_result ([$attr->{public_key}, $attr->{private_key}, $attr->{crypto_key}]);
435 $self->eof ([$attr->{PublicKey}, $attr->{PrivateKey}]);
436} 694}
437 695
438package Net::FCP::Txn::InvertPrivateKey; 696package Net::FCP::Txn::InvertPrivateKey;
439 697
440use base Net::FCP::Txn; 698use base Net::FCP::Txn;
441 699
442sub rcv_success { 700sub rcv_success {
443 my ($self, $attr) = @_; 701 my ($self, $attr) = @_;
444
445 $self->eof ($attr->{PublicKey}); 702 $self->set_result ($attr->{public_key});
446} 703}
447 704
448package Net::FCP::Txn::GetSize; 705package Net::FCP::Txn::GetSize;
449 706
450use base Net::FCP::Txn; 707use base Net::FCP::Txn;
451 708
452sub rcv_success { 709sub rcv_success {
453 my ($self, $attr) = @_; 710 my ($self, $attr) = @_;
454
455 $self->eof ($attr->{Length}); 711 $self->set_result (hex $attr->{length});
712}
713
714package Net::FCP::Txn::GetPut;
715
716# base class for get and put
717
718use base Net::FCP::Txn;
719
720*rcv_uri_error = \&Net::FCP::Txn::rcv_throw_exception;
721*rcv_route_not_found = \&Net::FCP::Txn::rcv_throw_exception;
722
723sub rcv_restarted {
724 my ($self, $attr, $type) = @_;
725
726 delete $self->{datalength};
727 delete $self->{metalength};
728 delete $self->{data};
729
730 $self->progress ($type, $attr);
731}
732
733package Net::FCP::Txn::ClientGet;
734
735use base Net::FCP::Txn::GetPut;
736
737*rcv_data_not_found = \&Net::FCP::Txn::rcv_throw_exception;
738
739sub rcv_data {
740 my ($self, $chunk) = @_;
741
742 $self->{data} .= $chunk;
743
744 $self->progress ("data", { chunk => length $chunk, received => length $self->{data}, total => $self->{datalength} });
745
746 if ($self->{datalength} == length $self->{data}) {
747 my $data = delete $self->{data};
748 my $meta = new Net::FCP::Metadata (substr $data, 0, $self->{metalength}, "");
749
750 $self->set_result ([$meta, $data]);
751 $self->eof;
752 }
753}
754
755sub rcv_data_found {
756 my ($self, $attr, $type) = @_;
757
758 $self->progress ($type, $attr);
759
760 $self->{datalength} = hex $attr->{data_length};
761 $self->{metalength} = hex $attr->{metadata_length};
762}
763
764package Net::FCP::Txn::ClientPut;
765
766use base Net::FCP::Txn::GetPut;
767
768*rcv_size_error = \&Net::FCP::Txn::rcv_throw_exception;
769
770sub rcv_pending {
771 my ($self, $attr, $type) = @_;
772 $self->progress ($type, $attr);
773}
774
775sub rcv_success {
776 my ($self, $attr, $type) = @_;
777 $self->set_result ($attr);
778}
779
780sub rcv_key_collision {
781 my ($self, $attr, $type) = @_;
782 $self->set_result ({ key_collision => 1, %$attr });
783}
784
785=back
786
787=head2 The Net::FCP::Exception CLASS
788
789Any unexpected (non-standard) responses that make it impossible to return
790the advertised result will result in an exception being thrown when the
791C<result> method is called.
792
793These exceptions are represented by objects of this class.
794
795=over 4
796
797=cut
798
799package Net::FCP::Exception;
800
801use overload
802 '""' => sub {
803 "Net::FCP::Exception<<$_[0][0]," . (join ":", %{$_[0][1]}) . ">>";
804 };
805
806=item $exc = new Net::FCP::Exception $type, \%attr
807
808Create a new exception object of the given type (a string like
809C<route_not_found>), and a hashref containing additional attributes
810(usually the attributes of the message causing the exception).
811
812=cut
813
814sub new {
815 my ($class, $type, $attr) = @_;
816
817 bless [Net::FCP::tolc $type, { %$attr }], $class;
818}
819
820=item $exc->type([$type])
821
822With no arguments, returns the exception type. Otherwise a boolean
823indicating wether the exception is of the given type is returned.
824
825=cut
826
827sub type {
828 my ($self, $type) = @_;
829
830 @_ >= 2
831 ? $self->[0] eq $type
832 : $self->[0];
833}
834
835=item $exc->attr([$attr])
836
837With no arguments, returns the attributes. Otherwise the named attribute
838value is returned.
839
840=cut
841
842sub attr {
843 my ($self, $attr) = @_;
844
845 @_ >= 2
846 ? $self->[1]{$attr}
847 : $self->[1];
456} 848}
457 849
458=back 850=back
459 851
460=head1 SEE ALSO 852=head1 SEE ALSO
468 Marc Lehmann <pcg@goof.com> 860 Marc Lehmann <pcg@goof.com>
469 http://www.goof.com/pcg/marc/ 861 http://www.goof.com/pcg/marc/
470 862
471=cut 863=cut
472 864
865package Net::FCP::Event::Auto;
866
867my @models = (
868 [Coro => Coro::Event::],
869 [Event => Event::],
870 [Glib => Glib::],
871 [Tk => Tk::],
872);
873
874sub AUTOLOAD {
875 $AUTOLOAD =~ s/.*://;
876
877 for (@models) {
878 my ($model, $package) = @$_;
879 if (defined ${"$package\::VERSION"}) {
880 $EVENT = "Net::FCP::Event::$model";
881 eval "require $EVENT"; die if $@;
882 goto &{"$EVENT\::$AUTOLOAD"};
883 }
884 }
885
886 for (@models) {
887 my ($model, $package) = @$_;
888 $EVENT = "Net::FCP::Event::$model";
889 if (eval "require $EVENT") {
890 goto &{"$EVENT\::$AUTOLOAD"};
891 }
892 }
893
894 die "No event module selected for Net::FCP and autodetect failed. Install any of these: Coro, Event, Glib or Tk.";
895}
896
4731; 8971;
474 898

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines