accounts/usbwallet, vendor: use hidapi instead of libusb directly

parent bdef758d
......@@ -18,18 +18,16 @@
// wallets. The wire protocol spec can be found in the Ledger Blue GitHub repo:
// https://raw.githubusercontent.com/LedgerHQ/blue-app-eth/master/doc/ethapp.asc
// +build !ios
package usbwallet
import (
"fmt"
"errors"
"sync"
"time"
"github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/event"
"github.com/karalabe/gousb/usb"
"github.com/karalabe/hid"
)
// LedgerScheme is the protocol scheme prefixing account and wallet URLs.
......@@ -49,8 +47,6 @@ const ledgerRefreshThrottling = 500 * time.Millisecond
// LedgerHub is a accounts.Backend that can find and handle Ledger hardware wallets.
type LedgerHub struct {
ctx *usb.Context // Context interfacing with a libusb instance
refreshed time.Time // Time instance when the list of wallets was last refreshed
wallets []accounts.Wallet // List of Ledger devices currently tracking
updateFeed event.Feed // Event feed to notify wallet additions/removals
......@@ -63,18 +59,13 @@ type LedgerHub struct {
// NewLedgerHub creates a new hardware wallet manager for Ledger devices.
func NewLedgerHub() (*LedgerHub, error) {
// Initialize the USB library to access Ledgers through
ctx, err := usb.NewContext()
if err != nil {
return nil, err
if !hid.Supported() {
return nil, errors.New("unsupported platform")
}
// Create the USB hub, start and return it
hub := &LedgerHub{
ctx: ctx,
quit: make(chan chan error),
}
hub.refreshWallets()
return hub, nil
}
......@@ -104,31 +95,23 @@ func (hub *LedgerHub) refreshWallets() {
return
}
// Retrieve the current list of Ledger devices
var devIDs []deviceID
var busIDs []uint16
hub.ctx.ListDevices(func(desc *usb.Descriptor) bool {
// Gather Ledger devices, don't connect any just yet
var ledgers []hid.DeviceInfo
for _, info := range hid.Enumerate(0, 0) { // Can't enumerate directly, one valid ID is the 0 wildcard
for _, id := range ledgerDeviceIDs {
if desc.Vendor == id.Vendor && desc.Product == id.Product {
devIDs = append(devIDs, deviceID{Vendor: desc.Vendor, Product: desc.Product})
busIDs = append(busIDs, uint16(desc.Bus)<<8+uint16(desc.Address))
return false
if info.VendorID == id.Vendor && info.ProductID == id.Product {
ledgers = append(ledgers, info)
break
}
}
// Not ledger, ignore and don't connect either
return false
})
}
// Transform the current list of wallets into the new one
hub.lock.Lock()
wallets := make([]accounts.Wallet, 0, len(devIDs))
wallets := make([]accounts.Wallet, 0, len(ledgers))
events := []accounts.WalletEvent{}
for i := 0; i < len(devIDs); i++ {
devID, busID := devIDs[i], busIDs[i]
url := accounts.URL{Scheme: LedgerScheme, Path: fmt.Sprintf("%03d:%03d", busID>>8, busID&0xff)}
for _, ledger := range ledgers {
url := accounts.URL{Scheme: LedgerScheme, Path: ledger.Path}
// Drop wallets in front of the next device or those that failed for some reason
for len(hub.wallets) > 0 && (hub.wallets[0].URL().Cmp(url) < 0 || hub.wallets[0].(*ledgerWallet).failed()) {
......@@ -137,7 +120,7 @@ func (hub *LedgerHub) refreshWallets() {
}
// If there are no more wallets or the device is before the next, wrap new wallet
if len(hub.wallets) == 0 || hub.wallets[0].URL().Cmp(url) > 0 {
wallet := &ledgerWallet{context: hub.ctx, hardwareID: devID, locationID: busID, url: &url}
wallet := &ledgerWallet{url: &url, info: ledger}
events = append(events, accounts.WalletEvent{Wallet: wallet, Arrive: true})
wallets = append(wallets, wallet)
......
......@@ -18,8 +18,6 @@
// wallets. The wire protocol spec can be found in the Ledger Blue GitHub repo:
// https://raw.githubusercontent.com/LedgerHQ/blue-app-eth/master/doc/ethapp.asc
// +build !ios
package usbwallet
import (
......@@ -39,7 +37,7 @@ import (
"github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/logger/glog"
"github.com/ethereum/go-ethereum/rlp"
"github.com/karalabe/gousb/usb"
"github.com/karalabe/hid"
"golang.org/x/net/context"
)
......@@ -74,22 +72,22 @@ const (
ledgerP2ReturnAddressChainCode ledgerParam2 = 0x01 // Require a user confirmation before returning the address
)
// errReplyInvalidHeader is the error message returned by a Ledfer data exchange
// errReplyInvalidHeader is the error message returned by a Ledger data exchange
// if the device replies with a mismatching header. This usually means the device
// is in browser mode.
var errReplyInvalidHeader = errors.New("invalid reply header")
// errInvalidVersionReply is the error message returned by a Ledger version retrieval
// when a response does arrive, but it does not contain the expected data.
var errInvalidVersionReply = errors.New("invalid version reply")
// ledgerWallet represents a live USB Ledger hardware wallet.
type ledgerWallet struct {
context *usb.Context // USB context to interface libusb through
hardwareID deviceID // USB identifiers to identify this device type
locationID uint16 // USB bus and address to identify this device instance
url *accounts.URL // Textual URL uniquely identifying this wallet
url *accounts.URL // Textual URL uniquely identifying this wallet
device *usb.Device // USB device advertising itself as a Ledger wallet
input usb.Endpoint // Input endpoint to send data to this device
output usb.Endpoint // Output endpoint to receive data from this device
failure error // Any failure that would make the device unusable
info hid.DeviceInfo // Known USB device infos about the wallet
device *hid.Device // USB device advertising itself as a Ledger wallet
failure error // Any failure that would make the device unusable
version [3]byte // Current version of the Ledger Ethereum app (zero if app is offline)
browser bool // Flag whether the Ledger is in browser mode (reply channel mismatch)
......@@ -183,59 +181,12 @@ func (w *ledgerWallet) Open(passphrase string) error {
return accounts.ErrWalletAlreadyOpen
}
// Otherwise iterate over all USB devices and find this again (no way to directly do this)
// Iterate over all attached devices and fetch those seemingly Ledger
devices, err := w.context.ListDevices(func(desc *usb.Descriptor) bool {
// Only open this single specific device
return desc.Vendor == w.hardwareID.Vendor && desc.Product == w.hardwareID.Product &&
uint16(desc.Bus)<<8+uint16(desc.Address) == w.locationID
})
device, err := w.info.Open()
if err != nil {
return err
}
if len(devices) == 0 {
return accounts.ErrUnknownWallet
}
// Device opened, attach to the input and output endpoints
device := devices[0]
var invalid string
switch {
case len(device.Descriptor.Configs) == 0:
invalid = "no endpoint config available"
case len(device.Descriptor.Configs[0].Interfaces) == 0:
invalid = "no endpoint interface available"
case len(device.Descriptor.Configs[0].Interfaces[0].Setups) == 0:
invalid = "no endpoint setup available"
case len(device.Descriptor.Configs[0].Interfaces[0].Setups[0].Endpoints) < 2:
invalid = "not enough IO endpoints available"
}
if invalid != "" {
device.Close()
return fmt.Errorf("ledger wallet [%s] invalid: %s", w.url, invalid)
}
// Open the input and output endpoints to the device
input, err := device.OpenEndpoint(
device.Descriptor.Configs[0].Config,
device.Descriptor.Configs[0].Interfaces[0].Number,
device.Descriptor.Configs[0].Interfaces[0].Setups[0].Number,
device.Descriptor.Configs[0].Interfaces[0].Setups[0].Endpoints[1].Address,
)
if err != nil {
device.Close()
return fmt.Errorf("ledger wallet [%s] input open failed: %v", w.url, err)
}
output, err := device.OpenEndpoint(
device.Descriptor.Configs[0].Config,
device.Descriptor.Configs[0].Interfaces[0].Number,
device.Descriptor.Configs[0].Interfaces[0].Setups[0].Number,
device.Descriptor.Configs[0].Interfaces[0].Setups[0].Endpoints[0].Address,
)
if err != nil {
device.Close()
return fmt.Errorf("ledger wallet [%s] output open failed: %v", w.url, err)
}
// Wallet seems to be successfully opened, guess if the Ethereum app is running
w.device, w.input, w.output = device, input, output
w.device = device
w.commsLock = make(chan struct{}, 1)
w.commsLock <- struct{}{} // Enable lock
......@@ -298,13 +249,13 @@ func (w *ledgerWallet) heartbeat() {
w.commsLock <- struct{}{}
w.stateLock.RUnlock()
if err == usb.ERROR_IO || err == usb.ERROR_NO_DEVICE {
if err != nil && err != errInvalidVersionReply {
w.stateLock.Lock() // Lock state to tear the wallet down
w.failure = err
w.close()
w.stateLock.Unlock()
}
// Ignore uninteresting errors
// Ignore non hardware related errors
err = nil
}
// In case of error, wait for termination
......@@ -363,13 +314,13 @@ func (w *ledgerWallet) close() error {
return nil
}
// Close the device, clear everything, then return
err := w.device.Close()
w.device.Close()
w.device = nil
w.device, w.input, w.output = nil, nil, nil
w.browser, w.version = false, [3]byte{}
w.accounts, w.paths = nil, nil
return err
return nil
}
// Accounts implements accounts.Wallet, returning the list of accounts pinned to
......@@ -664,7 +615,7 @@ func (w *ledgerWallet) ledgerVersion() ([3]byte, error) {
return [3]byte{}, err
}
if len(reply) != 4 {
return [3]byte{}, errors.New("reply not of correct size")
return [3]byte{}, errInvalidVersionReply
}
// Cache the version for future reference
var version [3]byte
......@@ -768,10 +719,6 @@ func (w *ledgerWallet) ledgerDerive(derivationPath []uint32) (common.Address, er
// signature R | 32 bytes
// signature S | 32 bytes
func (w *ledgerWallet) ledgerSign(derivationPath []uint32, address common.Address, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) {
// We need to modify the timeouts to account for user feedback
defer func(old time.Duration) { w.device.ReadTimeout = old }(w.device.ReadTimeout)
w.device.ReadTimeout = time.Hour * 24 * 30 // Timeout requires a Ledger power cycle, only if you must
// Flatten the derivation path into the Ledger request
path := make([]byte, 1+4*len(derivationPath))
path[0] = byte(len(derivationPath))
......@@ -903,9 +850,9 @@ func (w *ledgerWallet) ledgerExchange(opcode ledgerOpcode, p1 ledgerParam1, p2 l
}
// Send over to the device
if glog.V(logger.Detail) {
glog.Infof("-> %03d.%03d: %x", w.device.Bus, w.device.Address, chunk)
glog.Infof("-> %s: %x", w.device.Path, chunk)
}
if _, err := w.input.Write(chunk); err != nil {
if _, err := w.device.Write(chunk); err != nil {
return nil, err
}
}
......@@ -914,11 +861,11 @@ func (w *ledgerWallet) ledgerExchange(opcode ledgerOpcode, p1 ledgerParam1, p2 l
chunk = chunk[:64] // Yeah, we surely have enough space
for {
// Read the next chunk from the Ledger wallet
if _, err := io.ReadFull(w.output, chunk); err != nil {
if _, err := io.ReadFull(w.device, chunk); err != nil {
return nil, err
}
if glog.V(logger.Detail) {
glog.Infof("<- %03d.%03d: %x", w.device.Bus, w.device.Address, chunk)
glog.Infof("<- %s: %x", w.device.Path, chunk)
}
// Make sure the transport header matches
if chunk[0] != 0x01 || chunk[1] != 0x01 || chunk[2] != 0x05 {
......
......@@ -14,16 +14,12 @@
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
// +build !ios
// Package usbwallet implements support for USB hardware wallets.
package usbwallet
import "github.com/karalabe/gousb/usb"
// deviceID is a combined vendor/product identifier to uniquely identify a USB
// hardware device.
type deviceID struct {
Vendor usb.ID // The Vendor identifer
Product usb.ID // The Product identifier
Vendor uint16 // The Vendor identifer
Product uint16 // The Product identifier
}
// Copyright 2017 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
// This file contains the implementation for interacting with the Ledger hardware
// wallets. The wire protocol spec can be found in the Ledger Blue GitHub repo:
// https://raw.githubusercontent.com/LedgerHQ/blue-app-eth/master/doc/ethapp.asc
// +build ios
package usbwallet
import (
"errors"
"github.com/ethereum/go-ethereum/accounts"
)
// Here be dragons! There is no USB support on iOS.
// ErrIOSNotSupported is returned for all USB hardware backends on iOS.
var ErrIOSNotSupported = errors.New("no USB support on iOS")
func NewLedgerHub() (accounts.Backend, error) {
return nil, ErrIOSNotSupported
}
language: go
matrix:
include:
- os: linux
dist: trusty
go: 1.7.4
- os: osx
go: 1.7.4
script:
- go test -v -test.run='BCD|Parse' ./...
This diff is collapsed.
Introduction
============
[![Travis Build Status][travisimg]][travis]
[![AppVeyor Build Status][appveyorimg]][appveyor]
[![GoDoc][docimg]][doc]
The gousb package is an attempt at wrapping the `libusb` library into a Go-like binding in a fully self-contained, go-gettable package. Supported platforms include Linux, macOS and Windows as well as the mobile platforms Android and iOS.
This package is a fork of [`github.com/kylelemons/gousb`](https://github.com/kylelemons/gousb), which at the moment seems to be unmaintained. The current fork is different from the upstream package as it contains code to embed `libusb` directly into the Go package (thus becoming fully self-cotnained and go-gettable), as well as it features a few contributions and bugfixes that never really got addressed in the upstream package, but which address important issues nonetheless.
*Note, if @kylelemons decides to pick development of the upstream project up again, consider all commits made by me to this repo as ready contributions. I cannot vouch for other commits as the upstream repo needs a signed CLA for Google.*
[travisimg]: https://travis-ci.org/karalabe/gousb.svg?branch=master
[travis]: https://travis-ci.org/karalabe/gousb
[appveyorimg]: https://ci.appveyor.com/api/projects/status/84k9xse10rl72gn2/branch/master?svg=true
[appveyor]: https://ci.appveyor.com/project/karalabe/gousb
[docimg]: https://godoc.org/github.com/karalabe/gousb?status.svg
[doc]: https://godoc.org/github.com/karalabe/gousb
Installation
============
Example: lsusb
--------------
The gousb project provides a simple but useful example: lsusb. This binary will list the USB devices connected to your system and various interesting tidbits about them, their configurations, endpoints, etc. To install it, run the following command:
go get -v github.com/karalabe/gousb/lsusb
gousb
-----
If you installed the lsusb example, both libraries below are already installed.
Installing the primary gousb package is really easy:
go get -v github.com/karalabe/gousb/usb
There is also a `usbid` package that will not be installed by default by this command, but which provides useful information including the human-readable vendor and product codes for detected hardware. It's not installed by default and not linked into the `usb` package by default because it adds ~400kb to the resulting binary. If you want both, they can be installed thus:
go get -v github.com/karalabe/gousb/usb{,id}
Documentation
=============
The documentation can be viewed via local godoc or via the excellent [godoc.org](http://godoc.org/):
- [usb](http://godoc.org/github.com/karalabe/gousb/usb)
- [usbid](http://godoc.org/pkg/github.com/karalabe/gousb/usbid)
os: Visual Studio 2015
# Clone directly into GOPATH.
clone_folder: C:\gopath\src\github.com\karalabe\gousb
clone_depth: 5
version: "{branch}.{build}"
environment:
global:
GOPATH: C:\gopath
CC: gcc.exe
matrix:
- GOARCH: amd64
MSYS2_ARCH: x86_64
MSYS2_BITS: 64
MSYSTEM: MINGW64
PATH: C:\msys64\mingw64\bin\;%PATH%
- GOARCH: 386
MSYS2_ARCH: i686
MSYS2_BITS: 32
MSYSTEM: MINGW32
PATH: C:\msys64\mingw32\bin\;%PATH%
install:
- rmdir C:\go /s /q
- appveyor DownloadFile https://storage.googleapis.com/golang/go1.7.4.windows-%GOARCH%.zip
- 7z x go1.7.4.windows-%GOARCH%.zip -y -oC:\ > NUL
- go version
- gcc --version
build_script:
- go install ./...
test_script:
- go test -v -test.run="BCD|Parse" ./...
// Copyright 2013 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package usb
/*
#ifndef OS_WINDOWS
#include "os/threads_posix.h"
#endif
#include "libusbi.h"
#include "libusb.h"
*/
import "C"
import (
"fmt"
"reflect"
"unsafe"
)
type EndpointInfo struct {
Address uint8
Attributes uint8
MaxPacketSize uint16
MaxIsoPacket uint32
PollInterval uint8
RefreshRate uint8
SynchAddress uint8
}
func (e EndpointInfo) Number() int {
return int(e.Address) & ENDPOINT_NUM_MASK
}
func (e EndpointInfo) Direction() EndpointDirection {
return EndpointDirection(e.Address) & ENDPOINT_DIR_MASK
}
func (e EndpointInfo) String() string {
return fmt.Sprintf("Endpoint %d %-3s %s - %s %s [%d %d]",
e.Number(), e.Direction(),
TransferType(e.Attributes)&TRANSFER_TYPE_MASK,
IsoSyncType(e.Attributes)&ISO_SYNC_TYPE_MASK,
IsoUsageType(e.Attributes)&ISO_USAGE_TYPE_MASK,
e.MaxPacketSize, e.MaxIsoPacket,
)
}
type InterfaceInfo struct {
Number uint8
Setups []InterfaceSetup
}
func (i InterfaceInfo) String() string {
return fmt.Sprintf("Interface %02x (%d setups)", i.Number, len(i.Setups))
}
type InterfaceSetup struct {
Number uint8
Alternate uint8
IfClass uint8
IfSubClass uint8
IfProtocol uint8
Endpoints []EndpointInfo
}
func (a InterfaceSetup) String() string {
return fmt.Sprintf("Interface %02x Setup %02x", a.Number, a.Alternate)
}
type ConfigInfo struct {
Config uint8
Attributes uint8
MaxPower uint8
Interfaces []InterfaceInfo
}
func (c ConfigInfo) String() string {
return fmt.Sprintf("Config %02x", c.Config)
}
func newConfig(dev *C.libusb_device, cfg *C.struct_libusb_config_descriptor) ConfigInfo {
c := ConfigInfo{
Config: uint8(cfg.bConfigurationValue),
Attributes: uint8(cfg.bmAttributes),
MaxPower: uint8(cfg.MaxPower),
}
var ifaces []C.struct_libusb_interface
*(*reflect.SliceHeader)(unsafe.Pointer(&ifaces)) = reflect.SliceHeader{
Data: uintptr(unsafe.Pointer(cfg._interface)),
Len: int(cfg.bNumInterfaces),
Cap: int(cfg.bNumInterfaces),
}
c.Interfaces = make([]InterfaceInfo, 0, len(ifaces))
for _, iface := range ifaces {
if iface.num_altsetting == 0 {
continue
}
var alts []C.struct_libusb_interface_descriptor
*(*reflect.SliceHeader)(unsafe.Pointer(&alts)) = reflect.SliceHeader{
Data: uintptr(unsafe.Pointer(iface.altsetting)),
Len: int(iface.num_altsetting),
Cap: int(iface.num_altsetting),
}
descs := make([]InterfaceSetup, 0, len(alts))
for _, alt := range alts {
i := InterfaceSetup{
Number: uint8(alt.bInterfaceNumber),
Alternate: uint8(alt.bAlternateSetting),
IfClass: uint8(alt.bInterfaceClass),
IfSubClass: uint8(alt.bInterfaceSubClass),
IfProtocol: uint8(alt.bInterfaceProtocol),
}
var ends []C.struct_libusb_endpoint_descriptor
*(*reflect.SliceHeader)(unsafe.Pointer(&ends)) = reflect.SliceHeader{
Data: uintptr(unsafe.Pointer(alt.endpoint)),
Len: int(alt.bNumEndpoints),
Cap: int(alt.bNumEndpoints),
}
i.Endpoints = make([]EndpointInfo, 0, len(ends))
for _, end := range ends {
i.Endpoints = append(i.Endpoints, EndpointInfo{
Address: uint8(end.bEndpointAddress),
Attributes: uint8(end.bmAttributes),
MaxPacketSize: uint16(end.wMaxPacketSize),
//MaxIsoPacket: uint32(C.libusb_get_max_iso_packet_size(dev, C.uchar(end.bEndpointAddress))),
PollInterval: uint8(end.bInterval),
RefreshRate: uint8(end.bRefresh),
SynchAddress: uint8(end.bSynchAddress),
})
}
descs = append(descs, i)
}
c.Interfaces = append(c.Interfaces, InterfaceInfo{
Number: descs[0].Number,
Setups: descs,
})
}
return c
}
// Copyright 2013 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package usb
// #include "libusb.h"
import "C"
type Class uint8
const (
CLASS_PER_INTERFACE Class = C.LIBUSB_CLASS_PER_INTERFACE
CLASS_AUDIO Class = C.LIBUSB_CLASS_AUDIO
CLASS_COMM Class = C.LIBUSB_CLASS_COMM
CLASS_HID Class = C.LIBUSB_CLASS_HID
CLASS_PRINTER Class = C.LIBUSB_CLASS_PRINTER
CLASS_PTP Class = C.LIBUSB_CLASS_PTP
CLASS_MASS_STORAGE Class = C.LIBUSB_CLASS_MASS_STORAGE
CLASS_HUB Class = C.LIBUSB_CLASS_HUB
CLASS_DATA Class = C.LIBUSB_CLASS_DATA
CLASS_WIRELESS Class = C.LIBUSB_CLASS_WIRELESS
CLASS_APPLICATION Class = C.LIBUSB_CLASS_APPLICATION
CLASS_VENDOR_SPEC Class = C.LIBUSB_CLASS_VENDOR_SPEC
)
var classDescription = map[Class]string{
CLASS_PER_INTERFACE: "per-interface",
CLASS_AUDIO: "audio",
CLASS_COMM: "communications",
CLASS_HID: "human interface device",
CLASS_PRINTER: "printer dclass",
CLASS_PTP: "picture transfer protocol",
CLASS_MASS_STORAGE: "mass storage",
CLASS_HUB: "hub",
CLASS_DATA: "data",
CLASS_WIRELESS: "wireless",
CLASS_APPLICATION: "application",
CLASS_VENDOR_SPEC: "vendor-specific",
}
func (c Class) String() string {
return classDescription[c]
}
type DescriptorType uint8
const (
DT_DEVICE DescriptorType = C.LIBUSB_DT_DEVICE
DT_CONFIG DescriptorType = C.LIBUSB_DT_CONFIG
DT_STRING DescriptorType = C.LIBUSB_DT_STRING
DT_INTERFACE DescriptorType = C.LIBUSB_DT_INTERFACE
DT_ENDPOINT DescriptorType = C.LIBUSB_DT_ENDPOINT
DT_HID DescriptorType = C.LIBUSB_DT_HID
DT_REPORT DescriptorType = C.LIBUSB_DT_REPORT
DT_PHYSICAL DescriptorType = C.LIBUSB_DT_PHYSICAL
DT_HUB DescriptorType = C.LIBUSB_DT_HUB
)
var descriptorTypeDescription = map[DescriptorType]string{
DT_DEVICE: "device",
DT_CONFIG: "configuration",
DT_STRING: "string",
DT_INTERFACE: "interface",
DT_ENDPOINT: "endpoint",
DT_HID: "HID",
DT_REPORT: "HID report",
DT_PHYSICAL: "physical",
DT_HUB: "hub",
}
func (dt DescriptorType) String() string {
return descriptorTypeDescription[dt]
}
type EndpointDirection uint8
const (
ENDPOINT_NUM_MASK = 0x03
ENDPOINT_DIR_IN EndpointDirection = C.LIBUSB_ENDPOINT_IN
ENDPOINT_DIR_OUT EndpointDirection = C.LIBUSB_ENDPOINT_OUT
ENDPOINT_DIR_MASK EndpointDirection = 0x80
)
var endpointDirectionDescription = map[EndpointDirection]string{
ENDPOINT_DIR_IN: "IN",
ENDPOINT_DIR_OUT: "OUT",
}
func (ed EndpointDirection) String() string {
return endpointDirectionDescription[ed]
}
type TransferType uint8
const (
TRANSFER_TYPE_CONTROL TransferType = C.LIBUSB_TRANSFER_TYPE_CONTROL
TRANSFER_TYPE_ISOCHRONOUS TransferType = C.LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
TRANSFER_TYPE_BULK TransferType = C.LIBUSB_TRANSFER_TYPE_BULK
TRANSFER_TYPE_INTERRUPT TransferType = C.LIBUSB_TRANSFER_TYPE_INTERRUPT
TRANSFER_TYPE_MASK TransferType = 0x03
)
var transferTypeDescription = map[TransferType]string{
TRANSFER_TYPE_CONTROL: "control",
TRANSFER_TYPE_ISOCHRONOUS: "isochronous",
TRANSFER_TYPE_BULK: "bulk",
TRANSFER_TYPE_INTERRUPT: "interrupt",
}
func (tt TransferType) String() string {
return transferTypeDescription[tt]
}
type IsoSyncType uint8
const (
ISO_SYNC_TYPE_NONE IsoSyncType = C.LIBUSB_ISO_SYNC_TYPE_NONE << 2
ISO_SYNC_TYPE_ASYNC IsoSyncType = C.LIBUSB_ISO_SYNC_TYPE_ASYNC << 2
ISO_SYNC_TYPE_ADAPTIVE IsoSyncType = C.LIBUSB_ISO_SYNC_TYPE_ADAPTIVE << 2
ISO_SYNC_TYPE_SYNC IsoSyncType = C.LIBUSB_ISO_SYNC_TYPE_SYNC << 2
ISO_SYNC_TYPE_MASK IsoSyncType = 0x0C
)
var isoSyncTypeDescription = map[IsoSyncType]string{
ISO_SYNC_TYPE_NONE: "unsynchronized",
ISO_SYNC_TYPE_ASYNC: "asynchronous",
ISO_SYNC_TYPE_ADAPTIVE: "adaptive",
ISO_SYNC_TYPE_SYNC: "synchronous",
}
func (ist IsoSyncType) String() string {
return isoSyncTypeDescription[ist]
}
type IsoUsageType uint8
const (
ISO_USAGE_TYPE_DATA IsoUsageType = C.LIBUSB_ISO_USAGE_TYPE_DATA << 4
ISO_USAGE_TYPE_FEEDBACK IsoUsageType = C.LIBUSB_ISO_USAGE_TYPE_FEEDBACK << 4
ISO_USAGE_TYPE_IMPLICIT IsoUsageType = C.LIBUSB_ISO_USAGE_TYPE_IMPLICIT << 4
ISO_USAGE_TYPE_MASK IsoUsageType = 0x30
)
var isoUsageTypeDescription = map[IsoUsageType]string{
ISO_USAGE_TYPE_DATA: "data",
ISO_USAGE_TYPE_FEEDBACK: "feedback",
ISO_USAGE_TYPE_IMPLICIT: "implicit data",
}
func (iut IsoUsageType) String() string {
return isoUsageTypeDescription[iut]
}
type RequestType uint8
const (
REQUEST_TYPE_STANDARD = C.LIBUSB_REQUEST_TYPE_STANDARD
REQUEST_TYPE_CLASS = C.LIBUSB_REQUEST_TYPE_CLASS
REQUEST_TYPE_VENDOR = C.LIBUSB_REQUEST_TYPE_VENDOR
REQUEST_TYPE_RESERVED = C.LIBUSB_REQUEST_TYPE_RESERVED
)
var requestTypeDescription = map[RequestType]string{
REQUEST_TYPE_STANDARD: "standard",
REQUEST_TYPE_CLASS: "class",
REQUEST_TYPE_VENDOR: "vendor",
REQUEST_TYPE_RESERVED: "reserved",
}
func (rt RequestType) String() string {
return requestTypeDescription[rt]
}
// Copyright 2013 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package usb
// To enable internal debugging:
// -ldflags "-X github.com/karalabe/gousb/usb.debugInternal true"
import (
"io"
"io/ioutil"
"log" // TODO(kevlar): make a logger
"os"
)
var debug *log.Logger
var debugInternal string
func init() {
var out io.Writer = ioutil.Discard
if debugInternal != "" {
out = os.Stderr
}
debug = log.New(out, "usb", log.LstdFlags|log.Lshortfile)
}
// Copyright 2013 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package usb
/*
#ifndef OS_WINDOWS
#include "os/threads_posix.h"
#endif
#include "libusbi.h"
#include "libusb.h"
*/
import "C"
type Descriptor struct {
// Bus information
Bus uint8 // The bus on which the device was detected
Address uint8 // The address of the device on the bus
// Version information
Spec BCD // USB Specification Release Number
Device BCD // The device version
// Product information
Vendor ID // The Vendor identifer
Product ID // The Product identifier
// Protocol information
Class uint8 // The class of this device
SubClass uint8 // The sub-class (within the class) of this device
Protocol uint8 // The protocol (within the sub-class) of this device
// Configuration information
Configs []ConfigInfo
}
func newDescriptor(dev *C.libusb_device) (*Descriptor, error) {
var desc C.struct_libusb_device_descriptor
if errno := C.libusb_get_device_descriptor(dev, &desc); errno < 0 {
return nil, usbError(errno)
}
// Enumerate configurations
var cfgs []ConfigInfo
for i := 0; i < int(desc.bNumConfigurations); i++ {
var cfg *C.struct_libusb_config_descriptor
if errno := C.libusb_get_config_descriptor(dev, C.uint8_t(i), &cfg); errno < 0 {
return nil, usbError(errno)
}
cfgs = append(cfgs, newConfig(dev, cfg))
C.libusb_free_config_descriptor(cfg)
}
return &Descriptor{
Bus: uint8(C.libusb_get_bus_number(dev)),
Address: uint8(C.libusb_get_device_address(dev)),
Spec: BCD(desc.bcdUSB),
Device: BCD(desc.bcdDevice),
Vendor: ID(desc.idVendor),
Product: ID(desc.idProduct),
Class: uint8(desc.bDeviceClass),
SubClass: uint8(desc.bDeviceSubClass),
Protocol: uint8(desc.bDeviceProtocol),
Configs: cfgs,
}, nil
}
// Copyright 2013 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package usb
/*
#ifndef OS_WINDOWS
#include "os/threads_posix.h"
#endif
#include "libusbi.h"
#include "libusb.h"
*/
import "C"
import (
"fmt"
"reflect"
"sync"
"time"
"unsafe"
)
var DefaultReadTimeout = 1 * time.Second
var DefaultWriteTimeout = 1 * time.Second
var DefaultControlTimeout = 250 * time.Millisecond //5 * time.Second
type Device struct {
handle *C.libusb_device_handle
// Embed the device information for easy access
*Descriptor
// Timeouts
ReadTimeout time.Duration
WriteTimeout time.Duration
ControlTimeout time.Duration
// Claimed interfaces
lock *sync.Mutex
claimed map[uint8]int
// Detached kernel interfaces
detached map[uint8]int
}
func newDevice(handle *C.libusb_device_handle, desc *Descriptor) (*Device, error) {
ifaces := 0
d := &Device{
handle: handle,
Descriptor: desc,
ReadTimeout: DefaultReadTimeout,
WriteTimeout: DefaultWriteTimeout,
ControlTimeout: DefaultControlTimeout,
lock: new(sync.Mutex),
claimed: make(map[uint8]int, ifaces),
detached: make(map[uint8]int),
}
if err := d.detachKernelDriver(); err != nil {
d.Close()
return nil, err
}
return d, nil
}
// detachKernelDriver detaches any active kernel drivers, if supported by the platform.
// If there are any errors, like Context.ListDevices, only the final one will be returned.
func (d *Device) detachKernelDriver() (err error) {
for _, cfg := range d.Configs {
for _, iface := range cfg.Interfaces {
switch activeErr := C.libusb_kernel_driver_active(d.handle, C.int(iface.Number)); activeErr {
case C.LIBUSB_ERROR_NOT_SUPPORTED:
// no need to do any futher checking, no platform support
return
case 0:
continue
case 1:
switch detachErr := C.libusb_detach_kernel_driver(d.handle, C.int(iface.Number)); detachErr {
case C.LIBUSB_ERROR_NOT_SUPPORTED:
// shouldn't ever get here, should be caught by the outer switch
return
case 0:
d.detached[iface.Number]++
case C.LIBUSB_ERROR_NOT_FOUND:
// this status is returned if libusb's driver is already attached to the device
d.detached[iface.Number]++
default:
err = fmt.Errorf("usb: detach kernel driver: %s", usbError(detachErr))
}
default:
err = fmt.Errorf("usb: active kernel driver check: %s", usbError(activeErr))
}
}
}
return
}
// attachKernelDriver re-attaches kernel drivers to any previously detached interfaces, if supported by the platform.
// If there are any errors, like Context.ListDevices, only the final one will be returned.
func (d *Device) attachKernelDriver() (err error) {
for iface := range d.detached {
switch attachErr := C.libusb_attach_kernel_driver(d.handle, C.int(iface)); attachErr {
case C.LIBUSB_ERROR_NOT_SUPPORTED:
// no need to do any futher checking, no platform support
return
case 0:
continue
default:
err = fmt.Errorf("usb: attach kernel driver: %s", usbError(attachErr))
}
}
return
}
func (d *Device) Reset() error {
if errno := C.libusb_reset_device(d.handle); errno != 0 {
return usbError(errno)
}
return nil
}
func (d *Device) Control(rType, request uint8, val, idx uint16, data []byte) (int, error) {
//log.Printf("control xfer: %d:%d/%d:%d %x", idx, rType, request, val, string(data))
dataSlice := (*reflect.SliceHeader)(unsafe.Pointer(&data))
n := C.libusb_control_transfer(
d.handle,
C.uint8_t(rType),
C.uint8_t(request),
C.uint16_t(val),
C.uint16_t(idx),
(*C.uchar)(unsafe.Pointer(dataSlice.Data)),
C.uint16_t(len(data)),
C.uint(d.ControlTimeout/time.Millisecond))
if n < 0 {
return int(n), usbError(n)
}
return int(n), nil
}
// ActiveConfig returns the config id (not the index) of the active configuration.
// This corresponds to the ConfigInfo.Config field.
func (d *Device) ActiveConfig() (uint8, error) {
var cfg C.int
if errno := C.libusb_get_configuration(d.handle, &cfg); errno < 0 {
return 0, usbError(errno)
}
return uint8(cfg), nil
}
// SetConfig attempts to change the active configuration.
// The cfg provided is the config id (not the index) of the configuration to set,
// which corresponds to the ConfigInfo.Config field.
func (d *Device) SetConfig(cfg uint8) error {
if errno := C.libusb_set_configuration(d.handle, C.int(cfg)); errno < 0 {
return usbError(errno)
}
return nil
}
// Close the device.
func (d *Device) Close() error {
if d.handle == nil {
return fmt.Errorf("usb: double close on device")
}
d.lock.Lock()
defer d.lock.Unlock()
for iface := range d.claimed {
C.libusb_release_interface(d.handle, C.int(iface))
}
d.attachKernelDriver()
C.libusb_close(d.handle)
d.handle = nil
return nil
}
func (d *Device) OpenEndpoint(conf, iface, setup, epoint uint8) (Endpoint, error) {
end := &endpoint{
Device: d,
}
var setAlternate bool
for _, c := range d.Configs {
if c.Config != conf {
continue
}
debug.Printf("found conf: %#v\n", c)
for _, i := range c.Interfaces {
if i.Number != iface {
continue
}
debug.Printf("found iface: %#v\n", i)
for i, s := range i.Setups {
if s.Alternate != setup {
continue
}
setAlternate = i != 0
debug.Printf("found setup: %#v [default: %v]\n", s, !setAlternate)
for _, e := range s.Endpoints {
debug.Printf("ep %02x search: %#v\n", epoint, s)
if e.Address != epoint {
continue
}
end.InterfaceSetup = s
end.EndpointInfo = e
switch tt := TransferType(e.Attributes) & TRANSFER_TYPE_MASK; tt {
case TRANSFER_TYPE_BULK:
end.xfer = bulk_xfer
case TRANSFER_TYPE_INTERRUPT:
end.xfer = interrupt_xfer
case TRANSFER_TYPE_ISOCHRONOUS:
end.xfer = isochronous_xfer
default:
return nil, fmt.Errorf("usb: %s transfer is unsupported", tt)
}
goto found
}
return nil, fmt.Errorf("usb: unknown endpoint %02x", epoint)
}
return nil, fmt.Errorf("usb: unknown setup %02x", setup)
}
return nil, fmt.Errorf("usb: unknown interface %02x", iface)
}
return nil, fmt.Errorf("usb: unknown configuration %02x", conf)
found:
// Set the configuration
var activeConf C.int
if errno := C.libusb_get_configuration(d.handle, &activeConf); errno < 0 {
return nil, fmt.Errorf("usb: getcfg: %s", usbError(errno))
}
if int(activeConf) != int(conf) {
if errno := C.libusb_set_configuration(d.handle, C.int(conf)); errno < 0 {
return nil, fmt.Errorf("usb: setcfg: %s", usbError(errno))
}
}
// Claim the interface
if errno := C.libusb_claim_interface(d.handle, C.int(iface)); errno < 0 {
return nil, fmt.Errorf("usb: claim: %s", usbError(errno))
}
// Increment the claim count
d.lock.Lock()
d.claimed[iface]++
d.lock.Unlock() // unlock immediately because the next calls may block
// Choose the alternate
if setAlternate {
if errno := C.libusb_set_interface_alt_setting(d.handle, C.int(iface), C.int(setup)); errno < 0 {
debug.Printf("altsetting error: %s", usbError(errno))
return nil, fmt.Errorf("usb: setalt: %s", usbError(errno))
}
}
return end, nil
}
func (d *Device) GetStringDescriptor(desc_index int) (string, error) {
// allocate 200-byte array limited the length of string descriptor
goBuffer := make([]byte, 200)
// get string descriptor from libusb. if errno < 0 then there are any errors.
// if errno >= 0; it is a length of result string descriptor
errno := C.libusb_get_string_descriptor_ascii(
d.handle,
C.uint8_t(desc_index),
(*C.uchar)(unsafe.Pointer(&goBuffer[0])),
200)
// if any errors occur
if errno < 0 {
return "", fmt.Errorf("usb: getstr: %s", usbError(errno))
}
// convert slice of byte to string with limited length from errno
stringDescriptor := string(goBuffer[:errno])
return stringDescriptor, nil
}
// Copyright 2013 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package usb
// #include "libusb.h"
import "C"
import (
"fmt"
"reflect"
"time"
"unsafe"
)
type Endpoint interface {
Read(b []byte) (int, error)
Write(b []byte) (int, error)
Interface() InterfaceSetup
Info() EndpointInfo
}
type endpoint struct {
*Device
InterfaceSetup
EndpointInfo
xfer func(*endpoint, []byte, time.Duration) (int, error)
}
func (e *endpoint) Read(buf []byte) (int, error) {
if EndpointDirection(e.Address)&ENDPOINT_DIR_MASK != ENDPOINT_DIR_IN {
return 0, fmt.Errorf("usb: read: not an IN endpoint")
}
return e.xfer(e, buf, e.ReadTimeout)
}
func (e *endpoint) Write(buf []byte) (int, error) {
if EndpointDirection(e.Address)&ENDPOINT_DIR_MASK != ENDPOINT_DIR_OUT {
return 0, fmt.Errorf("usb: write: not an OUT endpoint")
}
return e.xfer(e, buf, e.WriteTimeout)
}
func (e *endpoint) Interface() InterfaceSetup { return e.InterfaceSetup }
func (e *endpoint) Info() EndpointInfo { return e.EndpointInfo }
// TODO(kevlar): (*Endpoint).Close
func bulk_xfer(e *endpoint, buf []byte, timeout time.Duration) (int, error) {
if len(buf) == 0 {
return 0, nil
}
data := (*reflect.SliceHeader)(unsafe.Pointer(&buf)).Data
var cnt C.int
if errno := C.libusb_bulk_transfer(
e.handle,
C.uchar(e.Address),
(*C.uchar)(unsafe.Pointer(data)),
C.int(len(buf)),
&cnt,
C.uint(timeout/time.Millisecond)); errno < 0 {
return 0, usbError(errno)
}
return int(cnt), nil
}
func interrupt_xfer(e *endpoint, buf []byte, timeout time.Duration) (int, error) {
if len(buf) == 0 {
return 0, nil
}
data := (*reflect.SliceHeader)(unsafe.Pointer(&buf)).Data
var cnt C.int
if errno := C.libusb_interrupt_transfer(
e.handle,
C.uchar(e.Address),
(*C.uchar)(unsafe.Pointer(data)),
C.int(len(buf)),
&cnt,
C.uint(timeout/time.Millisecond)); errno < 0 {
return 0, usbError(errno)
}
return int(cnt), nil
}
// Copyright 2013 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package usb
import (
"fmt"
)
// #include "libusb.h"
import "C"
type usbError C.int
func (e usbError) Error() string {
return fmt.Sprintf("libusb: %s [code %d]", usbErrorString[e], int(e))
}
const (
SUCCESS usbError = C.LIBUSB_SUCCESS
ERROR_IO usbError = C.LIBUSB_ERROR_IO
ERROR_INVALID_PARAM usbError = C.LIBUSB_ERROR_INVALID_PARAM
ERROR_ACCESS usbError = C.LIBUSB_ERROR_ACCESS
ERROR_NO_DEVICE usbError = C.LIBUSB_ERROR_NO_DEVICE
ERROR_NOT_FOUND usbError = C.LIBUSB_ERROR_NOT_FOUND
ERROR_BUSY usbError = C.LIBUSB_ERROR_BUSY
ERROR_TIMEOUT usbError = C.LIBUSB_ERROR_TIMEOUT
ERROR_OVERFLOW usbError = C.LIBUSB_ERROR_OVERFLOW
ERROR_PIPE usbError = C.LIBUSB_ERROR_PIPE
ERROR_INTERRUPTED usbError = C.LIBUSB_ERROR_INTERRUPTED
ERROR_NO_MEM usbError = C.LIBUSB_ERROR_NO_MEM
ERROR_NOT_SUPPORTED usbError = C.LIBUSB_ERROR_NOT_SUPPORTED
ERROR_OTHER usbError = C.LIBUSB_ERROR_OTHER
)
var usbErrorString = map[usbError]string{
C.LIBUSB_SUCCESS: "success",
C.LIBUSB_ERROR_IO: "i/o error",
C.LIBUSB_ERROR_INVALID_PARAM: "invalid param",
C.LIBUSB_ERROR_ACCESS: "bad access",
C.LIBUSB_ERROR_NO_DEVICE: "no device",
C.LIBUSB_ERROR_NOT_FOUND: "not found",
C.LIBUSB_ERROR_BUSY: "device or resource busy",
C.LIBUSB_ERROR_TIMEOUT: "timeout",
C.LIBUSB_ERROR_OVERFLOW: "overflow",
C.LIBUSB_ERROR_PIPE: "pipe error",
C.LIBUSB_ERROR_INTERRUPTED: "interrupted",
C.LIBUSB_ERROR_NO_MEM: "out of memory",
C.LIBUSB_ERROR_NOT_SUPPORTED: "not supported",
C.LIBUSB_ERROR_OTHER: "unknown error",
}
type TransferStatus uint8
const (
LIBUSB_TRANSFER_COMPLETED TransferStatus = C.LIBUSB_TRANSFER_COMPLETED
LIBUSB_TRANSFER_ERROR TransferStatus = C.LIBUSB_TRANSFER_ERROR
LIBUSB_TRANSFER_TIMED_OUT TransferStatus = C.LIBUSB_TRANSFER_TIMED_OUT
LIBUSB_TRANSFER_CANCELLED TransferStatus = C.LIBUSB_TRANSFER_CANCELLED
LIBUSB_TRANSFER_STALL TransferStatus = C.LIBUSB_TRANSFER_STALL
LIBUSB_TRANSFER_NO_DEVICE TransferStatus = C.LIBUSB_TRANSFER_NO_DEVICE
LIBUSB_TRANSFER_OVERFLOW TransferStatus = C.LIBUSB_TRANSFER_OVERFLOW
)
var transferStatusDescription = map[TransferStatus]string{
LIBUSB_TRANSFER_COMPLETED: "transfer completed without error",
LIBUSB_TRANSFER_ERROR: "transfer failed",
LIBUSB_TRANSFER_TIMED_OUT: "transfer timed out",
LIBUSB_TRANSFER_CANCELLED: "transfer was cancelled",
LIBUSB_TRANSFER_STALL: "halt condition detected (endpoint stalled) or control request not supported",
LIBUSB_TRANSFER_NO_DEVICE: "device was disconnected",
LIBUSB_TRANSFER_OVERFLOW: "device sent more data than requested",
}
func (ts TransferStatus) String() string {
return transferStatusDescription[ts]
}
func (ts TransferStatus) Error() string {
return "libusb: " + ts.String()
}
#include "libusb.h"
#include <stdio.h>
#include <string.h>
void print_xfer(struct libusb_transfer *xfer);
void iso_callback(void *);
void callback(struct libusb_transfer *xfer) {
//printf("Callback!\n");
//print_xfer(xfer);
iso_callback(xfer->user_data);
}
int submit(struct libusb_transfer *xfer) {
xfer->callback = &callback;
xfer->status = -1;
//print_xfer(xfer);
//printf("Transfer submitted\n");
/* fake
strcpy(xfer->buffer, "hello");
xfer->actual_length = 5;
callback(xfer);
return 0; */
return libusb_submit_transfer(xfer);
}
void print_xfer(struct libusb_transfer *xfer) {
int i;
printf("Transfer:\n");
printf(" dev_handle: %p\n", xfer->dev_handle);
printf(" flags: %08x\n", xfer->flags);
printf(" endpoint: %x\n", xfer->endpoint);
printf(" type: %x\n", xfer->type);
printf(" timeout: %dms\n", xfer->timeout);
printf(" status: %x\n", xfer->status);
printf(" length: %d (act: %d)\n", xfer->length, xfer->actual_length);
printf(" callback: %p\n", xfer->callback);
printf(" user_data: %p\n", xfer->user_data);
printf(" buffer: %p\n", xfer->buffer);
printf(" num_iso_pkts: %d\n", xfer->num_iso_packets);
printf(" packets:\n");
for (i = 0; i < xfer->num_iso_packets; i++) {
printf(" [%04d] %d (act: %d) %x\n", i,
xfer->iso_packet_desc[i].length,
xfer->iso_packet_desc[i].actual_length,
xfer->iso_packet_desc[i].status);
}
}
int extract_data(struct libusb_transfer *xfer, void *raw, int max, unsigned char *status) {
int i;
int copied = 0;
unsigned char *in = xfer->buffer;
unsigned char *out = raw;
for (i = 0; i < xfer->num_iso_packets; i++) {
struct libusb_iso_packet_descriptor pkt = xfer->iso_packet_desc[i];
// Copy the data
int len = pkt.actual_length;
if (len > max) {
len = max;
}
memcpy(out, in, len);
copied += len;
// Increment offsets
in += pkt.length;
out += len;
// Extract first error
if (pkt.status == 0 || *status != 0) {
continue;
}
*status = pkt.status;
}
return copied;
}
// Copyright 2013 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package usb
/*
#include "libusb.h"
int submit(struct libusb_transfer *xfer);
void print_xfer(struct libusb_transfer *xfer);
int extract_data(struct libusb_transfer *xfer, void *data, int max, unsigned char *status);
*/
import "C"
import (
"fmt"
"log"
"time"
"unsafe"
)
//export iso_callback
func iso_callback(cptr unsafe.Pointer) {
ch := *(*chan struct{})(cptr)
close(ch)
}
func (end *endpoint) allocTransfer() *Transfer {
// Use libusb_get_max_iso_packet_size ?
const (
iso_packets = 8 // 128 // 242
packet_size = 2 * 960 // 1760
)
xfer := C.libusb_alloc_transfer(C.int(iso_packets))
if xfer == nil {
log.Printf("usb: transfer allocation failed?!")
return nil
}
buf := make([]byte, iso_packets*packet_size)
done := make(chan struct{}, 1)
xfer.dev_handle = end.Device.handle
xfer.endpoint = C.uchar(end.Address)
xfer._type = C.LIBUSB_TRANSFER_TYPE_ISOCHRONOUS
xfer.buffer = (*C.uchar)((unsafe.Pointer)(&buf[0]))
xfer.length = C.int(len(buf))
xfer.num_iso_packets = iso_packets
C.libusb_set_iso_packet_lengths(xfer, packet_size)
/*
pkts := *(*[]C.struct_libusb_packet_descriptor)(unsafe.Pointer(&reflect.SliceHeader{
Data: uintptr(unsafe.Pointer(&xfer.iso_packet_desc)),
Len: iso_packets,
Cap: iso_packets,
}))
*/
t := &Transfer{
xfer: xfer,
done: done,
buf: buf,
}
xfer.user_data = (unsafe.Pointer)(&t.done)
return t
}
type Transfer struct {
xfer *C.struct_libusb_transfer
pkts []*C.struct_libusb_packet_descriptor
done chan struct{}
buf []byte
}
func (t *Transfer) Submit(timeout time.Duration) error {
//log.Printf("iso: submitting %#v", t.xfer)
t.xfer.timeout = C.uint(timeout / time.Millisecond)
if errno := C.submit(t.xfer); errno < 0 {
return usbError(errno)
}
return nil
}
func (t *Transfer) Wait(b []byte) (n int, err error) {
select {
case <-time.After(10 * time.Second):
return 0, fmt.Errorf("wait timed out after 10s")
case <-t.done:
}
// Non-iso transfers:
//n = int(t.xfer.actual_length)
//copy(b, ((*[1 << 16]byte)(unsafe.Pointer(t.xfer.buffer)))[:n])
//C.print_xfer(t.xfer)
/*
buf, offset := ((*[1 << 16]byte)(unsafe.Pointer(t.xfer.buffer))), 0
for i, pkt := range *t.pkts {
log.Printf("Type is %T", t.pkts)
n += copy(b[n:], buf[offset:][:pkt.actual_length])
offset += pkt.Length
if pkt.status != 0 && err == nil {
err = error(TransferStatus(pkt.status))
}
}
*/
var status uint8
n = int(C.extract_data(t.xfer, unsafe.Pointer(&b[0]), C.int(len(b)), (*C.uchar)(unsafe.Pointer(&status))))
if status != 0 {
err = TransferStatus(status)
}
return n, err
}
func (t *Transfer) Close() error {
C.libusb_free_transfer(t.xfer)
return nil
}
func isochronous_xfer(e *endpoint, buf []byte, timeout time.Duration) (int, error) {
t := e.allocTransfer()
defer t.Close()
if err := t.Submit(timeout); err != nil {
log.Printf("iso: xfer failed to submit: %s", err)
return 0, err
}
n, err := t.Wait(buf)
if err != nil {
log.Printf("iso: xfer failed: %s", err)
return 0, err
}
return n, err
}
// Copyright 2013 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package usb
import (
"fmt"
)
type BCD uint16
const (
USB_2_0 BCD = 0x0200
USB_1_1 BCD = 0x0110
USB_1_0 BCD = 0x0100
)
func (d BCD) Int() (i int) {
ten := 1
for o := uint(0); o < 4; o++ {
n := ((0xF << (o * 4)) & d) >> (o * 4)
i += int(n) * ten
ten *= 10
}
return
}
func (d BCD) String() string {
return fmt.Sprintf("%02x.%02x", int(d>>8), int(d&0xFF))
}
type ID uint16
func (id ID) String() string {
return fmt.Sprintf("%04x", int(id))
}
// Copyright 2013 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package usb provides a wrapper around libusb-1.0.
package usb
/*
#cgo CFLAGS: -I../internal/libusb/libusb
#cgo CFLAGS: -DDEFAULT_VISIBILITY=""
#cgo linux CFLAGS: -DOS_LINUX -D_GNU_SOURCE -DPOLL_NFDS_TYPE=int
#cgo darwin CFLAGS: -DOS_DARWIN -DPOLL_NFDS_TYPE=int
#cgo darwin LDFLAGS: -framework CoreFoundation -framework IOKit -lobjc
#cgo openbsd CFLAGS: -DOS_OPENBSD -DPOLL_NFDS_TYPE=int
#cgo windows CFLAGS: -DOS_WINDOWS -DUSE_USBDK -DPOLL_NFDS_TYPE=int
#if defined(OS_LINUX) || defined(OS_DARWIN) || defined(OS_OPENBSD)
#include <sys/poll.h>
#include "os/threads_posix.c"
#include "os/poll_posix.c"
#elif defined(OS_WINDOWS)
#include "os/threads_windows.c"
#include "os/poll_windows.c"
#endif
#ifdef OS_LINUX
#include "os/linux_usbfs.c"
#include "os/linux_netlink.c"
#elif OS_DARWIN
#include "os/darwin_usb.c"
#elif OS_OPENBSD
#include "os/openbsd_usb.c"
#elif OS_WINDOWS
#include "os/windows_nt_common.c"
#include "os/windows_usbdk.c"
#endif
#include "core.c"
#include "descriptor.c"
#include "hotplug.c"
#include "io.c"
#include "strerror.c"
#include "sync.c"
*/
import "C"
import (
"log"
"reflect"
"unsafe"
)
type Context struct {
ctx *C.libusb_context
done chan struct{}
}
func (c *Context) Debug(level int) {
C.libusb_set_debug(c.ctx, C.int(level))
}
func NewContext() (*Context, error) {
c := &Context{
done: make(chan struct{}),
}
if errno := C.libusb_init(&c.ctx); errno != 0 {
return nil, usbError(errno)
}
go func() {
tv := C.struct_timeval{
tv_sec: 0,
tv_usec: 100000,
}
for {
select {
case <-c.done:
return
default:
}
if errno := C.libusb_handle_events_timeout_completed(c.ctx, &tv, nil); errno < 0 {
log.Printf("handle_events: error: %s", usbError(errno))
continue
}
//log.Printf("handle_events returned")
}
}()
return c, nil
}
// ListDevices calls each with each enumerated device.
// If the function returns true, the device is opened and a Device is returned if the operation succeeds.
// Every Device returned (whether an error is also returned or not) must be closed.
// If there are any errors enumerating the devices,
// the final one is returned along with any successfully opened devices.
func (c *Context) ListDevices(each func(desc *Descriptor) bool) ([]*Device, error) {
var list **C.libusb_device
cnt := C.libusb_get_device_list(c.ctx, &list)
if cnt < 0 {
return nil, usbError(cnt)
}
defer C.libusb_free_device_list(list, 1)
var slice []*C.libusb_device
*(*reflect.SliceHeader)(unsafe.Pointer(&slice)) = reflect.SliceHeader{
Data: uintptr(unsafe.Pointer(list)),
Len: int(cnt),
Cap: int(cnt),
}
var reterr error
var ret []*Device
for _, dev := range slice {
desc, err := newDescriptor(dev)
if err != nil {
reterr = err
continue
}
if each(desc) {
var handle *C.libusb_device_handle
if errno := C.libusb_open(dev, &handle); errno != 0 {
reterr = usbError(errno)
continue
}
if dev, err := newDevice(handle, desc); err != nil {
reterr = err
} else {
ret = append(ret, dev)
}
}
}
return ret, reterr
}
// OpenDeviceWithVidPid opens Device from specific VendorId and ProductId.
// If there are any errors, it'll returns at second value.
func (c *Context) OpenDeviceWithVidPid(vid, pid int) (*Device, error) {
handle := C.libusb_open_device_with_vid_pid(c.ctx, (C.uint16_t)(vid), (C.uint16_t)(pid))
if handle == nil {
return nil, ERROR_NOT_FOUND
}
dev := C.libusb_get_device(handle)
if dev == nil {
return nil, ERROR_NO_DEVICE
}
desc, err := newDescriptor(dev)
// return an error from nil-handle and nil-device
if err != nil {
return nil, err
}
return newDevice(handle, desc)
}
func (c *Context) Close() error {
close(c.done)
if c.ctx != nil {
C.libusb_exit(c.ctx)
}
c.ctx = nil
return nil
}
The components of `hid` are licensed as such:
* `hidapi` is released under the [3-clause BSD](https://github.com/signal11/hidapi/blob/master/LICENSE-bsd.txt) license.
* `libusb` is released under the [GNU GPL 2.1](https://github.com/libusb/libusb/blob/master/COPYING)license.
* `go.hid` is released under the [2-clause BSD](https://github.com/GeertJohan/go.hid/blob/master/LICENSE) license.
* `gowchar` is released under the [3-clause BSD](https://github.com/orofarne/gowchar/blob/master/LICENSE) license.
Given the above, `hid` is licensed under GNU GPL 2.1 or later on Linux and 3-clause BSD on other platforms.
[![GoDoc][docimg]][docurl]
[docimg]: https://godoc.org/github.com/karalabe/hid?status.svg
[docurl]: https://godoc.org/github.com/karalabe/hid
# Gopher Interface Devices (USB HID)
The `hid` package is a cross platform library for accessing and communicating with USB Human Interface
Devices (HID). It is an alternative package to [`gousb`](https://github.com/karalabe/gousb) for use
cases where devices support this ligher mode of operation (e.g. input devices, hardware crypto wallets).
The package wraps [`hidapi`](https://github.com/signal11/hidapi) for accessing OS specific USB HID APIs
directly instead of using low level USB constructs, which might have permission issues on some platforms.
On Linux the package also wraps [`libusb`](https://github.com/libusb/libusb). Both of these dependencies
are vendored directly into the repository and wrapped using CGO, making the `hid` package self-contained
and go-gettable.
Supported platforms at the moment are Linux, macOS and Windows (exclude constraints are also specified
for Android and iOS to allow smoother vendoring into cross platform projects).
## Acknowledgements
Although the `hid` package is an implementation from scratch, it was heavily inspired by the existing
[`go.hid`](https://github.com/GeertJohan/go.hid) library, which seems abandoned since 2015; is incompatible
with Go 1.6+; and has various external dependencies. Given its inspirational roots, I thought it important
to give credit to the author of said package too.
Wide character support in the `hid` package is done via the [`gowchar`](https://github.com/orofarne/gowchar)
library, unmaintained since 2013; non buildable with a modern Go release and failing `go vet` checks. As
such, `gowchar` was also vendored in inline (copyright headers and origins preserved).
## License
The components of `hid` are licensed as such:
* `hidapi` is released under the [3-clause BSD](https://github.com/signal11/hidapi/blob/master/LICENSE-bsd.txt) license.
* `libusb` is released under the [GNU GPL 2.1](https://github.com/libusb/libusb/blob/master/COPYING)license.
* `go.hid` is released under the [2-clause BSD](https://github.com/GeertJohan/go.hid/blob/master/LICENSE) license.
* `gowchar` is released under the [3-clause BSD](https://github.com/orofarne/gowchar/blob/master/LICENSE) license.
Given the above, `hid` is licensed under GNU GPL 2.1 or later on Linux and 3-clause BSD on other platforms.
// hid - Gopher Interface Devices (USB HID)
// Copyright (c) 2017 Péter Szilágyi. All rights reserved.
//
// This file is released under the 3-clause BSD license. Note however that Linux
// support depends on libusb, released under GNU GPL 2.1 or later.
// Package hid provides an interface for USB HID devices.
package hid
import "errors"
// ErrDeviceClosed is returned for operations where the device closed before or
// during the execution.
var ErrDeviceClosed = errors.New("hid: device closed")
// ErrUnsupportedPlatform is returned for all operations where the underlying
// operating system is not supported by the library.
var ErrUnsupportedPlatform = errors.New("hid: unsupported platform")
// DeviceInfo is a hidapi info structure.
type DeviceInfo struct {
Path string // Platform-specific device path
VendorID uint16 // Device Vendor ID
ProductID uint16 // Device Product ID
Release uint16 // Device Release Number in binary-coded decimal, also known as Device Version Number
Serial string // Serial Number
Manufacturer string // Manufacturer String
Product string // Product string
UsagePage uint16 // Usage Page for this Device/Interface (Windows/Mac only)
Usage uint16 // Usage for this Device/Interface (Windows/Mac only)
// The USB interface which this logical device
// represents. Valid on both Linux implementations
// in all cases, and valid on the Windows implementation
// only if the device contains more than one interface.
Interface int
}
// hid - Gopher Interface Devices (USB HID)
// Copyright (c) 2017 Péter Szilágyi. All rights reserved.
//
// This file is released under the 3-clause BSD license. Note however that Linux
// support depends on libusb, released under GNU GPL 2.1 or later.
// +build !linux
// +build !darwin ios
// +build !windows
package hid
// Supported returns whether this platform is supported by the HID library or not.
// The goal of this method is to allow programatically handling platforms that do
// not support USB HID and not having to fall back to build constraints.
func Supported() bool {
return false
}
// Enumerate returns a list of all the HID devices attached to the system which
// match the vendor and product id. On platforms that this file implements the
// function is a noop and returns an empty list always.
func Enumerate(vendorID uint16, productID uint16) []DeviceInfo {
return nil
}
// Device is a live HID USB connected device handle. On platforms that this file
// implements the type lacks the actual HID device and all methods are noop.
type Device struct {
DeviceInfo // Embed the infos for easier access
}
// Open connects to an HID device by its path name. On platforms that this file
// implements the method just returns an error.
func (info DeviceInfo) Open() (*Device, error) {
return nil, ErrUnsupportedPlatform
}
// Close releases the HID USB device handle. On platforms that this file implements
// the method is just a noop.
func (dev *Device) Close() {}
// Write sends an output report to a HID device. On platforms that this file
// implements the method just returns an error.
func (dev *Device) Write(b []byte) (int, error) {
return 0, ErrUnsupportedPlatform
}
// Read retrieves an input report from a HID device. On platforms that this file
// implements the method just returns an error.
func (dev *Device) Read(b []byte) (int, error) {
return 0, ErrUnsupportedPlatform
}
// hid - Gopher Interface Devices (USB HID)
// Copyright (c) 2017 Péter Szilágyi. All rights reserved.
//
// This file is released under the 3-clause BSD license. Note however that Linux
// support depends on libusb, released under GNU GPL 2.1 or later.
// +build !ios
// +build linux darwin windows
package hid
/*
#cgo CFLAGS: -I./hidapi/hidapi
#cgo linux CFLAGS: -I./libusb/libusb -DDEFAULT_VISIBILITY="" -DOS_LINUX -D_GNU_SOURCE -DPOLL_NFDS_TYPE=int
#cgo darwin CFLAGS: -DOS_DARWIN
#cgo darwin LDFLAGS: -framework CoreFoundation -framework IOKit
#cgo windows CFLAGS: -DOS_WINDOWS
#cgo windows LDFLAGS: -lsetupapi
#ifdef OS_LINUX
#include <sys/poll.h>
#include "os/threads_posix.c"
#include "os/poll_posix.c"
#include "os/linux_usbfs.c"
#include "os/linux_netlink.c"
#include "core.c"
#include "descriptor.c"
#include "hotplug.c"
#include "io.c"
#include "strerror.c"
#include "sync.c"
#include "hidapi/libusb/hid.c"
#elif OS_DARWIN
#include "hidapi/mac/hid.c"
#elif OS_WINDOWS
#include "hidapi/windows/hid.c"
#endif
*/
import "C"
import (
"errors"
"runtime"
"sync"
"unsafe"
)
func init() {
// Initialize the HIDAPI library
C.hid_init()
}
// Supported returns whether this platform is supported by the HID library or not.
// The goal of this method is to allow programatically handling platforms that do
// not support USB HID and not having to fall back to build constraints.
func Supported() bool {
return true
}
// Enumerate returns a list of all the HID devices attached to the system which
// match the vendor and product id:
// - If the vendor id is set to 0 then any vendor matches.
// - If the product id is set to 0 then any product matches.
// - If the vendor and product id are both 0, all HID devices are returned.
func Enumerate(vendorID uint16, productID uint16) []DeviceInfo {
// Gather all device infos and ensure they are freed before returning
head := C.hid_enumerate(C.ushort(vendorID), C.ushort(productID))
if head == nil {
return nil
}
defer C.hid_free_enumeration(head)
// Iterate the list and retrieve the device details
var infos []DeviceInfo
for ; head != nil; head = head.next {
info := DeviceInfo{
Path: C.GoString(head.path),
VendorID: uint16(head.vendor_id),
ProductID: uint16(head.product_id),
Release: uint16(head.release_number),
UsagePage: uint16(head.usage_page),
Usage: uint16(head.usage),
Interface: int(head.interface_number),
}
if head.serial_number != nil {
info.Serial, _ = wcharTToString(head.serial_number)
}
if head.product_string != nil {
info.Product, _ = wcharTToString(head.product_string)
}
if head.manufacturer_string != nil {
info.Manufacturer, _ = wcharTToString(head.manufacturer_string)
}
infos = append(infos, info)
}
return infos
}
// Open connects to an HID device by its path name.
func (info DeviceInfo) Open() (*Device, error) {
path := C.CString(info.Path)
defer C.free(unsafe.Pointer(path))
device := C.hid_open_path(path)
if device == nil {
return nil, errors.New("hidapi: failed to open device")
}
return &Device{
DeviceInfo: info,
device: device,
}, nil
}
// Device is a live HID USB connected device handle.
type Device struct {
DeviceInfo // Embed the infos for easier access
device *C.hid_device // Low level HID device to communicate through
lock sync.Mutex
}
// Close releases the HID USB device handle.
func (dev *Device) Close() {
dev.lock.Lock()
defer dev.lock.Unlock()
if dev.device != nil {
C.hid_close(dev.device)
dev.device = nil
}
}
// Write sends an output report to a HID device.
//
// Write will send the data on the first OUT endpoint, if one exists. If it does
// not, it will send the data through the Control Endpoint (Endpoint 0).
func (dev *Device) Write(b []byte) (int, error) {
// Abort if nothing to write
if len(b) == 0 {
return 0, nil
}
// Abort if device closed in between
dev.lock.Lock()
device := dev.device
dev.lock.Unlock()
if device == nil {
return 0, ErrDeviceClosed
}
// Prepend a HID report ID on Windows, other OSes don't need it
var report []byte
if runtime.GOOS == "windows" {
report = append([]byte{0x00}, b...)
} else {
report = b
}
// Execute the write operation
written := int(C.hid_write(device, (*C.uchar)(&report[0]), C.size_t(len(report))))
if written == -1 {
// If the write failed, verify if closed or other error
dev.lock.Lock()
device = dev.device
dev.lock.Unlock()
if device == nil {
return 0, ErrDeviceClosed
}
// Device not closed, some other error occurred
message := C.hid_error(device)
if message == nil {
return 0, errors.New("hidapi: unknown failure")
}
failure, _ := wcharTToString(message)
return 0, errors.New("hidapi: " + failure)
}
return written, nil
}
// Read retrieves an input report from a HID device.
func (dev *Device) Read(b []byte) (int, error) {
// Aborth if nothing to read
if len(b) == 0 {
return 0, nil
}
// Abort if device closed in between
dev.lock.Lock()
device := dev.device
dev.lock.Unlock()
if device == nil {
return 0, ErrDeviceClosed
}
// Execute the read operation
read := int(C.hid_read(device, (*C.uchar)(&b[0]), C.size_t(len(b))))
if read == -1 {
// If the read failed, verify if closed or other error
dev.lock.Lock()
device = dev.device
dev.lock.Unlock()
if device == nil {
return 0, ErrDeviceClosed
}
// Device not closed, some other error occurred
message := C.hid_error(device)
if message == nil {
return 0, errors.New("hidapi: unknown failure")
}
failure, _ := wcharTToString(message)
return 0, errors.New("hidapi: " + failure)
}
return read, nil
}
HIDAPI Authors:
Alan Ott <alan@signal11.us>:
Original Author and Maintainer
Linux, Windows, and Mac implementations
Ludovic Rousseau <rousseau@debian.org>:
Formatting for Doxygen documentation
Bug fixes
Correctness fixes
For a comprehensive list of contributions, see the commit list at github:
http://github.com/signal11/hidapi/commits/master
Copyright (c) 2010, Alan Ott, Signal 11 Software
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Signal 11 Software nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
This diff is collapsed.
HIDAPI - Multi-Platform library for
communication with HID devices.
Copyright 2009, Alan Ott, Signal 11 Software.
All Rights Reserved.
This software may be used by anyone for any reason so
long as the copyright notice in the source files
remains intact.
HIDAPI can be used under one of three licenses.
1. The GNU General Public License, version 3.0, in LICENSE-gpl3.txt
2. A BSD-Style License, in LICENSE-bsd.txt.
3. The more liberal original HIDAPI license. LICENSE-orig.txt
The license chosen is at the discretion of the user of HIDAPI. For example:
1. An author of GPL software would likely use HIDAPI under the terms of the
GPL.
2. An author of commercial closed-source software would likely use HIDAPI
under the terms of the BSD-style license or the original HIDAPI license.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
......@@ -113,10 +113,11 @@
"revisionTime": "2016-06-03T03:41:37Z"
},
{
"checksumSHA1": "SdiKy93Lsh3ly7I2E7vhlyp2Xq8=",
"path": "github.com/karalabe/gousb/usb",
"revision": "ffa821b2e25aa1828ffca731f759a1ebfa410d73",
"revisionTime": "2017-01-24T16:09:49Z"
"checksumSHA1": "HKy8oSpuboe02Uqq+43zbIzD/AY=",
"path": "github.com/karalabe/hid",
"revision": "40280bf4f6fc762010efeb066cbff7490d467f03",
"revisionTime": "2017-02-17T09:52:56Z",
"tree": true
},
{
"checksumSHA1": "7hln62oZPZmyqEmgXaybf9WxQ7A=",
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment