This file is indexed.

/usr/bin/bbvirt is in bit-babbler 0.5.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

  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
416
417
418
419
420
421
422
423
424
425
#!/bin/bash
# This file is distributed as part of the bit-babbler package.
# Copyright 2015 - 2016,  Ron <ron@debian.org>

# Default configuration if not explicitly specified.
config_dir="/etc/bit-babbler"
config_file="$config_dir/vm.conf"
verbose=0

# Default to searching the PATH for tools we use.
seedd="seedd"
virsh="virsh"


die()
{
    echo "$0: $*" 1>&2
    exit 1
}

verb()
{
    n=$1
    shift

    (( verbose < n )) || echo "$*"
}

usage()
{
    cat 1>&2 <<EOF

 bbvirt attach|detach <device> [options]
 bbvirt attach-all|detach-all [<domain>] [options]

  Helper script to hotplug BitBabbler devices into (and back out of) libvirt
  managed virtual machines, either manually, or triggered by udev events.

  The first form above is used to attach or detach a single device from a VM,
  and is suitable for use as a hotplug trigger, such as a udev rule.

  The second form is offered as a convenience for the task of attaching or
  detaching all devices assigned to a particular VM domain (or all of the
  configured domains if no explicit domain is passed).

  A <device> may be specified by its serial number, its logical address on the
  USB bus in the form BUSNUM:DEVNUM, or its physical address on the USB bus in
  the form BUS-PORT[.PORT ...].  A <domain> is the libvirt VM domain name.

  The following options may also be used:

   -C, --config "file"  Use the specified configuration file for the default
                          assignment of devices to VM domains.

   -c, --connect "URI"  Override the default virsh URI (or the DOMAIN_URI that
                          is specified in the configuration file).

   -D, --domain "name"  Act on the given domain, overriding any assignment of
                          the device in the configuration file.

   -b, --busnum "num"   Explicitly specify the USB bus number that the device
                          is attached to, rather than searching for it.

   -d, --devnum "num"   Explicitly specify the logical USB device number on
                          the USB bus, rather than searching for it.

   -n, --dry-run        Don't attach or detach any devices, just show what
                          would happen if this was a live run.

   -v, --verbose        Be more noisy about what is happening.
   -?, --help           Shows this usage summary.

EOF
    exit "$1"
}

parse_args()
{
    while (( $# )); do
        case $1 in
            attach|detach)          action=$1; shift; device=$1 ;;

            attach-all|detach-all)  action=${1%-all}
                                    do_all=1
                                    if [[ $2 != -* ]]; then
                                        shift
                                        domain=$1
                                    fi
                                    ;;

            --busnum=*)             printf -v busnum "%03d" "$(( 10#${1#*=} ))" ;;
            --busnum|-b)    shift;  printf -v busnum "%03d" "$(( 10#$1 ))" ;;

            --devnum=*)             printf -v devnum "%03d" "$(( 10#${1#*=} ))" ;;
            --devnum|-d)    shift;  printf -v devnum "%03d" "$(( 10#$1 ))" ;;

            --connect=*)            uri=${1#*=} ;;
            --connect|-c)   shift;  uri=$1 ;;

            --domain=*)             domain=${1#*=} ;;
            --domain|-D)    shift;  domain=$1 ;;

            --config=*)             config_file=${1#*=} ;;
            --config|-C)    shift;  config_file=$1 ;;

            --dry-run|-n)           dry_run=1 ;&    # --dry-run implies --verbose
            --verbose|-v)           (( ++verbose )) ;;
            -vv)                    (( verbose += 2 ));;
            -vvv)                   (( verbose += 3 ));;
            -vvvv)                  (( verbose += 4 ));;

            --help|-\?)             show_help=1 ;;

            *)
                die "ERROR: unrecognised option '$1', try --help"
                ;;
        esac
        shift
    done
}

parse_args "$@"

[ -z "$show_help" ] || usage 0


