-
Notifications
You must be signed in to change notification settings - Fork 0
/
usbip-ssh
executable file
·415 lines (398 loc) · 12.2 KB
/
usbip-ssh
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
#! /usr/bin/perl
our $script = sprintf qq{#line %d "%s"\n%s}, __LINE__ + 1, __FILE__, <<'__END__';eval $script; die $@ if $@; exit;
use strict;
my $SSH = 'ssh';
my $PERL = '/usr/bin/perl';
my $drivers = '/sys/bus/usb/drivers';
my $devices = '/sys/bus/usb/devices';
my $verbose;
eval qq{\$$1="\Q$2\E";shift} or die $@ while $ARGV[0] =~ /^(\w+)=(.*)/s;
*DEBUG = sub { print STDERR "@_\n" } if $verbose;
if($ARGV[0] eq 'remote'){
shift; remote_script(@ARGV);
}elsif($ARGV[0] eq 'list'){
shift; list_devices(@ARGV);
}elsif($ARGV[0] eq 'find'){
shift; print find_dev(@ARGV), "\n";
}elsif($ARGV[0] eq 'unbind'){
shift; unbind(@ARGV);
}elsif($ARGV[0] eq 'detach'){
shift; local_detach(@ARGV);
}elsif($ARGV[0] eq 'keep'){
shift; persistent(@ARGV);
}elsif($ARGV[0] eq 'daemon'){
shift; daemon(@ARGV);
}elsif(length $ARGV[0]){
exit xwait(local_script(@ARGV));
}else{
my $cmd = $0 =~ s{^.*/}{}r;
die <<"EOT";
usage:
$cmd USER\@HOST DEV_PATTERN
attach single device matching DEV_PATTERN from HOST
$cmd USER\@HOST [list]
list devices from HOST
$cmd USER\@HOST find DEV_PATTERN
find single device matching DEV_PATTERN on HOST
$cmd keep USER\@HOST ...
same commands as above, but keep trying to connect to HOST
and to reconnect to it if the connection is broken
$cmd daemon USER\@HOST ...
same as 'keep' but detached from the tty and using syslog
for messages and errors
$cmd list
$cmd find DEV_PATTERN
same commands as above on the local machine
DEV_PATTERN is as returned by the 'list' command: a busid like 3-3.1, a
vip:pid like 03f0:e111, or a pattern matching the vid:pid, the product name
or the serial number.
You can add command line options for ssh before USER\@HOST.
EOT
}
###############################################
sub readfile { open my $h, shift or return ""; local $/; <$h> =~ s/\s+$//r }
sub DEBUG {}
sub ERROR { die "ERROR: @_\n" }
sub INFO { DEBUG "INFO", @_ }
sub xwritefile {
my $f = shift;
DEBUG "WRITE $f < @_";
open my $h, '>', $f or die "open> $f: $!\n";
syswrite $h, "@_" or die "write> $f @_: $!\n";
}
sub xreadfile {
my $f = shift;
open my $h, '<', $f or die "open< $f: $!\n";
local $/; my $d = <$h> or die "readline< $f: $!\n";
$d =~ s/\s+$//;
die "\nempty file $f" unless length $d;
DEBUG "READ $f > $d";
$d;
}
sub xsystem {
DEBUG "EXEC @_";
system(@_) == -1 and die "system $_[0]: $!";
die "system @_: status ".($? >> 8) if $?;
}
sub xtmpdir {
require File::Temp;
File::Temp->newdir("usbip-ssh-XXXXXX", TMPDIR => 1);
}
###############################################
use constant {
LOW => 1, FULL => 2, HIGH => 3, SUPER => 5, SUPER_PLUS => 6,
SDEV_ST_AVAILABLE => 1, SDEV_ST_USED => 2, VDEV_ST_NULL => 4,
};
sub remote_attach {
my ($sockfd, $busid) = @_;
my $status = readfile "$drivers/usbip-host/$busid/usbip_status";
if($status != SDEV_ST_AVAILABLE){
if($status == SDEV_ST_USED){
xwritefile "$devices/$busid/usbip_sockfd", -1;
}else{
xsystem qw(/sbin/modprobe -v usbip-host);
}
xwritefile "$drivers/usb/unbind", $busid;
xwritefile "$drivers/usbip-host/match_busid", "add $busid";
xwritefile "$drivers/usbip-host/bind", $busid;
}
xwritefile "$devices/$busid/usbip_sockfd", $sockfd;
}
sub local_attach {
my ($sockfd, $bus, $dev, $speed) = @_;
# as per linux/usb/ch9.h and drivers/usb/core/sysfs.c
my %hspeed = ( 1.5 => LOW, 12 => FULL, 480 => HIGH,
5000 => SUPER, 10000 => SUPER_PLUS, 20000 => SUPER_PLUS,
12 => LOW # override, FULL speed isn't supported
);
my $hspeed = $hspeed{$speed} // HIGH;
xsystem qw(/sbin/modprobe -v vhci-hcd);
my ($vhci, $port) = find_vhci_and_port($hspeed);
xwritefile "$vhci/attach",
sprintf "%d %d %d %d", $port, $sockfd, $bus<<16|$dev, $hspeed;
}
sub local_detach {
my $busid = join '|', map { /^all$/i ? '.*' : quotemeta } @_;
my (@b, $n);
for my $f (</sys/devices/platform/vhci_hcd.*/status*>){
open my $h, '<', $f or warn "open $f: $!" and next;
<$h>; # skip header
while(<$h>){
my ($hub, $port, $sta, $spd, $dev, $sock_fd, $lbusid)
= split;
next unless $sta == 6; # VDEV_ST_USED
push @b, $lbusid;
if($lbusid =~ $busid){
my ($vhci) = $f =~ m{(.*)/};
xwritefile "$vhci/detach", int($port);
$n++;
}
}
}
die "no devices attached\n" unless @b;
die "'@_' did not match any of: @b\n" unless $n;
}
sub unbind {
my $busid = find_dev(@_);
xwritefile "$drivers/usbip-host/unbind", $busid;
xwritefile "$drivers/usbip-host/match_busid", "del $busid";
xwritefile "$drivers/usbip-host/rebind", $busid;
}
###############################################
sub find_vhci_and_port {
my $speed = shift;
my $shub = $speed >= SUPER ? 'ss' : 'hs';
for my $f (</sys/devices/platform/vhci_hcd.*/status*>){
open my $h, '<', $f or warn "open $f: $!" and next;
<$h>; # skip header
while(<$h>){
my ($hub, $port, $sta) = split;
return $f =~ m{^(.*)/}, int($port)
if $sta == VDEV_ST_NULL and $hub eq $shub;
}
}
die "no suitable vhci port found for speed = $speed";
}
sub find_dev {
my ($pat) = @_;
if($pat =~ /^\d+-\d+(?:\.\d+)*$/){
return $pat if -d "$devices/$pat";
ERROR "no such device $pat";
}
s/\b0*(?=[0-9a-f]+:)/\\b0*/i, s/:0*([0-9a-f]+)\b/:0*$1\\b/i, $_ = qr/$_/
for my $rpat = $pat;
INFO "looking for $rpat inside $devices";
my @found;
for my $p (<$devices/[0-9]*>){
next unless my ($busid) = $p =~ m{/(\d+-\d+(?:\.\d+)*)$};
my ($vid, $pid, $serial, $manufacturer, $product) =
map readfile("$p/$_"),
qw(idVendor idProduct serial manufacturer product);
my $spec = sprintf "%-10s %s:%s %s %s %s %s %s",
$busid, $vid, $pid, $serial, $manufacturer, $product;
push @found, $busid if my $found = $spec =~ $rpat;
DEBUG sprintf " <%d> %s", $found, $spec;
}
return $found[0] if @found == 1;
ERROR @found ? "multiple" : "no", " devices match '$rpat'";
}
sub xwait {
waitpid shift // -1, 0; $? ? ($? >> 8 or $? | 64) : 0
}
sub ssh_myself {
use IPC::Open3;
my ($stdout, $stderr, $ssh, $uhost, @args) = @_;
unshift @args, 'verbose=1' if $verbose;
DEBUG "EXEC @$ssh $uhost $PERL - @args";
my $pid = open3 my $to, $_[0], $_[1], @$ssh, $uhost, $PERL, '-', @args;
print $to our $script or die;
INFO "pid=$pid";
return $pid;
}
sub ssh_myself_simple {
xwait ssh_myself '>&STDOUT', '>&STDERR', @_;
}
sub local_script {
my @ssh = $SSH;
while($_[0] =~ /^-/){
push @ssh, my $o = shift;
# see getopt(..) in ssh.c
push @ssh, shift
if $o =~ /^-[1246afgknqstvxACGKMNPTVXYy]*[bceilmopBDEFIJLOQRSwW]$/;
}
my $uhost = shift;
unless(@_){
return ssh_myself_simple [@ssh], $uhost, 'list';
}elsif($_[0] =~ /^(?:list|unbind|find)$/){
return ssh_myself_simple [@ssh], $uhost, @_;
}
my $tmpdir = xtmpdir;
my @ssh_S = ($ssh[0], -S => "$tmpdir/ctl", $uhost);
my $pid = ssh_myself my $sfrom, undef,
[@ssh, -S => "$tmpdir/ctl", '-M'], $uhost, 'remote', @_;
my $old_handler = $SIG{__DIE__};
$SIG{__DIE__} = sub {
$SIG{__DIE__} = $old_handler;
use POSIX ':sys_wait_h';
if(waitpid($pid, WNOHANG) == 0){
system @ssh_S, qw(-O exit);
print STDERR " $_" while <$sfrom>;
xwait $pid;
}
die @_
};
my $response;
while(<$sfrom>){
if(/^RESPONSE (.*)/){ $response = $1; last }
else { print STDERR " $_" }
}
die "remote failed to attach\n" unless $response;
my ($bus, $dev, $speed, $rpath) = split ' ', $response;
my $lpath = "$tmpdir/vhci";
xsystem @ssh_S, qw(-O forward), -L => "$lpath:$rpath";
require IO::Socket::UNIX;
my $sock = new IO::Socket::UNIX $lpath
or die "connect to $lpath: $!";
unlink $lpath or warn "unlink $lpath: $!";
sysread $sock, my $d, 1 or die "sysread on $lpath: $!\n";
INFO sprintf "DEVSPEC: fd=%d bus/dev=%d/%d (%d) speed=%d",
$sock->fileno, $bus, $dev, $bus<<16|$dev, $speed;
local_attach($sock->fileno, $bus, $dev, $speed);
close $sock;
xsystem @ssh_S, qw(-q -O stop); # should delete the ctl socket
undef $tmpdir; # should remove the tmp dir XXX
print STDERR " $_" while <$sfrom>;
return $pid;
}
sub remote_script {
my ($spec, $opt) = @_;
my $busid = find_dev($spec);
my ($bus, $dev, $speed) =
map xreadfile("$devices/$busid/$_"), qw(busnum devnum speed);
my $sock;
{
my $tmpdir = xtmpdir;
my $path = "$tmpdir/host";
require IO::Socket::UNIX;
my $srv = new IO::Socket::UNIX(Listen => 1, Local => $path)
or ERROR "bind to $path: $!";
printf "RESPONSE %d %d %s %s\n", $bus, $dev, $speed, $path;
open STDOUT, ">/dev/null" or die "open STDOUT>/dev/null: $!";
vec(my $rb, $srv->fileno, 1) = 1;
select($rb, undef, undef, .4)
or ERROR "timeout waiting for connection on $path";
$sock = $srv->accept or ERROR "accept on $path: $!";
remote_attach($sock->fileno, $busid);
syswrite $sock, "T", 1 or ERROR "syswrite on $path: $!";
unlink $path;
}
exit if $opt eq 'nolinger';
# the only purpose of lingering past this point is to unbind the
# usbip-host driver from the device after the other side has finished
# using it
require IO::Poll; sub POLLRDHUP(){ 0x2000 }
my $poll = new IO::Poll;
$poll->mask($sock, POLLRDHUP);
die "fork: $!" unless defined(my $pid = fork);
exit if $pid;
# no point in dying from a SIGPIPE
use_syslog();
open STDIN, "</dev/null" or die "open STDIN</dev/null: $!";
open STDERR, ">/dev/null" or die "open STDERR>/dev/null: $!";
$poll->poll(-1);
unbind($busid);
}
sub list_devices {
sub dv { $_[0] =~ s/(\d+)/reverse$1/ger }
opendir my $d, $devices or ERROR "opendir $devices: $!";
my $odev;
my %c = (
'01' => 'audio', '02' => 'COM',
'03' => 'HID',
'030001' => 'kbd',
'030002' => 'mouse',
'030101' => 'kbd', # boot
'030102' => 'mouse', # boot
'07' => 'printer', '08' => 'UMASS',
'09' => 'hub', '0a' => 'CDC', '0e' => 'video',
'e0' => 'wireless',
'e00101' => 'bluetooth',
'e00103' => 'RNDIS',
);
sub read_uevent { split /[=\n]/, readfile "$_[0]/uevent" }
for(sort {dv($a) cmp dv($b)} readdir $d){
my ($dev, $if) = /^(\d+-\d+(?:\.\d+)*)(:[\d.]+)?$/ or next;
my $path = "$devices/$_";
next if $if and $dev ne $odev;
$odev = $dev;
my %e = read_uevent $path;
my $indent = ' ' x ($dev =~ y/.//);
if($if){
my ($c, $s, $p) = map sprintf('%02x', $_),
split '/', $e{INTERFACE};
my @extra;
if(length(my $ifs = readfile "$path/interface")){
$ifs =~ s/ Interface$//;
push @extra, "/$ifs" unless
$c.$s.$p eq '080650' and
$ifs eq 'Bulk-In, Bulk-Out,';
}
if(my $drv = $e{DRIVER}){
push @extra, "[$drv]";
use File::Find;
find { wanted => sub {
next unless m{(.*)/dev(?:_id)?$}
and my %u = read_uevent $1;
push @extra,
$u{DEVNAME} =~ s{^input/}{}r;
}, no_chdir => 1 }, "$path/";
}
printf "%s %s %s%s%s %-5s %s\n",
$indent,
$if, $c, $s, $p,
$c{$c.$s.$p} // $c{$c.$s} // $c{$c},
join ' ', @extra;
}else{
my ($vid, $pid, $rev) = map hex, split '/', $e{PRODUCT};
my ($serial, $manufacturer, $product) =
map readfile("$path/$_"),
qw(serial manufacturer product);
my $driver = "[$e{DRIVER}]"
unless $e{DRIVER} =~ /^(?:usb|hub)$/;
$manufacturer =~ s/^Bluetooth v2\.0$|^USB$//;
my $extra = join ' ', grep length,
$serial, $manufacturer, $product, $driver;
printf "%s%s %04x:%04x %s\n",
$indent, $dev, $vid, $pid, $extra;
}
}
}
sub persistent {
my @args = @_;
unshift @args, qw(
-oConnectTimeout=15 -oServerAliveInterval=15
-oCheckHostIP=no -oBatchMode=yes);
my ($minwait, $maxwait) = (.5, 60);
for(my $wait = $minwait;;){
my $ot = time;
eval { xwait local_script(@args) };
warn $@ if $@ and !$SIG{__DIE__};
my $dt = time - $ot;
INFO "done after $dt seconds";
if($dt < $wait){
my $st = $wait / ($dt > 1 ? $dt : 1);
INFO "will sleep for $st seconds";
sleep $st;
}
if($dt > $maxwait){
$wait = $minwait;
}else{
$wait = $maxwait if ($wait *= 4) > $maxwait;
}
}
}
sub use_syslog {
use Sys::Syslog qw(:standard :macros);
my $syslog = sub {
openlog $0 =~ s{.*/}{}r, 0, LOG_DAEMON;
my $prio = shift; syslog $prio, '%s', "@_" =~ s/\n+$//r;
closelog;
};
$SIG{__DIE__} = sub { $syslog->(LOG_ERR, @_) };
$SIG{__WARN__} = sub { $syslog->(LOG_WARNING, @_) };
*DEBUG = sub { $syslog->(LOG_DEBUG, @_) };
}
sub daemon {
use POSIX qw(setsid);
return if my $pid = fork;
die "fork: $!" unless defined $pid;
use_syslog();
die "setsid: $!" unless setsid;
open *STDIN, '+</dev/null' or die "open /dev/null: $!";
open $_, '>&', *STDIN or die "open $_ >/dev/null: $!"
for *STDOUT, *STDERR;
my @args = @_;
unshift @args, '-y'; # let ssh use syslog
persistent(@args);
}
__END__