File: ControlPort.pm

package info (click to toggle)
tiarra 20100212-4
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 2,732 kB
  • ctags: 1,712
  • sloc: perl: 32,032; lisp: 193; sh: 109; makefile: 10
file content (380 lines) | stat: -rw-r--r-- 9,162 bytes parent folder | download | duplicates (4)
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
# -----------------------------------------------------------------------------
# $Id: ControlPort.pm 11365 2008-05-10 14:58:28Z topia $
# -----------------------------------------------------------------------------
=pod
    << NOTIFY Log::Channel TIARRACONTROL/1.0
    << Sender: LogManager
    << ID: synchronize

    >> TIARRACONTROL/1.0 204 No Content
    ----------------------------------------
    << GET :: TIARRACONTROL/1.0
    << Sender: Foo
    << ID: get-realname
    << Reference0: ircnet
    << Charset: UTF-8

    >> TIARRACONTROL/1.0 200 OK
    >> Value: (ネットワークircnetでの本名)
    >> Charset: UTF-8
=cut
# -----------------------------------------------------------------------------
package ControlPort;
use strict;
use warnings;
use Carp;
use IO::Dir;
use ExternalSocket;
use Tiarra::Encoding;
use RunLoop;
use Tiarra::TerminateManager;

# 複数のパッケージを混在させてるとSelfLoaderが使えない…?
#use SelfLoader;
#1;
#__DATA__

sub TIARRA_CONTROL_ROOT () { '/tmp/tiarra-control'; }

sub new {
    my ($class,$sockname) = @_;

    # IO::Socket::UNIXをuseする。失敗したらdie。
    eval q{
        use IO::Socket::UNIX;
    }; if ($@) {
	# 使えない。
	die "Tiarra control socket is not available for this environment.\n";
    }

    my $this = {
	sockname => $sockname,
	filename => TIARRA_CONTROL_ROOT.'/'.$sockname,
	server_sock => undef, # ExternalSocket
	clients => [], # ControlPort::Session
	session_handle_hook => undef, # RunLoop::Hook
    };
    bless $this,$class;
    $this->open;

    $this;
}

sub open {
    my $this = shift;
    my $filename = $this->{filename};

    # ディレクトリ/tmp/tiarra-controlが無ければ作る。
    if (!-d TIARRA_CONTROL_ROOT) {
	mkdir TIARRA_CONTROL_ROOT or die 'Couldn\'t make directory '.TIARRA_CONTROL_ROOT;
	# 他のユーザーも作れるようにする。
	# 最初に作成したユーザーが全ファイルを消すことが出来るが、対処法なし。
	chmod 01777, TIARRA_CONTROL_ROOT;
    }

    # ソケットが既に存在した場合は接続してみる。
    if (-e $filename) {
	my $sock = IO::Socket::UNIX->new(
	    Peer => $filename,
	   );
	if (!defined $sock) {
	    # もう使われていない?
	    unlink $filename;
	    undef $sock;
	}
    }

    # リスニング用ソケットを開く。
    my $sock = IO::Socket::UNIX->new(
	Type => &SOCK_STREAM,
	Local => $filename,
	Listen => 1);
    if (!defined $sock) {
	die "Couldn't make socket $filename: $!";
    }
    # パーミッションを700に。
    chmod 0700, $filename;
    $this->{server_sock} =
	ExternalSocket->new(
	    Socket => $sock,
	    Read => sub {
		my $server = shift->sock;
		my $client = $server->accept;
		if (defined $client) {
		    push @{$this->{clients}},ControlPort::Session->new($client);
		}
	    },
	    Write => sub{},
	    WantToWrite => sub{undef})->install;

    # セッションハンドル用のフックをかける。
    $this->{session_handle_hook} =
	RunLoop::Hook->new(
	    'ControlPort Session Handler',
	    sub {
		# セッション処理
		foreach my $client (@{$this->{clients}}) {
		    $client->main;
		}
		# 終了したセッションを削除
		@{$this->{clients}} = grep {
		    $_->is_alive;
		} @{$this->{clients}};
	    })->install;

    $this->{destructor} = Tiarra::TerminateManager::Hook->new(
	sub {
	    $this->destruct;
	})->install;

    $this;
}

sub destruct {
    my $this = shift;

    # 切断
    if (defined $this->{server_sock}) {
	eval {
	    $this->{server_sock}->disconnect;
	};
    }

    # このソケットファイルを削除
    unlink $this->{filename};

    # ディレクトリにソケットが一つも無くなったら、このディレクトリも消える。
    rmdir TIARRA_CONTROL_ROOT;

    $this;
}

package ControlPort::Session;
use strict;
use warnings;
use Tiarra::Socket::Lined;
use base qw(Tiarra::Socket::Lined);

sub new {
    # $sock: IO::Socket
    my ($class,$sock) = @_;
    my $this = $class->SUPER::new(name => 'ControlPort::Session');
    $this->{method} = undef; # GETまたはNOTIFY
    $this->{module} = undef; # Log::Channelなど。'::'はメインプログラムを表す。
    $this->{header} = undef; # {key => value}
    $this->{input_is_frost} = 0; # これ以上の入力を無視するか?
    bless $this,$class;
    $this->attach($sock);
    $this->install;
}