# Import the configuration of which devices belong to which VM domains.
import_domain_config()
{
    [[ $config_file == */* ]] ||
        config_file="$config_dir/$(basename -- "$config_file" .conf).conf"

    if [ -f "$config_file" ] && [ -r "$config_file" ]; then
        . "$config_file"
    else
        verb 1 "Unable to read config file '$config_file'"
        exit 0
    fi
}


# Device array indices
DA_STRIDE=9
DA_BUSNUM=1
DA_DEVNUM=2
DA_SERIAL=5
DA_PORTNUM=8
DA_MAGIC=$'\nD:'

# Import details of available devices in the shell machine readable format.
get_available_devices()
{
    all_devices=()

    # Clear IFS, the leading \n is part of the magic and we don't want it stripped.
    while IFS= read -r -d '' f; do
        all_devices+=("$f")
    done < <( "$seedd" --shell-mr )

    if (( verbose > 3 )); then
        printf "seedd reported:"
        printf " '%s'" "${all_devices[@]}"
        printf "\n"
    fi
}

# Find a device matching some combination of attributes.
# get_device_by index match [index match ...]
get_device_by()
{
    compare=( "$@" )
    selected_device=()

    for (( i = 0; i < ${#all_devices[@]}; i += DA_STRIDE )); do

        # Assert the array is framed with the expected stride and magic.
        [ "${all_devices[$i]}" = "$DA_MAGIC" ] ||
            die "Invalid device array magic at element $i '${all_devices[$i]}'"

        # Try the next device if this one doesn't match all attributes
        for (( j = 0; j < $#; j += 2 )); do
            index=${compare[$j]}
            match=${compare[(($j + 1))]}
            [ "${all_devices[(($i + $index))]}" = "$match" ] || continue 2
        done

        # Slice all details of the first matching device.
        selected_device=( "${all_devices[@]:$i:$DA_STRIDE}" )
        break;
    done
}

# Do $action for each available device assigned to $domain (with $propagate_opts)
act_on_all_devices_in_domain()
{
    devs="DOMAIN_RNG_${domain}[@]"

    for dev in "${!devs}"; do
        verb 4 "VM $domain, $action device $dev"

        get_device_by "$DA_SERIAL" "$dev"

        if (( ${#selected_device[@]} == DA_STRIDE )); then

            exec_opts=( "$action" "$dev" -D "$domain" )
            exec_opts+=( -b "${selected_device[$DA_BUSNUM]}" )
            exec_opts+=( -d "${selected_device[$DA_DEVNUM]}" )
            exec_opts+=( "${propagate_opts[@]}" )

            verb 2 "$0 ${exec_opts[*]}"
            "$0" "${exec_opts[@]}"
        fi
    done
}


# For attach-all or detach-all, we synthesise a series of attach/detach calls
# with all the necessary options for each device in the requested domain(s).
if [ -n "$do_all" ]; then

    import_domain_config
    get_available_devices

    propagate_opts=( ${config_file:+ -C "$config_file"} )
    propagate_opts+=( ${uri:+ -c "$uri"} )
    propagate_opts+=( ${dry_run:+ -n} )

    # Propagate verbose flags up to -vvvv (the maximum level we actually use),
    # accounting for the fact that dry_run bumps the verbosity level too.
    for (( i = ${dry_run:-0}; i < verbose; ++i )); do
        v+="v"
    done
    propagate_opts+=( ${v:+ "-${v:0:4}"} )


    if [ -n "$domain" ]; then

        # Act on all the devices configured for the given domain
        act_on_all_devices_in_domain

    else

        # Act on all the devices configured for all domains
        for dom in "${!DOMAIN_RNG_@}"; do
            domain=${dom#DOMAIN_RNG_}
            act_on_all_devices_in_domain
        done
    fi

    exit 0
fi


# We need at least these two to do anything at all below here.
[ -n "$action" ] || die "No action specified."
[ -n "$device" ] || die "No device specified."


check_or_set_busnum()
{
    if [ -z "$busnum" ]; then
        busnum=$1
    elif [ "$busnum" != "$1" ]; then
        die "Device bus $1 != --busnum $busnum."
    fi
}

check_or_set_devnum()
{
    if [ -z "$devnum" ]; then
        devnum=$1
    elif [ "$devnum" != "$1" ]; then
        die "Device number $1 != --devnum $devnum."
    fi
}


# Figure out which device we've been asked to act on.
if [[ $device =~ ^[[:digit:]]{1,3}:[[:digit:]]{1,3}$ ]]; then

    # We were passed a device logical address in the form BUSNUM:DEVNUM
    printf -v bnum "%03d" "$(( 10#${device%:*} ))"
    printf -v dnum "%03d" "$(( 10#${device#*:} ))"

    check_or_set_busnum "$bnum"
    check_or_set_devnum "$dnum"

    get_available_devices
    get_device_by "$DA_BUSNUM" "$busnum" "$DA_DEVNUM" "$devnum"

    (( ${#selected_device[@]} == DA_STRIDE )) ||
        die "Failed to find device '$device'"

    devserial=${selected_device[$DA_SERIAL]}

    verb 1 "Device at logical address $bnum:$dnum has serial '$devserial'."

elif [[ $device =~ ^[[:digit:]]+-[[:digit:].]+$ ]]; then

    # We were passed a device physical address in the form BUS-PORT[.PORT ...]
    printf -v bnum "%03d" "$(( 10#${device%-*} ))"
    pnum=${device#*-}

    check_or_set_busnum "$bnum"

    get_available_devices
    get_device_by "$DA_BUSNUM" "$busnum" "$DA_PORTNUM" "$pnum"

    (( ${#selected_device[@]} == DA_STRIDE )) ||
        die "Failed to find device '$device'"

    devserial=${selected_device[$DA_SERIAL]}

    check_or_set_devnum "${selected_device[$DA_DEVNUM]}"

    verb 1 "Device at physical address $((10#$bnum))-$pnum has serial '$devserial'."

elif [[ $device =~ ^[A-Z0-9]{6,7}$ ]]; then

    # If it wasn't either of the above, assume this may be a serial number.
    devserial=$device

else

    die "Invalid device identifier '$device'"
fi


# Build an index mapping device serial numbers to domain names.
map_devices_to_domains()
{
    import_domain_config

    for dom in "${!DOMAIN_RNG_@}"; do
        verb 4 "domain: $dom"

        devs="${dom}[@]"
        for dev in "${!devs}"; do
            verb 4 "   dev: $dev"
            domains[$dev]=${dom#DOMAIN_RNG_}
        done
    done

    if (( verbose > 2 )); then
        for dev in "${!domains[@]}"; do
            echo "device $dev is in domain ${domains[$dev]}"
        done
    fi
}


# If the VM domain wasn't explicitly specified, try to find it from the
# configured device allocations.  It's not an error for it not to be,
# the udev rule will run this for all devices, even those that we aren't
# passing through to a VM.
if [ -z "$domain" ]; then

    declare -A domains
    map_devices_to_domains

    domain=${domains[$devserial]}

    if [ -z "$domain" ]; then
        verb 1 "Device '$devserial' is not assigned to any domain."
        exit 0
    fi
fi

# Check if we need to pass an explicit --connect URI to virsh.
if [ -z "$uri" ]; then
    uri_config="DOMAIN_URI_$domain"
    uri=${!uri_config}
fi


# Check that we were passed, or have determined, the logical address of the
# device, since that is the only way that we can pass it to virsh at present.
if [ -z "$busnum" ] || [ -z "$devnum" ]; then

    get_available_devices
    get_device_by "$DA_SERIAL" "$devserial"

    check_or_set_busnum "${selected_device[$DA_BUSNUM]}"
    check_or_set_devnum "${selected_device[$DA_DEVNUM]}"

    if [ -z "$busnum" ] || [ -z "$devnum" ]; then
        die "Could not get bus or device number for '$device'"
    fi
fi


# Create the foul format that virsh requires us to use for this.
device_xml()
{
    cat <<EOL
<hostdev mode='subsystem' type='usb'>
  <source>
    <address type='usb' bus='$(( 10#$1 ))' device='$(( 10#$2 ))'/>
  </source>
</hostdev>
EOL
}


opts=( ${uri:+ -c "$uri"} "$action-device" "$domain" )

# Tell them what we are going to do.
verb 1 "$virsh ${opts[*]} <xml> --live"
verb 2 "$(device_xml "$busnum" "$devnum")"

# Do it (maybe).
[ -n "$dry_run" ] ||
    "$virsh" "${opts[@]}" <(device_xml "$busnum" "$devnum") --live

# Either way, don't fail at doing it.  This could be called by udev when a
# device is hotplugged, and we don't really want it to bitch at people just
# because the domain isn't actually running right now.  It's not necessarily
# an error for running this to be a no-op.
#
# We could try to do some other checks to see if the VM is running first, but
# it's hard to avoid a race where it might start or stop between checking that
# and acting on it, so we just try it and either it will work or it won't.
exit 0

# vi:sts=4:sw=4:et:foldmethod=marker