sub main {
    my $this = shift;

    while (defined($_ = $this->pop_queue)) {
	s/^\s*|\s*$//g;
	my $line = $_;

	if ($this->{input_is_frost}) {
	    last;
	}

	if (defined $this->{header}) {
	    # $this->{header}が存在するということは、最初のリクエスト行はもう受け取った。
	    if ($line eq '') {
		# 空の行だ。リクエスト終わり。
		$this->respond;
	    }
	    else {
		if ($line =~ m/^(.+?)\s*:\s*(.+)$/) {
		    $this->{header}{$1} = $2;
		}
		else {
		    $this->reply(401,'Bad Request');
		}
	    }
	}
	else {
	    if ($line =~ m|^(.+?)\s+(.+?)\s+TIARRACONTROL/(\d+)\.(\d+)$|) {
		$this->{method} = $1;
		$this->{module} = $2;
		if (!{GET => 1,NOTIFY => 1}->{$this->{method}}) {
		    $this->reply(501,'Method Not Implemented');
		}
		my $version = "$3.$4";
		if ($version > 1.0) {
		    $this->reply(401,'Bad Request');
		}
		$this->{header} = {};
	    }
	    else {
		$this->reply(401,'Bad Request');
	    }
	}
    }
}

sub reply {
    # $code: 204など
    # $str: No Contentなど
    # $header: {key => value} 省略可。文字コードはUTF-8。SenderとCharsetは不要。
    my ($this,$code,$str,$header) = @_;

    $this->append_line("TIARRACONTROL/1.0 $code $str");
    $this->append_line('Sender: Tiarra #'.&::version);
    my $unijp = Tiarra::Encoding->new;
    if (defined $header) {
	while (my ($key,$value) = each %$header) {
	    $this->append_line($unijp->set("$key: $value")->conv($this->charset));
	}
    }
    $this->append_line('Charset: '.$this->long_charset);
    $this->append_line('');
    $this->disconnect_after_writing;
}

sub charset {
    # リクエストで受け取ったCharsetから、Unicode::Japaneseエンコーディング名を返す。
    my $this = shift;

    if (!defined $this->{header}) {
	return 'utf8';
    }

    my $charset = $this->{header}->{Charset};
    if (!defined $charset) {
	return 'utf8';
    }

    my $charset_table = {
	'Shift_JIS' => 'sjis',
	'EUC-JP' => 'euc',
	'ISO-2022-JP' => 'jis',
	'UTF-8' => 'utf8',
    };
    $charset_table->{$charset} || 'utf8';
}

sub long_charset {
    my $this = shift;

    my $table = {
	'sjis' => 'Shift_JIS',
	'euc' => 'EUC-JP',
	'jis' => 'ISO-2022-JP',
	'utf8' => 'UTF-8',
    };
    $table->{$this->charset} || 'UTF-8';
}

sub is_alive {
    shift->connected;
}

sub respond {
    my $this = shift;

    my $req = ControlPort::Request->new($this->{method},$this->{module});
    my $charset = $this->charset;
    my $unijp = Tiarra::Encoding->new;
    while (my ($key,$value) = each %{$this->{header}}) {
	next if $key eq 'Charset';
	$req->$key($unijp->set($value,$charset)->utf8);
    }

    my $rep = eval {
	if ($req->module eq '::') {
	    # モジュール"::"はメインプログラムを表す。
	    # 後で。
	    die qq{Controlling '::' is not supported yet.\n};
	}
	else {
	    # このようなモジュールは存在するか?
	    my $mod = ModuleManager->shared->get($req->module);
	    if (defined $mod) {
		my $reply = $mod->control_requested($req);
		if (!defined $reply) {
		    die $this->{module}."->control_requested returned undef.\n";
		}
		elsif (!$reply->isa('ControlPort::Reply')) {
		    die $this->{module}."->control_requested returned bad ref: ".ref($reply)."\n";
		}
		else {
		    $reply;
		}
	    }
	    else {
		die qq{Module $this->{module} doesn't exist.\n};
	    }
	}
    };
    if ($@) {
	(my $detail = $@) =~ s/\n//g;
	$this->reply(500,'Internal Server Error',{Detail => $detail});
    }
    else {
	$this->reply($rep->code,$rep->status,$rep->table);
    }
}

package ControlPort::Packet;
use strict;
use warnings;
our $AUTOLOAD;
use Tiarra::Utils ();
Tiarra::Utils->define_attr_getter(0, qw(table));

sub new {
    my $class = shift;
    my $this = {
	table => {}, # {key => value}
    };
    bless $this,$class;
}

sub AUTOLOAD {
    my ($this,$value) = @_;
    if ($AUTOLOAD =~ /::DESTROY$/) {
	return;
    }

    (my $key = $AUTOLOAD) =~ s/.+?:://g;
    if (defined $value) {
	$this->{table}{$key} = $value;
    }
    $this->{table}{$key};
}

package ControlPort::Request;
use strict;
use warnings;
use base qw(ControlPort::Packet);
use Tiarra::Utils ();
Tiarra::Utils->define_attr_getter(0, qw(method module));

sub new {
    my ($class,$method,$module) = @_;
    my $this = $class->SUPER::new;
    $this->{method} = $method;
    $this->{module} = $module;
    $this;
}

package ControlPort::Reply;
use strict;
use warnings;
use base qw(ControlPort::Packet);
use Tiarra::Utils ();
Tiarra::Utils->define_attr_getter(0, qw(code status));

sub new {
    # $code: 204など
    # $status: No Contentなど
    my ($class,$code,$status) = @_;
    my $this = $class->SUPER::new;
    $this->{code} = $code;
    $this->{status} = $status;
    $this;
}

1;