diff --git a/Gopkg.lock b/Gopkg.lock index 5e05a0df..aaf6d706 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -111,15 +111,12 @@ "accounts/abi", "accounts/abi/bind", "accounts/keystore", - "accounts/usbwallet", - "accounts/usbwallet/internal/trezor", "common", "common/bitutil", "common/hexutil", "common/math", "common/mclock", "consensus", - "consensus/clique", "consensus/ethash", "consensus/misc", "core", @@ -132,32 +129,15 @@ "crypto/bn256", "crypto/bn256/cloudflare", "crypto/bn256/google", - "crypto/ecies", "crypto/randentropy", "crypto/secp256k1", "crypto/sha3", - "eth", - "eth/downloader", - "eth/fetcher", "eth/filters", - "eth/gasprice", - "eth/tracers", - "eth/tracers/internal/tracers", "ethclient", "ethdb", "event", - "internal/debug", - "internal/ethapi", "log", - "log/term", "metrics", - "metrics/exp", - "miner", - "node", - "p2p", - "p2p/discover", - "p2p/discv5", - "p2p/nat", "p2p/netutil", "params", "rlp", @@ -167,15 +147,6 @@ revision = "eeed4ff1db0b23d926a39e50462805aca03ef930" source = "github.com/getamis/go-ethereum" -[[projects]] - branch = "master" - name = "github.com/fjl/memsize" - packages = [ - ".", - "memsizeui" - ] - revision = "f6d5545993d68e9e42df43eb57958f898dea3623" - [[projects]] name = "github.com/fsnotify/fsnotify" packages = ["."] @@ -189,7 +160,6 @@ version = "v1.2.0" [[projects]] - branch = "develop" name = "github.com/getamis/sirius" packages = [ "crypto/rand", @@ -199,7 +169,8 @@ "log", "test" ] - revision = "d65c366c4b8fffe22d9314ac931381644151f951" + revision = "10abc6819b876cb480e394cb187eef5c648daf2f" + version = "v1.0.0" [[projects]] name = "github.com/go-sql-driver/mysql" @@ -219,15 +190,6 @@ revision = "1adfc126b41513cc696b209667c8656ea7aac67c" version = "v1.0.0" -[[projects]] - branch = "master" - name = "github.com/golang/protobuf" - packages = [ - "proto", - "protoc-gen-go/descriptor" - ] - revision = "3a3da3a4e26776cc22a79ef46d5d58477532dede" - [[projects]] branch = "master" name = "github.com/golang/snappy" @@ -260,32 +222,12 @@ ] revision = "ef8a98b0bbce4a65b5aa4c368430a80ddc533168" -[[projects]] - branch = "master" - name = "github.com/huin/goupnp" - packages = [ - ".", - "dcps/internetgateway1", - "dcps/internetgateway2", - "httpu", - "scpd", - "soap", - "ssdp" - ] - revision = "1395d1447324cbea88d249fbfcfd70ea878fdfca" - [[projects]] name = "github.com/inconshreveable/mousetrap" packages = ["."] revision = "76626ae9c91c4f2a10f34cad8ce83ea42c93bb75" version = "v1.0" -[[projects]] - name = "github.com/jackpal/go-nat-pmp" - packages = ["."] - revision = "c9cfead9f2a36ddf3daa40ba269aa7f4bbba6b62" - version = "v1.0.1" - [[projects]] name = "github.com/jinzhu/gorm" packages = ["."] @@ -298,30 +240,12 @@ packages = ["."] revision = "04140366298a54a039076d798123ffa108fff46c" -[[projects]] - branch = "master" - name = "github.com/karalabe/hid" - packages = ["."] - revision = "2b4488a37358b7283de4f9622553e85ebbe73125" - [[projects]] name = "github.com/magiconair/properties" packages = ["."] revision = "c2353362d570a7bfa228149c62842019201cfb71" version = "v1.8.0" -[[projects]] - name = "github.com/mattn/go-colorable" - packages = ["."] - revision = "167de6bfdfba052fa6b2d3664c8f5272e23c9072" - version = "v0.0.9" - -[[projects]] - name = "github.com/mattn/go-isatty" - packages = ["."] - revision = "0360b2af4f38e8d38c7fce2a9f4e702702d73a39" - version = "v0.0.3" - [[projects]] branch = "master" name = "github.com/mitchellh/mapstructure" @@ -420,12 +344,6 @@ revision = "792786c7400a136282c1664665ae0a8db921c6c2" version = "v1.0.0" -[[projects]] - name = "github.com/prometheus/prometheus" - packages = ["util/flock"] - revision = "85f23d82a045d103ea7f3c89a91fba4a93e6367a" - version = "v2.1.0" - [[projects]] branch = "master" name = "github.com/rjeczalik/notify" @@ -623,12 +541,6 @@ packages = ["."] revision = "c1b8fa8bdccecb0b8db834ee0b92fdbcfa606dd6" -[[projects]] - branch = "v3" - name = "gopkg.in/olebedev/go-duktape.v3" - packages = ["."] - revision = "abf0ba0be5d5d36b1f9266463cc320b9a5ab224e" - [[projects]] name = "gopkg.in/redis.v5" packages = [ @@ -642,12 +554,6 @@ revision = "a16aeec10ff407b1e7be6dd35797ccf5426ef0f0" version = "v5.2.9" -[[projects]] - name = "gopkg.in/urfave/cli.v1" - packages = ["."] - revision = "cfb38830724cc34fedffe9a2a29fb54fa9169cd1" - version = "v1.20.0" - [[projects]] name = "gopkg.in/yaml.v2" packages = ["."] @@ -657,6 +563,6 @@ [solve-meta] analyzer-name = "dep" analyzer-version = 1 - inputs-digest = "d33a516535816f7270374d8edfc5ea37c830dd9dded79d1fabd06becfec1691d" + inputs-digest = "987111ce22c18455538d8b860309b0a6015c7bcbb913c7ffd9e2a4514df5bd11" solver-name = "gps-cdcl" solver-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml index e76f9365..78db602c 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -30,8 +30,8 @@ branch = "feature/indexer_diff_1.8.10" [[constraint]] - branch = "develop" name = "github.com/getamis/sirius" + version = "=1.0.0" [[constraint]] name = "github.com/jinzhu/gorm" @@ -49,6 +49,10 @@ name = "github.com/stretchr/testify" version = "1.2.1" +[[constraint]] + name = "github.com/golang/protobuf" + version = "=1.1.0" + [[override]] branch = "master" name = "github.com/docker/libnetwork" diff --git a/README.md b/README.md index 48703f3c..7a391114 100644 --- a/README.md +++ b/README.md @@ -57,8 +57,8 @@ first time to run indexer you need to create the database schema ```shell $ mkdir -p ~/indexer-data/mysql ~/indexer-data/geth # Create database sechema -MYSQL_DATA_PATH="$HOME/indexer-data/mysql" docker-compose up ws-database ws-migration -# press Ctrl + C when see `eth-indexer_ws-migration_1 exited with code 0` +MYSQL_DATA_PATH="$HOME/indexer-data/mysql" docker-compose up idx-database idx-migration +# press Ctrl + C when see `eth-indexer_idx-migration_1 exited with code 0` ``` then use `docker-compose up` with environment variables to start indexer: diff --git a/client/balancer.go b/client/balancer.go index 3d60b77a..35d34e81 100644 --- a/client/balancer.go +++ b/client/balancer.go @@ -35,17 +35,17 @@ const ( // Balancer is a wrapper interface to batch get balances type Balancer interface { // BalanceOf returns the balances of ETH and multiple erc20 tokens for multiple accounts - BalanceOf(context.Context, *big.Int, map[ethCommon.Address]map[ethCommon.Address]struct{}) (map[ethCommon.Address]map[ethCommon.Address]*big.Int, error) + BalanceOf(context.Context, *big.Int, map[ethCommon.Address]map[ethCommon.Address]*big.Int) error } // BalanceOf returns the balances of ETH and multiple erc20 tokens for multiple accounts -func (c *client) BalanceOf(ctx context.Context, blockNumber *big.Int, addrs map[ethCommon.Address]map[ethCommon.Address]struct{}) (balances map[ethCommon.Address]map[ethCommon.Address]*big.Int, err error) { +func (c *client) BalanceOf(ctx context.Context, blockNumber *big.Int, balances map[ethCommon.Address]map[ethCommon.Address]*big.Int) (err error) { logger := log.New("number", blockNumber.Int64()) var msgs []*ethereum.CallMsg var owners []ethCommon.Address // Only handle non-ETH balances - for erc20Addr, list := range addrs { + for erc20Addr, list := range balances { if erc20Addr == model.ETHAddress { continue } @@ -56,8 +56,6 @@ func (c *client) BalanceOf(ctx context.Context, blockNumber *big.Int, addrs map[ } } - balances = make(map[ethCommon.Address]map[ethCommon.Address]*big.Int) - // Get batch results lens := len(msgs) for begin := 0; begin < lens; begin += chunkSize { @@ -70,46 +68,32 @@ func (c *client) BalanceOf(ctx context.Context, blockNumber *big.Int, addrs map[ logger.Info("processing ERC20 balance chunk", "total", lens, "begin", begin, "end", end) outputs, err := c.BatchCallContract(ctx, chunk, blockNumber) if err != nil { - return nil, err + return err } for i := 0; i < len(chunk); i++ { balance, err := contracts.DecodeBalanceOf(outputs[i]) if err != nil { - return nil, err + return err } contractAddr := *chunk[i].To - if balances[contractAddr] == nil { - balances[contractAddr] = make(map[ethCommon.Address]*big.Int) - } balances[contractAddr][owners[begin+i]] = balance } } // Handle ETH balances - if _, ok := addrs[model.ETHAddress]; ok { - balances[model.ETHAddress], err = c.ethBalanceOf(ctx, blockNumber, addrs[model.ETHAddress]) - if err != nil { - return nil, err - } + if _, ok := balances[model.ETHAddress]; !ok { + return } - return -} -// ethBalanceOf returns the ether balances -func (c *client) ethBalanceOf(ctx context.Context, blockNumber *big.Int, addrs map[ethCommon.Address]struct{}) (etherBalances map[ethCommon.Address]*big.Int, err error) { - logger := log.New("number", blockNumber.Int64()) - lens := len(addrs) var addrList []ethCommon.Address - for addr := range addrs { + for addr := range balances[model.ETHAddress] { addrList = append(addrList, addr) } - // Construct ether balances - etherBalances = make(map[ethCommon.Address]*big.Int, lens) - // Get ethers + lens = len(addrList) for begin := 0; begin < lens; begin += chunkSize { end := begin + chunkSize if end > lens { @@ -120,11 +104,11 @@ func (c *client) ethBalanceOf(ctx context.Context, blockNumber *big.Int, addrs m logger.Info("processing ETH balance chunk", "total", lens, "begin", begin, "end", end) ethers, err := c.BatchBalanceAt(ctx, chunk, blockNumber) if err != nil { - return nil, err + return err } for i, e := range ethers { - etherBalances[addrList[begin+i]] = e + balances[model.ETHAddress][addrList[begin+i]] = e } } return diff --git a/client/client.go b/client/client.go index 4966ac51..065436f9 100644 --- a/client/client.go +++ b/client/client.go @@ -169,27 +169,32 @@ func (c *client) GetERC20(ctx context.Context, addr common.Address) (*model.ERC2 } caller, err := contracts.NewERC20TokenCaller(addr, c) if err != nil { - logger.Warn("Failed to initiate contract caller", "err", err) + logger.Error("Failed to initiate contract caller", "err", err) + return nil, err + } + + // Set total supply + supply, err := caller.TotalSupply(&bind.CallOpts{}) + if err != nil { + logger.Error("Failed to get total supply", "err", err) + return nil, err + } + erc20.TotalSupply = supply.String() + + // Get optional methods + // Set decimals + decimal, err := caller.Decimals(&bind.CallOpts{}) + if err != nil { + logger.Warn("Failed to get decimals", "err", err) } else { - // Set decimals - decimal, err := caller.Decimals(&bind.CallOpts{}) - if err != nil { - logger.Warn("Failed to get decimals", "err", err) - } erc20.Decimals = int(decimal) + } - // Set total supply - supply, err := caller.TotalSupply(&bind.CallOpts{}) - if err != nil { - logger.Warn("Failed to get total supply", "err", err) - } - erc20.TotalSupply = supply.String() - - // Set name - name, err := caller.Name(&bind.CallOpts{}) - if err != nil { - logger.Warn("Failed to get name", "err", err) - } + // Set name + name, err := caller.Name(&bind.CallOpts{}) + if err != nil { + logger.Warn("Failed to get name", "err", err) + } else { erc20.Name = name } return erc20, nil diff --git a/client/mocks/Balancer.go b/client/mocks/Balancer.go index 3565fa69..de755f8d 100644 --- a/client/mocks/Balancer.go +++ b/client/mocks/Balancer.go @@ -13,24 +13,15 @@ type Balancer struct { } // BalanceOf provides a mock function with given fields: _a0, _a1, _a2 -func (_m *Balancer) BalanceOf(_a0 context.Context, _a1 *big.Int, _a2 map[common.Address]map[common.Address]struct{}) (map[common.Address]map[common.Address]*big.Int, error) { +func (_m *Balancer) BalanceOf(_a0 context.Context, _a1 *big.Int, _a2 map[common.Address]map[common.Address]*big.Int) error { ret := _m.Called(_a0, _a1, _a2) - var r0 map[common.Address]map[common.Address]*big.Int - if rf, ok := ret.Get(0).(func(context.Context, *big.Int, map[common.Address]map[common.Address]struct{}) map[common.Address]map[common.Address]*big.Int); ok { + var r0 error + if rf, ok := ret.Get(0).(func(context.Context, *big.Int, map[common.Address]map[common.Address]*big.Int) error); ok { r0 = rf(_a0, _a1, _a2) } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(map[common.Address]map[common.Address]*big.Int) - } + r0 = ret.Error(0) } - var r1 error - if rf, ok := ret.Get(1).(func(context.Context, *big.Int, map[common.Address]map[common.Address]struct{}) error); ok { - r1 = rf(_a0, _a1, _a2) - } else { - r1 = ret.Error(1) - } - - return r0, r1 + return r0 } diff --git a/client/mocks/EthClient.go b/client/mocks/EthClient.go index 113c80a4..7b158b71 100644 --- a/client/mocks/EthClient.go +++ b/client/mocks/EthClient.go @@ -39,26 +39,17 @@ func (_m *EthClient) BalanceAt(ctx context.Context, account common.Address, bloc } // BalanceOf provides a mock function with given fields: _a0, _a1, _a2 -func (_m *EthClient) BalanceOf(_a0 context.Context, _a1 *big.Int, _a2 map[common.Address]map[common.Address]struct{}) (map[common.Address]map[common.Address]*big.Int, error) { +func (_m *EthClient) BalanceOf(_a0 context.Context, _a1 *big.Int, _a2 map[common.Address]map[common.Address]*big.Int) error { ret := _m.Called(_a0, _a1, _a2) - var r0 map[common.Address]map[common.Address]*big.Int - if rf, ok := ret.Get(0).(func(context.Context, *big.Int, map[common.Address]map[common.Address]struct{}) map[common.Address]map[common.Address]*big.Int); ok { + var r0 error + if rf, ok := ret.Get(0).(func(context.Context, *big.Int, map[common.Address]map[common.Address]*big.Int) error); ok { r0 = rf(_a0, _a1, _a2) } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(map[common.Address]map[common.Address]*big.Int) - } - } - - var r1 error - if rf, ok := ret.Get(1).(func(context.Context, *big.Int, map[common.Address]map[common.Address]struct{}) error); ok { - r1 = rf(_a0, _a1, _a2) - } else { - r1 = ret.Error(1) + r0 = ret.Error(0) } - return r0, r1 + return r0 } // BatchBalanceAt provides a mock function with given fields: ctx, accounts, blockNumber diff --git a/cmd/flags/flags.go b/cmd/flags/flags.go index 4897920c..96785089 100644 --- a/cmd/flags/flags.go +++ b/cmd/flags/flags.go @@ -49,4 +49,7 @@ const ( // flags for enabled functions SubscribeErc20token = "functions.erc20token" + + // flags for enable test chain config + ChainTest = "chain.test" ) diff --git a/cmd/indexer/root.go b/cmd/indexer/root.go index 8ea4dfd8..22cb3c30 100644 --- a/cmd/indexer/root.go +++ b/cmd/indexer/root.go @@ -64,6 +64,9 @@ var ( // flags for functions subscribeErc20token bool + + // flag for chain tests + chainTest bool ) // RootCmd represents the base command when called without any subcommands @@ -98,7 +101,7 @@ var ServerCmd = &cobra.Command{ cancel() }() - indexer := indexer.New(ethClient, store.NewManager(db)) + indexer := indexer.New(ethClient, store.NewManager(db, chainTest)) if subscribeErc20token { erc20Addresses, err := LoadTokensFromConfig() @@ -172,6 +175,9 @@ func init() { // erc20 flags ServerCmd.Flags().Bool(flags.SubscribeErc20token, false, "Enable erc20 token subscription. Please specify the erc20 tokens in configs/erc20.yaml") + + // Profling flags + ServerCmd.Flags().Bool(flags.ChainTest, false, "Enable to load test chain config") } func initViper() { @@ -213,4 +219,5 @@ func assignVarFromViper() { // flags for enabled functions subscribeErc20token = viper.GetBool(flags.SubscribeErc20token) + chainTest = viper.GetBool(flags.ChainTest) } diff --git a/common/utils.go b/common/utils.go index 38491202..4478272e 100644 --- a/common/utils.go +++ b/common/utils.go @@ -117,8 +117,14 @@ func Header(b *types.Block) *model.Header { } // Transaction converts ethereum transaction to db transaction -func Transaction(b *types.Block, tx *types.Transaction) (*model.Transaction, error) { - signer := types.MakeSigner(params.MainnetChainConfig, b.Number()) +func Transaction(chainTest bool, b *types.Block, tx *types.Transaction) (*model.Transaction, error) { + var signer types.Signer + if chainTest { + signer = types.MakeSigner(params.TestChainConfig, b.Number()) + } else { + signer = types.MakeSigner(params.MainnetChainConfig, b.Number()) + } + msg, err := tx.AsMessage(signer) if err != nil { log.Error("Failed to get transaction message", "err", err) @@ -130,7 +136,7 @@ func Transaction(b *types.Block, tx *types.Transaction) (*model.Transaction, err BlockHash: b.Hash().Bytes(), From: msg.From().Bytes(), Nonce: int64(msg.Nonce()), - GasPrice: msg.GasPrice().String(), + GasPrice: msg.GasPrice().Int64(), GasLimit: int64(msg.Gas()), Amount: msg.Value().String(), Payload: msg.Data(), diff --git a/configs/config.yaml b/configs/config.yaml index ddfbd4d7..0dbd7191 100644 --- a/configs/config.yaml +++ b/configs/config.yaml @@ -17,3 +17,5 @@ pprof: address: "0.0.0.0" functions: erc20token: true +chain: + test: false diff --git a/migration/db/migrate/20180726041306_add_created_at_in_header.rb b/migration/db/migrate/20180726041306_add_created_at_in_header.rb new file mode 100644 index 00000000..4a18db07 --- /dev/null +++ b/migration/db/migrate/20180726041306_add_created_at_in_header.rb @@ -0,0 +1,6 @@ +class AddCreatedAtInHeader < ActiveRecord::Migration[5.2] + def change + add_column :block_headers, :created_at, :datetime, :null => false + add_index :block_headers, :created_at + end +end diff --git a/migration/db/migrate/20180726081811_change_gp_to_be_big_int.rb b/migration/db/migrate/20180726081811_change_gp_to_be_big_int.rb new file mode 100644 index 00000000..60e38237 --- /dev/null +++ b/migration/db/migrate/20180726081811_change_gp_to_be_big_int.rb @@ -0,0 +1,9 @@ +class ChangeGpToBeBigInt < ActiveRecord::Migration[5.2] + def up + change_column :transactions, :gas_price, :integer, :limit => 8 + end + + def down + change_column :transactions, :gas_price, :string, :limit => 32 + end +end diff --git a/migration/db/migrate/20180730070451_add_reorgs.rb b/migration/db/migrate/20180730070451_add_reorgs.rb new file mode 100644 index 00000000..8b74adff --- /dev/null +++ b/migration/db/migrate/20180730070451_add_reorgs.rb @@ -0,0 +1,12 @@ +class AddReorgs < ActiveRecord::Migration[5.2] + def change + create_table :reorgs do |t| + t.integer :from, :limit => 8, :null => false + t.binary :from_hash, :limit => 32, :null => false + t.integer :to, :limit => 8, :null => false + t.binary :to_hash, :limit => 32, :null => false + t.datetime :created_at, :null => false + end + add_index :reorgs, [:from, :to] + end +end diff --git a/migration/db/schema.rb b/migration/db/schema.rb index 753425a4..047d3839 100644 --- a/migration/db/schema.rb +++ b/migration/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 2018_07_18_053750) do +ActiveRecord::Schema.define(version: 2018_07_30_070451) do create_table "accounts", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci", force: :cascade do |t| t.binary "address", limit: 20, null: false @@ -45,6 +45,8 @@ t.binary "uncle1_coinbase", limit: 20 t.string "uncle2_reward", limit: 32 t.binary "uncle2_coinbase", limit: 20 + t.datetime "created_at", null: false + t.index ["created_at"], name: "index_block_headers_on_created_at" t.index ["hash"], name: "index_block_headers_on_hash", unique: true t.index ["number"], name: "index_block_headers_on_number", unique: true end @@ -86,6 +88,15 @@ t.index ["tx_hash"], name: "index_receipt_logs_on_tx_hash" end + create_table "reorgs", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci", force: :cascade do |t| + t.bigint "from", null: false + t.binary "from_hash", limit: 32, null: false + t.bigint "to", null: false + t.binary "to_hash", limit: 32, null: false + t.datetime "created_at", null: false + t.index ["from", "to"], name: "index_reorgs_on_from_and_to" + end + create_table "subscriptions", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci", force: :cascade do |t| t.bigint "block_number", default: 0 t.bigint "group", null: false @@ -138,7 +149,7 @@ t.binary "from", limit: 20, null: false t.binary "to", limit: 20 t.bigint "nonce", null: false - t.string "gas_price", limit: 32, null: false + t.bigint "gas_price", null: false t.bigint "gas_limit", null: false t.string "amount", limit: 32, null: false t.binary "payload", limit: 16777215, null: false diff --git a/model/types.go b/model/types.go index a46115f0..a660b554 100644 --- a/model/types.go +++ b/model/types.go @@ -47,6 +47,7 @@ var ( // Header represents the header of a block type Header struct { + ID int64 Hash []byte ParentHash []byte UncleHash []byte @@ -78,6 +79,8 @@ type Header struct { // for block header. (only block's nonce may go over int64 range) // https://github.com/golang/go/issues/6113 // https://github.com/golang/go/issues/9373 + + CreatedAt *time.Time } // TableName returns the table name of this model @@ -126,7 +129,7 @@ type Transaction struct { From []byte To []byte Nonce int64 - GasPrice string + GasPrice int64 GasLimit int64 Amount string Payload []byte @@ -283,3 +286,17 @@ type Subscription struct { func (s Subscription) TableName() string { return "subscriptions" } + +// Reorg represents the Reorg model +type Reorg struct { + From int64 + FromHash []byte + To int64 + ToHash []byte + CreatedAt time.Time `deepequal:"-"` +} + +// TableName retruns the table name of this Reorg event +func (s Reorg) TableName() string { + return "reorgs" +} diff --git a/service/indexer/indexer.go b/service/indexer/indexer.go index 004e236c..41510e4a 100644 --- a/service/indexer/indexer.go +++ b/service/indexer/indexer.go @@ -231,7 +231,7 @@ func (idx *indexer) getTd(ctx context.Context, hash []byte) (td *big.Int, err er return common.ParseTd(ltd) } -func (idx *indexer) insertBlocks(ctx context.Context, blocks []*types.Block, mode store.UpdateMode) (*types.Block, *big.Int, error) { +func (idx *indexer) insertBlocks(ctx context.Context, blocks []*types.Block, reorgEvent *model.Reorg) (*types.Block, *big.Int, error) { var lastTd *big.Int // Insert td for i := len(blocks) - 1; i >= 0; i-- { @@ -257,7 +257,7 @@ func (idx *indexer) insertBlocks(ctx context.Context, blocks []*types.Block, mod receipts = append(receipts, receipt) events = append(events, event) } - err := idx.manager.UpdateBlocks(ctx, newBlocks, receipts, events, mode) + err := idx.manager.UpdateBlocks(ctx, newBlocks, receipts, events, reorgEvent) if err != nil { log.Error("Failed to update blocks", "err", err) return nil, nil, err @@ -280,10 +280,16 @@ func (idx *indexer) addBlockMaybeReorg(ctx context.Context, target int64) (*type var blocksToInsert []*types.Block if target == 0 || bytes.Equal(block.ParentHash().Bytes(), idx.currentHeader.Hash) { blocksToInsert = append(blocksToInsert, block) - return idx.insertBlocks(ctx, blocksToInsert, store.ModeSync) + return idx.insertBlocks(ctx, blocksToInsert, nil) } logger.Trace("Reorg tracing: Start") + reorgEvent := &model.Reorg{ + From: idx.currentHeader.Number, + FromHash: idx.currentHeader.Hash, + To: idx.currentHeader.Number, + ToHash: idx.currentHeader.Hash, + } targetTD := block.Difficulty() blocks := []*types.Block{block} for { @@ -294,6 +300,9 @@ func (idx *indexer) addBlockMaybeReorg(ctx context.Context, target int64) (*type if bytes.Equal(dbHeader.Hash, block.ParentHash().Bytes()) { break } + // Update reorg event + reorgEvent.From = dbHeader.Number + reorgEvent.FromHash = dbHeader.Hash } else if !common.NotFoundError(err) { logger.Error("Reorg tracing: Failed to get header from local db", "number", block.Number().Int64()-1, "err", err) return nil, nil, err @@ -330,7 +339,7 @@ func (idx *indexer) addBlockMaybeReorg(ctx context.Context, target int64) (*type // Now atomically update the reorg'ed blocks logger.Trace("Reorg: Starting at", "branch", branchBlock.Number(), "hash", branchBlock.Hash().Hex()) - block, targetTD, err = idx.insertBlocks(ctx, blocksToInsert, store.ModeReOrg) + block, targetTD, err = idx.insertBlocks(ctx, blocksToInsert, reorgEvent) if err != nil { logger.Error("Reorg: Failed to insert blocks", "err", err) return nil, nil, err @@ -344,6 +353,11 @@ func (idx *indexer) getBlockData(ctx context.Context, block *types.Block) ([]*ty blockNumber := block.Number().Int64() logger := log.New("number", blockNumber, "hash", block.Hash().Hex()) + // Return empty receipts and transfer logs if it's a genesis block + if blockNumber == 0 { + return []*types.Receipt{}, []*types.TransferLog{}, nil + } + // Get receipts receipts, err := idx.client.GetBlockReceipts(ctx, block.Hash()) if err != nil { diff --git a/service/indexer/indexer_test.go b/service/indexer/indexer_test.go index 0de13d2a..7c35a0f4 100644 --- a/service/indexer/indexer_test.go +++ b/service/indexer/indexer_test.go @@ -27,7 +27,6 @@ import ( "github.com/ethereum/go-ethereum/core/types" clientMocks "github.com/getamis/eth-indexer/client/mocks" "github.com/getamis/eth-indexer/model" - "github.com/getamis/eth-indexer/store" storeMocks "github.com/getamis/eth-indexer/store/mocks" "github.com/jinzhu/gorm" . "github.com/onsi/ginkgo" @@ -54,6 +53,7 @@ var _ = Describe("Indexer Test", func() { mockStoreManager *storeMocks.Manager idx *indexer nilTransferLogs []*types.TransferLog + nilReorg *model.Reorg ) BeforeEach(func() { mockSub = &testSub{make(chan error)} @@ -212,7 +212,7 @@ var _ = Describe("Indexer Test", func() { mockStoreManager.On("InsertTd", block, big.NewInt(i)).Return(nil).Once() mockEthClient.On("GetBlockReceipts", mock.Anything, blocks[i].Hash()).Return(types.Receipts{receipt}, nil).Once() mockEthClient.On("GetTransferLogs", mock.Anything, blocks[i].Hash()).Return(nil, nil).Once() - mockStoreManager.On("UpdateBlocks", mock.Anything, []*types.Block{block}, [][]*types.Receipt{{receipt}}, [][]*types.TransferLog{nilTransferLogs}, store.ModeSync).Return(nil).Once() + mockStoreManager.On("UpdateBlocks", mock.Anything, []*types.Block{block}, [][]*types.Receipt{{receipt}}, [][]*types.TransferLog{nilTransferLogs}, nilReorg).Return(nil).Once() } mockStoreManager.On("LatestHeader").Return(&model.Header{ @@ -276,7 +276,7 @@ var _ = Describe("Indexer Test", func() { mockStoreManager.On("InsertTd", block, big.NewInt(i)).Return(nil).Once() mockEthClient.On("GetBlockReceipts", mock.Anything, blocks[i].Hash()).Return(types.Receipts{receipt}, nil).Once() mockEthClient.On("GetTransferLogs", mock.Anything, blocks[i].Hash()).Return(nil, nil).Once() - mockStoreManager.On("UpdateBlocks", mock.Anything, []*types.Block{block}, [][]*types.Receipt{{receipt}}, [][]*types.TransferLog{nilTransferLogs}, store.ModeSync).Return(nil).Once() + mockStoreManager.On("UpdateBlocks", mock.Anything, []*types.Block{block}, [][]*types.Receipt{{receipt}}, [][]*types.TransferLog{nilTransferLogs}, nilReorg).Return(nil).Once() } } @@ -325,10 +325,8 @@ var _ = Describe("Indexer Test", func() { }, []*types.Transaction{tx}, nil, []*types.Receipt{receipt}) blocks[0] = block mockEthClient.On("BlockByNumber", mock.Anything, big.NewInt(0)).Return(block, nil).Once() - mockEthClient.On("GetBlockReceipts", mock.Anything, block.Hash()).Return(types.Receipts{receipt}, nil).Once() mockStoreManager.On("InsertTd", block, big.NewInt(1)).Return(nil).Once() - mockEthClient.On("GetTransferLogs", mock.Anything, block.Hash()).Return(nil, nil).Once() - mockStoreManager.On("UpdateBlocks", mock.Anything, []*types.Block{block}, [][]*types.Receipt{{receipt}}, [][]*types.TransferLog{nilTransferLogs}, store.ModeSync).Return(nil).Once() + mockStoreManager.On("UpdateBlocks", mock.Anything, []*types.Block{block}, [][]*types.Receipt{{}}, [][]*types.TransferLog{{}}, nilReorg).Return(nil).Once() for i := int64(1); i <= 19; i++ { block = types.NewBlock( @@ -346,7 +344,7 @@ var _ = Describe("Indexer Test", func() { mockStoreManager.On("InsertTd", block, big.NewInt(i+1)).Return(nil).Once() mockEthClient.On("GetBlockReceipts", mock.Anything, blocks[i].Hash()).Return(types.Receipts{receipt}, nil).Once() mockEthClient.On("GetTransferLogs", mock.Anything, blocks[i].Hash()).Return(nil, nil).Once() - mockStoreManager.On("UpdateBlocks", mock.Anything, []*types.Block{block}, [][]*types.Receipt{{receipt}}, [][]*types.TransferLog{nilTransferLogs}, store.ModeSync).Return(nil).Once() + mockStoreManager.On("UpdateBlocks", mock.Anything, []*types.Block{block}, [][]*types.Receipt{{receipt}}, [][]*types.TransferLog{nilTransferLogs}, nilReorg).Return(nil).Once() } mockStoreManager.On("LatestHeader").Return(nil, gorm.ErrRecordNotFound).Once() @@ -395,7 +393,7 @@ var _ = Describe("Indexer Test", func() { mockStoreManager.On("InsertTd", block, big.NewInt(i)).Return(nil).Once() mockEthClient.On("GetBlockReceipts", mock.Anything, blocks[i].Hash()).Return(types.Receipts{receipt}, nil).Once() mockEthClient.On("GetTransferLogs", mock.Anything, blocks[i].Hash()).Return(nil, nil).Once() - mockStoreManager.On("UpdateBlocks", mock.Anything, []*types.Block{block}, [][]*types.Receipt{{receipt}}, [][]*types.TransferLog{nilTransferLogs}, store.ModeSync).Return(nil).Once() + mockStoreManager.On("UpdateBlocks", mock.Anything, []*types.Block{block}, [][]*types.Receipt{{receipt}}, [][]*types.TransferLog{nilTransferLogs}, nilReorg).Return(nil).Once() } mockStoreManager.On("LatestHeader").Return(&model.Header{ Number: 10, @@ -543,7 +541,7 @@ var _ = Describe("Indexer Test", func() { 10, parent, strconv.Itoa(10)}, nil).Once() mockStoreManager.On("InsertTd", block, big.NewInt(11)).Return(nil).Once() mockEthClient.On("GetTransferLogs", mock.Anything, block.Hash()).Return(nil, nil).Once() - mockStoreManager.On("UpdateBlocks", mock.Anything, []*types.Block{block}, [][]*types.Receipt{{receipt}}, [][]*types.TransferLog{nilTransferLogs}, store.ModeSync).Return(unknownErr).Once() + mockStoreManager.On("UpdateBlocks", mock.Anything, []*types.Block{block}, [][]*types.Receipt{{receipt}}, [][]*types.TransferLog{nilTransferLogs}, nilReorg).Return(unknownErr).Once() var recvCh chan<- *types.Header recvCh = ch @@ -763,14 +761,19 @@ var _ = Describe("Indexer Test", func() { for i := int64(16); i <= 17; i++ { mockEthClient.On("GetBlockReceipts", mock.Anything, blocks[i].Hash()).Return(types.Receipts{receipt}, nil).Once() mockEthClient.On("GetTransferLogs", mock.Anything, blocks[i].Hash()).Return(nil, nil).Once() - mockStoreManager.On("UpdateBlocks", mock.Anything, []*types.Block{blocks[i]}, [][]*types.Receipt{{receipt}}, [][]*types.TransferLog{nilTransferLogs}, store.ModeSync).Return(nil).Once() + mockStoreManager.On("UpdateBlocks", mock.Anything, []*types.Block{blocks[i]}, [][]*types.Receipt{{receipt}}, [][]*types.TransferLog{nilTransferLogs}, nilReorg).Return(nil).Once() } // state diff for the new blocks for i := int64(15); i <= 18; i++ { mockEthClient.On("GetBlockReceipts", mock.Anything, newBlocks[i].Hash()).Return(types.Receipts{receipt}, nil).Once() mockEthClient.On("GetTransferLogs", mock.Anything, newBlocks[i].Hash()).Return(nil, nil).Once() } - mockStoreManager.On("UpdateBlocks", mock.Anything, newBlocks[15:19], [][]*types.Receipt{{receipt}, {receipt}, {receipt}, {receipt}}, [][]*types.TransferLog{nilTransferLogs, nilTransferLogs, nilTransferLogs, nilTransferLogs}, store.ModeReOrg).Return(nil).Once() + mockStoreManager.On("UpdateBlocks", mock.Anything, newBlocks[15:19], [][]*types.Receipt{{receipt}, {receipt}, {receipt}, {receipt}}, [][]*types.TransferLog{nilTransferLogs, nilTransferLogs, nilTransferLogs, nilTransferLogs}, &model.Reorg{ + From: 15, + FromHash: blocks[15].Hash().Bytes(), + To: 17, + ToHash: blocks[17].Hash().Bytes(), + }).Return(nil).Once() var recvCh chan<- *types.Header recvCh = ch @@ -866,7 +869,12 @@ var _ = Describe("Indexer Test", func() { mockEthClient.On("GetBlockReceipts", mock.Anything, newBlocks[i].Hash()).Return(types.Receipts{receipt}, nil).Once() mockEthClient.On("GetTransferLogs", mock.Anything, newBlocks[i].Hash()).Return(nil, nil).Once() } - mockStoreManager.On("UpdateBlocks", mock.Anything, newBlocks[15:17], [][]*types.Receipt{{receipt}, {receipt}}, [][]*types.TransferLog{nilTransferLogs, nilTransferLogs}, store.ModeReOrg).Return(nil).Once() + mockStoreManager.On("UpdateBlocks", mock.Anything, newBlocks[15:17], [][]*types.Receipt{{receipt}, {receipt}}, [][]*types.TransferLog{nilTransferLogs, nilTransferLogs}, &model.Reorg{ + From: 15, + FromHash: blocks[15].Hash().Bytes(), + To: 17, + ToHash: blocks[17].Hash().Bytes(), + }).Return(nil).Once() var recvCh chan<- *types.Header recvCh = ch diff --git a/store/block_header/block_header_test.go b/store/block_header/block_header_test.go index f6e66217..6fbd6f63 100644 --- a/store/block_header/block_header_test.go +++ b/store/block_header/block_header_test.go @@ -85,14 +85,17 @@ var _ = Describe("Block Header Database Test", func() { result, err := store.FindBlockByHash(data1.Hash) Expect(err).Should(Succeed()) + result.CreatedAt = data1.CreatedAt Expect(*result).Should(Equal(*data1)) result, err = store.FindBlockByHash(data2.Hash) Expect(err).Should(Succeed()) + result.CreatedAt = data2.CreatedAt Expect(*result).Should(Equal(*data2)) lastResult, err := store.FindLatestBlock() Expect(err).Should(Succeed()) + lastResult.CreatedAt = data2.CreatedAt Expect(*lastResult).Should(Equal(*data2)) }) @@ -107,10 +110,12 @@ var _ = Describe("Block Header Database Test", func() { result, err := store.FindBlockByNumber(data1.Number) Expect(err).Should(Succeed()) + result.CreatedAt = data1.CreatedAt Expect(*result).Should(Equal(*data1)) result, err = store.FindBlockByNumber(data2.Number) Expect(err).Should(Succeed()) + result.CreatedAt = data2.CreatedAt Expect(*result).Should(Equal(*data2)) }) @@ -142,11 +147,13 @@ var _ = Describe("Block Header Database Test", func() { result, err := store.FindBlockByNumber(data1.Number) Expect(err).Should(Succeed()) + result.CreatedAt = data1.CreatedAt Expect(result).Should(Equal(data1)) _, err = store.FindBlockByNumber(data2.Number) Expect(common.NotFoundError(err)).Should(BeTrue()) result, err = store.FindBlockByNumber(data3.Number) Expect(err).Should(Succeed()) + result.CreatedAt = data3.CreatedAt Expect(result).Should(Equal(data3)) }) @@ -163,6 +170,7 @@ var _ = Describe("Block Header Database Test", func() { lastResult, err := store.FindLatestBlock() Expect(err).Should(Succeed()) + lastResult.CreatedAt = data3.CreatedAt Expect(*lastResult).Should(Equal(*data3)) }) diff --git a/store/mocks/Manager.go b/store/mocks/Manager.go index 16534df8..ca9445ae 100644 --- a/store/mocks/Manager.go +++ b/store/mocks/Manager.go @@ -149,13 +149,13 @@ func (_m *Manager) LatestHeader() (*model.Header, error) { return r0, r1 } -// UpdateBlocks provides a mock function with given fields: ctx, blocks, receipts, events, mode -func (_m *Manager) UpdateBlocks(ctx context.Context, blocks []*types.Block, receipts [][]*types.Receipt, events [][]*types.TransferLog, mode int) error { - ret := _m.Called(ctx, blocks, receipts, events, mode) +// UpdateBlocks provides a mock function with given fields: ctx, blocks, receipts, events, reorgEvent +func (_m *Manager) UpdateBlocks(ctx context.Context, blocks []*types.Block, receipts [][]*types.Receipt, events [][]*types.TransferLog, reorgEvent *model.Reorg) error { + ret := _m.Called(ctx, blocks, receipts, events, reorgEvent) var r0 error - if rf, ok := ret.Get(0).(func(context.Context, []*types.Block, [][]*types.Receipt, [][]*types.TransferLog, int) error); ok { - r0 = rf(ctx, blocks, receipts, events, mode) + if rf, ok := ret.Get(0).(func(context.Context, []*types.Block, [][]*types.Receipt, [][]*types.TransferLog, *model.Reorg) error); ok { + r0 = rf(ctx, blocks, receipts, events, reorgEvent) } else { r0 = ret.Error(0) } diff --git a/store/new_erc20.go b/store/new_erc20.go index 273e3ac8..6dc95683 100644 --- a/store/new_erc20.go +++ b/store/new_erc20.go @@ -75,27 +75,27 @@ func (m *manager) initNewERC20(ctx context.Context, accountStore account.Store, // Construct a set of subscription for membership testing subMap := make(map[gethCommon.Address]*model.Subscription) - contractsAddrs := make(map[gethCommon.Address]map[gethCommon.Address]struct{}) + balancesByContracts := make(map[gethCommon.Address]map[gethCommon.Address]*big.Int) for _, sub := range subs { subAddr := gethCommon.BytesToAddress(sub.Address) subMap[subAddr] = sub for _, token := range newTokens { tokenAddr := gethCommon.BytesToAddress(token.Address) - if contractsAddrs[tokenAddr] == nil { - contractsAddrs[tokenAddr] = make(map[gethCommon.Address]struct{}) + if balancesByContracts[tokenAddr] == nil { + balancesByContracts[tokenAddr] = make(map[gethCommon.Address]*big.Int) } - contractsAddrs[tokenAddr][subAddr] = struct{}{} + balancesByContracts[tokenAddr][subAddr] = new(big.Int) } } // Get balances - results, err := m.balancer.BalanceOf(ctx, big.NewInt(blockNumber), contractsAddrs) + err = m.balancer.BalanceOf(ctx, big.NewInt(blockNumber), balancesByContracts) if err != nil { - logger.Error("Failed to get ERC20 balance", "len", len(contractsAddrs), "err", err) + logger.Error("Failed to get ERC20 balance", "len", len(balancesByContracts), "err", err) return nil, err } // Update total balances - for contractAddr, addrs := range results { + for contractAddr, addrs := range balancesByContracts { for addr, balance := range addrs { sub, ok := subMap[addr] if !ok { diff --git a/store/new_erc20_test.go b/store/new_erc20_test.go index 3a069fe7..70f66106 100644 --- a/store/new_erc20_test.go +++ b/store/new_erc20_test.go @@ -29,6 +29,7 @@ import ( subsStore "github.com/getamis/eth-indexer/store/subscription" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "github.com/stretchr/testify/mock" ) var _ = Describe("New ERC20 Test", func() { @@ -64,16 +65,25 @@ var _ = Describe("New ERC20 Test", func() { db.Delete(&model.Header{}) db.Delete(&model.Transaction{}) db.Delete(&model.Receipt{}) - db.Delete(&model.Account{}) + db.Delete(&model.Account{ + ContractAddress: model.ETHBytes, + }) db.Delete(&model.ERC20{}) db.Delete(&model.TotalBalance{}) db.Delete(&model.Subscription{}) + db.Delete(&model.Reorg{}) db.DropTable(model.Transfer{ Address: erc20s[0].Address, }) db.DropTable(model.Transfer{ Address: erc20s[1].Address, }) + db.DropTable(model.Account{ + ContractAddress: erc20s[0].Address, + }) + db.DropTable(model.Account{ + ContractAddress: erc20s[1].Address, + }) }) It("should be successful", func() { @@ -141,7 +151,7 @@ var _ = Describe("New ERC20 Test", func() { events = [][]*types.TransferLog{{}, {}, {}} ctx := context.Background() - manager = NewManager(db) + manager = NewManager(db, false) for _, erc20 := range erc20s { err = manager.InsertERC20(erc20) @@ -162,40 +172,29 @@ var _ = Describe("New ERC20 Test", func() { Expect(err).Should(BeNil()) // For the 100 block - mockBalancer.On("BalanceOf", ctx, big.NewInt(100), map[gethCommon.Address]map[gethCommon.Address]struct{}{ - model.ETHAddress: { - gethCommon.BytesToAddress(subs[1].Address): struct{}{}, - gethCommon.BytesToAddress(subs[2].Address): struct{}{}, - }, - gethCommon.BytesToAddress(erc20s[0].Address): { - gethCommon.BytesToAddress(subs[1].Address): struct{}{}, - gethCommon.BytesToAddress(subs[2].Address): struct{}{}, - }, - }).Return(map[gethCommon.Address]map[gethCommon.Address]*big.Int{ - model.ETHAddress: { - gethCommon.BytesToAddress(subs[1].Address): big.NewInt(112), - gethCommon.BytesToAddress(subs[2].Address): big.NewInt(113), - }, - gethCommon.BytesToAddress(erc20s[0].Address): { - gethCommon.BytesToAddress(subs[1].Address): big.NewInt(212), - gethCommon.BytesToAddress(subs[2].Address): big.NewInt(213), - }, - }, nil).Once() + mockBalancer.On("BalanceOf", ctx, big.NewInt(100), mock.Anything).Run(func(args mock.Arguments) { + result := args.Get(2).(map[gethCommon.Address]map[gethCommon.Address]*big.Int) + result[model.ETHAddress][gethCommon.BytesToAddress(subs[1].Address)] = big.NewInt(112) + result[model.ETHAddress][gethCommon.BytesToAddress(subs[2].Address)] = big.NewInt(113) + result[gethCommon.BytesToAddress(erc20s[0].Address)][gethCommon.BytesToAddress(subs[1].Address)] = big.NewInt(212) + result[gethCommon.BytesToAddress(erc20s[0].Address)][gethCommon.BytesToAddress(subs[2].Address)] = big.NewInt(213) + }).Return(nil).Once() // For new token - for i, sub := range subs { - mockBalancer.On("BalanceOf", ctx, big.NewInt(100), map[gethCommon.Address]map[gethCommon.Address]struct{}{ - gethCommon.BytesToAddress(erc20s[1].Address): { - gethCommon.BytesToAddress(sub.Address): struct{}{}, - }, - }).Return(map[gethCommon.Address]map[gethCommon.Address]*big.Int{ - gethCommon.BytesToAddress(erc20s[1].Address): { - gethCommon.BytesToAddress(sub.Address): big.NewInt(310 + int64(i)), - }, - }, nil).Once() - } + mockBalancer.On("BalanceOf", ctx, big.NewInt(100), mock.Anything).Run(func(args mock.Arguments) { + result := args.Get(2).(map[gethCommon.Address]map[gethCommon.Address]*big.Int) + result[gethCommon.BytesToAddress(erc20s[1].Address)][gethCommon.BytesToAddress(subs[0].Address)] = big.NewInt(310) + }).Return(nil).Once() + mockBalancer.On("BalanceOf", ctx, big.NewInt(100), mock.Anything).Run(func(args mock.Arguments) { + result := args.Get(2).(map[gethCommon.Address]map[gethCommon.Address]*big.Int) + result[gethCommon.BytesToAddress(erc20s[1].Address)][gethCommon.BytesToAddress(subs[1].Address)] = big.NewInt(311) + }).Return(nil).Once() + mockBalancer.On("BalanceOf", ctx, big.NewInt(100), mock.Anything).Run(func(args mock.Arguments) { + result := args.Get(2).(map[gethCommon.Address]map[gethCommon.Address]*big.Int) + result[gethCommon.BytesToAddress(erc20s[1].Address)][gethCommon.BytesToAddress(subs[2].Address)] = big.NewInt(312) + }).Return(nil).Once() - err = manager.UpdateBlocks(ctx, blocks, receipts, events, ModeReOrg) + err = manager.UpdateBlocks(ctx, blocks, receipts, events, nil) Expect(err).Should(BeNil()) // block 100 @@ -261,39 +260,34 @@ var _ = Describe("New ERC20 Test", func() { By("Reorg blocks comes") // For the 100 block - mockBalancer.On("BalanceOf", ctx, big.NewInt(100), map[gethCommon.Address]map[gethCommon.Address]struct{}{ - model.ETHAddress: { - gethCommon.BytesToAddress(subs[1].Address): struct{}{}, - gethCommon.BytesToAddress(subs[2].Address): struct{}{}, - }, - gethCommon.BytesToAddress(erc20s[0].Address): { - gethCommon.BytesToAddress(subs[1].Address): struct{}{}, - gethCommon.BytesToAddress(subs[2].Address): struct{}{}, - }, - }).Return(map[gethCommon.Address]map[gethCommon.Address]*big.Int{ - model.ETHAddress: { - gethCommon.BytesToAddress(subs[1].Address): big.NewInt(1112), - gethCommon.BytesToAddress(subs[2].Address): big.NewInt(1113), - }, - gethCommon.BytesToAddress(erc20s[0].Address): { - gethCommon.BytesToAddress(subs[1].Address): big.NewInt(1212), - gethCommon.BytesToAddress(subs[2].Address): big.NewInt(1213), - }, - }, nil).Once() + mockBalancer.On("BalanceOf", ctx, big.NewInt(100), mock.Anything).Run(func(args mock.Arguments) { + result := args.Get(2).(map[gethCommon.Address]map[gethCommon.Address]*big.Int) + result[model.ETHAddress][gethCommon.BytesToAddress(subs[1].Address)] = big.NewInt(1112) + result[model.ETHAddress][gethCommon.BytesToAddress(subs[2].Address)] = big.NewInt(1113) + result[gethCommon.BytesToAddress(erc20s[0].Address)][gethCommon.BytesToAddress(subs[1].Address)] = big.NewInt(1212) + result[gethCommon.BytesToAddress(erc20s[0].Address)][gethCommon.BytesToAddress(subs[2].Address)] = big.NewInt(1213) + }).Return(nil).Once() // For new token - for i, sub := range subs { - mockBalancer.On("BalanceOf", ctx, big.NewInt(100), map[gethCommon.Address]map[gethCommon.Address]struct{}{ - gethCommon.BytesToAddress(erc20s[1].Address): { - gethCommon.BytesToAddress(sub.Address): struct{}{}, - }, - }).Return(map[gethCommon.Address]map[gethCommon.Address]*big.Int{ - gethCommon.BytesToAddress(erc20s[1].Address): { - gethCommon.BytesToAddress(sub.Address): big.NewInt(1310 + int64(i)), - }, - }, nil).Once() - } - err = manager.UpdateBlocks(ctx, blocks, receipts, events, ModeReOrg) + mockBalancer.On("BalanceOf", ctx, big.NewInt(100), mock.Anything).Run(func(args mock.Arguments) { + result := args.Get(2).(map[gethCommon.Address]map[gethCommon.Address]*big.Int) + result[gethCommon.BytesToAddress(erc20s[1].Address)][gethCommon.BytesToAddress(subs[0].Address)] = big.NewInt(1310) + }).Return(nil).Once() + mockBalancer.On("BalanceOf", ctx, big.NewInt(100), mock.Anything).Run(func(args mock.Arguments) { + result := args.Get(2).(map[gethCommon.Address]map[gethCommon.Address]*big.Int) + result[gethCommon.BytesToAddress(erc20s[1].Address)][gethCommon.BytesToAddress(subs[1].Address)] = big.NewInt(1311) + }).Return(nil).Once() + mockBalancer.On("BalanceOf", ctx, big.NewInt(100), mock.Anything).Run(func(args mock.Arguments) { + result := args.Get(2).(map[gethCommon.Address]map[gethCommon.Address]*big.Int) + result[gethCommon.BytesToAddress(erc20s[1].Address)][gethCommon.BytesToAddress(subs[2].Address)] = big.NewInt(1312) + }).Return(nil).Once() + + err = manager.UpdateBlocks(ctx, blocks, receipts, events, &model.Reorg{ + From: blocks[0].Number().Int64(), + To: blocks[len(blocks)-1].Number().Int64(), + FromHash: blocks[0].Hash().Bytes(), + ToHash: blocks[len(blocks)-1].Hash().Bytes(), + }) Expect(err).Should(BeNil()) // block 100 diff --git a/store/reorg/mocks/Store.go b/store/reorg/mocks/Store.go new file mode 100644 index 00000000..117b0719 --- /dev/null +++ b/store/reorg/mocks/Store.go @@ -0,0 +1,24 @@ +// Code generated by mockery v1.0.0 +package mocks + +import mock "github.com/stretchr/testify/mock" +import model "github.com/getamis/eth-indexer/model" + +// Store is an autogenerated mock type for the Store type +type Store struct { + mock.Mock +} + +// Insert provides a mock function with given fields: data +func (_m *Store) Insert(data *model.Reorg) error { + ret := _m.Called(data) + + var r0 error + if rf, ok := ret.Get(0).(func(*model.Reorg) error); ok { + r0 = rf(data) + } else { + r0 = ret.Error(0) + } + + return r0 +} diff --git a/store/reorg/reorg.go b/store/reorg/reorg.go new file mode 100644 index 00000000..5c6afc3a --- /dev/null +++ b/store/reorg/reorg.go @@ -0,0 +1,48 @@ +// Copyright 2018 The eth-indexer Authors +// This file is part of the eth-indexer library. +// +// The eth-indexer 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 eth-indexer 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 eth-indexer library. If not, see . + +package reorg + +import ( + "github.com/getamis/eth-indexer/model" + "github.com/jinzhu/gorm" +) + +//go:generate mockery -name Store +type Store interface { + Insert(data *model.Reorg) error + // For testing + List() ([]*model.Reorg, error) +} + +type store struct { + db *gorm.DB +} + +func NewWithDB(db *gorm.DB) Store { + return &store{ + db: db, + } +} + +func (s *store) Insert(data *model.Reorg) error { + return s.db.Create(data).Error +} + +func (s *store) List() (results []*model.Reorg, err error) { + err = s.db.Find(&results).Error + return +} diff --git a/store/reorg/reorg_test.go b/store/reorg/reorg_test.go new file mode 100644 index 00000000..463e7efc --- /dev/null +++ b/store/reorg/reorg_test.go @@ -0,0 +1,85 @@ +// Copyright 2018 The eth-indexer Authors +// This file is part of the eth-indexer library. +// +// The eth-indexer 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 eth-indexer 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 eth-indexer library. If not, see . + +package reorg + +import ( + "os" + "testing" + + "github.com/getamis/eth-indexer/model" + "github.com/getamis/sirius/test" + "github.com/jinzhu/gorm" + . "github.com/onsi/ginkgo" + . "github.com/onsi/gomega" +) + +var _ = Describe("Reorg Database Test", func() { + var ( + mysql *test.MySQLContainer + db *gorm.DB + ) + BeforeSuite(func() { + var err error + mysql, err = test.NewMySQLContainer("quay.io/amis/eth-indexer-db-migration") + Expect(mysql).ShouldNot(BeNil()) + Expect(err).Should(Succeed()) + Expect(mysql.Start()).Should(Succeed()) + + db, err = gorm.Open("mysql", mysql.URL) + Expect(err).Should(Succeed()) + Expect(db).ShouldNot(BeNil()) + + db.LogMode(os.Getenv("ENABLE_DB_LOG_IN_TEST") != "") + }) + + AfterSuite(func() { + mysql.Stop() + }) + + BeforeEach(func() { + db.Delete(&model.Reorg{}) + }) + + It("should insert", func() { + store := NewWithDB(db) + + data1 := &model.Reorg{ + From: 100, + FromHash: []byte("hash1"), + To: 110, + ToHash: []byte("hash2"), + } + + By("insert new reorg") + err := store.Insert(data1) + Expect(err).Should(Succeed()) + + By("insert the reorg again") + err = store.Insert(data1) + Expect(err).Should(Succeed()) + + By("check reorgs size") + rs, err := store.List() + Expect(err).Should(Succeed()) + Expect(len(rs)).Should(BeNumerically("==", 2)) + }) +}) + +func TestReorg(t *testing.T) { + RegisterFailHandler(Fail) + RunSpecs(t, "Reorg Test") +} diff --git a/store/store.go b/store/store.go index 80f497cc..32b31f39 100644 --- a/store/store.go +++ b/store/store.go @@ -27,6 +27,7 @@ import ( "github.com/getamis/eth-indexer/model" "github.com/getamis/eth-indexer/store/account" "github.com/getamis/eth-indexer/store/block_header" + "github.com/getamis/eth-indexer/store/reorg" "github.com/getamis/eth-indexer/store/subscription" "github.com/getamis/eth-indexer/store/transaction" "github.com/getamis/eth-indexer/store/transaction_receipt" @@ -34,18 +35,6 @@ import ( "github.com/jinzhu/gorm" ) -// UpdateMode defines the mode to update blocks -type UpdateMode = int - -const ( - // ModeReOrg represents update blocks by reorg - // Stop if any errors occur. - ModeReOrg UpdateMode = iota - // ModeSync represents update blocks by ethereum sync - // Stop if any errors occur, but return nil error if it's a duplicate error - ModeSync -) - //go:generate mockery -name Manager // Manager is a wrapper interface to insert block, receipt and states quickly @@ -64,20 +53,22 @@ type Manager interface { GetHeaderByNumber(number int64) (*model.Header, error) // GetTd returns the TD of the given block hash GetTd(hash []byte) (*model.TotalDifficulty, error) - // UpdateBlocks updates all block data. 'delete' indicates whether deletes all data before update. - UpdateBlocks(ctx context.Context, blocks []*types.Block, receipts [][]*types.Receipt, events [][]*types.TransferLog, mode UpdateMode) error + // UpdateBlocks updates all block data + UpdateBlocks(ctx context.Context, blocks []*types.Block, receipts [][]*types.Receipt, events [][]*types.TransferLog, reorgEvent *model.Reorg) error } type manager struct { db *gorm.DB + chainTest bool tokenList map[gethCommon.Address]*model.ERC20 balancer client.Balancer } // NewManager news a store manager to insert block, receipts and states. -func NewManager(db *gorm.DB) Manager { +func NewManager(db *gorm.DB, chainTest bool) Manager { return &manager{ - db: db, + db: db, + chainTest: chainTest, } } @@ -105,7 +96,7 @@ func (m *manager) InsertTd(block *types.Block, td *big.Int) error { return block_header.NewWithDB(m.db).InsertTd(common.TotalDifficulty(block, td)) } -func (m *manager) UpdateBlocks(ctx context.Context, blocks []*types.Block, receipts [][]*types.Receipt, events [][]*types.TransferLog, mode UpdateMode) (err error) { +func (m *manager) UpdateBlocks(ctx context.Context, blocks []*types.Block, receipts [][]*types.Receipt, events [][]*types.TransferLog, reorgEvent *model.Reorg) (err error) { size := len(blocks) if size != len(receipts) || size != len(events) { log.Error("Inconsistent states", "blocks", size, "receipts", len(receipts)) @@ -129,7 +120,13 @@ func (m *manager) UpdateBlocks(ctx context.Context, blocks []*types.Block, recei }() // In ModeReOrg, delete all blocks, recipients and states within this range before insertions - if mode == ModeReOrg { + isReorg := reorgEvent != nil + if isReorg { + reorgStore := reorg.NewWithDB(dbTx) + err = reorgStore.Insert(reorgEvent) + if err != nil { + return err + } err = m.delete(dbTx, from, to) if err != nil { return err @@ -172,7 +169,7 @@ func (m *manager) insertBlock(ctx context.Context, dbTx *gorm.DB, block *types.B // Insert txs var txs []*model.Transaction for _, t := range block.Transactions() { - tx, err := common.Transaction(block, t) + tx, err := common.Transaction(m.chainTest, block, t) if err != nil { return err } diff --git a/store/store_test.go b/store/store_test.go index ba059e81..186fbc9e 100644 --- a/store/store_test.go +++ b/store/store_test.go @@ -28,6 +28,7 @@ import ( "github.com/ethereum/go-ethereum/crypto" "github.com/getamis/eth-indexer/common" "github.com/getamis/eth-indexer/model" + "github.com/getamis/eth-indexer/store/reorg" "github.com/getamis/sirius/test" "github.com/jinzhu/gorm" . "github.com/onsi/ginkgo" @@ -187,7 +188,7 @@ var _ = Describe("Manager Test", func() { } var err error - manager = NewManager(db) + manager = NewManager(db, false) err = manager.Init(nil) Expect(err).Should(BeNil()) @@ -198,7 +199,7 @@ var _ = Describe("Manager Test", func() { Expect(err).Should(BeNil()) Expect(resERC20).Should(Equal(erc20)) - err = manager.UpdateBlocks(context.Background(), blocks, receipts, events, ModeReOrg) + err = manager.UpdateBlocks(context.Background(), blocks, receipts, events, nil) Expect(err).Should(BeNil()) }) @@ -207,8 +208,11 @@ var _ = Describe("Manager Test", func() { db.Delete(&model.Header{}) db.Delete(&model.Transaction{}) db.Delete(&model.Receipt{}) - db.Delete(&model.Account{}) + db.Delete(&model.Account{ + ContractAddress: model.ETHBytes, + }) db.Delete(&model.ERC20{}) + db.Delete(&model.Reorg{}) db.DropTable(model.Account{ ContractAddress: erc20.Address, }) @@ -239,7 +243,7 @@ var _ = Describe("Manager Test", func() { receipts[1], receipts[0], } - err := manager.UpdateBlocks(context.Background(), newBlocks, newReceipts, events, ModeSync) + err := manager.UpdateBlocks(context.Background(), newBlocks, newReceipts, events, nil) Expect(common.DuplicateError(err)).Should(BeTrue()) minerBaseReward, uncleInclusionReward, uncleCBs, unclesReward, unclesHash := common.AccumulateRewards(blocks[0].Header(), blocks[0].Uncles()) @@ -247,6 +251,8 @@ var _ = Describe("Manager Test", func() { Expect(err).Should(BeNil()) h, err := common.Header(blocks[0]).AddReward(big.NewInt(20), minerBaseReward, uncleInclusionReward, unclesReward, uncleCBs, unclesHash) Expect(err).Should(BeNil()) + h.CreatedAt = header.CreatedAt + h.ID = header.ID Expect(header).Should(Equal(h)) }) @@ -269,7 +275,12 @@ var _ = Describe("Manager Test", func() { receipts[1], receipts[0], } - err := manager.UpdateBlocks(context.Background(), newBlocks, newReceipts, events, ModeReOrg) + err := manager.UpdateBlocks(context.Background(), newBlocks, newReceipts, events, &model.Reorg{ + From: blocks[0].Number().Int64(), + To: blocks[len(blocks)-1].Number().Int64(), + FromHash: blocks[0].Hash().Bytes(), + ToHash: blocks[len(blocks)-1].Hash().Bytes(), + }) Expect(err).Should(BeNil()) minerBaseReward, uncleInclusionReward, uncleCBs, unclesReward, unclesHash := common.AccumulateRewards(blocks[0].Header(), blocks[0].Uncles()) @@ -277,7 +288,13 @@ var _ = Describe("Manager Test", func() { Expect(err).Should(BeNil()) h, err := common.Header(newBlocks[0]).AddReward(big.NewInt(20), minerBaseReward, uncleInclusionReward, unclesReward, uncleCBs, unclesHash) Expect(err).Should(BeNil()) + h.CreatedAt = header.CreatedAt + h.ID = header.ID Expect(header).Should(Equal(h)) + reorgStore := reorg.NewWithDB(db) + rs, err := reorgStore.List() + Expect(err).Should(Succeed()) + Expect(len(rs)).Should(BeNumerically("==", 1)) }) It("failed due to wrong signer", func() { @@ -288,7 +305,7 @@ var _ = Describe("Manager Test", func() { types.NewReceipt([]byte{}, false, 0), }) - err := manager.UpdateBlocks(context.Background(), blocks, receipts, events, ModeReOrg) + err := manager.UpdateBlocks(context.Background(), blocks, receipts, events, nil) Expect(err).Should(Equal(common.ErrWrongSigner)) }) }) @@ -318,6 +335,8 @@ var _ = Describe("Manager Test", func() { h, err := common.Header(block).AddReward(big.NewInt(20), minerBaseReward, uncleInclusionReward, unclesReward, uncleCBs, unclesHash) Expect(err).Should(BeNil()) + h.CreatedAt = header.CreatedAt + h.ID = header.ID Expect(header).Should(Equal(h)) } }) @@ -331,6 +350,8 @@ var _ = Describe("Manager Test", func() { h, err := common.Header(blocks[1]).AddReward(big.NewInt(20), minerBaseReward, uncleInclusionReward, unclesReward, uncleCBs, unclesHash) Expect(err).Should(BeNil()) + h.CreatedAt = header.CreatedAt + h.ID = header.ID Expect(header).Should(Equal(h)) }) }) diff --git a/store/transaction/transaction_test.go b/store/transaction/transaction_test.go index 0ca93e68..1772e3cc 100644 --- a/store/transaction/transaction_test.go +++ b/store/transaction/transaction_test.go @@ -34,7 +34,7 @@ func makeTx(blockNum int64, blockHex, txHex string) *model.Transaction { BlockHash: common.HexToBytes(blockHex), From: common.HexToBytes("0xB287a379e6caCa6732E50b88D23c290aA990A892"), Nonce: 10013, - GasPrice: "123456789", + GasPrice: 123456789, GasLimit: 45000, Amount: "4840283445", Payload: []byte{12, 34}, diff --git a/store/transfer_processor.go b/store/transfer_processor.go index 27cf70cd..85d8efdc 100644 --- a/store/transfer_processor.go +++ b/store/transfer_processor.go @@ -107,7 +107,7 @@ func (s *transferProcessor) process(ctx context.Context, events []*model.Transfe return err } - contractsAddrs := make(map[gethCommon.Address]map[gethCommon.Address]struct{}) + balancesByContracts := make(map[gethCommon.Address]map[gethCommon.Address]*big.Int) newSubs := make(map[gethCommon.Address]*model.Subscription) var newAddrs [][]byte for _, sub := range newSubResults { @@ -116,10 +116,10 @@ func (s *transferProcessor) process(ctx context.Context, events []*model.Transfe newSubs[newAddr] = sub // Make sure to collect ETH/ERC20 balances for the new subscriptions too. for token := range s.tokenList { - if contractsAddrs[token] == nil { - contractsAddrs[token] = make(map[gethCommon.Address]struct{}) + if balancesByContracts[token] == nil { + balancesByContracts[token] = make(map[gethCommon.Address]*big.Int) } - contractsAddrs[token][newAddr] = struct{}{} + balancesByContracts[token][newAddr] = new(big.Int) } } @@ -159,16 +159,16 @@ func (s *transferProcessor) process(ctx context.Context, events []*model.Transfe return err } contractAddr := gethCommon.BytesToAddress(e.Address) - if contractsAddrs[contractAddr] == nil { - contractsAddrs[contractAddr] = make(map[gethCommon.Address]struct{}) + if balancesByContracts[contractAddr] == nil { + balancesByContracts[contractAddr] = make(map[gethCommon.Address]*big.Int) } if hasFrom { from := gethCommon.BytesToAddress(e.From) - contractsAddrs[contractAddr][from] = struct{}{} + balancesByContracts[contractAddr][from] = new(big.Int) } if hasTo { to := gethCommon.BytesToAddress(e.To) - contractsAddrs[contractAddr][to] = struct{}{} + balancesByContracts[contractAddr][to] = new(big.Int) } if e.IsMinerRewardEvent() { @@ -206,30 +206,30 @@ func (s *transferProcessor) process(ctx context.Context, events []*model.Transfe } // Assume the tx and receipt are in the same order r := s.receipts[i] - price, _ := new(big.Int).SetString(tx.GasPrice, 10) + price := big.NewInt(tx.GasPrice) fee := new(big.Int).Mul(price, big.NewInt(int64(r.GasUsed))) if feeDiff[from] == nil { feeDiff[from] = new(big.Int).Set(fee) } else { feeDiff[from] = new(big.Int).Add(feeDiff[from], fee) } - if contractsAddrs[model.ETHAddress] == nil { - contractsAddrs[model.ETHAddress] = make(map[gethCommon.Address]struct{}) + if balancesByContracts[model.ETHAddress] == nil { + balancesByContracts[model.ETHAddress] = make(map[gethCommon.Address]*big.Int) } - contractsAddrs[model.ETHAddress][from] = struct{}{} + balancesByContracts[model.ETHAddress][from] = new(big.Int) } // Get balances - results, err := s.balancer.BalanceOf(ctx, big.NewInt(s.blockNumber), contractsAddrs) + err = s.balancer.BalanceOf(ctx, big.NewInt(s.blockNumber), balancesByContracts) if err != nil { - s.logger.Error("Failed to get ERC20 balance with ethclient", "len", len(contractsAddrs), "err", err) + s.logger.Error("Failed to get ERC20 balance with ethclient", "len", len(balancesByContracts), "err", err) return err } // Insert balance and calculate diff to total balances addrDiff := make(map[gethCommon.Address]map[gethCommon.Address]*big.Int) allAddrs := append(addrs, newAddrs...) - for contractAddr, addrs := range results { + for contractAddr, addrs := range balancesByContracts { // Get last recorded balance for these accounts latestBalances, err := s.getLatestBalances(contractAddr, allAddrs) if err != nil { diff --git a/store/transfer_processor_test.go b/store/transfer_processor_test.go index 7ed039c0..86ec496c 100644 --- a/store/transfer_processor_test.go +++ b/store/transfer_processor_test.go @@ -29,6 +29,7 @@ import ( subsStore "github.com/getamis/eth-indexer/store/subscription" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "github.com/stretchr/testify/mock" ) var _ = Describe("Subscription Test", func() { @@ -59,13 +60,19 @@ var _ = Describe("Subscription Test", func() { db.Delete(&model.Header{}) db.Delete(&model.Transaction{}) db.Delete(&model.Receipt{}) - db.Delete(&model.Account{}) + db.Delete(&model.Account{ + ContractAddress: model.ETHBytes, + }) db.Delete(&model.TotalBalance{}) db.Delete(&model.Subscription{}) db.Delete(&model.ERC20{}) + db.Delete(&model.Reorg{}) db.DropTable(model.Transfer{ Address: erc20.Address, }) + db.DropTable(model.Account{ + ContractAddress: erc20.Address, + }) }) It("should be successful", func() { @@ -282,7 +289,7 @@ var _ = Describe("Subscription Test", func() { } ctx := context.Background() - manager = NewManager(db) + manager = NewManager(db, false) err = manager.InsertERC20(erc20) Expect(err).Should(BeNil()) @@ -309,69 +316,35 @@ var _ = Describe("Subscription Test", func() { Expect(err).Should(BeNil()) // For the 100 block - mockBalancer.On("BalanceOf", ctx, big.NewInt(100), map[gethCommon.Address]map[gethCommon.Address]struct{}{ - model.ETHAddress: { - gethCommon.BytesToAddress(subs[0].Address): struct{}{}, - gethCommon.BytesToAddress(subs[1].Address): struct{}{}, - gethCommon.BytesToAddress(subs[2].Address): struct{}{}, - }, - gethCommon.BytesToAddress(erc20.Address): { - gethCommon.BytesToAddress(subs[0].Address): struct{}{}, - gethCommon.BytesToAddress(subs[1].Address): struct{}{}, - gethCommon.BytesToAddress(subs[2].Address): struct{}{}, - }, - }).Return(map[gethCommon.Address]map[gethCommon.Address]*big.Int{ - model.ETHAddress: { - gethCommon.BytesToAddress(subs[0].Address): big.NewInt(999), - gethCommon.BytesToAddress(subs[1].Address): big.NewInt(100), - gethCommon.BytesToAddress(subs[2].Address): big.NewInt(500), - }, - gethCommon.BytesToAddress(erc20.Address): { - gethCommon.BytesToAddress(subs[0].Address): big.NewInt(2000), - gethCommon.BytesToAddress(subs[1].Address): big.NewInt(150), - gethCommon.BytesToAddress(subs[2].Address): big.NewInt(1000), - }, - }, nil).Once() + mockBalancer.On("BalanceOf", ctx, big.NewInt(100), mock.Anything).Run(func(args mock.Arguments) { + result := args.Get(2).(map[gethCommon.Address]map[gethCommon.Address]*big.Int) + result[model.ETHAddress][gethCommon.BytesToAddress(subs[0].Address)] = big.NewInt(999) + result[model.ETHAddress][gethCommon.BytesToAddress(subs[1].Address)] = big.NewInt(100) + result[model.ETHAddress][gethCommon.BytesToAddress(subs[2].Address)] = big.NewInt(500) + result[gethCommon.BytesToAddress(erc20.Address)][gethCommon.BytesToAddress(subs[0].Address)] = big.NewInt(2000) + result[gethCommon.BytesToAddress(erc20.Address)][gethCommon.BytesToAddress(subs[1].Address)] = big.NewInt(150) + result[gethCommon.BytesToAddress(erc20.Address)][gethCommon.BytesToAddress(subs[2].Address)] = big.NewInt(1000) + }).Return(nil).Once() // For the 101 block - mockBalancer.On("BalanceOf", ctx, big.NewInt(101), map[gethCommon.Address]map[gethCommon.Address]struct{}{ - model.ETHAddress: { - gethCommon.BytesToAddress(subs[0].Address): struct{}{}, - gethCommon.BytesToAddress(subs[1].Address): struct{}{}, - gethCommon.BytesToAddress(subs[2].Address): struct{}{}, - }, - gethCommon.BytesToAddress(erc20.Address): { - gethCommon.BytesToAddress(subs[0].Address): struct{}{}, - gethCommon.BytesToAddress(subs[1].Address): struct{}{}, - gethCommon.BytesToAddress(subs[2].Address): struct{}{}, - }, - }).Return(map[gethCommon.Address]map[gethCommon.Address]*big.Int{ - model.ETHAddress: { - gethCommon.BytesToAddress(subs[0].Address): big.NewInt(1000), - gethCommon.BytesToAddress(subs[1].Address): big.NewInt(101), - gethCommon.BytesToAddress(subs[2].Address): big.NewInt(458), - }, - gethCommon.BytesToAddress(erc20.Address): { - gethCommon.BytesToAddress(subs[0].Address): big.NewInt(2000), - gethCommon.BytesToAddress(subs[1].Address): big.NewInt(151), - gethCommon.BytesToAddress(subs[2].Address): big.NewInt(999), - }, - }, nil).Once() + mockBalancer.On("BalanceOf", ctx, big.NewInt(101), mock.Anything).Run(func(args mock.Arguments) { + result := args.Get(2).(map[gethCommon.Address]map[gethCommon.Address]*big.Int) + result[model.ETHAddress][gethCommon.BytesToAddress(subs[0].Address)] = big.NewInt(1000) + result[model.ETHAddress][gethCommon.BytesToAddress(subs[1].Address)] = big.NewInt(101) + result[model.ETHAddress][gethCommon.BytesToAddress(subs[2].Address)] = big.NewInt(458) + result[gethCommon.BytesToAddress(erc20.Address)][gethCommon.BytesToAddress(subs[0].Address)] = big.NewInt(2000) + result[gethCommon.BytesToAddress(erc20.Address)][gethCommon.BytesToAddress(subs[1].Address)] = big.NewInt(151) + result[gethCommon.BytesToAddress(erc20.Address)][gethCommon.BytesToAddress(subs[2].Address)] = big.NewInt(999) + }).Return(nil).Once() // For the 102 block - mockBalancer.On("BalanceOf", ctx, big.NewInt(102), map[gethCommon.Address]map[gethCommon.Address]struct{}{ - model.ETHAddress: { - gethCommon.BytesToAddress(subs[1].Address): struct{}{}, - gethCommon.BytesToAddress(subs[2].Address): struct{}{}, - }, - }).Return(map[gethCommon.Address]map[gethCommon.Address]*big.Int{ - model.ETHAddress: { - gethCommon.BytesToAddress(subs[1].Address): big.NewInt(201), - gethCommon.BytesToAddress(subs[2].Address): big.NewInt(438), - }, - }, nil).Once() + mockBalancer.On("BalanceOf", ctx, big.NewInt(102), mock.Anything).Run(func(args mock.Arguments) { + result := args.Get(2).(map[gethCommon.Address]map[gethCommon.Address]*big.Int) + result[model.ETHAddress][gethCommon.BytesToAddress(subs[1].Address)] = big.NewInt(201) + result[model.ETHAddress][gethCommon.BytesToAddress(subs[2].Address)] = big.NewInt(438) + }).Return(nil).Once() - err = manager.UpdateBlocks(ctx, blocks, receipts, events, ModeReOrg) + err = manager.UpdateBlocks(ctx, blocks, receipts, events, nil) Expect(err).Should(BeNil()) // Verify total balances @@ -534,36 +507,25 @@ var _ = Describe("Subscription Test", func() { {}, } - mockBalancer.On("BalanceOf", ctx, big.NewInt(100), map[gethCommon.Address]map[gethCommon.Address]struct{}{ - model.ETHAddress: { - gethCommon.BytesToAddress(subs[1].Address): struct{}{}, - gethCommon.BytesToAddress(subs[2].Address): struct{}{}, - }, - gethCommon.BytesToAddress(erc20.Address): { - gethCommon.BytesToAddress(subs[1].Address): struct{}{}, - gethCommon.BytesToAddress(subs[2].Address): struct{}{}, - }, - }).Return(map[gethCommon.Address]map[gethCommon.Address]*big.Int{ - model.ETHAddress: { - gethCommon.BytesToAddress(subs[1].Address): big.NewInt(112), - gethCommon.BytesToAddress(subs[2].Address): big.NewInt(113), - }, - gethCommon.BytesToAddress(erc20.Address): { - gethCommon.BytesToAddress(subs[1].Address): big.NewInt(212), - gethCommon.BytesToAddress(subs[2].Address): big.NewInt(213), - }, - }, nil).Once() - - mockBalancer.On("BalanceOf", ctx, big.NewInt(102), map[gethCommon.Address]map[gethCommon.Address]struct{}{ - model.ETHAddress: { - gethCommon.BytesToAddress(subs[0].Address): struct{}{}, - }, - }).Return(map[gethCommon.Address]map[gethCommon.Address]*big.Int{ - model.ETHAddress: { - gethCommon.BytesToAddress(subs[0].Address): big.NewInt(1000), - }, - }, nil).Once() - err = manager.UpdateBlocks(ctx, blocks, receipts, events, ModeReOrg) + mockBalancer.On("BalanceOf", ctx, big.NewInt(100), mock.Anything).Run(func(args mock.Arguments) { + result := args.Get(2).(map[gethCommon.Address]map[gethCommon.Address]*big.Int) + result[model.ETHAddress][gethCommon.BytesToAddress(subs[1].Address)] = big.NewInt(112) + result[model.ETHAddress][gethCommon.BytesToAddress(subs[2].Address)] = big.NewInt(113) + result[gethCommon.BytesToAddress(erc20.Address)][gethCommon.BytesToAddress(subs[1].Address)] = big.NewInt(212) + result[gethCommon.BytesToAddress(erc20.Address)][gethCommon.BytesToAddress(subs[2].Address)] = big.NewInt(213) + }).Return(nil).Once() + + mockBalancer.On("BalanceOf", ctx, big.NewInt(102), mock.Anything).Run(func(args mock.Arguments) { + result := args.Get(2).(map[gethCommon.Address]map[gethCommon.Address]*big.Int) + result[model.ETHAddress][gethCommon.BytesToAddress(subs[0].Address)] = big.NewInt(1000) + }).Return(nil).Once() + + err = manager.UpdateBlocks(ctx, blocks, receipts, events, &model.Reorg{ + From: blocks[0].Number().Int64(), + To: blocks[len(blocks)-1].Number().Int64(), + FromHash: blocks[0].Hash().Bytes(), + ToHash: blocks[len(blocks)-1].Hash().Bytes(), + }) Expect(err).Should(BeNil()) // Verify total balances diff --git a/vendor/github.com/fjl/memsize/LICENSE b/vendor/github.com/fjl/memsize/LICENSE deleted file mode 100644 index 8b804564..00000000 --- a/vendor/github.com/fjl/memsize/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2018 Felix Lange - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/fjl/memsize/bitmap.go b/vendor/github.com/fjl/memsize/bitmap.go deleted file mode 100644 index c3894a24..00000000 --- a/vendor/github.com/fjl/memsize/bitmap.go +++ /dev/null @@ -1,119 +0,0 @@ -package memsize - -import ( - "math/bits" -) - -const ( - uintptrBits = 32 << (uint64(^uintptr(0)) >> 63) - uintptrBytes = uintptrBits / 8 - bmBlockRange = 1 * 1024 * 1024 // bytes covered by bmBlock - bmBlockWords = bmBlockRange / uintptrBits -) - -// bitmap is a sparse bitmap. -type bitmap struct { - blocks map[uintptr]*bmBlock -} - -func newBitmap() *bitmap { - return &bitmap{make(map[uintptr]*bmBlock)} -} - -// markRange sets n consecutive bits starting at addr. -func (b *bitmap) markRange(addr, n uintptr) { - for end := addr + n; addr < end; { - block, baddr := b.block(addr) - for i := baddr; i < bmBlockRange && addr < end; i++ { - block.mark(i) - addr++ - } - } -} - -// isMarked returns the value of the bit at the given address. -func (b *bitmap) isMarked(addr uintptr) bool { - block, baddr := b.block(addr) - return block.isMarked(baddr) -} - -// countRange returns the number of set bits in the range [addr, addr+n]. -func (b *bitmap) countRange(addr, n uintptr) uintptr { - c := uintptr(0) - for end := addr + n; addr < end; { - block, baddr := b.block(addr) - bend := uintptr(bmBlockRange - 1) - if baddr+(end-addr) < bmBlockRange { - bend = baddr + (end - addr) - } - c += uintptr(block.count(baddr, bend)) - // Move addr to next block. - addr += bmBlockRange - baddr - } - return c -} - -// block finds the block corresponding to the given memory address. -// It also returns the block's starting address. -func (b *bitmap) block(addr uintptr) (*bmBlock, uintptr) { - index := addr / bmBlockRange - block := b.blocks[index] - if block == nil { - block = new(bmBlock) - b.blocks[index] = block - } - return block, addr % bmBlockRange -} - -// size returns the sum of the byte sizes of all blocks. -func (b *bitmap) size() uintptr { - return uintptr(len(b.blocks)) * bmBlockWords * uintptrBytes -} - -// utilization returns the mean percentage of one bits across all blocks. -func (b *bitmap) utilization() float32 { - var avg float32 - for _, block := range b.blocks { - avg += float32(block.count(0, bmBlockRange-1)) / float32(bmBlockRange) - } - return avg / float32(len(b.blocks)) -} - -// bmBlock is a bitmap block. -type bmBlock [bmBlockWords]uintptr - -// mark sets the i'th bit to one. -func (b *bmBlock) mark(i uintptr) { - b[i/uintptrBits] |= 1 << (i % uintptrBits) -} - -// isMarked returns the value of the i'th bit. -func (b *bmBlock) isMarked(i uintptr) bool { - return (b[i/uintptrBits] & (1 << (i % uintptrBits))) != 0 -} - -// count returns the number of set bits in the range [start, end]. -func (b *bmBlock) count(start, end uintptr) (count int) { - br := b[start/uintptrBits : end/uintptrBits+1] - for i, w := range br { - if i == 0 { - w &= blockmask(start) - } - if i == len(br)-1 { - w &^= blockmask(end) - } - count += onesCountPtr(w) - } - return count -} - -func blockmask(x uintptr) uintptr { - return ^uintptr(0) << (x % uintptrBits) -} - -func onesCountPtr(x uintptr) int { - if uintptrBits == 64 { - return bits.OnesCount64(uint64(x)) - } - return bits.OnesCount32(uint32(x)) -} diff --git a/vendor/github.com/fjl/memsize/doc.go b/vendor/github.com/fjl/memsize/doc.go deleted file mode 100644 index 640cfba5..00000000 --- a/vendor/github.com/fjl/memsize/doc.go +++ /dev/null @@ -1,16 +0,0 @@ -/* -Package memsize computes the size of your object graph. - -So you made a spiffy algorithm and it works really well, but geez it's using -way too much memory. Where did it all go? memsize to the rescue! - -To get started, find a value that references all your objects and scan it. -This traverses the graph, counting sizes per type. - - sizes := memsize.Scan(myValue) - fmt.Println(sizes.Total) - -memsize can handle cycles just fine and tracks both private and public struct fields. -Unfortunately function closures cannot be inspected in any way. -*/ -package memsize diff --git a/vendor/github.com/fjl/memsize/memsize.go b/vendor/github.com/fjl/memsize/memsize.go deleted file mode 100644 index fcbff1f8..00000000 --- a/vendor/github.com/fjl/memsize/memsize.go +++ /dev/null @@ -1,246 +0,0 @@ -package memsize - -import ( - "bytes" - "fmt" - "reflect" - "sort" - "strings" - "text/tabwriter" - "unsafe" -) - -// Scan traverses all objects reachable from v and counts how much memory -// is used per type. The value must be a non-nil pointer to any value. -func Scan(v interface{}) Sizes { - rv := reflect.ValueOf(v) - if rv.Kind() != reflect.Ptr || rv.IsNil() { - panic("value to scan must be non-nil pointer") - } - - stopTheWorld("memsize scan") - defer startTheWorld() - - ctx := newContext() - ctx.scan(invalidAddr, rv, false) - ctx.s.BitmapSize = ctx.seen.size() - ctx.s.BitmapUtilization = ctx.seen.utilization() - return *ctx.s -} - -// Sizes is the result of a scan. -type Sizes struct { - Total uintptr - ByType map[reflect.Type]*TypeSize - // Internal stats (for debugging) - BitmapSize uintptr - BitmapUtilization float32 -} - -type TypeSize struct { - Total uintptr - Count uintptr -} - -func newSizes() *Sizes { - return &Sizes{ByType: make(map[reflect.Type]*TypeSize)} -} - -// Report returns a human-readable report. -func (s Sizes) Report() string { - type typLine struct { - name string - count uintptr - total uintptr - } - tab := []typLine{{"ALL", 0, s.Total}} - for _, typ := range s.ByType { - tab[0].count += typ.Count - } - maxname := 0 - for typ, s := range s.ByType { - line := typLine{typ.String(), s.Count, s.Total} - tab = append(tab, line) - if len(line.name) > maxname { - maxname = len(line.name) - } - } - sort.Slice(tab, func(i, j int) bool { return tab[i].total > tab[j].total }) - - buf := new(bytes.Buffer) - w := tabwriter.NewWriter(buf, 0, 0, 0, ' ', tabwriter.AlignRight) - for _, line := range tab { - namespace := strings.Repeat(" ", maxname-len(line.name)) - fmt.Fprintf(w, "%s%s\t %v\t %s\t\n", line.name, namespace, line.count, HumanSize(line.total)) - } - w.Flush() - return buf.String() -} - -// addValue is called during scan and adds the memory of given object. -func (s *Sizes) addValue(v reflect.Value, size uintptr) { - s.Total += size - rs := s.ByType[v.Type()] - if rs == nil { - rs = new(TypeSize) - s.ByType[v.Type()] = rs - } - rs.Total += size - rs.Count++ -} - -type context struct { - // We track previously scanned objects to prevent infinite loops - // when scanning cycles and to prevent counting objects more than once. - seen *bitmap - tc typCache - s *Sizes -} - -func newContext() *context { - return &context{seen: newBitmap(), tc: make(typCache), s: newSizes()} -} - -// scan walks all objects below v, determining their size. It returns the size of the -// previously unscanned parts of the object. -func (c *context) scan(addr address, v reflect.Value, add bool) (extraSize uintptr) { - size := v.Type().Size() - var marked uintptr - if addr.valid() { - marked = c.seen.countRange(uintptr(addr), size) - if marked == size { - return 0 // Skip if we have already seen the whole object. - } - c.seen.markRange(uintptr(addr), size) - } - // fmt.Printf("%v: %v ⮑ (marked %d)\n", addr, v.Type(), marked) - if c.tc.needScan(v.Type()) { - extraSize = c.scanContent(addr, v) - } - size -= marked - size += extraSize - // fmt.Printf("%v: %v %d (add %v, size %d, marked %d, extra %d)\n", addr, v.Type(), size+extraSize, add, v.Type().Size(), marked, extraSize) - if add { - c.s.addValue(v, size) - } - return size -} - -// scanContent and all other scan* functions below return the amount of 'extra' memory -// (e.g. slice data) that is referenced by the object. -func (c *context) scanContent(addr address, v reflect.Value) uintptr { - switch v.Kind() { - case reflect.Array: - return c.scanArray(addr, v) - case reflect.Chan: - return c.scanChan(v) - case reflect.Func: - // can't do anything here - return 0 - case reflect.Interface: - return c.scanInterface(v) - case reflect.Map: - return c.scanMap(v) - case reflect.Ptr: - if !v.IsNil() { - c.scan(address(v.Pointer()), v.Elem(), true) - } - return 0 - case reflect.Slice: - return c.scanSlice(v) - case reflect.String: - return uintptr(v.Len()) - case reflect.Struct: - return c.scanStruct(addr, v) - default: - unhandledKind(v.Kind()) - return 0 - } -} - -func (c *context) scanChan(v reflect.Value) uintptr { - etyp := v.Type().Elem() - extra := uintptr(0) - if c.tc.needScan(etyp) { - // Scan the channel buffer. This is unsafe but doesn't race because - // the world is stopped during scan. - hchan := unsafe.Pointer(v.Pointer()) - for i := uint(0); i < uint(v.Cap()); i++ { - addr := chanbuf(hchan, i) - elem := reflect.NewAt(etyp, addr).Elem() - extra += c.scanContent(address(addr), elem) - } - } - return uintptr(v.Cap())*etyp.Size() + extra -} - -func (c *context) scanStruct(base address, v reflect.Value) uintptr { - extra := uintptr(0) - for i := 0; i < v.NumField(); i++ { - f := v.Type().Field(i) - if c.tc.needScan(f.Type) { - addr := base.addOffset(f.Offset) - extra += c.scanContent(addr, v.Field(i)) - } - } - return extra -} - -func (c *context) scanArray(addr address, v reflect.Value) uintptr { - esize := v.Type().Elem().Size() - extra := uintptr(0) - for i := 0; i < v.Len(); i++ { - extra += c.scanContent(addr, v.Index(i)) - addr = addr.addOffset(esize) - } - return extra -} - -func (c *context) scanSlice(v reflect.Value) uintptr { - slice := v.Slice(0, v.Cap()) - esize := slice.Type().Elem().Size() - base := slice.Pointer() - // Add size of the unscanned portion of the backing array to extra. - blen := uintptr(slice.Len()) * esize - marked := c.seen.countRange(base, blen) - extra := blen - marked - c.seen.markRange(uintptr(base), blen) - if c.tc.needScan(slice.Type().Elem()) { - // Elements may contain pointers, scan them individually. - addr := address(base) - for i := 0; i < slice.Len(); i++ { - extra += c.scanContent(addr, slice.Index(i)) - addr = addr.addOffset(esize) - } - } - return extra -} - -func (c *context) scanMap(v reflect.Value) uintptr { - var ( - typ = v.Type() - len = uintptr(v.Len()) - extra = uintptr(0) - ) - if c.tc.needScan(typ.Key()) || c.tc.needScan(typ.Elem()) { - for _, k := range v.MapKeys() { - extra += c.scan(invalidAddr, k, false) - extra += c.scan(invalidAddr, v.MapIndex(k), false) - } - } else { - extra = len*typ.Key().Size() + len*typ.Elem().Size() - } - return extra -} - -func (c *context) scanInterface(v reflect.Value) uintptr { - elem := v.Elem() - if !elem.IsValid() { - return 0 // nil interface - } - extra := c.scan(invalidAddr, elem, false) - if elem.Type().Kind() == reflect.Ptr { - extra -= uintptrBytes - } - return extra -} diff --git a/vendor/github.com/fjl/memsize/memsizeui/template.go b/vendor/github.com/fjl/memsize/memsizeui/template.go deleted file mode 100644 index b60fe6ba..00000000 --- a/vendor/github.com/fjl/memsize/memsizeui/template.go +++ /dev/null @@ -1,106 +0,0 @@ -package memsizeui - -import ( - "html/template" - "strconv" - "sync" - - "github.com/fjl/memsize" -) - -var ( - base *template.Template // the "base" template - baseInitOnce sync.Once -) - -func baseInit() { - base = template.Must(template.New("base").Parse(` - - - - memsize - - - - {{template "content" .}} - -`)) - - base.Funcs(template.FuncMap{ - "quote": strconv.Quote, - "humansize": memsize.HumanSize, - }) - - template.Must(base.New("rootbuttons").Parse(` -Overview -{{- range $root := .Roots -}} -
- -
-{{- end -}}`)) -} - -func contentTemplate(source string) *template.Template { - baseInitOnce.Do(baseInit) - t := template.Must(base.Clone()) - template.Must(t.New("content").Parse(source)) - return t -} - -var rootTemplate = contentTemplate(` -

Memsize

-{{template "rootbuttons" .}} -
-

Reports

- -`) - -var notFoundTemplate = contentTemplate(` -

{{.Data}}

-{{template "rootbuttons" .}} -`) - -var reportTemplate = contentTemplate(` -{{- $report := .Data -}} -

Memsize Report {{$report.ID}}

-
- Overview - -
-
-Root: {{quote $report.RootName}}
-Date: {{$report.Date}}
-Duration: {{$report.Duration}}
-Bitmap Size: {{$report.Sizes.BitmapSize | humansize}}
-Bitmap Utilization: {{$report.Sizes.BitmapUtilization}}
-
-
-
-{{$report.Sizes.Report}}
-
-`) diff --git a/vendor/github.com/fjl/memsize/memsizeui/ui.go b/vendor/github.com/fjl/memsize/memsizeui/ui.go deleted file mode 100644 index c48fc53f..00000000 --- a/vendor/github.com/fjl/memsize/memsizeui/ui.go +++ /dev/null @@ -1,153 +0,0 @@ -package memsizeui - -import ( - "bytes" - "fmt" - "html/template" - "net/http" - "reflect" - "sort" - "strings" - "sync" - "time" - - "github.com/fjl/memsize" -) - -type Handler struct { - init sync.Once - mux http.ServeMux - mu sync.Mutex - reports map[int]Report - roots map[string]interface{} - reportID int -} - -type Report struct { - ID int - Date time.Time - Duration time.Duration - RootName string - Sizes memsize.Sizes -} - -type templateInfo struct { - Roots []string - Reports map[int]Report - PathDepth int - Data interface{} -} - -func (ti *templateInfo) Link(path ...string) string { - prefix := strings.Repeat("../", ti.PathDepth) - return prefix + strings.Join(path, "") -} - -func (h *Handler) Add(name string, v interface{}) { - rv := reflect.ValueOf(v) - if rv.Kind() != reflect.Ptr || rv.IsNil() { - panic("root must be non-nil pointer") - } - h.mu.Lock() - if h.roots == nil { - h.roots = make(map[string]interface{}) - } - h.roots[name] = v - h.mu.Unlock() -} - -func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - h.init.Do(func() { - h.reports = make(map[int]Report) - h.mux.HandleFunc("/", h.handleRoot) - h.mux.HandleFunc("/scan", h.handleScan) - h.mux.HandleFunc("/report/", h.handleReport) - }) - h.mux.ServeHTTP(w, r) -} - -func (h *Handler) templateInfo(r *http.Request, data interface{}) *templateInfo { - h.mu.Lock() - roots := make([]string, 0, len(h.roots)) - for name := range h.roots { - roots = append(roots, name) - } - h.mu.Unlock() - sort.Strings(roots) - - return &templateInfo{ - Roots: roots, - Reports: h.reports, - PathDepth: strings.Count(r.URL.Path, "/") - 1, - Data: data, - } -} - -func (h *Handler) handleRoot(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != "/" { - http.NotFound(w, r) - return - } - serveHTML(w, rootTemplate, http.StatusOK, h.templateInfo(r, nil)) -} - -func (h *Handler) handleScan(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodPost { - http.Error(w, "invalid HTTP method, want POST", http.StatusMethodNotAllowed) - return - } - ti := h.templateInfo(r, "Unknown root") - id, ok := h.scan(r.URL.Query().Get("root")) - if !ok { - serveHTML(w, notFoundTemplate, http.StatusNotFound, ti) - return - } - w.Header().Add("Location", ti.Link(fmt.Sprintf("report/%d", id))) - w.WriteHeader(http.StatusSeeOther) -} - -func (h *Handler) handleReport(w http.ResponseWriter, r *http.Request) { - var id int - fmt.Sscan(strings.TrimPrefix(r.URL.Path, "/report/"), &id) - h.mu.Lock() - report, ok := h.reports[id] - h.mu.Unlock() - - if !ok { - serveHTML(w, notFoundTemplate, http.StatusNotFound, h.templateInfo(r, "Report not found")) - } else { - serveHTML(w, reportTemplate, http.StatusOK, h.templateInfo(r, report)) - } -} - -func (h *Handler) scan(root string) (int, bool) { - h.mu.Lock() - defer h.mu.Unlock() - - val, ok := h.roots[root] - if !ok { - return 0, false - } - id := h.reportID - start := time.Now() - sizes := memsize.Scan(val) - h.reports[id] = Report{ - ID: id, - RootName: root, - Date: start.Truncate(1 * time.Second), - Duration: time.Since(start), - Sizes: sizes, - } - h.reportID++ - return id, true -} - -func serveHTML(w http.ResponseWriter, tpl *template.Template, status int, ti *templateInfo) { - w.Header().Set("content-type", "text/html") - var buf bytes.Buffer - if err := tpl.Execute(&buf, ti); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - buf.WriteTo(w) -} diff --git a/vendor/github.com/fjl/memsize/runtimefunc.go b/vendor/github.com/fjl/memsize/runtimefunc.go deleted file mode 100644 index 912a3e76..00000000 --- a/vendor/github.com/fjl/memsize/runtimefunc.go +++ /dev/null @@ -1,14 +0,0 @@ -package memsize - -import "unsafe" - -var _ = unsafe.Pointer(nil) - -//go:linkname stopTheWorld runtime.stopTheWorld -func stopTheWorld(reason string) - -//go:linkname startTheWorld runtime.startTheWorld -func startTheWorld() - -//go:linkname chanbuf runtime.chanbuf -func chanbuf(ch unsafe.Pointer, i uint) unsafe.Pointer diff --git a/vendor/github.com/fjl/memsize/runtimefunc.s b/vendor/github.com/fjl/memsize/runtimefunc.s deleted file mode 100644 index a091e2fa..00000000 --- a/vendor/github.com/fjl/memsize/runtimefunc.s +++ /dev/null @@ -1 +0,0 @@ -// This file is required to make stub function declarations work. diff --git a/vendor/github.com/fjl/memsize/type.go b/vendor/github.com/fjl/memsize/type.go deleted file mode 100644 index 5d6f59e9..00000000 --- a/vendor/github.com/fjl/memsize/type.go +++ /dev/null @@ -1,119 +0,0 @@ -package memsize - -import ( - "fmt" - "reflect" -) - -// address is a memory location. -// -// Code dealing with uintptr is oblivious to the zero address. -// Code dealing with address is not: it treats the zero address -// as invalid. Offsetting an invalid address doesn't do anything. -// -// This distinction is useful because there are objects that we can't -// get the pointer to. -type address uintptr - -const invalidAddr = address(0) - -func (a address) valid() bool { - return a != 0 -} - -func (a address) addOffset(off uintptr) address { - if !a.valid() { - return invalidAddr - } - return a + address(off) -} - -func (a address) String() string { - if uintptrBits == 32 { - return fmt.Sprintf("%#0.8x", uintptr(a)) - } - return fmt.Sprintf("%#0.16x", uintptr(a)) -} - -type typCache map[reflect.Type]typInfo - -type typInfo struct { - isPointer bool - needScan bool -} - -// isPointer returns true for pointer-ish values. The notion of -// pointer includes everything but plain values, i.e. slices, maps -// channels, interfaces are 'pointer', too. -func (tc *typCache) isPointer(typ reflect.Type) bool { - return tc.info(typ).isPointer -} - -// needScan reports whether a value of the type needs to be scanned -// recursively because it may contain pointers. -func (tc *typCache) needScan(typ reflect.Type) bool { - return tc.info(typ).needScan -} - -func (tc *typCache) info(typ reflect.Type) typInfo { - info, found := (*tc)[typ] - switch { - case found: - return info - case isPointer(typ): - info = typInfo{true, true} - default: - info = typInfo{false, tc.checkNeedScan(typ)} - } - (*tc)[typ] = info - return info -} - -func (tc *typCache) checkNeedScan(typ reflect.Type) bool { - switch k := typ.Kind(); k { - case reflect.Struct: - // Structs don't need scan if none of their fields need it. - for i := 0; i < typ.NumField(); i++ { - if tc.needScan(typ.Field(i).Type) { - return true - } - } - case reflect.Array: - // Arrays don't need scan if their element type doesn't. - return tc.needScan(typ.Elem()) - } - return false -} - -func isPointer(typ reflect.Type) bool { - k := typ.Kind() - switch { - case k <= reflect.Complex128: - return false - case k == reflect.Array: - return false - case k >= reflect.Chan && k <= reflect.String: - return true - case k == reflect.Struct || k == reflect.UnsafePointer: - return false - default: - unhandledKind(k) - return false - } -} - -func unhandledKind(k reflect.Kind) { - panic("unhandled kind " + k.String()) -} - -// HumanSize formats the given number of bytes as a readable string. -func HumanSize(bytes uintptr) string { - switch { - case bytes < 1024: - return fmt.Sprintf("%d B", bytes) - case bytes < 1024*1024: - return fmt.Sprintf("%.3f KB", float64(bytes)/1024) - default: - return fmt.Sprintf("%.3f MB", float64(bytes)/1024/1024) - } -} diff --git a/vendor/github.com/golang/protobuf/AUTHORS b/vendor/github.com/golang/protobuf/AUTHORS deleted file mode 100644 index 15167cd7..00000000 --- a/vendor/github.com/golang/protobuf/AUTHORS +++ /dev/null @@ -1,3 +0,0 @@ -# This source code refers to The Go Authors for copyright purposes. -# The master list of authors is in the main Go distribution, -# visible at http://tip.golang.org/AUTHORS. diff --git a/vendor/github.com/golang/protobuf/CONTRIBUTORS b/vendor/github.com/golang/protobuf/CONTRIBUTORS deleted file mode 100644 index 1c4577e9..00000000 --- a/vendor/github.com/golang/protobuf/CONTRIBUTORS +++ /dev/null @@ -1,3 +0,0 @@ -# This source code was written by the Go contributors. -# The master list of contributors is in the main Go distribution, -# visible at http://tip.golang.org/CONTRIBUTORS. diff --git a/vendor/github.com/golang/protobuf/LICENSE b/vendor/github.com/golang/protobuf/LICENSE deleted file mode 100644 index 0f646931..00000000 --- a/vendor/github.com/golang/protobuf/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Copyright 2010 The Go Authors. 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 Google Inc. 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 -OWNER 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. - diff --git a/vendor/github.com/golang/protobuf/proto/clone.go b/vendor/github.com/golang/protobuf/proto/clone.go deleted file mode 100644 index 3cd3249f..00000000 --- a/vendor/github.com/golang/protobuf/proto/clone.go +++ /dev/null @@ -1,253 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2011 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 -// OWNER 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. - -// Protocol buffer deep copy and merge. -// TODO: RawMessage. - -package proto - -import ( - "fmt" - "log" - "reflect" - "strings" -) - -// Clone returns a deep copy of a protocol buffer. -func Clone(src Message) Message { - in := reflect.ValueOf(src) - if in.IsNil() { - return src - } - out := reflect.New(in.Type().Elem()) - dst := out.Interface().(Message) - Merge(dst, src) - return dst -} - -// Merger is the interface representing objects that can merge messages of the same type. -type Merger interface { - // Merge merges src into this message. - // Required and optional fields that are set in src will be set to that value in dst. - // Elements of repeated fields will be appended. - // - // Merge may panic if called with a different argument type than the receiver. - Merge(src Message) -} - -// generatedMerger is the custom merge method that generated protos will have. -// We must add this method since a generate Merge method will conflict with -// many existing protos that have a Merge data field already defined. -type generatedMerger interface { - XXX_Merge(src Message) -} - -// Merge merges src into dst. -// Required and optional fields that are set in src will be set to that value in dst. -// Elements of repeated fields will be appended. -// Merge panics if src and dst are not the same type, or if dst is nil. -func Merge(dst, src Message) { - if m, ok := dst.(Merger); ok { - m.Merge(src) - return - } - - in := reflect.ValueOf(src) - out := reflect.ValueOf(dst) - if out.IsNil() { - panic("proto: nil destination") - } - if in.Type() != out.Type() { - panic(fmt.Sprintf("proto.Merge(%T, %T) type mismatch", dst, src)) - } - if in.IsNil() { - return // Merge from nil src is a noop - } - if m, ok := dst.(generatedMerger); ok { - m.XXX_Merge(src) - return - } - mergeStruct(out.Elem(), in.Elem()) -} - -func mergeStruct(out, in reflect.Value) { - sprop := GetProperties(in.Type()) - for i := 0; i < in.NumField(); i++ { - f := in.Type().Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i]) - } - - if emIn, err := extendable(in.Addr().Interface()); err == nil { - emOut, _ := extendable(out.Addr().Interface()) - mIn, muIn := emIn.extensionsRead() - if mIn != nil { - mOut := emOut.extensionsWrite() - muIn.Lock() - mergeExtension(mOut, mIn) - muIn.Unlock() - } - } - - uf := in.FieldByName("XXX_unrecognized") - if !uf.IsValid() { - return - } - uin := uf.Bytes() - if len(uin) > 0 { - out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...)) - } -} - -// mergeAny performs a merge between two values of the same type. -// viaPtr indicates whether the values were indirected through a pointer (implying proto2). -// prop is set if this is a struct field (it may be nil). -func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) { - if in.Type() == protoMessageType { - if !in.IsNil() { - if out.IsNil() { - out.Set(reflect.ValueOf(Clone(in.Interface().(Message)))) - } else { - Merge(out.Interface().(Message), in.Interface().(Message)) - } - } - return - } - switch in.Kind() { - case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, - reflect.String, reflect.Uint32, reflect.Uint64: - if !viaPtr && isProto3Zero(in) { - return - } - out.Set(in) - case reflect.Interface: - // Probably a oneof field; copy non-nil values. - if in.IsNil() { - return - } - // Allocate destination if it is not set, or set to a different type. - // Otherwise we will merge as normal. - if out.IsNil() || out.Elem().Type() != in.Elem().Type() { - out.Set(reflect.New(in.Elem().Elem().Type())) // interface -> *T -> T -> new(T) - } - mergeAny(out.Elem(), in.Elem(), false, nil) - case reflect.Map: - if in.Len() == 0 { - return - } - if out.IsNil() { - out.Set(reflect.MakeMap(in.Type())) - } - // For maps with value types of *T or []byte we need to deep copy each value. - elemKind := in.Type().Elem().Kind() - for _, key := range in.MapKeys() { - var val reflect.Value - switch elemKind { - case reflect.Ptr: - val = reflect.New(in.Type().Elem().Elem()) - mergeAny(val, in.MapIndex(key), false, nil) - case reflect.Slice: - val = in.MapIndex(key) - val = reflect.ValueOf(append([]byte{}, val.Bytes()...)) - default: - val = in.MapIndex(key) - } - out.SetMapIndex(key, val) - } - case reflect.Ptr: - if in.IsNil() { - return - } - if out.IsNil() { - out.Set(reflect.New(in.Elem().Type())) - } - mergeAny(out.Elem(), in.Elem(), true, nil) - case reflect.Slice: - if in.IsNil() { - return - } - if in.Type().Elem().Kind() == reflect.Uint8 { - // []byte is a scalar bytes field, not a repeated field. - - // Edge case: if this is in a proto3 message, a zero length - // bytes field is considered the zero value, and should not - // be merged. - if prop != nil && prop.proto3 && in.Len() == 0 { - return - } - - // Make a deep copy. - // Append to []byte{} instead of []byte(nil) so that we never end up - // with a nil result. - out.SetBytes(append([]byte{}, in.Bytes()...)) - return - } - n := in.Len() - if out.IsNil() { - out.Set(reflect.MakeSlice(in.Type(), 0, n)) - } - switch in.Type().Elem().Kind() { - case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, - reflect.String, reflect.Uint32, reflect.Uint64: - out.Set(reflect.AppendSlice(out, in)) - default: - for i := 0; i < n; i++ { - x := reflect.Indirect(reflect.New(in.Type().Elem())) - mergeAny(x, in.Index(i), false, nil) - out.Set(reflect.Append(out, x)) - } - } - case reflect.Struct: - mergeStruct(out, in) - default: - // unknown type, so not a protocol buffer - log.Printf("proto: don't know how to copy %v", in) - } -} - -func mergeExtension(out, in map[int32]Extension) { - for extNum, eIn := range in { - eOut := Extension{desc: eIn.desc} - if eIn.value != nil { - v := reflect.New(reflect.TypeOf(eIn.value)).Elem() - mergeAny(v, reflect.ValueOf(eIn.value), false, nil) - eOut.value = v.Interface() - } - if eIn.enc != nil { - eOut.enc = make([]byte, len(eIn.enc)) - copy(eOut.enc, eIn.enc) - } - - out[extNum] = eOut - } -} diff --git a/vendor/github.com/golang/protobuf/proto/decode.go b/vendor/github.com/golang/protobuf/proto/decode.go deleted file mode 100644 index d9aa3c42..00000000 --- a/vendor/github.com/golang/protobuf/proto/decode.go +++ /dev/null @@ -1,428 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 -// OWNER 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. - -package proto - -/* - * Routines for decoding protocol buffer data to construct in-memory representations. - */ - -import ( - "errors" - "fmt" - "io" -) - -// errOverflow is returned when an integer is too large to be represented. -var errOverflow = errors.New("proto: integer overflow") - -// ErrInternalBadWireType is returned by generated code when an incorrect -// wire type is encountered. It does not get returned to user code. -var ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for oneof") - -// DecodeVarint reads a varint-encoded integer from the slice. -// It returns the integer and the number of bytes consumed, or -// zero if there is not enough. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -func DecodeVarint(buf []byte) (x uint64, n int) { - for shift := uint(0); shift < 64; shift += 7 { - if n >= len(buf) { - return 0, 0 - } - b := uint64(buf[n]) - n++ - x |= (b & 0x7F) << shift - if (b & 0x80) == 0 { - return x, n - } - } - - // The number is too large to represent in a 64-bit value. - return 0, 0 -} - -func (p *Buffer) decodeVarintSlow() (x uint64, err error) { - i := p.index - l := len(p.buf) - - for shift := uint(0); shift < 64; shift += 7 { - if i >= l { - err = io.ErrUnexpectedEOF - return - } - b := p.buf[i] - i++ - x |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - p.index = i - return - } - } - - // The number is too large to represent in a 64-bit value. - err = errOverflow - return -} - -// DecodeVarint reads a varint-encoded integer from the Buffer. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -func (p *Buffer) DecodeVarint() (x uint64, err error) { - i := p.index - buf := p.buf - - if i >= len(buf) { - return 0, io.ErrUnexpectedEOF - } else if buf[i] < 0x80 { - p.index++ - return uint64(buf[i]), nil - } else if len(buf)-i < 10 { - return p.decodeVarintSlow() - } - - var b uint64 - // we already checked the first byte - x = uint64(buf[i]) - 0x80 - i++ - - b = uint64(buf[i]) - i++ - x += b << 7 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 7 - - b = uint64(buf[i]) - i++ - x += b << 14 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 14 - - b = uint64(buf[i]) - i++ - x += b << 21 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 21 - - b = uint64(buf[i]) - i++ - x += b << 28 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 28 - - b = uint64(buf[i]) - i++ - x += b << 35 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 35 - - b = uint64(buf[i]) - i++ - x += b << 42 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 42 - - b = uint64(buf[i]) - i++ - x += b << 49 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 49 - - b = uint64(buf[i]) - i++ - x += b << 56 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 56 - - b = uint64(buf[i]) - i++ - x += b << 63 - if b&0x80 == 0 { - goto done - } - // x -= 0x80 << 63 // Always zero. - - return 0, errOverflow - -done: - p.index = i - return x, nil -} - -// DecodeFixed64 reads a 64-bit integer from the Buffer. -// This is the format for the -// fixed64, sfixed64, and double protocol buffer types. -func (p *Buffer) DecodeFixed64() (x uint64, err error) { - // x, err already 0 - i := p.index + 8 - if i < 0 || i > len(p.buf) { - err = io.ErrUnexpectedEOF - return - } - p.index = i - - x = uint64(p.buf[i-8]) - x |= uint64(p.buf[i-7]) << 8 - x |= uint64(p.buf[i-6]) << 16 - x |= uint64(p.buf[i-5]) << 24 - x |= uint64(p.buf[i-4]) << 32 - x |= uint64(p.buf[i-3]) << 40 - x |= uint64(p.buf[i-2]) << 48 - x |= uint64(p.buf[i-1]) << 56 - return -} - -// DecodeFixed32 reads a 32-bit integer from the Buffer. -// This is the format for the -// fixed32, sfixed32, and float protocol buffer types. -func (p *Buffer) DecodeFixed32() (x uint64, err error) { - // x, err already 0 - i := p.index + 4 - if i < 0 || i > len(p.buf) { - err = io.ErrUnexpectedEOF - return - } - p.index = i - - x = uint64(p.buf[i-4]) - x |= uint64(p.buf[i-3]) << 8 - x |= uint64(p.buf[i-2]) << 16 - x |= uint64(p.buf[i-1]) << 24 - return -} - -// DecodeZigzag64 reads a zigzag-encoded 64-bit integer -// from the Buffer. -// This is the format used for the sint64 protocol buffer type. -func (p *Buffer) DecodeZigzag64() (x uint64, err error) { - x, err = p.DecodeVarint() - if err != nil { - return - } - x = (x >> 1) ^ uint64((int64(x&1)<<63)>>63) - return -} - -// DecodeZigzag32 reads a zigzag-encoded 32-bit integer -// from the Buffer. -// This is the format used for the sint32 protocol buffer type. -func (p *Buffer) DecodeZigzag32() (x uint64, err error) { - x, err = p.DecodeVarint() - if err != nil { - return - } - x = uint64((uint32(x) >> 1) ^ uint32((int32(x&1)<<31)>>31)) - return -} - -// DecodeRawBytes reads a count-delimited byte buffer from the Buffer. -// This is the format used for the bytes protocol buffer -// type and for embedded messages. -func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error) { - n, err := p.DecodeVarint() - if err != nil { - return nil, err - } - - nb := int(n) - if nb < 0 { - return nil, fmt.Errorf("proto: bad byte length %d", nb) - } - end := p.index + nb - if end < p.index || end > len(p.buf) { - return nil, io.ErrUnexpectedEOF - } - - if !alloc { - // todo: check if can get more uses of alloc=false - buf = p.buf[p.index:end] - p.index += nb - return - } - - buf = make([]byte, nb) - copy(buf, p.buf[p.index:]) - p.index += nb - return -} - -// DecodeStringBytes reads an encoded string from the Buffer. -// This is the format used for the proto2 string type. -func (p *Buffer) DecodeStringBytes() (s string, err error) { - buf, err := p.DecodeRawBytes(false) - if err != nil { - return - } - return string(buf), nil -} - -// Unmarshaler is the interface representing objects that can -// unmarshal themselves. The argument points to data that may be -// overwritten, so implementations should not keep references to the -// buffer. -// Unmarshal implementations should not clear the receiver. -// Any unmarshaled data should be merged into the receiver. -// Callers of Unmarshal that do not want to retain existing data -// should Reset the receiver before calling Unmarshal. -type Unmarshaler interface { - Unmarshal([]byte) error -} - -// newUnmarshaler is the interface representing objects that can -// unmarshal themselves. The semantics are identical to Unmarshaler. -// -// This exists to support protoc-gen-go generated messages. -// The proto package will stop type-asserting to this interface in the future. -// -// DO NOT DEPEND ON THIS. -type newUnmarshaler interface { - XXX_Unmarshal([]byte) error -} - -// Unmarshal parses the protocol buffer representation in buf and places the -// decoded result in pb. If the struct underlying pb does not match -// the data in buf, the results can be unpredictable. -// -// Unmarshal resets pb before starting to unmarshal, so any -// existing data in pb is always removed. Use UnmarshalMerge -// to preserve and append to existing data. -func Unmarshal(buf []byte, pb Message) error { - pb.Reset() - if u, ok := pb.(newUnmarshaler); ok { - return u.XXX_Unmarshal(buf) - } - if u, ok := pb.(Unmarshaler); ok { - return u.Unmarshal(buf) - } - return NewBuffer(buf).Unmarshal(pb) -} - -// UnmarshalMerge parses the protocol buffer representation in buf and -// writes the decoded result to pb. If the struct underlying pb does not match -// the data in buf, the results can be unpredictable. -// -// UnmarshalMerge merges into existing data in pb. -// Most code should use Unmarshal instead. -func UnmarshalMerge(buf []byte, pb Message) error { - if u, ok := pb.(newUnmarshaler); ok { - return u.XXX_Unmarshal(buf) - } - if u, ok := pb.(Unmarshaler); ok { - // NOTE: The history of proto have unfortunately been inconsistent - // whether Unmarshaler should or should not implicitly clear itself. - // Some implementations do, most do not. - // Thus, calling this here may or may not do what people want. - // - // See https://github.com/golang/protobuf/issues/424 - return u.Unmarshal(buf) - } - return NewBuffer(buf).Unmarshal(pb) -} - -// DecodeMessage reads a count-delimited message from the Buffer. -func (p *Buffer) DecodeMessage(pb Message) error { - enc, err := p.DecodeRawBytes(false) - if err != nil { - return err - } - return NewBuffer(enc).Unmarshal(pb) -} - -// DecodeGroup reads a tag-delimited group from the Buffer. -// StartGroup tag is already consumed. This function consumes -// EndGroup tag. -func (p *Buffer) DecodeGroup(pb Message) error { - b := p.buf[p.index:] - x, y := findEndGroup(b) - if x < 0 { - return io.ErrUnexpectedEOF - } - err := Unmarshal(b[:x], pb) - p.index += y - return err -} - -// Unmarshal parses the protocol buffer representation in the -// Buffer and places the decoded result in pb. If the struct -// underlying pb does not match the data in the buffer, the results can be -// unpredictable. -// -// Unlike proto.Unmarshal, this does not reset pb before starting to unmarshal. -func (p *Buffer) Unmarshal(pb Message) error { - // If the object can unmarshal itself, let it. - if u, ok := pb.(newUnmarshaler); ok { - err := u.XXX_Unmarshal(p.buf[p.index:]) - p.index = len(p.buf) - return err - } - if u, ok := pb.(Unmarshaler); ok { - // NOTE: The history of proto have unfortunately been inconsistent - // whether Unmarshaler should or should not implicitly clear itself. - // Some implementations do, most do not. - // Thus, calling this here may or may not do what people want. - // - // See https://github.com/golang/protobuf/issues/424 - err := u.Unmarshal(p.buf[p.index:]) - p.index = len(p.buf) - return err - } - - // Slow workaround for messages that aren't Unmarshalers. - // This includes some hand-coded .pb.go files and - // bootstrap protos. - // TODO: fix all of those and then add Unmarshal to - // the Message interface. Then: - // The cast above and code below can be deleted. - // The old unmarshaler can be deleted. - // Clients can call Unmarshal directly (can already do that, actually). - var info InternalMessageInfo - err := info.Unmarshal(pb, p.buf[p.index:]) - p.index = len(p.buf) - return err -} diff --git a/vendor/github.com/golang/protobuf/proto/discard.go b/vendor/github.com/golang/protobuf/proto/discard.go deleted file mode 100644 index dea2617c..00000000 --- a/vendor/github.com/golang/protobuf/proto/discard.go +++ /dev/null @@ -1,350 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2017 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 -// OWNER 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. - -package proto - -import ( - "fmt" - "reflect" - "strings" - "sync" - "sync/atomic" -) - -type generatedDiscarder interface { - XXX_DiscardUnknown() -} - -// DiscardUnknown recursively discards all unknown fields from this message -// and all embedded messages. -// -// When unmarshaling a message with unrecognized fields, the tags and values -// of such fields are preserved in the Message. This allows a later call to -// marshal to be able to produce a message that continues to have those -// unrecognized fields. To avoid this, DiscardUnknown is used to -// explicitly clear the unknown fields after unmarshaling. -// -// For proto2 messages, the unknown fields of message extensions are only -// discarded from messages that have been accessed via GetExtension. -func DiscardUnknown(m Message) { - if m, ok := m.(generatedDiscarder); ok { - m.XXX_DiscardUnknown() - return - } - // TODO: Dynamically populate a InternalMessageInfo for legacy messages, - // but the master branch has no implementation for InternalMessageInfo, - // so it would be more work to replicate that approach. - discardLegacy(m) -} - -// DiscardUnknown recursively discards all unknown fields. -func (a *InternalMessageInfo) DiscardUnknown(m Message) { - di := atomicLoadDiscardInfo(&a.discard) - if di == nil { - di = getDiscardInfo(reflect.TypeOf(m).Elem()) - atomicStoreDiscardInfo(&a.discard, di) - } - di.discard(toPointer(&m)) -} - -type discardInfo struct { - typ reflect.Type - - initialized int32 // 0: only typ is valid, 1: everything is valid - lock sync.Mutex - - fields []discardFieldInfo - unrecognized field -} - -type discardFieldInfo struct { - field field // Offset of field, guaranteed to be valid - discard func(src pointer) -} - -var ( - discardInfoMap = map[reflect.Type]*discardInfo{} - discardInfoLock sync.Mutex -) - -func getDiscardInfo(t reflect.Type) *discardInfo { - discardInfoLock.Lock() - defer discardInfoLock.Unlock() - di := discardInfoMap[t] - if di == nil { - di = &discardInfo{typ: t} - discardInfoMap[t] = di - } - return di -} - -func (di *discardInfo) discard(src pointer) { - if src.isNil() { - return // Nothing to do. - } - - if atomic.LoadInt32(&di.initialized) == 0 { - di.computeDiscardInfo() - } - - for _, fi := range di.fields { - sfp := src.offset(fi.field) - fi.discard(sfp) - } - - // For proto2 messages, only discard unknown fields in message extensions - // that have been accessed via GetExtension. - if em, err := extendable(src.asPointerTo(di.typ).Interface()); err == nil { - // Ignore lock since DiscardUnknown is not concurrency safe. - emm, _ := em.extensionsRead() - for _, mx := range emm { - if m, ok := mx.value.(Message); ok { - DiscardUnknown(m) - } - } - } - - if di.unrecognized.IsValid() { - *src.offset(di.unrecognized).toBytes() = nil - } -} - -func (di *discardInfo) computeDiscardInfo() { - di.lock.Lock() - defer di.lock.Unlock() - if di.initialized != 0 { - return - } - t := di.typ - n := t.NumField() - - for i := 0; i < n; i++ { - f := t.Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - - dfi := discardFieldInfo{field: toField(&f)} - tf := f.Type - - // Unwrap tf to get its most basic type. - var isPointer, isSlice bool - if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 { - isSlice = true - tf = tf.Elem() - } - if tf.Kind() == reflect.Ptr { - isPointer = true - tf = tf.Elem() - } - if isPointer && isSlice && tf.Kind() != reflect.Struct { - panic(fmt.Sprintf("%v.%s cannot be a slice of pointers to primitive types", t, f.Name)) - } - - switch tf.Kind() { - case reflect.Struct: - switch { - case !isPointer: - panic(fmt.Sprintf("%v.%s cannot be a direct struct value", t, f.Name)) - case isSlice: // E.g., []*pb.T - di := getDiscardInfo(tf) - dfi.discard = func(src pointer) { - sps := src.getPointerSlice() - for _, sp := range sps { - if !sp.isNil() { - di.discard(sp) - } - } - } - default: // E.g., *pb.T - di := getDiscardInfo(tf) - dfi.discard = func(src pointer) { - sp := src.getPointer() - if !sp.isNil() { - di.discard(sp) - } - } - } - case reflect.Map: - switch { - case isPointer || isSlice: - panic(fmt.Sprintf("%v.%s cannot be a pointer to a map or a slice of map values", t, f.Name)) - default: // E.g., map[K]V - if tf.Elem().Kind() == reflect.Ptr { // Proto struct (e.g., *T) - dfi.discard = func(src pointer) { - sm := src.asPointerTo(tf).Elem() - if sm.Len() == 0 { - return - } - for _, key := range sm.MapKeys() { - val := sm.MapIndex(key) - DiscardUnknown(val.Interface().(Message)) - } - } - } else { - dfi.discard = func(pointer) {} // Noop - } - } - case reflect.Interface: - // Must be oneof field. - switch { - case isPointer || isSlice: - panic(fmt.Sprintf("%v.%s cannot be a pointer to a interface or a slice of interface values", t, f.Name)) - default: // E.g., interface{} - // TODO: Make this faster? - dfi.discard = func(src pointer) { - su := src.asPointerTo(tf).Elem() - if !su.IsNil() { - sv := su.Elem().Elem().Field(0) - if sv.Kind() == reflect.Ptr && sv.IsNil() { - return - } - switch sv.Type().Kind() { - case reflect.Ptr: // Proto struct (e.g., *T) - DiscardUnknown(sv.Interface().(Message)) - } - } - } - } - default: - continue - } - di.fields = append(di.fields, dfi) - } - - di.unrecognized = invalidField - if f, ok := t.FieldByName("XXX_unrecognized"); ok { - if f.Type != reflect.TypeOf([]byte{}) { - panic("expected XXX_unrecognized to be of type []byte") - } - di.unrecognized = toField(&f) - } - - atomic.StoreInt32(&di.initialized, 1) -} - -func discardLegacy(m Message) { - v := reflect.ValueOf(m) - if v.Kind() != reflect.Ptr || v.IsNil() { - return - } - v = v.Elem() - if v.Kind() != reflect.Struct { - return - } - t := v.Type() - - for i := 0; i < v.NumField(); i++ { - f := t.Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - vf := v.Field(i) - tf := f.Type - - // Unwrap tf to get its most basic type. - var isPointer, isSlice bool - if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 { - isSlice = true - tf = tf.Elem() - } - if tf.Kind() == reflect.Ptr { - isPointer = true - tf = tf.Elem() - } - if isPointer && isSlice && tf.Kind() != reflect.Struct { - panic(fmt.Sprintf("%T.%s cannot be a slice of pointers to primitive types", m, f.Name)) - } - - switch tf.Kind() { - case reflect.Struct: - switch { - case !isPointer: - panic(fmt.Sprintf("%T.%s cannot be a direct struct value", m, f.Name)) - case isSlice: // E.g., []*pb.T - for j := 0; j < vf.Len(); j++ { - discardLegacy(vf.Index(j).Interface().(Message)) - } - default: // E.g., *pb.T - discardLegacy(vf.Interface().(Message)) - } - case reflect.Map: - switch { - case isPointer || isSlice: - panic(fmt.Sprintf("%T.%s cannot be a pointer to a map or a slice of map values", m, f.Name)) - default: // E.g., map[K]V - tv := vf.Type().Elem() - if tv.Kind() == reflect.Ptr && tv.Implements(protoMessageType) { // Proto struct (e.g., *T) - for _, key := range vf.MapKeys() { - val := vf.MapIndex(key) - discardLegacy(val.Interface().(Message)) - } - } - } - case reflect.Interface: - // Must be oneof field. - switch { - case isPointer || isSlice: - panic(fmt.Sprintf("%T.%s cannot be a pointer to a interface or a slice of interface values", m, f.Name)) - default: // E.g., test_proto.isCommunique_Union interface - if !vf.IsNil() && f.Tag.Get("protobuf_oneof") != "" { - vf = vf.Elem() // E.g., *test_proto.Communique_Msg - if !vf.IsNil() { - vf = vf.Elem() // E.g., test_proto.Communique_Msg - vf = vf.Field(0) // E.g., Proto struct (e.g., *T) or primitive value - if vf.Kind() == reflect.Ptr { - discardLegacy(vf.Interface().(Message)) - } - } - } - } - } - } - - if vf := v.FieldByName("XXX_unrecognized"); vf.IsValid() { - if vf.Type() != reflect.TypeOf([]byte{}) { - panic("expected XXX_unrecognized to be of type []byte") - } - vf.Set(reflect.ValueOf([]byte(nil))) - } - - // For proto2 messages, only discard unknown fields in message extensions - // that have been accessed via GetExtension. - if em, err := extendable(m); err == nil { - // Ignore lock since discardLegacy is not concurrency safe. - emm, _ := em.extensionsRead() - for _, mx := range emm { - if m, ok := mx.value.(Message); ok { - discardLegacy(m) - } - } - } -} diff --git a/vendor/github.com/golang/protobuf/proto/encode.go b/vendor/github.com/golang/protobuf/proto/encode.go deleted file mode 100644 index 4c35d337..00000000 --- a/vendor/github.com/golang/protobuf/proto/encode.go +++ /dev/null @@ -1,218 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 -// OWNER 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. - -package proto - -/* - * Routines for encoding data into the wire format for protocol buffers. - */ - -import ( - "errors" - "fmt" - "reflect" -) - -// RequiredNotSetError is an error type returned by either Marshal or Unmarshal. -// Marshal reports this when a required field is not initialized. -// Unmarshal reports this when a required field is missing from the wire data. -type RequiredNotSetError struct { - field string -} - -func (e *RequiredNotSetError) Error() string { - if e.field == "" { - return fmt.Sprintf("proto: required field not set") - } - return fmt.Sprintf("proto: required field %q not set", e.field) -} - -var ( - // errRepeatedHasNil is the error returned if Marshal is called with - // a struct with a repeated field containing a nil element. - errRepeatedHasNil = errors.New("proto: repeated field has nil element") - - // errOneofHasNil is the error returned if Marshal is called with - // a struct with a oneof field containing a nil element. - errOneofHasNil = errors.New("proto: oneof field has nil value") - - // ErrNil is the error returned if Marshal is called with nil. - ErrNil = errors.New("proto: Marshal called with nil") - - // ErrTooLarge is the error returned if Marshal is called with a - // message that encodes to >2GB. - ErrTooLarge = errors.New("proto: message encodes to over 2 GB") -) - -// The fundamental encoders that put bytes on the wire. -// Those that take integer types all accept uint64 and are -// therefore of type valueEncoder. - -const maxVarintBytes = 10 // maximum length of a varint - -// EncodeVarint returns the varint encoding of x. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -// Not used by the package itself, but helpful to clients -// wishing to use the same encoding. -func EncodeVarint(x uint64) []byte { - var buf [maxVarintBytes]byte - var n int - for n = 0; x > 127; n++ { - buf[n] = 0x80 | uint8(x&0x7F) - x >>= 7 - } - buf[n] = uint8(x) - n++ - return buf[0:n] -} - -// EncodeVarint writes a varint-encoded integer to the Buffer. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -func (p *Buffer) EncodeVarint(x uint64) error { - for x >= 1<<7 { - p.buf = append(p.buf, uint8(x&0x7f|0x80)) - x >>= 7 - } - p.buf = append(p.buf, uint8(x)) - return nil -} - -// SizeVarint returns the varint encoding size of an integer. -func SizeVarint(x uint64) int { - switch { - case x < 1<<7: - return 1 - case x < 1<<14: - return 2 - case x < 1<<21: - return 3 - case x < 1<<28: - return 4 - case x < 1<<35: - return 5 - case x < 1<<42: - return 6 - case x < 1<<49: - return 7 - case x < 1<<56: - return 8 - case x < 1<<63: - return 9 - } - return 10 -} - -// EncodeFixed64 writes a 64-bit integer to the Buffer. -// This is the format for the -// fixed64, sfixed64, and double protocol buffer types. -func (p *Buffer) EncodeFixed64(x uint64) error { - p.buf = append(p.buf, - uint8(x), - uint8(x>>8), - uint8(x>>16), - uint8(x>>24), - uint8(x>>32), - uint8(x>>40), - uint8(x>>48), - uint8(x>>56)) - return nil -} - -// EncodeFixed32 writes a 32-bit integer to the Buffer. -// This is the format for the -// fixed32, sfixed32, and float protocol buffer types. -func (p *Buffer) EncodeFixed32(x uint64) error { - p.buf = append(p.buf, - uint8(x), - uint8(x>>8), - uint8(x>>16), - uint8(x>>24)) - return nil -} - -// EncodeZigzag64 writes a zigzag-encoded 64-bit integer -// to the Buffer. -// This is the format used for the sint64 protocol buffer type. -func (p *Buffer) EncodeZigzag64(x uint64) error { - // use signed number to get arithmetic right shift. - return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} - -// EncodeZigzag32 writes a zigzag-encoded 32-bit integer -// to the Buffer. -// This is the format used for the sint32 protocol buffer type. -func (p *Buffer) EncodeZigzag32(x uint64) error { - // use signed number to get arithmetic right shift. - return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31)))) -} - -// EncodeRawBytes writes a count-delimited byte buffer to the Buffer. -// This is the format used for the bytes protocol buffer -// type and for embedded messages. -func (p *Buffer) EncodeRawBytes(b []byte) error { - p.EncodeVarint(uint64(len(b))) - p.buf = append(p.buf, b...) - return nil -} - -// EncodeStringBytes writes an encoded string to the Buffer. -// This is the format used for the proto2 string type. -func (p *Buffer) EncodeStringBytes(s string) error { - p.EncodeVarint(uint64(len(s))) - p.buf = append(p.buf, s...) - return nil -} - -// Marshaler is the interface representing objects that can marshal themselves. -type Marshaler interface { - Marshal() ([]byte, error) -} - -// EncodeMessage writes the protocol buffer to the Buffer, -// prefixed by a varint-encoded length. -func (p *Buffer) EncodeMessage(pb Message) error { - siz := Size(pb) - p.EncodeVarint(uint64(siz)) - return p.Marshal(pb) -} - -// All protocol buffer fields are nillable, but be careful. -func isNil(v reflect.Value) bool { - switch v.Kind() { - case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - return v.IsNil() - } - return false -} diff --git a/vendor/github.com/golang/protobuf/proto/equal.go b/vendor/github.com/golang/protobuf/proto/equal.go deleted file mode 100644 index d4db5a1c..00000000 --- a/vendor/github.com/golang/protobuf/proto/equal.go +++ /dev/null @@ -1,300 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2011 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 -// OWNER 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. - -// Protocol buffer comparison. - -package proto - -import ( - "bytes" - "log" - "reflect" - "strings" -) - -/* -Equal returns true iff protocol buffers a and b are equal. -The arguments must both be pointers to protocol buffer structs. - -Equality is defined in this way: - - Two messages are equal iff they are the same type, - corresponding fields are equal, unknown field sets - are equal, and extensions sets are equal. - - Two set scalar fields are equal iff their values are equal. - If the fields are of a floating-point type, remember that - NaN != x for all x, including NaN. If the message is defined - in a proto3 .proto file, fields are not "set"; specifically, - zero length proto3 "bytes" fields are equal (nil == {}). - - Two repeated fields are equal iff their lengths are the same, - and their corresponding elements are equal. Note a "bytes" field, - although represented by []byte, is not a repeated field and the - rule for the scalar fields described above applies. - - Two unset fields are equal. - - Two unknown field sets are equal if their current - encoded state is equal. - - Two extension sets are equal iff they have corresponding - elements that are pairwise equal. - - Two map fields are equal iff their lengths are the same, - and they contain the same set of elements. Zero-length map - fields are equal. - - Every other combination of things are not equal. - -The return value is undefined if a and b are not protocol buffers. -*/ -func Equal(a, b Message) bool { - if a == nil || b == nil { - return a == b - } - v1, v2 := reflect.ValueOf(a), reflect.ValueOf(b) - if v1.Type() != v2.Type() { - return false - } - if v1.Kind() == reflect.Ptr { - if v1.IsNil() { - return v2.IsNil() - } - if v2.IsNil() { - return false - } - v1, v2 = v1.Elem(), v2.Elem() - } - if v1.Kind() != reflect.Struct { - return false - } - return equalStruct(v1, v2) -} - -// v1 and v2 are known to have the same type. -func equalStruct(v1, v2 reflect.Value) bool { - sprop := GetProperties(v1.Type()) - for i := 0; i < v1.NumField(); i++ { - f := v1.Type().Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - f1, f2 := v1.Field(i), v2.Field(i) - if f.Type.Kind() == reflect.Ptr { - if n1, n2 := f1.IsNil(), f2.IsNil(); n1 && n2 { - // both unset - continue - } else if n1 != n2 { - // set/unset mismatch - return false - } - f1, f2 = f1.Elem(), f2.Elem() - } - if !equalAny(f1, f2, sprop.Prop[i]) { - return false - } - } - - if em1 := v1.FieldByName("XXX_InternalExtensions"); em1.IsValid() { - em2 := v2.FieldByName("XXX_InternalExtensions") - if !equalExtensions(v1.Type(), em1.Interface().(XXX_InternalExtensions), em2.Interface().(XXX_InternalExtensions)) { - return false - } - } - - if em1 := v1.FieldByName("XXX_extensions"); em1.IsValid() { - em2 := v2.FieldByName("XXX_extensions") - if !equalExtMap(v1.Type(), em1.Interface().(map[int32]Extension), em2.Interface().(map[int32]Extension)) { - return false - } - } - - uf := v1.FieldByName("XXX_unrecognized") - if !uf.IsValid() { - return true - } - - u1 := uf.Bytes() - u2 := v2.FieldByName("XXX_unrecognized").Bytes() - return bytes.Equal(u1, u2) -} - -// v1 and v2 are known to have the same type. -// prop may be nil. -func equalAny(v1, v2 reflect.Value, prop *Properties) bool { - if v1.Type() == protoMessageType { - m1, _ := v1.Interface().(Message) - m2, _ := v2.Interface().(Message) - return Equal(m1, m2) - } - switch v1.Kind() { - case reflect.Bool: - return v1.Bool() == v2.Bool() - case reflect.Float32, reflect.Float64: - return v1.Float() == v2.Float() - case reflect.Int32, reflect.Int64: - return v1.Int() == v2.Int() - case reflect.Interface: - // Probably a oneof field; compare the inner values. - n1, n2 := v1.IsNil(), v2.IsNil() - if n1 || n2 { - return n1 == n2 - } - e1, e2 := v1.Elem(), v2.Elem() - if e1.Type() != e2.Type() { - return false - } - return equalAny(e1, e2, nil) - case reflect.Map: - if v1.Len() != v2.Len() { - return false - } - for _, key := range v1.MapKeys() { - val2 := v2.MapIndex(key) - if !val2.IsValid() { - // This key was not found in the second map. - return false - } - if !equalAny(v1.MapIndex(key), val2, nil) { - return false - } - } - return true - case reflect.Ptr: - // Maps may have nil values in them, so check for nil. - if v1.IsNil() && v2.IsNil() { - return true - } - if v1.IsNil() != v2.IsNil() { - return false - } - return equalAny(v1.Elem(), v2.Elem(), prop) - case reflect.Slice: - if v1.Type().Elem().Kind() == reflect.Uint8 { - // short circuit: []byte - - // Edge case: if this is in a proto3 message, a zero length - // bytes field is considered the zero value. - if prop != nil && prop.proto3 && v1.Len() == 0 && v2.Len() == 0 { - return true - } - if v1.IsNil() != v2.IsNil() { - return false - } - return bytes.Equal(v1.Interface().([]byte), v2.Interface().([]byte)) - } - - if v1.Len() != v2.Len() { - return false - } - for i := 0; i < v1.Len(); i++ { - if !equalAny(v1.Index(i), v2.Index(i), prop) { - return false - } - } - return true - case reflect.String: - return v1.Interface().(string) == v2.Interface().(string) - case reflect.Struct: - return equalStruct(v1, v2) - case reflect.Uint32, reflect.Uint64: - return v1.Uint() == v2.Uint() - } - - // unknown type, so not a protocol buffer - log.Printf("proto: don't know how to compare %v", v1) - return false -} - -// base is the struct type that the extensions are based on. -// x1 and x2 are InternalExtensions. -func equalExtensions(base reflect.Type, x1, x2 XXX_InternalExtensions) bool { - em1, _ := x1.extensionsRead() - em2, _ := x2.extensionsRead() - return equalExtMap(base, em1, em2) -} - -func equalExtMap(base reflect.Type, em1, em2 map[int32]Extension) bool { - if len(em1) != len(em2) { - return false - } - - for extNum, e1 := range em1 { - e2, ok := em2[extNum] - if !ok { - return false - } - - m1, m2 := e1.value, e2.value - - if m1 == nil && m2 == nil { - // Both have only encoded form. - if bytes.Equal(e1.enc, e2.enc) { - continue - } - // The bytes are different, but the extensions might still be - // equal. We need to decode them to compare. - } - - if m1 != nil && m2 != nil { - // Both are unencoded. - if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) { - return false - } - continue - } - - // At least one is encoded. To do a semantically correct comparison - // we need to unmarshal them first. - var desc *ExtensionDesc - if m := extensionMaps[base]; m != nil { - desc = m[extNum] - } - if desc == nil { - // If both have only encoded form and the bytes are the same, - // it is handled above. We get here when the bytes are different. - // We don't know how to decode it, so just compare them as byte - // slices. - log.Printf("proto: don't know how to compare extension %d of %v", extNum, base) - return false - } - var err error - if m1 == nil { - m1, err = decodeExtension(e1.enc, desc) - } - if m2 == nil && err == nil { - m2, err = decodeExtension(e2.enc, desc) - } - if err != nil { - // The encoded form is invalid. - log.Printf("proto: badly encoded extension %d of %v: %v", extNum, base, err) - return false - } - if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) { - return false - } - } - - return true -} diff --git a/vendor/github.com/golang/protobuf/proto/extensions.go b/vendor/github.com/golang/protobuf/proto/extensions.go deleted file mode 100644 index 816a3b9d..00000000 --- a/vendor/github.com/golang/protobuf/proto/extensions.go +++ /dev/null @@ -1,543 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 -// OWNER 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. - -package proto - -/* - * Types and routines for supporting protocol buffer extensions. - */ - -import ( - "errors" - "fmt" - "io" - "reflect" - "strconv" - "sync" -) - -// ErrMissingExtension is the error returned by GetExtension if the named extension is not in the message. -var ErrMissingExtension = errors.New("proto: missing extension") - -// ExtensionRange represents a range of message extensions for a protocol buffer. -// Used in code generated by the protocol compiler. -type ExtensionRange struct { - Start, End int32 // both inclusive -} - -// extendableProto is an interface implemented by any protocol buffer generated by the current -// proto compiler that may be extended. -type extendableProto interface { - Message - ExtensionRangeArray() []ExtensionRange - extensionsWrite() map[int32]Extension - extensionsRead() (map[int32]Extension, sync.Locker) -} - -// extendableProtoV1 is an interface implemented by a protocol buffer generated by the previous -// version of the proto compiler that may be extended. -type extendableProtoV1 interface { - Message - ExtensionRangeArray() []ExtensionRange - ExtensionMap() map[int32]Extension -} - -// extensionAdapter is a wrapper around extendableProtoV1 that implements extendableProto. -type extensionAdapter struct { - extendableProtoV1 -} - -func (e extensionAdapter) extensionsWrite() map[int32]Extension { - return e.ExtensionMap() -} - -func (e extensionAdapter) extensionsRead() (map[int32]Extension, sync.Locker) { - return e.ExtensionMap(), notLocker{} -} - -// notLocker is a sync.Locker whose Lock and Unlock methods are nops. -type notLocker struct{} - -func (n notLocker) Lock() {} -func (n notLocker) Unlock() {} - -// extendable returns the extendableProto interface for the given generated proto message. -// If the proto message has the old extension format, it returns a wrapper that implements -// the extendableProto interface. -func extendable(p interface{}) (extendableProto, error) { - switch p := p.(type) { - case extendableProto: - if isNilPtr(p) { - return nil, fmt.Errorf("proto: nil %T is not extendable", p) - } - return p, nil - case extendableProtoV1: - if isNilPtr(p) { - return nil, fmt.Errorf("proto: nil %T is not extendable", p) - } - return extensionAdapter{p}, nil - } - // Don't allocate a specific error containing %T: - // this is the hot path for Clone and MarshalText. - return nil, errNotExtendable -} - -var errNotExtendable = errors.New("proto: not an extendable proto.Message") - -func isNilPtr(x interface{}) bool { - v := reflect.ValueOf(x) - return v.Kind() == reflect.Ptr && v.IsNil() -} - -// XXX_InternalExtensions is an internal representation of proto extensions. -// -// Each generated message struct type embeds an anonymous XXX_InternalExtensions field, -// thus gaining the unexported 'extensions' method, which can be called only from the proto package. -// -// The methods of XXX_InternalExtensions are not concurrency safe in general, -// but calls to logically read-only methods such as has and get may be executed concurrently. -type XXX_InternalExtensions struct { - // The struct must be indirect so that if a user inadvertently copies a - // generated message and its embedded XXX_InternalExtensions, they - // avoid the mayhem of a copied mutex. - // - // The mutex serializes all logically read-only operations to p.extensionMap. - // It is up to the client to ensure that write operations to p.extensionMap are - // mutually exclusive with other accesses. - p *struct { - mu sync.Mutex - extensionMap map[int32]Extension - } -} - -// extensionsWrite returns the extension map, creating it on first use. -func (e *XXX_InternalExtensions) extensionsWrite() map[int32]Extension { - if e.p == nil { - e.p = new(struct { - mu sync.Mutex - extensionMap map[int32]Extension - }) - e.p.extensionMap = make(map[int32]Extension) - } - return e.p.extensionMap -} - -// extensionsRead returns the extensions map for read-only use. It may be nil. -// The caller must hold the returned mutex's lock when accessing Elements within the map. -func (e *XXX_InternalExtensions) extensionsRead() (map[int32]Extension, sync.Locker) { - if e.p == nil { - return nil, nil - } - return e.p.extensionMap, &e.p.mu -} - -// ExtensionDesc represents an extension specification. -// Used in generated code from the protocol compiler. -type ExtensionDesc struct { - ExtendedType Message // nil pointer to the type that is being extended - ExtensionType interface{} // nil pointer to the extension type - Field int32 // field number - Name string // fully-qualified name of extension, for text formatting - Tag string // protobuf tag style - Filename string // name of the file in which the extension is defined -} - -func (ed *ExtensionDesc) repeated() bool { - t := reflect.TypeOf(ed.ExtensionType) - return t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 -} - -// Extension represents an extension in a message. -type Extension struct { - // When an extension is stored in a message using SetExtension - // only desc and value are set. When the message is marshaled - // enc will be set to the encoded form of the message. - // - // When a message is unmarshaled and contains extensions, each - // extension will have only enc set. When such an extension is - // accessed using GetExtension (or GetExtensions) desc and value - // will be set. - desc *ExtensionDesc - value interface{} - enc []byte -} - -// SetRawExtension is for testing only. -func SetRawExtension(base Message, id int32, b []byte) { - epb, err := extendable(base) - if err != nil { - return - } - extmap := epb.extensionsWrite() - extmap[id] = Extension{enc: b} -} - -// isExtensionField returns true iff the given field number is in an extension range. -func isExtensionField(pb extendableProto, field int32) bool { - for _, er := range pb.ExtensionRangeArray() { - if er.Start <= field && field <= er.End { - return true - } - } - return false -} - -// checkExtensionTypes checks that the given extension is valid for pb. -func checkExtensionTypes(pb extendableProto, extension *ExtensionDesc) error { - var pbi interface{} = pb - // Check the extended type. - if ea, ok := pbi.(extensionAdapter); ok { - pbi = ea.extendableProtoV1 - } - if a, b := reflect.TypeOf(pbi), reflect.TypeOf(extension.ExtendedType); a != b { - return fmt.Errorf("proto: bad extended type; %v does not extend %v", b, a) - } - // Check the range. - if !isExtensionField(pb, extension.Field) { - return errors.New("proto: bad extension number; not in declared ranges") - } - return nil -} - -// extPropKey is sufficient to uniquely identify an extension. -type extPropKey struct { - base reflect.Type - field int32 -} - -var extProp = struct { - sync.RWMutex - m map[extPropKey]*Properties -}{ - m: make(map[extPropKey]*Properties), -} - -func extensionProperties(ed *ExtensionDesc) *Properties { - key := extPropKey{base: reflect.TypeOf(ed.ExtendedType), field: ed.Field} - - extProp.RLock() - if prop, ok := extProp.m[key]; ok { - extProp.RUnlock() - return prop - } - extProp.RUnlock() - - extProp.Lock() - defer extProp.Unlock() - // Check again. - if prop, ok := extProp.m[key]; ok { - return prop - } - - prop := new(Properties) - prop.Init(reflect.TypeOf(ed.ExtensionType), "unknown_name", ed.Tag, nil) - extProp.m[key] = prop - return prop -} - -// HasExtension returns whether the given extension is present in pb. -func HasExtension(pb Message, extension *ExtensionDesc) bool { - // TODO: Check types, field numbers, etc.? - epb, err := extendable(pb) - if err != nil { - return false - } - extmap, mu := epb.extensionsRead() - if extmap == nil { - return false - } - mu.Lock() - _, ok := extmap[extension.Field] - mu.Unlock() - return ok -} - -// ClearExtension removes the given extension from pb. -func ClearExtension(pb Message, extension *ExtensionDesc) { - epb, err := extendable(pb) - if err != nil { - return - } - // TODO: Check types, field numbers, etc.? - extmap := epb.extensionsWrite() - delete(extmap, extension.Field) -} - -// GetExtension retrieves a proto2 extended field from pb. -// -// If the descriptor is type complete (i.e., ExtensionDesc.ExtensionType is non-nil), -// then GetExtension parses the encoded field and returns a Go value of the specified type. -// If the field is not present, then the default value is returned (if one is specified), -// otherwise ErrMissingExtension is reported. -// -// If the descriptor is not type complete (i.e., ExtensionDesc.ExtensionType is nil), -// then GetExtension returns the raw encoded bytes of the field extension. -func GetExtension(pb Message, extension *ExtensionDesc) (interface{}, error) { - epb, err := extendable(pb) - if err != nil { - return nil, err - } - - if extension.ExtendedType != nil { - // can only check type if this is a complete descriptor - if err := checkExtensionTypes(epb, extension); err != nil { - return nil, err - } - } - - emap, mu := epb.extensionsRead() - if emap == nil { - return defaultExtensionValue(extension) - } - mu.Lock() - defer mu.Unlock() - e, ok := emap[extension.Field] - if !ok { - // defaultExtensionValue returns the default value or - // ErrMissingExtension if there is no default. - return defaultExtensionValue(extension) - } - - if e.value != nil { - // Already decoded. Check the descriptor, though. - if e.desc != extension { - // This shouldn't happen. If it does, it means that - // GetExtension was called twice with two different - // descriptors with the same field number. - return nil, errors.New("proto: descriptor conflict") - } - return e.value, nil - } - - if extension.ExtensionType == nil { - // incomplete descriptor - return e.enc, nil - } - - v, err := decodeExtension(e.enc, extension) - if err != nil { - return nil, err - } - - // Remember the decoded version and drop the encoded version. - // That way it is safe to mutate what we return. - e.value = v - e.desc = extension - e.enc = nil - emap[extension.Field] = e - return e.value, nil -} - -// defaultExtensionValue returns the default value for extension. -// If no default for an extension is defined ErrMissingExtension is returned. -func defaultExtensionValue(extension *ExtensionDesc) (interface{}, error) { - if extension.ExtensionType == nil { - // incomplete descriptor, so no default - return nil, ErrMissingExtension - } - - t := reflect.TypeOf(extension.ExtensionType) - props := extensionProperties(extension) - - sf, _, err := fieldDefault(t, props) - if err != nil { - return nil, err - } - - if sf == nil || sf.value == nil { - // There is no default value. - return nil, ErrMissingExtension - } - - if t.Kind() != reflect.Ptr { - // We do not need to return a Ptr, we can directly return sf.value. - return sf.value, nil - } - - // We need to return an interface{} that is a pointer to sf.value. - value := reflect.New(t).Elem() - value.Set(reflect.New(value.Type().Elem())) - if sf.kind == reflect.Int32 { - // We may have an int32 or an enum, but the underlying data is int32. - // Since we can't set an int32 into a non int32 reflect.value directly - // set it as a int32. - value.Elem().SetInt(int64(sf.value.(int32))) - } else { - value.Elem().Set(reflect.ValueOf(sf.value)) - } - return value.Interface(), nil -} - -// decodeExtension decodes an extension encoded in b. -func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) { - t := reflect.TypeOf(extension.ExtensionType) - unmarshal := typeUnmarshaler(t, extension.Tag) - - // t is a pointer to a struct, pointer to basic type or a slice. - // Allocate space to store the pointer/slice. - value := reflect.New(t).Elem() - - var err error - for { - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - wire := int(x) & 7 - - b, err = unmarshal(b, valToPointer(value.Addr()), wire) - if err != nil { - return nil, err - } - - if len(b) == 0 { - break - } - } - return value.Interface(), nil -} - -// GetExtensions returns a slice of the extensions present in pb that are also listed in es. -// The returned slice has the same length as es; missing extensions will appear as nil elements. -func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error) { - epb, err := extendable(pb) - if err != nil { - return nil, err - } - extensions = make([]interface{}, len(es)) - for i, e := range es { - extensions[i], err = GetExtension(epb, e) - if err == ErrMissingExtension { - err = nil - } - if err != nil { - return - } - } - return -} - -// ExtensionDescs returns a new slice containing pb's extension descriptors, in undefined order. -// For non-registered extensions, ExtensionDescs returns an incomplete descriptor containing -// just the Field field, which defines the extension's field number. -func ExtensionDescs(pb Message) ([]*ExtensionDesc, error) { - epb, err := extendable(pb) - if err != nil { - return nil, err - } - registeredExtensions := RegisteredExtensions(pb) - - emap, mu := epb.extensionsRead() - if emap == nil { - return nil, nil - } - mu.Lock() - defer mu.Unlock() - extensions := make([]*ExtensionDesc, 0, len(emap)) - for extid, e := range emap { - desc := e.desc - if desc == nil { - desc = registeredExtensions[extid] - if desc == nil { - desc = &ExtensionDesc{Field: extid} - } - } - - extensions = append(extensions, desc) - } - return extensions, nil -} - -// SetExtension sets the specified extension of pb to the specified value. -func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error { - epb, err := extendable(pb) - if err != nil { - return err - } - if err := checkExtensionTypes(epb, extension); err != nil { - return err - } - typ := reflect.TypeOf(extension.ExtensionType) - if typ != reflect.TypeOf(value) { - return errors.New("proto: bad extension value type") - } - // nil extension values need to be caught early, because the - // encoder can't distinguish an ErrNil due to a nil extension - // from an ErrNil due to a missing field. Extensions are - // always optional, so the encoder would just swallow the error - // and drop all the extensions from the encoded message. - if reflect.ValueOf(value).IsNil() { - return fmt.Errorf("proto: SetExtension called with nil value of type %T", value) - } - - extmap := epb.extensionsWrite() - extmap[extension.Field] = Extension{desc: extension, value: value} - return nil -} - -// ClearAllExtensions clears all extensions from pb. -func ClearAllExtensions(pb Message) { - epb, err := extendable(pb) - if err != nil { - return - } - m := epb.extensionsWrite() - for k := range m { - delete(m, k) - } -} - -// A global registry of extensions. -// The generated code will register the generated descriptors by calling RegisterExtension. - -var extensionMaps = make(map[reflect.Type]map[int32]*ExtensionDesc) - -// RegisterExtension is called from the generated code. -func RegisterExtension(desc *ExtensionDesc) { - st := reflect.TypeOf(desc.ExtendedType).Elem() - m := extensionMaps[st] - if m == nil { - m = make(map[int32]*ExtensionDesc) - extensionMaps[st] = m - } - if _, ok := m[desc.Field]; ok { - panic("proto: duplicate extension registered: " + st.String() + " " + strconv.Itoa(int(desc.Field))) - } - m[desc.Field] = desc -} - -// RegisteredExtensions returns a map of the registered extensions of a -// protocol buffer struct, indexed by the extension number. -// The argument pb should be a nil pointer to the struct type. -func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc { - return extensionMaps[reflect.TypeOf(pb).Elem()] -} diff --git a/vendor/github.com/golang/protobuf/proto/lib.go b/vendor/github.com/golang/protobuf/proto/lib.go deleted file mode 100644 index 0e2191b8..00000000 --- a/vendor/github.com/golang/protobuf/proto/lib.go +++ /dev/null @@ -1,921 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 -// OWNER 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. - -/* -Package proto converts data structures to and from the wire format of -protocol buffers. It works in concert with the Go source code generated -for .proto files by the protocol compiler. - -A summary of the properties of the protocol buffer interface -for a protocol buffer variable v: - - - Names are turned from camel_case to CamelCase for export. - - There are no methods on v to set fields; just treat - them as structure fields. - - There are getters that return a field's value if set, - and return the field's default value if unset. - The getters work even if the receiver is a nil message. - - The zero value for a struct is its correct initialization state. - All desired fields must be set before marshaling. - - A Reset() method will restore a protobuf struct to its zero state. - - Non-repeated fields are pointers to the values; nil means unset. - That is, optional or required field int32 f becomes F *int32. - - Repeated fields are slices. - - Helper functions are available to aid the setting of fields. - msg.Foo = proto.String("hello") // set field - - Constants are defined to hold the default values of all fields that - have them. They have the form Default_StructName_FieldName. - Because the getter methods handle defaulted values, - direct use of these constants should be rare. - - Enums are given type names and maps from names to values. - Enum values are prefixed by the enclosing message's name, or by the - enum's type name if it is a top-level enum. Enum types have a String - method, and a Enum method to assist in message construction. - - Nested messages, groups and enums have type names prefixed with the name of - the surrounding message type. - - Extensions are given descriptor names that start with E_, - followed by an underscore-delimited list of the nested messages - that contain it (if any) followed by the CamelCased name of the - extension field itself. HasExtension, ClearExtension, GetExtension - and SetExtension are functions for manipulating extensions. - - Oneof field sets are given a single field in their message, - with distinguished wrapper types for each possible field value. - - Marshal and Unmarshal are functions to encode and decode the wire format. - -When the .proto file specifies `syntax="proto3"`, there are some differences: - - - Non-repeated fields of non-message type are values instead of pointers. - - Enum types do not get an Enum method. - -The simplest way to describe this is to see an example. -Given file test.proto, containing - - package example; - - enum FOO { X = 17; } - - message Test { - required string label = 1; - optional int32 type = 2 [default=77]; - repeated int64 reps = 3; - optional group OptionalGroup = 4 { - required string RequiredField = 5; - } - oneof union { - int32 number = 6; - string name = 7; - } - } - -The resulting file, test.pb.go, is: - - package example - - import proto "github.com/golang/protobuf/proto" - import math "math" - - type FOO int32 - const ( - FOO_X FOO = 17 - ) - var FOO_name = map[int32]string{ - 17: "X", - } - var FOO_value = map[string]int32{ - "X": 17, - } - - func (x FOO) Enum() *FOO { - p := new(FOO) - *p = x - return p - } - func (x FOO) String() string { - return proto.EnumName(FOO_name, int32(x)) - } - func (x *FOO) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FOO_value, data) - if err != nil { - return err - } - *x = FOO(value) - return nil - } - - type Test struct { - Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"` - Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"` - Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"` - Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"` - // Types that are valid to be assigned to Union: - // *Test_Number - // *Test_Name - Union isTest_Union `protobuf_oneof:"union"` - XXX_unrecognized []byte `json:"-"` - } - func (m *Test) Reset() { *m = Test{} } - func (m *Test) String() string { return proto.CompactTextString(m) } - func (*Test) ProtoMessage() {} - - type isTest_Union interface { - isTest_Union() - } - - type Test_Number struct { - Number int32 `protobuf:"varint,6,opt,name=number"` - } - type Test_Name struct { - Name string `protobuf:"bytes,7,opt,name=name"` - } - - func (*Test_Number) isTest_Union() {} - func (*Test_Name) isTest_Union() {} - - func (m *Test) GetUnion() isTest_Union { - if m != nil { - return m.Union - } - return nil - } - const Default_Test_Type int32 = 77 - - func (m *Test) GetLabel() string { - if m != nil && m.Label != nil { - return *m.Label - } - return "" - } - - func (m *Test) GetType() int32 { - if m != nil && m.Type != nil { - return *m.Type - } - return Default_Test_Type - } - - func (m *Test) GetOptionalgroup() *Test_OptionalGroup { - if m != nil { - return m.Optionalgroup - } - return nil - } - - type Test_OptionalGroup struct { - RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"` - } - func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} } - func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) } - - func (m *Test_OptionalGroup) GetRequiredField() string { - if m != nil && m.RequiredField != nil { - return *m.RequiredField - } - return "" - } - - func (m *Test) GetNumber() int32 { - if x, ok := m.GetUnion().(*Test_Number); ok { - return x.Number - } - return 0 - } - - func (m *Test) GetName() string { - if x, ok := m.GetUnion().(*Test_Name); ok { - return x.Name - } - return "" - } - - func init() { - proto.RegisterEnum("example.FOO", FOO_name, FOO_value) - } - -To create and play with a Test object: - - package main - - import ( - "log" - - "github.com/golang/protobuf/proto" - pb "./example.pb" - ) - - func main() { - test := &pb.Test{ - Label: proto.String("hello"), - Type: proto.Int32(17), - Reps: []int64{1, 2, 3}, - Optionalgroup: &pb.Test_OptionalGroup{ - RequiredField: proto.String("good bye"), - }, - Union: &pb.Test_Name{"fred"}, - } - data, err := proto.Marshal(test) - if err != nil { - log.Fatal("marshaling error: ", err) - } - newTest := &pb.Test{} - err = proto.Unmarshal(data, newTest) - if err != nil { - log.Fatal("unmarshaling error: ", err) - } - // Now test and newTest contain the same data. - if test.GetLabel() != newTest.GetLabel() { - log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel()) - } - // Use a type switch to determine which oneof was set. - switch u := test.Union.(type) { - case *pb.Test_Number: // u.Number contains the number. - case *pb.Test_Name: // u.Name contains the string. - } - // etc. - } -*/ -package proto - -import ( - "encoding/json" - "errors" - "fmt" - "log" - "reflect" - "sort" - "strconv" - "sync" -) - -var errInvalidUTF8 = errors.New("proto: invalid UTF-8 string") - -// Message is implemented by generated protocol buffer messages. -type Message interface { - Reset() - String() string - ProtoMessage() -} - -// Stats records allocation details about the protocol buffer encoders -// and decoders. Useful for tuning the library itself. -type Stats struct { - Emalloc uint64 // mallocs in encode - Dmalloc uint64 // mallocs in decode - Encode uint64 // number of encodes - Decode uint64 // number of decodes - Chit uint64 // number of cache hits - Cmiss uint64 // number of cache misses - Size uint64 // number of sizes -} - -// Set to true to enable stats collection. -const collectStats = false - -var stats Stats - -// GetStats returns a copy of the global Stats structure. -func GetStats() Stats { return stats } - -// A Buffer is a buffer manager for marshaling and unmarshaling -// protocol buffers. It may be reused between invocations to -// reduce memory usage. It is not necessary to use a Buffer; -// the global functions Marshal and Unmarshal create a -// temporary Buffer and are fine for most applications. -type Buffer struct { - buf []byte // encode/decode byte stream - index int // read point - - deterministic bool -} - -// NewBuffer allocates a new Buffer and initializes its internal data to -// the contents of the argument slice. -func NewBuffer(e []byte) *Buffer { - return &Buffer{buf: e} -} - -// Reset resets the Buffer, ready for marshaling a new protocol buffer. -func (p *Buffer) Reset() { - p.buf = p.buf[0:0] // for reading/writing - p.index = 0 // for reading -} - -// SetBuf replaces the internal buffer with the slice, -// ready for unmarshaling the contents of the slice. -func (p *Buffer) SetBuf(s []byte) { - p.buf = s - p.index = 0 -} - -// Bytes returns the contents of the Buffer. -func (p *Buffer) Bytes() []byte { return p.buf } - -// SetDeterministic sets whether to use deterministic serialization. -// -// Deterministic serialization guarantees that for a given binary, equal -// messages will always be serialized to the same bytes. This implies: -// -// - Repeated serialization of a message will return the same bytes. -// - Different processes of the same binary (which may be executing on -// different machines) will serialize equal messages to the same bytes. -// -// Note that the deterministic serialization is NOT canonical across -// languages. It is not guaranteed to remain stable over time. It is unstable -// across different builds with schema changes due to unknown fields. -// Users who need canonical serialization (e.g., persistent storage in a -// canonical form, fingerprinting, etc.) should define their own -// canonicalization specification and implement their own serializer rather -// than relying on this API. -// -// If deterministic serialization is requested, map entries will be sorted -// by keys in lexographical order. This is an implementation detail and -// subject to change. -func (p *Buffer) SetDeterministic(deterministic bool) { - p.deterministic = deterministic -} - -/* - * Helper routines for simplifying the creation of optional fields of basic type. - */ - -// Bool is a helper routine that allocates a new bool value -// to store v and returns a pointer to it. -func Bool(v bool) *bool { - return &v -} - -// Int32 is a helper routine that allocates a new int32 value -// to store v and returns a pointer to it. -func Int32(v int32) *int32 { - return &v -} - -// Int is a helper routine that allocates a new int32 value -// to store v and returns a pointer to it, but unlike Int32 -// its argument value is an int. -func Int(v int) *int32 { - p := new(int32) - *p = int32(v) - return p -} - -// Int64 is a helper routine that allocates a new int64 value -// to store v and returns a pointer to it. -func Int64(v int64) *int64 { - return &v -} - -// Float32 is a helper routine that allocates a new float32 value -// to store v and returns a pointer to it. -func Float32(v float32) *float32 { - return &v -} - -// Float64 is a helper routine that allocates a new float64 value -// to store v and returns a pointer to it. -func Float64(v float64) *float64 { - return &v -} - -// Uint32 is a helper routine that allocates a new uint32 value -// to store v and returns a pointer to it. -func Uint32(v uint32) *uint32 { - return &v -} - -// Uint64 is a helper routine that allocates a new uint64 value -// to store v and returns a pointer to it. -func Uint64(v uint64) *uint64 { - return &v -} - -// String is a helper routine that allocates a new string value -// to store v and returns a pointer to it. -func String(v string) *string { - return &v -} - -// EnumName is a helper function to simplify printing protocol buffer enums -// by name. Given an enum map and a value, it returns a useful string. -func EnumName(m map[int32]string, v int32) string { - s, ok := m[v] - if ok { - return s - } - return strconv.Itoa(int(v)) -} - -// UnmarshalJSONEnum is a helper function to simplify recovering enum int values -// from their JSON-encoded representation. Given a map from the enum's symbolic -// names to its int values, and a byte buffer containing the JSON-encoded -// value, it returns an int32 that can be cast to the enum type by the caller. -// -// The function can deal with both JSON representations, numeric and symbolic. -func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) { - if data[0] == '"' { - // New style: enums are strings. - var repr string - if err := json.Unmarshal(data, &repr); err != nil { - return -1, err - } - val, ok := m[repr] - if !ok { - return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr) - } - return val, nil - } - // Old style: enums are ints. - var val int32 - if err := json.Unmarshal(data, &val); err != nil { - return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName) - } - return val, nil -} - -// DebugPrint dumps the encoded data in b in a debugging format with a header -// including the string s. Used in testing but made available for general debugging. -func (p *Buffer) DebugPrint(s string, b []byte) { - var u uint64 - - obuf := p.buf - index := p.index - p.buf = b - p.index = 0 - depth := 0 - - fmt.Printf("\n--- %s ---\n", s) - -out: - for { - for i := 0; i < depth; i++ { - fmt.Print(" ") - } - - index := p.index - if index == len(p.buf) { - break - } - - op, err := p.DecodeVarint() - if err != nil { - fmt.Printf("%3d: fetching op err %v\n", index, err) - break out - } - tag := op >> 3 - wire := op & 7 - - switch wire { - default: - fmt.Printf("%3d: t=%3d unknown wire=%d\n", - index, tag, wire) - break out - - case WireBytes: - var r []byte - - r, err = p.DecodeRawBytes(false) - if err != nil { - break out - } - fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r)) - if len(r) <= 6 { - for i := 0; i < len(r); i++ { - fmt.Printf(" %.2x", r[i]) - } - } else { - for i := 0; i < 3; i++ { - fmt.Printf(" %.2x", r[i]) - } - fmt.Printf(" ..") - for i := len(r) - 3; i < len(r); i++ { - fmt.Printf(" %.2x", r[i]) - } - } - fmt.Printf("\n") - - case WireFixed32: - u, err = p.DecodeFixed32() - if err != nil { - fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err) - break out - } - fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u) - - case WireFixed64: - u, err = p.DecodeFixed64() - if err != nil { - fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err) - break out - } - fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u) - - case WireVarint: - u, err = p.DecodeVarint() - if err != nil { - fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err) - break out - } - fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u) - - case WireStartGroup: - fmt.Printf("%3d: t=%3d start\n", index, tag) - depth++ - - case WireEndGroup: - depth-- - fmt.Printf("%3d: t=%3d end\n", index, tag) - } - } - - if depth != 0 { - fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth) - } - fmt.Printf("\n") - - p.buf = obuf - p.index = index -} - -// SetDefaults sets unset protocol buffer fields to their default values. -// It only modifies fields that are both unset and have defined defaults. -// It recursively sets default values in any non-nil sub-messages. -func SetDefaults(pb Message) { - setDefaults(reflect.ValueOf(pb), true, false) -} - -// v is a pointer to a struct. -func setDefaults(v reflect.Value, recur, zeros bool) { - v = v.Elem() - - defaultMu.RLock() - dm, ok := defaults[v.Type()] - defaultMu.RUnlock() - if !ok { - dm = buildDefaultMessage(v.Type()) - defaultMu.Lock() - defaults[v.Type()] = dm - defaultMu.Unlock() - } - - for _, sf := range dm.scalars { - f := v.Field(sf.index) - if !f.IsNil() { - // field already set - continue - } - dv := sf.value - if dv == nil && !zeros { - // no explicit default, and don't want to set zeros - continue - } - fptr := f.Addr().Interface() // **T - // TODO: Consider batching the allocations we do here. - switch sf.kind { - case reflect.Bool: - b := new(bool) - if dv != nil { - *b = dv.(bool) - } - *(fptr.(**bool)) = b - case reflect.Float32: - f := new(float32) - if dv != nil { - *f = dv.(float32) - } - *(fptr.(**float32)) = f - case reflect.Float64: - f := new(float64) - if dv != nil { - *f = dv.(float64) - } - *(fptr.(**float64)) = f - case reflect.Int32: - // might be an enum - if ft := f.Type(); ft != int32PtrType { - // enum - f.Set(reflect.New(ft.Elem())) - if dv != nil { - f.Elem().SetInt(int64(dv.(int32))) - } - } else { - // int32 field - i := new(int32) - if dv != nil { - *i = dv.(int32) - } - *(fptr.(**int32)) = i - } - case reflect.Int64: - i := new(int64) - if dv != nil { - *i = dv.(int64) - } - *(fptr.(**int64)) = i - case reflect.String: - s := new(string) - if dv != nil { - *s = dv.(string) - } - *(fptr.(**string)) = s - case reflect.Uint8: - // exceptional case: []byte - var b []byte - if dv != nil { - db := dv.([]byte) - b = make([]byte, len(db)) - copy(b, db) - } else { - b = []byte{} - } - *(fptr.(*[]byte)) = b - case reflect.Uint32: - u := new(uint32) - if dv != nil { - *u = dv.(uint32) - } - *(fptr.(**uint32)) = u - case reflect.Uint64: - u := new(uint64) - if dv != nil { - *u = dv.(uint64) - } - *(fptr.(**uint64)) = u - default: - log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind) - } - } - - for _, ni := range dm.nested { - f := v.Field(ni) - // f is *T or []*T or map[T]*T - switch f.Kind() { - case reflect.Ptr: - if f.IsNil() { - continue - } - setDefaults(f, recur, zeros) - - case reflect.Slice: - for i := 0; i < f.Len(); i++ { - e := f.Index(i) - if e.IsNil() { - continue - } - setDefaults(e, recur, zeros) - } - - case reflect.Map: - for _, k := range f.MapKeys() { - e := f.MapIndex(k) - if e.IsNil() { - continue - } - setDefaults(e, recur, zeros) - } - } - } -} - -var ( - // defaults maps a protocol buffer struct type to a slice of the fields, - // with its scalar fields set to their proto-declared non-zero default values. - defaultMu sync.RWMutex - defaults = make(map[reflect.Type]defaultMessage) - - int32PtrType = reflect.TypeOf((*int32)(nil)) -) - -// defaultMessage represents information about the default values of a message. -type defaultMessage struct { - scalars []scalarField - nested []int // struct field index of nested messages -} - -type scalarField struct { - index int // struct field index - kind reflect.Kind // element type (the T in *T or []T) - value interface{} // the proto-declared default value, or nil -} - -// t is a struct type. -func buildDefaultMessage(t reflect.Type) (dm defaultMessage) { - sprop := GetProperties(t) - for _, prop := range sprop.Prop { - fi, ok := sprop.decoderTags.get(prop.Tag) - if !ok { - // XXX_unrecognized - continue - } - ft := t.Field(fi).Type - - sf, nested, err := fieldDefault(ft, prop) - switch { - case err != nil: - log.Print(err) - case nested: - dm.nested = append(dm.nested, fi) - case sf != nil: - sf.index = fi - dm.scalars = append(dm.scalars, *sf) - } - } - - return dm -} - -// fieldDefault returns the scalarField for field type ft. -// sf will be nil if the field can not have a default. -// nestedMessage will be true if this is a nested message. -// Note that sf.index is not set on return. -func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) { - var canHaveDefault bool - switch ft.Kind() { - case reflect.Ptr: - if ft.Elem().Kind() == reflect.Struct { - nestedMessage = true - } else { - canHaveDefault = true // proto2 scalar field - } - - case reflect.Slice: - switch ft.Elem().Kind() { - case reflect.Ptr: - nestedMessage = true // repeated message - case reflect.Uint8: - canHaveDefault = true // bytes field - } - - case reflect.Map: - if ft.Elem().Kind() == reflect.Ptr { - nestedMessage = true // map with message values - } - } - - if !canHaveDefault { - if nestedMessage { - return nil, true, nil - } - return nil, false, nil - } - - // We now know that ft is a pointer or slice. - sf = &scalarField{kind: ft.Elem().Kind()} - - // scalar fields without defaults - if !prop.HasDefault { - return sf, false, nil - } - - // a scalar field: either *T or []byte - switch ft.Elem().Kind() { - case reflect.Bool: - x, err := strconv.ParseBool(prop.Default) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err) - } - sf.value = x - case reflect.Float32: - x, err := strconv.ParseFloat(prop.Default, 32) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err) - } - sf.value = float32(x) - case reflect.Float64: - x, err := strconv.ParseFloat(prop.Default, 64) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err) - } - sf.value = x - case reflect.Int32: - x, err := strconv.ParseInt(prop.Default, 10, 32) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err) - } - sf.value = int32(x) - case reflect.Int64: - x, err := strconv.ParseInt(prop.Default, 10, 64) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err) - } - sf.value = x - case reflect.String: - sf.value = prop.Default - case reflect.Uint8: - // []byte (not *uint8) - sf.value = []byte(prop.Default) - case reflect.Uint32: - x, err := strconv.ParseUint(prop.Default, 10, 32) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err) - } - sf.value = uint32(x) - case reflect.Uint64: - x, err := strconv.ParseUint(prop.Default, 10, 64) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err) - } - sf.value = x - default: - return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind()) - } - - return sf, false, nil -} - -// mapKeys returns a sort.Interface to be used for sorting the map keys. -// Map fields may have key types of non-float scalars, strings and enums. -func mapKeys(vs []reflect.Value) sort.Interface { - s := mapKeySorter{vs: vs} - - // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps. - if len(vs) == 0 { - return s - } - switch vs[0].Kind() { - case reflect.Int32, reflect.Int64: - s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() } - case reflect.Uint32, reflect.Uint64: - s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() } - case reflect.Bool: - s.less = func(a, b reflect.Value) bool { return !a.Bool() && b.Bool() } // false < true - case reflect.String: - s.less = func(a, b reflect.Value) bool { return a.String() < b.String() } - default: - panic(fmt.Sprintf("unsupported map key type: %v", vs[0].Kind())) - } - - return s -} - -type mapKeySorter struct { - vs []reflect.Value - less func(a, b reflect.Value) bool -} - -func (s mapKeySorter) Len() int { return len(s.vs) } -func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] } -func (s mapKeySorter) Less(i, j int) bool { - return s.less(s.vs[i], s.vs[j]) -} - -// isProto3Zero reports whether v is a zero proto3 value. -func isProto3Zero(v reflect.Value) bool { - switch v.Kind() { - case reflect.Bool: - return !v.Bool() - case reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint32, reflect.Uint64: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.String: - return v.String() == "" - } - return false -} - -// ProtoPackageIsVersion2 is referenced from generated protocol buffer files -// to assert that that code is compatible with this version of the proto package. -const ProtoPackageIsVersion2 = true - -// ProtoPackageIsVersion1 is referenced from generated protocol buffer files -// to assert that that code is compatible with this version of the proto package. -const ProtoPackageIsVersion1 = true - -// InternalMessageInfo is a type used internally by generated .pb.go files. -// This type is not intended to be used by non-generated code. -// This type is not subject to any compatibility guarantee. -type InternalMessageInfo struct { - marshal *marshalInfo - unmarshal *unmarshalInfo - merge *mergeInfo - discard *discardInfo -} diff --git a/vendor/github.com/golang/protobuf/proto/message_set.go b/vendor/github.com/golang/protobuf/proto/message_set.go deleted file mode 100644 index 3b6ca41d..00000000 --- a/vendor/github.com/golang/protobuf/proto/message_set.go +++ /dev/null @@ -1,314 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 -// OWNER 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. - -package proto - -/* - * Support for message sets. - */ - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "reflect" - "sort" - "sync" -) - -// errNoMessageTypeID occurs when a protocol buffer does not have a message type ID. -// A message type ID is required for storing a protocol buffer in a message set. -var errNoMessageTypeID = errors.New("proto does not have a message type ID") - -// The first two types (_MessageSet_Item and messageSet) -// model what the protocol compiler produces for the following protocol message: -// message MessageSet { -// repeated group Item = 1 { -// required int32 type_id = 2; -// required string message = 3; -// }; -// } -// That is the MessageSet wire format. We can't use a proto to generate these -// because that would introduce a circular dependency between it and this package. - -type _MessageSet_Item struct { - TypeId *int32 `protobuf:"varint,2,req,name=type_id"` - Message []byte `protobuf:"bytes,3,req,name=message"` -} - -type messageSet struct { - Item []*_MessageSet_Item `protobuf:"group,1,rep"` - XXX_unrecognized []byte - // TODO: caching? -} - -// Make sure messageSet is a Message. -var _ Message = (*messageSet)(nil) - -// messageTypeIder is an interface satisfied by a protocol buffer type -// that may be stored in a MessageSet. -type messageTypeIder interface { - MessageTypeId() int32 -} - -func (ms *messageSet) find(pb Message) *_MessageSet_Item { - mti, ok := pb.(messageTypeIder) - if !ok { - return nil - } - id := mti.MessageTypeId() - for _, item := range ms.Item { - if *item.TypeId == id { - return item - } - } - return nil -} - -func (ms *messageSet) Has(pb Message) bool { - return ms.find(pb) != nil -} - -func (ms *messageSet) Unmarshal(pb Message) error { - if item := ms.find(pb); item != nil { - return Unmarshal(item.Message, pb) - } - if _, ok := pb.(messageTypeIder); !ok { - return errNoMessageTypeID - } - return nil // TODO: return error instead? -} - -func (ms *messageSet) Marshal(pb Message) error { - msg, err := Marshal(pb) - if err != nil { - return err - } - if item := ms.find(pb); item != nil { - // reuse existing item - item.Message = msg - return nil - } - - mti, ok := pb.(messageTypeIder) - if !ok { - return errNoMessageTypeID - } - - mtid := mti.MessageTypeId() - ms.Item = append(ms.Item, &_MessageSet_Item{ - TypeId: &mtid, - Message: msg, - }) - return nil -} - -func (ms *messageSet) Reset() { *ms = messageSet{} } -func (ms *messageSet) String() string { return CompactTextString(ms) } -func (*messageSet) ProtoMessage() {} - -// Support for the message_set_wire_format message option. - -func skipVarint(buf []byte) []byte { - i := 0 - for ; buf[i]&0x80 != 0; i++ { - } - return buf[i+1:] -} - -// MarshalMessageSet encodes the extension map represented by m in the message set wire format. -// It is called by generated Marshal methods on protocol buffer messages with the message_set_wire_format option. -func MarshalMessageSet(exts interface{}) ([]byte, error) { - return marshalMessageSet(exts, false) -} - -// marshaMessageSet implements above function, with the opt to turn on / off deterministic during Marshal. -func marshalMessageSet(exts interface{}, deterministic bool) ([]byte, error) { - switch exts := exts.(type) { - case *XXX_InternalExtensions: - var u marshalInfo - siz := u.sizeMessageSet(exts) - b := make([]byte, 0, siz) - return u.appendMessageSet(b, exts, deterministic) - - case map[int32]Extension: - // This is an old-style extension map. - // Wrap it in a new-style XXX_InternalExtensions. - ie := XXX_InternalExtensions{ - p: &struct { - mu sync.Mutex - extensionMap map[int32]Extension - }{ - extensionMap: exts, - }, - } - - var u marshalInfo - siz := u.sizeMessageSet(&ie) - b := make([]byte, 0, siz) - return u.appendMessageSet(b, &ie, deterministic) - - default: - return nil, errors.New("proto: not an extension map") - } -} - -// UnmarshalMessageSet decodes the extension map encoded in buf in the message set wire format. -// It is called by Unmarshal methods on protocol buffer messages with the message_set_wire_format option. -func UnmarshalMessageSet(buf []byte, exts interface{}) error { - var m map[int32]Extension - switch exts := exts.(type) { - case *XXX_InternalExtensions: - m = exts.extensionsWrite() - case map[int32]Extension: - m = exts - default: - return errors.New("proto: not an extension map") - } - - ms := new(messageSet) - if err := Unmarshal(buf, ms); err != nil { - return err - } - for _, item := range ms.Item { - id := *item.TypeId - msg := item.Message - - // Restore wire type and field number varint, plus length varint. - // Be careful to preserve duplicate items. - b := EncodeVarint(uint64(id)<<3 | WireBytes) - if ext, ok := m[id]; ok { - // Existing data; rip off the tag and length varint - // so we join the new data correctly. - // We can assume that ext.enc is set because we are unmarshaling. - o := ext.enc[len(b):] // skip wire type and field number - _, n := DecodeVarint(o) // calculate length of length varint - o = o[n:] // skip length varint - msg = append(o, msg...) // join old data and new data - } - b = append(b, EncodeVarint(uint64(len(msg)))...) - b = append(b, msg...) - - m[id] = Extension{enc: b} - } - return nil -} - -// MarshalMessageSetJSON encodes the extension map represented by m in JSON format. -// It is called by generated MarshalJSON methods on protocol buffer messages with the message_set_wire_format option. -func MarshalMessageSetJSON(exts interface{}) ([]byte, error) { - var m map[int32]Extension - switch exts := exts.(type) { - case *XXX_InternalExtensions: - var mu sync.Locker - m, mu = exts.extensionsRead() - if m != nil { - // Keep the extensions map locked until we're done marshaling to prevent - // races between marshaling and unmarshaling the lazily-{en,de}coded - // values. - mu.Lock() - defer mu.Unlock() - } - case map[int32]Extension: - m = exts - default: - return nil, errors.New("proto: not an extension map") - } - var b bytes.Buffer - b.WriteByte('{') - - // Process the map in key order for deterministic output. - ids := make([]int32, 0, len(m)) - for id := range m { - ids = append(ids, id) - } - sort.Sort(int32Slice(ids)) // int32Slice defined in text.go - - for i, id := range ids { - ext := m[id] - msd, ok := messageSetMap[id] - if !ok { - // Unknown type; we can't render it, so skip it. - continue - } - - if i > 0 && b.Len() > 1 { - b.WriteByte(',') - } - - fmt.Fprintf(&b, `"[%s]":`, msd.name) - - x := ext.value - if x == nil { - x = reflect.New(msd.t.Elem()).Interface() - if err := Unmarshal(ext.enc, x.(Message)); err != nil { - return nil, err - } - } - d, err := json.Marshal(x) - if err != nil { - return nil, err - } - b.Write(d) - } - b.WriteByte('}') - return b.Bytes(), nil -} - -// UnmarshalMessageSetJSON decodes the extension map encoded in buf in JSON format. -// It is called by generated UnmarshalJSON methods on protocol buffer messages with the message_set_wire_format option. -func UnmarshalMessageSetJSON(buf []byte, exts interface{}) error { - // Common-case fast path. - if len(buf) == 0 || bytes.Equal(buf, []byte("{}")) { - return nil - } - - // This is fairly tricky, and it's not clear that it is needed. - return errors.New("TODO: UnmarshalMessageSetJSON not yet implemented") -} - -// A global registry of types that can be used in a MessageSet. - -var messageSetMap = make(map[int32]messageSetDesc) - -type messageSetDesc struct { - t reflect.Type // pointer to struct - name string -} - -// RegisterMessageSetType is called from the generated code. -func RegisterMessageSetType(m Message, fieldNum int32, name string) { - messageSetMap[fieldNum] = messageSetDesc{ - t: reflect.TypeOf(m), - name: name, - } -} diff --git a/vendor/github.com/golang/protobuf/proto/pointer_reflect.go b/vendor/github.com/golang/protobuf/proto/pointer_reflect.go deleted file mode 100644 index b6cad908..00000000 --- a/vendor/github.com/golang/protobuf/proto/pointer_reflect.go +++ /dev/null @@ -1,357 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 -// OWNER 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. - -// +build purego appengine js - -// This file contains an implementation of proto field accesses using package reflect. -// It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can -// be used on App Engine. - -package proto - -import ( - "reflect" - "sync" -) - -const unsafeAllowed = false - -// A field identifies a field in a struct, accessible from a pointer. -// In this implementation, a field is identified by the sequence of field indices -// passed to reflect's FieldByIndex. -type field []int - -// toField returns a field equivalent to the given reflect field. -func toField(f *reflect.StructField) field { - return f.Index -} - -// invalidField is an invalid field identifier. -var invalidField = field(nil) - -// zeroField is a noop when calling pointer.offset. -var zeroField = field([]int{}) - -// IsValid reports whether the field identifier is valid. -func (f field) IsValid() bool { return f != nil } - -// The pointer type is for the table-driven decoder. -// The implementation here uses a reflect.Value of pointer type to -// create a generic pointer. In pointer_unsafe.go we use unsafe -// instead of reflect to implement the same (but faster) interface. -type pointer struct { - v reflect.Value -} - -// toPointer converts an interface of pointer type to a pointer -// that points to the same target. -func toPointer(i *Message) pointer { - return pointer{v: reflect.ValueOf(*i)} -} - -// toAddrPointer converts an interface to a pointer that points to -// the interface data. -func toAddrPointer(i *interface{}, isptr bool) pointer { - v := reflect.ValueOf(*i) - u := reflect.New(v.Type()) - u.Elem().Set(v) - return pointer{v: u} -} - -// valToPointer converts v to a pointer. v must be of pointer type. -func valToPointer(v reflect.Value) pointer { - return pointer{v: v} -} - -// offset converts from a pointer to a structure to a pointer to -// one of its fields. -func (p pointer) offset(f field) pointer { - return pointer{v: p.v.Elem().FieldByIndex(f).Addr()} -} - -func (p pointer) isNil() bool { - return p.v.IsNil() -} - -// grow updates the slice s in place to make it one element longer. -// s must be addressable. -// Returns the (addressable) new element. -func grow(s reflect.Value) reflect.Value { - n, m := s.Len(), s.Cap() - if n < m { - s.SetLen(n + 1) - } else { - s.Set(reflect.Append(s, reflect.Zero(s.Type().Elem()))) - } - return s.Index(n) -} - -func (p pointer) toInt64() *int64 { - return p.v.Interface().(*int64) -} -func (p pointer) toInt64Ptr() **int64 { - return p.v.Interface().(**int64) -} -func (p pointer) toInt64Slice() *[]int64 { - return p.v.Interface().(*[]int64) -} - -var int32ptr = reflect.TypeOf((*int32)(nil)) - -func (p pointer) toInt32() *int32 { - return p.v.Convert(int32ptr).Interface().(*int32) -} - -// The toInt32Ptr/Slice methods don't work because of enums. -// Instead, we must use set/get methods for the int32ptr/slice case. -/* - func (p pointer) toInt32Ptr() **int32 { - return p.v.Interface().(**int32) -} - func (p pointer) toInt32Slice() *[]int32 { - return p.v.Interface().(*[]int32) -} -*/ -func (p pointer) getInt32Ptr() *int32 { - if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) { - // raw int32 type - return p.v.Elem().Interface().(*int32) - } - // an enum - return p.v.Elem().Convert(int32PtrType).Interface().(*int32) -} -func (p pointer) setInt32Ptr(v int32) { - // Allocate value in a *int32. Possibly convert that to a *enum. - // Then assign it to a **int32 or **enum. - // Note: we can convert *int32 to *enum, but we can't convert - // **int32 to **enum! - p.v.Elem().Set(reflect.ValueOf(&v).Convert(p.v.Type().Elem())) -} - -// getInt32Slice copies []int32 from p as a new slice. -// This behavior differs from the implementation in pointer_unsafe.go. -func (p pointer) getInt32Slice() []int32 { - if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) { - // raw int32 type - return p.v.Elem().Interface().([]int32) - } - // an enum - // Allocate a []int32, then assign []enum's values into it. - // Note: we can't convert []enum to []int32. - slice := p.v.Elem() - s := make([]int32, slice.Len()) - for i := 0; i < slice.Len(); i++ { - s[i] = int32(slice.Index(i).Int()) - } - return s -} - -// setInt32Slice copies []int32 into p as a new slice. -// This behavior differs from the implementation in pointer_unsafe.go. -func (p pointer) setInt32Slice(v []int32) { - if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) { - // raw int32 type - p.v.Elem().Set(reflect.ValueOf(v)) - return - } - // an enum - // Allocate a []enum, then assign []int32's values into it. - // Note: we can't convert []enum to []int32. - slice := reflect.MakeSlice(p.v.Type().Elem(), len(v), cap(v)) - for i, x := range v { - slice.Index(i).SetInt(int64(x)) - } - p.v.Elem().Set(slice) -} -func (p pointer) appendInt32Slice(v int32) { - grow(p.v.Elem()).SetInt(int64(v)) -} - -func (p pointer) toUint64() *uint64 { - return p.v.Interface().(*uint64) -} -func (p pointer) toUint64Ptr() **uint64 { - return p.v.Interface().(**uint64) -} -func (p pointer) toUint64Slice() *[]uint64 { - return p.v.Interface().(*[]uint64) -} -func (p pointer) toUint32() *uint32 { - return p.v.Interface().(*uint32) -} -func (p pointer) toUint32Ptr() **uint32 { - return p.v.Interface().(**uint32) -} -func (p pointer) toUint32Slice() *[]uint32 { - return p.v.Interface().(*[]uint32) -} -func (p pointer) toBool() *bool { - return p.v.Interface().(*bool) -} -func (p pointer) toBoolPtr() **bool { - return p.v.Interface().(**bool) -} -func (p pointer) toBoolSlice() *[]bool { - return p.v.Interface().(*[]bool) -} -func (p pointer) toFloat64() *float64 { - return p.v.Interface().(*float64) -} -func (p pointer) toFloat64Ptr() **float64 { - return p.v.Interface().(**float64) -} -func (p pointer) toFloat64Slice() *[]float64 { - return p.v.Interface().(*[]float64) -} -func (p pointer) toFloat32() *float32 { - return p.v.Interface().(*float32) -} -func (p pointer) toFloat32Ptr() **float32 { - return p.v.Interface().(**float32) -} -func (p pointer) toFloat32Slice() *[]float32 { - return p.v.Interface().(*[]float32) -} -func (p pointer) toString() *string { - return p.v.Interface().(*string) -} -func (p pointer) toStringPtr() **string { - return p.v.Interface().(**string) -} -func (p pointer) toStringSlice() *[]string { - return p.v.Interface().(*[]string) -} -func (p pointer) toBytes() *[]byte { - return p.v.Interface().(*[]byte) -} -func (p pointer) toBytesSlice() *[][]byte { - return p.v.Interface().(*[][]byte) -} -func (p pointer) toExtensions() *XXX_InternalExtensions { - return p.v.Interface().(*XXX_InternalExtensions) -} -func (p pointer) toOldExtensions() *map[int32]Extension { - return p.v.Interface().(*map[int32]Extension) -} -func (p pointer) getPointer() pointer { - return pointer{v: p.v.Elem()} -} -func (p pointer) setPointer(q pointer) { - p.v.Elem().Set(q.v) -} -func (p pointer) appendPointer(q pointer) { - grow(p.v.Elem()).Set(q.v) -} - -// getPointerSlice copies []*T from p as a new []pointer. -// This behavior differs from the implementation in pointer_unsafe.go. -func (p pointer) getPointerSlice() []pointer { - if p.v.IsNil() { - return nil - } - n := p.v.Elem().Len() - s := make([]pointer, n) - for i := 0; i < n; i++ { - s[i] = pointer{v: p.v.Elem().Index(i)} - } - return s -} - -// setPointerSlice copies []pointer into p as a new []*T. -// This behavior differs from the implementation in pointer_unsafe.go. -func (p pointer) setPointerSlice(v []pointer) { - if v == nil { - p.v.Elem().Set(reflect.New(p.v.Elem().Type()).Elem()) - return - } - s := reflect.MakeSlice(p.v.Elem().Type(), 0, len(v)) - for _, p := range v { - s = reflect.Append(s, p.v) - } - p.v.Elem().Set(s) -} - -// getInterfacePointer returns a pointer that points to the -// interface data of the interface pointed by p. -func (p pointer) getInterfacePointer() pointer { - if p.v.Elem().IsNil() { - return pointer{v: p.v.Elem()} - } - return pointer{v: p.v.Elem().Elem().Elem().Field(0).Addr()} // *interface -> interface -> *struct -> struct -} - -func (p pointer) asPointerTo(t reflect.Type) reflect.Value { - // TODO: check that p.v.Type().Elem() == t? - return p.v -} - -func atomicLoadUnmarshalInfo(p **unmarshalInfo) *unmarshalInfo { - atomicLock.Lock() - defer atomicLock.Unlock() - return *p -} -func atomicStoreUnmarshalInfo(p **unmarshalInfo, v *unmarshalInfo) { - atomicLock.Lock() - defer atomicLock.Unlock() - *p = v -} -func atomicLoadMarshalInfo(p **marshalInfo) *marshalInfo { - atomicLock.Lock() - defer atomicLock.Unlock() - return *p -} -func atomicStoreMarshalInfo(p **marshalInfo, v *marshalInfo) { - atomicLock.Lock() - defer atomicLock.Unlock() - *p = v -} -func atomicLoadMergeInfo(p **mergeInfo) *mergeInfo { - atomicLock.Lock() - defer atomicLock.Unlock() - return *p -} -func atomicStoreMergeInfo(p **mergeInfo, v *mergeInfo) { - atomicLock.Lock() - defer atomicLock.Unlock() - *p = v -} -func atomicLoadDiscardInfo(p **discardInfo) *discardInfo { - atomicLock.Lock() - defer atomicLock.Unlock() - return *p -} -func atomicStoreDiscardInfo(p **discardInfo, v *discardInfo) { - atomicLock.Lock() - defer atomicLock.Unlock() - *p = v -} - -var atomicLock sync.Mutex diff --git a/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go b/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go deleted file mode 100644 index d55a335d..00000000 --- a/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go +++ /dev/null @@ -1,308 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 -// OWNER 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. - -// +build !purego,!appengine,!js - -// This file contains the implementation of the proto field accesses using package unsafe. - -package proto - -import ( - "reflect" - "sync/atomic" - "unsafe" -) - -const unsafeAllowed = true - -// A field identifies a field in a struct, accessible from a pointer. -// In this implementation, a field is identified by its byte offset from the start of the struct. -type field uintptr - -// toField returns a field equivalent to the given reflect field. -func toField(f *reflect.StructField) field { - return field(f.Offset) -} - -// invalidField is an invalid field identifier. -const invalidField = ^field(0) - -// zeroField is a noop when calling pointer.offset. -const zeroField = field(0) - -// IsValid reports whether the field identifier is valid. -func (f field) IsValid() bool { - return f != invalidField -} - -// The pointer type below is for the new table-driven encoder/decoder. -// The implementation here uses unsafe.Pointer to create a generic pointer. -// In pointer_reflect.go we use reflect instead of unsafe to implement -// the same (but slower) interface. -type pointer struct { - p unsafe.Pointer -} - -// size of pointer -var ptrSize = unsafe.Sizeof(uintptr(0)) - -// toPointer converts an interface of pointer type to a pointer -// that points to the same target. -func toPointer(i *Message) pointer { - // Super-tricky - read pointer out of data word of interface value. - // Saves ~25ns over the equivalent: - // return valToPointer(reflect.ValueOf(*i)) - return pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]} -} - -// toAddrPointer converts an interface to a pointer that points to -// the interface data. -func toAddrPointer(i *interface{}, isptr bool) pointer { - // Super-tricky - read or get the address of data word of interface value. - if isptr { - // The interface is of pointer type, thus it is a direct interface. - // The data word is the pointer data itself. We take its address. - return pointer{p: unsafe.Pointer(uintptr(unsafe.Pointer(i)) + ptrSize)} - } - // The interface is not of pointer type. The data word is the pointer - // to the data. - return pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]} -} - -// valToPointer converts v to a pointer. v must be of pointer type. -func valToPointer(v reflect.Value) pointer { - return pointer{p: unsafe.Pointer(v.Pointer())} -} - -// offset converts from a pointer to a structure to a pointer to -// one of its fields. -func (p pointer) offset(f field) pointer { - // For safety, we should panic if !f.IsValid, however calling panic causes - // this to no longer be inlineable, which is a serious performance cost. - /* - if !f.IsValid() { - panic("invalid field") - } - */ - return pointer{p: unsafe.Pointer(uintptr(p.p) + uintptr(f))} -} - -func (p pointer) isNil() bool { - return p.p == nil -} - -func (p pointer) toInt64() *int64 { - return (*int64)(p.p) -} -func (p pointer) toInt64Ptr() **int64 { - return (**int64)(p.p) -} -func (p pointer) toInt64Slice() *[]int64 { - return (*[]int64)(p.p) -} -func (p pointer) toInt32() *int32 { - return (*int32)(p.p) -} - -// See pointer_reflect.go for why toInt32Ptr/Slice doesn't exist. -/* - func (p pointer) toInt32Ptr() **int32 { - return (**int32)(p.p) - } - func (p pointer) toInt32Slice() *[]int32 { - return (*[]int32)(p.p) - } -*/ -func (p pointer) getInt32Ptr() *int32 { - return *(**int32)(p.p) -} -func (p pointer) setInt32Ptr(v int32) { - *(**int32)(p.p) = &v -} - -// getInt32Slice loads a []int32 from p. -// The value returned is aliased with the original slice. -// This behavior differs from the implementation in pointer_reflect.go. -func (p pointer) getInt32Slice() []int32 { - return *(*[]int32)(p.p) -} - -// setInt32Slice stores a []int32 to p. -// The value set is aliased with the input slice. -// This behavior differs from the implementation in pointer_reflect.go. -func (p pointer) setInt32Slice(v []int32) { - *(*[]int32)(p.p) = v -} - -// TODO: Can we get rid of appendInt32Slice and use setInt32Slice instead? -func (p pointer) appendInt32Slice(v int32) { - s := (*[]int32)(p.p) - *s = append(*s, v) -} - -func (p pointer) toUint64() *uint64 { - return (*uint64)(p.p) -} -func (p pointer) toUint64Ptr() **uint64 { - return (**uint64)(p.p) -} -func (p pointer) toUint64Slice() *[]uint64 { - return (*[]uint64)(p.p) -} -func (p pointer) toUint32() *uint32 { - return (*uint32)(p.p) -} -func (p pointer) toUint32Ptr() **uint32 { - return (**uint32)(p.p) -} -func (p pointer) toUint32Slice() *[]uint32 { - return (*[]uint32)(p.p) -} -func (p pointer) toBool() *bool { - return (*bool)(p.p) -} -func (p pointer) toBoolPtr() **bool { - return (**bool)(p.p) -} -func (p pointer) toBoolSlice() *[]bool { - return (*[]bool)(p.p) -} -func (p pointer) toFloat64() *float64 { - return (*float64)(p.p) -} -func (p pointer) toFloat64Ptr() **float64 { - return (**float64)(p.p) -} -func (p pointer) toFloat64Slice() *[]float64 { - return (*[]float64)(p.p) -} -func (p pointer) toFloat32() *float32 { - return (*float32)(p.p) -} -func (p pointer) toFloat32Ptr() **float32 { - return (**float32)(p.p) -} -func (p pointer) toFloat32Slice() *[]float32 { - return (*[]float32)(p.p) -} -func (p pointer) toString() *string { - return (*string)(p.p) -} -func (p pointer) toStringPtr() **string { - return (**string)(p.p) -} -func (p pointer) toStringSlice() *[]string { - return (*[]string)(p.p) -} -func (p pointer) toBytes() *[]byte { - return (*[]byte)(p.p) -} -func (p pointer) toBytesSlice() *[][]byte { - return (*[][]byte)(p.p) -} -func (p pointer) toExtensions() *XXX_InternalExtensions { - return (*XXX_InternalExtensions)(p.p) -} -func (p pointer) toOldExtensions() *map[int32]Extension { - return (*map[int32]Extension)(p.p) -} - -// getPointerSlice loads []*T from p as a []pointer. -// The value returned is aliased with the original slice. -// This behavior differs from the implementation in pointer_reflect.go. -func (p pointer) getPointerSlice() []pointer { - // Super-tricky - p should point to a []*T where T is a - // message type. We load it as []pointer. - return *(*[]pointer)(p.p) -} - -// setPointerSlice stores []pointer into p as a []*T. -// The value set is aliased with the input slice. -// This behavior differs from the implementation in pointer_reflect.go. -func (p pointer) setPointerSlice(v []pointer) { - // Super-tricky - p should point to a []*T where T is a - // message type. We store it as []pointer. - *(*[]pointer)(p.p) = v -} - -// getPointer loads the pointer at p and returns it. -func (p pointer) getPointer() pointer { - return pointer{p: *(*unsafe.Pointer)(p.p)} -} - -// setPointer stores the pointer q at p. -func (p pointer) setPointer(q pointer) { - *(*unsafe.Pointer)(p.p) = q.p -} - -// append q to the slice pointed to by p. -func (p pointer) appendPointer(q pointer) { - s := (*[]unsafe.Pointer)(p.p) - *s = append(*s, q.p) -} - -// getInterfacePointer returns a pointer that points to the -// interface data of the interface pointed by p. -func (p pointer) getInterfacePointer() pointer { - // Super-tricky - read pointer out of data word of interface value. - return pointer{p: (*(*[2]unsafe.Pointer)(p.p))[1]} -} - -// asPointerTo returns a reflect.Value that is a pointer to an -// object of type t stored at p. -func (p pointer) asPointerTo(t reflect.Type) reflect.Value { - return reflect.NewAt(t, p.p) -} - -func atomicLoadUnmarshalInfo(p **unmarshalInfo) *unmarshalInfo { - return (*unmarshalInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) -} -func atomicStoreUnmarshalInfo(p **unmarshalInfo, v *unmarshalInfo) { - atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) -} -func atomicLoadMarshalInfo(p **marshalInfo) *marshalInfo { - return (*marshalInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) -} -func atomicStoreMarshalInfo(p **marshalInfo, v *marshalInfo) { - atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) -} -func atomicLoadMergeInfo(p **mergeInfo) *mergeInfo { - return (*mergeInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) -} -func atomicStoreMergeInfo(p **mergeInfo, v *mergeInfo) { - atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) -} -func atomicLoadDiscardInfo(p **discardInfo) *discardInfo { - return (*discardInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) -} -func atomicStoreDiscardInfo(p **discardInfo, v *discardInfo) { - atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) -} diff --git a/vendor/github.com/golang/protobuf/proto/properties.go b/vendor/github.com/golang/protobuf/proto/properties.go deleted file mode 100644 index f710adab..00000000 --- a/vendor/github.com/golang/protobuf/proto/properties.go +++ /dev/null @@ -1,544 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 -// OWNER 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. - -package proto - -/* - * Routines for encoding data into the wire format for protocol buffers. - */ - -import ( - "fmt" - "log" - "os" - "reflect" - "sort" - "strconv" - "strings" - "sync" -) - -const debug bool = false - -// Constants that identify the encoding of a value on the wire. -const ( - WireVarint = 0 - WireFixed64 = 1 - WireBytes = 2 - WireStartGroup = 3 - WireEndGroup = 4 - WireFixed32 = 5 -) - -// tagMap is an optimization over map[int]int for typical protocol buffer -// use-cases. Encoded protocol buffers are often in tag order with small tag -// numbers. -type tagMap struct { - fastTags []int - slowTags map[int]int -} - -// tagMapFastLimit is the upper bound on the tag number that will be stored in -// the tagMap slice rather than its map. -const tagMapFastLimit = 1024 - -func (p *tagMap) get(t int) (int, bool) { - if t > 0 && t < tagMapFastLimit { - if t >= len(p.fastTags) { - return 0, false - } - fi := p.fastTags[t] - return fi, fi >= 0 - } - fi, ok := p.slowTags[t] - return fi, ok -} - -func (p *tagMap) put(t int, fi int) { - if t > 0 && t < tagMapFastLimit { - for len(p.fastTags) < t+1 { - p.fastTags = append(p.fastTags, -1) - } - p.fastTags[t] = fi - return - } - if p.slowTags == nil { - p.slowTags = make(map[int]int) - } - p.slowTags[t] = fi -} - -// StructProperties represents properties for all the fields of a struct. -// decoderTags and decoderOrigNames should only be used by the decoder. -type StructProperties struct { - Prop []*Properties // properties for each field - reqCount int // required count - decoderTags tagMap // map from proto tag to struct field number - decoderOrigNames map[string]int // map from original name to struct field number - order []int // list of struct field numbers in tag order - - // OneofTypes contains information about the oneof fields in this message. - // It is keyed by the original name of a field. - OneofTypes map[string]*OneofProperties -} - -// OneofProperties represents information about a specific field in a oneof. -type OneofProperties struct { - Type reflect.Type // pointer to generated struct type for this oneof field - Field int // struct field number of the containing oneof in the message - Prop *Properties -} - -// Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec. -// See encode.go, (*Buffer).enc_struct. - -func (sp *StructProperties) Len() int { return len(sp.order) } -func (sp *StructProperties) Less(i, j int) bool { - return sp.Prop[sp.order[i]].Tag < sp.Prop[sp.order[j]].Tag -} -func (sp *StructProperties) Swap(i, j int) { sp.order[i], sp.order[j] = sp.order[j], sp.order[i] } - -// Properties represents the protocol-specific behavior of a single struct field. -type Properties struct { - Name string // name of the field, for error messages - OrigName string // original name before protocol compiler (always set) - JSONName string // name to use for JSON; determined by protoc - Wire string - WireType int - Tag int - Required bool - Optional bool - Repeated bool - Packed bool // relevant for repeated primitives only - Enum string // set for enum types only - proto3 bool // whether this is known to be a proto3 field; set for []byte only - oneof bool // whether this is a oneof field - - Default string // default value - HasDefault bool // whether an explicit default was provided - - stype reflect.Type // set for struct types only - sprop *StructProperties // set for struct types only - - mtype reflect.Type // set for map types only - mkeyprop *Properties // set for map types only - mvalprop *Properties // set for map types only -} - -// String formats the properties in the protobuf struct field tag style. -func (p *Properties) String() string { - s := p.Wire - s += "," - s += strconv.Itoa(p.Tag) - if p.Required { - s += ",req" - } - if p.Optional { - s += ",opt" - } - if p.Repeated { - s += ",rep" - } - if p.Packed { - s += ",packed" - } - s += ",name=" + p.OrigName - if p.JSONName != p.OrigName { - s += ",json=" + p.JSONName - } - if p.proto3 { - s += ",proto3" - } - if p.oneof { - s += ",oneof" - } - if len(p.Enum) > 0 { - s += ",enum=" + p.Enum - } - if p.HasDefault { - s += ",def=" + p.Default - } - return s -} - -// Parse populates p by parsing a string in the protobuf struct field tag style. -func (p *Properties) Parse(s string) { - // "bytes,49,opt,name=foo,def=hello!" - fields := strings.Split(s, ",") // breaks def=, but handled below. - if len(fields) < 2 { - fmt.Fprintf(os.Stderr, "proto: tag has too few fields: %q\n", s) - return - } - - p.Wire = fields[0] - switch p.Wire { - case "varint": - p.WireType = WireVarint - case "fixed32": - p.WireType = WireFixed32 - case "fixed64": - p.WireType = WireFixed64 - case "zigzag32": - p.WireType = WireVarint - case "zigzag64": - p.WireType = WireVarint - case "bytes", "group": - p.WireType = WireBytes - // no numeric converter for non-numeric types - default: - fmt.Fprintf(os.Stderr, "proto: tag has unknown wire type: %q\n", s) - return - } - - var err error - p.Tag, err = strconv.Atoi(fields[1]) - if err != nil { - return - } - -outer: - for i := 2; i < len(fields); i++ { - f := fields[i] - switch { - case f == "req": - p.Required = true - case f == "opt": - p.Optional = true - case f == "rep": - p.Repeated = true - case f == "packed": - p.Packed = true - case strings.HasPrefix(f, "name="): - p.OrigName = f[5:] - case strings.HasPrefix(f, "json="): - p.JSONName = f[5:] - case strings.HasPrefix(f, "enum="): - p.Enum = f[5:] - case f == "proto3": - p.proto3 = true - case f == "oneof": - p.oneof = true - case strings.HasPrefix(f, "def="): - p.HasDefault = true - p.Default = f[4:] // rest of string - if i+1 < len(fields) { - // Commas aren't escaped, and def is always last. - p.Default += "," + strings.Join(fields[i+1:], ",") - break outer - } - } - } -} - -var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem() - -// setFieldProps initializes the field properties for submessages and maps. -func (p *Properties) setFieldProps(typ reflect.Type, f *reflect.StructField, lockGetProp bool) { - switch t1 := typ; t1.Kind() { - case reflect.Ptr: - if t1.Elem().Kind() == reflect.Struct { - p.stype = t1.Elem() - } - - case reflect.Slice: - if t2 := t1.Elem(); t2.Kind() == reflect.Ptr && t2.Elem().Kind() == reflect.Struct { - p.stype = t2.Elem() - } - - case reflect.Map: - p.mtype = t1 - p.mkeyprop = &Properties{} - p.mkeyprop.init(reflect.PtrTo(p.mtype.Key()), "Key", f.Tag.Get("protobuf_key"), nil, lockGetProp) - p.mvalprop = &Properties{} - vtype := p.mtype.Elem() - if vtype.Kind() != reflect.Ptr && vtype.Kind() != reflect.Slice { - // The value type is not a message (*T) or bytes ([]byte), - // so we need encoders for the pointer to this type. - vtype = reflect.PtrTo(vtype) - } - p.mvalprop.init(vtype, "Value", f.Tag.Get("protobuf_val"), nil, lockGetProp) - } - - if p.stype != nil { - if lockGetProp { - p.sprop = GetProperties(p.stype) - } else { - p.sprop = getPropertiesLocked(p.stype) - } - } -} - -var ( - marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem() -) - -// Init populates the properties from a protocol buffer struct tag. -func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) { - p.init(typ, name, tag, f, true) -} - -func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructField, lockGetProp bool) { - // "bytes,49,opt,def=hello!" - p.Name = name - p.OrigName = name - if tag == "" { - return - } - p.Parse(tag) - p.setFieldProps(typ, f, lockGetProp) -} - -var ( - propertiesMu sync.RWMutex - propertiesMap = make(map[reflect.Type]*StructProperties) -) - -// GetProperties returns the list of properties for the type represented by t. -// t must represent a generated struct type of a protocol message. -func GetProperties(t reflect.Type) *StructProperties { - if t.Kind() != reflect.Struct { - panic("proto: type must have kind struct") - } - - // Most calls to GetProperties in a long-running program will be - // retrieving details for types we have seen before. - propertiesMu.RLock() - sprop, ok := propertiesMap[t] - propertiesMu.RUnlock() - if ok { - if collectStats { - stats.Chit++ - } - return sprop - } - - propertiesMu.Lock() - sprop = getPropertiesLocked(t) - propertiesMu.Unlock() - return sprop -} - -// getPropertiesLocked requires that propertiesMu is held. -func getPropertiesLocked(t reflect.Type) *StructProperties { - if prop, ok := propertiesMap[t]; ok { - if collectStats { - stats.Chit++ - } - return prop - } - if collectStats { - stats.Cmiss++ - } - - prop := new(StructProperties) - // in case of recursive protos, fill this in now. - propertiesMap[t] = prop - - // build properties - prop.Prop = make([]*Properties, t.NumField()) - prop.order = make([]int, t.NumField()) - - for i := 0; i < t.NumField(); i++ { - f := t.Field(i) - p := new(Properties) - name := f.Name - p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false) - - oneof := f.Tag.Get("protobuf_oneof") // special case - if oneof != "" { - // Oneof fields don't use the traditional protobuf tag. - p.OrigName = oneof - } - prop.Prop[i] = p - prop.order[i] = i - if debug { - print(i, " ", f.Name, " ", t.String(), " ") - if p.Tag > 0 { - print(p.String()) - } - print("\n") - } - } - - // Re-order prop.order. - sort.Sort(prop) - - type oneofMessage interface { - XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{}) - } - if om, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(oneofMessage); ok { - var oots []interface{} - _, _, _, oots = om.XXX_OneofFuncs() - - // Interpret oneof metadata. - prop.OneofTypes = make(map[string]*OneofProperties) - for _, oot := range oots { - oop := &OneofProperties{ - Type: reflect.ValueOf(oot).Type(), // *T - Prop: new(Properties), - } - sft := oop.Type.Elem().Field(0) - oop.Prop.Name = sft.Name - oop.Prop.Parse(sft.Tag.Get("protobuf")) - // There will be exactly one interface field that - // this new value is assignable to. - for i := 0; i < t.NumField(); i++ { - f := t.Field(i) - if f.Type.Kind() != reflect.Interface { - continue - } - if !oop.Type.AssignableTo(f.Type) { - continue - } - oop.Field = i - break - } - prop.OneofTypes[oop.Prop.OrigName] = oop - } - } - - // build required counts - // build tags - reqCount := 0 - prop.decoderOrigNames = make(map[string]int) - for i, p := range prop.Prop { - if strings.HasPrefix(p.Name, "XXX_") { - // Internal fields should not appear in tags/origNames maps. - // They are handled specially when encoding and decoding. - continue - } - if p.Required { - reqCount++ - } - prop.decoderTags.put(p.Tag, i) - prop.decoderOrigNames[p.OrigName] = i - } - prop.reqCount = reqCount - - return prop -} - -// A global registry of enum types. -// The generated code will register the generated maps by calling RegisterEnum. - -var enumValueMaps = make(map[string]map[string]int32) - -// RegisterEnum is called from the generated code to install the enum descriptor -// maps into the global table to aid parsing text format protocol buffers. -func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32) { - if _, ok := enumValueMaps[typeName]; ok { - panic("proto: duplicate enum registered: " + typeName) - } - enumValueMaps[typeName] = valueMap -} - -// EnumValueMap returns the mapping from names to integers of the -// enum type enumType, or a nil if not found. -func EnumValueMap(enumType string) map[string]int32 { - return enumValueMaps[enumType] -} - -// A registry of all linked message types. -// The string is a fully-qualified proto name ("pkg.Message"). -var ( - protoTypedNils = make(map[string]Message) // a map from proto names to typed nil pointers - protoMapTypes = make(map[string]reflect.Type) // a map from proto names to map types - revProtoTypes = make(map[reflect.Type]string) -) - -// RegisterType is called from generated code and maps from the fully qualified -// proto name to the type (pointer to struct) of the protocol buffer. -func RegisterType(x Message, name string) { - if _, ok := protoTypedNils[name]; ok { - // TODO: Some day, make this a panic. - log.Printf("proto: duplicate proto type registered: %s", name) - return - } - t := reflect.TypeOf(x) - if v := reflect.ValueOf(x); v.Kind() == reflect.Ptr && v.Pointer() == 0 { - // Generated code always calls RegisterType with nil x. - // This check is just for extra safety. - protoTypedNils[name] = x - } else { - protoTypedNils[name] = reflect.Zero(t).Interface().(Message) - } - revProtoTypes[t] = name -} - -// RegisterMapType is called from generated code and maps from the fully qualified -// proto name to the native map type of the proto map definition. -func RegisterMapType(x interface{}, name string) { - if reflect.TypeOf(x).Kind() != reflect.Map { - panic(fmt.Sprintf("RegisterMapType(%T, %q); want map", x, name)) - } - if _, ok := protoMapTypes[name]; ok { - log.Printf("proto: duplicate proto type registered: %s", name) - return - } - t := reflect.TypeOf(x) - protoMapTypes[name] = t - revProtoTypes[t] = name -} - -// MessageName returns the fully-qualified proto name for the given message type. -func MessageName(x Message) string { - type xname interface { - XXX_MessageName() string - } - if m, ok := x.(xname); ok { - return m.XXX_MessageName() - } - return revProtoTypes[reflect.TypeOf(x)] -} - -// MessageType returns the message type (pointer to struct) for a named message. -// The type is not guaranteed to implement proto.Message if the name refers to a -// map entry. -func MessageType(name string) reflect.Type { - if t, ok := protoTypedNils[name]; ok { - return reflect.TypeOf(t) - } - return protoMapTypes[name] -} - -// A registry of all linked proto files. -var ( - protoFiles = make(map[string][]byte) // file name => fileDescriptor -) - -// RegisterFile is called from generated code and maps from the -// full file name of a .proto file to its compressed FileDescriptorProto. -func RegisterFile(filename string, fileDescriptor []byte) { - protoFiles[filename] = fileDescriptor -} - -// FileDescriptor returns the compressed FileDescriptorProto for a .proto file. -func FileDescriptor(filename string) []byte { return protoFiles[filename] } diff --git a/vendor/github.com/golang/protobuf/proto/table_marshal.go b/vendor/github.com/golang/protobuf/proto/table_marshal.go deleted file mode 100644 index be7b2428..00000000 --- a/vendor/github.com/golang/protobuf/proto/table_marshal.go +++ /dev/null @@ -1,2685 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 -// OWNER 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. - -package proto - -import ( - "errors" - "fmt" - "math" - "reflect" - "sort" - "strconv" - "strings" - "sync" - "sync/atomic" - "unicode/utf8" -) - -// a sizer takes a pointer to a field and the size of its tag, computes the size of -// the encoded data. -type sizer func(pointer, int) int - -// a marshaler takes a byte slice, a pointer to a field, and its tag (in wire format), -// marshals the field to the end of the slice, returns the slice and error (if any). -type marshaler func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) - -// marshalInfo is the information used for marshaling a message. -type marshalInfo struct { - typ reflect.Type - fields []*marshalFieldInfo - unrecognized field // offset of XXX_unrecognized - extensions field // offset of XXX_InternalExtensions - v1extensions field // offset of XXX_extensions - sizecache field // offset of XXX_sizecache - initialized int32 // 0 -- only typ is set, 1 -- fully initialized - messageset bool // uses message set wire format - hasmarshaler bool // has custom marshaler - sync.RWMutex // protect extElems map, also for initialization - extElems map[int32]*marshalElemInfo // info of extension elements -} - -// marshalFieldInfo is the information used for marshaling a field of a message. -type marshalFieldInfo struct { - field field - wiretag uint64 // tag in wire format - tagsize int // size of tag in wire format - sizer sizer - marshaler marshaler - isPointer bool - required bool // field is required - name string // name of the field, for error reporting - oneofElems map[reflect.Type]*marshalElemInfo // info of oneof elements -} - -// marshalElemInfo is the information used for marshaling an extension or oneof element. -type marshalElemInfo struct { - wiretag uint64 // tag in wire format - tagsize int // size of tag in wire format - sizer sizer - marshaler marshaler - isptr bool // elem is pointer typed, thus interface of this type is a direct interface (extension only) -} - -var ( - marshalInfoMap = map[reflect.Type]*marshalInfo{} - marshalInfoLock sync.Mutex -) - -// getMarshalInfo returns the information to marshal a given type of message. -// The info it returns may not necessarily initialized. -// t is the type of the message (NOT the pointer to it). -func getMarshalInfo(t reflect.Type) *marshalInfo { - marshalInfoLock.Lock() - u, ok := marshalInfoMap[t] - if !ok { - u = &marshalInfo{typ: t} - marshalInfoMap[t] = u - } - marshalInfoLock.Unlock() - return u -} - -// Size is the entry point from generated code, -// and should be ONLY called by generated code. -// It computes the size of encoded data of msg. -// a is a pointer to a place to store cached marshal info. -func (a *InternalMessageInfo) Size(msg Message) int { - u := getMessageMarshalInfo(msg, a) - ptr := toPointer(&msg) - if ptr.isNil() { - // We get here if msg is a typed nil ((*SomeMessage)(nil)), - // so it satisfies the interface, and msg == nil wouldn't - // catch it. We don't want crash in this case. - return 0 - } - return u.size(ptr) -} - -// Marshal is the entry point from generated code, -// and should be ONLY called by generated code. -// It marshals msg to the end of b. -// a is a pointer to a place to store cached marshal info. -func (a *InternalMessageInfo) Marshal(b []byte, msg Message, deterministic bool) ([]byte, error) { - u := getMessageMarshalInfo(msg, a) - ptr := toPointer(&msg) - if ptr.isNil() { - // We get here if msg is a typed nil ((*SomeMessage)(nil)), - // so it satisfies the interface, and msg == nil wouldn't - // catch it. We don't want crash in this case. - return b, ErrNil - } - return u.marshal(b, ptr, deterministic) -} - -func getMessageMarshalInfo(msg interface{}, a *InternalMessageInfo) *marshalInfo { - // u := a.marshal, but atomically. - // We use an atomic here to ensure memory consistency. - u := atomicLoadMarshalInfo(&a.marshal) - if u == nil { - // Get marshal information from type of message. - t := reflect.ValueOf(msg).Type() - if t.Kind() != reflect.Ptr { - panic(fmt.Sprintf("cannot handle non-pointer message type %v", t)) - } - u = getMarshalInfo(t.Elem()) - // Store it in the cache for later users. - // a.marshal = u, but atomically. - atomicStoreMarshalInfo(&a.marshal, u) - } - return u -} - -// size is the main function to compute the size of the encoded data of a message. -// ptr is the pointer to the message. -func (u *marshalInfo) size(ptr pointer) int { - if atomic.LoadInt32(&u.initialized) == 0 { - u.computeMarshalInfo() - } - - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - if u.hasmarshaler { - m := ptr.asPointerTo(u.typ).Interface().(Marshaler) - b, _ := m.Marshal() - return len(b) - } - - n := 0 - for _, f := range u.fields { - if f.isPointer && ptr.offset(f.field).getPointer().isNil() { - // nil pointer always marshals to nothing - continue - } - n += f.sizer(ptr.offset(f.field), f.tagsize) - } - if u.extensions.IsValid() { - e := ptr.offset(u.extensions).toExtensions() - if u.messageset { - n += u.sizeMessageSet(e) - } else { - n += u.sizeExtensions(e) - } - } - if u.v1extensions.IsValid() { - m := *ptr.offset(u.v1extensions).toOldExtensions() - n += u.sizeV1Extensions(m) - } - if u.unrecognized.IsValid() { - s := *ptr.offset(u.unrecognized).toBytes() - n += len(s) - } - // cache the result for use in marshal - if u.sizecache.IsValid() { - atomic.StoreInt32(ptr.offset(u.sizecache).toInt32(), int32(n)) - } - return n -} - -// cachedsize gets the size from cache. If there is no cache (i.e. message is not generated), -// fall back to compute the size. -func (u *marshalInfo) cachedsize(ptr pointer) int { - if u.sizecache.IsValid() { - return int(atomic.LoadInt32(ptr.offset(u.sizecache).toInt32())) - } - return u.size(ptr) -} - -// marshal is the main function to marshal a message. It takes a byte slice and appends -// the encoded data to the end of the slice, returns the slice and error (if any). -// ptr is the pointer to the message. -// If deterministic is true, map is marshaled in deterministic order. -func (u *marshalInfo) marshal(b []byte, ptr pointer, deterministic bool) ([]byte, error) { - if atomic.LoadInt32(&u.initialized) == 0 { - u.computeMarshalInfo() - } - - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - if u.hasmarshaler { - m := ptr.asPointerTo(u.typ).Interface().(Marshaler) - b1, err := m.Marshal() - b = append(b, b1...) - return b, err - } - - var err, errreq error - // The old marshaler encodes extensions at beginning. - if u.extensions.IsValid() { - e := ptr.offset(u.extensions).toExtensions() - if u.messageset { - b, err = u.appendMessageSet(b, e, deterministic) - } else { - b, err = u.appendExtensions(b, e, deterministic) - } - if err != nil { - return b, err - } - } - if u.v1extensions.IsValid() { - m := *ptr.offset(u.v1extensions).toOldExtensions() - b, err = u.appendV1Extensions(b, m, deterministic) - if err != nil { - return b, err - } - } - for _, f := range u.fields { - if f.required && errreq == nil { - if ptr.offset(f.field).getPointer().isNil() { - // Required field is not set. - // We record the error but keep going, to give a complete marshaling. - errreq = &RequiredNotSetError{f.name} - continue - } - } - if f.isPointer && ptr.offset(f.field).getPointer().isNil() { - // nil pointer always marshals to nothing - continue - } - b, err = f.marshaler(b, ptr.offset(f.field), f.wiretag, deterministic) - if err != nil { - if err1, ok := err.(*RequiredNotSetError); ok { - // Required field in submessage is not set. - // We record the error but keep going, to give a complete marshaling. - if errreq == nil { - errreq = &RequiredNotSetError{f.name + "." + err1.field} - } - continue - } - if err == errRepeatedHasNil { - err = errors.New("proto: repeated field " + f.name + " has nil element") - } - if err == errInvalidUTF8 { - fullName := revProtoTypes[reflect.PtrTo(u.typ)] + "." + f.name - err = fmt.Errorf("proto: string field %q contains invalid UTF-8", fullName) - } - return b, err - } - } - if u.unrecognized.IsValid() { - s := *ptr.offset(u.unrecognized).toBytes() - b = append(b, s...) - } - return b, errreq -} - -// computeMarshalInfo initializes the marshal info. -func (u *marshalInfo) computeMarshalInfo() { - u.Lock() - defer u.Unlock() - if u.initialized != 0 { // non-atomic read is ok as it is protected by the lock - return - } - - t := u.typ - u.unrecognized = invalidField - u.extensions = invalidField - u.v1extensions = invalidField - u.sizecache = invalidField - - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - if reflect.PtrTo(t).Implements(marshalerType) { - u.hasmarshaler = true - atomic.StoreInt32(&u.initialized, 1) - return - } - - // get oneof implementers - var oneofImplementers []interface{} - if m, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(oneofMessage); ok { - _, _, _, oneofImplementers = m.XXX_OneofFuncs() - } - - n := t.NumField() - - // deal with XXX fields first - for i := 0; i < t.NumField(); i++ { - f := t.Field(i) - if !strings.HasPrefix(f.Name, "XXX_") { - continue - } - switch f.Name { - case "XXX_sizecache": - u.sizecache = toField(&f) - case "XXX_unrecognized": - u.unrecognized = toField(&f) - case "XXX_InternalExtensions": - u.extensions = toField(&f) - u.messageset = f.Tag.Get("protobuf_messageset") == "1" - case "XXX_extensions": - u.v1extensions = toField(&f) - case "XXX_NoUnkeyedLiteral": - // nothing to do - default: - panic("unknown XXX field: " + f.Name) - } - n-- - } - - // normal fields - fields := make([]marshalFieldInfo, n) // batch allocation - u.fields = make([]*marshalFieldInfo, 0, n) - for i, j := 0, 0; i < t.NumField(); i++ { - f := t.Field(i) - - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - field := &fields[j] - j++ - field.name = f.Name - u.fields = append(u.fields, field) - if f.Tag.Get("protobuf_oneof") != "" { - field.computeOneofFieldInfo(&f, oneofImplementers) - continue - } - if f.Tag.Get("protobuf") == "" { - // field has no tag (not in generated message), ignore it - u.fields = u.fields[:len(u.fields)-1] - j-- - continue - } - field.computeMarshalFieldInfo(&f) - } - - // fields are marshaled in tag order on the wire. - sort.Sort(byTag(u.fields)) - - atomic.StoreInt32(&u.initialized, 1) -} - -// helper for sorting fields by tag -type byTag []*marshalFieldInfo - -func (a byTag) Len() int { return len(a) } -func (a byTag) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a byTag) Less(i, j int) bool { return a[i].wiretag < a[j].wiretag } - -// getExtElemInfo returns the information to marshal an extension element. -// The info it returns is initialized. -func (u *marshalInfo) getExtElemInfo(desc *ExtensionDesc) *marshalElemInfo { - // get from cache first - u.RLock() - e, ok := u.extElems[desc.Field] - u.RUnlock() - if ok { - return e - } - - t := reflect.TypeOf(desc.ExtensionType) // pointer or slice to basic type or struct - tags := strings.Split(desc.Tag, ",") - tag, err := strconv.Atoi(tags[1]) - if err != nil { - panic("tag is not an integer") - } - wt := wiretype(tags[0]) - sizer, marshaler := typeMarshaler(t, tags, false, false) - e = &marshalElemInfo{ - wiretag: uint64(tag)<<3 | wt, - tagsize: SizeVarint(uint64(tag) << 3), - sizer: sizer, - marshaler: marshaler, - isptr: t.Kind() == reflect.Ptr, - } - - // update cache - u.Lock() - if u.extElems == nil { - u.extElems = make(map[int32]*marshalElemInfo) - } - u.extElems[desc.Field] = e - u.Unlock() - return e -} - -// computeMarshalFieldInfo fills up the information to marshal a field. -func (fi *marshalFieldInfo) computeMarshalFieldInfo(f *reflect.StructField) { - // parse protobuf tag of the field. - // tag has format of "bytes,49,opt,name=foo,def=hello!" - tags := strings.Split(f.Tag.Get("protobuf"), ",") - if tags[0] == "" { - return - } - tag, err := strconv.Atoi(tags[1]) - if err != nil { - panic("tag is not an integer") - } - wt := wiretype(tags[0]) - if tags[2] == "req" { - fi.required = true - } - fi.setTag(f, tag, wt) - fi.setMarshaler(f, tags) -} - -func (fi *marshalFieldInfo) computeOneofFieldInfo(f *reflect.StructField, oneofImplementers []interface{}) { - fi.field = toField(f) - fi.wiretag = 1<<31 - 1 // Use a large tag number, make oneofs sorted at the end. This tag will not appear on the wire. - fi.isPointer = true - fi.sizer, fi.marshaler = makeOneOfMarshaler(fi, f) - fi.oneofElems = make(map[reflect.Type]*marshalElemInfo) - - ityp := f.Type // interface type - for _, o := range oneofImplementers { - t := reflect.TypeOf(o) - if !t.Implements(ityp) { - continue - } - sf := t.Elem().Field(0) // oneof implementer is a struct with a single field - tags := strings.Split(sf.Tag.Get("protobuf"), ",") - tag, err := strconv.Atoi(tags[1]) - if err != nil { - panic("tag is not an integer") - } - wt := wiretype(tags[0]) - sizer, marshaler := typeMarshaler(sf.Type, tags, false, true) // oneof should not omit any zero value - fi.oneofElems[t.Elem()] = &marshalElemInfo{ - wiretag: uint64(tag)<<3 | wt, - tagsize: SizeVarint(uint64(tag) << 3), - sizer: sizer, - marshaler: marshaler, - } - } -} - -type oneofMessage interface { - XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{}) -} - -// wiretype returns the wire encoding of the type. -func wiretype(encoding string) uint64 { - switch encoding { - case "fixed32": - return WireFixed32 - case "fixed64": - return WireFixed64 - case "varint", "zigzag32", "zigzag64": - return WireVarint - case "bytes": - return WireBytes - case "group": - return WireStartGroup - } - panic("unknown wire type " + encoding) -} - -// setTag fills up the tag (in wire format) and its size in the info of a field. -func (fi *marshalFieldInfo) setTag(f *reflect.StructField, tag int, wt uint64) { - fi.field = toField(f) - fi.wiretag = uint64(tag)<<3 | wt - fi.tagsize = SizeVarint(uint64(tag) << 3) -} - -// setMarshaler fills up the sizer and marshaler in the info of a field. -func (fi *marshalFieldInfo) setMarshaler(f *reflect.StructField, tags []string) { - switch f.Type.Kind() { - case reflect.Map: - // map field - fi.isPointer = true - fi.sizer, fi.marshaler = makeMapMarshaler(f) - return - case reflect.Ptr, reflect.Slice: - fi.isPointer = true - } - fi.sizer, fi.marshaler = typeMarshaler(f.Type, tags, true, false) -} - -// typeMarshaler returns the sizer and marshaler of a given field. -// t is the type of the field. -// tags is the generated "protobuf" tag of the field. -// If nozero is true, zero value is not marshaled to the wire. -// If oneof is true, it is a oneof field. -func typeMarshaler(t reflect.Type, tags []string, nozero, oneof bool) (sizer, marshaler) { - encoding := tags[0] - - pointer := false - slice := false - if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 { - slice = true - t = t.Elem() - } - if t.Kind() == reflect.Ptr { - pointer = true - t = t.Elem() - } - - packed := false - proto3 := false - for i := 2; i < len(tags); i++ { - if tags[i] == "packed" { - packed = true - } - if tags[i] == "proto3" { - proto3 = true - } - } - - switch t.Kind() { - case reflect.Bool: - if pointer { - return sizeBoolPtr, appendBoolPtr - } - if slice { - if packed { - return sizeBoolPackedSlice, appendBoolPackedSlice - } - return sizeBoolSlice, appendBoolSlice - } - if nozero { - return sizeBoolValueNoZero, appendBoolValueNoZero - } - return sizeBoolValue, appendBoolValue - case reflect.Uint32: - switch encoding { - case "fixed32": - if pointer { - return sizeFixed32Ptr, appendFixed32Ptr - } - if slice { - if packed { - return sizeFixed32PackedSlice, appendFixed32PackedSlice - } - return sizeFixed32Slice, appendFixed32Slice - } - if nozero { - return sizeFixed32ValueNoZero, appendFixed32ValueNoZero - } - return sizeFixed32Value, appendFixed32Value - case "varint": - if pointer { - return sizeVarint32Ptr, appendVarint32Ptr - } - if slice { - if packed { - return sizeVarint32PackedSlice, appendVarint32PackedSlice - } - return sizeVarint32Slice, appendVarint32Slice - } - if nozero { - return sizeVarint32ValueNoZero, appendVarint32ValueNoZero - } - return sizeVarint32Value, appendVarint32Value - } - case reflect.Int32: - switch encoding { - case "fixed32": - if pointer { - return sizeFixedS32Ptr, appendFixedS32Ptr - } - if slice { - if packed { - return sizeFixedS32PackedSlice, appendFixedS32PackedSlice - } - return sizeFixedS32Slice, appendFixedS32Slice - } - if nozero { - return sizeFixedS32ValueNoZero, appendFixedS32ValueNoZero - } - return sizeFixedS32Value, appendFixedS32Value - case "varint": - if pointer { - return sizeVarintS32Ptr, appendVarintS32Ptr - } - if slice { - if packed { - return sizeVarintS32PackedSlice, appendVarintS32PackedSlice - } - return sizeVarintS32Slice, appendVarintS32Slice - } - if nozero { - return sizeVarintS32ValueNoZero, appendVarintS32ValueNoZero - } - return sizeVarintS32Value, appendVarintS32Value - case "zigzag32": - if pointer { - return sizeZigzag32Ptr, appendZigzag32Ptr - } - if slice { - if packed { - return sizeZigzag32PackedSlice, appendZigzag32PackedSlice - } - return sizeZigzag32Slice, appendZigzag32Slice - } - if nozero { - return sizeZigzag32ValueNoZero, appendZigzag32ValueNoZero - } - return sizeZigzag32Value, appendZigzag32Value - } - case reflect.Uint64: - switch encoding { - case "fixed64": - if pointer { - return sizeFixed64Ptr, appendFixed64Ptr - } - if slice { - if packed { - return sizeFixed64PackedSlice, appendFixed64PackedSlice - } - return sizeFixed64Slice, appendFixed64Slice - } - if nozero { - return sizeFixed64ValueNoZero, appendFixed64ValueNoZero - } - return sizeFixed64Value, appendFixed64Value - case "varint": - if pointer { - return sizeVarint64Ptr, appendVarint64Ptr - } - if slice { - if packed { - return sizeVarint64PackedSlice, appendVarint64PackedSlice - } - return sizeVarint64Slice, appendVarint64Slice - } - if nozero { - return sizeVarint64ValueNoZero, appendVarint64ValueNoZero - } - return sizeVarint64Value, appendVarint64Value - } - case reflect.Int64: - switch encoding { - case "fixed64": - if pointer { - return sizeFixedS64Ptr, appendFixedS64Ptr - } - if slice { - if packed { - return sizeFixedS64PackedSlice, appendFixedS64PackedSlice - } - return sizeFixedS64Slice, appendFixedS64Slice - } - if nozero { - return sizeFixedS64ValueNoZero, appendFixedS64ValueNoZero - } - return sizeFixedS64Value, appendFixedS64Value - case "varint": - if pointer { - return sizeVarintS64Ptr, appendVarintS64Ptr - } - if slice { - if packed { - return sizeVarintS64PackedSlice, appendVarintS64PackedSlice - } - return sizeVarintS64Slice, appendVarintS64Slice - } - if nozero { - return sizeVarintS64ValueNoZero, appendVarintS64ValueNoZero - } - return sizeVarintS64Value, appendVarintS64Value - case "zigzag64": - if pointer { - return sizeZigzag64Ptr, appendZigzag64Ptr - } - if slice { - if packed { - return sizeZigzag64PackedSlice, appendZigzag64PackedSlice - } - return sizeZigzag64Slice, appendZigzag64Slice - } - if nozero { - return sizeZigzag64ValueNoZero, appendZigzag64ValueNoZero - } - return sizeZigzag64Value, appendZigzag64Value - } - case reflect.Float32: - if pointer { - return sizeFloat32Ptr, appendFloat32Ptr - } - if slice { - if packed { - return sizeFloat32PackedSlice, appendFloat32PackedSlice - } - return sizeFloat32Slice, appendFloat32Slice - } - if nozero { - return sizeFloat32ValueNoZero, appendFloat32ValueNoZero - } - return sizeFloat32Value, appendFloat32Value - case reflect.Float64: - if pointer { - return sizeFloat64Ptr, appendFloat64Ptr - } - if slice { - if packed { - return sizeFloat64PackedSlice, appendFloat64PackedSlice - } - return sizeFloat64Slice, appendFloat64Slice - } - if nozero { - return sizeFloat64ValueNoZero, appendFloat64ValueNoZero - } - return sizeFloat64Value, appendFloat64Value - case reflect.String: - if pointer { - return sizeStringPtr, appendStringPtr - } - if slice { - return sizeStringSlice, appendStringSlice - } - if nozero { - return sizeStringValueNoZero, appendStringValueNoZero - } - return sizeStringValue, appendStringValue - case reflect.Slice: - if slice { - return sizeBytesSlice, appendBytesSlice - } - if oneof { - // Oneof bytes field may also have "proto3" tag. - // We want to marshal it as a oneof field. Do this - // check before the proto3 check. - return sizeBytesOneof, appendBytesOneof - } - if proto3 { - return sizeBytes3, appendBytes3 - } - return sizeBytes, appendBytes - case reflect.Struct: - switch encoding { - case "group": - if slice { - return makeGroupSliceMarshaler(getMarshalInfo(t)) - } - return makeGroupMarshaler(getMarshalInfo(t)) - case "bytes": - if slice { - return makeMessageSliceMarshaler(getMarshalInfo(t)) - } - return makeMessageMarshaler(getMarshalInfo(t)) - } - } - panic(fmt.Sprintf("unknown or mismatched type: type: %v, wire type: %v", t, encoding)) -} - -// Below are functions to size/marshal a specific type of a field. -// They are stored in the field's info, and called by function pointers. -// They have type sizer or marshaler. - -func sizeFixed32Value(_ pointer, tagsize int) int { - return 4 + tagsize -} -func sizeFixed32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toUint32() - if v == 0 { - return 0 - } - return 4 + tagsize -} -func sizeFixed32Ptr(ptr pointer, tagsize int) int { - p := *ptr.toUint32Ptr() - if p == nil { - return 0 - } - return 4 + tagsize -} -func sizeFixed32Slice(ptr pointer, tagsize int) int { - s := *ptr.toUint32Slice() - return (4 + tagsize) * len(s) -} -func sizeFixed32PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toUint32Slice() - if len(s) == 0 { - return 0 - } - return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize -} -func sizeFixedS32Value(_ pointer, tagsize int) int { - return 4 + tagsize -} -func sizeFixedS32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - if v == 0 { - return 0 - } - return 4 + tagsize -} -func sizeFixedS32Ptr(ptr pointer, tagsize int) int { - p := ptr.getInt32Ptr() - if p == nil { - return 0 - } - return 4 + tagsize -} -func sizeFixedS32Slice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - return (4 + tagsize) * len(s) -} -func sizeFixedS32PackedSlice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - if len(s) == 0 { - return 0 - } - return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize -} -func sizeFloat32Value(_ pointer, tagsize int) int { - return 4 + tagsize -} -func sizeFloat32ValueNoZero(ptr pointer, tagsize int) int { - v := math.Float32bits(*ptr.toFloat32()) - if v == 0 { - return 0 - } - return 4 + tagsize -} -func sizeFloat32Ptr(ptr pointer, tagsize int) int { - p := *ptr.toFloat32Ptr() - if p == nil { - return 0 - } - return 4 + tagsize -} -func sizeFloat32Slice(ptr pointer, tagsize int) int { - s := *ptr.toFloat32Slice() - return (4 + tagsize) * len(s) -} -func sizeFloat32PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toFloat32Slice() - if len(s) == 0 { - return 0 - } - return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize -} -func sizeFixed64Value(_ pointer, tagsize int) int { - return 8 + tagsize -} -func sizeFixed64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toUint64() - if v == 0 { - return 0 - } - return 8 + tagsize -} -func sizeFixed64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toUint64Ptr() - if p == nil { - return 0 - } - return 8 + tagsize -} -func sizeFixed64Slice(ptr pointer, tagsize int) int { - s := *ptr.toUint64Slice() - return (8 + tagsize) * len(s) -} -func sizeFixed64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toUint64Slice() - if len(s) == 0 { - return 0 - } - return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize -} -func sizeFixedS64Value(_ pointer, tagsize int) int { - return 8 + tagsize -} -func sizeFixedS64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - if v == 0 { - return 0 - } - return 8 + tagsize -} -func sizeFixedS64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toInt64Ptr() - if p == nil { - return 0 - } - return 8 + tagsize -} -func sizeFixedS64Slice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - return (8 + tagsize) * len(s) -} -func sizeFixedS64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return 0 - } - return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize -} -func sizeFloat64Value(_ pointer, tagsize int) int { - return 8 + tagsize -} -func sizeFloat64ValueNoZero(ptr pointer, tagsize int) int { - v := math.Float64bits(*ptr.toFloat64()) - if v == 0 { - return 0 - } - return 8 + tagsize -} -func sizeFloat64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toFloat64Ptr() - if p == nil { - return 0 - } - return 8 + tagsize -} -func sizeFloat64Slice(ptr pointer, tagsize int) int { - s := *ptr.toFloat64Slice() - return (8 + tagsize) * len(s) -} -func sizeFloat64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toFloat64Slice() - if len(s) == 0 { - return 0 - } - return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize -} -func sizeVarint32Value(ptr pointer, tagsize int) int { - v := *ptr.toUint32() - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarint32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toUint32() - if v == 0 { - return 0 - } - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarint32Ptr(ptr pointer, tagsize int) int { - p := *ptr.toUint32Ptr() - if p == nil { - return 0 - } - return SizeVarint(uint64(*p)) + tagsize -} -func sizeVarint32Slice(ptr pointer, tagsize int) int { - s := *ptr.toUint32Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) + tagsize - } - return n -} -func sizeVarint32PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toUint32Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeVarintS32Value(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarintS32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - if v == 0 { - return 0 - } - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarintS32Ptr(ptr pointer, tagsize int) int { - p := ptr.getInt32Ptr() - if p == nil { - return 0 - } - return SizeVarint(uint64(*p)) + tagsize -} -func sizeVarintS32Slice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) + tagsize - } - return n -} -func sizeVarintS32PackedSlice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeVarint64Value(ptr pointer, tagsize int) int { - v := *ptr.toUint64() - return SizeVarint(v) + tagsize -} -func sizeVarint64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toUint64() - if v == 0 { - return 0 - } - return SizeVarint(v) + tagsize -} -func sizeVarint64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toUint64Ptr() - if p == nil { - return 0 - } - return SizeVarint(*p) + tagsize -} -func sizeVarint64Slice(ptr pointer, tagsize int) int { - s := *ptr.toUint64Slice() - n := 0 - for _, v := range s { - n += SizeVarint(v) + tagsize - } - return n -} -func sizeVarint64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toUint64Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(v) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeVarintS64Value(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarintS64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - if v == 0 { - return 0 - } - return SizeVarint(uint64(v)) + tagsize -} -func sizeVarintS64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toInt64Ptr() - if p == nil { - return 0 - } - return SizeVarint(uint64(*p)) + tagsize -} -func sizeVarintS64Slice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) + tagsize - } - return n -} -func sizeVarintS64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeZigzag32Value(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize -} -func sizeZigzag32ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt32() - if v == 0 { - return 0 - } - return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize -} -func sizeZigzag32Ptr(ptr pointer, tagsize int) int { - p := ptr.getInt32Ptr() - if p == nil { - return 0 - } - v := *p - return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize -} -func sizeZigzag32Slice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize - } - return n -} -func sizeZigzag32PackedSlice(ptr pointer, tagsize int) int { - s := ptr.getInt32Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31)))) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeZigzag64Value(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize -} -func sizeZigzag64ValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toInt64() - if v == 0 { - return 0 - } - return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize -} -func sizeZigzag64Ptr(ptr pointer, tagsize int) int { - p := *ptr.toInt64Ptr() - if p == nil { - return 0 - } - v := *p - return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize -} -func sizeZigzag64Slice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize - } - return n -} -func sizeZigzag64PackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return 0 - } - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63))) - } - return n + SizeVarint(uint64(n)) + tagsize -} -func sizeBoolValue(_ pointer, tagsize int) int { - return 1 + tagsize -} -func sizeBoolValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toBool() - if !v { - return 0 - } - return 1 + tagsize -} -func sizeBoolPtr(ptr pointer, tagsize int) int { - p := *ptr.toBoolPtr() - if p == nil { - return 0 - } - return 1 + tagsize -} -func sizeBoolSlice(ptr pointer, tagsize int) int { - s := *ptr.toBoolSlice() - return (1 + tagsize) * len(s) -} -func sizeBoolPackedSlice(ptr pointer, tagsize int) int { - s := *ptr.toBoolSlice() - if len(s) == 0 { - return 0 - } - return len(s) + SizeVarint(uint64(len(s))) + tagsize -} -func sizeStringValue(ptr pointer, tagsize int) int { - v := *ptr.toString() - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeStringValueNoZero(ptr pointer, tagsize int) int { - v := *ptr.toString() - if v == "" { - return 0 - } - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeStringPtr(ptr pointer, tagsize int) int { - p := *ptr.toStringPtr() - if p == nil { - return 0 - } - v := *p - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeStringSlice(ptr pointer, tagsize int) int { - s := *ptr.toStringSlice() - n := 0 - for _, v := range s { - n += len(v) + SizeVarint(uint64(len(v))) + tagsize - } - return n -} -func sizeBytes(ptr pointer, tagsize int) int { - v := *ptr.toBytes() - if v == nil { - return 0 - } - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeBytes3(ptr pointer, tagsize int) int { - v := *ptr.toBytes() - if len(v) == 0 { - return 0 - } - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeBytesOneof(ptr pointer, tagsize int) int { - v := *ptr.toBytes() - return len(v) + SizeVarint(uint64(len(v))) + tagsize -} -func sizeBytesSlice(ptr pointer, tagsize int) int { - s := *ptr.toBytesSlice() - n := 0 - for _, v := range s { - n += len(v) + SizeVarint(uint64(len(v))) + tagsize - } - return n -} - -// appendFixed32 appends an encoded fixed32 to b. -func appendFixed32(b []byte, v uint32) []byte { - b = append(b, - byte(v), - byte(v>>8), - byte(v>>16), - byte(v>>24)) - return b -} - -// appendFixed64 appends an encoded fixed64 to b. -func appendFixed64(b []byte, v uint64) []byte { - b = append(b, - byte(v), - byte(v>>8), - byte(v>>16), - byte(v>>24), - byte(v>>32), - byte(v>>40), - byte(v>>48), - byte(v>>56)) - return b -} - -// appendVarint appends an encoded varint to b. -func appendVarint(b []byte, v uint64) []byte { - // TODO: make 1-byte (maybe 2-byte) case inline-able, once we - // have non-leaf inliner. - switch { - case v < 1<<7: - b = append(b, byte(v)) - case v < 1<<14: - b = append(b, - byte(v&0x7f|0x80), - byte(v>>7)) - case v < 1<<21: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte(v>>14)) - case v < 1<<28: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte(v>>21)) - case v < 1<<35: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte(v>>28)) - case v < 1<<42: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte(v>>35)) - case v < 1<<49: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte((v>>35)&0x7f|0x80), - byte(v>>42)) - case v < 1<<56: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte((v>>35)&0x7f|0x80), - byte((v>>42)&0x7f|0x80), - byte(v>>49)) - case v < 1<<63: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte((v>>35)&0x7f|0x80), - byte((v>>42)&0x7f|0x80), - byte((v>>49)&0x7f|0x80), - byte(v>>56)) - default: - b = append(b, - byte(v&0x7f|0x80), - byte((v>>7)&0x7f|0x80), - byte((v>>14)&0x7f|0x80), - byte((v>>21)&0x7f|0x80), - byte((v>>28)&0x7f|0x80), - byte((v>>35)&0x7f|0x80), - byte((v>>42)&0x7f|0x80), - byte((v>>49)&0x7f|0x80), - byte((v>>56)&0x7f|0x80), - 1) - } - return b -} - -func appendFixed32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint32() - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - return b, nil -} -func appendFixed32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - return b, nil -} -func appendFixed32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toUint32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, *p) - return b, nil -} -func appendFixed32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - } - return b, nil -} -func appendFixed32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(4*len(s))) - for _, v := range s { - b = appendFixed32(b, v) - } - return b, nil -} -func appendFixedS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - b = appendVarint(b, wiretag) - b = appendFixed32(b, uint32(v)) - return b, nil -} -func appendFixedS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, uint32(v)) - return b, nil -} -func appendFixedS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := ptr.getInt32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, uint32(*p)) - return b, nil -} -func appendFixedS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed32(b, uint32(v)) - } - return b, nil -} -func appendFixedS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(4*len(s))) - for _, v := range s { - b = appendFixed32(b, uint32(v)) - } - return b, nil -} -func appendFloat32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := math.Float32bits(*ptr.toFloat32()) - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - return b, nil -} -func appendFloat32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := math.Float32bits(*ptr.toFloat32()) - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, v) - return b, nil -} -func appendFloat32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toFloat32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed32(b, math.Float32bits(*p)) - return b, nil -} -func appendFloat32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toFloat32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed32(b, math.Float32bits(v)) - } - return b, nil -} -func appendFloat32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toFloat32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(4*len(s))) - for _, v := range s { - b = appendFixed32(b, math.Float32bits(v)) - } - return b, nil -} -func appendFixed64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint64() - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - return b, nil -} -func appendFixed64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - return b, nil -} -func appendFixed64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toUint64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, *p) - return b, nil -} -func appendFixed64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - } - return b, nil -} -func appendFixed64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(8*len(s))) - for _, v := range s { - b = appendFixed64(b, v) - } - return b, nil -} -func appendFixedS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - b = appendVarint(b, wiretag) - b = appendFixed64(b, uint64(v)) - return b, nil -} -func appendFixedS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, uint64(v)) - return b, nil -} -func appendFixedS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toInt64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, uint64(*p)) - return b, nil -} -func appendFixedS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed64(b, uint64(v)) - } - return b, nil -} -func appendFixedS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(8*len(s))) - for _, v := range s { - b = appendFixed64(b, uint64(v)) - } - return b, nil -} -func appendFloat64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := math.Float64bits(*ptr.toFloat64()) - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - return b, nil -} -func appendFloat64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := math.Float64bits(*ptr.toFloat64()) - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, v) - return b, nil -} -func appendFloat64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toFloat64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendFixed64(b, math.Float64bits(*p)) - return b, nil -} -func appendFloat64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toFloat64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendFixed64(b, math.Float64bits(v)) - } - return b, nil -} -func appendFloat64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toFloat64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(8*len(s))) - for _, v := range s { - b = appendFixed64(b, math.Float64bits(v)) - } - return b, nil -} -func appendVarint32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint32() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarint32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarint32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toUint32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(*p)) - return b, nil -} -func appendVarint32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarint32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarintS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarintS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarintS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := ptr.getInt32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(*p)) - return b, nil -} -func appendVarintS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarintS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarint64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint64() - b = appendVarint(b, wiretag) - b = appendVarint(b, v) - return b, nil -} -func appendVarint64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toUint64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, v) - return b, nil -} -func appendVarint64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toUint64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, *p) - return b, nil -} -func appendVarint64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, v) - } - return b, nil -} -func appendVarint64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toUint64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(v) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, v) - } - return b, nil -} -func appendVarintS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarintS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - return b, nil -} -func appendVarintS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toInt64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(*p)) - return b, nil -} -func appendVarintS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendVarintS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v)) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64(v)) - } - return b, nil -} -func appendZigzag32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - return b, nil -} -func appendZigzag32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt32() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - return b, nil -} -func appendZigzag32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := ptr.getInt32Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - v := *p - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - return b, nil -} -func appendZigzag32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - } - return b, nil -} -func appendZigzag32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := ptr.getInt32Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31)))) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) - } - return b, nil -} -func appendZigzag64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - return b, nil -} -func appendZigzag64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toInt64() - if v == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - return b, nil -} -func appendZigzag64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toInt64Ptr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - v := *p - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - return b, nil -} -func appendZigzag64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - } - return b, nil -} -func appendZigzag64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toInt64Slice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - // compute size - n := 0 - for _, v := range s { - n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63))) - } - b = appendVarint(b, uint64(n)) - for _, v := range s { - b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) - } - return b, nil -} -func appendBoolValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBool() - b = appendVarint(b, wiretag) - if v { - b = append(b, 1) - } else { - b = append(b, 0) - } - return b, nil -} -func appendBoolValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBool() - if !v { - return b, nil - } - b = appendVarint(b, wiretag) - b = append(b, 1) - return b, nil -} - -func appendBoolPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toBoolPtr() - if p == nil { - return b, nil - } - b = appendVarint(b, wiretag) - if *p { - b = append(b, 1) - } else { - b = append(b, 0) - } - return b, nil -} -func appendBoolSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toBoolSlice() - for _, v := range s { - b = appendVarint(b, wiretag) - if v { - b = append(b, 1) - } else { - b = append(b, 0) - } - } - return b, nil -} -func appendBoolPackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toBoolSlice() - if len(s) == 0 { - return b, nil - } - b = appendVarint(b, wiretag&^7|WireBytes) - b = appendVarint(b, uint64(len(s))) - for _, v := range s { - if v { - b = append(b, 1) - } else { - b = append(b, 0) - } - } - return b, nil -} -func appendStringValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toString() - if !utf8.ValidString(v) { - return nil, errInvalidUTF8 - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendStringValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toString() - if v == "" { - return b, nil - } - if !utf8.ValidString(v) { - return nil, errInvalidUTF8 - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendStringPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - p := *ptr.toStringPtr() - if p == nil { - return b, nil - } - v := *p - if !utf8.ValidString(v) { - return nil, errInvalidUTF8 - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendStringSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toStringSlice() - for _, v := range s { - if !utf8.ValidString(v) { - return nil, errInvalidUTF8 - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - } - return b, nil -} -func appendBytes(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBytes() - if v == nil { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendBytes3(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBytes() - if len(v) == 0 { - return b, nil - } - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendBytesOneof(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - v := *ptr.toBytes() - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - return b, nil -} -func appendBytesSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { - s := *ptr.toBytesSlice() - for _, v := range s { - b = appendVarint(b, wiretag) - b = appendVarint(b, uint64(len(v))) - b = append(b, v...) - } - return b, nil -} - -// makeGroupMarshaler returns the sizer and marshaler for a group. -// u is the marshal info of the underlying message. -func makeGroupMarshaler(u *marshalInfo) (sizer, marshaler) { - return func(ptr pointer, tagsize int) int { - p := ptr.getPointer() - if p.isNil() { - return 0 - } - return u.size(p) + 2*tagsize - }, - func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { - p := ptr.getPointer() - if p.isNil() { - return b, nil - } - var err error - b = appendVarint(b, wiretag) // start group - b, err = u.marshal(b, p, deterministic) - b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group - return b, err - } -} - -// makeGroupSliceMarshaler returns the sizer and marshaler for a group slice. -// u is the marshal info of the underlying message. -func makeGroupSliceMarshaler(u *marshalInfo) (sizer, marshaler) { - return func(ptr pointer, tagsize int) int { - s := ptr.getPointerSlice() - n := 0 - for _, v := range s { - if v.isNil() { - continue - } - n += u.size(v) + 2*tagsize - } - return n - }, - func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { - s := ptr.getPointerSlice() - var err, errreq error - for _, v := range s { - if v.isNil() { - return b, errRepeatedHasNil - } - b = appendVarint(b, wiretag) // start group - b, err = u.marshal(b, v, deterministic) - b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group - if err != nil { - if _, ok := err.(*RequiredNotSetError); ok { - // Required field in submessage is not set. - // We record the error but keep going, to give a complete marshaling. - if errreq == nil { - errreq = err - } - continue - } - if err == ErrNil { - err = errRepeatedHasNil - } - return b, err - } - } - return b, errreq - } -} - -// makeMessageMarshaler returns the sizer and marshaler for a message field. -// u is the marshal info of the message. -func makeMessageMarshaler(u *marshalInfo) (sizer, marshaler) { - return func(ptr pointer, tagsize int) int { - p := ptr.getPointer() - if p.isNil() { - return 0 - } - siz := u.size(p) - return siz + SizeVarint(uint64(siz)) + tagsize - }, - func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { - p := ptr.getPointer() - if p.isNil() { - return b, nil - } - b = appendVarint(b, wiretag) - siz := u.cachedsize(p) - b = appendVarint(b, uint64(siz)) - return u.marshal(b, p, deterministic) - } -} - -// makeMessageSliceMarshaler returns the sizer and marshaler for a message slice. -// u is the marshal info of the message. -func makeMessageSliceMarshaler(u *marshalInfo) (sizer, marshaler) { - return func(ptr pointer, tagsize int) int { - s := ptr.getPointerSlice() - n := 0 - for _, v := range s { - if v.isNil() { - continue - } - siz := u.size(v) - n += siz + SizeVarint(uint64(siz)) + tagsize - } - return n - }, - func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { - s := ptr.getPointerSlice() - var err, errreq error - for _, v := range s { - if v.isNil() { - return b, errRepeatedHasNil - } - b = appendVarint(b, wiretag) - siz := u.cachedsize(v) - b = appendVarint(b, uint64(siz)) - b, err = u.marshal(b, v, deterministic) - - if err != nil { - if _, ok := err.(*RequiredNotSetError); ok { - // Required field in submessage is not set. - // We record the error but keep going, to give a complete marshaling. - if errreq == nil { - errreq = err - } - continue - } - if err == ErrNil { - err = errRepeatedHasNil - } - return b, err - } - } - return b, errreq - } -} - -// makeMapMarshaler returns the sizer and marshaler for a map field. -// f is the pointer to the reflect data structure of the field. -func makeMapMarshaler(f *reflect.StructField) (sizer, marshaler) { - // figure out key and value type - t := f.Type - keyType := t.Key() - valType := t.Elem() - keyTags := strings.Split(f.Tag.Get("protobuf_key"), ",") - valTags := strings.Split(f.Tag.Get("protobuf_val"), ",") - keySizer, keyMarshaler := typeMarshaler(keyType, keyTags, false, false) // don't omit zero value in map - valSizer, valMarshaler := typeMarshaler(valType, valTags, false, false) // don't omit zero value in map - keyWireTag := 1<<3 | wiretype(keyTags[0]) - valWireTag := 2<<3 | wiretype(valTags[0]) - - // We create an interface to get the addresses of the map key and value. - // If value is pointer-typed, the interface is a direct interface, the - // idata itself is the value. Otherwise, the idata is the pointer to the - // value. - // Key cannot be pointer-typed. - valIsPtr := valType.Kind() == reflect.Ptr - return func(ptr pointer, tagsize int) int { - m := ptr.asPointerTo(t).Elem() // the map - n := 0 - for _, k := range m.MapKeys() { - ki := k.Interface() - vi := m.MapIndex(k).Interface() - kaddr := toAddrPointer(&ki, false) // pointer to key - vaddr := toAddrPointer(&vi, valIsPtr) // pointer to value - siz := keySizer(kaddr, 1) + valSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1) - n += siz + SizeVarint(uint64(siz)) + tagsize - } - return n - }, - func(b []byte, ptr pointer, tag uint64, deterministic bool) ([]byte, error) { - m := ptr.asPointerTo(t).Elem() // the map - var err error - keys := m.MapKeys() - if len(keys) > 1 && deterministic { - sort.Sort(mapKeys(keys)) - } - for _, k := range keys { - ki := k.Interface() - vi := m.MapIndex(k).Interface() - kaddr := toAddrPointer(&ki, false) // pointer to key - vaddr := toAddrPointer(&vi, valIsPtr) // pointer to value - b = appendVarint(b, tag) - siz := keySizer(kaddr, 1) + valSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1) - b = appendVarint(b, uint64(siz)) - b, err = keyMarshaler(b, kaddr, keyWireTag, deterministic) - if err != nil { - return b, err - } - b, err = valMarshaler(b, vaddr, valWireTag, deterministic) - if err != nil && err != ErrNil { // allow nil value in map - return b, err - } - } - return b, nil - } -} - -// makeOneOfMarshaler returns the sizer and marshaler for a oneof field. -// fi is the marshal info of the field. -// f is the pointer to the reflect data structure of the field. -func makeOneOfMarshaler(fi *marshalFieldInfo, f *reflect.StructField) (sizer, marshaler) { - // Oneof field is an interface. We need to get the actual data type on the fly. - t := f.Type - return func(ptr pointer, _ int) int { - p := ptr.getInterfacePointer() - if p.isNil() { - return 0 - } - v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct - telem := v.Type() - e := fi.oneofElems[telem] - return e.sizer(p, e.tagsize) - }, - func(b []byte, ptr pointer, _ uint64, deterministic bool) ([]byte, error) { - p := ptr.getInterfacePointer() - if p.isNil() { - return b, nil - } - v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct - telem := v.Type() - if telem.Field(0).Type.Kind() == reflect.Ptr && p.getPointer().isNil() { - return b, errOneofHasNil - } - e := fi.oneofElems[telem] - return e.marshaler(b, p, e.wiretag, deterministic) - } -} - -// sizeExtensions computes the size of encoded data for a XXX_InternalExtensions field. -func (u *marshalInfo) sizeExtensions(ext *XXX_InternalExtensions) int { - m, mu := ext.extensionsRead() - if m == nil { - return 0 - } - mu.Lock() - - n := 0 - for _, e := range m { - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - n += len(e.enc) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - n += ei.sizer(p, ei.tagsize) - } - mu.Unlock() - return n -} - -// appendExtensions marshals a XXX_InternalExtensions field to the end of byte slice b. -func (u *marshalInfo) appendExtensions(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) { - m, mu := ext.extensionsRead() - if m == nil { - return b, nil - } - mu.Lock() - defer mu.Unlock() - - var err error - - // Fast-path for common cases: zero or one extensions. - // Don't bother sorting the keys. - if len(m) <= 1 { - for _, e := range m { - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - b = append(b, e.enc...) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - b, err = ei.marshaler(b, p, ei.wiretag, deterministic) - if err != nil { - return b, err - } - } - return b, nil - } - - // Sort the keys to provide a deterministic encoding. - // Not sure this is required, but the old code does it. - keys := make([]int, 0, len(m)) - for k := range m { - keys = append(keys, int(k)) - } - sort.Ints(keys) - - for _, k := range keys { - e := m[int32(k)] - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - b = append(b, e.enc...) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - b, err = ei.marshaler(b, p, ei.wiretag, deterministic) - if err != nil { - return b, err - } - } - return b, nil -} - -// message set format is: -// message MessageSet { -// repeated group Item = 1 { -// required int32 type_id = 2; -// required string message = 3; -// }; -// } - -// sizeMessageSet computes the size of encoded data for a XXX_InternalExtensions field -// in message set format (above). -func (u *marshalInfo) sizeMessageSet(ext *XXX_InternalExtensions) int { - m, mu := ext.extensionsRead() - if m == nil { - return 0 - } - mu.Lock() - - n := 0 - for id, e := range m { - n += 2 // start group, end group. tag = 1 (size=1) - n += SizeVarint(uint64(id)) + 1 // type_id, tag = 2 (size=1) - - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint - siz := len(msgWithLen) - n += siz + 1 // message, tag = 3 (size=1) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - n += ei.sizer(p, 1) // message, tag = 3 (size=1) - } - mu.Unlock() - return n -} - -// appendMessageSet marshals a XXX_InternalExtensions field in message set format (above) -// to the end of byte slice b. -func (u *marshalInfo) appendMessageSet(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) { - m, mu := ext.extensionsRead() - if m == nil { - return b, nil - } - mu.Lock() - defer mu.Unlock() - - var err error - - // Fast-path for common cases: zero or one extensions. - // Don't bother sorting the keys. - if len(m) <= 1 { - for id, e := range m { - b = append(b, 1<<3|WireStartGroup) - b = append(b, 2<<3|WireVarint) - b = appendVarint(b, uint64(id)) - - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint - b = append(b, 3<<3|WireBytes) - b = append(b, msgWithLen...) - b = append(b, 1<<3|WireEndGroup) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic) - if err != nil { - return b, err - } - b = append(b, 1<<3|WireEndGroup) - } - return b, nil - } - - // Sort the keys to provide a deterministic encoding. - keys := make([]int, 0, len(m)) - for k := range m { - keys = append(keys, int(k)) - } - sort.Ints(keys) - - for _, id := range keys { - e := m[int32(id)] - b = append(b, 1<<3|WireStartGroup) - b = append(b, 2<<3|WireVarint) - b = appendVarint(b, uint64(id)) - - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint - b = append(b, 3<<3|WireBytes) - b = append(b, msgWithLen...) - b = append(b, 1<<3|WireEndGroup) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic) - b = append(b, 1<<3|WireEndGroup) - if err != nil { - return b, err - } - } - return b, nil -} - -// sizeV1Extensions computes the size of encoded data for a V1-API extension field. -func (u *marshalInfo) sizeV1Extensions(m map[int32]Extension) int { - if m == nil { - return 0 - } - - n := 0 - for _, e := range m { - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - n += len(e.enc) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - n += ei.sizer(p, ei.tagsize) - } - return n -} - -// appendV1Extensions marshals a V1-API extension field to the end of byte slice b. -func (u *marshalInfo) appendV1Extensions(b []byte, m map[int32]Extension, deterministic bool) ([]byte, error) { - if m == nil { - return b, nil - } - - // Sort the keys to provide a deterministic encoding. - keys := make([]int, 0, len(m)) - for k := range m { - keys = append(keys, int(k)) - } - sort.Ints(keys) - - var err error - for _, k := range keys { - e := m[int32(k)] - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - b = append(b, e.enc...) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - ei := u.getExtElemInfo(e.desc) - v := e.value - p := toAddrPointer(&v, ei.isptr) - b, err = ei.marshaler(b, p, ei.wiretag, deterministic) - if err != nil { - return b, err - } - } - return b, nil -} - -// newMarshaler is the interface representing objects that can marshal themselves. -// -// This exists to support protoc-gen-go generated messages. -// The proto package will stop type-asserting to this interface in the future. -// -// DO NOT DEPEND ON THIS. -type newMarshaler interface { - XXX_Size() int - XXX_Marshal(b []byte, deterministic bool) ([]byte, error) -} - -// Size returns the encoded size of a protocol buffer message. -// This is the main entry point. -func Size(pb Message) int { - if m, ok := pb.(newMarshaler); ok { - return m.XXX_Size() - } - if m, ok := pb.(Marshaler); ok { - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - b, _ := m.Marshal() - return len(b) - } - // in case somehow we didn't generate the wrapper - if pb == nil { - return 0 - } - var info InternalMessageInfo - return info.Size(pb) -} - -// Marshal takes a protocol buffer message -// and encodes it into the wire format, returning the data. -// This is the main entry point. -func Marshal(pb Message) ([]byte, error) { - if m, ok := pb.(newMarshaler); ok { - siz := m.XXX_Size() - b := make([]byte, 0, siz) - return m.XXX_Marshal(b, false) - } - if m, ok := pb.(Marshaler); ok { - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - return m.Marshal() - } - // in case somehow we didn't generate the wrapper - if pb == nil { - return nil, ErrNil - } - var info InternalMessageInfo - siz := info.Size(pb) - b := make([]byte, 0, siz) - return info.Marshal(b, pb, false) -} - -// Marshal takes a protocol buffer message -// and encodes it into the wire format, writing the result to the -// Buffer. -// This is an alternative entry point. It is not necessary to use -// a Buffer for most applications. -func (p *Buffer) Marshal(pb Message) error { - var err error - if m, ok := pb.(newMarshaler); ok { - siz := m.XXX_Size() - p.grow(siz) // make sure buf has enough capacity - p.buf, err = m.XXX_Marshal(p.buf, p.deterministic) - return err - } - if m, ok := pb.(Marshaler); ok { - // If the message can marshal itself, let it do it, for compatibility. - // NOTE: This is not efficient. - b, err := m.Marshal() - p.buf = append(p.buf, b...) - return err - } - // in case somehow we didn't generate the wrapper - if pb == nil { - return ErrNil - } - var info InternalMessageInfo - siz := info.Size(pb) - p.grow(siz) // make sure buf has enough capacity - p.buf, err = info.Marshal(p.buf, pb, p.deterministic) - return err -} - -// grow grows the buffer's capacity, if necessary, to guarantee space for -// another n bytes. After grow(n), at least n bytes can be written to the -// buffer without another allocation. -func (p *Buffer) grow(n int) { - need := len(p.buf) + n - if need <= cap(p.buf) { - return - } - newCap := len(p.buf) * 2 - if newCap < need { - newCap = need - } - p.buf = append(make([]byte, 0, newCap), p.buf...) -} diff --git a/vendor/github.com/golang/protobuf/proto/table_merge.go b/vendor/github.com/golang/protobuf/proto/table_merge.go deleted file mode 100644 index 5525def6..00000000 --- a/vendor/github.com/golang/protobuf/proto/table_merge.go +++ /dev/null @@ -1,654 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 -// OWNER 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. - -package proto - -import ( - "fmt" - "reflect" - "strings" - "sync" - "sync/atomic" -) - -// Merge merges the src message into dst. -// This assumes that dst and src of the same type and are non-nil. -func (a *InternalMessageInfo) Merge(dst, src Message) { - mi := atomicLoadMergeInfo(&a.merge) - if mi == nil { - mi = getMergeInfo(reflect.TypeOf(dst).Elem()) - atomicStoreMergeInfo(&a.merge, mi) - } - mi.merge(toPointer(&dst), toPointer(&src)) -} - -type mergeInfo struct { - typ reflect.Type - - initialized int32 // 0: only typ is valid, 1: everything is valid - lock sync.Mutex - - fields []mergeFieldInfo - unrecognized field // Offset of XXX_unrecognized -} - -type mergeFieldInfo struct { - field field // Offset of field, guaranteed to be valid - - // isPointer reports whether the value in the field is a pointer. - // This is true for the following situations: - // * Pointer to struct - // * Pointer to basic type (proto2 only) - // * Slice (first value in slice header is a pointer) - // * String (first value in string header is a pointer) - isPointer bool - - // basicWidth reports the width of the field assuming that it is directly - // embedded in the struct (as is the case for basic types in proto3). - // The possible values are: - // 0: invalid - // 1: bool - // 4: int32, uint32, float32 - // 8: int64, uint64, float64 - basicWidth int - - // Where dst and src are pointers to the types being merged. - merge func(dst, src pointer) -} - -var ( - mergeInfoMap = map[reflect.Type]*mergeInfo{} - mergeInfoLock sync.Mutex -) - -func getMergeInfo(t reflect.Type) *mergeInfo { - mergeInfoLock.Lock() - defer mergeInfoLock.Unlock() - mi := mergeInfoMap[t] - if mi == nil { - mi = &mergeInfo{typ: t} - mergeInfoMap[t] = mi - } - return mi -} - -// merge merges src into dst assuming they are both of type *mi.typ. -func (mi *mergeInfo) merge(dst, src pointer) { - if dst.isNil() { - panic("proto: nil destination") - } - if src.isNil() { - return // Nothing to do. - } - - if atomic.LoadInt32(&mi.initialized) == 0 { - mi.computeMergeInfo() - } - - for _, fi := range mi.fields { - sfp := src.offset(fi.field) - - // As an optimization, we can avoid the merge function call cost - // if we know for sure that the source will have no effect - // by checking if it is the zero value. - if unsafeAllowed { - if fi.isPointer && sfp.getPointer().isNil() { // Could be slice or string - continue - } - if fi.basicWidth > 0 { - switch { - case fi.basicWidth == 1 && !*sfp.toBool(): - continue - case fi.basicWidth == 4 && *sfp.toUint32() == 0: - continue - case fi.basicWidth == 8 && *sfp.toUint64() == 0: - continue - } - } - } - - dfp := dst.offset(fi.field) - fi.merge(dfp, sfp) - } - - // TODO: Make this faster? - out := dst.asPointerTo(mi.typ).Elem() - in := src.asPointerTo(mi.typ).Elem() - if emIn, err := extendable(in.Addr().Interface()); err == nil { - emOut, _ := extendable(out.Addr().Interface()) - mIn, muIn := emIn.extensionsRead() - if mIn != nil { - mOut := emOut.extensionsWrite() - muIn.Lock() - mergeExtension(mOut, mIn) - muIn.Unlock() - } - } - - if mi.unrecognized.IsValid() { - if b := *src.offset(mi.unrecognized).toBytes(); len(b) > 0 { - *dst.offset(mi.unrecognized).toBytes() = append([]byte(nil), b...) - } - } -} - -func (mi *mergeInfo) computeMergeInfo() { - mi.lock.Lock() - defer mi.lock.Unlock() - if mi.initialized != 0 { - return - } - t := mi.typ - n := t.NumField() - - props := GetProperties(t) - for i := 0; i < n; i++ { - f := t.Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - - mfi := mergeFieldInfo{field: toField(&f)} - tf := f.Type - - // As an optimization, we can avoid the merge function call cost - // if we know for sure that the source will have no effect - // by checking if it is the zero value. - if unsafeAllowed { - switch tf.Kind() { - case reflect.Ptr, reflect.Slice, reflect.String: - // As a special case, we assume slices and strings are pointers - // since we know that the first field in the SliceSlice or - // StringHeader is a data pointer. - mfi.isPointer = true - case reflect.Bool: - mfi.basicWidth = 1 - case reflect.Int32, reflect.Uint32, reflect.Float32: - mfi.basicWidth = 4 - case reflect.Int64, reflect.Uint64, reflect.Float64: - mfi.basicWidth = 8 - } - } - - // Unwrap tf to get at its most basic type. - var isPointer, isSlice bool - if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 { - isSlice = true - tf = tf.Elem() - } - if tf.Kind() == reflect.Ptr { - isPointer = true - tf = tf.Elem() - } - if isPointer && isSlice && tf.Kind() != reflect.Struct { - panic("both pointer and slice for basic type in " + tf.Name()) - } - - switch tf.Kind() { - case reflect.Int32: - switch { - case isSlice: // E.g., []int32 - mfi.merge = func(dst, src pointer) { - // NOTE: toInt32Slice is not defined (see pointer_reflect.go). - /* - sfsp := src.toInt32Slice() - if *sfsp != nil { - dfsp := dst.toInt32Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []int64{} - } - } - */ - sfs := src.getInt32Slice() - if sfs != nil { - dfs := dst.getInt32Slice() - dfs = append(dfs, sfs...) - if dfs == nil { - dfs = []int32{} - } - dst.setInt32Slice(dfs) - } - } - case isPointer: // E.g., *int32 - mfi.merge = func(dst, src pointer) { - // NOTE: toInt32Ptr is not defined (see pointer_reflect.go). - /* - sfpp := src.toInt32Ptr() - if *sfpp != nil { - dfpp := dst.toInt32Ptr() - if *dfpp == nil { - *dfpp = Int32(**sfpp) - } else { - **dfpp = **sfpp - } - } - */ - sfp := src.getInt32Ptr() - if sfp != nil { - dfp := dst.getInt32Ptr() - if dfp == nil { - dst.setInt32Ptr(*sfp) - } else { - *dfp = *sfp - } - } - } - default: // E.g., int32 - mfi.merge = func(dst, src pointer) { - if v := *src.toInt32(); v != 0 { - *dst.toInt32() = v - } - } - } - case reflect.Int64: - switch { - case isSlice: // E.g., []int64 - mfi.merge = func(dst, src pointer) { - sfsp := src.toInt64Slice() - if *sfsp != nil { - dfsp := dst.toInt64Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []int64{} - } - } - } - case isPointer: // E.g., *int64 - mfi.merge = func(dst, src pointer) { - sfpp := src.toInt64Ptr() - if *sfpp != nil { - dfpp := dst.toInt64Ptr() - if *dfpp == nil { - *dfpp = Int64(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., int64 - mfi.merge = func(dst, src pointer) { - if v := *src.toInt64(); v != 0 { - *dst.toInt64() = v - } - } - } - case reflect.Uint32: - switch { - case isSlice: // E.g., []uint32 - mfi.merge = func(dst, src pointer) { - sfsp := src.toUint32Slice() - if *sfsp != nil { - dfsp := dst.toUint32Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []uint32{} - } - } - } - case isPointer: // E.g., *uint32 - mfi.merge = func(dst, src pointer) { - sfpp := src.toUint32Ptr() - if *sfpp != nil { - dfpp := dst.toUint32Ptr() - if *dfpp == nil { - *dfpp = Uint32(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., uint32 - mfi.merge = func(dst, src pointer) { - if v := *src.toUint32(); v != 0 { - *dst.toUint32() = v - } - } - } - case reflect.Uint64: - switch { - case isSlice: // E.g., []uint64 - mfi.merge = func(dst, src pointer) { - sfsp := src.toUint64Slice() - if *sfsp != nil { - dfsp := dst.toUint64Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []uint64{} - } - } - } - case isPointer: // E.g., *uint64 - mfi.merge = func(dst, src pointer) { - sfpp := src.toUint64Ptr() - if *sfpp != nil { - dfpp := dst.toUint64Ptr() - if *dfpp == nil { - *dfpp = Uint64(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., uint64 - mfi.merge = func(dst, src pointer) { - if v := *src.toUint64(); v != 0 { - *dst.toUint64() = v - } - } - } - case reflect.Float32: - switch { - case isSlice: // E.g., []float32 - mfi.merge = func(dst, src pointer) { - sfsp := src.toFloat32Slice() - if *sfsp != nil { - dfsp := dst.toFloat32Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []float32{} - } - } - } - case isPointer: // E.g., *float32 - mfi.merge = func(dst, src pointer) { - sfpp := src.toFloat32Ptr() - if *sfpp != nil { - dfpp := dst.toFloat32Ptr() - if *dfpp == nil { - *dfpp = Float32(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., float32 - mfi.merge = func(dst, src pointer) { - if v := *src.toFloat32(); v != 0 { - *dst.toFloat32() = v - } - } - } - case reflect.Float64: - switch { - case isSlice: // E.g., []float64 - mfi.merge = func(dst, src pointer) { - sfsp := src.toFloat64Slice() - if *sfsp != nil { - dfsp := dst.toFloat64Slice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []float64{} - } - } - } - case isPointer: // E.g., *float64 - mfi.merge = func(dst, src pointer) { - sfpp := src.toFloat64Ptr() - if *sfpp != nil { - dfpp := dst.toFloat64Ptr() - if *dfpp == nil { - *dfpp = Float64(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., float64 - mfi.merge = func(dst, src pointer) { - if v := *src.toFloat64(); v != 0 { - *dst.toFloat64() = v - } - } - } - case reflect.Bool: - switch { - case isSlice: // E.g., []bool - mfi.merge = func(dst, src pointer) { - sfsp := src.toBoolSlice() - if *sfsp != nil { - dfsp := dst.toBoolSlice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []bool{} - } - } - } - case isPointer: // E.g., *bool - mfi.merge = func(dst, src pointer) { - sfpp := src.toBoolPtr() - if *sfpp != nil { - dfpp := dst.toBoolPtr() - if *dfpp == nil { - *dfpp = Bool(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., bool - mfi.merge = func(dst, src pointer) { - if v := *src.toBool(); v { - *dst.toBool() = v - } - } - } - case reflect.String: - switch { - case isSlice: // E.g., []string - mfi.merge = func(dst, src pointer) { - sfsp := src.toStringSlice() - if *sfsp != nil { - dfsp := dst.toStringSlice() - *dfsp = append(*dfsp, *sfsp...) - if *dfsp == nil { - *dfsp = []string{} - } - } - } - case isPointer: // E.g., *string - mfi.merge = func(dst, src pointer) { - sfpp := src.toStringPtr() - if *sfpp != nil { - dfpp := dst.toStringPtr() - if *dfpp == nil { - *dfpp = String(**sfpp) - } else { - **dfpp = **sfpp - } - } - } - default: // E.g., string - mfi.merge = func(dst, src pointer) { - if v := *src.toString(); v != "" { - *dst.toString() = v - } - } - } - case reflect.Slice: - isProto3 := props.Prop[i].proto3 - switch { - case isPointer: - panic("bad pointer in byte slice case in " + tf.Name()) - case tf.Elem().Kind() != reflect.Uint8: - panic("bad element kind in byte slice case in " + tf.Name()) - case isSlice: // E.g., [][]byte - mfi.merge = func(dst, src pointer) { - sbsp := src.toBytesSlice() - if *sbsp != nil { - dbsp := dst.toBytesSlice() - for _, sb := range *sbsp { - if sb == nil { - *dbsp = append(*dbsp, nil) - } else { - *dbsp = append(*dbsp, append([]byte{}, sb...)) - } - } - if *dbsp == nil { - *dbsp = [][]byte{} - } - } - } - default: // E.g., []byte - mfi.merge = func(dst, src pointer) { - sbp := src.toBytes() - if *sbp != nil { - dbp := dst.toBytes() - if !isProto3 || len(*sbp) > 0 { - *dbp = append([]byte{}, *sbp...) - } - } - } - } - case reflect.Struct: - switch { - case !isPointer: - panic(fmt.Sprintf("message field %s without pointer", tf)) - case isSlice: // E.g., []*pb.T - mi := getMergeInfo(tf) - mfi.merge = func(dst, src pointer) { - sps := src.getPointerSlice() - if sps != nil { - dps := dst.getPointerSlice() - for _, sp := range sps { - var dp pointer - if !sp.isNil() { - dp = valToPointer(reflect.New(tf)) - mi.merge(dp, sp) - } - dps = append(dps, dp) - } - if dps == nil { - dps = []pointer{} - } - dst.setPointerSlice(dps) - } - } - default: // E.g., *pb.T - mi := getMergeInfo(tf) - mfi.merge = func(dst, src pointer) { - sp := src.getPointer() - if !sp.isNil() { - dp := dst.getPointer() - if dp.isNil() { - dp = valToPointer(reflect.New(tf)) - dst.setPointer(dp) - } - mi.merge(dp, sp) - } - } - } - case reflect.Map: - switch { - case isPointer || isSlice: - panic("bad pointer or slice in map case in " + tf.Name()) - default: // E.g., map[K]V - mfi.merge = func(dst, src pointer) { - sm := src.asPointerTo(tf).Elem() - if sm.Len() == 0 { - return - } - dm := dst.asPointerTo(tf).Elem() - if dm.IsNil() { - dm.Set(reflect.MakeMap(tf)) - } - - switch tf.Elem().Kind() { - case reflect.Ptr: // Proto struct (e.g., *T) - for _, key := range sm.MapKeys() { - val := sm.MapIndex(key) - val = reflect.ValueOf(Clone(val.Interface().(Message))) - dm.SetMapIndex(key, val) - } - case reflect.Slice: // E.g. Bytes type (e.g., []byte) - for _, key := range sm.MapKeys() { - val := sm.MapIndex(key) - val = reflect.ValueOf(append([]byte{}, val.Bytes()...)) - dm.SetMapIndex(key, val) - } - default: // Basic type (e.g., string) - for _, key := range sm.MapKeys() { - val := sm.MapIndex(key) - dm.SetMapIndex(key, val) - } - } - } - } - case reflect.Interface: - // Must be oneof field. - switch { - case isPointer || isSlice: - panic("bad pointer or slice in interface case in " + tf.Name()) - default: // E.g., interface{} - // TODO: Make this faster? - mfi.merge = func(dst, src pointer) { - su := src.asPointerTo(tf).Elem() - if !su.IsNil() { - du := dst.asPointerTo(tf).Elem() - typ := su.Elem().Type() - if du.IsNil() || du.Elem().Type() != typ { - du.Set(reflect.New(typ.Elem())) // Initialize interface if empty - } - sv := su.Elem().Elem().Field(0) - if sv.Kind() == reflect.Ptr && sv.IsNil() { - return - } - dv := du.Elem().Elem().Field(0) - if dv.Kind() == reflect.Ptr && dv.IsNil() { - dv.Set(reflect.New(sv.Type().Elem())) // Initialize proto message if empty - } - switch sv.Type().Kind() { - case reflect.Ptr: // Proto struct (e.g., *T) - Merge(dv.Interface().(Message), sv.Interface().(Message)) - case reflect.Slice: // E.g. Bytes type (e.g., []byte) - dv.Set(reflect.ValueOf(append([]byte{}, sv.Bytes()...))) - default: // Basic type (e.g., string) - dv.Set(sv) - } - } - } - } - default: - panic(fmt.Sprintf("merger not found for type:%s", tf)) - } - mi.fields = append(mi.fields, mfi) - } - - mi.unrecognized = invalidField - if f, ok := t.FieldByName("XXX_unrecognized"); ok { - if f.Type != reflect.TypeOf([]byte{}) { - panic("expected XXX_unrecognized to be of type []byte") - } - mi.unrecognized = toField(&f) - } - - atomic.StoreInt32(&mi.initialized, 1) -} diff --git a/vendor/github.com/golang/protobuf/proto/table_unmarshal.go b/vendor/github.com/golang/protobuf/proto/table_unmarshal.go deleted file mode 100644 index 96764347..00000000 --- a/vendor/github.com/golang/protobuf/proto/table_unmarshal.go +++ /dev/null @@ -1,1981 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 -// OWNER 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. - -package proto - -import ( - "errors" - "fmt" - "io" - "math" - "reflect" - "strconv" - "strings" - "sync" - "sync/atomic" - "unicode/utf8" -) - -// Unmarshal is the entry point from the generated .pb.go files. -// This function is not intended to be used by non-generated code. -// This function is not subject to any compatibility guarantee. -// msg contains a pointer to a protocol buffer struct. -// b is the data to be unmarshaled into the protocol buffer. -// a is a pointer to a place to store cached unmarshal information. -func (a *InternalMessageInfo) Unmarshal(msg Message, b []byte) error { - // Load the unmarshal information for this message type. - // The atomic load ensures memory consistency. - u := atomicLoadUnmarshalInfo(&a.unmarshal) - if u == nil { - // Slow path: find unmarshal info for msg, update a with it. - u = getUnmarshalInfo(reflect.TypeOf(msg).Elem()) - atomicStoreUnmarshalInfo(&a.unmarshal, u) - } - // Then do the unmarshaling. - err := u.unmarshal(toPointer(&msg), b) - return err -} - -type unmarshalInfo struct { - typ reflect.Type // type of the protobuf struct - - // 0 = only typ field is initialized - // 1 = completely initialized - initialized int32 - lock sync.Mutex // prevents double initialization - dense []unmarshalFieldInfo // fields indexed by tag # - sparse map[uint64]unmarshalFieldInfo // fields indexed by tag # - reqFields []string // names of required fields - reqMask uint64 // 1< 0 { - // Read tag and wire type. - // Special case 1 and 2 byte varints. - var x uint64 - if b[0] < 128 { - x = uint64(b[0]) - b = b[1:] - } else if len(b) >= 2 && b[1] < 128 { - x = uint64(b[0]&0x7f) + uint64(b[1])<<7 - b = b[2:] - } else { - var n int - x, n = decodeVarint(b) - if n == 0 { - return io.ErrUnexpectedEOF - } - b = b[n:] - } - tag := x >> 3 - wire := int(x) & 7 - - // Dispatch on the tag to one of the unmarshal* functions below. - var f unmarshalFieldInfo - if tag < uint64(len(u.dense)) { - f = u.dense[tag] - } else { - f = u.sparse[tag] - } - if fn := f.unmarshal; fn != nil { - var err error - b, err = fn(b, m.offset(f.field), wire) - if err == nil { - reqMask |= f.reqMask - continue - } - if r, ok := err.(*RequiredNotSetError); ok { - // Remember this error, but keep parsing. We need to produce - // a full parse even if a required field is missing. - rnse = r - reqMask |= f.reqMask - continue - } - if err != errInternalBadWireType { - if err == errInvalidUTF8 { - fullName := revProtoTypes[reflect.PtrTo(u.typ)] + "." + f.name - err = fmt.Errorf("proto: string field %q contains invalid UTF-8", fullName) - } - return err - } - // Fragments with bad wire type are treated as unknown fields. - } - - // Unknown tag. - if !u.unrecognized.IsValid() { - // Don't keep unrecognized data; just skip it. - var err error - b, err = skipField(b, wire) - if err != nil { - return err - } - continue - } - // Keep unrecognized data around. - // maybe in extensions, maybe in the unrecognized field. - z := m.offset(u.unrecognized).toBytes() - var emap map[int32]Extension - var e Extension - for _, r := range u.extensionRanges { - if uint64(r.Start) <= tag && tag <= uint64(r.End) { - if u.extensions.IsValid() { - mp := m.offset(u.extensions).toExtensions() - emap = mp.extensionsWrite() - e = emap[int32(tag)] - z = &e.enc - break - } - if u.oldExtensions.IsValid() { - p := m.offset(u.oldExtensions).toOldExtensions() - emap = *p - if emap == nil { - emap = map[int32]Extension{} - *p = emap - } - e = emap[int32(tag)] - z = &e.enc - break - } - panic("no extensions field available") - } - } - - // Use wire type to skip data. - var err error - b0 := b - b, err = skipField(b, wire) - if err != nil { - return err - } - *z = encodeVarint(*z, tag<<3|uint64(wire)) - *z = append(*z, b0[:len(b0)-len(b)]...) - - if emap != nil { - emap[int32(tag)] = e - } - } - if rnse != nil { - // A required field of a submessage/group is missing. Return that error. - return rnse - } - if reqMask != u.reqMask { - // A required field of this message is missing. - for _, n := range u.reqFields { - if reqMask&1 == 0 { - return &RequiredNotSetError{n} - } - reqMask >>= 1 - } - } - return nil -} - -// computeUnmarshalInfo fills in u with information for use -// in unmarshaling protocol buffers of type u.typ. -func (u *unmarshalInfo) computeUnmarshalInfo() { - u.lock.Lock() - defer u.lock.Unlock() - if u.initialized != 0 { - return - } - t := u.typ - n := t.NumField() - - // Set up the "not found" value for the unrecognized byte buffer. - // This is the default for proto3. - u.unrecognized = invalidField - u.extensions = invalidField - u.oldExtensions = invalidField - - // List of the generated type and offset for each oneof field. - type oneofField struct { - ityp reflect.Type // interface type of oneof field - field field // offset in containing message - } - var oneofFields []oneofField - - for i := 0; i < n; i++ { - f := t.Field(i) - if f.Name == "XXX_unrecognized" { - // The byte slice used to hold unrecognized input is special. - if f.Type != reflect.TypeOf(([]byte)(nil)) { - panic("bad type for XXX_unrecognized field: " + f.Type.Name()) - } - u.unrecognized = toField(&f) - continue - } - if f.Name == "XXX_InternalExtensions" { - // Ditto here. - if f.Type != reflect.TypeOf(XXX_InternalExtensions{}) { - panic("bad type for XXX_InternalExtensions field: " + f.Type.Name()) - } - u.extensions = toField(&f) - if f.Tag.Get("protobuf_messageset") == "1" { - u.isMessageSet = true - } - continue - } - if f.Name == "XXX_extensions" { - // An older form of the extensions field. - if f.Type != reflect.TypeOf((map[int32]Extension)(nil)) { - panic("bad type for XXX_extensions field: " + f.Type.Name()) - } - u.oldExtensions = toField(&f) - continue - } - if f.Name == "XXX_NoUnkeyedLiteral" || f.Name == "XXX_sizecache" { - continue - } - - oneof := f.Tag.Get("protobuf_oneof") - if oneof != "" { - oneofFields = append(oneofFields, oneofField{f.Type, toField(&f)}) - // The rest of oneof processing happens below. - continue - } - - tags := f.Tag.Get("protobuf") - tagArray := strings.Split(tags, ",") - if len(tagArray) < 2 { - panic("protobuf tag not enough fields in " + t.Name() + "." + f.Name + ": " + tags) - } - tag, err := strconv.Atoi(tagArray[1]) - if err != nil { - panic("protobuf tag field not an integer: " + tagArray[1]) - } - - name := "" - for _, tag := range tagArray[3:] { - if strings.HasPrefix(tag, "name=") { - name = tag[5:] - } - } - - // Extract unmarshaling function from the field (its type and tags). - unmarshal := fieldUnmarshaler(&f) - - // Required field? - var reqMask uint64 - if tagArray[2] == "req" { - bit := len(u.reqFields) - u.reqFields = append(u.reqFields, name) - reqMask = uint64(1) << uint(bit) - // TODO: if we have more than 64 required fields, we end up - // not verifying that all required fields are present. - // Fix this, perhaps using a count of required fields? - } - - // Store the info in the correct slot in the message. - u.setTag(tag, toField(&f), unmarshal, reqMask, name) - } - - // Find any types associated with oneof fields. - // TODO: XXX_OneofFuncs returns more info than we need. Get rid of some of it? - fn := reflect.Zero(reflect.PtrTo(t)).MethodByName("XXX_OneofFuncs") - if fn.IsValid() { - res := fn.Call(nil)[3] // last return value from XXX_OneofFuncs: []interface{} - for i := res.Len() - 1; i >= 0; i-- { - v := res.Index(i) // interface{} - tptr := reflect.ValueOf(v.Interface()).Type() // *Msg_X - typ := tptr.Elem() // Msg_X - - f := typ.Field(0) // oneof implementers have one field - baseUnmarshal := fieldUnmarshaler(&f) - tags := strings.Split(f.Tag.Get("protobuf"), ",") - fieldNum, err := strconv.Atoi(tags[1]) - if err != nil { - panic("protobuf tag field not an integer: " + tags[1]) - } - var name string - for _, tag := range tags { - if strings.HasPrefix(tag, "name=") { - name = strings.TrimPrefix(tag, "name=") - break - } - } - - // Find the oneof field that this struct implements. - // Might take O(n^2) to process all of the oneofs, but who cares. - for _, of := range oneofFields { - if tptr.Implements(of.ityp) { - // We have found the corresponding interface for this struct. - // That lets us know where this struct should be stored - // when we encounter it during unmarshaling. - unmarshal := makeUnmarshalOneof(typ, of.ityp, baseUnmarshal) - u.setTag(fieldNum, of.field, unmarshal, 0, name) - } - } - } - } - - // Get extension ranges, if any. - fn = reflect.Zero(reflect.PtrTo(t)).MethodByName("ExtensionRangeArray") - if fn.IsValid() { - if !u.extensions.IsValid() && !u.oldExtensions.IsValid() { - panic("a message with extensions, but no extensions field in " + t.Name()) - } - u.extensionRanges = fn.Call(nil)[0].Interface().([]ExtensionRange) - } - - // Explicitly disallow tag 0. This will ensure we flag an error - // when decoding a buffer of all zeros. Without this code, we - // would decode and skip an all-zero buffer of even length. - // [0 0] is [tag=0/wiretype=varint varint-encoded-0]. - u.setTag(0, zeroField, func(b []byte, f pointer, w int) ([]byte, error) { - return nil, fmt.Errorf("proto: %s: illegal tag 0 (wire type %d)", t, w) - }, 0, "") - - // Set mask for required field check. - u.reqMask = uint64(1)<= 0 && (tag < 16 || tag < 2*n) { // TODO: what are the right numbers here? - for len(u.dense) <= tag { - u.dense = append(u.dense, unmarshalFieldInfo{}) - } - u.dense[tag] = i - return - } - if u.sparse == nil { - u.sparse = map[uint64]unmarshalFieldInfo{} - } - u.sparse[uint64(tag)] = i -} - -// fieldUnmarshaler returns an unmarshaler for the given field. -func fieldUnmarshaler(f *reflect.StructField) unmarshaler { - if f.Type.Kind() == reflect.Map { - return makeUnmarshalMap(f) - } - return typeUnmarshaler(f.Type, f.Tag.Get("protobuf")) -} - -// typeUnmarshaler returns an unmarshaler for the given field type / field tag pair. -func typeUnmarshaler(t reflect.Type, tags string) unmarshaler { - tagArray := strings.Split(tags, ",") - encoding := tagArray[0] - name := "unknown" - for _, tag := range tagArray[3:] { - if strings.HasPrefix(tag, "name=") { - name = tag[5:] - } - } - - // Figure out packaging (pointer, slice, or both) - slice := false - pointer := false - if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 { - slice = true - t = t.Elem() - } - if t.Kind() == reflect.Ptr { - pointer = true - t = t.Elem() - } - - // We'll never have both pointer and slice for basic types. - if pointer && slice && t.Kind() != reflect.Struct { - panic("both pointer and slice for basic type in " + t.Name()) - } - - switch t.Kind() { - case reflect.Bool: - if pointer { - return unmarshalBoolPtr - } - if slice { - return unmarshalBoolSlice - } - return unmarshalBoolValue - case reflect.Int32: - switch encoding { - case "fixed32": - if pointer { - return unmarshalFixedS32Ptr - } - if slice { - return unmarshalFixedS32Slice - } - return unmarshalFixedS32Value - case "varint": - // this could be int32 or enum - if pointer { - return unmarshalInt32Ptr - } - if slice { - return unmarshalInt32Slice - } - return unmarshalInt32Value - case "zigzag32": - if pointer { - return unmarshalSint32Ptr - } - if slice { - return unmarshalSint32Slice - } - return unmarshalSint32Value - } - case reflect.Int64: - switch encoding { - case "fixed64": - if pointer { - return unmarshalFixedS64Ptr - } - if slice { - return unmarshalFixedS64Slice - } - return unmarshalFixedS64Value - case "varint": - if pointer { - return unmarshalInt64Ptr - } - if slice { - return unmarshalInt64Slice - } - return unmarshalInt64Value - case "zigzag64": - if pointer { - return unmarshalSint64Ptr - } - if slice { - return unmarshalSint64Slice - } - return unmarshalSint64Value - } - case reflect.Uint32: - switch encoding { - case "fixed32": - if pointer { - return unmarshalFixed32Ptr - } - if slice { - return unmarshalFixed32Slice - } - return unmarshalFixed32Value - case "varint": - if pointer { - return unmarshalUint32Ptr - } - if slice { - return unmarshalUint32Slice - } - return unmarshalUint32Value - } - case reflect.Uint64: - switch encoding { - case "fixed64": - if pointer { - return unmarshalFixed64Ptr - } - if slice { - return unmarshalFixed64Slice - } - return unmarshalFixed64Value - case "varint": - if pointer { - return unmarshalUint64Ptr - } - if slice { - return unmarshalUint64Slice - } - return unmarshalUint64Value - } - case reflect.Float32: - if pointer { - return unmarshalFloat32Ptr - } - if slice { - return unmarshalFloat32Slice - } - return unmarshalFloat32Value - case reflect.Float64: - if pointer { - return unmarshalFloat64Ptr - } - if slice { - return unmarshalFloat64Slice - } - return unmarshalFloat64Value - case reflect.Map: - panic("map type in typeUnmarshaler in " + t.Name()) - case reflect.Slice: - if pointer { - panic("bad pointer in slice case in " + t.Name()) - } - if slice { - return unmarshalBytesSlice - } - return unmarshalBytesValue - case reflect.String: - if pointer { - return unmarshalStringPtr - } - if slice { - return unmarshalStringSlice - } - return unmarshalStringValue - case reflect.Struct: - // message or group field - if !pointer { - panic(fmt.Sprintf("message/group field %s:%s without pointer", t, encoding)) - } - switch encoding { - case "bytes": - if slice { - return makeUnmarshalMessageSlicePtr(getUnmarshalInfo(t), name) - } - return makeUnmarshalMessagePtr(getUnmarshalInfo(t), name) - case "group": - if slice { - return makeUnmarshalGroupSlicePtr(getUnmarshalInfo(t), name) - } - return makeUnmarshalGroupPtr(getUnmarshalInfo(t), name) - } - } - panic(fmt.Sprintf("unmarshaler not found type:%s encoding:%s", t, encoding)) -} - -// Below are all the unmarshalers for individual fields of various types. - -func unmarshalInt64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x) - *f.toInt64() = v - return b, nil -} - -func unmarshalInt64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x) - *f.toInt64Ptr() = &v - return b, nil -} - -func unmarshalInt64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x) - s := f.toInt64Slice() - *s = append(*s, v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x) - s := f.toInt64Slice() - *s = append(*s, v) - return b, nil -} - -func unmarshalSint64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x>>1) ^ int64(x)<<63>>63 - *f.toInt64() = v - return b, nil -} - -func unmarshalSint64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x>>1) ^ int64(x)<<63>>63 - *f.toInt64Ptr() = &v - return b, nil -} - -func unmarshalSint64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x>>1) ^ int64(x)<<63>>63 - s := f.toInt64Slice() - *s = append(*s, v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int64(x>>1) ^ int64(x)<<63>>63 - s := f.toInt64Slice() - *s = append(*s, v) - return b, nil -} - -func unmarshalUint64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint64(x) - *f.toUint64() = v - return b, nil -} - -func unmarshalUint64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint64(x) - *f.toUint64Ptr() = &v - return b, nil -} - -func unmarshalUint64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint64(x) - s := f.toUint64Slice() - *s = append(*s, v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint64(x) - s := f.toUint64Slice() - *s = append(*s, v) - return b, nil -} - -func unmarshalInt32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x) - *f.toInt32() = v - return b, nil -} - -func unmarshalInt32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x) - f.setInt32Ptr(v) - return b, nil -} - -func unmarshalInt32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x) - f.appendInt32Slice(v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x) - f.appendInt32Slice(v) - return b, nil -} - -func unmarshalSint32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x>>1) ^ int32(x)<<31>>31 - *f.toInt32() = v - return b, nil -} - -func unmarshalSint32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x>>1) ^ int32(x)<<31>>31 - f.setInt32Ptr(v) - return b, nil -} - -func unmarshalSint32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x>>1) ^ int32(x)<<31>>31 - f.appendInt32Slice(v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := int32(x>>1) ^ int32(x)<<31>>31 - f.appendInt32Slice(v) - return b, nil -} - -func unmarshalUint32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint32(x) - *f.toUint32() = v - return b, nil -} - -func unmarshalUint32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint32(x) - *f.toUint32Ptr() = &v - return b, nil -} - -func unmarshalUint32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint32(x) - s := f.toUint32Slice() - *s = append(*s, v) - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - v := uint32(x) - s := f.toUint32Slice() - *s = append(*s, v) - return b, nil -} - -func unmarshalFixed64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 - *f.toUint64() = v - return b[8:], nil -} - -func unmarshalFixed64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 - *f.toUint64Ptr() = &v - return b[8:], nil -} - -func unmarshalFixed64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 - s := f.toUint64Slice() - *s = append(*s, v) - b = b[8:] - } - return res, nil - } - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 - s := f.toUint64Slice() - *s = append(*s, v) - return b[8:], nil -} - -func unmarshalFixedS64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 - *f.toInt64() = v - return b[8:], nil -} - -func unmarshalFixedS64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 - *f.toInt64Ptr() = &v - return b[8:], nil -} - -func unmarshalFixedS64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 - s := f.toInt64Slice() - *s = append(*s, v) - b = b[8:] - } - return res, nil - } - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 - s := f.toInt64Slice() - *s = append(*s, v) - return b[8:], nil -} - -func unmarshalFixed32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 - *f.toUint32() = v - return b[4:], nil -} - -func unmarshalFixed32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 - *f.toUint32Ptr() = &v - return b[4:], nil -} - -func unmarshalFixed32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 - s := f.toUint32Slice() - *s = append(*s, v) - b = b[4:] - } - return res, nil - } - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 - s := f.toUint32Slice() - *s = append(*s, v) - return b[4:], nil -} - -func unmarshalFixedS32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 - *f.toInt32() = v - return b[4:], nil -} - -func unmarshalFixedS32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 - f.setInt32Ptr(v) - return b[4:], nil -} - -func unmarshalFixedS32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 - f.appendInt32Slice(v) - b = b[4:] - } - return res, nil - } - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 - f.appendInt32Slice(v) - return b[4:], nil -} - -func unmarshalBoolValue(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - // Note: any length varint is allowed, even though any sane - // encoder will use one byte. - // See https://github.com/golang/protobuf/issues/76 - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - // TODO: check if x>1? Tests seem to indicate no. - v := x != 0 - *f.toBool() = v - return b[n:], nil -} - -func unmarshalBoolPtr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - v := x != 0 - *f.toBoolPtr() = &v - return b[n:], nil -} - -func unmarshalBoolSlice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - x, n = decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - v := x != 0 - s := f.toBoolSlice() - *s = append(*s, v) - b = b[n:] - } - return res, nil - } - if w != WireVarint { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - v := x != 0 - s := f.toBoolSlice() - *s = append(*s, v) - return b[n:], nil -} - -func unmarshalFloat64Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) - *f.toFloat64() = v - return b[8:], nil -} - -func unmarshalFloat64Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) - *f.toFloat64Ptr() = &v - return b[8:], nil -} - -func unmarshalFloat64Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) - s := f.toFloat64Slice() - *s = append(*s, v) - b = b[8:] - } - return res, nil - } - if w != WireFixed64 { - return b, errInternalBadWireType - } - if len(b) < 8 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56) - s := f.toFloat64Slice() - *s = append(*s, v) - return b[8:], nil -} - -func unmarshalFloat32Value(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) - *f.toFloat32() = v - return b[4:], nil -} - -func unmarshalFloat32Ptr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) - *f.toFloat32Ptr() = &v - return b[4:], nil -} - -func unmarshalFloat32Slice(b []byte, f pointer, w int) ([]byte, error) { - if w == WireBytes { // packed - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - res := b[x:] - b = b[:x] - for len(b) > 0 { - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) - s := f.toFloat32Slice() - *s = append(*s, v) - b = b[4:] - } - return res, nil - } - if w != WireFixed32 { - return b, errInternalBadWireType - } - if len(b) < 4 { - return nil, io.ErrUnexpectedEOF - } - v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) - s := f.toFloat32Slice() - *s = append(*s, v) - return b[4:], nil -} - -func unmarshalStringValue(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - if !utf8.ValidString(v) { - return nil, errInvalidUTF8 - } - *f.toString() = v - return b[x:], nil -} - -func unmarshalStringPtr(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - if !utf8.ValidString(v) { - return nil, errInvalidUTF8 - } - *f.toStringPtr() = &v - return b[x:], nil -} - -func unmarshalStringSlice(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := string(b[:x]) - if !utf8.ValidString(v) { - return nil, errInvalidUTF8 - } - s := f.toStringSlice() - *s = append(*s, v) - return b[x:], nil -} - -var emptyBuf [0]byte - -func unmarshalBytesValue(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - // The use of append here is a trick which avoids the zeroing - // that would be required if we used a make/copy pair. - // We append to emptyBuf instead of nil because we want - // a non-nil result even when the length is 0. - v := append(emptyBuf[:], b[:x]...) - *f.toBytes() = v - return b[x:], nil -} - -func unmarshalBytesSlice(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := append(emptyBuf[:], b[:x]...) - s := f.toBytesSlice() - *s = append(*s, v) - return b[x:], nil -} - -func makeUnmarshalMessagePtr(sub *unmarshalInfo, name string) unmarshaler { - return func(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - // First read the message field to see if something is there. - // The semantics of multiple submessages are weird. Instead of - // the last one winning (as it is for all other fields), multiple - // submessages are merged. - v := f.getPointer() - if v.isNil() { - v = valToPointer(reflect.New(sub.typ)) - f.setPointer(v) - } - err := sub.unmarshal(v, b[:x]) - if err != nil { - if r, ok := err.(*RequiredNotSetError); ok { - r.field = name + "." + r.field - } else { - return nil, err - } - } - return b[x:], err - } -} - -func makeUnmarshalMessageSlicePtr(sub *unmarshalInfo, name string) unmarshaler { - return func(b []byte, f pointer, w int) ([]byte, error) { - if w != WireBytes { - return b, errInternalBadWireType - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - v := valToPointer(reflect.New(sub.typ)) - err := sub.unmarshal(v, b[:x]) - if err != nil { - if r, ok := err.(*RequiredNotSetError); ok { - r.field = name + "." + r.field - } else { - return nil, err - } - } - f.appendPointer(v) - return b[x:], err - } -} - -func makeUnmarshalGroupPtr(sub *unmarshalInfo, name string) unmarshaler { - return func(b []byte, f pointer, w int) ([]byte, error) { - if w != WireStartGroup { - return b, errInternalBadWireType - } - x, y := findEndGroup(b) - if x < 0 { - return nil, io.ErrUnexpectedEOF - } - v := f.getPointer() - if v.isNil() { - v = valToPointer(reflect.New(sub.typ)) - f.setPointer(v) - } - err := sub.unmarshal(v, b[:x]) - if err != nil { - if r, ok := err.(*RequiredNotSetError); ok { - r.field = name + "." + r.field - } else { - return nil, err - } - } - return b[y:], err - } -} - -func makeUnmarshalGroupSlicePtr(sub *unmarshalInfo, name string) unmarshaler { - return func(b []byte, f pointer, w int) ([]byte, error) { - if w != WireStartGroup { - return b, errInternalBadWireType - } - x, y := findEndGroup(b) - if x < 0 { - return nil, io.ErrUnexpectedEOF - } - v := valToPointer(reflect.New(sub.typ)) - err := sub.unmarshal(v, b[:x]) - if err != nil { - if r, ok := err.(*RequiredNotSetError); ok { - r.field = name + "." + r.field - } else { - return nil, err - } - } - f.appendPointer(v) - return b[y:], err - } -} - -func makeUnmarshalMap(f *reflect.StructField) unmarshaler { - t := f.Type - kt := t.Key() - vt := t.Elem() - unmarshalKey := typeUnmarshaler(kt, f.Tag.Get("protobuf_key")) - unmarshalVal := typeUnmarshaler(vt, f.Tag.Get("protobuf_val")) - return func(b []byte, f pointer, w int) ([]byte, error) { - // The map entry is a submessage. Figure out how big it is. - if w != WireBytes { - return nil, fmt.Errorf("proto: bad wiretype for map field: got %d want %d", w, WireBytes) - } - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - b = b[n:] - if x > uint64(len(b)) { - return nil, io.ErrUnexpectedEOF - } - r := b[x:] // unused data to return - b = b[:x] // data for map entry - - // Note: we could use #keys * #values ~= 200 functions - // to do map decoding without reflection. Probably not worth it. - // Maps will be somewhat slow. Oh well. - - // Read key and value from data. - k := reflect.New(kt) - v := reflect.New(vt) - for len(b) > 0 { - x, n := decodeVarint(b) - if n == 0 { - return nil, io.ErrUnexpectedEOF - } - wire := int(x) & 7 - b = b[n:] - - var err error - switch x >> 3 { - case 1: - b, err = unmarshalKey(b, valToPointer(k), wire) - case 2: - b, err = unmarshalVal(b, valToPointer(v), wire) - default: - err = errInternalBadWireType // skip unknown tag - } - - if err == nil { - continue - } - if err != errInternalBadWireType { - return nil, err - } - - // Skip past unknown fields. - b, err = skipField(b, wire) - if err != nil { - return nil, err - } - } - - // Get map, allocate if needed. - m := f.asPointerTo(t).Elem() // an addressable map[K]T - if m.IsNil() { - m.Set(reflect.MakeMap(t)) - } - - // Insert into map. - m.SetMapIndex(k.Elem(), v.Elem()) - - return r, nil - } -} - -// makeUnmarshalOneof makes an unmarshaler for oneof fields. -// for: -// message Msg { -// oneof F { -// int64 X = 1; -// float64 Y = 2; -// } -// } -// typ is the type of the concrete entry for a oneof case (e.g. Msg_X). -// ityp is the interface type of the oneof field (e.g. isMsg_F). -// unmarshal is the unmarshaler for the base type of the oneof case (e.g. int64). -// Note that this function will be called once for each case in the oneof. -func makeUnmarshalOneof(typ, ityp reflect.Type, unmarshal unmarshaler) unmarshaler { - sf := typ.Field(0) - field0 := toField(&sf) - return func(b []byte, f pointer, w int) ([]byte, error) { - // Allocate holder for value. - v := reflect.New(typ) - - // Unmarshal data into holder. - // We unmarshal into the first field of the holder object. - var err error - b, err = unmarshal(b, valToPointer(v).offset(field0), w) - if err != nil { - return nil, err - } - - // Write pointer to holder into target field. - f.asPointerTo(ityp).Elem().Set(v) - - return b, nil - } -} - -// Error used by decode internally. -var errInternalBadWireType = errors.New("proto: internal error: bad wiretype") - -// skipField skips past a field of type wire and returns the remaining bytes. -func skipField(b []byte, wire int) ([]byte, error) { - switch wire { - case WireVarint: - _, k := decodeVarint(b) - if k == 0 { - return b, io.ErrUnexpectedEOF - } - b = b[k:] - case WireFixed32: - if len(b) < 4 { - return b, io.ErrUnexpectedEOF - } - b = b[4:] - case WireFixed64: - if len(b) < 8 { - return b, io.ErrUnexpectedEOF - } - b = b[8:] - case WireBytes: - m, k := decodeVarint(b) - if k == 0 || uint64(len(b)-k) < m { - return b, io.ErrUnexpectedEOF - } - b = b[uint64(k)+m:] - case WireStartGroup: - _, i := findEndGroup(b) - if i == -1 { - return b, io.ErrUnexpectedEOF - } - b = b[i:] - default: - return b, fmt.Errorf("proto: can't skip unknown wire type %d", wire) - } - return b, nil -} - -// findEndGroup finds the index of the next EndGroup tag. -// Groups may be nested, so the "next" EndGroup tag is the first -// unpaired EndGroup. -// findEndGroup returns the indexes of the start and end of the EndGroup tag. -// Returns (-1,-1) if it can't find one. -func findEndGroup(b []byte) (int, int) { - depth := 1 - i := 0 - for { - x, n := decodeVarint(b[i:]) - if n == 0 { - return -1, -1 - } - j := i - i += n - switch x & 7 { - case WireVarint: - _, k := decodeVarint(b[i:]) - if k == 0 { - return -1, -1 - } - i += k - case WireFixed32: - if len(b)-4 < i { - return -1, -1 - } - i += 4 - case WireFixed64: - if len(b)-8 < i { - return -1, -1 - } - i += 8 - case WireBytes: - m, k := decodeVarint(b[i:]) - if k == 0 { - return -1, -1 - } - i += k - if uint64(len(b)-i) < m { - return -1, -1 - } - i += int(m) - case WireStartGroup: - depth++ - case WireEndGroup: - depth-- - if depth == 0 { - return j, i - } - default: - return -1, -1 - } - } -} - -// encodeVarint appends a varint-encoded integer to b and returns the result. -func encodeVarint(b []byte, x uint64) []byte { - for x >= 1<<7 { - b = append(b, byte(x&0x7f|0x80)) - x >>= 7 - } - return append(b, byte(x)) -} - -// decodeVarint reads a varint-encoded integer from b. -// Returns the decoded integer and the number of bytes read. -// If there is an error, it returns 0,0. -func decodeVarint(b []byte) (uint64, int) { - var x, y uint64 - if len(b) <= 0 { - goto bad - } - x = uint64(b[0]) - if x < 0x80 { - return x, 1 - } - x -= 0x80 - - if len(b) <= 1 { - goto bad - } - y = uint64(b[1]) - x += y << 7 - if y < 0x80 { - return x, 2 - } - x -= 0x80 << 7 - - if len(b) <= 2 { - goto bad - } - y = uint64(b[2]) - x += y << 14 - if y < 0x80 { - return x, 3 - } - x -= 0x80 << 14 - - if len(b) <= 3 { - goto bad - } - y = uint64(b[3]) - x += y << 21 - if y < 0x80 { - return x, 4 - } - x -= 0x80 << 21 - - if len(b) <= 4 { - goto bad - } - y = uint64(b[4]) - x += y << 28 - if y < 0x80 { - return x, 5 - } - x -= 0x80 << 28 - - if len(b) <= 5 { - goto bad - } - y = uint64(b[5]) - x += y << 35 - if y < 0x80 { - return x, 6 - } - x -= 0x80 << 35 - - if len(b) <= 6 { - goto bad - } - y = uint64(b[6]) - x += y << 42 - if y < 0x80 { - return x, 7 - } - x -= 0x80 << 42 - - if len(b) <= 7 { - goto bad - } - y = uint64(b[7]) - x += y << 49 - if y < 0x80 { - return x, 8 - } - x -= 0x80 << 49 - - if len(b) <= 8 { - goto bad - } - y = uint64(b[8]) - x += y << 56 - if y < 0x80 { - return x, 9 - } - x -= 0x80 << 56 - - if len(b) <= 9 { - goto bad - } - y = uint64(b[9]) - x += y << 63 - if y < 2 { - return x, 10 - } - -bad: - return 0, 0 -} diff --git a/vendor/github.com/golang/protobuf/proto/text.go b/vendor/github.com/golang/protobuf/proto/text.go deleted file mode 100644 index 2205fdaa..00000000 --- a/vendor/github.com/golang/protobuf/proto/text.go +++ /dev/null @@ -1,843 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 -// OWNER 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. - -package proto - -// Functions for writing the text protocol buffer format. - -import ( - "bufio" - "bytes" - "encoding" - "errors" - "fmt" - "io" - "log" - "math" - "reflect" - "sort" - "strings" -) - -var ( - newline = []byte("\n") - spaces = []byte(" ") - endBraceNewline = []byte("}\n") - backslashN = []byte{'\\', 'n'} - backslashR = []byte{'\\', 'r'} - backslashT = []byte{'\\', 't'} - backslashDQ = []byte{'\\', '"'} - backslashBS = []byte{'\\', '\\'} - posInf = []byte("inf") - negInf = []byte("-inf") - nan = []byte("nan") -) - -type writer interface { - io.Writer - WriteByte(byte) error -} - -// textWriter is an io.Writer that tracks its indentation level. -type textWriter struct { - ind int - complete bool // if the current position is a complete line - compact bool // whether to write out as a one-liner - w writer -} - -func (w *textWriter) WriteString(s string) (n int, err error) { - if !strings.Contains(s, "\n") { - if !w.compact && w.complete { - w.writeIndent() - } - w.complete = false - return io.WriteString(w.w, s) - } - // WriteString is typically called without newlines, so this - // codepath and its copy are rare. We copy to avoid - // duplicating all of Write's logic here. - return w.Write([]byte(s)) -} - -func (w *textWriter) Write(p []byte) (n int, err error) { - newlines := bytes.Count(p, newline) - if newlines == 0 { - if !w.compact && w.complete { - w.writeIndent() - } - n, err = w.w.Write(p) - w.complete = false - return n, err - } - - frags := bytes.SplitN(p, newline, newlines+1) - if w.compact { - for i, frag := range frags { - if i > 0 { - if err := w.w.WriteByte(' '); err != nil { - return n, err - } - n++ - } - nn, err := w.w.Write(frag) - n += nn - if err != nil { - return n, err - } - } - return n, nil - } - - for i, frag := range frags { - if w.complete { - w.writeIndent() - } - nn, err := w.w.Write(frag) - n += nn - if err != nil { - return n, err - } - if i+1 < len(frags) { - if err := w.w.WriteByte('\n'); err != nil { - return n, err - } - n++ - } - } - w.complete = len(frags[len(frags)-1]) == 0 - return n, nil -} - -func (w *textWriter) WriteByte(c byte) error { - if w.compact && c == '\n' { - c = ' ' - } - if !w.compact && w.complete { - w.writeIndent() - } - err := w.w.WriteByte(c) - w.complete = c == '\n' - return err -} - -func (w *textWriter) indent() { w.ind++ } - -func (w *textWriter) unindent() { - if w.ind == 0 { - log.Print("proto: textWriter unindented too far") - return - } - w.ind-- -} - -func writeName(w *textWriter, props *Properties) error { - if _, err := w.WriteString(props.OrigName); err != nil { - return err - } - if props.Wire != "group" { - return w.WriteByte(':') - } - return nil -} - -func requiresQuotes(u string) bool { - // When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted. - for _, ch := range u { - switch { - case ch == '.' || ch == '/' || ch == '_': - continue - case '0' <= ch && ch <= '9': - continue - case 'A' <= ch && ch <= 'Z': - continue - case 'a' <= ch && ch <= 'z': - continue - default: - return true - } - } - return false -} - -// isAny reports whether sv is a google.protobuf.Any message -func isAny(sv reflect.Value) bool { - type wkt interface { - XXX_WellKnownType() string - } - t, ok := sv.Addr().Interface().(wkt) - return ok && t.XXX_WellKnownType() == "Any" -} - -// writeProto3Any writes an expanded google.protobuf.Any message. -// -// It returns (false, nil) if sv value can't be unmarshaled (e.g. because -// required messages are not linked in). -// -// It returns (true, error) when sv was written in expanded format or an error -// was encountered. -func (tm *TextMarshaler) writeProto3Any(w *textWriter, sv reflect.Value) (bool, error) { - turl := sv.FieldByName("TypeUrl") - val := sv.FieldByName("Value") - if !turl.IsValid() || !val.IsValid() { - return true, errors.New("proto: invalid google.protobuf.Any message") - } - - b, ok := val.Interface().([]byte) - if !ok { - return true, errors.New("proto: invalid google.protobuf.Any message") - } - - parts := strings.Split(turl.String(), "/") - mt := MessageType(parts[len(parts)-1]) - if mt == nil { - return false, nil - } - m := reflect.New(mt.Elem()) - if err := Unmarshal(b, m.Interface().(Message)); err != nil { - return false, nil - } - w.Write([]byte("[")) - u := turl.String() - if requiresQuotes(u) { - writeString(w, u) - } else { - w.Write([]byte(u)) - } - if w.compact { - w.Write([]byte("]:<")) - } else { - w.Write([]byte("]: <\n")) - w.ind++ - } - if err := tm.writeStruct(w, m.Elem()); err != nil { - return true, err - } - if w.compact { - w.Write([]byte("> ")) - } else { - w.ind-- - w.Write([]byte(">\n")) - } - return true, nil -} - -func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error { - if tm.ExpandAny && isAny(sv) { - if canExpand, err := tm.writeProto3Any(w, sv); canExpand { - return err - } - } - st := sv.Type() - sprops := GetProperties(st) - for i := 0; i < sv.NumField(); i++ { - fv := sv.Field(i) - props := sprops.Prop[i] - name := st.Field(i).Name - - if name == "XXX_NoUnkeyedLiteral" { - continue - } - - if strings.HasPrefix(name, "XXX_") { - // There are two XXX_ fields: - // XXX_unrecognized []byte - // XXX_extensions map[int32]proto.Extension - // The first is handled here; - // the second is handled at the bottom of this function. - if name == "XXX_unrecognized" && !fv.IsNil() { - if err := writeUnknownStruct(w, fv.Interface().([]byte)); err != nil { - return err - } - } - continue - } - if fv.Kind() == reflect.Ptr && fv.IsNil() { - // Field not filled in. This could be an optional field or - // a required field that wasn't filled in. Either way, there - // isn't anything we can show for it. - continue - } - if fv.Kind() == reflect.Slice && fv.IsNil() { - // Repeated field that is empty, or a bytes field that is unused. - continue - } - - if props.Repeated && fv.Kind() == reflect.Slice { - // Repeated field. - for j := 0; j < fv.Len(); j++ { - if err := writeName(w, props); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - v := fv.Index(j) - if v.Kind() == reflect.Ptr && v.IsNil() { - // A nil message in a repeated field is not valid, - // but we can handle that more gracefully than panicking. - if _, err := w.Write([]byte("\n")); err != nil { - return err - } - continue - } - if err := tm.writeAny(w, v, props); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - } - continue - } - if fv.Kind() == reflect.Map { - // Map fields are rendered as a repeated struct with key/value fields. - keys := fv.MapKeys() - sort.Sort(mapKeys(keys)) - for _, key := range keys { - val := fv.MapIndex(key) - if err := writeName(w, props); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - // open struct - if err := w.WriteByte('<'); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte('\n'); err != nil { - return err - } - } - w.indent() - // key - if _, err := w.WriteString("key:"); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - if err := tm.writeAny(w, key, props.mkeyprop); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - // nil values aren't legal, but we can avoid panicking because of them. - if val.Kind() != reflect.Ptr || !val.IsNil() { - // value - if _, err := w.WriteString("value:"); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - if err := tm.writeAny(w, val, props.mvalprop); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - } - // close struct - w.unindent() - if err := w.WriteByte('>'); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - } - continue - } - if props.proto3 && fv.Kind() == reflect.Slice && fv.Len() == 0 { - // empty bytes field - continue - } - if fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice { - // proto3 non-repeated scalar field; skip if zero value - if isProto3Zero(fv) { - continue - } - } - - if fv.Kind() == reflect.Interface { - // Check if it is a oneof. - if st.Field(i).Tag.Get("protobuf_oneof") != "" { - // fv is nil, or holds a pointer to generated struct. - // That generated struct has exactly one field, - // which has a protobuf struct tag. - if fv.IsNil() { - continue - } - inner := fv.Elem().Elem() // interface -> *T -> T - tag := inner.Type().Field(0).Tag.Get("protobuf") - props = new(Properties) // Overwrite the outer props var, but not its pointee. - props.Parse(tag) - // Write the value in the oneof, not the oneof itself. - fv = inner.Field(0) - - // Special case to cope with malformed messages gracefully: - // If the value in the oneof is a nil pointer, don't panic - // in writeAny. - if fv.Kind() == reflect.Ptr && fv.IsNil() { - // Use errors.New so writeAny won't render quotes. - msg := errors.New("/* nil */") - fv = reflect.ValueOf(&msg).Elem() - } - } - } - - if err := writeName(w, props); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - - // Enums have a String method, so writeAny will work fine. - if err := tm.writeAny(w, fv, props); err != nil { - return err - } - - if err := w.WriteByte('\n'); err != nil { - return err - } - } - - // Extensions (the XXX_extensions field). - pv := sv.Addr() - if _, err := extendable(pv.Interface()); err == nil { - if err := tm.writeExtensions(w, pv); err != nil { - return err - } - } - - return nil -} - -// writeAny writes an arbitrary field. -func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Properties) error { - v = reflect.Indirect(v) - - // Floats have special cases. - if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 { - x := v.Float() - var b []byte - switch { - case math.IsInf(x, 1): - b = posInf - case math.IsInf(x, -1): - b = negInf - case math.IsNaN(x): - b = nan - } - if b != nil { - _, err := w.Write(b) - return err - } - // Other values are handled below. - } - - // We don't attempt to serialise every possible value type; only those - // that can occur in protocol buffers. - switch v.Kind() { - case reflect.Slice: - // Should only be a []byte; repeated fields are handled in writeStruct. - if err := writeString(w, string(v.Bytes())); err != nil { - return err - } - case reflect.String: - if err := writeString(w, v.String()); err != nil { - return err - } - case reflect.Struct: - // Required/optional group/message. - var bra, ket byte = '<', '>' - if props != nil && props.Wire == "group" { - bra, ket = '{', '}' - } - if err := w.WriteByte(bra); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte('\n'); err != nil { - return err - } - } - w.indent() - if v.CanAddr() { - // Calling v.Interface on a struct causes the reflect package to - // copy the entire struct. This is racy with the new Marshaler - // since we atomically update the XXX_sizecache. - // - // Thus, we retrieve a pointer to the struct if possible to avoid - // a race since v.Interface on the pointer doesn't copy the struct. - // - // If v is not addressable, then we are not worried about a race - // since it implies that the binary Marshaler cannot possibly be - // mutating this value. - v = v.Addr() - } - if etm, ok := v.Interface().(encoding.TextMarshaler); ok { - text, err := etm.MarshalText() - if err != nil { - return err - } - if _, err = w.Write(text); err != nil { - return err - } - } else { - if v.Kind() == reflect.Ptr { - v = v.Elem() - } - if err := tm.writeStruct(w, v); err != nil { - return err - } - } - w.unindent() - if err := w.WriteByte(ket); err != nil { - return err - } - default: - _, err := fmt.Fprint(w, v.Interface()) - return err - } - return nil -} - -// equivalent to C's isprint. -func isprint(c byte) bool { - return c >= 0x20 && c < 0x7f -} - -// writeString writes a string in the protocol buffer text format. -// It is similar to strconv.Quote except we don't use Go escape sequences, -// we treat the string as a byte sequence, and we use octal escapes. -// These differences are to maintain interoperability with the other -// languages' implementations of the text format. -func writeString(w *textWriter, s string) error { - // use WriteByte here to get any needed indent - if err := w.WriteByte('"'); err != nil { - return err - } - // Loop over the bytes, not the runes. - for i := 0; i < len(s); i++ { - var err error - // Divergence from C++: we don't escape apostrophes. - // There's no need to escape them, and the C++ parser - // copes with a naked apostrophe. - switch c := s[i]; c { - case '\n': - _, err = w.w.Write(backslashN) - case '\r': - _, err = w.w.Write(backslashR) - case '\t': - _, err = w.w.Write(backslashT) - case '"': - _, err = w.w.Write(backslashDQ) - case '\\': - _, err = w.w.Write(backslashBS) - default: - if isprint(c) { - err = w.w.WriteByte(c) - } else { - _, err = fmt.Fprintf(w.w, "\\%03o", c) - } - } - if err != nil { - return err - } - } - return w.WriteByte('"') -} - -func writeUnknownStruct(w *textWriter, data []byte) (err error) { - if !w.compact { - if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil { - return err - } - } - b := NewBuffer(data) - for b.index < len(b.buf) { - x, err := b.DecodeVarint() - if err != nil { - _, err := fmt.Fprintf(w, "/* %v */\n", err) - return err - } - wire, tag := x&7, x>>3 - if wire == WireEndGroup { - w.unindent() - if _, err := w.Write(endBraceNewline); err != nil { - return err - } - continue - } - if _, err := fmt.Fprint(w, tag); err != nil { - return err - } - if wire != WireStartGroup { - if err := w.WriteByte(':'); err != nil { - return err - } - } - if !w.compact || wire == WireStartGroup { - if err := w.WriteByte(' '); err != nil { - return err - } - } - switch wire { - case WireBytes: - buf, e := b.DecodeRawBytes(false) - if e == nil { - _, err = fmt.Fprintf(w, "%q", buf) - } else { - _, err = fmt.Fprintf(w, "/* %v */", e) - } - case WireFixed32: - x, err = b.DecodeFixed32() - err = writeUnknownInt(w, x, err) - case WireFixed64: - x, err = b.DecodeFixed64() - err = writeUnknownInt(w, x, err) - case WireStartGroup: - err = w.WriteByte('{') - w.indent() - case WireVarint: - x, err = b.DecodeVarint() - err = writeUnknownInt(w, x, err) - default: - _, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire) - } - if err != nil { - return err - } - if err = w.WriteByte('\n'); err != nil { - return err - } - } - return nil -} - -func writeUnknownInt(w *textWriter, x uint64, err error) error { - if err == nil { - _, err = fmt.Fprint(w, x) - } else { - _, err = fmt.Fprintf(w, "/* %v */", err) - } - return err -} - -type int32Slice []int32 - -func (s int32Slice) Len() int { return len(s) } -func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] } -func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } - -// writeExtensions writes all the extensions in pv. -// pv is assumed to be a pointer to a protocol message struct that is extendable. -func (tm *TextMarshaler) writeExtensions(w *textWriter, pv reflect.Value) error { - emap := extensionMaps[pv.Type().Elem()] - ep, _ := extendable(pv.Interface()) - - // Order the extensions by ID. - // This isn't strictly necessary, but it will give us - // canonical output, which will also make testing easier. - m, mu := ep.extensionsRead() - if m == nil { - return nil - } - mu.Lock() - ids := make([]int32, 0, len(m)) - for id := range m { - ids = append(ids, id) - } - sort.Sort(int32Slice(ids)) - mu.Unlock() - - for _, extNum := range ids { - ext := m[extNum] - var desc *ExtensionDesc - if emap != nil { - desc = emap[extNum] - } - if desc == nil { - // Unknown extension. - if err := writeUnknownStruct(w, ext.enc); err != nil { - return err - } - continue - } - - pb, err := GetExtension(ep, desc) - if err != nil { - return fmt.Errorf("failed getting extension: %v", err) - } - - // Repeated extensions will appear as a slice. - if !desc.repeated() { - if err := tm.writeExtension(w, desc.Name, pb); err != nil { - return err - } - } else { - v := reflect.ValueOf(pb) - for i := 0; i < v.Len(); i++ { - if err := tm.writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil { - return err - } - } - } - } - return nil -} - -func (tm *TextMarshaler) writeExtension(w *textWriter, name string, pb interface{}) error { - if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - if err := tm.writeAny(w, reflect.ValueOf(pb), nil); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - return nil -} - -func (w *textWriter) writeIndent() { - if !w.complete { - return - } - remain := w.ind * 2 - for remain > 0 { - n := remain - if n > len(spaces) { - n = len(spaces) - } - w.w.Write(spaces[:n]) - remain -= n - } - w.complete = false -} - -// TextMarshaler is a configurable text format marshaler. -type TextMarshaler struct { - Compact bool // use compact text format (one line). - ExpandAny bool // expand google.protobuf.Any messages of known types -} - -// Marshal writes a given protocol buffer in text format. -// The only errors returned are from w. -func (tm *TextMarshaler) Marshal(w io.Writer, pb Message) error { - val := reflect.ValueOf(pb) - if pb == nil || val.IsNil() { - w.Write([]byte("")) - return nil - } - var bw *bufio.Writer - ww, ok := w.(writer) - if !ok { - bw = bufio.NewWriter(w) - ww = bw - } - aw := &textWriter{ - w: ww, - complete: true, - compact: tm.Compact, - } - - if etm, ok := pb.(encoding.TextMarshaler); ok { - text, err := etm.MarshalText() - if err != nil { - return err - } - if _, err = aw.Write(text); err != nil { - return err - } - if bw != nil { - return bw.Flush() - } - return nil - } - // Dereference the received pointer so we don't have outer < and >. - v := reflect.Indirect(val) - if err := tm.writeStruct(aw, v); err != nil { - return err - } - if bw != nil { - return bw.Flush() - } - return nil -} - -// Text is the same as Marshal, but returns the string directly. -func (tm *TextMarshaler) Text(pb Message) string { - var buf bytes.Buffer - tm.Marshal(&buf, pb) - return buf.String() -} - -var ( - defaultTextMarshaler = TextMarshaler{} - compactTextMarshaler = TextMarshaler{Compact: true} -) - -// TODO: consider removing some of the Marshal functions below. - -// MarshalText writes a given protocol buffer in text format. -// The only errors returned are from w. -func MarshalText(w io.Writer, pb Message) error { return defaultTextMarshaler.Marshal(w, pb) } - -// MarshalTextString is the same as MarshalText, but returns the string directly. -func MarshalTextString(pb Message) string { return defaultTextMarshaler.Text(pb) } - -// CompactText writes a given protocol buffer in compact text format (one line). -func CompactText(w io.Writer, pb Message) error { return compactTextMarshaler.Marshal(w, pb) } - -// CompactTextString is the same as CompactText, but returns the string directly. -func CompactTextString(pb Message) string { return compactTextMarshaler.Text(pb) } diff --git a/vendor/github.com/golang/protobuf/proto/text_parser.go b/vendor/github.com/golang/protobuf/proto/text_parser.go deleted file mode 100644 index 0685bae3..00000000 --- a/vendor/github.com/golang/protobuf/proto/text_parser.go +++ /dev/null @@ -1,880 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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 Google Inc. 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 -// OWNER 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. - -package proto - -// Functions for parsing the Text protocol buffer format. -// TODO: message sets. - -import ( - "encoding" - "errors" - "fmt" - "reflect" - "strconv" - "strings" - "unicode/utf8" -) - -// Error string emitted when deserializing Any and fields are already set -const anyRepeatedlyUnpacked = "Any message unpacked multiple times, or %q already set" - -type ParseError struct { - Message string - Line int // 1-based line number - Offset int // 0-based byte offset from start of input -} - -func (p *ParseError) Error() string { - if p.Line == 1 { - // show offset only for first line - return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message) - } - return fmt.Sprintf("line %d: %v", p.Line, p.Message) -} - -type token struct { - value string - err *ParseError - line int // line number - offset int // byte number from start of input, not start of line - unquoted string // the unquoted version of value, if it was a quoted string -} - -func (t *token) String() string { - if t.err == nil { - return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset) - } - return fmt.Sprintf("parse error: %v", t.err) -} - -type textParser struct { - s string // remaining input - done bool // whether the parsing is finished (success or error) - backed bool // whether back() was called - offset, line int - cur token -} - -func newTextParser(s string) *textParser { - p := new(textParser) - p.s = s - p.line = 1 - p.cur.line = 1 - return p -} - -func (p *textParser) errorf(format string, a ...interface{}) *ParseError { - pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset} - p.cur.err = pe - p.done = true - return pe -} - -// Numbers and identifiers are matched by [-+._A-Za-z0-9] -func isIdentOrNumberChar(c byte) bool { - switch { - case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z': - return true - case '0' <= c && c <= '9': - return true - } - switch c { - case '-', '+', '.', '_': - return true - } - return false -} - -func isWhitespace(c byte) bool { - switch c { - case ' ', '\t', '\n', '\r': - return true - } - return false -} - -func isQuote(c byte) bool { - switch c { - case '"', '\'': - return true - } - return false -} - -func (p *textParser) skipWhitespace() { - i := 0 - for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') { - if p.s[i] == '#' { - // comment; skip to end of line or input - for i < len(p.s) && p.s[i] != '\n' { - i++ - } - if i == len(p.s) { - break - } - } - if p.s[i] == '\n' { - p.line++ - } - i++ - } - p.offset += i - p.s = p.s[i:len(p.s)] - if len(p.s) == 0 { - p.done = true - } -} - -func (p *textParser) advance() { - // Skip whitespace - p.skipWhitespace() - if p.done { - return - } - - // Start of non-whitespace - p.cur.err = nil - p.cur.offset, p.cur.line = p.offset, p.line - p.cur.unquoted = "" - switch p.s[0] { - case '<', '>', '{', '}', ':', '[', ']', ';', ',', '/': - // Single symbol - p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)] - case '"', '\'': - // Quoted string - i := 1 - for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' { - if p.s[i] == '\\' && i+1 < len(p.s) { - // skip escaped char - i++ - } - i++ - } - if i >= len(p.s) || p.s[i] != p.s[0] { - p.errorf("unmatched quote") - return - } - unq, err := unquoteC(p.s[1:i], rune(p.s[0])) - if err != nil { - p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err) - return - } - p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)] - p.cur.unquoted = unq - default: - i := 0 - for i < len(p.s) && isIdentOrNumberChar(p.s[i]) { - i++ - } - if i == 0 { - p.errorf("unexpected byte %#x", p.s[0]) - return - } - p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)] - } - p.offset += len(p.cur.value) -} - -var ( - errBadUTF8 = errors.New("proto: bad UTF-8") -) - -func unquoteC(s string, quote rune) (string, error) { - // This is based on C++'s tokenizer.cc. - // Despite its name, this is *not* parsing C syntax. - // For instance, "\0" is an invalid quoted string. - - // Avoid allocation in trivial cases. - simple := true - for _, r := range s { - if r == '\\' || r == quote { - simple = false - break - } - } - if simple { - return s, nil - } - - buf := make([]byte, 0, 3*len(s)/2) - for len(s) > 0 { - r, n := utf8.DecodeRuneInString(s) - if r == utf8.RuneError && n == 1 { - return "", errBadUTF8 - } - s = s[n:] - if r != '\\' { - if r < utf8.RuneSelf { - buf = append(buf, byte(r)) - } else { - buf = append(buf, string(r)...) - } - continue - } - - ch, tail, err := unescape(s) - if err != nil { - return "", err - } - buf = append(buf, ch...) - s = tail - } - return string(buf), nil -} - -func unescape(s string) (ch string, tail string, err error) { - r, n := utf8.DecodeRuneInString(s) - if r == utf8.RuneError && n == 1 { - return "", "", errBadUTF8 - } - s = s[n:] - switch r { - case 'a': - return "\a", s, nil - case 'b': - return "\b", s, nil - case 'f': - return "\f", s, nil - case 'n': - return "\n", s, nil - case 'r': - return "\r", s, nil - case 't': - return "\t", s, nil - case 'v': - return "\v", s, nil - case '?': - return "?", s, nil // trigraph workaround - case '\'', '"', '\\': - return string(r), s, nil - case '0', '1', '2', '3', '4', '5', '6', '7': - if len(s) < 2 { - return "", "", fmt.Errorf(`\%c requires 2 following digits`, r) - } - ss := string(r) + s[:2] - s = s[2:] - i, err := strconv.ParseUint(ss, 8, 8) - if err != nil { - return "", "", fmt.Errorf(`\%s contains non-octal digits`, ss) - } - return string([]byte{byte(i)}), s, nil - case 'x', 'X', 'u', 'U': - var n int - switch r { - case 'x', 'X': - n = 2 - case 'u': - n = 4 - case 'U': - n = 8 - } - if len(s) < n { - return "", "", fmt.Errorf(`\%c requires %d following digits`, r, n) - } - ss := s[:n] - s = s[n:] - i, err := strconv.ParseUint(ss, 16, 64) - if err != nil { - return "", "", fmt.Errorf(`\%c%s contains non-hexadecimal digits`, r, ss) - } - if r == 'x' || r == 'X' { - return string([]byte{byte(i)}), s, nil - } - if i > utf8.MaxRune { - return "", "", fmt.Errorf(`\%c%s is not a valid Unicode code point`, r, ss) - } - return string(i), s, nil - } - return "", "", fmt.Errorf(`unknown escape \%c`, r) -} - -// Back off the parser by one token. Can only be done between calls to next(). -// It makes the next advance() a no-op. -func (p *textParser) back() { p.backed = true } - -// Advances the parser and returns the new current token. -func (p *textParser) next() *token { - if p.backed || p.done { - p.backed = false - return &p.cur - } - p.advance() - if p.done { - p.cur.value = "" - } else if len(p.cur.value) > 0 && isQuote(p.cur.value[0]) { - // Look for multiple quoted strings separated by whitespace, - // and concatenate them. - cat := p.cur - for { - p.skipWhitespace() - if p.done || !isQuote(p.s[0]) { - break - } - p.advance() - if p.cur.err != nil { - return &p.cur - } - cat.value += " " + p.cur.value - cat.unquoted += p.cur.unquoted - } - p.done = false // parser may have seen EOF, but we want to return cat - p.cur = cat - } - return &p.cur -} - -func (p *textParser) consumeToken(s string) error { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != s { - p.back() - return p.errorf("expected %q, found %q", s, tok.value) - } - return nil -} - -// Return a RequiredNotSetError indicating which required field was not set. -func (p *textParser) missingRequiredFieldError(sv reflect.Value) *RequiredNotSetError { - st := sv.Type() - sprops := GetProperties(st) - for i := 0; i < st.NumField(); i++ { - if !isNil(sv.Field(i)) { - continue - } - - props := sprops.Prop[i] - if props.Required { - return &RequiredNotSetError{fmt.Sprintf("%v.%v", st, props.OrigName)} - } - } - return &RequiredNotSetError{fmt.Sprintf("%v.", st)} // should not happen -} - -// Returns the index in the struct for the named field, as well as the parsed tag properties. -func structFieldByName(sprops *StructProperties, name string) (int, *Properties, bool) { - i, ok := sprops.decoderOrigNames[name] - if ok { - return i, sprops.Prop[i], true - } - return -1, nil, false -} - -// Consume a ':' from the input stream (if the next token is a colon), -// returning an error if a colon is needed but not present. -func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != ":" { - // Colon is optional when the field is a group or message. - needColon := true - switch props.Wire { - case "group": - needColon = false - case "bytes": - // A "bytes" field is either a message, a string, or a repeated field; - // those three become *T, *string and []T respectively, so we can check for - // this field being a pointer to a non-string. - if typ.Kind() == reflect.Ptr { - // *T or *string - if typ.Elem().Kind() == reflect.String { - break - } - } else if typ.Kind() == reflect.Slice { - // []T or []*T - if typ.Elem().Kind() != reflect.Ptr { - break - } - } else if typ.Kind() == reflect.String { - // The proto3 exception is for a string field, - // which requires a colon. - break - } - needColon = false - } - if needColon { - return p.errorf("expected ':', found %q", tok.value) - } - p.back() - } - return nil -} - -func (p *textParser) readStruct(sv reflect.Value, terminator string) error { - st := sv.Type() - sprops := GetProperties(st) - reqCount := sprops.reqCount - var reqFieldErr error - fieldSet := make(map[string]bool) - // A struct is a sequence of "name: value", terminated by one of - // '>' or '}', or the end of the input. A name may also be - // "[extension]" or "[type/url]". - // - // The whole struct can also be an expanded Any message, like: - // [type/url] < ... struct contents ... > - for { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == terminator { - break - } - if tok.value == "[" { - // Looks like an extension or an Any. - // - // TODO: Check whether we need to handle - // namespace rooted names (e.g. ".something.Foo"). - extName, err := p.consumeExtName() - if err != nil { - return err - } - - if s := strings.LastIndex(extName, "/"); s >= 0 { - // If it contains a slash, it's an Any type URL. - messageName := extName[s+1:] - mt := MessageType(messageName) - if mt == nil { - return p.errorf("unrecognized message %q in google.protobuf.Any", messageName) - } - tok = p.next() - if tok.err != nil { - return tok.err - } - // consume an optional colon - if tok.value == ":" { - tok = p.next() - if tok.err != nil { - return tok.err - } - } - var terminator string - switch tok.value { - case "<": - terminator = ">" - case "{": - terminator = "}" - default: - return p.errorf("expected '{' or '<', found %q", tok.value) - } - v := reflect.New(mt.Elem()) - if pe := p.readStruct(v.Elem(), terminator); pe != nil { - return pe - } - b, err := Marshal(v.Interface().(Message)) - if err != nil { - return p.errorf("failed to marshal message of type %q: %v", messageName, err) - } - if fieldSet["type_url"] { - return p.errorf(anyRepeatedlyUnpacked, "type_url") - } - if fieldSet["value"] { - return p.errorf(anyRepeatedlyUnpacked, "value") - } - sv.FieldByName("TypeUrl").SetString(extName) - sv.FieldByName("Value").SetBytes(b) - fieldSet["type_url"] = true - fieldSet["value"] = true - continue - } - - var desc *ExtensionDesc - // This could be faster, but it's functional. - // TODO: Do something smarter than a linear scan. - for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) { - if d.Name == extName { - desc = d - break - } - } - if desc == nil { - return p.errorf("unrecognized extension %q", extName) - } - - props := &Properties{} - props.Parse(desc.Tag) - - typ := reflect.TypeOf(desc.ExtensionType) - if err := p.checkForColon(props, typ); err != nil { - return err - } - - rep := desc.repeated() - - // Read the extension structure, and set it in - // the value we're constructing. - var ext reflect.Value - if !rep { - ext = reflect.New(typ).Elem() - } else { - ext = reflect.New(typ.Elem()).Elem() - } - if err := p.readAny(ext, props); err != nil { - if _, ok := err.(*RequiredNotSetError); !ok { - return err - } - reqFieldErr = err - } - ep := sv.Addr().Interface().(Message) - if !rep { - SetExtension(ep, desc, ext.Interface()) - } else { - old, err := GetExtension(ep, desc) - var sl reflect.Value - if err == nil { - sl = reflect.ValueOf(old) // existing slice - } else { - sl = reflect.MakeSlice(typ, 0, 1) - } - sl = reflect.Append(sl, ext) - SetExtension(ep, desc, sl.Interface()) - } - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - continue - } - - // This is a normal, non-extension field. - name := tok.value - var dst reflect.Value - fi, props, ok := structFieldByName(sprops, name) - if ok { - dst = sv.Field(fi) - } else if oop, ok := sprops.OneofTypes[name]; ok { - // It is a oneof. - props = oop.Prop - nv := reflect.New(oop.Type.Elem()) - dst = nv.Elem().Field(0) - field := sv.Field(oop.Field) - if !field.IsNil() { - return p.errorf("field '%s' would overwrite already parsed oneof '%s'", name, sv.Type().Field(oop.Field).Name) - } - field.Set(nv) - } - if !dst.IsValid() { - return p.errorf("unknown field name %q in %v", name, st) - } - - if dst.Kind() == reflect.Map { - // Consume any colon. - if err := p.checkForColon(props, dst.Type()); err != nil { - return err - } - - // Construct the map if it doesn't already exist. - if dst.IsNil() { - dst.Set(reflect.MakeMap(dst.Type())) - } - key := reflect.New(dst.Type().Key()).Elem() - val := reflect.New(dst.Type().Elem()).Elem() - - // The map entry should be this sequence of tokens: - // < key : KEY value : VALUE > - // However, implementations may omit key or value, and technically - // we should support them in any order. See b/28924776 for a time - // this went wrong. - - tok := p.next() - var terminator string - switch tok.value { - case "<": - terminator = ">" - case "{": - terminator = "}" - default: - return p.errorf("expected '{' or '<', found %q", tok.value) - } - for { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == terminator { - break - } - switch tok.value { - case "key": - if err := p.consumeToken(":"); err != nil { - return err - } - if err := p.readAny(key, props.mkeyprop); err != nil { - return err - } - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - case "value": - if err := p.checkForColon(props.mvalprop, dst.Type().Elem()); err != nil { - return err - } - if err := p.readAny(val, props.mvalprop); err != nil { - return err - } - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - default: - p.back() - return p.errorf(`expected "key", "value", or %q, found %q`, terminator, tok.value) - } - } - - dst.SetMapIndex(key, val) - continue - } - - // Check that it's not already set if it's not a repeated field. - if !props.Repeated && fieldSet[name] { - return p.errorf("non-repeated field %q was repeated", name) - } - - if err := p.checkForColon(props, dst.Type()); err != nil { - return err - } - - // Parse into the field. - fieldSet[name] = true - if err := p.readAny(dst, props); err != nil { - if _, ok := err.(*RequiredNotSetError); !ok { - return err - } - reqFieldErr = err - } - if props.Required { - reqCount-- - } - - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - - } - - if reqCount > 0 { - return p.missingRequiredFieldError(sv) - } - return reqFieldErr -} - -// consumeExtName consumes extension name or expanded Any type URL and the -// following ']'. It returns the name or URL consumed. -func (p *textParser) consumeExtName() (string, error) { - tok := p.next() - if tok.err != nil { - return "", tok.err - } - - // If extension name or type url is quoted, it's a single token. - if len(tok.value) > 2 && isQuote(tok.value[0]) && tok.value[len(tok.value)-1] == tok.value[0] { - name, err := unquoteC(tok.value[1:len(tok.value)-1], rune(tok.value[0])) - if err != nil { - return "", err - } - return name, p.consumeToken("]") - } - - // Consume everything up to "]" - var parts []string - for tok.value != "]" { - parts = append(parts, tok.value) - tok = p.next() - if tok.err != nil { - return "", p.errorf("unrecognized type_url or extension name: %s", tok.err) - } - if p.done && tok.value != "]" { - return "", p.errorf("unclosed type_url or extension name") - } - } - return strings.Join(parts, ""), nil -} - -// consumeOptionalSeparator consumes an optional semicolon or comma. -// It is used in readStruct to provide backward compatibility. -func (p *textParser) consumeOptionalSeparator() error { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != ";" && tok.value != "," { - p.back() - } - return nil -} - -func (p *textParser) readAny(v reflect.Value, props *Properties) error { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == "" { - return p.errorf("unexpected EOF") - } - - switch fv := v; fv.Kind() { - case reflect.Slice: - at := v.Type() - if at.Elem().Kind() == reflect.Uint8 { - // Special case for []byte - if tok.value[0] != '"' && tok.value[0] != '\'' { - // Deliberately written out here, as the error after - // this switch statement would write "invalid []byte: ...", - // which is not as user-friendly. - return p.errorf("invalid string: %v", tok.value) - } - bytes := []byte(tok.unquoted) - fv.Set(reflect.ValueOf(bytes)) - return nil - } - // Repeated field. - if tok.value == "[" { - // Repeated field with list notation, like [1,2,3]. - for { - fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem())) - err := p.readAny(fv.Index(fv.Len()-1), props) - if err != nil { - return err - } - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == "]" { - break - } - if tok.value != "," { - return p.errorf("Expected ']' or ',' found %q", tok.value) - } - } - return nil - } - // One value of the repeated field. - p.back() - fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem())) - return p.readAny(fv.Index(fv.Len()-1), props) - case reflect.Bool: - // true/1/t/True or false/f/0/False. - switch tok.value { - case "true", "1", "t", "True": - fv.SetBool(true) - return nil - case "false", "0", "f", "False": - fv.SetBool(false) - return nil - } - case reflect.Float32, reflect.Float64: - v := tok.value - // Ignore 'f' for compatibility with output generated by C++, but don't - // remove 'f' when the value is "-inf" or "inf". - if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" { - v = v[:len(v)-1] - } - if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil { - fv.SetFloat(f) - return nil - } - case reflect.Int32: - if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil { - fv.SetInt(x) - return nil - } - - if len(props.Enum) == 0 { - break - } - m, ok := enumValueMaps[props.Enum] - if !ok { - break - } - x, ok := m[tok.value] - if !ok { - break - } - fv.SetInt(int64(x)) - return nil - case reflect.Int64: - if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil { - fv.SetInt(x) - return nil - } - - case reflect.Ptr: - // A basic field (indirected through pointer), or a repeated message/group - p.back() - fv.Set(reflect.New(fv.Type().Elem())) - return p.readAny(fv.Elem(), props) - case reflect.String: - if tok.value[0] == '"' || tok.value[0] == '\'' { - fv.SetString(tok.unquoted) - return nil - } - case reflect.Struct: - var terminator string - switch tok.value { - case "{": - terminator = "}" - case "<": - terminator = ">" - default: - return p.errorf("expected '{' or '<', found %q", tok.value) - } - // TODO: Handle nested messages which implement encoding.TextUnmarshaler. - return p.readStruct(fv, terminator) - case reflect.Uint32: - if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil { - fv.SetUint(uint64(x)) - return nil - } - case reflect.Uint64: - if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil { - fv.SetUint(x) - return nil - } - } - return p.errorf("invalid %v: %v", v.Type(), tok.value) -} - -// UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb -// before starting to unmarshal, so any existing data in pb is always removed. -// If a required field is not set and no other error occurs, -// UnmarshalText returns *RequiredNotSetError. -func UnmarshalText(s string, pb Message) error { - if um, ok := pb.(encoding.TextUnmarshaler); ok { - return um.UnmarshalText([]byte(s)) - } - pb.Reset() - v := reflect.ValueOf(pb) - return newTextParser(s).readStruct(v.Elem(), "") -} diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go deleted file mode 100644 index e855b1f5..00000000 --- a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go +++ /dev/null @@ -1,2812 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: google/protobuf/descriptor.proto - -package descriptor // import "github.com/golang/protobuf/protoc-gen-go/descriptor" - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type FieldDescriptorProto_Type int32 - -const ( - // 0 is reserved for errors. - // Order is weird for historical reasons. - FieldDescriptorProto_TYPE_DOUBLE FieldDescriptorProto_Type = 1 - FieldDescriptorProto_TYPE_FLOAT FieldDescriptorProto_Type = 2 - // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if - // negative values are likely. - FieldDescriptorProto_TYPE_INT64 FieldDescriptorProto_Type = 3 - FieldDescriptorProto_TYPE_UINT64 FieldDescriptorProto_Type = 4 - // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if - // negative values are likely. - FieldDescriptorProto_TYPE_INT32 FieldDescriptorProto_Type = 5 - FieldDescriptorProto_TYPE_FIXED64 FieldDescriptorProto_Type = 6 - FieldDescriptorProto_TYPE_FIXED32 FieldDescriptorProto_Type = 7 - FieldDescriptorProto_TYPE_BOOL FieldDescriptorProto_Type = 8 - FieldDescriptorProto_TYPE_STRING FieldDescriptorProto_Type = 9 - // Tag-delimited aggregate. - // Group type is deprecated and not supported in proto3. However, Proto3 - // implementations should still be able to parse the group wire format and - // treat group fields as unknown fields. - FieldDescriptorProto_TYPE_GROUP FieldDescriptorProto_Type = 10 - FieldDescriptorProto_TYPE_MESSAGE FieldDescriptorProto_Type = 11 - // New in version 2. - FieldDescriptorProto_TYPE_BYTES FieldDescriptorProto_Type = 12 - FieldDescriptorProto_TYPE_UINT32 FieldDescriptorProto_Type = 13 - FieldDescriptorProto_TYPE_ENUM FieldDescriptorProto_Type = 14 - FieldDescriptorProto_TYPE_SFIXED32 FieldDescriptorProto_Type = 15 - FieldDescriptorProto_TYPE_SFIXED64 FieldDescriptorProto_Type = 16 - FieldDescriptorProto_TYPE_SINT32 FieldDescriptorProto_Type = 17 - FieldDescriptorProto_TYPE_SINT64 FieldDescriptorProto_Type = 18 -) - -var FieldDescriptorProto_Type_name = map[int32]string{ - 1: "TYPE_DOUBLE", - 2: "TYPE_FLOAT", - 3: "TYPE_INT64", - 4: "TYPE_UINT64", - 5: "TYPE_INT32", - 6: "TYPE_FIXED64", - 7: "TYPE_FIXED32", - 8: "TYPE_BOOL", - 9: "TYPE_STRING", - 10: "TYPE_GROUP", - 11: "TYPE_MESSAGE", - 12: "TYPE_BYTES", - 13: "TYPE_UINT32", - 14: "TYPE_ENUM", - 15: "TYPE_SFIXED32", - 16: "TYPE_SFIXED64", - 17: "TYPE_SINT32", - 18: "TYPE_SINT64", -} -var FieldDescriptorProto_Type_value = map[string]int32{ - "TYPE_DOUBLE": 1, - "TYPE_FLOAT": 2, - "TYPE_INT64": 3, - "TYPE_UINT64": 4, - "TYPE_INT32": 5, - "TYPE_FIXED64": 6, - "TYPE_FIXED32": 7, - "TYPE_BOOL": 8, - "TYPE_STRING": 9, - "TYPE_GROUP": 10, - "TYPE_MESSAGE": 11, - "TYPE_BYTES": 12, - "TYPE_UINT32": 13, - "TYPE_ENUM": 14, - "TYPE_SFIXED32": 15, - "TYPE_SFIXED64": 16, - "TYPE_SINT32": 17, - "TYPE_SINT64": 18, -} - -func (x FieldDescriptorProto_Type) Enum() *FieldDescriptorProto_Type { - p := new(FieldDescriptorProto_Type) - *p = x - return p -} -func (x FieldDescriptorProto_Type) String() string { - return proto.EnumName(FieldDescriptorProto_Type_name, int32(x)) -} -func (x *FieldDescriptorProto_Type) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Type_value, data, "FieldDescriptorProto_Type") - if err != nil { - return err - } - *x = FieldDescriptorProto_Type(value) - return nil -} -func (FieldDescriptorProto_Type) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{4, 0} -} - -type FieldDescriptorProto_Label int32 - -const ( - // 0 is reserved for errors - FieldDescriptorProto_LABEL_OPTIONAL FieldDescriptorProto_Label = 1 - FieldDescriptorProto_LABEL_REQUIRED FieldDescriptorProto_Label = 2 - FieldDescriptorProto_LABEL_REPEATED FieldDescriptorProto_Label = 3 -) - -var FieldDescriptorProto_Label_name = map[int32]string{ - 1: "LABEL_OPTIONAL", - 2: "LABEL_REQUIRED", - 3: "LABEL_REPEATED", -} -var FieldDescriptorProto_Label_value = map[string]int32{ - "LABEL_OPTIONAL": 1, - "LABEL_REQUIRED": 2, - "LABEL_REPEATED": 3, -} - -func (x FieldDescriptorProto_Label) Enum() *FieldDescriptorProto_Label { - p := new(FieldDescriptorProto_Label) - *p = x - return p -} -func (x FieldDescriptorProto_Label) String() string { - return proto.EnumName(FieldDescriptorProto_Label_name, int32(x)) -} -func (x *FieldDescriptorProto_Label) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Label_value, data, "FieldDescriptorProto_Label") - if err != nil { - return err - } - *x = FieldDescriptorProto_Label(value) - return nil -} -func (FieldDescriptorProto_Label) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{4, 1} -} - -// Generated classes can be optimized for speed or code size. -type FileOptions_OptimizeMode int32 - -const ( - FileOptions_SPEED FileOptions_OptimizeMode = 1 - // etc. - FileOptions_CODE_SIZE FileOptions_OptimizeMode = 2 - FileOptions_LITE_RUNTIME FileOptions_OptimizeMode = 3 -) - -var FileOptions_OptimizeMode_name = map[int32]string{ - 1: "SPEED", - 2: "CODE_SIZE", - 3: "LITE_RUNTIME", -} -var FileOptions_OptimizeMode_value = map[string]int32{ - "SPEED": 1, - "CODE_SIZE": 2, - "LITE_RUNTIME": 3, -} - -func (x FileOptions_OptimizeMode) Enum() *FileOptions_OptimizeMode { - p := new(FileOptions_OptimizeMode) - *p = x - return p -} -func (x FileOptions_OptimizeMode) String() string { - return proto.EnumName(FileOptions_OptimizeMode_name, int32(x)) -} -func (x *FileOptions_OptimizeMode) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FileOptions_OptimizeMode_value, data, "FileOptions_OptimizeMode") - if err != nil { - return err - } - *x = FileOptions_OptimizeMode(value) - return nil -} -func (FileOptions_OptimizeMode) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{10, 0} -} - -type FieldOptions_CType int32 - -const ( - // Default mode. - FieldOptions_STRING FieldOptions_CType = 0 - FieldOptions_CORD FieldOptions_CType = 1 - FieldOptions_STRING_PIECE FieldOptions_CType = 2 -) - -var FieldOptions_CType_name = map[int32]string{ - 0: "STRING", - 1: "CORD", - 2: "STRING_PIECE", -} -var FieldOptions_CType_value = map[string]int32{ - "STRING": 0, - "CORD": 1, - "STRING_PIECE": 2, -} - -func (x FieldOptions_CType) Enum() *FieldOptions_CType { - p := new(FieldOptions_CType) - *p = x - return p -} -func (x FieldOptions_CType) String() string { - return proto.EnumName(FieldOptions_CType_name, int32(x)) -} -func (x *FieldOptions_CType) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FieldOptions_CType_value, data, "FieldOptions_CType") - if err != nil { - return err - } - *x = FieldOptions_CType(value) - return nil -} -func (FieldOptions_CType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{12, 0} -} - -type FieldOptions_JSType int32 - -const ( - // Use the default type. - FieldOptions_JS_NORMAL FieldOptions_JSType = 0 - // Use JavaScript strings. - FieldOptions_JS_STRING FieldOptions_JSType = 1 - // Use JavaScript numbers. - FieldOptions_JS_NUMBER FieldOptions_JSType = 2 -) - -var FieldOptions_JSType_name = map[int32]string{ - 0: "JS_NORMAL", - 1: "JS_STRING", - 2: "JS_NUMBER", -} -var FieldOptions_JSType_value = map[string]int32{ - "JS_NORMAL": 0, - "JS_STRING": 1, - "JS_NUMBER": 2, -} - -func (x FieldOptions_JSType) Enum() *FieldOptions_JSType { - p := new(FieldOptions_JSType) - *p = x - return p -} -func (x FieldOptions_JSType) String() string { - return proto.EnumName(FieldOptions_JSType_name, int32(x)) -} -func (x *FieldOptions_JSType) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FieldOptions_JSType_value, data, "FieldOptions_JSType") - if err != nil { - return err - } - *x = FieldOptions_JSType(value) - return nil -} -func (FieldOptions_JSType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{12, 1} -} - -// Is this method side-effect-free (or safe in HTTP parlance), or idempotent, -// or neither? HTTP based RPC implementation may choose GET verb for safe -// methods, and PUT verb for idempotent methods instead of the default POST. -type MethodOptions_IdempotencyLevel int32 - -const ( - MethodOptions_IDEMPOTENCY_UNKNOWN MethodOptions_IdempotencyLevel = 0 - MethodOptions_NO_SIDE_EFFECTS MethodOptions_IdempotencyLevel = 1 - MethodOptions_IDEMPOTENT MethodOptions_IdempotencyLevel = 2 -) - -var MethodOptions_IdempotencyLevel_name = map[int32]string{ - 0: "IDEMPOTENCY_UNKNOWN", - 1: "NO_SIDE_EFFECTS", - 2: "IDEMPOTENT", -} -var MethodOptions_IdempotencyLevel_value = map[string]int32{ - "IDEMPOTENCY_UNKNOWN": 0, - "NO_SIDE_EFFECTS": 1, - "IDEMPOTENT": 2, -} - -func (x MethodOptions_IdempotencyLevel) Enum() *MethodOptions_IdempotencyLevel { - p := new(MethodOptions_IdempotencyLevel) - *p = x - return p -} -func (x MethodOptions_IdempotencyLevel) String() string { - return proto.EnumName(MethodOptions_IdempotencyLevel_name, int32(x)) -} -func (x *MethodOptions_IdempotencyLevel) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(MethodOptions_IdempotencyLevel_value, data, "MethodOptions_IdempotencyLevel") - if err != nil { - return err - } - *x = MethodOptions_IdempotencyLevel(value) - return nil -} -func (MethodOptions_IdempotencyLevel) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{17, 0} -} - -// The protocol compiler can output a FileDescriptorSet containing the .proto -// files it parses. -type FileDescriptorSet struct { - File []*FileDescriptorProto `protobuf:"bytes,1,rep,name=file" json:"file,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FileDescriptorSet) Reset() { *m = FileDescriptorSet{} } -func (m *FileDescriptorSet) String() string { return proto.CompactTextString(m) } -func (*FileDescriptorSet) ProtoMessage() {} -func (*FileDescriptorSet) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{0} -} -func (m *FileDescriptorSet) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FileDescriptorSet.Unmarshal(m, b) -} -func (m *FileDescriptorSet) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FileDescriptorSet.Marshal(b, m, deterministic) -} -func (dst *FileDescriptorSet) XXX_Merge(src proto.Message) { - xxx_messageInfo_FileDescriptorSet.Merge(dst, src) -} -func (m *FileDescriptorSet) XXX_Size() int { - return xxx_messageInfo_FileDescriptorSet.Size(m) -} -func (m *FileDescriptorSet) XXX_DiscardUnknown() { - xxx_messageInfo_FileDescriptorSet.DiscardUnknown(m) -} - -var xxx_messageInfo_FileDescriptorSet proto.InternalMessageInfo - -func (m *FileDescriptorSet) GetFile() []*FileDescriptorProto { - if m != nil { - return m.File - } - return nil -} - -// Describes a complete .proto file. -type FileDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Package *string `protobuf:"bytes,2,opt,name=package" json:"package,omitempty"` - // Names of files imported by this file. - Dependency []string `protobuf:"bytes,3,rep,name=dependency" json:"dependency,omitempty"` - // Indexes of the public imported files in the dependency list above. - PublicDependency []int32 `protobuf:"varint,10,rep,name=public_dependency,json=publicDependency" json:"public_dependency,omitempty"` - // Indexes of the weak imported files in the dependency list. - // For Google-internal migration only. Do not use. - WeakDependency []int32 `protobuf:"varint,11,rep,name=weak_dependency,json=weakDependency" json:"weak_dependency,omitempty"` - // All top-level definitions in this file. - MessageType []*DescriptorProto `protobuf:"bytes,4,rep,name=message_type,json=messageType" json:"message_type,omitempty"` - EnumType []*EnumDescriptorProto `protobuf:"bytes,5,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"` - Service []*ServiceDescriptorProto `protobuf:"bytes,6,rep,name=service" json:"service,omitempty"` - Extension []*FieldDescriptorProto `protobuf:"bytes,7,rep,name=extension" json:"extension,omitempty"` - Options *FileOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"` - // This field contains optional information about the original source code. - // You may safely remove this entire field without harming runtime - // functionality of the descriptors -- the information is needed only by - // development tools. - SourceCodeInfo *SourceCodeInfo `protobuf:"bytes,9,opt,name=source_code_info,json=sourceCodeInfo" json:"source_code_info,omitempty"` - // The syntax of the proto file. - // The supported values are "proto2" and "proto3". - Syntax *string `protobuf:"bytes,12,opt,name=syntax" json:"syntax,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FileDescriptorProto) Reset() { *m = FileDescriptorProto{} } -func (m *FileDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*FileDescriptorProto) ProtoMessage() {} -func (*FileDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{1} -} -func (m *FileDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FileDescriptorProto.Unmarshal(m, b) -} -func (m *FileDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FileDescriptorProto.Marshal(b, m, deterministic) -} -func (dst *FileDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_FileDescriptorProto.Merge(dst, src) -} -func (m *FileDescriptorProto) XXX_Size() int { - return xxx_messageInfo_FileDescriptorProto.Size(m) -} -func (m *FileDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_FileDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_FileDescriptorProto proto.InternalMessageInfo - -func (m *FileDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *FileDescriptorProto) GetPackage() string { - if m != nil && m.Package != nil { - return *m.Package - } - return "" -} - -func (m *FileDescriptorProto) GetDependency() []string { - if m != nil { - return m.Dependency - } - return nil -} - -func (m *FileDescriptorProto) GetPublicDependency() []int32 { - if m != nil { - return m.PublicDependency - } - return nil -} - -func (m *FileDescriptorProto) GetWeakDependency() []int32 { - if m != nil { - return m.WeakDependency - } - return nil -} - -func (m *FileDescriptorProto) GetMessageType() []*DescriptorProto { - if m != nil { - return m.MessageType - } - return nil -} - -func (m *FileDescriptorProto) GetEnumType() []*EnumDescriptorProto { - if m != nil { - return m.EnumType - } - return nil -} - -func (m *FileDescriptorProto) GetService() []*ServiceDescriptorProto { - if m != nil { - return m.Service - } - return nil -} - -func (m *FileDescriptorProto) GetExtension() []*FieldDescriptorProto { - if m != nil { - return m.Extension - } - return nil -} - -func (m *FileDescriptorProto) GetOptions() *FileOptions { - if m != nil { - return m.Options - } - return nil -} - -func (m *FileDescriptorProto) GetSourceCodeInfo() *SourceCodeInfo { - if m != nil { - return m.SourceCodeInfo - } - return nil -} - -func (m *FileDescriptorProto) GetSyntax() string { - if m != nil && m.Syntax != nil { - return *m.Syntax - } - return "" -} - -// Describes a message type. -type DescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Field []*FieldDescriptorProto `protobuf:"bytes,2,rep,name=field" json:"field,omitempty"` - Extension []*FieldDescriptorProto `protobuf:"bytes,6,rep,name=extension" json:"extension,omitempty"` - NestedType []*DescriptorProto `protobuf:"bytes,3,rep,name=nested_type,json=nestedType" json:"nested_type,omitempty"` - EnumType []*EnumDescriptorProto `protobuf:"bytes,4,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"` - ExtensionRange []*DescriptorProto_ExtensionRange `protobuf:"bytes,5,rep,name=extension_range,json=extensionRange" json:"extension_range,omitempty"` - OneofDecl []*OneofDescriptorProto `protobuf:"bytes,8,rep,name=oneof_decl,json=oneofDecl" json:"oneof_decl,omitempty"` - Options *MessageOptions `protobuf:"bytes,7,opt,name=options" json:"options,omitempty"` - ReservedRange []*DescriptorProto_ReservedRange `protobuf:"bytes,9,rep,name=reserved_range,json=reservedRange" json:"reserved_range,omitempty"` - // Reserved field names, which may not be used by fields in the same message. - // A given name may only be reserved once. - ReservedName []string `protobuf:"bytes,10,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DescriptorProto) Reset() { *m = DescriptorProto{} } -func (m *DescriptorProto) String() string { return proto.CompactTextString(m) } -func (*DescriptorProto) ProtoMessage() {} -func (*DescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{2} -} -func (m *DescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DescriptorProto.Unmarshal(m, b) -} -func (m *DescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DescriptorProto.Marshal(b, m, deterministic) -} -func (dst *DescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_DescriptorProto.Merge(dst, src) -} -func (m *DescriptorProto) XXX_Size() int { - return xxx_messageInfo_DescriptorProto.Size(m) -} -func (m *DescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_DescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_DescriptorProto proto.InternalMessageInfo - -func (m *DescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *DescriptorProto) GetField() []*FieldDescriptorProto { - if m != nil { - return m.Field - } - return nil -} - -func (m *DescriptorProto) GetExtension() []*FieldDescriptorProto { - if m != nil { - return m.Extension - } - return nil -} - -func (m *DescriptorProto) GetNestedType() []*DescriptorProto { - if m != nil { - return m.NestedType - } - return nil -} - -func (m *DescriptorProto) GetEnumType() []*EnumDescriptorProto { - if m != nil { - return m.EnumType - } - return nil -} - -func (m *DescriptorProto) GetExtensionRange() []*DescriptorProto_ExtensionRange { - if m != nil { - return m.ExtensionRange - } - return nil -} - -func (m *DescriptorProto) GetOneofDecl() []*OneofDescriptorProto { - if m != nil { - return m.OneofDecl - } - return nil -} - -func (m *DescriptorProto) GetOptions() *MessageOptions { - if m != nil { - return m.Options - } - return nil -} - -func (m *DescriptorProto) GetReservedRange() []*DescriptorProto_ReservedRange { - if m != nil { - return m.ReservedRange - } - return nil -} - -func (m *DescriptorProto) GetReservedName() []string { - if m != nil { - return m.ReservedName - } - return nil -} - -type DescriptorProto_ExtensionRange struct { - Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` - End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` - Options *ExtensionRangeOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DescriptorProto_ExtensionRange) Reset() { *m = DescriptorProto_ExtensionRange{} } -func (m *DescriptorProto_ExtensionRange) String() string { return proto.CompactTextString(m) } -func (*DescriptorProto_ExtensionRange) ProtoMessage() {} -func (*DescriptorProto_ExtensionRange) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{2, 0} -} -func (m *DescriptorProto_ExtensionRange) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DescriptorProto_ExtensionRange.Unmarshal(m, b) -} -func (m *DescriptorProto_ExtensionRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DescriptorProto_ExtensionRange.Marshal(b, m, deterministic) -} -func (dst *DescriptorProto_ExtensionRange) XXX_Merge(src proto.Message) { - xxx_messageInfo_DescriptorProto_ExtensionRange.Merge(dst, src) -} -func (m *DescriptorProto_ExtensionRange) XXX_Size() int { - return xxx_messageInfo_DescriptorProto_ExtensionRange.Size(m) -} -func (m *DescriptorProto_ExtensionRange) XXX_DiscardUnknown() { - xxx_messageInfo_DescriptorProto_ExtensionRange.DiscardUnknown(m) -} - -var xxx_messageInfo_DescriptorProto_ExtensionRange proto.InternalMessageInfo - -func (m *DescriptorProto_ExtensionRange) GetStart() int32 { - if m != nil && m.Start != nil { - return *m.Start - } - return 0 -} - -func (m *DescriptorProto_ExtensionRange) GetEnd() int32 { - if m != nil && m.End != nil { - return *m.End - } - return 0 -} - -func (m *DescriptorProto_ExtensionRange) GetOptions() *ExtensionRangeOptions { - if m != nil { - return m.Options - } - return nil -} - -// Range of reserved tag numbers. Reserved tag numbers may not be used by -// fields or extension ranges in the same message. Reserved ranges may -// not overlap. -type DescriptorProto_ReservedRange struct { - Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` - End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DescriptorProto_ReservedRange) Reset() { *m = DescriptorProto_ReservedRange{} } -func (m *DescriptorProto_ReservedRange) String() string { return proto.CompactTextString(m) } -func (*DescriptorProto_ReservedRange) ProtoMessage() {} -func (*DescriptorProto_ReservedRange) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{2, 1} -} -func (m *DescriptorProto_ReservedRange) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DescriptorProto_ReservedRange.Unmarshal(m, b) -} -func (m *DescriptorProto_ReservedRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DescriptorProto_ReservedRange.Marshal(b, m, deterministic) -} -func (dst *DescriptorProto_ReservedRange) XXX_Merge(src proto.Message) { - xxx_messageInfo_DescriptorProto_ReservedRange.Merge(dst, src) -} -func (m *DescriptorProto_ReservedRange) XXX_Size() int { - return xxx_messageInfo_DescriptorProto_ReservedRange.Size(m) -} -func (m *DescriptorProto_ReservedRange) XXX_DiscardUnknown() { - xxx_messageInfo_DescriptorProto_ReservedRange.DiscardUnknown(m) -} - -var xxx_messageInfo_DescriptorProto_ReservedRange proto.InternalMessageInfo - -func (m *DescriptorProto_ReservedRange) GetStart() int32 { - if m != nil && m.Start != nil { - return *m.Start - } - return 0 -} - -func (m *DescriptorProto_ReservedRange) GetEnd() int32 { - if m != nil && m.End != nil { - return *m.End - } - return 0 -} - -type ExtensionRangeOptions struct { - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ExtensionRangeOptions) Reset() { *m = ExtensionRangeOptions{} } -func (m *ExtensionRangeOptions) String() string { return proto.CompactTextString(m) } -func (*ExtensionRangeOptions) ProtoMessage() {} -func (*ExtensionRangeOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{3} -} - -var extRange_ExtensionRangeOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*ExtensionRangeOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_ExtensionRangeOptions -} -func (m *ExtensionRangeOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ExtensionRangeOptions.Unmarshal(m, b) -} -func (m *ExtensionRangeOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ExtensionRangeOptions.Marshal(b, m, deterministic) -} -func (dst *ExtensionRangeOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_ExtensionRangeOptions.Merge(dst, src) -} -func (m *ExtensionRangeOptions) XXX_Size() int { - return xxx_messageInfo_ExtensionRangeOptions.Size(m) -} -func (m *ExtensionRangeOptions) XXX_DiscardUnknown() { - xxx_messageInfo_ExtensionRangeOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_ExtensionRangeOptions proto.InternalMessageInfo - -func (m *ExtensionRangeOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -// Describes a field within a message. -type FieldDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Number *int32 `protobuf:"varint,3,opt,name=number" json:"number,omitempty"` - Label *FieldDescriptorProto_Label `protobuf:"varint,4,opt,name=label,enum=google.protobuf.FieldDescriptorProto_Label" json:"label,omitempty"` - // If type_name is set, this need not be set. If both this and type_name - // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP. - Type *FieldDescriptorProto_Type `protobuf:"varint,5,opt,name=type,enum=google.protobuf.FieldDescriptorProto_Type" json:"type,omitempty"` - // For message and enum types, this is the name of the type. If the name - // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping - // rules are used to find the type (i.e. first the nested types within this - // message are searched, then within the parent, on up to the root - // namespace). - TypeName *string `protobuf:"bytes,6,opt,name=type_name,json=typeName" json:"type_name,omitempty"` - // For extensions, this is the name of the type being extended. It is - // resolved in the same manner as type_name. - Extendee *string `protobuf:"bytes,2,opt,name=extendee" json:"extendee,omitempty"` - // For numeric types, contains the original text representation of the value. - // For booleans, "true" or "false". - // For strings, contains the default text contents (not escaped in any way). - // For bytes, contains the C escaped value. All bytes >= 128 are escaped. - // TODO(kenton): Base-64 encode? - DefaultValue *string `protobuf:"bytes,7,opt,name=default_value,json=defaultValue" json:"default_value,omitempty"` - // If set, gives the index of a oneof in the containing type's oneof_decl - // list. This field is a member of that oneof. - OneofIndex *int32 `protobuf:"varint,9,opt,name=oneof_index,json=oneofIndex" json:"oneof_index,omitempty"` - // JSON name of this field. The value is set by protocol compiler. If the - // user has set a "json_name" option on this field, that option's value - // will be used. Otherwise, it's deduced from the field's name by converting - // it to camelCase. - JsonName *string `protobuf:"bytes,10,opt,name=json_name,json=jsonName" json:"json_name,omitempty"` - Options *FieldOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FieldDescriptorProto) Reset() { *m = FieldDescriptorProto{} } -func (m *FieldDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*FieldDescriptorProto) ProtoMessage() {} -func (*FieldDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{4} -} -func (m *FieldDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FieldDescriptorProto.Unmarshal(m, b) -} -func (m *FieldDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FieldDescriptorProto.Marshal(b, m, deterministic) -} -func (dst *FieldDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_FieldDescriptorProto.Merge(dst, src) -} -func (m *FieldDescriptorProto) XXX_Size() int { - return xxx_messageInfo_FieldDescriptorProto.Size(m) -} -func (m *FieldDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_FieldDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_FieldDescriptorProto proto.InternalMessageInfo - -func (m *FieldDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *FieldDescriptorProto) GetNumber() int32 { - if m != nil && m.Number != nil { - return *m.Number - } - return 0 -} - -func (m *FieldDescriptorProto) GetLabel() FieldDescriptorProto_Label { - if m != nil && m.Label != nil { - return *m.Label - } - return FieldDescriptorProto_LABEL_OPTIONAL -} - -func (m *FieldDescriptorProto) GetType() FieldDescriptorProto_Type { - if m != nil && m.Type != nil { - return *m.Type - } - return FieldDescriptorProto_TYPE_DOUBLE -} - -func (m *FieldDescriptorProto) GetTypeName() string { - if m != nil && m.TypeName != nil { - return *m.TypeName - } - return "" -} - -func (m *FieldDescriptorProto) GetExtendee() string { - if m != nil && m.Extendee != nil { - return *m.Extendee - } - return "" -} - -func (m *FieldDescriptorProto) GetDefaultValue() string { - if m != nil && m.DefaultValue != nil { - return *m.DefaultValue - } - return "" -} - -func (m *FieldDescriptorProto) GetOneofIndex() int32 { - if m != nil && m.OneofIndex != nil { - return *m.OneofIndex - } - return 0 -} - -func (m *FieldDescriptorProto) GetJsonName() string { - if m != nil && m.JsonName != nil { - return *m.JsonName - } - return "" -} - -func (m *FieldDescriptorProto) GetOptions() *FieldOptions { - if m != nil { - return m.Options - } - return nil -} - -// Describes a oneof. -type OneofDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Options *OneofOptions `protobuf:"bytes,2,opt,name=options" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *OneofDescriptorProto) Reset() { *m = OneofDescriptorProto{} } -func (m *OneofDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*OneofDescriptorProto) ProtoMessage() {} -func (*OneofDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{5} -} -func (m *OneofDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_OneofDescriptorProto.Unmarshal(m, b) -} -func (m *OneofDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_OneofDescriptorProto.Marshal(b, m, deterministic) -} -func (dst *OneofDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_OneofDescriptorProto.Merge(dst, src) -} -func (m *OneofDescriptorProto) XXX_Size() int { - return xxx_messageInfo_OneofDescriptorProto.Size(m) -} -func (m *OneofDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_OneofDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_OneofDescriptorProto proto.InternalMessageInfo - -func (m *OneofDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *OneofDescriptorProto) GetOptions() *OneofOptions { - if m != nil { - return m.Options - } - return nil -} - -// Describes an enum type. -type EnumDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Value []*EnumValueDescriptorProto `protobuf:"bytes,2,rep,name=value" json:"value,omitempty"` - Options *EnumOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` - // Range of reserved numeric values. Reserved numeric values may not be used - // by enum values in the same enum declaration. Reserved ranges may not - // overlap. - ReservedRange []*EnumDescriptorProto_EnumReservedRange `protobuf:"bytes,4,rep,name=reserved_range,json=reservedRange" json:"reserved_range,omitempty"` - // Reserved enum value names, which may not be reused. A given name may only - // be reserved once. - ReservedName []string `protobuf:"bytes,5,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EnumDescriptorProto) Reset() { *m = EnumDescriptorProto{} } -func (m *EnumDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*EnumDescriptorProto) ProtoMessage() {} -func (*EnumDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{6} -} -func (m *EnumDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EnumDescriptorProto.Unmarshal(m, b) -} -func (m *EnumDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EnumDescriptorProto.Marshal(b, m, deterministic) -} -func (dst *EnumDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_EnumDescriptorProto.Merge(dst, src) -} -func (m *EnumDescriptorProto) XXX_Size() int { - return xxx_messageInfo_EnumDescriptorProto.Size(m) -} -func (m *EnumDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_EnumDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_EnumDescriptorProto proto.InternalMessageInfo - -func (m *EnumDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *EnumDescriptorProto) GetValue() []*EnumValueDescriptorProto { - if m != nil { - return m.Value - } - return nil -} - -func (m *EnumDescriptorProto) GetOptions() *EnumOptions { - if m != nil { - return m.Options - } - return nil -} - -func (m *EnumDescriptorProto) GetReservedRange() []*EnumDescriptorProto_EnumReservedRange { - if m != nil { - return m.ReservedRange - } - return nil -} - -func (m *EnumDescriptorProto) GetReservedName() []string { - if m != nil { - return m.ReservedName - } - return nil -} - -// Range of reserved numeric values. Reserved values may not be used by -// entries in the same enum. Reserved ranges may not overlap. -// -// Note that this is distinct from DescriptorProto.ReservedRange in that it -// is inclusive such that it can appropriately represent the entire int32 -// domain. -type EnumDescriptorProto_EnumReservedRange struct { - Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` - End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EnumDescriptorProto_EnumReservedRange) Reset() { *m = EnumDescriptorProto_EnumReservedRange{} } -func (m *EnumDescriptorProto_EnumReservedRange) String() string { return proto.CompactTextString(m) } -func (*EnumDescriptorProto_EnumReservedRange) ProtoMessage() {} -func (*EnumDescriptorProto_EnumReservedRange) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{6, 0} -} -func (m *EnumDescriptorProto_EnumReservedRange) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Unmarshal(m, b) -} -func (m *EnumDescriptorProto_EnumReservedRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Marshal(b, m, deterministic) -} -func (dst *EnumDescriptorProto_EnumReservedRange) XXX_Merge(src proto.Message) { - xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Merge(dst, src) -} -func (m *EnumDescriptorProto_EnumReservedRange) XXX_Size() int { - return xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Size(m) -} -func (m *EnumDescriptorProto_EnumReservedRange) XXX_DiscardUnknown() { - xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.DiscardUnknown(m) -} - -var xxx_messageInfo_EnumDescriptorProto_EnumReservedRange proto.InternalMessageInfo - -func (m *EnumDescriptorProto_EnumReservedRange) GetStart() int32 { - if m != nil && m.Start != nil { - return *m.Start - } - return 0 -} - -func (m *EnumDescriptorProto_EnumReservedRange) GetEnd() int32 { - if m != nil && m.End != nil { - return *m.End - } - return 0 -} - -// Describes a value within an enum. -type EnumValueDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Number *int32 `protobuf:"varint,2,opt,name=number" json:"number,omitempty"` - Options *EnumValueOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EnumValueDescriptorProto) Reset() { *m = EnumValueDescriptorProto{} } -func (m *EnumValueDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*EnumValueDescriptorProto) ProtoMessage() {} -func (*EnumValueDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{7} -} -func (m *EnumValueDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EnumValueDescriptorProto.Unmarshal(m, b) -} -func (m *EnumValueDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EnumValueDescriptorProto.Marshal(b, m, deterministic) -} -func (dst *EnumValueDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_EnumValueDescriptorProto.Merge(dst, src) -} -func (m *EnumValueDescriptorProto) XXX_Size() int { - return xxx_messageInfo_EnumValueDescriptorProto.Size(m) -} -func (m *EnumValueDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_EnumValueDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_EnumValueDescriptorProto proto.InternalMessageInfo - -func (m *EnumValueDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *EnumValueDescriptorProto) GetNumber() int32 { - if m != nil && m.Number != nil { - return *m.Number - } - return 0 -} - -func (m *EnumValueDescriptorProto) GetOptions() *EnumValueOptions { - if m != nil { - return m.Options - } - return nil -} - -// Describes a service. -type ServiceDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Method []*MethodDescriptorProto `protobuf:"bytes,2,rep,name=method" json:"method,omitempty"` - Options *ServiceOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ServiceDescriptorProto) Reset() { *m = ServiceDescriptorProto{} } -func (m *ServiceDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*ServiceDescriptorProto) ProtoMessage() {} -func (*ServiceDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{8} -} -func (m *ServiceDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ServiceDescriptorProto.Unmarshal(m, b) -} -func (m *ServiceDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ServiceDescriptorProto.Marshal(b, m, deterministic) -} -func (dst *ServiceDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_ServiceDescriptorProto.Merge(dst, src) -} -func (m *ServiceDescriptorProto) XXX_Size() int { - return xxx_messageInfo_ServiceDescriptorProto.Size(m) -} -func (m *ServiceDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_ServiceDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_ServiceDescriptorProto proto.InternalMessageInfo - -func (m *ServiceDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *ServiceDescriptorProto) GetMethod() []*MethodDescriptorProto { - if m != nil { - return m.Method - } - return nil -} - -func (m *ServiceDescriptorProto) GetOptions() *ServiceOptions { - if m != nil { - return m.Options - } - return nil -} - -// Describes a method of a service. -type MethodDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - // Input and output type names. These are resolved in the same way as - // FieldDescriptorProto.type_name, but must refer to a message type. - InputType *string `protobuf:"bytes,2,opt,name=input_type,json=inputType" json:"input_type,omitempty"` - OutputType *string `protobuf:"bytes,3,opt,name=output_type,json=outputType" json:"output_type,omitempty"` - Options *MethodOptions `protobuf:"bytes,4,opt,name=options" json:"options,omitempty"` - // Identifies if client streams multiple client messages - ClientStreaming *bool `protobuf:"varint,5,opt,name=client_streaming,json=clientStreaming,def=0" json:"client_streaming,omitempty"` - // Identifies if server streams multiple server messages - ServerStreaming *bool `protobuf:"varint,6,opt,name=server_streaming,json=serverStreaming,def=0" json:"server_streaming,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MethodDescriptorProto) Reset() { *m = MethodDescriptorProto{} } -func (m *MethodDescriptorProto) String() string { return proto.CompactTextString(m) } -func (*MethodDescriptorProto) ProtoMessage() {} -func (*MethodDescriptorProto) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{9} -} -func (m *MethodDescriptorProto) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MethodDescriptorProto.Unmarshal(m, b) -} -func (m *MethodDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MethodDescriptorProto.Marshal(b, m, deterministic) -} -func (dst *MethodDescriptorProto) XXX_Merge(src proto.Message) { - xxx_messageInfo_MethodDescriptorProto.Merge(dst, src) -} -func (m *MethodDescriptorProto) XXX_Size() int { - return xxx_messageInfo_MethodDescriptorProto.Size(m) -} -func (m *MethodDescriptorProto) XXX_DiscardUnknown() { - xxx_messageInfo_MethodDescriptorProto.DiscardUnknown(m) -} - -var xxx_messageInfo_MethodDescriptorProto proto.InternalMessageInfo - -const Default_MethodDescriptorProto_ClientStreaming bool = false -const Default_MethodDescriptorProto_ServerStreaming bool = false - -func (m *MethodDescriptorProto) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *MethodDescriptorProto) GetInputType() string { - if m != nil && m.InputType != nil { - return *m.InputType - } - return "" -} - -func (m *MethodDescriptorProto) GetOutputType() string { - if m != nil && m.OutputType != nil { - return *m.OutputType - } - return "" -} - -func (m *MethodDescriptorProto) GetOptions() *MethodOptions { - if m != nil { - return m.Options - } - return nil -} - -func (m *MethodDescriptorProto) GetClientStreaming() bool { - if m != nil && m.ClientStreaming != nil { - return *m.ClientStreaming - } - return Default_MethodDescriptorProto_ClientStreaming -} - -func (m *MethodDescriptorProto) GetServerStreaming() bool { - if m != nil && m.ServerStreaming != nil { - return *m.ServerStreaming - } - return Default_MethodDescriptorProto_ServerStreaming -} - -type FileOptions struct { - // Sets the Java package where classes generated from this .proto will be - // placed. By default, the proto package is used, but this is often - // inappropriate because proto packages do not normally start with backwards - // domain names. - JavaPackage *string `protobuf:"bytes,1,opt,name=java_package,json=javaPackage" json:"java_package,omitempty"` - // If set, all the classes from the .proto file are wrapped in a single - // outer class with the given name. This applies to both Proto1 - // (equivalent to the old "--one_java_file" option) and Proto2 (where - // a .proto always translates to a single class, but you may want to - // explicitly choose the class name). - JavaOuterClassname *string `protobuf:"bytes,8,opt,name=java_outer_classname,json=javaOuterClassname" json:"java_outer_classname,omitempty"` - // If set true, then the Java code generator will generate a separate .java - // file for each top-level message, enum, and service defined in the .proto - // file. Thus, these types will *not* be nested inside the outer class - // named by java_outer_classname. However, the outer class will still be - // generated to contain the file's getDescriptor() method as well as any - // top-level extensions defined in the file. - JavaMultipleFiles *bool `protobuf:"varint,10,opt,name=java_multiple_files,json=javaMultipleFiles,def=0" json:"java_multiple_files,omitempty"` - // This option does nothing. - JavaGenerateEqualsAndHash *bool `protobuf:"varint,20,opt,name=java_generate_equals_and_hash,json=javaGenerateEqualsAndHash" json:"java_generate_equals_and_hash,omitempty"` // Deprecated: Do not use. - // If set true, then the Java2 code generator will generate code that - // throws an exception whenever an attempt is made to assign a non-UTF-8 - // byte sequence to a string field. - // Message reflection will do the same. - // However, an extension field still accepts non-UTF-8 byte sequences. - // This option has no effect on when used with the lite runtime. - JavaStringCheckUtf8 *bool `protobuf:"varint,27,opt,name=java_string_check_utf8,json=javaStringCheckUtf8,def=0" json:"java_string_check_utf8,omitempty"` - OptimizeFor *FileOptions_OptimizeMode `protobuf:"varint,9,opt,name=optimize_for,json=optimizeFor,enum=google.protobuf.FileOptions_OptimizeMode,def=1" json:"optimize_for,omitempty"` - // Sets the Go package where structs generated from this .proto will be - // placed. If omitted, the Go package will be derived from the following: - // - The basename of the package import path, if provided. - // - Otherwise, the package statement in the .proto file, if present. - // - Otherwise, the basename of the .proto file, without extension. - GoPackage *string `protobuf:"bytes,11,opt,name=go_package,json=goPackage" json:"go_package,omitempty"` - // Should generic services be generated in each language? "Generic" services - // are not specific to any particular RPC system. They are generated by the - // main code generators in each language (without additional plugins). - // Generic services were the only kind of service generation supported by - // early versions of google.protobuf. - // - // Generic services are now considered deprecated in favor of using plugins - // that generate code specific to your particular RPC system. Therefore, - // these default to false. Old code which depends on generic services should - // explicitly set them to true. - CcGenericServices *bool `protobuf:"varint,16,opt,name=cc_generic_services,json=ccGenericServices,def=0" json:"cc_generic_services,omitempty"` - JavaGenericServices *bool `protobuf:"varint,17,opt,name=java_generic_services,json=javaGenericServices,def=0" json:"java_generic_services,omitempty"` - PyGenericServices *bool `protobuf:"varint,18,opt,name=py_generic_services,json=pyGenericServices,def=0" json:"py_generic_services,omitempty"` - PhpGenericServices *bool `protobuf:"varint,42,opt,name=php_generic_services,json=phpGenericServices,def=0" json:"php_generic_services,omitempty"` - // Is this file deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for everything in the file, or it will be completely ignored; in the very - // least, this is a formalization for deprecating files. - Deprecated *bool `protobuf:"varint,23,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // Enables the use of arenas for the proto messages in this file. This applies - // only to generated classes for C++. - CcEnableArenas *bool `protobuf:"varint,31,opt,name=cc_enable_arenas,json=ccEnableArenas,def=0" json:"cc_enable_arenas,omitempty"` - // Sets the objective c class prefix which is prepended to all objective c - // generated classes from this .proto. There is no default. - ObjcClassPrefix *string `protobuf:"bytes,36,opt,name=objc_class_prefix,json=objcClassPrefix" json:"objc_class_prefix,omitempty"` - // Namespace for generated classes; defaults to the package. - CsharpNamespace *string `protobuf:"bytes,37,opt,name=csharp_namespace,json=csharpNamespace" json:"csharp_namespace,omitempty"` - // By default Swift generators will take the proto package and CamelCase it - // replacing '.' with underscore and use that to prefix the types/symbols - // defined. When this options is provided, they will use this value instead - // to prefix the types/symbols defined. - SwiftPrefix *string `protobuf:"bytes,39,opt,name=swift_prefix,json=swiftPrefix" json:"swift_prefix,omitempty"` - // Sets the php class prefix which is prepended to all php generated classes - // from this .proto. Default is empty. - PhpClassPrefix *string `protobuf:"bytes,40,opt,name=php_class_prefix,json=phpClassPrefix" json:"php_class_prefix,omitempty"` - // Use this option to change the namespace of php generated classes. Default - // is empty. When this option is empty, the package name will be used for - // determining the namespace. - PhpNamespace *string `protobuf:"bytes,41,opt,name=php_namespace,json=phpNamespace" json:"php_namespace,omitempty"` - // The parser stores options it doesn't recognize here. - // See the documentation for the "Options" section above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FileOptions) Reset() { *m = FileOptions{} } -func (m *FileOptions) String() string { return proto.CompactTextString(m) } -func (*FileOptions) ProtoMessage() {} -func (*FileOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{10} -} - -var extRange_FileOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*FileOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_FileOptions -} -func (m *FileOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FileOptions.Unmarshal(m, b) -} -func (m *FileOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FileOptions.Marshal(b, m, deterministic) -} -func (dst *FileOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_FileOptions.Merge(dst, src) -} -func (m *FileOptions) XXX_Size() int { - return xxx_messageInfo_FileOptions.Size(m) -} -func (m *FileOptions) XXX_DiscardUnknown() { - xxx_messageInfo_FileOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_FileOptions proto.InternalMessageInfo - -const Default_FileOptions_JavaMultipleFiles bool = false -const Default_FileOptions_JavaStringCheckUtf8 bool = false -const Default_FileOptions_OptimizeFor FileOptions_OptimizeMode = FileOptions_SPEED -const Default_FileOptions_CcGenericServices bool = false -const Default_FileOptions_JavaGenericServices bool = false -const Default_FileOptions_PyGenericServices bool = false -const Default_FileOptions_PhpGenericServices bool = false -const Default_FileOptions_Deprecated bool = false -const Default_FileOptions_CcEnableArenas bool = false - -func (m *FileOptions) GetJavaPackage() string { - if m != nil && m.JavaPackage != nil { - return *m.JavaPackage - } - return "" -} - -func (m *FileOptions) GetJavaOuterClassname() string { - if m != nil && m.JavaOuterClassname != nil { - return *m.JavaOuterClassname - } - return "" -} - -func (m *FileOptions) GetJavaMultipleFiles() bool { - if m != nil && m.JavaMultipleFiles != nil { - return *m.JavaMultipleFiles - } - return Default_FileOptions_JavaMultipleFiles -} - -// Deprecated: Do not use. -func (m *FileOptions) GetJavaGenerateEqualsAndHash() bool { - if m != nil && m.JavaGenerateEqualsAndHash != nil { - return *m.JavaGenerateEqualsAndHash - } - return false -} - -func (m *FileOptions) GetJavaStringCheckUtf8() bool { - if m != nil && m.JavaStringCheckUtf8 != nil { - return *m.JavaStringCheckUtf8 - } - return Default_FileOptions_JavaStringCheckUtf8 -} - -func (m *FileOptions) GetOptimizeFor() FileOptions_OptimizeMode { - if m != nil && m.OptimizeFor != nil { - return *m.OptimizeFor - } - return Default_FileOptions_OptimizeFor -} - -func (m *FileOptions) GetGoPackage() string { - if m != nil && m.GoPackage != nil { - return *m.GoPackage - } - return "" -} - -func (m *FileOptions) GetCcGenericServices() bool { - if m != nil && m.CcGenericServices != nil { - return *m.CcGenericServices - } - return Default_FileOptions_CcGenericServices -} - -func (m *FileOptions) GetJavaGenericServices() bool { - if m != nil && m.JavaGenericServices != nil { - return *m.JavaGenericServices - } - return Default_FileOptions_JavaGenericServices -} - -func (m *FileOptions) GetPyGenericServices() bool { - if m != nil && m.PyGenericServices != nil { - return *m.PyGenericServices - } - return Default_FileOptions_PyGenericServices -} - -func (m *FileOptions) GetPhpGenericServices() bool { - if m != nil && m.PhpGenericServices != nil { - return *m.PhpGenericServices - } - return Default_FileOptions_PhpGenericServices -} - -func (m *FileOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_FileOptions_Deprecated -} - -func (m *FileOptions) GetCcEnableArenas() bool { - if m != nil && m.CcEnableArenas != nil { - return *m.CcEnableArenas - } - return Default_FileOptions_CcEnableArenas -} - -func (m *FileOptions) GetObjcClassPrefix() string { - if m != nil && m.ObjcClassPrefix != nil { - return *m.ObjcClassPrefix - } - return "" -} - -func (m *FileOptions) GetCsharpNamespace() string { - if m != nil && m.CsharpNamespace != nil { - return *m.CsharpNamespace - } - return "" -} - -func (m *FileOptions) GetSwiftPrefix() string { - if m != nil && m.SwiftPrefix != nil { - return *m.SwiftPrefix - } - return "" -} - -func (m *FileOptions) GetPhpClassPrefix() string { - if m != nil && m.PhpClassPrefix != nil { - return *m.PhpClassPrefix - } - return "" -} - -func (m *FileOptions) GetPhpNamespace() string { - if m != nil && m.PhpNamespace != nil { - return *m.PhpNamespace - } - return "" -} - -func (m *FileOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type MessageOptions struct { - // Set true to use the old proto1 MessageSet wire format for extensions. - // This is provided for backwards-compatibility with the MessageSet wire - // format. You should not use this for any other reason: It's less - // efficient, has fewer features, and is more complicated. - // - // The message must be defined exactly as follows: - // message Foo { - // option message_set_wire_format = true; - // extensions 4 to max; - // } - // Note that the message cannot have any defined fields; MessageSets only - // have extensions. - // - // All extensions of your type must be singular messages; e.g. they cannot - // be int32s, enums, or repeated messages. - // - // Because this is an option, the above two restrictions are not enforced by - // the protocol compiler. - MessageSetWireFormat *bool `protobuf:"varint,1,opt,name=message_set_wire_format,json=messageSetWireFormat,def=0" json:"message_set_wire_format,omitempty"` - // Disables the generation of the standard "descriptor()" accessor, which can - // conflict with a field of the same name. This is meant to make migration - // from proto1 easier; new code should avoid fields named "descriptor". - NoStandardDescriptorAccessor *bool `protobuf:"varint,2,opt,name=no_standard_descriptor_accessor,json=noStandardDescriptorAccessor,def=0" json:"no_standard_descriptor_accessor,omitempty"` - // Is this message deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the message, or it will be completely ignored; in the very least, - // this is a formalization for deprecating messages. - Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // Whether the message is an automatically generated map entry type for the - // maps field. - // - // For maps fields: - // map map_field = 1; - // The parsed descriptor looks like: - // message MapFieldEntry { - // option map_entry = true; - // optional KeyType key = 1; - // optional ValueType value = 2; - // } - // repeated MapFieldEntry map_field = 1; - // - // Implementations may choose not to generate the map_entry=true message, but - // use a native map in the target language to hold the keys and values. - // The reflection APIs in such implementions still need to work as - // if the field is a repeated message field. - // - // NOTE: Do not set the option in .proto files. Always use the maps syntax - // instead. The option should only be implicitly set by the proto compiler - // parser. - MapEntry *bool `protobuf:"varint,7,opt,name=map_entry,json=mapEntry" json:"map_entry,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MessageOptions) Reset() { *m = MessageOptions{} } -func (m *MessageOptions) String() string { return proto.CompactTextString(m) } -func (*MessageOptions) ProtoMessage() {} -func (*MessageOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{11} -} - -var extRange_MessageOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*MessageOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_MessageOptions -} -func (m *MessageOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MessageOptions.Unmarshal(m, b) -} -func (m *MessageOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MessageOptions.Marshal(b, m, deterministic) -} -func (dst *MessageOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_MessageOptions.Merge(dst, src) -} -func (m *MessageOptions) XXX_Size() int { - return xxx_messageInfo_MessageOptions.Size(m) -} -func (m *MessageOptions) XXX_DiscardUnknown() { - xxx_messageInfo_MessageOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_MessageOptions proto.InternalMessageInfo - -const Default_MessageOptions_MessageSetWireFormat bool = false -const Default_MessageOptions_NoStandardDescriptorAccessor bool = false -const Default_MessageOptions_Deprecated bool = false - -func (m *MessageOptions) GetMessageSetWireFormat() bool { - if m != nil && m.MessageSetWireFormat != nil { - return *m.MessageSetWireFormat - } - return Default_MessageOptions_MessageSetWireFormat -} - -func (m *MessageOptions) GetNoStandardDescriptorAccessor() bool { - if m != nil && m.NoStandardDescriptorAccessor != nil { - return *m.NoStandardDescriptorAccessor - } - return Default_MessageOptions_NoStandardDescriptorAccessor -} - -func (m *MessageOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_MessageOptions_Deprecated -} - -func (m *MessageOptions) GetMapEntry() bool { - if m != nil && m.MapEntry != nil { - return *m.MapEntry - } - return false -} - -func (m *MessageOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type FieldOptions struct { - // The ctype option instructs the C++ code generator to use a different - // representation of the field than it normally would. See the specific - // options below. This option is not yet implemented in the open source - // release -- sorry, we'll try to include it in a future version! - Ctype *FieldOptions_CType `protobuf:"varint,1,opt,name=ctype,enum=google.protobuf.FieldOptions_CType,def=0" json:"ctype,omitempty"` - // The packed option can be enabled for repeated primitive fields to enable - // a more efficient representation on the wire. Rather than repeatedly - // writing the tag and type for each element, the entire array is encoded as - // a single length-delimited blob. In proto3, only explicit setting it to - // false will avoid using packed encoding. - Packed *bool `protobuf:"varint,2,opt,name=packed" json:"packed,omitempty"` - // The jstype option determines the JavaScript type used for values of the - // field. The option is permitted only for 64 bit integral and fixed types - // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING - // is represented as JavaScript string, which avoids loss of precision that - // can happen when a large value is converted to a floating point JavaScript. - // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to - // use the JavaScript "number" type. The behavior of the default option - // JS_NORMAL is implementation dependent. - // - // This option is an enum to permit additional types to be added, e.g. - // goog.math.Integer. - Jstype *FieldOptions_JSType `protobuf:"varint,6,opt,name=jstype,enum=google.protobuf.FieldOptions_JSType,def=0" json:"jstype,omitempty"` - // Should this field be parsed lazily? Lazy applies only to message-type - // fields. It means that when the outer message is initially parsed, the - // inner message's contents will not be parsed but instead stored in encoded - // form. The inner message will actually be parsed when it is first accessed. - // - // This is only a hint. Implementations are free to choose whether to use - // eager or lazy parsing regardless of the value of this option. However, - // setting this option true suggests that the protocol author believes that - // using lazy parsing on this field is worth the additional bookkeeping - // overhead typically needed to implement it. - // - // This option does not affect the public interface of any generated code; - // all method signatures remain the same. Furthermore, thread-safety of the - // interface is not affected by this option; const methods remain safe to - // call from multiple threads concurrently, while non-const methods continue - // to require exclusive access. - // - // - // Note that implementations may choose not to check required fields within - // a lazy sub-message. That is, calling IsInitialized() on the outer message - // may return true even if the inner message has missing required fields. - // This is necessary because otherwise the inner message would have to be - // parsed in order to perform the check, defeating the purpose of lazy - // parsing. An implementation which chooses not to check required fields - // must be consistent about it. That is, for any particular sub-message, the - // implementation must either *always* check its required fields, or *never* - // check its required fields, regardless of whether or not the message has - // been parsed. - Lazy *bool `protobuf:"varint,5,opt,name=lazy,def=0" json:"lazy,omitempty"` - // Is this field deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for accessors, or it will be completely ignored; in the very least, this - // is a formalization for deprecating fields. - Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // For Google-internal migration only. Do not use. - Weak *bool `protobuf:"varint,10,opt,name=weak,def=0" json:"weak,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *FieldOptions) Reset() { *m = FieldOptions{} } -func (m *FieldOptions) String() string { return proto.CompactTextString(m) } -func (*FieldOptions) ProtoMessage() {} -func (*FieldOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{12} -} - -var extRange_FieldOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*FieldOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_FieldOptions -} -func (m *FieldOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_FieldOptions.Unmarshal(m, b) -} -func (m *FieldOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_FieldOptions.Marshal(b, m, deterministic) -} -func (dst *FieldOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_FieldOptions.Merge(dst, src) -} -func (m *FieldOptions) XXX_Size() int { - return xxx_messageInfo_FieldOptions.Size(m) -} -func (m *FieldOptions) XXX_DiscardUnknown() { - xxx_messageInfo_FieldOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_FieldOptions proto.InternalMessageInfo - -const Default_FieldOptions_Ctype FieldOptions_CType = FieldOptions_STRING -const Default_FieldOptions_Jstype FieldOptions_JSType = FieldOptions_JS_NORMAL -const Default_FieldOptions_Lazy bool = false -const Default_FieldOptions_Deprecated bool = false -const Default_FieldOptions_Weak bool = false - -func (m *FieldOptions) GetCtype() FieldOptions_CType { - if m != nil && m.Ctype != nil { - return *m.Ctype - } - return Default_FieldOptions_Ctype -} - -func (m *FieldOptions) GetPacked() bool { - if m != nil && m.Packed != nil { - return *m.Packed - } - return false -} - -func (m *FieldOptions) GetJstype() FieldOptions_JSType { - if m != nil && m.Jstype != nil { - return *m.Jstype - } - return Default_FieldOptions_Jstype -} - -func (m *FieldOptions) GetLazy() bool { - if m != nil && m.Lazy != nil { - return *m.Lazy - } - return Default_FieldOptions_Lazy -} - -func (m *FieldOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_FieldOptions_Deprecated -} - -func (m *FieldOptions) GetWeak() bool { - if m != nil && m.Weak != nil { - return *m.Weak - } - return Default_FieldOptions_Weak -} - -func (m *FieldOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type OneofOptions struct { - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *OneofOptions) Reset() { *m = OneofOptions{} } -func (m *OneofOptions) String() string { return proto.CompactTextString(m) } -func (*OneofOptions) ProtoMessage() {} -func (*OneofOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{13} -} - -var extRange_OneofOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*OneofOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_OneofOptions -} -func (m *OneofOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_OneofOptions.Unmarshal(m, b) -} -func (m *OneofOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_OneofOptions.Marshal(b, m, deterministic) -} -func (dst *OneofOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_OneofOptions.Merge(dst, src) -} -func (m *OneofOptions) XXX_Size() int { - return xxx_messageInfo_OneofOptions.Size(m) -} -func (m *OneofOptions) XXX_DiscardUnknown() { - xxx_messageInfo_OneofOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_OneofOptions proto.InternalMessageInfo - -func (m *OneofOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type EnumOptions struct { - // Set this option to true to allow mapping different tag names to the same - // value. - AllowAlias *bool `protobuf:"varint,2,opt,name=allow_alias,json=allowAlias" json:"allow_alias,omitempty"` - // Is this enum deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the enum, or it will be completely ignored; in the very least, this - // is a formalization for deprecating enums. - Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EnumOptions) Reset() { *m = EnumOptions{} } -func (m *EnumOptions) String() string { return proto.CompactTextString(m) } -func (*EnumOptions) ProtoMessage() {} -func (*EnumOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{14} -} - -var extRange_EnumOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*EnumOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_EnumOptions -} -func (m *EnumOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EnumOptions.Unmarshal(m, b) -} -func (m *EnumOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EnumOptions.Marshal(b, m, deterministic) -} -func (dst *EnumOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_EnumOptions.Merge(dst, src) -} -func (m *EnumOptions) XXX_Size() int { - return xxx_messageInfo_EnumOptions.Size(m) -} -func (m *EnumOptions) XXX_DiscardUnknown() { - xxx_messageInfo_EnumOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_EnumOptions proto.InternalMessageInfo - -const Default_EnumOptions_Deprecated bool = false - -func (m *EnumOptions) GetAllowAlias() bool { - if m != nil && m.AllowAlias != nil { - return *m.AllowAlias - } - return false -} - -func (m *EnumOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_EnumOptions_Deprecated -} - -func (m *EnumOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type EnumValueOptions struct { - // Is this enum value deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the enum value, or it will be completely ignored; in the very least, - // this is a formalization for deprecating enum values. - Deprecated *bool `protobuf:"varint,1,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *EnumValueOptions) Reset() { *m = EnumValueOptions{} } -func (m *EnumValueOptions) String() string { return proto.CompactTextString(m) } -func (*EnumValueOptions) ProtoMessage() {} -func (*EnumValueOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{15} -} - -var extRange_EnumValueOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*EnumValueOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_EnumValueOptions -} -func (m *EnumValueOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_EnumValueOptions.Unmarshal(m, b) -} -func (m *EnumValueOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_EnumValueOptions.Marshal(b, m, deterministic) -} -func (dst *EnumValueOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_EnumValueOptions.Merge(dst, src) -} -func (m *EnumValueOptions) XXX_Size() int { - return xxx_messageInfo_EnumValueOptions.Size(m) -} -func (m *EnumValueOptions) XXX_DiscardUnknown() { - xxx_messageInfo_EnumValueOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_EnumValueOptions proto.InternalMessageInfo - -const Default_EnumValueOptions_Deprecated bool = false - -func (m *EnumValueOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_EnumValueOptions_Deprecated -} - -func (m *EnumValueOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type ServiceOptions struct { - // Is this service deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the service, or it will be completely ignored; in the very least, - // this is a formalization for deprecating services. - Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ServiceOptions) Reset() { *m = ServiceOptions{} } -func (m *ServiceOptions) String() string { return proto.CompactTextString(m) } -func (*ServiceOptions) ProtoMessage() {} -func (*ServiceOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{16} -} - -var extRange_ServiceOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*ServiceOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_ServiceOptions -} -func (m *ServiceOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ServiceOptions.Unmarshal(m, b) -} -func (m *ServiceOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ServiceOptions.Marshal(b, m, deterministic) -} -func (dst *ServiceOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_ServiceOptions.Merge(dst, src) -} -func (m *ServiceOptions) XXX_Size() int { - return xxx_messageInfo_ServiceOptions.Size(m) -} -func (m *ServiceOptions) XXX_DiscardUnknown() { - xxx_messageInfo_ServiceOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_ServiceOptions proto.InternalMessageInfo - -const Default_ServiceOptions_Deprecated bool = false - -func (m *ServiceOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_ServiceOptions_Deprecated -} - -func (m *ServiceOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -type MethodOptions struct { - // Is this method deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for the method, or it will be completely ignored; in the very least, - // this is a formalization for deprecating methods. - Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"` - IdempotencyLevel *MethodOptions_IdempotencyLevel `protobuf:"varint,34,opt,name=idempotency_level,json=idempotencyLevel,enum=google.protobuf.MethodOptions_IdempotencyLevel,def=0" json:"idempotency_level,omitempty"` - // The parser stores options it doesn't recognize here. See above. - UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - proto.XXX_InternalExtensions `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MethodOptions) Reset() { *m = MethodOptions{} } -func (m *MethodOptions) String() string { return proto.CompactTextString(m) } -func (*MethodOptions) ProtoMessage() {} -func (*MethodOptions) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{17} -} - -var extRange_MethodOptions = []proto.ExtensionRange{ - {Start: 1000, End: 536870911}, -} - -func (*MethodOptions) ExtensionRangeArray() []proto.ExtensionRange { - return extRange_MethodOptions -} -func (m *MethodOptions) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_MethodOptions.Unmarshal(m, b) -} -func (m *MethodOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_MethodOptions.Marshal(b, m, deterministic) -} -func (dst *MethodOptions) XXX_Merge(src proto.Message) { - xxx_messageInfo_MethodOptions.Merge(dst, src) -} -func (m *MethodOptions) XXX_Size() int { - return xxx_messageInfo_MethodOptions.Size(m) -} -func (m *MethodOptions) XXX_DiscardUnknown() { - xxx_messageInfo_MethodOptions.DiscardUnknown(m) -} - -var xxx_messageInfo_MethodOptions proto.InternalMessageInfo - -const Default_MethodOptions_Deprecated bool = false -const Default_MethodOptions_IdempotencyLevel MethodOptions_IdempotencyLevel = MethodOptions_IDEMPOTENCY_UNKNOWN - -func (m *MethodOptions) GetDeprecated() bool { - if m != nil && m.Deprecated != nil { - return *m.Deprecated - } - return Default_MethodOptions_Deprecated -} - -func (m *MethodOptions) GetIdempotencyLevel() MethodOptions_IdempotencyLevel { - if m != nil && m.IdempotencyLevel != nil { - return *m.IdempotencyLevel - } - return Default_MethodOptions_IdempotencyLevel -} - -func (m *MethodOptions) GetUninterpretedOption() []*UninterpretedOption { - if m != nil { - return m.UninterpretedOption - } - return nil -} - -// A message representing a option the parser does not recognize. This only -// appears in options protos created by the compiler::Parser class. -// DescriptorPool resolves these when building Descriptor objects. Therefore, -// options protos in descriptor objects (e.g. returned by Descriptor::options(), -// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions -// in them. -type UninterpretedOption struct { - Name []*UninterpretedOption_NamePart `protobuf:"bytes,2,rep,name=name" json:"name,omitempty"` - // The value of the uninterpreted option, in whatever type the tokenizer - // identified it as during parsing. Exactly one of these should be set. - IdentifierValue *string `protobuf:"bytes,3,opt,name=identifier_value,json=identifierValue" json:"identifier_value,omitempty"` - PositiveIntValue *uint64 `protobuf:"varint,4,opt,name=positive_int_value,json=positiveIntValue" json:"positive_int_value,omitempty"` - NegativeIntValue *int64 `protobuf:"varint,5,opt,name=negative_int_value,json=negativeIntValue" json:"negative_int_value,omitempty"` - DoubleValue *float64 `protobuf:"fixed64,6,opt,name=double_value,json=doubleValue" json:"double_value,omitempty"` - StringValue []byte `protobuf:"bytes,7,opt,name=string_value,json=stringValue" json:"string_value,omitempty"` - AggregateValue *string `protobuf:"bytes,8,opt,name=aggregate_value,json=aggregateValue" json:"aggregate_value,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *UninterpretedOption) Reset() { *m = UninterpretedOption{} } -func (m *UninterpretedOption) String() string { return proto.CompactTextString(m) } -func (*UninterpretedOption) ProtoMessage() {} -func (*UninterpretedOption) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{18} -} -func (m *UninterpretedOption) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_UninterpretedOption.Unmarshal(m, b) -} -func (m *UninterpretedOption) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_UninterpretedOption.Marshal(b, m, deterministic) -} -func (dst *UninterpretedOption) XXX_Merge(src proto.Message) { - xxx_messageInfo_UninterpretedOption.Merge(dst, src) -} -func (m *UninterpretedOption) XXX_Size() int { - return xxx_messageInfo_UninterpretedOption.Size(m) -} -func (m *UninterpretedOption) XXX_DiscardUnknown() { - xxx_messageInfo_UninterpretedOption.DiscardUnknown(m) -} - -var xxx_messageInfo_UninterpretedOption proto.InternalMessageInfo - -func (m *UninterpretedOption) GetName() []*UninterpretedOption_NamePart { - if m != nil { - return m.Name - } - return nil -} - -func (m *UninterpretedOption) GetIdentifierValue() string { - if m != nil && m.IdentifierValue != nil { - return *m.IdentifierValue - } - return "" -} - -func (m *UninterpretedOption) GetPositiveIntValue() uint64 { - if m != nil && m.PositiveIntValue != nil { - return *m.PositiveIntValue - } - return 0 -} - -func (m *UninterpretedOption) GetNegativeIntValue() int64 { - if m != nil && m.NegativeIntValue != nil { - return *m.NegativeIntValue - } - return 0 -} - -func (m *UninterpretedOption) GetDoubleValue() float64 { - if m != nil && m.DoubleValue != nil { - return *m.DoubleValue - } - return 0 -} - -func (m *UninterpretedOption) GetStringValue() []byte { - if m != nil { - return m.StringValue - } - return nil -} - -func (m *UninterpretedOption) GetAggregateValue() string { - if m != nil && m.AggregateValue != nil { - return *m.AggregateValue - } - return "" -} - -// The name of the uninterpreted option. Each string represents a segment in -// a dot-separated name. is_extension is true iff a segment represents an -// extension (denoted with parentheses in options specs in .proto files). -// E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents -// "foo.(bar.baz).qux". -type UninterpretedOption_NamePart struct { - NamePart *string `protobuf:"bytes,1,req,name=name_part,json=namePart" json:"name_part,omitempty"` - IsExtension *bool `protobuf:"varint,2,req,name=is_extension,json=isExtension" json:"is_extension,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *UninterpretedOption_NamePart) Reset() { *m = UninterpretedOption_NamePart{} } -func (m *UninterpretedOption_NamePart) String() string { return proto.CompactTextString(m) } -func (*UninterpretedOption_NamePart) ProtoMessage() {} -func (*UninterpretedOption_NamePart) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{18, 0} -} -func (m *UninterpretedOption_NamePart) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_UninterpretedOption_NamePart.Unmarshal(m, b) -} -func (m *UninterpretedOption_NamePart) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_UninterpretedOption_NamePart.Marshal(b, m, deterministic) -} -func (dst *UninterpretedOption_NamePart) XXX_Merge(src proto.Message) { - xxx_messageInfo_UninterpretedOption_NamePart.Merge(dst, src) -} -func (m *UninterpretedOption_NamePart) XXX_Size() int { - return xxx_messageInfo_UninterpretedOption_NamePart.Size(m) -} -func (m *UninterpretedOption_NamePart) XXX_DiscardUnknown() { - xxx_messageInfo_UninterpretedOption_NamePart.DiscardUnknown(m) -} - -var xxx_messageInfo_UninterpretedOption_NamePart proto.InternalMessageInfo - -func (m *UninterpretedOption_NamePart) GetNamePart() string { - if m != nil && m.NamePart != nil { - return *m.NamePart - } - return "" -} - -func (m *UninterpretedOption_NamePart) GetIsExtension() bool { - if m != nil && m.IsExtension != nil { - return *m.IsExtension - } - return false -} - -// Encapsulates information about the original source file from which a -// FileDescriptorProto was generated. -type SourceCodeInfo struct { - // A Location identifies a piece of source code in a .proto file which - // corresponds to a particular definition. This information is intended - // to be useful to IDEs, code indexers, documentation generators, and similar - // tools. - // - // For example, say we have a file like: - // message Foo { - // optional string foo = 1; - // } - // Let's look at just the field definition: - // optional string foo = 1; - // ^ ^^ ^^ ^ ^^^ - // a bc de f ghi - // We have the following locations: - // span path represents - // [a,i) [ 4, 0, 2, 0 ] The whole field definition. - // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional). - // [c,d) [ 4, 0, 2, 0, 5 ] The type (string). - // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo). - // [g,h) [ 4, 0, 2, 0, 3 ] The number (1). - // - // Notes: - // - A location may refer to a repeated field itself (i.e. not to any - // particular index within it). This is used whenever a set of elements are - // logically enclosed in a single code segment. For example, an entire - // extend block (possibly containing multiple extension definitions) will - // have an outer location whose path refers to the "extensions" repeated - // field without an index. - // - Multiple locations may have the same path. This happens when a single - // logical declaration is spread out across multiple places. The most - // obvious example is the "extend" block again -- there may be multiple - // extend blocks in the same scope, each of which will have the same path. - // - A location's span is not always a subset of its parent's span. For - // example, the "extendee" of an extension declaration appears at the - // beginning of the "extend" block and is shared by all extensions within - // the block. - // - Just because a location's span is a subset of some other location's span - // does not mean that it is a descendent. For example, a "group" defines - // both a type and a field in a single declaration. Thus, the locations - // corresponding to the type and field and their components will overlap. - // - Code which tries to interpret locations should probably be designed to - // ignore those that it doesn't understand, as more types of locations could - // be recorded in the future. - Location []*SourceCodeInfo_Location `protobuf:"bytes,1,rep,name=location" json:"location,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SourceCodeInfo) Reset() { *m = SourceCodeInfo{} } -func (m *SourceCodeInfo) String() string { return proto.CompactTextString(m) } -func (*SourceCodeInfo) ProtoMessage() {} -func (*SourceCodeInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{19} -} -func (m *SourceCodeInfo) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SourceCodeInfo.Unmarshal(m, b) -} -func (m *SourceCodeInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SourceCodeInfo.Marshal(b, m, deterministic) -} -func (dst *SourceCodeInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_SourceCodeInfo.Merge(dst, src) -} -func (m *SourceCodeInfo) XXX_Size() int { - return xxx_messageInfo_SourceCodeInfo.Size(m) -} -func (m *SourceCodeInfo) XXX_DiscardUnknown() { - xxx_messageInfo_SourceCodeInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_SourceCodeInfo proto.InternalMessageInfo - -func (m *SourceCodeInfo) GetLocation() []*SourceCodeInfo_Location { - if m != nil { - return m.Location - } - return nil -} - -type SourceCodeInfo_Location struct { - // Identifies which part of the FileDescriptorProto was defined at this - // location. - // - // Each element is a field number or an index. They form a path from - // the root FileDescriptorProto to the place where the definition. For - // example, this path: - // [ 4, 3, 2, 7, 1 ] - // refers to: - // file.message_type(3) // 4, 3 - // .field(7) // 2, 7 - // .name() // 1 - // This is because FileDescriptorProto.message_type has field number 4: - // repeated DescriptorProto message_type = 4; - // and DescriptorProto.field has field number 2: - // repeated FieldDescriptorProto field = 2; - // and FieldDescriptorProto.name has field number 1: - // optional string name = 1; - // - // Thus, the above path gives the location of a field name. If we removed - // the last element: - // [ 4, 3, 2, 7 ] - // this path refers to the whole field declaration (from the beginning - // of the label to the terminating semicolon). - Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"` - // Always has exactly three or four elements: start line, start column, - // end line (optional, otherwise assumed same as start line), end column. - // These are packed into a single field for efficiency. Note that line - // and column numbers are zero-based -- typically you will want to add - // 1 to each before displaying to a user. - Span []int32 `protobuf:"varint,2,rep,packed,name=span" json:"span,omitempty"` - // If this SourceCodeInfo represents a complete declaration, these are any - // comments appearing before and after the declaration which appear to be - // attached to the declaration. - // - // A series of line comments appearing on consecutive lines, with no other - // tokens appearing on those lines, will be treated as a single comment. - // - // leading_detached_comments will keep paragraphs of comments that appear - // before (but not connected to) the current element. Each paragraph, - // separated by empty lines, will be one comment element in the repeated - // field. - // - // Only the comment content is provided; comment markers (e.g. //) are - // stripped out. For block comments, leading whitespace and an asterisk - // will be stripped from the beginning of each line other than the first. - // Newlines are included in the output. - // - // Examples: - // - // optional int32 foo = 1; // Comment attached to foo. - // // Comment attached to bar. - // optional int32 bar = 2; - // - // optional string baz = 3; - // // Comment attached to baz. - // // Another line attached to baz. - // - // // Comment attached to qux. - // // - // // Another line attached to qux. - // optional double qux = 4; - // - // // Detached comment for corge. This is not leading or trailing comments - // // to qux or corge because there are blank lines separating it from - // // both. - // - // // Detached comment for corge paragraph 2. - // - // optional string corge = 5; - // /* Block comment attached - // * to corge. Leading asterisks - // * will be removed. */ - // /* Block comment attached to - // * grault. */ - // optional int32 grault = 6; - // - // // ignored detached comments. - LeadingComments *string `protobuf:"bytes,3,opt,name=leading_comments,json=leadingComments" json:"leading_comments,omitempty"` - TrailingComments *string `protobuf:"bytes,4,opt,name=trailing_comments,json=trailingComments" json:"trailing_comments,omitempty"` - LeadingDetachedComments []string `protobuf:"bytes,6,rep,name=leading_detached_comments,json=leadingDetachedComments" json:"leading_detached_comments,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SourceCodeInfo_Location) Reset() { *m = SourceCodeInfo_Location{} } -func (m *SourceCodeInfo_Location) String() string { return proto.CompactTextString(m) } -func (*SourceCodeInfo_Location) ProtoMessage() {} -func (*SourceCodeInfo_Location) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{19, 0} -} -func (m *SourceCodeInfo_Location) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SourceCodeInfo_Location.Unmarshal(m, b) -} -func (m *SourceCodeInfo_Location) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SourceCodeInfo_Location.Marshal(b, m, deterministic) -} -func (dst *SourceCodeInfo_Location) XXX_Merge(src proto.Message) { - xxx_messageInfo_SourceCodeInfo_Location.Merge(dst, src) -} -func (m *SourceCodeInfo_Location) XXX_Size() int { - return xxx_messageInfo_SourceCodeInfo_Location.Size(m) -} -func (m *SourceCodeInfo_Location) XXX_DiscardUnknown() { - xxx_messageInfo_SourceCodeInfo_Location.DiscardUnknown(m) -} - -var xxx_messageInfo_SourceCodeInfo_Location proto.InternalMessageInfo - -func (m *SourceCodeInfo_Location) GetPath() []int32 { - if m != nil { - return m.Path - } - return nil -} - -func (m *SourceCodeInfo_Location) GetSpan() []int32 { - if m != nil { - return m.Span - } - return nil -} - -func (m *SourceCodeInfo_Location) GetLeadingComments() string { - if m != nil && m.LeadingComments != nil { - return *m.LeadingComments - } - return "" -} - -func (m *SourceCodeInfo_Location) GetTrailingComments() string { - if m != nil && m.TrailingComments != nil { - return *m.TrailingComments - } - return "" -} - -func (m *SourceCodeInfo_Location) GetLeadingDetachedComments() []string { - if m != nil { - return m.LeadingDetachedComments - } - return nil -} - -// Describes the relationship between generated code and its original source -// file. A GeneratedCodeInfo message is associated with only one generated -// source file, but may contain references to different source .proto files. -type GeneratedCodeInfo struct { - // An Annotation connects some span of text in generated code to an element - // of its generating .proto file. - Annotation []*GeneratedCodeInfo_Annotation `protobuf:"bytes,1,rep,name=annotation" json:"annotation,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GeneratedCodeInfo) Reset() { *m = GeneratedCodeInfo{} } -func (m *GeneratedCodeInfo) String() string { return proto.CompactTextString(m) } -func (*GeneratedCodeInfo) ProtoMessage() {} -func (*GeneratedCodeInfo) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{20} -} -func (m *GeneratedCodeInfo) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GeneratedCodeInfo.Unmarshal(m, b) -} -func (m *GeneratedCodeInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GeneratedCodeInfo.Marshal(b, m, deterministic) -} -func (dst *GeneratedCodeInfo) XXX_Merge(src proto.Message) { - xxx_messageInfo_GeneratedCodeInfo.Merge(dst, src) -} -func (m *GeneratedCodeInfo) XXX_Size() int { - return xxx_messageInfo_GeneratedCodeInfo.Size(m) -} -func (m *GeneratedCodeInfo) XXX_DiscardUnknown() { - xxx_messageInfo_GeneratedCodeInfo.DiscardUnknown(m) -} - -var xxx_messageInfo_GeneratedCodeInfo proto.InternalMessageInfo - -func (m *GeneratedCodeInfo) GetAnnotation() []*GeneratedCodeInfo_Annotation { - if m != nil { - return m.Annotation - } - return nil -} - -type GeneratedCodeInfo_Annotation struct { - // Identifies the element in the original source .proto file. This field - // is formatted the same as SourceCodeInfo.Location.path. - Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"` - // Identifies the filesystem path to the original source .proto. - SourceFile *string `protobuf:"bytes,2,opt,name=source_file,json=sourceFile" json:"source_file,omitempty"` - // Identifies the starting offset in bytes in the generated code - // that relates to the identified object. - Begin *int32 `protobuf:"varint,3,opt,name=begin" json:"begin,omitempty"` - // Identifies the ending offset in bytes in the generated code that - // relates to the identified offset. The end offset should be one past - // the last relevant byte (so the length of the text = end - begin). - End *int32 `protobuf:"varint,4,opt,name=end" json:"end,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *GeneratedCodeInfo_Annotation) Reset() { *m = GeneratedCodeInfo_Annotation{} } -func (m *GeneratedCodeInfo_Annotation) String() string { return proto.CompactTextString(m) } -func (*GeneratedCodeInfo_Annotation) ProtoMessage() {} -func (*GeneratedCodeInfo_Annotation) Descriptor() ([]byte, []int) { - return fileDescriptor_descriptor_4df4cb5f42392df6, []int{20, 0} -} -func (m *GeneratedCodeInfo_Annotation) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_GeneratedCodeInfo_Annotation.Unmarshal(m, b) -} -func (m *GeneratedCodeInfo_Annotation) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_GeneratedCodeInfo_Annotation.Marshal(b, m, deterministic) -} -func (dst *GeneratedCodeInfo_Annotation) XXX_Merge(src proto.Message) { - xxx_messageInfo_GeneratedCodeInfo_Annotation.Merge(dst, src) -} -func (m *GeneratedCodeInfo_Annotation) XXX_Size() int { - return xxx_messageInfo_GeneratedCodeInfo_Annotation.Size(m) -} -func (m *GeneratedCodeInfo_Annotation) XXX_DiscardUnknown() { - xxx_messageInfo_GeneratedCodeInfo_Annotation.DiscardUnknown(m) -} - -var xxx_messageInfo_GeneratedCodeInfo_Annotation proto.InternalMessageInfo - -func (m *GeneratedCodeInfo_Annotation) GetPath() []int32 { - if m != nil { - return m.Path - } - return nil -} - -func (m *GeneratedCodeInfo_Annotation) GetSourceFile() string { - if m != nil && m.SourceFile != nil { - return *m.SourceFile - } - return "" -} - -func (m *GeneratedCodeInfo_Annotation) GetBegin() int32 { - if m != nil && m.Begin != nil { - return *m.Begin - } - return 0 -} - -func (m *GeneratedCodeInfo_Annotation) GetEnd() int32 { - if m != nil && m.End != nil { - return *m.End - } - return 0 -} - -func init() { - proto.RegisterType((*FileDescriptorSet)(nil), "google.protobuf.FileDescriptorSet") - proto.RegisterType((*FileDescriptorProto)(nil), "google.protobuf.FileDescriptorProto") - proto.RegisterType((*DescriptorProto)(nil), "google.protobuf.DescriptorProto") - proto.RegisterType((*DescriptorProto_ExtensionRange)(nil), "google.protobuf.DescriptorProto.ExtensionRange") - proto.RegisterType((*DescriptorProto_ReservedRange)(nil), "google.protobuf.DescriptorProto.ReservedRange") - proto.RegisterType((*ExtensionRangeOptions)(nil), "google.protobuf.ExtensionRangeOptions") - proto.RegisterType((*FieldDescriptorProto)(nil), "google.protobuf.FieldDescriptorProto") - proto.RegisterType((*OneofDescriptorProto)(nil), "google.protobuf.OneofDescriptorProto") - proto.RegisterType((*EnumDescriptorProto)(nil), "google.protobuf.EnumDescriptorProto") - proto.RegisterType((*EnumDescriptorProto_EnumReservedRange)(nil), "google.protobuf.EnumDescriptorProto.EnumReservedRange") - proto.RegisterType((*EnumValueDescriptorProto)(nil), "google.protobuf.EnumValueDescriptorProto") - proto.RegisterType((*ServiceDescriptorProto)(nil), "google.protobuf.ServiceDescriptorProto") - proto.RegisterType((*MethodDescriptorProto)(nil), "google.protobuf.MethodDescriptorProto") - proto.RegisterType((*FileOptions)(nil), "google.protobuf.FileOptions") - proto.RegisterType((*MessageOptions)(nil), "google.protobuf.MessageOptions") - proto.RegisterType((*FieldOptions)(nil), "google.protobuf.FieldOptions") - proto.RegisterType((*OneofOptions)(nil), "google.protobuf.OneofOptions") - proto.RegisterType((*EnumOptions)(nil), "google.protobuf.EnumOptions") - proto.RegisterType((*EnumValueOptions)(nil), "google.protobuf.EnumValueOptions") - proto.RegisterType((*ServiceOptions)(nil), "google.protobuf.ServiceOptions") - proto.RegisterType((*MethodOptions)(nil), "google.protobuf.MethodOptions") - proto.RegisterType((*UninterpretedOption)(nil), "google.protobuf.UninterpretedOption") - proto.RegisterType((*UninterpretedOption_NamePart)(nil), "google.protobuf.UninterpretedOption.NamePart") - proto.RegisterType((*SourceCodeInfo)(nil), "google.protobuf.SourceCodeInfo") - proto.RegisterType((*SourceCodeInfo_Location)(nil), "google.protobuf.SourceCodeInfo.Location") - proto.RegisterType((*GeneratedCodeInfo)(nil), "google.protobuf.GeneratedCodeInfo") - proto.RegisterType((*GeneratedCodeInfo_Annotation)(nil), "google.protobuf.GeneratedCodeInfo.Annotation") - proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Type", FieldDescriptorProto_Type_name, FieldDescriptorProto_Type_value) - proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Label", FieldDescriptorProto_Label_name, FieldDescriptorProto_Label_value) - proto.RegisterEnum("google.protobuf.FileOptions_OptimizeMode", FileOptions_OptimizeMode_name, FileOptions_OptimizeMode_value) - proto.RegisterEnum("google.protobuf.FieldOptions_CType", FieldOptions_CType_name, FieldOptions_CType_value) - proto.RegisterEnum("google.protobuf.FieldOptions_JSType", FieldOptions_JSType_name, FieldOptions_JSType_value) - proto.RegisterEnum("google.protobuf.MethodOptions_IdempotencyLevel", MethodOptions_IdempotencyLevel_name, MethodOptions_IdempotencyLevel_value) -} - -func init() { - proto.RegisterFile("google/protobuf/descriptor.proto", fileDescriptor_descriptor_4df4cb5f42392df6) -} - -var fileDescriptor_descriptor_4df4cb5f42392df6 = []byte{ - // 2555 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x59, 0xdd, 0x6e, 0x1b, 0xc7, - 0xf5, 0xcf, 0xf2, 0x4b, 0xe4, 0x21, 0x45, 0x8d, 0x46, 0x8a, 0xbd, 0x56, 0x3e, 0x2c, 0x33, 0x1f, - 0x96, 0x9d, 0x7f, 0xa8, 0xc0, 0xb1, 0x1d, 0x47, 0xfe, 0x23, 0x2d, 0x45, 0xae, 0x15, 0xaa, 0x12, - 0xc9, 0x2e, 0xa9, 0xe6, 0x03, 0x28, 0x16, 0xa3, 0xdd, 0x21, 0xb9, 0xf6, 0x72, 0x77, 0xb3, 0xbb, - 0xb4, 0xad, 0xa0, 0x17, 0x06, 0x7a, 0xd5, 0xab, 0xde, 0x16, 0x45, 0xd1, 0x8b, 0xde, 0x04, 0xe8, - 0x03, 0x14, 0xc8, 0x5d, 0x9f, 0xa0, 0x40, 0xde, 0xa0, 0x68, 0x0b, 0xb4, 0x8f, 0xd0, 0xcb, 0x62, - 0x66, 0x76, 0x97, 0xbb, 0x24, 0x15, 0x2b, 0x01, 0xe2, 0x5c, 0x91, 0xf3, 0x9b, 0xdf, 0x39, 0x73, - 0xe6, 0xcc, 0x99, 0x33, 0x67, 0x66, 0x61, 0x7b, 0xe4, 0x38, 0x23, 0x8b, 0xee, 0xba, 0x9e, 0x13, - 0x38, 0xa7, 0xd3, 0xe1, 0xae, 0x41, 0x7d, 0xdd, 0x33, 0xdd, 0xc0, 0xf1, 0xea, 0x1c, 0xc3, 0x6b, - 0x82, 0x51, 0x8f, 0x18, 0xb5, 0x63, 0x58, 0x7f, 0x60, 0x5a, 0xb4, 0x15, 0x13, 0xfb, 0x34, 0xc0, - 0xf7, 0x20, 0x37, 0x34, 0x2d, 0x2a, 0x4b, 0xdb, 0xd9, 0x9d, 0xf2, 0xad, 0x37, 0xeb, 0x73, 0x42, - 0xf5, 0xb4, 0x44, 0x8f, 0xc1, 0x2a, 0x97, 0xa8, 0xfd, 0x2b, 0x07, 0x1b, 0x4b, 0x7a, 0x31, 0x86, - 0x9c, 0x4d, 0x26, 0x4c, 0xa3, 0xb4, 0x53, 0x52, 0xf9, 0x7f, 0x2c, 0xc3, 0x8a, 0x4b, 0xf4, 0x47, - 0x64, 0x44, 0xe5, 0x0c, 0x87, 0xa3, 0x26, 0x7e, 0x1d, 0xc0, 0xa0, 0x2e, 0xb5, 0x0d, 0x6a, 0xeb, - 0x67, 0x72, 0x76, 0x3b, 0xbb, 0x53, 0x52, 0x13, 0x08, 0x7e, 0x07, 0xd6, 0xdd, 0xe9, 0xa9, 0x65, - 0xea, 0x5a, 0x82, 0x06, 0xdb, 0xd9, 0x9d, 0xbc, 0x8a, 0x44, 0x47, 0x6b, 0x46, 0xbe, 0x0e, 0x6b, - 0x4f, 0x28, 0x79, 0x94, 0xa4, 0x96, 0x39, 0xb5, 0xca, 0xe0, 0x04, 0xb1, 0x09, 0x95, 0x09, 0xf5, - 0x7d, 0x32, 0xa2, 0x5a, 0x70, 0xe6, 0x52, 0x39, 0xc7, 0x67, 0xbf, 0xbd, 0x30, 0xfb, 0xf9, 0x99, - 0x97, 0x43, 0xa9, 0xc1, 0x99, 0x4b, 0x71, 0x03, 0x4a, 0xd4, 0x9e, 0x4e, 0x84, 0x86, 0xfc, 0x39, - 0xfe, 0x53, 0xec, 0xe9, 0x64, 0x5e, 0x4b, 0x91, 0x89, 0x85, 0x2a, 0x56, 0x7c, 0xea, 0x3d, 0x36, - 0x75, 0x2a, 0x17, 0xb8, 0x82, 0xeb, 0x0b, 0x0a, 0xfa, 0xa2, 0x7f, 0x5e, 0x47, 0x24, 0x87, 0x9b, - 0x50, 0xa2, 0x4f, 0x03, 0x6a, 0xfb, 0xa6, 0x63, 0xcb, 0x2b, 0x5c, 0xc9, 0x5b, 0x4b, 0x56, 0x91, - 0x5a, 0xc6, 0xbc, 0x8a, 0x99, 0x1c, 0xbe, 0x0b, 0x2b, 0x8e, 0x1b, 0x98, 0x8e, 0xed, 0xcb, 0xc5, - 0x6d, 0x69, 0xa7, 0x7c, 0xeb, 0xd5, 0xa5, 0x81, 0xd0, 0x15, 0x1c, 0x35, 0x22, 0xe3, 0x36, 0x20, - 0xdf, 0x99, 0x7a, 0x3a, 0xd5, 0x74, 0xc7, 0xa0, 0x9a, 0x69, 0x0f, 0x1d, 0xb9, 0xc4, 0x15, 0x5c, - 0x5d, 0x9c, 0x08, 0x27, 0x36, 0x1d, 0x83, 0xb6, 0xed, 0xa1, 0xa3, 0x56, 0xfd, 0x54, 0x1b, 0x5f, - 0x82, 0x82, 0x7f, 0x66, 0x07, 0xe4, 0xa9, 0x5c, 0xe1, 0x11, 0x12, 0xb6, 0x6a, 0x5f, 0x17, 0x60, - 0xed, 0x22, 0x21, 0x76, 0x1f, 0xf2, 0x43, 0x36, 0x4b, 0x39, 0xf3, 0x5d, 0x7c, 0x20, 0x64, 0xd2, - 0x4e, 0x2c, 0x7c, 0x4f, 0x27, 0x36, 0xa0, 0x6c, 0x53, 0x3f, 0xa0, 0x86, 0x88, 0x88, 0xec, 0x05, - 0x63, 0x0a, 0x84, 0xd0, 0x62, 0x48, 0xe5, 0xbe, 0x57, 0x48, 0x7d, 0x0a, 0x6b, 0xb1, 0x49, 0x9a, - 0x47, 0xec, 0x51, 0x14, 0x9b, 0xbb, 0xcf, 0xb3, 0xa4, 0xae, 0x44, 0x72, 0x2a, 0x13, 0x53, 0xab, - 0x34, 0xd5, 0xc6, 0x2d, 0x00, 0xc7, 0xa6, 0xce, 0x50, 0x33, 0xa8, 0x6e, 0xc9, 0xc5, 0x73, 0xbc, - 0xd4, 0x65, 0x94, 0x05, 0x2f, 0x39, 0x02, 0xd5, 0x2d, 0xfc, 0xe1, 0x2c, 0xd4, 0x56, 0xce, 0x89, - 0x94, 0x63, 0xb1, 0xc9, 0x16, 0xa2, 0xed, 0x04, 0xaa, 0x1e, 0x65, 0x71, 0x4f, 0x8d, 0x70, 0x66, - 0x25, 0x6e, 0x44, 0xfd, 0xb9, 0x33, 0x53, 0x43, 0x31, 0x31, 0xb1, 0x55, 0x2f, 0xd9, 0xc4, 0x6f, - 0x40, 0x0c, 0x68, 0x3c, 0xac, 0x80, 0x67, 0xa1, 0x4a, 0x04, 0x76, 0xc8, 0x84, 0x6e, 0x7d, 0x09, - 0xd5, 0xb4, 0x7b, 0xf0, 0x26, 0xe4, 0xfd, 0x80, 0x78, 0x01, 0x8f, 0xc2, 0xbc, 0x2a, 0x1a, 0x18, - 0x41, 0x96, 0xda, 0x06, 0xcf, 0x72, 0x79, 0x95, 0xfd, 0xc5, 0x3f, 0x9d, 0x4d, 0x38, 0xcb, 0x27, - 0xfc, 0xf6, 0xe2, 0x8a, 0xa6, 0x34, 0xcf, 0xcf, 0x7b, 0xeb, 0x03, 0x58, 0x4d, 0x4d, 0xe0, 0xa2, - 0x43, 0xd7, 0x7e, 0x05, 0x2f, 0x2f, 0x55, 0x8d, 0x3f, 0x85, 0xcd, 0xa9, 0x6d, 0xda, 0x01, 0xf5, - 0x5c, 0x8f, 0xb2, 0x88, 0x15, 0x43, 0xc9, 0xff, 0x5e, 0x39, 0x27, 0xe6, 0x4e, 0x92, 0x6c, 0xa1, - 0x45, 0xdd, 0x98, 0x2e, 0x82, 0x37, 0x4b, 0xc5, 0xff, 0xac, 0xa0, 0x67, 0xcf, 0x9e, 0x3d, 0xcb, - 0xd4, 0x7e, 0x57, 0x80, 0xcd, 0x65, 0x7b, 0x66, 0xe9, 0xf6, 0xbd, 0x04, 0x05, 0x7b, 0x3a, 0x39, - 0xa5, 0x1e, 0x77, 0x52, 0x5e, 0x0d, 0x5b, 0xb8, 0x01, 0x79, 0x8b, 0x9c, 0x52, 0x4b, 0xce, 0x6d, - 0x4b, 0x3b, 0xd5, 0x5b, 0xef, 0x5c, 0x68, 0x57, 0xd6, 0x8f, 0x98, 0x88, 0x2a, 0x24, 0xf1, 0x47, - 0x90, 0x0b, 0x53, 0x34, 0xd3, 0x70, 0xf3, 0x62, 0x1a, 0xd8, 0x5e, 0x52, 0xb9, 0x1c, 0x7e, 0x05, - 0x4a, 0xec, 0x57, 0xc4, 0x46, 0x81, 0xdb, 0x5c, 0x64, 0x00, 0x8b, 0x0b, 0xbc, 0x05, 0x45, 0xbe, - 0x4d, 0x0c, 0x1a, 0x1d, 0x6d, 0x71, 0x9b, 0x05, 0x96, 0x41, 0x87, 0x64, 0x6a, 0x05, 0xda, 0x63, - 0x62, 0x4d, 0x29, 0x0f, 0xf8, 0x92, 0x5a, 0x09, 0xc1, 0x5f, 0x30, 0x0c, 0x5f, 0x85, 0xb2, 0xd8, - 0x55, 0xa6, 0x6d, 0xd0, 0xa7, 0x3c, 0x7b, 0xe6, 0x55, 0xb1, 0xd1, 0xda, 0x0c, 0x61, 0xc3, 0x3f, - 0xf4, 0x1d, 0x3b, 0x0a, 0x4d, 0x3e, 0x04, 0x03, 0xf8, 0xf0, 0x1f, 0xcc, 0x27, 0xee, 0xd7, 0x96, - 0x4f, 0x6f, 0x3e, 0xa6, 0x6a, 0x7f, 0xc9, 0x40, 0x8e, 0xe7, 0x8b, 0x35, 0x28, 0x0f, 0x3e, 0xeb, - 0x29, 0x5a, 0xab, 0x7b, 0xb2, 0x7f, 0xa4, 0x20, 0x09, 0x57, 0x01, 0x38, 0xf0, 0xe0, 0xa8, 0xdb, - 0x18, 0xa0, 0x4c, 0xdc, 0x6e, 0x77, 0x06, 0x77, 0x6f, 0xa3, 0x6c, 0x2c, 0x70, 0x22, 0x80, 0x5c, - 0x92, 0xf0, 0xfe, 0x2d, 0x94, 0xc7, 0x08, 0x2a, 0x42, 0x41, 0xfb, 0x53, 0xa5, 0x75, 0xf7, 0x36, - 0x2a, 0xa4, 0x91, 0xf7, 0x6f, 0xa1, 0x15, 0xbc, 0x0a, 0x25, 0x8e, 0xec, 0x77, 0xbb, 0x47, 0xa8, - 0x18, 0xeb, 0xec, 0x0f, 0xd4, 0x76, 0xe7, 0x00, 0x95, 0x62, 0x9d, 0x07, 0x6a, 0xf7, 0xa4, 0x87, - 0x20, 0xd6, 0x70, 0xac, 0xf4, 0xfb, 0x8d, 0x03, 0x05, 0x95, 0x63, 0xc6, 0xfe, 0x67, 0x03, 0xa5, - 0x8f, 0x2a, 0x29, 0xb3, 0xde, 0xbf, 0x85, 0x56, 0xe3, 0x21, 0x94, 0xce, 0xc9, 0x31, 0xaa, 0xe2, - 0x75, 0x58, 0x15, 0x43, 0x44, 0x46, 0xac, 0xcd, 0x41, 0x77, 0x6f, 0x23, 0x34, 0x33, 0x44, 0x68, - 0x59, 0x4f, 0x01, 0x77, 0x6f, 0x23, 0x5c, 0x6b, 0x42, 0x9e, 0x47, 0x17, 0xc6, 0x50, 0x3d, 0x6a, - 0xec, 0x2b, 0x47, 0x5a, 0xb7, 0x37, 0x68, 0x77, 0x3b, 0x8d, 0x23, 0x24, 0xcd, 0x30, 0x55, 0xf9, - 0xf9, 0x49, 0x5b, 0x55, 0x5a, 0x28, 0x93, 0xc4, 0x7a, 0x4a, 0x63, 0xa0, 0xb4, 0x50, 0xb6, 0xa6, - 0xc3, 0xe6, 0xb2, 0x3c, 0xb9, 0x74, 0x67, 0x24, 0x96, 0x38, 0x73, 0xce, 0x12, 0x73, 0x5d, 0x0b, - 0x4b, 0xfc, 0xcf, 0x0c, 0x6c, 0x2c, 0x39, 0x2b, 0x96, 0x0e, 0xf2, 0x13, 0xc8, 0x8b, 0x10, 0x15, - 0xa7, 0xe7, 0x8d, 0xa5, 0x87, 0x0e, 0x0f, 0xd8, 0x85, 0x13, 0x94, 0xcb, 0x25, 0x2b, 0x88, 0xec, - 0x39, 0x15, 0x04, 0x53, 0xb1, 0x90, 0xd3, 0x7f, 0xb9, 0x90, 0xd3, 0xc5, 0xb1, 0x77, 0xf7, 0x22, - 0xc7, 0x1e, 0xc7, 0xbe, 0x5b, 0x6e, 0xcf, 0x2f, 0xc9, 0xed, 0xf7, 0x61, 0x7d, 0x41, 0xd1, 0x85, - 0x73, 0xec, 0xaf, 0x25, 0x90, 0xcf, 0x73, 0xce, 0x73, 0x32, 0x5d, 0x26, 0x95, 0xe9, 0xee, 0xcf, - 0x7b, 0xf0, 0xda, 0xf9, 0x8b, 0xb0, 0xb0, 0xd6, 0x5f, 0x49, 0x70, 0x69, 0x79, 0xa5, 0xb8, 0xd4, - 0x86, 0x8f, 0xa0, 0x30, 0xa1, 0xc1, 0xd8, 0x89, 0xaa, 0xa5, 0xb7, 0x97, 0x9c, 0xc1, 0xac, 0x7b, - 0x7e, 0xb1, 0x43, 0xa9, 0xe4, 0x21, 0x9e, 0x3d, 0xaf, 0xdc, 0x13, 0xd6, 0x2c, 0x58, 0xfa, 0x9b, - 0x0c, 0xbc, 0xbc, 0x54, 0xf9, 0x52, 0x43, 0x5f, 0x03, 0x30, 0x6d, 0x77, 0x1a, 0x88, 0x8a, 0x48, - 0x24, 0xd8, 0x12, 0x47, 0x78, 0xf2, 0x62, 0xc9, 0x73, 0x1a, 0xc4, 0xfd, 0x59, 0xde, 0x0f, 0x02, - 0xe2, 0x84, 0x7b, 0x33, 0x43, 0x73, 0xdc, 0xd0, 0xd7, 0xcf, 0x99, 0xe9, 0x42, 0x60, 0xbe, 0x07, - 0x48, 0xb7, 0x4c, 0x6a, 0x07, 0x9a, 0x1f, 0x78, 0x94, 0x4c, 0x4c, 0x7b, 0xc4, 0x4f, 0x90, 0xe2, - 0x5e, 0x7e, 0x48, 0x2c, 0x9f, 0xaa, 0x6b, 0xa2, 0xbb, 0x1f, 0xf5, 0x32, 0x09, 0x1e, 0x40, 0x5e, - 0x42, 0xa2, 0x90, 0x92, 0x10, 0xdd, 0xb1, 0x44, 0xed, 0xeb, 0x22, 0x94, 0x13, 0x75, 0x35, 0xbe, - 0x06, 0x95, 0x87, 0xe4, 0x31, 0xd1, 0xa2, 0xbb, 0x92, 0xf0, 0x44, 0x99, 0x61, 0xbd, 0xf0, 0xbe, - 0xf4, 0x1e, 0x6c, 0x72, 0x8a, 0x33, 0x0d, 0xa8, 0xa7, 0xe9, 0x16, 0xf1, 0x7d, 0xee, 0xb4, 0x22, - 0xa7, 0x62, 0xd6, 0xd7, 0x65, 0x5d, 0xcd, 0xa8, 0x07, 0xdf, 0x81, 0x0d, 0x2e, 0x31, 0x99, 0x5a, - 0x81, 0xe9, 0x5a, 0x54, 0x63, 0xb7, 0x37, 0x9f, 0x9f, 0x24, 0xb1, 0x65, 0xeb, 0x8c, 0x71, 0x1c, - 0x12, 0x98, 0x45, 0x3e, 0x6e, 0xc1, 0x6b, 0x5c, 0x6c, 0x44, 0x6d, 0xea, 0x91, 0x80, 0x6a, 0xf4, - 0x8b, 0x29, 0xb1, 0x7c, 0x8d, 0xd8, 0x86, 0x36, 0x26, 0xfe, 0x58, 0xde, 0x64, 0x0a, 0xf6, 0x33, - 0xb2, 0xa4, 0x5e, 0x61, 0xc4, 0x83, 0x90, 0xa7, 0x70, 0x5a, 0xc3, 0x36, 0x3e, 0x26, 0xfe, 0x18, - 0xef, 0xc1, 0x25, 0xae, 0xc5, 0x0f, 0x3c, 0xd3, 0x1e, 0x69, 0xfa, 0x98, 0xea, 0x8f, 0xb4, 0x69, - 0x30, 0xbc, 0x27, 0xbf, 0x92, 0x1c, 0x9f, 0x5b, 0xd8, 0xe7, 0x9c, 0x26, 0xa3, 0x9c, 0x04, 0xc3, - 0x7b, 0xb8, 0x0f, 0x15, 0xb6, 0x18, 0x13, 0xf3, 0x4b, 0xaa, 0x0d, 0x1d, 0x8f, 0x1f, 0x8d, 0xd5, - 0x25, 0xa9, 0x29, 0xe1, 0xc1, 0x7a, 0x37, 0x14, 0x38, 0x76, 0x0c, 0xba, 0x97, 0xef, 0xf7, 0x14, - 0xa5, 0xa5, 0x96, 0x23, 0x2d, 0x0f, 0x1c, 0x8f, 0x05, 0xd4, 0xc8, 0x89, 0x1d, 0x5c, 0x16, 0x01, - 0x35, 0x72, 0x22, 0xf7, 0xde, 0x81, 0x0d, 0x5d, 0x17, 0x73, 0x36, 0x75, 0x2d, 0xbc, 0x63, 0xf9, - 0x32, 0x4a, 0x39, 0x4b, 0xd7, 0x0f, 0x04, 0x21, 0x8c, 0x71, 0x1f, 0x7f, 0x08, 0x2f, 0xcf, 0x9c, - 0x95, 0x14, 0x5c, 0x5f, 0x98, 0xe5, 0xbc, 0xe8, 0x1d, 0xd8, 0x70, 0xcf, 0x16, 0x05, 0x71, 0x6a, - 0x44, 0xf7, 0x6c, 0x5e, 0xec, 0x03, 0xd8, 0x74, 0xc7, 0xee, 0xa2, 0xdc, 0xcd, 0xa4, 0x1c, 0x76, - 0xc7, 0xee, 0xbc, 0xe0, 0x5b, 0xfc, 0xc2, 0xed, 0x51, 0x9d, 0x04, 0xd4, 0x90, 0x2f, 0x27, 0xe9, - 0x89, 0x0e, 0xbc, 0x0b, 0x48, 0xd7, 0x35, 0x6a, 0x93, 0x53, 0x8b, 0x6a, 0xc4, 0xa3, 0x36, 0xf1, - 0xe5, 0xab, 0x49, 0x72, 0x55, 0xd7, 0x15, 0xde, 0xdb, 0xe0, 0x9d, 0xf8, 0x26, 0xac, 0x3b, 0xa7, - 0x0f, 0x75, 0x11, 0x92, 0x9a, 0xeb, 0xd1, 0xa1, 0xf9, 0x54, 0x7e, 0x93, 0xfb, 0x77, 0x8d, 0x75, - 0xf0, 0x80, 0xec, 0x71, 0x18, 0xdf, 0x00, 0xa4, 0xfb, 0x63, 0xe2, 0xb9, 0x3c, 0x27, 0xfb, 0x2e, - 0xd1, 0xa9, 0xfc, 0x96, 0xa0, 0x0a, 0xbc, 0x13, 0xc1, 0x6c, 0x4b, 0xf8, 0x4f, 0xcc, 0x61, 0x10, - 0x69, 0xbc, 0x2e, 0xb6, 0x04, 0xc7, 0x42, 0x6d, 0x3b, 0x80, 0x98, 0x2b, 0x52, 0x03, 0xef, 0x70, - 0x5a, 0xd5, 0x1d, 0xbb, 0xc9, 0x71, 0xdf, 0x80, 0x55, 0xc6, 0x9c, 0x0d, 0x7a, 0x43, 0x14, 0x64, - 0xee, 0x38, 0x31, 0xe2, 0x0f, 0x56, 0x1b, 0xd7, 0xf6, 0xa0, 0x92, 0x8c, 0x4f, 0x5c, 0x02, 0x11, - 0xa1, 0x48, 0x62, 0xc5, 0x4a, 0xb3, 0xdb, 0x62, 0x65, 0xc6, 0xe7, 0x0a, 0xca, 0xb0, 0x72, 0xe7, - 0xa8, 0x3d, 0x50, 0x34, 0xf5, 0xa4, 0x33, 0x68, 0x1f, 0x2b, 0x28, 0x9b, 0xa8, 0xab, 0x0f, 0x73, - 0xc5, 0xb7, 0xd1, 0xf5, 0xda, 0x37, 0x19, 0xa8, 0xa6, 0x2f, 0x4a, 0xf8, 0xff, 0xe1, 0x72, 0xf4, - 0xaa, 0xe1, 0xd3, 0x40, 0x7b, 0x62, 0x7a, 0x7c, 0xe3, 0x4c, 0x88, 0x38, 0xc4, 0xe2, 0xa5, 0xdb, - 0x0c, 0x59, 0x7d, 0x1a, 0x7c, 0x62, 0x7a, 0x6c, 0x5b, 0x4c, 0x48, 0x80, 0x8f, 0xe0, 0xaa, 0xed, - 0x68, 0x7e, 0x40, 0x6c, 0x83, 0x78, 0x86, 0x36, 0x7b, 0x4f, 0xd2, 0x88, 0xae, 0x53, 0xdf, 0x77, - 0xc4, 0x81, 0x15, 0x6b, 0x79, 0xd5, 0x76, 0xfa, 0x21, 0x79, 0x96, 0xc9, 0x1b, 0x21, 0x75, 0x2e, - 0xcc, 0xb2, 0xe7, 0x85, 0xd9, 0x2b, 0x50, 0x9a, 0x10, 0x57, 0xa3, 0x76, 0xe0, 0x9d, 0xf1, 0xf2, - 0xb8, 0xa8, 0x16, 0x27, 0xc4, 0x55, 0x58, 0xfb, 0x85, 0xdc, 0x52, 0x0e, 0x73, 0xc5, 0x22, 0x2a, - 0x1d, 0xe6, 0x8a, 0x25, 0x04, 0xb5, 0x7f, 0x64, 0xa1, 0x92, 0x2c, 0x97, 0xd9, 0xed, 0x43, 0xe7, - 0x27, 0x8b, 0xc4, 0x73, 0xcf, 0x1b, 0xdf, 0x5a, 0x5c, 0xd7, 0x9b, 0xec, 0xc8, 0xd9, 0x2b, 0x88, - 0x22, 0x56, 0x15, 0x92, 0xec, 0xb8, 0x67, 0xd9, 0x86, 0x8a, 0xa2, 0xa1, 0xa8, 0x86, 0x2d, 0x7c, - 0x00, 0x85, 0x87, 0x3e, 0xd7, 0x5d, 0xe0, 0xba, 0xdf, 0xfc, 0x76, 0xdd, 0x87, 0x7d, 0xae, 0xbc, - 0x74, 0xd8, 0xd7, 0x3a, 0x5d, 0xf5, 0xb8, 0x71, 0xa4, 0x86, 0xe2, 0xf8, 0x0a, 0xe4, 0x2c, 0xf2, - 0xe5, 0x59, 0xfa, 0x70, 0xe2, 0xd0, 0x45, 0x17, 0xe1, 0x0a, 0xe4, 0x9e, 0x50, 0xf2, 0x28, 0x7d, - 0x24, 0x70, 0xe8, 0x07, 0xdc, 0x0c, 0xbb, 0x90, 0xe7, 0xfe, 0xc2, 0x00, 0xa1, 0xc7, 0xd0, 0x4b, - 0xb8, 0x08, 0xb9, 0x66, 0x57, 0x65, 0x1b, 0x02, 0x41, 0x45, 0xa0, 0x5a, 0xaf, 0xad, 0x34, 0x15, - 0x94, 0xa9, 0xdd, 0x81, 0x82, 0x70, 0x02, 0xdb, 0x2c, 0xb1, 0x1b, 0xd0, 0x4b, 0x61, 0x33, 0xd4, - 0x21, 0x45, 0xbd, 0x27, 0xc7, 0xfb, 0x8a, 0x8a, 0x32, 0xe9, 0xa5, 0xce, 0xa1, 0x7c, 0xcd, 0x87, - 0x4a, 0xb2, 0x5e, 0x7e, 0x31, 0x77, 0xe1, 0xbf, 0x4a, 0x50, 0x4e, 0xd4, 0xbf, 0xac, 0x70, 0x21, - 0x96, 0xe5, 0x3c, 0xd1, 0x88, 0x65, 0x12, 0x3f, 0x0c, 0x0d, 0xe0, 0x50, 0x83, 0x21, 0x17, 0x5d, - 0xba, 0x17, 0xb4, 0x45, 0xf2, 0xa8, 0x50, 0xfb, 0xa3, 0x04, 0x68, 0xbe, 0x00, 0x9d, 0x33, 0x53, - 0xfa, 0x31, 0xcd, 0xac, 0xfd, 0x41, 0x82, 0x6a, 0xba, 0xea, 0x9c, 0x33, 0xef, 0xda, 0x8f, 0x6a, - 0xde, 0xdf, 0x33, 0xb0, 0x9a, 0xaa, 0x35, 0x2f, 0x6a, 0xdd, 0x17, 0xb0, 0x6e, 0x1a, 0x74, 0xe2, - 0x3a, 0x01, 0xb5, 0xf5, 0x33, 0xcd, 0xa2, 0x8f, 0xa9, 0x25, 0xd7, 0x78, 0xd2, 0xd8, 0xfd, 0xf6, - 0x6a, 0xb6, 0xde, 0x9e, 0xc9, 0x1d, 0x31, 0xb1, 0xbd, 0x8d, 0x76, 0x4b, 0x39, 0xee, 0x75, 0x07, - 0x4a, 0xa7, 0xf9, 0x99, 0x76, 0xd2, 0xf9, 0x59, 0xa7, 0xfb, 0x49, 0x47, 0x45, 0xe6, 0x1c, 0xed, - 0x07, 0xdc, 0xf6, 0x3d, 0x40, 0xf3, 0x46, 0xe1, 0xcb, 0xb0, 0xcc, 0x2c, 0xf4, 0x12, 0xde, 0x80, - 0xb5, 0x4e, 0x57, 0xeb, 0xb7, 0x5b, 0x8a, 0xa6, 0x3c, 0x78, 0xa0, 0x34, 0x07, 0x7d, 0xf1, 0x3e, - 0x11, 0xb3, 0x07, 0xa9, 0x0d, 0x5e, 0xfb, 0x7d, 0x16, 0x36, 0x96, 0x58, 0x82, 0x1b, 0xe1, 0xcd, - 0x42, 0x5c, 0x76, 0xde, 0xbd, 0x88, 0xf5, 0x75, 0x56, 0x10, 0xf4, 0x88, 0x17, 0x84, 0x17, 0x91, - 0x1b, 0xc0, 0xbc, 0x64, 0x07, 0xe6, 0xd0, 0xa4, 0x5e, 0xf8, 0x9c, 0x23, 0xae, 0x1b, 0x6b, 0x33, - 0x5c, 0xbc, 0xe8, 0xfc, 0x1f, 0x60, 0xd7, 0xf1, 0xcd, 0xc0, 0x7c, 0x4c, 0x35, 0xd3, 0x8e, 0xde, - 0x7e, 0xd8, 0xf5, 0x23, 0xa7, 0xa2, 0xa8, 0xa7, 0x6d, 0x07, 0x31, 0xdb, 0xa6, 0x23, 0x32, 0xc7, - 0x66, 0xc9, 0x3c, 0xab, 0xa2, 0xa8, 0x27, 0x66, 0x5f, 0x83, 0x8a, 0xe1, 0x4c, 0x59, 0x4d, 0x26, - 0x78, 0xec, 0xec, 0x90, 0xd4, 0xb2, 0xc0, 0x62, 0x4a, 0x58, 0x6d, 0xcf, 0x1e, 0x9d, 0x2a, 0x6a, - 0x59, 0x60, 0x82, 0x72, 0x1d, 0xd6, 0xc8, 0x68, 0xe4, 0x31, 0xe5, 0x91, 0x22, 0x71, 0x7f, 0xa8, - 0xc6, 0x30, 0x27, 0x6e, 0x1d, 0x42, 0x31, 0xf2, 0x03, 0x3b, 0xaa, 0x99, 0x27, 0x34, 0x57, 0x5c, - 0x8a, 0x33, 0x3b, 0x25, 0xb5, 0x68, 0x47, 0x9d, 0xd7, 0xa0, 0x62, 0xfa, 0xda, 0xec, 0x0d, 0x3d, - 0xb3, 0x9d, 0xd9, 0x29, 0xaa, 0x65, 0xd3, 0x8f, 0xdf, 0x1f, 0x6b, 0x5f, 0x65, 0xa0, 0x9a, 0xfe, - 0x06, 0x80, 0x5b, 0x50, 0xb4, 0x1c, 0x9d, 0xf0, 0xd0, 0x12, 0x1f, 0xa0, 0x76, 0x9e, 0xf3, 0xd9, - 0xa0, 0x7e, 0x14, 0xf2, 0xd5, 0x58, 0x72, 0xeb, 0x6f, 0x12, 0x14, 0x23, 0x18, 0x5f, 0x82, 0x9c, - 0x4b, 0x82, 0x31, 0x57, 0x97, 0xdf, 0xcf, 0x20, 0x49, 0xe5, 0x6d, 0x86, 0xfb, 0x2e, 0xb1, 0x79, - 0x08, 0x84, 0x38, 0x6b, 0xb3, 0x75, 0xb5, 0x28, 0x31, 0xf8, 0xe5, 0xc4, 0x99, 0x4c, 0xa8, 0x1d, - 0xf8, 0xd1, 0xba, 0x86, 0x78, 0x33, 0x84, 0xf1, 0x3b, 0xb0, 0x1e, 0x78, 0xc4, 0xb4, 0x52, 0xdc, - 0x1c, 0xe7, 0xa2, 0xa8, 0x23, 0x26, 0xef, 0xc1, 0x95, 0x48, 0xaf, 0x41, 0x03, 0xa2, 0x8f, 0xa9, - 0x31, 0x13, 0x2a, 0xf0, 0x47, 0x88, 0xcb, 0x21, 0xa1, 0x15, 0xf6, 0x47, 0xb2, 0xb5, 0x6f, 0x24, - 0x58, 0x8f, 0xae, 0x53, 0x46, 0xec, 0xac, 0x63, 0x00, 0x62, 0xdb, 0x4e, 0x90, 0x74, 0xd7, 0x62, - 0x28, 0x2f, 0xc8, 0xd5, 0x1b, 0xb1, 0x90, 0x9a, 0x50, 0xb0, 0x35, 0x01, 0x98, 0xf5, 0x9c, 0xeb, - 0xb6, 0xab, 0x50, 0x0e, 0x3f, 0xf0, 0xf0, 0xaf, 0x84, 0xe2, 0x02, 0x0e, 0x02, 0x62, 0xf7, 0x2e, - 0xbc, 0x09, 0xf9, 0x53, 0x3a, 0x32, 0xed, 0xf0, 0xd9, 0x56, 0x34, 0xa2, 0x67, 0x92, 0x5c, 0xfc, - 0x4c, 0xb2, 0xff, 0x5b, 0x09, 0x36, 0x74, 0x67, 0x32, 0x6f, 0xef, 0x3e, 0x9a, 0x7b, 0x05, 0xf0, - 0x3f, 0x96, 0x3e, 0xff, 0x68, 0x64, 0x06, 0xe3, 0xe9, 0x69, 0x5d, 0x77, 0x26, 0xbb, 0x23, 0xc7, - 0x22, 0xf6, 0x68, 0xf6, 0x99, 0x93, 0xff, 0xd1, 0xdf, 0x1d, 0x51, 0xfb, 0xdd, 0x91, 0x93, 0xf8, - 0xe8, 0x79, 0x7f, 0xf6, 0xf7, 0xbf, 0x92, 0xf4, 0xa7, 0x4c, 0xf6, 0xa0, 0xb7, 0xff, 0xe7, 0xcc, - 0xd6, 0x81, 0x18, 0xae, 0x17, 0xb9, 0x47, 0xa5, 0x43, 0x8b, 0xea, 0x6c, 0xca, 0xff, 0x0b, 0x00, - 0x00, 0xff, 0xff, 0x1a, 0x28, 0x25, 0x79, 0x42, 0x1d, 0x00, 0x00, -} diff --git a/vendor/github.com/huin/goupnp/LICENSE b/vendor/github.com/huin/goupnp/LICENSE deleted file mode 100644 index c5a45bcb..00000000 --- a/vendor/github.com/huin/goupnp/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -Copyright (c) 2013, John Beisley -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. - -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. diff --git a/vendor/github.com/huin/goupnp/dcps/internetgateway1/internetgateway1.go b/vendor/github.com/huin/goupnp/dcps/internetgateway1/internetgateway1.go deleted file mode 100644 index e9335047..00000000 --- a/vendor/github.com/huin/goupnp/dcps/internetgateway1/internetgateway1.go +++ /dev/null @@ -1,3651 +0,0 @@ -// Client for UPnP Device Control Protocol Internet Gateway Device v1. -// -// This DCP is documented in detail at: http://upnp.org/specs/gw/UPnP-gw-InternetGatewayDevice-v1-Device.pdf -// -// Typically, use one of the New* functions to create clients for services. -package internetgateway1 - -// *********************************************************** -// GENERATED FILE - DO NOT EDIT BY HAND. See README.md -// *********************************************************** - -import ( - "net/url" - "time" - - "github.com/huin/goupnp" - "github.com/huin/goupnp/soap" -) - -// Hack to avoid Go complaining if time isn't used. -var _ time.Time - -// Device URNs: -const ( - URN_LANDevice_1 = "urn:schemas-upnp-org:device:LANDevice:1" - URN_WANConnectionDevice_1 = "urn:schemas-upnp-org:device:WANConnectionDevice:1" - URN_WANDevice_1 = "urn:schemas-upnp-org:device:WANDevice:1" -) - -// Service URNs: -const ( - URN_LANHostConfigManagement_1 = "urn:schemas-upnp-org:service:LANHostConfigManagement:1" - URN_Layer3Forwarding_1 = "urn:schemas-upnp-org:service:Layer3Forwarding:1" - URN_WANCableLinkConfig_1 = "urn:schemas-upnp-org:service:WANCableLinkConfig:1" - URN_WANCommonInterfaceConfig_1 = "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1" - URN_WANDSLLinkConfig_1 = "urn:schemas-upnp-org:service:WANDSLLinkConfig:1" - URN_WANEthernetLinkConfig_1 = "urn:schemas-upnp-org:service:WANEthernetLinkConfig:1" - URN_WANIPConnection_1 = "urn:schemas-upnp-org:service:WANIPConnection:1" - URN_WANPOTSLinkConfig_1 = "urn:schemas-upnp-org:service:WANPOTSLinkConfig:1" - URN_WANPPPConnection_1 = "urn:schemas-upnp-org:service:WANPPPConnection:1" -) - -// LANHostConfigManagement1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:LANHostConfigManagement:1". See -// goupnp.ServiceClient, which contains RootDevice and Service attributes which -// are provided for informational value. -type LANHostConfigManagement1 struct { - goupnp.ServiceClient -} - -// NewLANHostConfigManagement1Clients discovers instances of the service on the network, -// and returns clients to any that are found. errors will contain an error for -// any devices that replied but which could not be queried, and err will be set -// if the discovery process failed outright. -// -// This is a typical entry calling point into this package. -func NewLANHostConfigManagement1Clients() (clients []*LANHostConfigManagement1, errors []error, err error) { - var genericClients []goupnp.ServiceClient - if genericClients, errors, err = goupnp.NewServiceClients(URN_LANHostConfigManagement_1); err != nil { - return - } - clients = newLANHostConfigManagement1ClientsFromGenericClients(genericClients) - return -} - -// NewLANHostConfigManagement1ClientsByURL discovers instances of the service at the given -// URL, and returns clients to any that are found. An error is returned if -// there was an error probing the service. -// -// This is a typical entry calling point into this package when reusing an -// previously discovered service URL. -func NewLANHostConfigManagement1ClientsByURL(loc *url.URL) ([]*LANHostConfigManagement1, error) { - genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_LANHostConfigManagement_1) - if err != nil { - return nil, err - } - return newLANHostConfigManagement1ClientsFromGenericClients(genericClients), nil -} - -// NewLANHostConfigManagement1ClientsFromRootDevice discovers instances of the service in -// a given root device, and returns clients to any that are found. An error is -// returned if there was not at least one instance of the service within the -// device. The location parameter is simply assigned to the Location attribute -// of the wrapped ServiceClient(s). -// -// This is a typical entry calling point into this package when reusing an -// previously discovered root device. -func NewLANHostConfigManagement1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*LANHostConfigManagement1, error) { - genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_LANHostConfigManagement_1) - if err != nil { - return nil, err - } - return newLANHostConfigManagement1ClientsFromGenericClients(genericClients), nil -} - -func newLANHostConfigManagement1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*LANHostConfigManagement1 { - clients := make([]*LANHostConfigManagement1, len(genericClients)) - for i := range genericClients { - clients[i] = &LANHostConfigManagement1{genericClients[i]} - } - return clients -} - -func (client *LANHostConfigManagement1) SetDHCPServerConfigurable(NewDHCPServerConfigurable bool) (err error) { - // Request structure. - request := &struct { - NewDHCPServerConfigurable string - }{} - // BEGIN Marshal arguments into request. - - if request.NewDHCPServerConfigurable, err = soap.MarshalBoolean(NewDHCPServerConfigurable); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetDHCPServerConfigurable", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) GetDHCPServerConfigurable() (NewDHCPServerConfigurable bool, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewDHCPServerConfigurable string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetDHCPServerConfigurable", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewDHCPServerConfigurable, err = soap.UnmarshalBoolean(response.NewDHCPServerConfigurable); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) SetDHCPRelay(NewDHCPRelay bool) (err error) { - // Request structure. - request := &struct { - NewDHCPRelay string - }{} - // BEGIN Marshal arguments into request. - - if request.NewDHCPRelay, err = soap.MarshalBoolean(NewDHCPRelay); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetDHCPRelay", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) GetDHCPRelay() (NewDHCPRelay bool, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewDHCPRelay string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetDHCPRelay", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewDHCPRelay, err = soap.UnmarshalBoolean(response.NewDHCPRelay); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) SetSubnetMask(NewSubnetMask string) (err error) { - // Request structure. - request := &struct { - NewSubnetMask string - }{} - // BEGIN Marshal arguments into request. - - if request.NewSubnetMask, err = soap.MarshalString(NewSubnetMask); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetSubnetMask", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) GetSubnetMask() (NewSubnetMask string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewSubnetMask string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetSubnetMask", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewSubnetMask, err = soap.UnmarshalString(response.NewSubnetMask); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) SetIPRouter(NewIPRouters string) (err error) { - // Request structure. - request := &struct { - NewIPRouters string - }{} - // BEGIN Marshal arguments into request. - - if request.NewIPRouters, err = soap.MarshalString(NewIPRouters); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetIPRouter", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) DeleteIPRouter(NewIPRouters string) (err error) { - // Request structure. - request := &struct { - NewIPRouters string - }{} - // BEGIN Marshal arguments into request. - - if request.NewIPRouters, err = soap.MarshalString(NewIPRouters); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "DeleteIPRouter", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) GetIPRoutersList() (NewIPRouters string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewIPRouters string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetIPRoutersList", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewIPRouters, err = soap.UnmarshalString(response.NewIPRouters); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) SetDomainName(NewDomainName string) (err error) { - // Request structure. - request := &struct { - NewDomainName string - }{} - // BEGIN Marshal arguments into request. - - if request.NewDomainName, err = soap.MarshalString(NewDomainName); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetDomainName", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) GetDomainName() (NewDomainName string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewDomainName string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetDomainName", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewDomainName, err = soap.UnmarshalString(response.NewDomainName); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) SetAddressRange(NewMinAddress string, NewMaxAddress string) (err error) { - // Request structure. - request := &struct { - NewMinAddress string - NewMaxAddress string - }{} - // BEGIN Marshal arguments into request. - - if request.NewMinAddress, err = soap.MarshalString(NewMinAddress); err != nil { - return - } - if request.NewMaxAddress, err = soap.MarshalString(NewMaxAddress); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetAddressRange", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) GetAddressRange() (NewMinAddress string, NewMaxAddress string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewMinAddress string - NewMaxAddress string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetAddressRange", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewMinAddress, err = soap.UnmarshalString(response.NewMinAddress); err != nil { - return - } - if NewMaxAddress, err = soap.UnmarshalString(response.NewMaxAddress); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) SetReservedAddress(NewReservedAddresses string) (err error) { - // Request structure. - request := &struct { - NewReservedAddresses string - }{} - // BEGIN Marshal arguments into request. - - if request.NewReservedAddresses, err = soap.MarshalString(NewReservedAddresses); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetReservedAddress", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) DeleteReservedAddress(NewReservedAddresses string) (err error) { - // Request structure. - request := &struct { - NewReservedAddresses string - }{} - // BEGIN Marshal arguments into request. - - if request.NewReservedAddresses, err = soap.MarshalString(NewReservedAddresses); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "DeleteReservedAddress", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) GetReservedAddresses() (NewReservedAddresses string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewReservedAddresses string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetReservedAddresses", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewReservedAddresses, err = soap.UnmarshalString(response.NewReservedAddresses); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) SetDNSServer(NewDNSServers string) (err error) { - // Request structure. - request := &struct { - NewDNSServers string - }{} - // BEGIN Marshal arguments into request. - - if request.NewDNSServers, err = soap.MarshalString(NewDNSServers); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetDNSServer", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) DeleteDNSServer(NewDNSServers string) (err error) { - // Request structure. - request := &struct { - NewDNSServers string - }{} - // BEGIN Marshal arguments into request. - - if request.NewDNSServers, err = soap.MarshalString(NewDNSServers); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "DeleteDNSServer", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) GetDNSServers() (NewDNSServers string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewDNSServers string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetDNSServers", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewDNSServers, err = soap.UnmarshalString(response.NewDNSServers); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// Layer3Forwarding1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:Layer3Forwarding:1". See -// goupnp.ServiceClient, which contains RootDevice and Service attributes which -// are provided for informational value. -type Layer3Forwarding1 struct { - goupnp.ServiceClient -} - -// NewLayer3Forwarding1Clients discovers instances of the service on the network, -// and returns clients to any that are found. errors will contain an error for -// any devices that replied but which could not be queried, and err will be set -// if the discovery process failed outright. -// -// This is a typical entry calling point into this package. -func NewLayer3Forwarding1Clients() (clients []*Layer3Forwarding1, errors []error, err error) { - var genericClients []goupnp.ServiceClient - if genericClients, errors, err = goupnp.NewServiceClients(URN_Layer3Forwarding_1); err != nil { - return - } - clients = newLayer3Forwarding1ClientsFromGenericClients(genericClients) - return -} - -// NewLayer3Forwarding1ClientsByURL discovers instances of the service at the given -// URL, and returns clients to any that are found. An error is returned if -// there was an error probing the service. -// -// This is a typical entry calling point into this package when reusing an -// previously discovered service URL. -func NewLayer3Forwarding1ClientsByURL(loc *url.URL) ([]*Layer3Forwarding1, error) { - genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_Layer3Forwarding_1) - if err != nil { - return nil, err - } - return newLayer3Forwarding1ClientsFromGenericClients(genericClients), nil -} - -// NewLayer3Forwarding1ClientsFromRootDevice discovers instances of the service in -// a given root device, and returns clients to any that are found. An error is -// returned if there was not at least one instance of the service within the -// device. The location parameter is simply assigned to the Location attribute -// of the wrapped ServiceClient(s). -// -// This is a typical entry calling point into this package when reusing an -// previously discovered root device. -func NewLayer3Forwarding1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*Layer3Forwarding1, error) { - genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_Layer3Forwarding_1) - if err != nil { - return nil, err - } - return newLayer3Forwarding1ClientsFromGenericClients(genericClients), nil -} - -func newLayer3Forwarding1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*Layer3Forwarding1 { - clients := make([]*Layer3Forwarding1, len(genericClients)) - for i := range genericClients { - clients[i] = &Layer3Forwarding1{genericClients[i]} - } - return clients -} - -func (client *Layer3Forwarding1) SetDefaultConnectionService(NewDefaultConnectionService string) (err error) { - // Request structure. - request := &struct { - NewDefaultConnectionService string - }{} - // BEGIN Marshal arguments into request. - - if request.NewDefaultConnectionService, err = soap.MarshalString(NewDefaultConnectionService); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_Layer3Forwarding_1, "SetDefaultConnectionService", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *Layer3Forwarding1) GetDefaultConnectionService() (NewDefaultConnectionService string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewDefaultConnectionService string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_Layer3Forwarding_1, "GetDefaultConnectionService", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewDefaultConnectionService, err = soap.UnmarshalString(response.NewDefaultConnectionService); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// WANCableLinkConfig1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANCableLinkConfig:1". See -// goupnp.ServiceClient, which contains RootDevice and Service attributes which -// are provided for informational value. -type WANCableLinkConfig1 struct { - goupnp.ServiceClient -} - -// NewWANCableLinkConfig1Clients discovers instances of the service on the network, -// and returns clients to any that are found. errors will contain an error for -// any devices that replied but which could not be queried, and err will be set -// if the discovery process failed outright. -// -// This is a typical entry calling point into this package. -func NewWANCableLinkConfig1Clients() (clients []*WANCableLinkConfig1, errors []error, err error) { - var genericClients []goupnp.ServiceClient - if genericClients, errors, err = goupnp.NewServiceClients(URN_WANCableLinkConfig_1); err != nil { - return - } - clients = newWANCableLinkConfig1ClientsFromGenericClients(genericClients) - return -} - -// NewWANCableLinkConfig1ClientsByURL discovers instances of the service at the given -// URL, and returns clients to any that are found. An error is returned if -// there was an error probing the service. -// -// This is a typical entry calling point into this package when reusing an -// previously discovered service URL. -func NewWANCableLinkConfig1ClientsByURL(loc *url.URL) ([]*WANCableLinkConfig1, error) { - genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANCableLinkConfig_1) - if err != nil { - return nil, err - } - return newWANCableLinkConfig1ClientsFromGenericClients(genericClients), nil -} - -// NewWANCableLinkConfig1ClientsFromRootDevice discovers instances of the service in -// a given root device, and returns clients to any that are found. An error is -// returned if there was not at least one instance of the service within the -// device. The location parameter is simply assigned to the Location attribute -// of the wrapped ServiceClient(s). -// -// This is a typical entry calling point into this package when reusing an -// previously discovered root device. -func NewWANCableLinkConfig1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANCableLinkConfig1, error) { - genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANCableLinkConfig_1) - if err != nil { - return nil, err - } - return newWANCableLinkConfig1ClientsFromGenericClients(genericClients), nil -} - -func newWANCableLinkConfig1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANCableLinkConfig1 { - clients := make([]*WANCableLinkConfig1, len(genericClients)) - for i := range genericClients { - clients[i] = &WANCableLinkConfig1{genericClients[i]} - } - return clients -} - -// -// Return values: -// -// * NewCableLinkConfigState: allowed values: notReady, dsSyncComplete, usParamAcquired, rangingComplete, ipComplete, todEstablished, paramTransferComplete, registrationComplete, operational, accessDenied -// -// * NewLinkType: allowed values: Ethernet -func (client *WANCableLinkConfig1) GetCableLinkConfigInfo() (NewCableLinkConfigState string, NewLinkType string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewCableLinkConfigState string - NewLinkType string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetCableLinkConfigInfo", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewCableLinkConfigState, err = soap.UnmarshalString(response.NewCableLinkConfigState); err != nil { - return - } - if NewLinkType, err = soap.UnmarshalString(response.NewLinkType); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANCableLinkConfig1) GetDownstreamFrequency() (NewDownstreamFrequency uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewDownstreamFrequency string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetDownstreamFrequency", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewDownstreamFrequency, err = soap.UnmarshalUi4(response.NewDownstreamFrequency); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// -// Return values: -// -// * NewDownstreamModulation: allowed values: 64QAM, 256QAM -func (client *WANCableLinkConfig1) GetDownstreamModulation() (NewDownstreamModulation string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewDownstreamModulation string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetDownstreamModulation", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewDownstreamModulation, err = soap.UnmarshalString(response.NewDownstreamModulation); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANCableLinkConfig1) GetUpstreamFrequency() (NewUpstreamFrequency uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewUpstreamFrequency string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetUpstreamFrequency", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewUpstreamFrequency, err = soap.UnmarshalUi4(response.NewUpstreamFrequency); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// -// Return values: -// -// * NewUpstreamModulation: allowed values: QPSK, 16QAM -func (client *WANCableLinkConfig1) GetUpstreamModulation() (NewUpstreamModulation string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewUpstreamModulation string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetUpstreamModulation", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewUpstreamModulation, err = soap.UnmarshalString(response.NewUpstreamModulation); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANCableLinkConfig1) GetUpstreamChannelID() (NewUpstreamChannelID uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewUpstreamChannelID string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetUpstreamChannelID", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewUpstreamChannelID, err = soap.UnmarshalUi4(response.NewUpstreamChannelID); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANCableLinkConfig1) GetUpstreamPowerLevel() (NewUpstreamPowerLevel uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewUpstreamPowerLevel string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetUpstreamPowerLevel", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewUpstreamPowerLevel, err = soap.UnmarshalUi4(response.NewUpstreamPowerLevel); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANCableLinkConfig1) GetBPIEncryptionEnabled() (NewBPIEncryptionEnabled bool, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewBPIEncryptionEnabled string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetBPIEncryptionEnabled", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewBPIEncryptionEnabled, err = soap.UnmarshalBoolean(response.NewBPIEncryptionEnabled); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANCableLinkConfig1) GetConfigFile() (NewConfigFile string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewConfigFile string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetConfigFile", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewConfigFile, err = soap.UnmarshalString(response.NewConfigFile); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANCableLinkConfig1) GetTFTPServer() (NewTFTPServer string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewTFTPServer string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetTFTPServer", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewTFTPServer, err = soap.UnmarshalString(response.NewTFTPServer); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// WANCommonInterfaceConfig1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1". See -// goupnp.ServiceClient, which contains RootDevice and Service attributes which -// are provided for informational value. -type WANCommonInterfaceConfig1 struct { - goupnp.ServiceClient -} - -// NewWANCommonInterfaceConfig1Clients discovers instances of the service on the network, -// and returns clients to any that are found. errors will contain an error for -// any devices that replied but which could not be queried, and err will be set -// if the discovery process failed outright. -// -// This is a typical entry calling point into this package. -func NewWANCommonInterfaceConfig1Clients() (clients []*WANCommonInterfaceConfig1, errors []error, err error) { - var genericClients []goupnp.ServiceClient - if genericClients, errors, err = goupnp.NewServiceClients(URN_WANCommonInterfaceConfig_1); err != nil { - return - } - clients = newWANCommonInterfaceConfig1ClientsFromGenericClients(genericClients) - return -} - -// NewWANCommonInterfaceConfig1ClientsByURL discovers instances of the service at the given -// URL, and returns clients to any that are found. An error is returned if -// there was an error probing the service. -// -// This is a typical entry calling point into this package when reusing an -// previously discovered service URL. -func NewWANCommonInterfaceConfig1ClientsByURL(loc *url.URL) ([]*WANCommonInterfaceConfig1, error) { - genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANCommonInterfaceConfig_1) - if err != nil { - return nil, err - } - return newWANCommonInterfaceConfig1ClientsFromGenericClients(genericClients), nil -} - -// NewWANCommonInterfaceConfig1ClientsFromRootDevice discovers instances of the service in -// a given root device, and returns clients to any that are found. An error is -// returned if there was not at least one instance of the service within the -// device. The location parameter is simply assigned to the Location attribute -// of the wrapped ServiceClient(s). -// -// This is a typical entry calling point into this package when reusing an -// previously discovered root device. -func NewWANCommonInterfaceConfig1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANCommonInterfaceConfig1, error) { - genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANCommonInterfaceConfig_1) - if err != nil { - return nil, err - } - return newWANCommonInterfaceConfig1ClientsFromGenericClients(genericClients), nil -} - -func newWANCommonInterfaceConfig1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANCommonInterfaceConfig1 { - clients := make([]*WANCommonInterfaceConfig1, len(genericClients)) - for i := range genericClients { - clients[i] = &WANCommonInterfaceConfig1{genericClients[i]} - } - return clients -} - -func (client *WANCommonInterfaceConfig1) SetEnabledForInternet(NewEnabledForInternet bool) (err error) { - // Request structure. - request := &struct { - NewEnabledForInternet string - }{} - // BEGIN Marshal arguments into request. - - if request.NewEnabledForInternet, err = soap.MarshalBoolean(NewEnabledForInternet); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "SetEnabledForInternet", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANCommonInterfaceConfig1) GetEnabledForInternet() (NewEnabledForInternet bool, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewEnabledForInternet string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetEnabledForInternet", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewEnabledForInternet, err = soap.UnmarshalBoolean(response.NewEnabledForInternet); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// -// Return values: -// -// * NewWANAccessType: allowed values: DSL, POTS, Cable, Ethernet -// -// * NewPhysicalLinkStatus: allowed values: Up, Down -func (client *WANCommonInterfaceConfig1) GetCommonLinkProperties() (NewWANAccessType string, NewLayer1UpstreamMaxBitRate uint32, NewLayer1DownstreamMaxBitRate uint32, NewPhysicalLinkStatus string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewWANAccessType string - NewLayer1UpstreamMaxBitRate string - NewLayer1DownstreamMaxBitRate string - NewPhysicalLinkStatus string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetCommonLinkProperties", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewWANAccessType, err = soap.UnmarshalString(response.NewWANAccessType); err != nil { - return - } - if NewLayer1UpstreamMaxBitRate, err = soap.UnmarshalUi4(response.NewLayer1UpstreamMaxBitRate); err != nil { - return - } - if NewLayer1DownstreamMaxBitRate, err = soap.UnmarshalUi4(response.NewLayer1DownstreamMaxBitRate); err != nil { - return - } - if NewPhysicalLinkStatus, err = soap.UnmarshalString(response.NewPhysicalLinkStatus); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANCommonInterfaceConfig1) GetWANAccessProvider() (NewWANAccessProvider string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewWANAccessProvider string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetWANAccessProvider", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewWANAccessProvider, err = soap.UnmarshalString(response.NewWANAccessProvider); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// -// Return values: -// -// * NewMaximumActiveConnections: allowed value range: minimum=1, step=1 -func (client *WANCommonInterfaceConfig1) GetMaximumActiveConnections() (NewMaximumActiveConnections uint16, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewMaximumActiveConnections string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetMaximumActiveConnections", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewMaximumActiveConnections, err = soap.UnmarshalUi2(response.NewMaximumActiveConnections); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANCommonInterfaceConfig1) GetTotalBytesSent() (NewTotalBytesSent uint64, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewTotalBytesSent string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetTotalBytesSent", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewTotalBytesSent, err = soap.UnmarshalUi8(response.NewTotalBytesSent); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANCommonInterfaceConfig1) GetTotalBytesReceived() (NewTotalBytesReceived uint64, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewTotalBytesReceived string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetTotalBytesReceived", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewTotalBytesReceived, err = soap.UnmarshalUi8(response.NewTotalBytesReceived); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANCommonInterfaceConfig1) GetTotalPacketsSent() (NewTotalPacketsSent uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewTotalPacketsSent string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetTotalPacketsSent", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewTotalPacketsSent, err = soap.UnmarshalUi4(response.NewTotalPacketsSent); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANCommonInterfaceConfig1) GetTotalPacketsReceived() (NewTotalPacketsReceived uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewTotalPacketsReceived string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetTotalPacketsReceived", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewTotalPacketsReceived, err = soap.UnmarshalUi4(response.NewTotalPacketsReceived); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANCommonInterfaceConfig1) GetActiveConnection(NewActiveConnectionIndex uint16) (NewActiveConnDeviceContainer string, NewActiveConnectionServiceID string, err error) { - // Request structure. - request := &struct { - NewActiveConnectionIndex string - }{} - // BEGIN Marshal arguments into request. - - if request.NewActiveConnectionIndex, err = soap.MarshalUi2(NewActiveConnectionIndex); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewActiveConnDeviceContainer string - NewActiveConnectionServiceID string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetActiveConnection", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewActiveConnDeviceContainer, err = soap.UnmarshalString(response.NewActiveConnDeviceContainer); err != nil { - return - } - if NewActiveConnectionServiceID, err = soap.UnmarshalString(response.NewActiveConnectionServiceID); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// WANDSLLinkConfig1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANDSLLinkConfig:1". See -// goupnp.ServiceClient, which contains RootDevice and Service attributes which -// are provided for informational value. -type WANDSLLinkConfig1 struct { - goupnp.ServiceClient -} - -// NewWANDSLLinkConfig1Clients discovers instances of the service on the network, -// and returns clients to any that are found. errors will contain an error for -// any devices that replied but which could not be queried, and err will be set -// if the discovery process failed outright. -// -// This is a typical entry calling point into this package. -func NewWANDSLLinkConfig1Clients() (clients []*WANDSLLinkConfig1, errors []error, err error) { - var genericClients []goupnp.ServiceClient - if genericClients, errors, err = goupnp.NewServiceClients(URN_WANDSLLinkConfig_1); err != nil { - return - } - clients = newWANDSLLinkConfig1ClientsFromGenericClients(genericClients) - return -} - -// NewWANDSLLinkConfig1ClientsByURL discovers instances of the service at the given -// URL, and returns clients to any that are found. An error is returned if -// there was an error probing the service. -// -// This is a typical entry calling point into this package when reusing an -// previously discovered service URL. -func NewWANDSLLinkConfig1ClientsByURL(loc *url.URL) ([]*WANDSLLinkConfig1, error) { - genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANDSLLinkConfig_1) - if err != nil { - return nil, err - } - return newWANDSLLinkConfig1ClientsFromGenericClients(genericClients), nil -} - -// NewWANDSLLinkConfig1ClientsFromRootDevice discovers instances of the service in -// a given root device, and returns clients to any that are found. An error is -// returned if there was not at least one instance of the service within the -// device. The location parameter is simply assigned to the Location attribute -// of the wrapped ServiceClient(s). -// -// This is a typical entry calling point into this package when reusing an -// previously discovered root device. -func NewWANDSLLinkConfig1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANDSLLinkConfig1, error) { - genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANDSLLinkConfig_1) - if err != nil { - return nil, err - } - return newWANDSLLinkConfig1ClientsFromGenericClients(genericClients), nil -} - -func newWANDSLLinkConfig1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANDSLLinkConfig1 { - clients := make([]*WANDSLLinkConfig1, len(genericClients)) - for i := range genericClients { - clients[i] = &WANDSLLinkConfig1{genericClients[i]} - } - return clients -} - -func (client *WANDSLLinkConfig1) SetDSLLinkType(NewLinkType string) (err error) { - // Request structure. - request := &struct { - NewLinkType string - }{} - // BEGIN Marshal arguments into request. - - if request.NewLinkType, err = soap.MarshalString(NewLinkType); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "SetDSLLinkType", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -// -// Return values: -// -// * NewLinkStatus: allowed values: Up, Down -func (client *WANDSLLinkConfig1) GetDSLLinkInfo() (NewLinkType string, NewLinkStatus string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewLinkType string - NewLinkStatus string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "GetDSLLinkInfo", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewLinkType, err = soap.UnmarshalString(response.NewLinkType); err != nil { - return - } - if NewLinkStatus, err = soap.UnmarshalString(response.NewLinkStatus); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANDSLLinkConfig1) GetAutoConfig() (NewAutoConfig bool, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewAutoConfig string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "GetAutoConfig", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewAutoConfig, err = soap.UnmarshalBoolean(response.NewAutoConfig); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANDSLLinkConfig1) GetModulationType() (NewModulationType string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewModulationType string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "GetModulationType", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewModulationType, err = soap.UnmarshalString(response.NewModulationType); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANDSLLinkConfig1) SetDestinationAddress(NewDestinationAddress string) (err error) { - // Request structure. - request := &struct { - NewDestinationAddress string - }{} - // BEGIN Marshal arguments into request. - - if request.NewDestinationAddress, err = soap.MarshalString(NewDestinationAddress); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "SetDestinationAddress", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANDSLLinkConfig1) GetDestinationAddress() (NewDestinationAddress string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewDestinationAddress string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "GetDestinationAddress", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewDestinationAddress, err = soap.UnmarshalString(response.NewDestinationAddress); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANDSLLinkConfig1) SetATMEncapsulation(NewATMEncapsulation string) (err error) { - // Request structure. - request := &struct { - NewATMEncapsulation string - }{} - // BEGIN Marshal arguments into request. - - if request.NewATMEncapsulation, err = soap.MarshalString(NewATMEncapsulation); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "SetATMEncapsulation", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANDSLLinkConfig1) GetATMEncapsulation() (NewATMEncapsulation string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewATMEncapsulation string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "GetATMEncapsulation", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewATMEncapsulation, err = soap.UnmarshalString(response.NewATMEncapsulation); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANDSLLinkConfig1) SetFCSPreserved(NewFCSPreserved bool) (err error) { - // Request structure. - request := &struct { - NewFCSPreserved string - }{} - // BEGIN Marshal arguments into request. - - if request.NewFCSPreserved, err = soap.MarshalBoolean(NewFCSPreserved); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "SetFCSPreserved", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANDSLLinkConfig1) GetFCSPreserved() (NewFCSPreserved bool, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewFCSPreserved string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "GetFCSPreserved", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewFCSPreserved, err = soap.UnmarshalBoolean(response.NewFCSPreserved); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// WANEthernetLinkConfig1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANEthernetLinkConfig:1". See -// goupnp.ServiceClient, which contains RootDevice and Service attributes which -// are provided for informational value. -type WANEthernetLinkConfig1 struct { - goupnp.ServiceClient -} - -// NewWANEthernetLinkConfig1Clients discovers instances of the service on the network, -// and returns clients to any that are found. errors will contain an error for -// any devices that replied but which could not be queried, and err will be set -// if the discovery process failed outright. -// -// This is a typical entry calling point into this package. -func NewWANEthernetLinkConfig1Clients() (clients []*WANEthernetLinkConfig1, errors []error, err error) { - var genericClients []goupnp.ServiceClient - if genericClients, errors, err = goupnp.NewServiceClients(URN_WANEthernetLinkConfig_1); err != nil { - return - } - clients = newWANEthernetLinkConfig1ClientsFromGenericClients(genericClients) - return -} - -// NewWANEthernetLinkConfig1ClientsByURL discovers instances of the service at the given -// URL, and returns clients to any that are found. An error is returned if -// there was an error probing the service. -// -// This is a typical entry calling point into this package when reusing an -// previously discovered service URL. -func NewWANEthernetLinkConfig1ClientsByURL(loc *url.URL) ([]*WANEthernetLinkConfig1, error) { - genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANEthernetLinkConfig_1) - if err != nil { - return nil, err - } - return newWANEthernetLinkConfig1ClientsFromGenericClients(genericClients), nil -} - -// NewWANEthernetLinkConfig1ClientsFromRootDevice discovers instances of the service in -// a given root device, and returns clients to any that are found. An error is -// returned if there was not at least one instance of the service within the -// device. The location parameter is simply assigned to the Location attribute -// of the wrapped ServiceClient(s). -// -// This is a typical entry calling point into this package when reusing an -// previously discovered root device. -func NewWANEthernetLinkConfig1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANEthernetLinkConfig1, error) { - genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANEthernetLinkConfig_1) - if err != nil { - return nil, err - } - return newWANEthernetLinkConfig1ClientsFromGenericClients(genericClients), nil -} - -func newWANEthernetLinkConfig1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANEthernetLinkConfig1 { - clients := make([]*WANEthernetLinkConfig1, len(genericClients)) - for i := range genericClients { - clients[i] = &WANEthernetLinkConfig1{genericClients[i]} - } - return clients -} - -// -// Return values: -// -// * NewEthernetLinkStatus: allowed values: Up, Down -func (client *WANEthernetLinkConfig1) GetEthernetLinkStatus() (NewEthernetLinkStatus string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewEthernetLinkStatus string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANEthernetLinkConfig_1, "GetEthernetLinkStatus", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewEthernetLinkStatus, err = soap.UnmarshalString(response.NewEthernetLinkStatus); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// WANIPConnection1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANIPConnection:1". See -// goupnp.ServiceClient, which contains RootDevice and Service attributes which -// are provided for informational value. -type WANIPConnection1 struct { - goupnp.ServiceClient -} - -// NewWANIPConnection1Clients discovers instances of the service on the network, -// and returns clients to any that are found. errors will contain an error for -// any devices that replied but which could not be queried, and err will be set -// if the discovery process failed outright. -// -// This is a typical entry calling point into this package. -func NewWANIPConnection1Clients() (clients []*WANIPConnection1, errors []error, err error) { - var genericClients []goupnp.ServiceClient - if genericClients, errors, err = goupnp.NewServiceClients(URN_WANIPConnection_1); err != nil { - return - } - clients = newWANIPConnection1ClientsFromGenericClients(genericClients) - return -} - -// NewWANIPConnection1ClientsByURL discovers instances of the service at the given -// URL, and returns clients to any that are found. An error is returned if -// there was an error probing the service. -// -// This is a typical entry calling point into this package when reusing an -// previously discovered service URL. -func NewWANIPConnection1ClientsByURL(loc *url.URL) ([]*WANIPConnection1, error) { - genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANIPConnection_1) - if err != nil { - return nil, err - } - return newWANIPConnection1ClientsFromGenericClients(genericClients), nil -} - -// NewWANIPConnection1ClientsFromRootDevice discovers instances of the service in -// a given root device, and returns clients to any that are found. An error is -// returned if there was not at least one instance of the service within the -// device. The location parameter is simply assigned to the Location attribute -// of the wrapped ServiceClient(s). -// -// This is a typical entry calling point into this package when reusing an -// previously discovered root device. -func NewWANIPConnection1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANIPConnection1, error) { - genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANIPConnection_1) - if err != nil { - return nil, err - } - return newWANIPConnection1ClientsFromGenericClients(genericClients), nil -} - -func newWANIPConnection1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANIPConnection1 { - clients := make([]*WANIPConnection1, len(genericClients)) - for i := range genericClients { - clients[i] = &WANIPConnection1{genericClients[i]} - } - return clients -} - -func (client *WANIPConnection1) SetConnectionType(NewConnectionType string) (err error) { - // Request structure. - request := &struct { - NewConnectionType string - }{} - // BEGIN Marshal arguments into request. - - if request.NewConnectionType, err = soap.MarshalString(NewConnectionType); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "SetConnectionType", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -// -// Return values: -// -// * NewPossibleConnectionTypes: allowed values: Unconfigured, IP_Routed, IP_Bridged -func (client *WANIPConnection1) GetConnectionTypeInfo() (NewConnectionType string, NewPossibleConnectionTypes string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewConnectionType string - NewPossibleConnectionTypes string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetConnectionTypeInfo", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewConnectionType, err = soap.UnmarshalString(response.NewConnectionType); err != nil { - return - } - if NewPossibleConnectionTypes, err = soap.UnmarshalString(response.NewPossibleConnectionTypes); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection1) RequestConnection() (err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "RequestConnection", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection1) RequestTermination() (err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "RequestTermination", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection1) ForceTermination() (err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "ForceTermination", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection1) SetAutoDisconnectTime(NewAutoDisconnectTime uint32) (err error) { - // Request structure. - request := &struct { - NewAutoDisconnectTime string - }{} - // BEGIN Marshal arguments into request. - - if request.NewAutoDisconnectTime, err = soap.MarshalUi4(NewAutoDisconnectTime); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "SetAutoDisconnectTime", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection1) SetIdleDisconnectTime(NewIdleDisconnectTime uint32) (err error) { - // Request structure. - request := &struct { - NewIdleDisconnectTime string - }{} - // BEGIN Marshal arguments into request. - - if request.NewIdleDisconnectTime, err = soap.MarshalUi4(NewIdleDisconnectTime); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "SetIdleDisconnectTime", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection1) SetWarnDisconnectDelay(NewWarnDisconnectDelay uint32) (err error) { - // Request structure. - request := &struct { - NewWarnDisconnectDelay string - }{} - // BEGIN Marshal arguments into request. - - if request.NewWarnDisconnectDelay, err = soap.MarshalUi4(NewWarnDisconnectDelay); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "SetWarnDisconnectDelay", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -// -// Return values: -// -// * NewConnectionStatus: allowed values: Unconfigured, Connected, Disconnected -// -// * NewLastConnectionError: allowed values: ERROR_NONE -func (client *WANIPConnection1) GetStatusInfo() (NewConnectionStatus string, NewLastConnectionError string, NewUptime uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewConnectionStatus string - NewLastConnectionError string - NewUptime string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetStatusInfo", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewConnectionStatus, err = soap.UnmarshalString(response.NewConnectionStatus); err != nil { - return - } - if NewLastConnectionError, err = soap.UnmarshalString(response.NewLastConnectionError); err != nil { - return - } - if NewUptime, err = soap.UnmarshalUi4(response.NewUptime); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection1) GetAutoDisconnectTime() (NewAutoDisconnectTime uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewAutoDisconnectTime string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetAutoDisconnectTime", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewAutoDisconnectTime, err = soap.UnmarshalUi4(response.NewAutoDisconnectTime); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection1) GetIdleDisconnectTime() (NewIdleDisconnectTime uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewIdleDisconnectTime string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetIdleDisconnectTime", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewIdleDisconnectTime, err = soap.UnmarshalUi4(response.NewIdleDisconnectTime); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection1) GetWarnDisconnectDelay() (NewWarnDisconnectDelay uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewWarnDisconnectDelay string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetWarnDisconnectDelay", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewWarnDisconnectDelay, err = soap.UnmarshalUi4(response.NewWarnDisconnectDelay); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection1) GetNATRSIPStatus() (NewRSIPAvailable bool, NewNATEnabled bool, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewRSIPAvailable string - NewNATEnabled string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetNATRSIPStatus", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewRSIPAvailable, err = soap.UnmarshalBoolean(response.NewRSIPAvailable); err != nil { - return - } - if NewNATEnabled, err = soap.UnmarshalBoolean(response.NewNATEnabled); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// -// Return values: -// -// * NewProtocol: allowed values: TCP, UDP -func (client *WANIPConnection1) GetGenericPortMappingEntry(NewPortMappingIndex uint16) (NewRemoteHost string, NewExternalPort uint16, NewProtocol string, NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32, err error) { - // Request structure. - request := &struct { - NewPortMappingIndex string - }{} - // BEGIN Marshal arguments into request. - - if request.NewPortMappingIndex, err = soap.MarshalUi2(NewPortMappingIndex); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewRemoteHost string - NewExternalPort string - NewProtocol string - NewInternalPort string - NewInternalClient string - NewEnabled string - NewPortMappingDescription string - NewLeaseDuration string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetGenericPortMappingEntry", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewRemoteHost, err = soap.UnmarshalString(response.NewRemoteHost); err != nil { - return - } - if NewExternalPort, err = soap.UnmarshalUi2(response.NewExternalPort); err != nil { - return - } - if NewProtocol, err = soap.UnmarshalString(response.NewProtocol); err != nil { - return - } - if NewInternalPort, err = soap.UnmarshalUi2(response.NewInternalPort); err != nil { - return - } - if NewInternalClient, err = soap.UnmarshalString(response.NewInternalClient); err != nil { - return - } - if NewEnabled, err = soap.UnmarshalBoolean(response.NewEnabled); err != nil { - return - } - if NewPortMappingDescription, err = soap.UnmarshalString(response.NewPortMappingDescription); err != nil { - return - } - if NewLeaseDuration, err = soap.UnmarshalUi4(response.NewLeaseDuration); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// -// Arguments: -// -// * NewProtocol: allowed values: TCP, UDP - -func (client *WANIPConnection1) GetSpecificPortMappingEntry(NewRemoteHost string, NewExternalPort uint16, NewProtocol string) (NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32, err error) { - // Request structure. - request := &struct { - NewRemoteHost string - NewExternalPort string - NewProtocol string - }{} - // BEGIN Marshal arguments into request. - - if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil { - return - } - if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil { - return - } - if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewInternalPort string - NewInternalClient string - NewEnabled string - NewPortMappingDescription string - NewLeaseDuration string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetSpecificPortMappingEntry", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewInternalPort, err = soap.UnmarshalUi2(response.NewInternalPort); err != nil { - return - } - if NewInternalClient, err = soap.UnmarshalString(response.NewInternalClient); err != nil { - return - } - if NewEnabled, err = soap.UnmarshalBoolean(response.NewEnabled); err != nil { - return - } - if NewPortMappingDescription, err = soap.UnmarshalString(response.NewPortMappingDescription); err != nil { - return - } - if NewLeaseDuration, err = soap.UnmarshalUi4(response.NewLeaseDuration); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// -// Arguments: -// -// * NewProtocol: allowed values: TCP, UDP - -func (client *WANIPConnection1) AddPortMapping(NewRemoteHost string, NewExternalPort uint16, NewProtocol string, NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32) (err error) { - // Request structure. - request := &struct { - NewRemoteHost string - NewExternalPort string - NewProtocol string - NewInternalPort string - NewInternalClient string - NewEnabled string - NewPortMappingDescription string - NewLeaseDuration string - }{} - // BEGIN Marshal arguments into request. - - if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil { - return - } - if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil { - return - } - if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil { - return - } - if request.NewInternalPort, err = soap.MarshalUi2(NewInternalPort); err != nil { - return - } - if request.NewInternalClient, err = soap.MarshalString(NewInternalClient); err != nil { - return - } - if request.NewEnabled, err = soap.MarshalBoolean(NewEnabled); err != nil { - return - } - if request.NewPortMappingDescription, err = soap.MarshalString(NewPortMappingDescription); err != nil { - return - } - if request.NewLeaseDuration, err = soap.MarshalUi4(NewLeaseDuration); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "AddPortMapping", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -// -// Arguments: -// -// * NewProtocol: allowed values: TCP, UDP - -func (client *WANIPConnection1) DeletePortMapping(NewRemoteHost string, NewExternalPort uint16, NewProtocol string) (err error) { - // Request structure. - request := &struct { - NewRemoteHost string - NewExternalPort string - NewProtocol string - }{} - // BEGIN Marshal arguments into request. - - if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil { - return - } - if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil { - return - } - if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "DeletePortMapping", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection1) GetExternalIPAddress() (NewExternalIPAddress string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewExternalIPAddress string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetExternalIPAddress", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewExternalIPAddress, err = soap.UnmarshalString(response.NewExternalIPAddress); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// WANPOTSLinkConfig1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANPOTSLinkConfig:1". See -// goupnp.ServiceClient, which contains RootDevice and Service attributes which -// are provided for informational value. -type WANPOTSLinkConfig1 struct { - goupnp.ServiceClient -} - -// NewWANPOTSLinkConfig1Clients discovers instances of the service on the network, -// and returns clients to any that are found. errors will contain an error for -// any devices that replied but which could not be queried, and err will be set -// if the discovery process failed outright. -// -// This is a typical entry calling point into this package. -func NewWANPOTSLinkConfig1Clients() (clients []*WANPOTSLinkConfig1, errors []error, err error) { - var genericClients []goupnp.ServiceClient - if genericClients, errors, err = goupnp.NewServiceClients(URN_WANPOTSLinkConfig_1); err != nil { - return - } - clients = newWANPOTSLinkConfig1ClientsFromGenericClients(genericClients) - return -} - -// NewWANPOTSLinkConfig1ClientsByURL discovers instances of the service at the given -// URL, and returns clients to any that are found. An error is returned if -// there was an error probing the service. -// -// This is a typical entry calling point into this package when reusing an -// previously discovered service URL. -func NewWANPOTSLinkConfig1ClientsByURL(loc *url.URL) ([]*WANPOTSLinkConfig1, error) { - genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANPOTSLinkConfig_1) - if err != nil { - return nil, err - } - return newWANPOTSLinkConfig1ClientsFromGenericClients(genericClients), nil -} - -// NewWANPOTSLinkConfig1ClientsFromRootDevice discovers instances of the service in -// a given root device, and returns clients to any that are found. An error is -// returned if there was not at least one instance of the service within the -// device. The location parameter is simply assigned to the Location attribute -// of the wrapped ServiceClient(s). -// -// This is a typical entry calling point into this package when reusing an -// previously discovered root device. -func NewWANPOTSLinkConfig1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANPOTSLinkConfig1, error) { - genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANPOTSLinkConfig_1) - if err != nil { - return nil, err - } - return newWANPOTSLinkConfig1ClientsFromGenericClients(genericClients), nil -} - -func newWANPOTSLinkConfig1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANPOTSLinkConfig1 { - clients := make([]*WANPOTSLinkConfig1, len(genericClients)) - for i := range genericClients { - clients[i] = &WANPOTSLinkConfig1{genericClients[i]} - } - return clients -} - -// -// Arguments: -// -// * NewLinkType: allowed values: PPP_Dialup - -func (client *WANPOTSLinkConfig1) SetISPInfo(NewISPPhoneNumber string, NewISPInfo string, NewLinkType string) (err error) { - // Request structure. - request := &struct { - NewISPPhoneNumber string - NewISPInfo string - NewLinkType string - }{} - // BEGIN Marshal arguments into request. - - if request.NewISPPhoneNumber, err = soap.MarshalString(NewISPPhoneNumber); err != nil { - return - } - if request.NewISPInfo, err = soap.MarshalString(NewISPInfo); err != nil { - return - } - if request.NewLinkType, err = soap.MarshalString(NewLinkType); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "SetISPInfo", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANPOTSLinkConfig1) SetCallRetryInfo(NewNumberOfRetries uint32, NewDelayBetweenRetries uint32) (err error) { - // Request structure. - request := &struct { - NewNumberOfRetries string - NewDelayBetweenRetries string - }{} - // BEGIN Marshal arguments into request. - - if request.NewNumberOfRetries, err = soap.MarshalUi4(NewNumberOfRetries); err != nil { - return - } - if request.NewDelayBetweenRetries, err = soap.MarshalUi4(NewDelayBetweenRetries); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "SetCallRetryInfo", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -// -// Return values: -// -// * NewLinkType: allowed values: PPP_Dialup -func (client *WANPOTSLinkConfig1) GetISPInfo() (NewISPPhoneNumber string, NewISPInfo string, NewLinkType string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewISPPhoneNumber string - NewISPInfo string - NewLinkType string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "GetISPInfo", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewISPPhoneNumber, err = soap.UnmarshalString(response.NewISPPhoneNumber); err != nil { - return - } - if NewISPInfo, err = soap.UnmarshalString(response.NewISPInfo); err != nil { - return - } - if NewLinkType, err = soap.UnmarshalString(response.NewLinkType); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPOTSLinkConfig1) GetCallRetryInfo() (NewNumberOfRetries uint32, NewDelayBetweenRetries uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewNumberOfRetries string - NewDelayBetweenRetries string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "GetCallRetryInfo", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewNumberOfRetries, err = soap.UnmarshalUi4(response.NewNumberOfRetries); err != nil { - return - } - if NewDelayBetweenRetries, err = soap.UnmarshalUi4(response.NewDelayBetweenRetries); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPOTSLinkConfig1) GetFclass() (NewFclass string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewFclass string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "GetFclass", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewFclass, err = soap.UnmarshalString(response.NewFclass); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPOTSLinkConfig1) GetDataModulationSupported() (NewDataModulationSupported string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewDataModulationSupported string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "GetDataModulationSupported", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewDataModulationSupported, err = soap.UnmarshalString(response.NewDataModulationSupported); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPOTSLinkConfig1) GetDataProtocol() (NewDataProtocol string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewDataProtocol string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "GetDataProtocol", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewDataProtocol, err = soap.UnmarshalString(response.NewDataProtocol); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPOTSLinkConfig1) GetDataCompression() (NewDataCompression string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewDataCompression string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "GetDataCompression", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewDataCompression, err = soap.UnmarshalString(response.NewDataCompression); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPOTSLinkConfig1) GetPlusVTRCommandSupported() (NewPlusVTRCommandSupported bool, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewPlusVTRCommandSupported string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "GetPlusVTRCommandSupported", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewPlusVTRCommandSupported, err = soap.UnmarshalBoolean(response.NewPlusVTRCommandSupported); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// WANPPPConnection1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANPPPConnection:1". See -// goupnp.ServiceClient, which contains RootDevice and Service attributes which -// are provided for informational value. -type WANPPPConnection1 struct { - goupnp.ServiceClient -} - -// NewWANPPPConnection1Clients discovers instances of the service on the network, -// and returns clients to any that are found. errors will contain an error for -// any devices that replied but which could not be queried, and err will be set -// if the discovery process failed outright. -// -// This is a typical entry calling point into this package. -func NewWANPPPConnection1Clients() (clients []*WANPPPConnection1, errors []error, err error) { - var genericClients []goupnp.ServiceClient - if genericClients, errors, err = goupnp.NewServiceClients(URN_WANPPPConnection_1); err != nil { - return - } - clients = newWANPPPConnection1ClientsFromGenericClients(genericClients) - return -} - -// NewWANPPPConnection1ClientsByURL discovers instances of the service at the given -// URL, and returns clients to any that are found. An error is returned if -// there was an error probing the service. -// -// This is a typical entry calling point into this package when reusing an -// previously discovered service URL. -func NewWANPPPConnection1ClientsByURL(loc *url.URL) ([]*WANPPPConnection1, error) { - genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANPPPConnection_1) - if err != nil { - return nil, err - } - return newWANPPPConnection1ClientsFromGenericClients(genericClients), nil -} - -// NewWANPPPConnection1ClientsFromRootDevice discovers instances of the service in -// a given root device, and returns clients to any that are found. An error is -// returned if there was not at least one instance of the service within the -// device. The location parameter is simply assigned to the Location attribute -// of the wrapped ServiceClient(s). -// -// This is a typical entry calling point into this package when reusing an -// previously discovered root device. -func NewWANPPPConnection1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANPPPConnection1, error) { - genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANPPPConnection_1) - if err != nil { - return nil, err - } - return newWANPPPConnection1ClientsFromGenericClients(genericClients), nil -} - -func newWANPPPConnection1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANPPPConnection1 { - clients := make([]*WANPPPConnection1, len(genericClients)) - for i := range genericClients { - clients[i] = &WANPPPConnection1{genericClients[i]} - } - return clients -} - -func (client *WANPPPConnection1) SetConnectionType(NewConnectionType string) (err error) { - // Request structure. - request := &struct { - NewConnectionType string - }{} - // BEGIN Marshal arguments into request. - - if request.NewConnectionType, err = soap.MarshalString(NewConnectionType); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "SetConnectionType", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -// -// Return values: -// -// * NewPossibleConnectionTypes: allowed values: Unconfigured, IP_Routed, DHCP_Spoofed, PPPoE_Bridged, PPTP_Relay, L2TP_Relay, PPPoE_Relay -func (client *WANPPPConnection1) GetConnectionTypeInfo() (NewConnectionType string, NewPossibleConnectionTypes string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewConnectionType string - NewPossibleConnectionTypes string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetConnectionTypeInfo", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewConnectionType, err = soap.UnmarshalString(response.NewConnectionType); err != nil { - return - } - if NewPossibleConnectionTypes, err = soap.UnmarshalString(response.NewPossibleConnectionTypes); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) ConfigureConnection(NewUserName string, NewPassword string) (err error) { - // Request structure. - request := &struct { - NewUserName string - NewPassword string - }{} - // BEGIN Marshal arguments into request. - - if request.NewUserName, err = soap.MarshalString(NewUserName); err != nil { - return - } - if request.NewPassword, err = soap.MarshalString(NewPassword); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "ConfigureConnection", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) RequestConnection() (err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "RequestConnection", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) RequestTermination() (err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "RequestTermination", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) ForceTermination() (err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "ForceTermination", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) SetAutoDisconnectTime(NewAutoDisconnectTime uint32) (err error) { - // Request structure. - request := &struct { - NewAutoDisconnectTime string - }{} - // BEGIN Marshal arguments into request. - - if request.NewAutoDisconnectTime, err = soap.MarshalUi4(NewAutoDisconnectTime); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "SetAutoDisconnectTime", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) SetIdleDisconnectTime(NewIdleDisconnectTime uint32) (err error) { - // Request structure. - request := &struct { - NewIdleDisconnectTime string - }{} - // BEGIN Marshal arguments into request. - - if request.NewIdleDisconnectTime, err = soap.MarshalUi4(NewIdleDisconnectTime); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "SetIdleDisconnectTime", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) SetWarnDisconnectDelay(NewWarnDisconnectDelay uint32) (err error) { - // Request structure. - request := &struct { - NewWarnDisconnectDelay string - }{} - // BEGIN Marshal arguments into request. - - if request.NewWarnDisconnectDelay, err = soap.MarshalUi4(NewWarnDisconnectDelay); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "SetWarnDisconnectDelay", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -// -// Return values: -// -// * NewConnectionStatus: allowed values: Unconfigured, Connected, Disconnected -// -// * NewLastConnectionError: allowed values: ERROR_NONE -func (client *WANPPPConnection1) GetStatusInfo() (NewConnectionStatus string, NewLastConnectionError string, NewUptime uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewConnectionStatus string - NewLastConnectionError string - NewUptime string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetStatusInfo", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewConnectionStatus, err = soap.UnmarshalString(response.NewConnectionStatus); err != nil { - return - } - if NewLastConnectionError, err = soap.UnmarshalString(response.NewLastConnectionError); err != nil { - return - } - if NewUptime, err = soap.UnmarshalUi4(response.NewUptime); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) GetLinkLayerMaxBitRates() (NewUpstreamMaxBitRate uint32, NewDownstreamMaxBitRate uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewUpstreamMaxBitRate string - NewDownstreamMaxBitRate string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetLinkLayerMaxBitRates", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewUpstreamMaxBitRate, err = soap.UnmarshalUi4(response.NewUpstreamMaxBitRate); err != nil { - return - } - if NewDownstreamMaxBitRate, err = soap.UnmarshalUi4(response.NewDownstreamMaxBitRate); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) GetPPPEncryptionProtocol() (NewPPPEncryptionProtocol string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewPPPEncryptionProtocol string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetPPPEncryptionProtocol", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewPPPEncryptionProtocol, err = soap.UnmarshalString(response.NewPPPEncryptionProtocol); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) GetPPPCompressionProtocol() (NewPPPCompressionProtocol string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewPPPCompressionProtocol string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetPPPCompressionProtocol", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewPPPCompressionProtocol, err = soap.UnmarshalString(response.NewPPPCompressionProtocol); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) GetPPPAuthenticationProtocol() (NewPPPAuthenticationProtocol string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewPPPAuthenticationProtocol string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetPPPAuthenticationProtocol", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewPPPAuthenticationProtocol, err = soap.UnmarshalString(response.NewPPPAuthenticationProtocol); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) GetUserName() (NewUserName string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewUserName string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetUserName", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewUserName, err = soap.UnmarshalString(response.NewUserName); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) GetPassword() (NewPassword string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewPassword string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetPassword", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewPassword, err = soap.UnmarshalString(response.NewPassword); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) GetAutoDisconnectTime() (NewAutoDisconnectTime uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewAutoDisconnectTime string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetAutoDisconnectTime", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewAutoDisconnectTime, err = soap.UnmarshalUi4(response.NewAutoDisconnectTime); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) GetIdleDisconnectTime() (NewIdleDisconnectTime uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewIdleDisconnectTime string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetIdleDisconnectTime", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewIdleDisconnectTime, err = soap.UnmarshalUi4(response.NewIdleDisconnectTime); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) GetWarnDisconnectDelay() (NewWarnDisconnectDelay uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewWarnDisconnectDelay string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetWarnDisconnectDelay", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewWarnDisconnectDelay, err = soap.UnmarshalUi4(response.NewWarnDisconnectDelay); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) GetNATRSIPStatus() (NewRSIPAvailable bool, NewNATEnabled bool, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewRSIPAvailable string - NewNATEnabled string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetNATRSIPStatus", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewRSIPAvailable, err = soap.UnmarshalBoolean(response.NewRSIPAvailable); err != nil { - return - } - if NewNATEnabled, err = soap.UnmarshalBoolean(response.NewNATEnabled); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// -// Return values: -// -// * NewProtocol: allowed values: TCP, UDP -func (client *WANPPPConnection1) GetGenericPortMappingEntry(NewPortMappingIndex uint16) (NewRemoteHost string, NewExternalPort uint16, NewProtocol string, NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32, err error) { - // Request structure. - request := &struct { - NewPortMappingIndex string - }{} - // BEGIN Marshal arguments into request. - - if request.NewPortMappingIndex, err = soap.MarshalUi2(NewPortMappingIndex); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewRemoteHost string - NewExternalPort string - NewProtocol string - NewInternalPort string - NewInternalClient string - NewEnabled string - NewPortMappingDescription string - NewLeaseDuration string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetGenericPortMappingEntry", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewRemoteHost, err = soap.UnmarshalString(response.NewRemoteHost); err != nil { - return - } - if NewExternalPort, err = soap.UnmarshalUi2(response.NewExternalPort); err != nil { - return - } - if NewProtocol, err = soap.UnmarshalString(response.NewProtocol); err != nil { - return - } - if NewInternalPort, err = soap.UnmarshalUi2(response.NewInternalPort); err != nil { - return - } - if NewInternalClient, err = soap.UnmarshalString(response.NewInternalClient); err != nil { - return - } - if NewEnabled, err = soap.UnmarshalBoolean(response.NewEnabled); err != nil { - return - } - if NewPortMappingDescription, err = soap.UnmarshalString(response.NewPortMappingDescription); err != nil { - return - } - if NewLeaseDuration, err = soap.UnmarshalUi4(response.NewLeaseDuration); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// -// Arguments: -// -// * NewProtocol: allowed values: TCP, UDP - -func (client *WANPPPConnection1) GetSpecificPortMappingEntry(NewRemoteHost string, NewExternalPort uint16, NewProtocol string) (NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32, err error) { - // Request structure. - request := &struct { - NewRemoteHost string - NewExternalPort string - NewProtocol string - }{} - // BEGIN Marshal arguments into request. - - if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil { - return - } - if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil { - return - } - if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewInternalPort string - NewInternalClient string - NewEnabled string - NewPortMappingDescription string - NewLeaseDuration string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetSpecificPortMappingEntry", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewInternalPort, err = soap.UnmarshalUi2(response.NewInternalPort); err != nil { - return - } - if NewInternalClient, err = soap.UnmarshalString(response.NewInternalClient); err != nil { - return - } - if NewEnabled, err = soap.UnmarshalBoolean(response.NewEnabled); err != nil { - return - } - if NewPortMappingDescription, err = soap.UnmarshalString(response.NewPortMappingDescription); err != nil { - return - } - if NewLeaseDuration, err = soap.UnmarshalUi4(response.NewLeaseDuration); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// -// Arguments: -// -// * NewProtocol: allowed values: TCP, UDP - -func (client *WANPPPConnection1) AddPortMapping(NewRemoteHost string, NewExternalPort uint16, NewProtocol string, NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32) (err error) { - // Request structure. - request := &struct { - NewRemoteHost string - NewExternalPort string - NewProtocol string - NewInternalPort string - NewInternalClient string - NewEnabled string - NewPortMappingDescription string - NewLeaseDuration string - }{} - // BEGIN Marshal arguments into request. - - if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil { - return - } - if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil { - return - } - if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil { - return - } - if request.NewInternalPort, err = soap.MarshalUi2(NewInternalPort); err != nil { - return - } - if request.NewInternalClient, err = soap.MarshalString(NewInternalClient); err != nil { - return - } - if request.NewEnabled, err = soap.MarshalBoolean(NewEnabled); err != nil { - return - } - if request.NewPortMappingDescription, err = soap.MarshalString(NewPortMappingDescription); err != nil { - return - } - if request.NewLeaseDuration, err = soap.MarshalUi4(NewLeaseDuration); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "AddPortMapping", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -// -// Arguments: -// -// * NewProtocol: allowed values: TCP, UDP - -func (client *WANPPPConnection1) DeletePortMapping(NewRemoteHost string, NewExternalPort uint16, NewProtocol string) (err error) { - // Request structure. - request := &struct { - NewRemoteHost string - NewExternalPort string - NewProtocol string - }{} - // BEGIN Marshal arguments into request. - - if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil { - return - } - if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil { - return - } - if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "DeletePortMapping", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) GetExternalIPAddress() (NewExternalIPAddress string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewExternalIPAddress string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetExternalIPAddress", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewExternalIPAddress, err = soap.UnmarshalString(response.NewExternalIPAddress); err != nil { - return - } - // END Unmarshal arguments from response. - return -} diff --git a/vendor/github.com/huin/goupnp/dcps/internetgateway2/internetgateway2.go b/vendor/github.com/huin/goupnp/dcps/internetgateway2/internetgateway2.go deleted file mode 100644 index 4eb5f610..00000000 --- a/vendor/github.com/huin/goupnp/dcps/internetgateway2/internetgateway2.go +++ /dev/null @@ -1,5248 +0,0 @@ -// Client for UPnP Device Control Protocol Internet Gateway Device v2. -// -// This DCP is documented in detail at: http://upnp.org/specs/gw/UPnP-gw-InternetGatewayDevice-v2-Device.pdf -// -// Typically, use one of the New* functions to create clients for services. -package internetgateway2 - -// *********************************************************** -// GENERATED FILE - DO NOT EDIT BY HAND. See README.md -// *********************************************************** - -import ( - "net/url" - "time" - - "github.com/huin/goupnp" - "github.com/huin/goupnp/soap" -) - -// Hack to avoid Go complaining if time isn't used. -var _ time.Time - -// Device URNs: -const ( - URN_LANDevice_1 = "urn:schemas-upnp-org:device:LANDevice:1" - URN_WANConnectionDevice_1 = "urn:schemas-upnp-org:device:WANConnectionDevice:1" - URN_WANConnectionDevice_2 = "urn:schemas-upnp-org:device:WANConnectionDevice:2" - URN_WANDevice_1 = "urn:schemas-upnp-org:device:WANDevice:1" - URN_WANDevice_2 = "urn:schemas-upnp-org:device:WANDevice:2" -) - -// Service URNs: -const ( - URN_DeviceProtection_1 = "urn:schemas-upnp-org:service:DeviceProtection:1" - URN_LANHostConfigManagement_1 = "urn:schemas-upnp-org:service:LANHostConfigManagement:1" - URN_Layer3Forwarding_1 = "urn:schemas-upnp-org:service:Layer3Forwarding:1" - URN_WANCableLinkConfig_1 = "urn:schemas-upnp-org:service:WANCableLinkConfig:1" - URN_WANCommonInterfaceConfig_1 = "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1" - URN_WANDSLLinkConfig_1 = "urn:schemas-upnp-org:service:WANDSLLinkConfig:1" - URN_WANEthernetLinkConfig_1 = "urn:schemas-upnp-org:service:WANEthernetLinkConfig:1" - URN_WANIPConnection_1 = "urn:schemas-upnp-org:service:WANIPConnection:1" - URN_WANIPConnection_2 = "urn:schemas-upnp-org:service:WANIPConnection:2" - URN_WANIPv6FirewallControl_1 = "urn:schemas-upnp-org:service:WANIPv6FirewallControl:1" - URN_WANPOTSLinkConfig_1 = "urn:schemas-upnp-org:service:WANPOTSLinkConfig:1" - URN_WANPPPConnection_1 = "urn:schemas-upnp-org:service:WANPPPConnection:1" -) - -// DeviceProtection1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:DeviceProtection:1". See -// goupnp.ServiceClient, which contains RootDevice and Service attributes which -// are provided for informational value. -type DeviceProtection1 struct { - goupnp.ServiceClient -} - -// NewDeviceProtection1Clients discovers instances of the service on the network, -// and returns clients to any that are found. errors will contain an error for -// any devices that replied but which could not be queried, and err will be set -// if the discovery process failed outright. -// -// This is a typical entry calling point into this package. -func NewDeviceProtection1Clients() (clients []*DeviceProtection1, errors []error, err error) { - var genericClients []goupnp.ServiceClient - if genericClients, errors, err = goupnp.NewServiceClients(URN_DeviceProtection_1); err != nil { - return - } - clients = newDeviceProtection1ClientsFromGenericClients(genericClients) - return -} - -// NewDeviceProtection1ClientsByURL discovers instances of the service at the given -// URL, and returns clients to any that are found. An error is returned if -// there was an error probing the service. -// -// This is a typical entry calling point into this package when reusing an -// previously discovered service URL. -func NewDeviceProtection1ClientsByURL(loc *url.URL) ([]*DeviceProtection1, error) { - genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_DeviceProtection_1) - if err != nil { - return nil, err - } - return newDeviceProtection1ClientsFromGenericClients(genericClients), nil -} - -// NewDeviceProtection1ClientsFromRootDevice discovers instances of the service in -// a given root device, and returns clients to any that are found. An error is -// returned if there was not at least one instance of the service within the -// device. The location parameter is simply assigned to the Location attribute -// of the wrapped ServiceClient(s). -// -// This is a typical entry calling point into this package when reusing an -// previously discovered root device. -func NewDeviceProtection1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*DeviceProtection1, error) { - genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_DeviceProtection_1) - if err != nil { - return nil, err - } - return newDeviceProtection1ClientsFromGenericClients(genericClients), nil -} - -func newDeviceProtection1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*DeviceProtection1 { - clients := make([]*DeviceProtection1, len(genericClients)) - for i := range genericClients { - clients[i] = &DeviceProtection1{genericClients[i]} - } - return clients -} - -func (client *DeviceProtection1) SendSetupMessage(ProtocolType string, InMessage []byte) (OutMessage []byte, err error) { - // Request structure. - request := &struct { - ProtocolType string - InMessage string - }{} - // BEGIN Marshal arguments into request. - - if request.ProtocolType, err = soap.MarshalString(ProtocolType); err != nil { - return - } - if request.InMessage, err = soap.MarshalBinBase64(InMessage); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := &struct { - OutMessage string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_DeviceProtection_1, "SendSetupMessage", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if OutMessage, err = soap.UnmarshalBinBase64(response.OutMessage); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *DeviceProtection1) GetSupportedProtocols() (ProtocolList string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - ProtocolList string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_DeviceProtection_1, "GetSupportedProtocols", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if ProtocolList, err = soap.UnmarshalString(response.ProtocolList); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *DeviceProtection1) GetAssignedRoles() (RoleList string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - RoleList string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_DeviceProtection_1, "GetAssignedRoles", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if RoleList, err = soap.UnmarshalString(response.RoleList); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *DeviceProtection1) GetRolesForAction(DeviceUDN string, ServiceId string, ActionName string) (RoleList string, RestrictedRoleList string, err error) { - // Request structure. - request := &struct { - DeviceUDN string - ServiceId string - ActionName string - }{} - // BEGIN Marshal arguments into request. - - if request.DeviceUDN, err = soap.MarshalString(DeviceUDN); err != nil { - return - } - if request.ServiceId, err = soap.MarshalString(ServiceId); err != nil { - return - } - if request.ActionName, err = soap.MarshalString(ActionName); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := &struct { - RoleList string - RestrictedRoleList string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_DeviceProtection_1, "GetRolesForAction", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if RoleList, err = soap.UnmarshalString(response.RoleList); err != nil { - return - } - if RestrictedRoleList, err = soap.UnmarshalString(response.RestrictedRoleList); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *DeviceProtection1) GetUserLoginChallenge(ProtocolType string, Name string) (Salt []byte, Challenge []byte, err error) { - // Request structure. - request := &struct { - ProtocolType string - Name string - }{} - // BEGIN Marshal arguments into request. - - if request.ProtocolType, err = soap.MarshalString(ProtocolType); err != nil { - return - } - if request.Name, err = soap.MarshalString(Name); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := &struct { - Salt string - Challenge string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_DeviceProtection_1, "GetUserLoginChallenge", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if Salt, err = soap.UnmarshalBinBase64(response.Salt); err != nil { - return - } - if Challenge, err = soap.UnmarshalBinBase64(response.Challenge); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *DeviceProtection1) UserLogin(ProtocolType string, Challenge []byte, Authenticator []byte) (err error) { - // Request structure. - request := &struct { - ProtocolType string - Challenge string - Authenticator string - }{} - // BEGIN Marshal arguments into request. - - if request.ProtocolType, err = soap.MarshalString(ProtocolType); err != nil { - return - } - if request.Challenge, err = soap.MarshalBinBase64(Challenge); err != nil { - return - } - if request.Authenticator, err = soap.MarshalBinBase64(Authenticator); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_DeviceProtection_1, "UserLogin", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *DeviceProtection1) UserLogout() (err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_DeviceProtection_1, "UserLogout", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *DeviceProtection1) GetACLData() (ACL string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - ACL string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_DeviceProtection_1, "GetACLData", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if ACL, err = soap.UnmarshalString(response.ACL); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *DeviceProtection1) AddIdentityList(IdentityList string) (IdentityListResult string, err error) { - // Request structure. - request := &struct { - IdentityList string - }{} - // BEGIN Marshal arguments into request. - - if request.IdentityList, err = soap.MarshalString(IdentityList); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := &struct { - IdentityListResult string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_DeviceProtection_1, "AddIdentityList", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if IdentityListResult, err = soap.UnmarshalString(response.IdentityListResult); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *DeviceProtection1) RemoveIdentity(Identity string) (err error) { - // Request structure. - request := &struct { - Identity string - }{} - // BEGIN Marshal arguments into request. - - if request.Identity, err = soap.MarshalString(Identity); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_DeviceProtection_1, "RemoveIdentity", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *DeviceProtection1) SetUserLoginPassword(ProtocolType string, Name string, Stored []byte, Salt []byte) (err error) { - // Request structure. - request := &struct { - ProtocolType string - Name string - Stored string - Salt string - }{} - // BEGIN Marshal arguments into request. - - if request.ProtocolType, err = soap.MarshalString(ProtocolType); err != nil { - return - } - if request.Name, err = soap.MarshalString(Name); err != nil { - return - } - if request.Stored, err = soap.MarshalBinBase64(Stored); err != nil { - return - } - if request.Salt, err = soap.MarshalBinBase64(Salt); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_DeviceProtection_1, "SetUserLoginPassword", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *DeviceProtection1) AddRolesForIdentity(Identity string, RoleList string) (err error) { - // Request structure. - request := &struct { - Identity string - RoleList string - }{} - // BEGIN Marshal arguments into request. - - if request.Identity, err = soap.MarshalString(Identity); err != nil { - return - } - if request.RoleList, err = soap.MarshalString(RoleList); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_DeviceProtection_1, "AddRolesForIdentity", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *DeviceProtection1) RemoveRolesForIdentity(Identity string, RoleList string) (err error) { - // Request structure. - request := &struct { - Identity string - RoleList string - }{} - // BEGIN Marshal arguments into request. - - if request.Identity, err = soap.MarshalString(Identity); err != nil { - return - } - if request.RoleList, err = soap.MarshalString(RoleList); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_DeviceProtection_1, "RemoveRolesForIdentity", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -// LANHostConfigManagement1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:LANHostConfigManagement:1". See -// goupnp.ServiceClient, which contains RootDevice and Service attributes which -// are provided for informational value. -type LANHostConfigManagement1 struct { - goupnp.ServiceClient -} - -// NewLANHostConfigManagement1Clients discovers instances of the service on the network, -// and returns clients to any that are found. errors will contain an error for -// any devices that replied but which could not be queried, and err will be set -// if the discovery process failed outright. -// -// This is a typical entry calling point into this package. -func NewLANHostConfigManagement1Clients() (clients []*LANHostConfigManagement1, errors []error, err error) { - var genericClients []goupnp.ServiceClient - if genericClients, errors, err = goupnp.NewServiceClients(URN_LANHostConfigManagement_1); err != nil { - return - } - clients = newLANHostConfigManagement1ClientsFromGenericClients(genericClients) - return -} - -// NewLANHostConfigManagement1ClientsByURL discovers instances of the service at the given -// URL, and returns clients to any that are found. An error is returned if -// there was an error probing the service. -// -// This is a typical entry calling point into this package when reusing an -// previously discovered service URL. -func NewLANHostConfigManagement1ClientsByURL(loc *url.URL) ([]*LANHostConfigManagement1, error) { - genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_LANHostConfigManagement_1) - if err != nil { - return nil, err - } - return newLANHostConfigManagement1ClientsFromGenericClients(genericClients), nil -} - -// NewLANHostConfigManagement1ClientsFromRootDevice discovers instances of the service in -// a given root device, and returns clients to any that are found. An error is -// returned if there was not at least one instance of the service within the -// device. The location parameter is simply assigned to the Location attribute -// of the wrapped ServiceClient(s). -// -// This is a typical entry calling point into this package when reusing an -// previously discovered root device. -func NewLANHostConfigManagement1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*LANHostConfigManagement1, error) { - genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_LANHostConfigManagement_1) - if err != nil { - return nil, err - } - return newLANHostConfigManagement1ClientsFromGenericClients(genericClients), nil -} - -func newLANHostConfigManagement1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*LANHostConfigManagement1 { - clients := make([]*LANHostConfigManagement1, len(genericClients)) - for i := range genericClients { - clients[i] = &LANHostConfigManagement1{genericClients[i]} - } - return clients -} - -func (client *LANHostConfigManagement1) SetDHCPServerConfigurable(NewDHCPServerConfigurable bool) (err error) { - // Request structure. - request := &struct { - NewDHCPServerConfigurable string - }{} - // BEGIN Marshal arguments into request. - - if request.NewDHCPServerConfigurable, err = soap.MarshalBoolean(NewDHCPServerConfigurable); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetDHCPServerConfigurable", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) GetDHCPServerConfigurable() (NewDHCPServerConfigurable bool, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewDHCPServerConfigurable string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetDHCPServerConfigurable", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewDHCPServerConfigurable, err = soap.UnmarshalBoolean(response.NewDHCPServerConfigurable); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) SetDHCPRelay(NewDHCPRelay bool) (err error) { - // Request structure. - request := &struct { - NewDHCPRelay string - }{} - // BEGIN Marshal arguments into request. - - if request.NewDHCPRelay, err = soap.MarshalBoolean(NewDHCPRelay); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetDHCPRelay", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) GetDHCPRelay() (NewDHCPRelay bool, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewDHCPRelay string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetDHCPRelay", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewDHCPRelay, err = soap.UnmarshalBoolean(response.NewDHCPRelay); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) SetSubnetMask(NewSubnetMask string) (err error) { - // Request structure. - request := &struct { - NewSubnetMask string - }{} - // BEGIN Marshal arguments into request. - - if request.NewSubnetMask, err = soap.MarshalString(NewSubnetMask); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetSubnetMask", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) GetSubnetMask() (NewSubnetMask string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewSubnetMask string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetSubnetMask", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewSubnetMask, err = soap.UnmarshalString(response.NewSubnetMask); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) SetIPRouter(NewIPRouters string) (err error) { - // Request structure. - request := &struct { - NewIPRouters string - }{} - // BEGIN Marshal arguments into request. - - if request.NewIPRouters, err = soap.MarshalString(NewIPRouters); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetIPRouter", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) DeleteIPRouter(NewIPRouters string) (err error) { - // Request structure. - request := &struct { - NewIPRouters string - }{} - // BEGIN Marshal arguments into request. - - if request.NewIPRouters, err = soap.MarshalString(NewIPRouters); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "DeleteIPRouter", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) GetIPRoutersList() (NewIPRouters string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewIPRouters string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetIPRoutersList", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewIPRouters, err = soap.UnmarshalString(response.NewIPRouters); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) SetDomainName(NewDomainName string) (err error) { - // Request structure. - request := &struct { - NewDomainName string - }{} - // BEGIN Marshal arguments into request. - - if request.NewDomainName, err = soap.MarshalString(NewDomainName); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetDomainName", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) GetDomainName() (NewDomainName string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewDomainName string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetDomainName", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewDomainName, err = soap.UnmarshalString(response.NewDomainName); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) SetAddressRange(NewMinAddress string, NewMaxAddress string) (err error) { - // Request structure. - request := &struct { - NewMinAddress string - NewMaxAddress string - }{} - // BEGIN Marshal arguments into request. - - if request.NewMinAddress, err = soap.MarshalString(NewMinAddress); err != nil { - return - } - if request.NewMaxAddress, err = soap.MarshalString(NewMaxAddress); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetAddressRange", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) GetAddressRange() (NewMinAddress string, NewMaxAddress string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewMinAddress string - NewMaxAddress string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetAddressRange", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewMinAddress, err = soap.UnmarshalString(response.NewMinAddress); err != nil { - return - } - if NewMaxAddress, err = soap.UnmarshalString(response.NewMaxAddress); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) SetReservedAddress(NewReservedAddresses string) (err error) { - // Request structure. - request := &struct { - NewReservedAddresses string - }{} - // BEGIN Marshal arguments into request. - - if request.NewReservedAddresses, err = soap.MarshalString(NewReservedAddresses); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetReservedAddress", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) DeleteReservedAddress(NewReservedAddresses string) (err error) { - // Request structure. - request := &struct { - NewReservedAddresses string - }{} - // BEGIN Marshal arguments into request. - - if request.NewReservedAddresses, err = soap.MarshalString(NewReservedAddresses); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "DeleteReservedAddress", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) GetReservedAddresses() (NewReservedAddresses string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewReservedAddresses string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetReservedAddresses", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewReservedAddresses, err = soap.UnmarshalString(response.NewReservedAddresses); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) SetDNSServer(NewDNSServers string) (err error) { - // Request structure. - request := &struct { - NewDNSServers string - }{} - // BEGIN Marshal arguments into request. - - if request.NewDNSServers, err = soap.MarshalString(NewDNSServers); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetDNSServer", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) DeleteDNSServer(NewDNSServers string) (err error) { - // Request structure. - request := &struct { - NewDNSServers string - }{} - // BEGIN Marshal arguments into request. - - if request.NewDNSServers, err = soap.MarshalString(NewDNSServers); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "DeleteDNSServer", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *LANHostConfigManagement1) GetDNSServers() (NewDNSServers string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewDNSServers string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetDNSServers", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewDNSServers, err = soap.UnmarshalString(response.NewDNSServers); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// Layer3Forwarding1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:Layer3Forwarding:1". See -// goupnp.ServiceClient, which contains RootDevice and Service attributes which -// are provided for informational value. -type Layer3Forwarding1 struct { - goupnp.ServiceClient -} - -// NewLayer3Forwarding1Clients discovers instances of the service on the network, -// and returns clients to any that are found. errors will contain an error for -// any devices that replied but which could not be queried, and err will be set -// if the discovery process failed outright. -// -// This is a typical entry calling point into this package. -func NewLayer3Forwarding1Clients() (clients []*Layer3Forwarding1, errors []error, err error) { - var genericClients []goupnp.ServiceClient - if genericClients, errors, err = goupnp.NewServiceClients(URN_Layer3Forwarding_1); err != nil { - return - } - clients = newLayer3Forwarding1ClientsFromGenericClients(genericClients) - return -} - -// NewLayer3Forwarding1ClientsByURL discovers instances of the service at the given -// URL, and returns clients to any that are found. An error is returned if -// there was an error probing the service. -// -// This is a typical entry calling point into this package when reusing an -// previously discovered service URL. -func NewLayer3Forwarding1ClientsByURL(loc *url.URL) ([]*Layer3Forwarding1, error) { - genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_Layer3Forwarding_1) - if err != nil { - return nil, err - } - return newLayer3Forwarding1ClientsFromGenericClients(genericClients), nil -} - -// NewLayer3Forwarding1ClientsFromRootDevice discovers instances of the service in -// a given root device, and returns clients to any that are found. An error is -// returned if there was not at least one instance of the service within the -// device. The location parameter is simply assigned to the Location attribute -// of the wrapped ServiceClient(s). -// -// This is a typical entry calling point into this package when reusing an -// previously discovered root device. -func NewLayer3Forwarding1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*Layer3Forwarding1, error) { - genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_Layer3Forwarding_1) - if err != nil { - return nil, err - } - return newLayer3Forwarding1ClientsFromGenericClients(genericClients), nil -} - -func newLayer3Forwarding1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*Layer3Forwarding1 { - clients := make([]*Layer3Forwarding1, len(genericClients)) - for i := range genericClients { - clients[i] = &Layer3Forwarding1{genericClients[i]} - } - return clients -} - -func (client *Layer3Forwarding1) SetDefaultConnectionService(NewDefaultConnectionService string) (err error) { - // Request structure. - request := &struct { - NewDefaultConnectionService string - }{} - // BEGIN Marshal arguments into request. - - if request.NewDefaultConnectionService, err = soap.MarshalString(NewDefaultConnectionService); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_Layer3Forwarding_1, "SetDefaultConnectionService", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *Layer3Forwarding1) GetDefaultConnectionService() (NewDefaultConnectionService string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewDefaultConnectionService string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_Layer3Forwarding_1, "GetDefaultConnectionService", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewDefaultConnectionService, err = soap.UnmarshalString(response.NewDefaultConnectionService); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// WANCableLinkConfig1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANCableLinkConfig:1". See -// goupnp.ServiceClient, which contains RootDevice and Service attributes which -// are provided for informational value. -type WANCableLinkConfig1 struct { - goupnp.ServiceClient -} - -// NewWANCableLinkConfig1Clients discovers instances of the service on the network, -// and returns clients to any that are found. errors will contain an error for -// any devices that replied but which could not be queried, and err will be set -// if the discovery process failed outright. -// -// This is a typical entry calling point into this package. -func NewWANCableLinkConfig1Clients() (clients []*WANCableLinkConfig1, errors []error, err error) { - var genericClients []goupnp.ServiceClient - if genericClients, errors, err = goupnp.NewServiceClients(URN_WANCableLinkConfig_1); err != nil { - return - } - clients = newWANCableLinkConfig1ClientsFromGenericClients(genericClients) - return -} - -// NewWANCableLinkConfig1ClientsByURL discovers instances of the service at the given -// URL, and returns clients to any that are found. An error is returned if -// there was an error probing the service. -// -// This is a typical entry calling point into this package when reusing an -// previously discovered service URL. -func NewWANCableLinkConfig1ClientsByURL(loc *url.URL) ([]*WANCableLinkConfig1, error) { - genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANCableLinkConfig_1) - if err != nil { - return nil, err - } - return newWANCableLinkConfig1ClientsFromGenericClients(genericClients), nil -} - -// NewWANCableLinkConfig1ClientsFromRootDevice discovers instances of the service in -// a given root device, and returns clients to any that are found. An error is -// returned if there was not at least one instance of the service within the -// device. The location parameter is simply assigned to the Location attribute -// of the wrapped ServiceClient(s). -// -// This is a typical entry calling point into this package when reusing an -// previously discovered root device. -func NewWANCableLinkConfig1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANCableLinkConfig1, error) { - genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANCableLinkConfig_1) - if err != nil { - return nil, err - } - return newWANCableLinkConfig1ClientsFromGenericClients(genericClients), nil -} - -func newWANCableLinkConfig1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANCableLinkConfig1 { - clients := make([]*WANCableLinkConfig1, len(genericClients)) - for i := range genericClients { - clients[i] = &WANCableLinkConfig1{genericClients[i]} - } - return clients -} - -// -// Return values: -// -// * NewCableLinkConfigState: allowed values: notReady, dsSyncComplete, usParamAcquired, rangingComplete, ipComplete, todEstablished, paramTransferComplete, registrationComplete, operational, accessDenied -// -// * NewLinkType: allowed values: Ethernet -func (client *WANCableLinkConfig1) GetCableLinkConfigInfo() (NewCableLinkConfigState string, NewLinkType string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewCableLinkConfigState string - NewLinkType string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetCableLinkConfigInfo", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewCableLinkConfigState, err = soap.UnmarshalString(response.NewCableLinkConfigState); err != nil { - return - } - if NewLinkType, err = soap.UnmarshalString(response.NewLinkType); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANCableLinkConfig1) GetDownstreamFrequency() (NewDownstreamFrequency uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewDownstreamFrequency string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetDownstreamFrequency", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewDownstreamFrequency, err = soap.UnmarshalUi4(response.NewDownstreamFrequency); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// -// Return values: -// -// * NewDownstreamModulation: allowed values: 64QAM, 256QAM -func (client *WANCableLinkConfig1) GetDownstreamModulation() (NewDownstreamModulation string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewDownstreamModulation string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetDownstreamModulation", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewDownstreamModulation, err = soap.UnmarshalString(response.NewDownstreamModulation); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANCableLinkConfig1) GetUpstreamFrequency() (NewUpstreamFrequency uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewUpstreamFrequency string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetUpstreamFrequency", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewUpstreamFrequency, err = soap.UnmarshalUi4(response.NewUpstreamFrequency); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// -// Return values: -// -// * NewUpstreamModulation: allowed values: QPSK, 16QAM -func (client *WANCableLinkConfig1) GetUpstreamModulation() (NewUpstreamModulation string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewUpstreamModulation string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetUpstreamModulation", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewUpstreamModulation, err = soap.UnmarshalString(response.NewUpstreamModulation); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANCableLinkConfig1) GetUpstreamChannelID() (NewUpstreamChannelID uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewUpstreamChannelID string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetUpstreamChannelID", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewUpstreamChannelID, err = soap.UnmarshalUi4(response.NewUpstreamChannelID); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANCableLinkConfig1) GetUpstreamPowerLevel() (NewUpstreamPowerLevel uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewUpstreamPowerLevel string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetUpstreamPowerLevel", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewUpstreamPowerLevel, err = soap.UnmarshalUi4(response.NewUpstreamPowerLevel); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANCableLinkConfig1) GetBPIEncryptionEnabled() (NewBPIEncryptionEnabled bool, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewBPIEncryptionEnabled string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetBPIEncryptionEnabled", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewBPIEncryptionEnabled, err = soap.UnmarshalBoolean(response.NewBPIEncryptionEnabled); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANCableLinkConfig1) GetConfigFile() (NewConfigFile string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewConfigFile string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetConfigFile", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewConfigFile, err = soap.UnmarshalString(response.NewConfigFile); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANCableLinkConfig1) GetTFTPServer() (NewTFTPServer string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewTFTPServer string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetTFTPServer", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewTFTPServer, err = soap.UnmarshalString(response.NewTFTPServer); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// WANCommonInterfaceConfig1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1". See -// goupnp.ServiceClient, which contains RootDevice and Service attributes which -// are provided for informational value. -type WANCommonInterfaceConfig1 struct { - goupnp.ServiceClient -} - -// NewWANCommonInterfaceConfig1Clients discovers instances of the service on the network, -// and returns clients to any that are found. errors will contain an error for -// any devices that replied but which could not be queried, and err will be set -// if the discovery process failed outright. -// -// This is a typical entry calling point into this package. -func NewWANCommonInterfaceConfig1Clients() (clients []*WANCommonInterfaceConfig1, errors []error, err error) { - var genericClients []goupnp.ServiceClient - if genericClients, errors, err = goupnp.NewServiceClients(URN_WANCommonInterfaceConfig_1); err != nil { - return - } - clients = newWANCommonInterfaceConfig1ClientsFromGenericClients(genericClients) - return -} - -// NewWANCommonInterfaceConfig1ClientsByURL discovers instances of the service at the given -// URL, and returns clients to any that are found. An error is returned if -// there was an error probing the service. -// -// This is a typical entry calling point into this package when reusing an -// previously discovered service URL. -func NewWANCommonInterfaceConfig1ClientsByURL(loc *url.URL) ([]*WANCommonInterfaceConfig1, error) { - genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANCommonInterfaceConfig_1) - if err != nil { - return nil, err - } - return newWANCommonInterfaceConfig1ClientsFromGenericClients(genericClients), nil -} - -// NewWANCommonInterfaceConfig1ClientsFromRootDevice discovers instances of the service in -// a given root device, and returns clients to any that are found. An error is -// returned if there was not at least one instance of the service within the -// device. The location parameter is simply assigned to the Location attribute -// of the wrapped ServiceClient(s). -// -// This is a typical entry calling point into this package when reusing an -// previously discovered root device. -func NewWANCommonInterfaceConfig1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANCommonInterfaceConfig1, error) { - genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANCommonInterfaceConfig_1) - if err != nil { - return nil, err - } - return newWANCommonInterfaceConfig1ClientsFromGenericClients(genericClients), nil -} - -func newWANCommonInterfaceConfig1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANCommonInterfaceConfig1 { - clients := make([]*WANCommonInterfaceConfig1, len(genericClients)) - for i := range genericClients { - clients[i] = &WANCommonInterfaceConfig1{genericClients[i]} - } - return clients -} - -func (client *WANCommonInterfaceConfig1) SetEnabledForInternet(NewEnabledForInternet bool) (err error) { - // Request structure. - request := &struct { - NewEnabledForInternet string - }{} - // BEGIN Marshal arguments into request. - - if request.NewEnabledForInternet, err = soap.MarshalBoolean(NewEnabledForInternet); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "SetEnabledForInternet", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANCommonInterfaceConfig1) GetEnabledForInternet() (NewEnabledForInternet bool, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewEnabledForInternet string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetEnabledForInternet", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewEnabledForInternet, err = soap.UnmarshalBoolean(response.NewEnabledForInternet); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// -// Return values: -// -// * NewWANAccessType: allowed values: DSL, POTS, Cable, Ethernet -// -// * NewPhysicalLinkStatus: allowed values: Up, Down -func (client *WANCommonInterfaceConfig1) GetCommonLinkProperties() (NewWANAccessType string, NewLayer1UpstreamMaxBitRate uint32, NewLayer1DownstreamMaxBitRate uint32, NewPhysicalLinkStatus string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewWANAccessType string - NewLayer1UpstreamMaxBitRate string - NewLayer1DownstreamMaxBitRate string - NewPhysicalLinkStatus string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetCommonLinkProperties", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewWANAccessType, err = soap.UnmarshalString(response.NewWANAccessType); err != nil { - return - } - if NewLayer1UpstreamMaxBitRate, err = soap.UnmarshalUi4(response.NewLayer1UpstreamMaxBitRate); err != nil { - return - } - if NewLayer1DownstreamMaxBitRate, err = soap.UnmarshalUi4(response.NewLayer1DownstreamMaxBitRate); err != nil { - return - } - if NewPhysicalLinkStatus, err = soap.UnmarshalString(response.NewPhysicalLinkStatus); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANCommonInterfaceConfig1) GetWANAccessProvider() (NewWANAccessProvider string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewWANAccessProvider string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetWANAccessProvider", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewWANAccessProvider, err = soap.UnmarshalString(response.NewWANAccessProvider); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// -// Return values: -// -// * NewMaximumActiveConnections: allowed value range: minimum=1, step=1 -func (client *WANCommonInterfaceConfig1) GetMaximumActiveConnections() (NewMaximumActiveConnections uint16, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewMaximumActiveConnections string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetMaximumActiveConnections", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewMaximumActiveConnections, err = soap.UnmarshalUi2(response.NewMaximumActiveConnections); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANCommonInterfaceConfig1) GetTotalBytesSent() (NewTotalBytesSent uint64, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewTotalBytesSent string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetTotalBytesSent", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewTotalBytesSent, err = soap.UnmarshalUi8(response.NewTotalBytesSent); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANCommonInterfaceConfig1) GetTotalBytesReceived() (NewTotalBytesReceived uint64, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewTotalBytesReceived string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetTotalBytesReceived", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewTotalBytesReceived, err = soap.UnmarshalUi8(response.NewTotalBytesReceived); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANCommonInterfaceConfig1) GetTotalPacketsSent() (NewTotalPacketsSent uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewTotalPacketsSent string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetTotalPacketsSent", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewTotalPacketsSent, err = soap.UnmarshalUi4(response.NewTotalPacketsSent); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANCommonInterfaceConfig1) GetTotalPacketsReceived() (NewTotalPacketsReceived uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewTotalPacketsReceived string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetTotalPacketsReceived", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewTotalPacketsReceived, err = soap.UnmarshalUi4(response.NewTotalPacketsReceived); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANCommonInterfaceConfig1) GetActiveConnection(NewActiveConnectionIndex uint16) (NewActiveConnDeviceContainer string, NewActiveConnectionServiceID string, err error) { - // Request structure. - request := &struct { - NewActiveConnectionIndex string - }{} - // BEGIN Marshal arguments into request. - - if request.NewActiveConnectionIndex, err = soap.MarshalUi2(NewActiveConnectionIndex); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewActiveConnDeviceContainer string - NewActiveConnectionServiceID string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetActiveConnection", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewActiveConnDeviceContainer, err = soap.UnmarshalString(response.NewActiveConnDeviceContainer); err != nil { - return - } - if NewActiveConnectionServiceID, err = soap.UnmarshalString(response.NewActiveConnectionServiceID); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// WANDSLLinkConfig1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANDSLLinkConfig:1". See -// goupnp.ServiceClient, which contains RootDevice and Service attributes which -// are provided for informational value. -type WANDSLLinkConfig1 struct { - goupnp.ServiceClient -} - -// NewWANDSLLinkConfig1Clients discovers instances of the service on the network, -// and returns clients to any that are found. errors will contain an error for -// any devices that replied but which could not be queried, and err will be set -// if the discovery process failed outright. -// -// This is a typical entry calling point into this package. -func NewWANDSLLinkConfig1Clients() (clients []*WANDSLLinkConfig1, errors []error, err error) { - var genericClients []goupnp.ServiceClient - if genericClients, errors, err = goupnp.NewServiceClients(URN_WANDSLLinkConfig_1); err != nil { - return - } - clients = newWANDSLLinkConfig1ClientsFromGenericClients(genericClients) - return -} - -// NewWANDSLLinkConfig1ClientsByURL discovers instances of the service at the given -// URL, and returns clients to any that are found. An error is returned if -// there was an error probing the service. -// -// This is a typical entry calling point into this package when reusing an -// previously discovered service URL. -func NewWANDSLLinkConfig1ClientsByURL(loc *url.URL) ([]*WANDSLLinkConfig1, error) { - genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANDSLLinkConfig_1) - if err != nil { - return nil, err - } - return newWANDSLLinkConfig1ClientsFromGenericClients(genericClients), nil -} - -// NewWANDSLLinkConfig1ClientsFromRootDevice discovers instances of the service in -// a given root device, and returns clients to any that are found. An error is -// returned if there was not at least one instance of the service within the -// device. The location parameter is simply assigned to the Location attribute -// of the wrapped ServiceClient(s). -// -// This is a typical entry calling point into this package when reusing an -// previously discovered root device. -func NewWANDSLLinkConfig1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANDSLLinkConfig1, error) { - genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANDSLLinkConfig_1) - if err != nil { - return nil, err - } - return newWANDSLLinkConfig1ClientsFromGenericClients(genericClients), nil -} - -func newWANDSLLinkConfig1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANDSLLinkConfig1 { - clients := make([]*WANDSLLinkConfig1, len(genericClients)) - for i := range genericClients { - clients[i] = &WANDSLLinkConfig1{genericClients[i]} - } - return clients -} - -func (client *WANDSLLinkConfig1) SetDSLLinkType(NewLinkType string) (err error) { - // Request structure. - request := &struct { - NewLinkType string - }{} - // BEGIN Marshal arguments into request. - - if request.NewLinkType, err = soap.MarshalString(NewLinkType); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "SetDSLLinkType", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -// -// Return values: -// -// * NewLinkStatus: allowed values: Up, Down -func (client *WANDSLLinkConfig1) GetDSLLinkInfo() (NewLinkType string, NewLinkStatus string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewLinkType string - NewLinkStatus string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "GetDSLLinkInfo", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewLinkType, err = soap.UnmarshalString(response.NewLinkType); err != nil { - return - } - if NewLinkStatus, err = soap.UnmarshalString(response.NewLinkStatus); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANDSLLinkConfig1) GetAutoConfig() (NewAutoConfig bool, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewAutoConfig string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "GetAutoConfig", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewAutoConfig, err = soap.UnmarshalBoolean(response.NewAutoConfig); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANDSLLinkConfig1) GetModulationType() (NewModulationType string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewModulationType string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "GetModulationType", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewModulationType, err = soap.UnmarshalString(response.NewModulationType); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANDSLLinkConfig1) SetDestinationAddress(NewDestinationAddress string) (err error) { - // Request structure. - request := &struct { - NewDestinationAddress string - }{} - // BEGIN Marshal arguments into request. - - if request.NewDestinationAddress, err = soap.MarshalString(NewDestinationAddress); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "SetDestinationAddress", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANDSLLinkConfig1) GetDestinationAddress() (NewDestinationAddress string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewDestinationAddress string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "GetDestinationAddress", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewDestinationAddress, err = soap.UnmarshalString(response.NewDestinationAddress); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANDSLLinkConfig1) SetATMEncapsulation(NewATMEncapsulation string) (err error) { - // Request structure. - request := &struct { - NewATMEncapsulation string - }{} - // BEGIN Marshal arguments into request. - - if request.NewATMEncapsulation, err = soap.MarshalString(NewATMEncapsulation); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "SetATMEncapsulation", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANDSLLinkConfig1) GetATMEncapsulation() (NewATMEncapsulation string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewATMEncapsulation string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "GetATMEncapsulation", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewATMEncapsulation, err = soap.UnmarshalString(response.NewATMEncapsulation); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANDSLLinkConfig1) SetFCSPreserved(NewFCSPreserved bool) (err error) { - // Request structure. - request := &struct { - NewFCSPreserved string - }{} - // BEGIN Marshal arguments into request. - - if request.NewFCSPreserved, err = soap.MarshalBoolean(NewFCSPreserved); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "SetFCSPreserved", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANDSLLinkConfig1) GetFCSPreserved() (NewFCSPreserved bool, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewFCSPreserved string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "GetFCSPreserved", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewFCSPreserved, err = soap.UnmarshalBoolean(response.NewFCSPreserved); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// WANEthernetLinkConfig1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANEthernetLinkConfig:1". See -// goupnp.ServiceClient, which contains RootDevice and Service attributes which -// are provided for informational value. -type WANEthernetLinkConfig1 struct { - goupnp.ServiceClient -} - -// NewWANEthernetLinkConfig1Clients discovers instances of the service on the network, -// and returns clients to any that are found. errors will contain an error for -// any devices that replied but which could not be queried, and err will be set -// if the discovery process failed outright. -// -// This is a typical entry calling point into this package. -func NewWANEthernetLinkConfig1Clients() (clients []*WANEthernetLinkConfig1, errors []error, err error) { - var genericClients []goupnp.ServiceClient - if genericClients, errors, err = goupnp.NewServiceClients(URN_WANEthernetLinkConfig_1); err != nil { - return - } - clients = newWANEthernetLinkConfig1ClientsFromGenericClients(genericClients) - return -} - -// NewWANEthernetLinkConfig1ClientsByURL discovers instances of the service at the given -// URL, and returns clients to any that are found. An error is returned if -// there was an error probing the service. -// -// This is a typical entry calling point into this package when reusing an -// previously discovered service URL. -func NewWANEthernetLinkConfig1ClientsByURL(loc *url.URL) ([]*WANEthernetLinkConfig1, error) { - genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANEthernetLinkConfig_1) - if err != nil { - return nil, err - } - return newWANEthernetLinkConfig1ClientsFromGenericClients(genericClients), nil -} - -// NewWANEthernetLinkConfig1ClientsFromRootDevice discovers instances of the service in -// a given root device, and returns clients to any that are found. An error is -// returned if there was not at least one instance of the service within the -// device. The location parameter is simply assigned to the Location attribute -// of the wrapped ServiceClient(s). -// -// This is a typical entry calling point into this package when reusing an -// previously discovered root device. -func NewWANEthernetLinkConfig1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANEthernetLinkConfig1, error) { - genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANEthernetLinkConfig_1) - if err != nil { - return nil, err - } - return newWANEthernetLinkConfig1ClientsFromGenericClients(genericClients), nil -} - -func newWANEthernetLinkConfig1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANEthernetLinkConfig1 { - clients := make([]*WANEthernetLinkConfig1, len(genericClients)) - for i := range genericClients { - clients[i] = &WANEthernetLinkConfig1{genericClients[i]} - } - return clients -} - -// -// Return values: -// -// * NewEthernetLinkStatus: allowed values: Up, Down -func (client *WANEthernetLinkConfig1) GetEthernetLinkStatus() (NewEthernetLinkStatus string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewEthernetLinkStatus string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANEthernetLinkConfig_1, "GetEthernetLinkStatus", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewEthernetLinkStatus, err = soap.UnmarshalString(response.NewEthernetLinkStatus); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// WANIPConnection1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANIPConnection:1". See -// goupnp.ServiceClient, which contains RootDevice and Service attributes which -// are provided for informational value. -type WANIPConnection1 struct { - goupnp.ServiceClient -} - -// NewWANIPConnection1Clients discovers instances of the service on the network, -// and returns clients to any that are found. errors will contain an error for -// any devices that replied but which could not be queried, and err will be set -// if the discovery process failed outright. -// -// This is a typical entry calling point into this package. -func NewWANIPConnection1Clients() (clients []*WANIPConnection1, errors []error, err error) { - var genericClients []goupnp.ServiceClient - if genericClients, errors, err = goupnp.NewServiceClients(URN_WANIPConnection_1); err != nil { - return - } - clients = newWANIPConnection1ClientsFromGenericClients(genericClients) - return -} - -// NewWANIPConnection1ClientsByURL discovers instances of the service at the given -// URL, and returns clients to any that are found. An error is returned if -// there was an error probing the service. -// -// This is a typical entry calling point into this package when reusing an -// previously discovered service URL. -func NewWANIPConnection1ClientsByURL(loc *url.URL) ([]*WANIPConnection1, error) { - genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANIPConnection_1) - if err != nil { - return nil, err - } - return newWANIPConnection1ClientsFromGenericClients(genericClients), nil -} - -// NewWANIPConnection1ClientsFromRootDevice discovers instances of the service in -// a given root device, and returns clients to any that are found. An error is -// returned if there was not at least one instance of the service within the -// device. The location parameter is simply assigned to the Location attribute -// of the wrapped ServiceClient(s). -// -// This is a typical entry calling point into this package when reusing an -// previously discovered root device. -func NewWANIPConnection1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANIPConnection1, error) { - genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANIPConnection_1) - if err != nil { - return nil, err - } - return newWANIPConnection1ClientsFromGenericClients(genericClients), nil -} - -func newWANIPConnection1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANIPConnection1 { - clients := make([]*WANIPConnection1, len(genericClients)) - for i := range genericClients { - clients[i] = &WANIPConnection1{genericClients[i]} - } - return clients -} - -func (client *WANIPConnection1) SetConnectionType(NewConnectionType string) (err error) { - // Request structure. - request := &struct { - NewConnectionType string - }{} - // BEGIN Marshal arguments into request. - - if request.NewConnectionType, err = soap.MarshalString(NewConnectionType); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "SetConnectionType", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -// -// Return values: -// -// * NewPossibleConnectionTypes: allowed values: Unconfigured, IP_Routed, IP_Bridged -func (client *WANIPConnection1) GetConnectionTypeInfo() (NewConnectionType string, NewPossibleConnectionTypes string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewConnectionType string - NewPossibleConnectionTypes string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetConnectionTypeInfo", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewConnectionType, err = soap.UnmarshalString(response.NewConnectionType); err != nil { - return - } - if NewPossibleConnectionTypes, err = soap.UnmarshalString(response.NewPossibleConnectionTypes); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection1) RequestConnection() (err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "RequestConnection", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection1) RequestTermination() (err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "RequestTermination", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection1) ForceTermination() (err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "ForceTermination", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection1) SetAutoDisconnectTime(NewAutoDisconnectTime uint32) (err error) { - // Request structure. - request := &struct { - NewAutoDisconnectTime string - }{} - // BEGIN Marshal arguments into request. - - if request.NewAutoDisconnectTime, err = soap.MarshalUi4(NewAutoDisconnectTime); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "SetAutoDisconnectTime", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection1) SetIdleDisconnectTime(NewIdleDisconnectTime uint32) (err error) { - // Request structure. - request := &struct { - NewIdleDisconnectTime string - }{} - // BEGIN Marshal arguments into request. - - if request.NewIdleDisconnectTime, err = soap.MarshalUi4(NewIdleDisconnectTime); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "SetIdleDisconnectTime", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection1) SetWarnDisconnectDelay(NewWarnDisconnectDelay uint32) (err error) { - // Request structure. - request := &struct { - NewWarnDisconnectDelay string - }{} - // BEGIN Marshal arguments into request. - - if request.NewWarnDisconnectDelay, err = soap.MarshalUi4(NewWarnDisconnectDelay); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "SetWarnDisconnectDelay", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -// -// Return values: -// -// * NewConnectionStatus: allowed values: Unconfigured, Connected, Disconnected -// -// * NewLastConnectionError: allowed values: ERROR_NONE -func (client *WANIPConnection1) GetStatusInfo() (NewConnectionStatus string, NewLastConnectionError string, NewUptime uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewConnectionStatus string - NewLastConnectionError string - NewUptime string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetStatusInfo", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewConnectionStatus, err = soap.UnmarshalString(response.NewConnectionStatus); err != nil { - return - } - if NewLastConnectionError, err = soap.UnmarshalString(response.NewLastConnectionError); err != nil { - return - } - if NewUptime, err = soap.UnmarshalUi4(response.NewUptime); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection1) GetAutoDisconnectTime() (NewAutoDisconnectTime uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewAutoDisconnectTime string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetAutoDisconnectTime", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewAutoDisconnectTime, err = soap.UnmarshalUi4(response.NewAutoDisconnectTime); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection1) GetIdleDisconnectTime() (NewIdleDisconnectTime uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewIdleDisconnectTime string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetIdleDisconnectTime", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewIdleDisconnectTime, err = soap.UnmarshalUi4(response.NewIdleDisconnectTime); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection1) GetWarnDisconnectDelay() (NewWarnDisconnectDelay uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewWarnDisconnectDelay string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetWarnDisconnectDelay", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewWarnDisconnectDelay, err = soap.UnmarshalUi4(response.NewWarnDisconnectDelay); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection1) GetNATRSIPStatus() (NewRSIPAvailable bool, NewNATEnabled bool, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewRSIPAvailable string - NewNATEnabled string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetNATRSIPStatus", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewRSIPAvailable, err = soap.UnmarshalBoolean(response.NewRSIPAvailable); err != nil { - return - } - if NewNATEnabled, err = soap.UnmarshalBoolean(response.NewNATEnabled); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// -// Return values: -// -// * NewProtocol: allowed values: TCP, UDP -func (client *WANIPConnection1) GetGenericPortMappingEntry(NewPortMappingIndex uint16) (NewRemoteHost string, NewExternalPort uint16, NewProtocol string, NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32, err error) { - // Request structure. - request := &struct { - NewPortMappingIndex string - }{} - // BEGIN Marshal arguments into request. - - if request.NewPortMappingIndex, err = soap.MarshalUi2(NewPortMappingIndex); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewRemoteHost string - NewExternalPort string - NewProtocol string - NewInternalPort string - NewInternalClient string - NewEnabled string - NewPortMappingDescription string - NewLeaseDuration string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetGenericPortMappingEntry", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewRemoteHost, err = soap.UnmarshalString(response.NewRemoteHost); err != nil { - return - } - if NewExternalPort, err = soap.UnmarshalUi2(response.NewExternalPort); err != nil { - return - } - if NewProtocol, err = soap.UnmarshalString(response.NewProtocol); err != nil { - return - } - if NewInternalPort, err = soap.UnmarshalUi2(response.NewInternalPort); err != nil { - return - } - if NewInternalClient, err = soap.UnmarshalString(response.NewInternalClient); err != nil { - return - } - if NewEnabled, err = soap.UnmarshalBoolean(response.NewEnabled); err != nil { - return - } - if NewPortMappingDescription, err = soap.UnmarshalString(response.NewPortMappingDescription); err != nil { - return - } - if NewLeaseDuration, err = soap.UnmarshalUi4(response.NewLeaseDuration); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// -// Arguments: -// -// * NewProtocol: allowed values: TCP, UDP - -func (client *WANIPConnection1) GetSpecificPortMappingEntry(NewRemoteHost string, NewExternalPort uint16, NewProtocol string) (NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32, err error) { - // Request structure. - request := &struct { - NewRemoteHost string - NewExternalPort string - NewProtocol string - }{} - // BEGIN Marshal arguments into request. - - if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil { - return - } - if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil { - return - } - if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewInternalPort string - NewInternalClient string - NewEnabled string - NewPortMappingDescription string - NewLeaseDuration string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetSpecificPortMappingEntry", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewInternalPort, err = soap.UnmarshalUi2(response.NewInternalPort); err != nil { - return - } - if NewInternalClient, err = soap.UnmarshalString(response.NewInternalClient); err != nil { - return - } - if NewEnabled, err = soap.UnmarshalBoolean(response.NewEnabled); err != nil { - return - } - if NewPortMappingDescription, err = soap.UnmarshalString(response.NewPortMappingDescription); err != nil { - return - } - if NewLeaseDuration, err = soap.UnmarshalUi4(response.NewLeaseDuration); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// -// Arguments: -// -// * NewProtocol: allowed values: TCP, UDP - -func (client *WANIPConnection1) AddPortMapping(NewRemoteHost string, NewExternalPort uint16, NewProtocol string, NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32) (err error) { - // Request structure. - request := &struct { - NewRemoteHost string - NewExternalPort string - NewProtocol string - NewInternalPort string - NewInternalClient string - NewEnabled string - NewPortMappingDescription string - NewLeaseDuration string - }{} - // BEGIN Marshal arguments into request. - - if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil { - return - } - if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil { - return - } - if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil { - return - } - if request.NewInternalPort, err = soap.MarshalUi2(NewInternalPort); err != nil { - return - } - if request.NewInternalClient, err = soap.MarshalString(NewInternalClient); err != nil { - return - } - if request.NewEnabled, err = soap.MarshalBoolean(NewEnabled); err != nil { - return - } - if request.NewPortMappingDescription, err = soap.MarshalString(NewPortMappingDescription); err != nil { - return - } - if request.NewLeaseDuration, err = soap.MarshalUi4(NewLeaseDuration); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "AddPortMapping", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -// -// Arguments: -// -// * NewProtocol: allowed values: TCP, UDP - -func (client *WANIPConnection1) DeletePortMapping(NewRemoteHost string, NewExternalPort uint16, NewProtocol string) (err error) { - // Request structure. - request := &struct { - NewRemoteHost string - NewExternalPort string - NewProtocol string - }{} - // BEGIN Marshal arguments into request. - - if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil { - return - } - if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil { - return - } - if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "DeletePortMapping", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection1) GetExternalIPAddress() (NewExternalIPAddress string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewExternalIPAddress string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetExternalIPAddress", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewExternalIPAddress, err = soap.UnmarshalString(response.NewExternalIPAddress); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// WANIPConnection2 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANIPConnection:2". See -// goupnp.ServiceClient, which contains RootDevice and Service attributes which -// are provided for informational value. -type WANIPConnection2 struct { - goupnp.ServiceClient -} - -// NewWANIPConnection2Clients discovers instances of the service on the network, -// and returns clients to any that are found. errors will contain an error for -// any devices that replied but which could not be queried, and err will be set -// if the discovery process failed outright. -// -// This is a typical entry calling point into this package. -func NewWANIPConnection2Clients() (clients []*WANIPConnection2, errors []error, err error) { - var genericClients []goupnp.ServiceClient - if genericClients, errors, err = goupnp.NewServiceClients(URN_WANIPConnection_2); err != nil { - return - } - clients = newWANIPConnection2ClientsFromGenericClients(genericClients) - return -} - -// NewWANIPConnection2ClientsByURL discovers instances of the service at the given -// URL, and returns clients to any that are found. An error is returned if -// there was an error probing the service. -// -// This is a typical entry calling point into this package when reusing an -// previously discovered service URL. -func NewWANIPConnection2ClientsByURL(loc *url.URL) ([]*WANIPConnection2, error) { - genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANIPConnection_2) - if err != nil { - return nil, err - } - return newWANIPConnection2ClientsFromGenericClients(genericClients), nil -} - -// NewWANIPConnection2ClientsFromRootDevice discovers instances of the service in -// a given root device, and returns clients to any that are found. An error is -// returned if there was not at least one instance of the service within the -// device. The location parameter is simply assigned to the Location attribute -// of the wrapped ServiceClient(s). -// -// This is a typical entry calling point into this package when reusing an -// previously discovered root device. -func NewWANIPConnection2ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANIPConnection2, error) { - genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANIPConnection_2) - if err != nil { - return nil, err - } - return newWANIPConnection2ClientsFromGenericClients(genericClients), nil -} - -func newWANIPConnection2ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANIPConnection2 { - clients := make([]*WANIPConnection2, len(genericClients)) - for i := range genericClients { - clients[i] = &WANIPConnection2{genericClients[i]} - } - return clients -} - -func (client *WANIPConnection2) SetConnectionType(NewConnectionType string) (err error) { - // Request structure. - request := &struct { - NewConnectionType string - }{} - // BEGIN Marshal arguments into request. - - if request.NewConnectionType, err = soap.MarshalString(NewConnectionType); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "SetConnectionType", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection2) GetConnectionTypeInfo() (NewConnectionType string, NewPossibleConnectionTypes string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewConnectionType string - NewPossibleConnectionTypes string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "GetConnectionTypeInfo", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewConnectionType, err = soap.UnmarshalString(response.NewConnectionType); err != nil { - return - } - if NewPossibleConnectionTypes, err = soap.UnmarshalString(response.NewPossibleConnectionTypes); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection2) RequestConnection() (err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "RequestConnection", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection2) RequestTermination() (err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "RequestTermination", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection2) ForceTermination() (err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "ForceTermination", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection2) SetAutoDisconnectTime(NewAutoDisconnectTime uint32) (err error) { - // Request structure. - request := &struct { - NewAutoDisconnectTime string - }{} - // BEGIN Marshal arguments into request. - - if request.NewAutoDisconnectTime, err = soap.MarshalUi4(NewAutoDisconnectTime); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "SetAutoDisconnectTime", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection2) SetIdleDisconnectTime(NewIdleDisconnectTime uint32) (err error) { - // Request structure. - request := &struct { - NewIdleDisconnectTime string - }{} - // BEGIN Marshal arguments into request. - - if request.NewIdleDisconnectTime, err = soap.MarshalUi4(NewIdleDisconnectTime); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "SetIdleDisconnectTime", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection2) SetWarnDisconnectDelay(NewWarnDisconnectDelay uint32) (err error) { - // Request structure. - request := &struct { - NewWarnDisconnectDelay string - }{} - // BEGIN Marshal arguments into request. - - if request.NewWarnDisconnectDelay, err = soap.MarshalUi4(NewWarnDisconnectDelay); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "SetWarnDisconnectDelay", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -// -// Return values: -// -// * NewConnectionStatus: allowed values: Unconfigured, Connecting, Connected, PendingDisconnect, Disconnecting, Disconnected -// -// * NewLastConnectionError: allowed values: ERROR_NONE, ERROR_COMMAND_ABORTED, ERROR_NOT_ENABLED_FOR_INTERNET, ERROR_USER_DISCONNECT, ERROR_ISP_DISCONNECT, ERROR_IDLE_DISCONNECT, ERROR_FORCED_DISCONNECT, ERROR_NO_CARRIER, ERROR_IP_CONFIGURATION, ERROR_UNKNOWN -func (client *WANIPConnection2) GetStatusInfo() (NewConnectionStatus string, NewLastConnectionError string, NewUptime uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewConnectionStatus string - NewLastConnectionError string - NewUptime string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "GetStatusInfo", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewConnectionStatus, err = soap.UnmarshalString(response.NewConnectionStatus); err != nil { - return - } - if NewLastConnectionError, err = soap.UnmarshalString(response.NewLastConnectionError); err != nil { - return - } - if NewUptime, err = soap.UnmarshalUi4(response.NewUptime); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection2) GetAutoDisconnectTime() (NewAutoDisconnectTime uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewAutoDisconnectTime string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "GetAutoDisconnectTime", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewAutoDisconnectTime, err = soap.UnmarshalUi4(response.NewAutoDisconnectTime); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection2) GetIdleDisconnectTime() (NewIdleDisconnectTime uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewIdleDisconnectTime string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "GetIdleDisconnectTime", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewIdleDisconnectTime, err = soap.UnmarshalUi4(response.NewIdleDisconnectTime); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection2) GetWarnDisconnectDelay() (NewWarnDisconnectDelay uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewWarnDisconnectDelay string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "GetWarnDisconnectDelay", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewWarnDisconnectDelay, err = soap.UnmarshalUi4(response.NewWarnDisconnectDelay); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection2) GetNATRSIPStatus() (NewRSIPAvailable bool, NewNATEnabled bool, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewRSIPAvailable string - NewNATEnabled string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "GetNATRSIPStatus", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewRSIPAvailable, err = soap.UnmarshalBoolean(response.NewRSIPAvailable); err != nil { - return - } - if NewNATEnabled, err = soap.UnmarshalBoolean(response.NewNATEnabled); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// -// Return values: -// -// * NewProtocol: allowed values: TCP, UDP -func (client *WANIPConnection2) GetGenericPortMappingEntry(NewPortMappingIndex uint16) (NewRemoteHost string, NewExternalPort uint16, NewProtocol string, NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32, err error) { - // Request structure. - request := &struct { - NewPortMappingIndex string - }{} - // BEGIN Marshal arguments into request. - - if request.NewPortMappingIndex, err = soap.MarshalUi2(NewPortMappingIndex); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewRemoteHost string - NewExternalPort string - NewProtocol string - NewInternalPort string - NewInternalClient string - NewEnabled string - NewPortMappingDescription string - NewLeaseDuration string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "GetGenericPortMappingEntry", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewRemoteHost, err = soap.UnmarshalString(response.NewRemoteHost); err != nil { - return - } - if NewExternalPort, err = soap.UnmarshalUi2(response.NewExternalPort); err != nil { - return - } - if NewProtocol, err = soap.UnmarshalString(response.NewProtocol); err != nil { - return - } - if NewInternalPort, err = soap.UnmarshalUi2(response.NewInternalPort); err != nil { - return - } - if NewInternalClient, err = soap.UnmarshalString(response.NewInternalClient); err != nil { - return - } - if NewEnabled, err = soap.UnmarshalBoolean(response.NewEnabled); err != nil { - return - } - if NewPortMappingDescription, err = soap.UnmarshalString(response.NewPortMappingDescription); err != nil { - return - } - if NewLeaseDuration, err = soap.UnmarshalUi4(response.NewLeaseDuration); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// -// Arguments: -// -// * NewProtocol: allowed values: TCP, UDP - -func (client *WANIPConnection2) GetSpecificPortMappingEntry(NewRemoteHost string, NewExternalPort uint16, NewProtocol string) (NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32, err error) { - // Request structure. - request := &struct { - NewRemoteHost string - NewExternalPort string - NewProtocol string - }{} - // BEGIN Marshal arguments into request. - - if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil { - return - } - if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil { - return - } - if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewInternalPort string - NewInternalClient string - NewEnabled string - NewPortMappingDescription string - NewLeaseDuration string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "GetSpecificPortMappingEntry", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewInternalPort, err = soap.UnmarshalUi2(response.NewInternalPort); err != nil { - return - } - if NewInternalClient, err = soap.UnmarshalString(response.NewInternalClient); err != nil { - return - } - if NewEnabled, err = soap.UnmarshalBoolean(response.NewEnabled); err != nil { - return - } - if NewPortMappingDescription, err = soap.UnmarshalString(response.NewPortMappingDescription); err != nil { - return - } - if NewLeaseDuration, err = soap.UnmarshalUi4(response.NewLeaseDuration); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// -// Arguments: -// -// * NewProtocol: allowed values: TCP, UDP - -func (client *WANIPConnection2) AddPortMapping(NewRemoteHost string, NewExternalPort uint16, NewProtocol string, NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32) (err error) { - // Request structure. - request := &struct { - NewRemoteHost string - NewExternalPort string - NewProtocol string - NewInternalPort string - NewInternalClient string - NewEnabled string - NewPortMappingDescription string - NewLeaseDuration string - }{} - // BEGIN Marshal arguments into request. - - if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil { - return - } - if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil { - return - } - if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil { - return - } - if request.NewInternalPort, err = soap.MarshalUi2(NewInternalPort); err != nil { - return - } - if request.NewInternalClient, err = soap.MarshalString(NewInternalClient); err != nil { - return - } - if request.NewEnabled, err = soap.MarshalBoolean(NewEnabled); err != nil { - return - } - if request.NewPortMappingDescription, err = soap.MarshalString(NewPortMappingDescription); err != nil { - return - } - if request.NewLeaseDuration, err = soap.MarshalUi4(NewLeaseDuration); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "AddPortMapping", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -// -// Arguments: -// -// * NewProtocol: allowed values: TCP, UDP - -func (client *WANIPConnection2) DeletePortMapping(NewRemoteHost string, NewExternalPort uint16, NewProtocol string) (err error) { - // Request structure. - request := &struct { - NewRemoteHost string - NewExternalPort string - NewProtocol string - }{} - // BEGIN Marshal arguments into request. - - if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil { - return - } - if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil { - return - } - if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "DeletePortMapping", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -// -// Arguments: -// -// * NewProtocol: allowed values: TCP, UDP - -func (client *WANIPConnection2) DeletePortMappingRange(NewStartPort uint16, NewEndPort uint16, NewProtocol string, NewManage bool) (err error) { - // Request structure. - request := &struct { - NewStartPort string - NewEndPort string - NewProtocol string - NewManage string - }{} - // BEGIN Marshal arguments into request. - - if request.NewStartPort, err = soap.MarshalUi2(NewStartPort); err != nil { - return - } - if request.NewEndPort, err = soap.MarshalUi2(NewEndPort); err != nil { - return - } - if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil { - return - } - if request.NewManage, err = soap.MarshalBoolean(NewManage); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "DeletePortMappingRange", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANIPConnection2) GetExternalIPAddress() (NewExternalIPAddress string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewExternalIPAddress string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "GetExternalIPAddress", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewExternalIPAddress, err = soap.UnmarshalString(response.NewExternalIPAddress); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// -// Arguments: -// -// * NewProtocol: allowed values: TCP, UDP - -func (client *WANIPConnection2) GetListOfPortMappings(NewStartPort uint16, NewEndPort uint16, NewProtocol string, NewManage bool, NewNumberOfPorts uint16) (NewPortListing string, err error) { - // Request structure. - request := &struct { - NewStartPort string - NewEndPort string - NewProtocol string - NewManage string - NewNumberOfPorts string - }{} - // BEGIN Marshal arguments into request. - - if request.NewStartPort, err = soap.MarshalUi2(NewStartPort); err != nil { - return - } - if request.NewEndPort, err = soap.MarshalUi2(NewEndPort); err != nil { - return - } - if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil { - return - } - if request.NewManage, err = soap.MarshalBoolean(NewManage); err != nil { - return - } - if request.NewNumberOfPorts, err = soap.MarshalUi2(NewNumberOfPorts); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewPortListing string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "GetListOfPortMappings", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewPortListing, err = soap.UnmarshalString(response.NewPortListing); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// -// Arguments: -// -// * NewProtocol: allowed values: TCP, UDP - -func (client *WANIPConnection2) AddAnyPortMapping(NewRemoteHost string, NewExternalPort uint16, NewProtocol string, NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32) (NewReservedPort uint16, err error) { - // Request structure. - request := &struct { - NewRemoteHost string - NewExternalPort string - NewProtocol string - NewInternalPort string - NewInternalClient string - NewEnabled string - NewPortMappingDescription string - NewLeaseDuration string - }{} - // BEGIN Marshal arguments into request. - - if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil { - return - } - if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil { - return - } - if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil { - return - } - if request.NewInternalPort, err = soap.MarshalUi2(NewInternalPort); err != nil { - return - } - if request.NewInternalClient, err = soap.MarshalString(NewInternalClient); err != nil { - return - } - if request.NewEnabled, err = soap.MarshalBoolean(NewEnabled); err != nil { - return - } - if request.NewPortMappingDescription, err = soap.MarshalString(NewPortMappingDescription); err != nil { - return - } - if request.NewLeaseDuration, err = soap.MarshalUi4(NewLeaseDuration); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewReservedPort string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "AddAnyPortMapping", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewReservedPort, err = soap.UnmarshalUi2(response.NewReservedPort); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// WANIPv6FirewallControl1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANIPv6FirewallControl:1". See -// goupnp.ServiceClient, which contains RootDevice and Service attributes which -// are provided for informational value. -type WANIPv6FirewallControl1 struct { - goupnp.ServiceClient -} - -// NewWANIPv6FirewallControl1Clients discovers instances of the service on the network, -// and returns clients to any that are found. errors will contain an error for -// any devices that replied but which could not be queried, and err will be set -// if the discovery process failed outright. -// -// This is a typical entry calling point into this package. -func NewWANIPv6FirewallControl1Clients() (clients []*WANIPv6FirewallControl1, errors []error, err error) { - var genericClients []goupnp.ServiceClient - if genericClients, errors, err = goupnp.NewServiceClients(URN_WANIPv6FirewallControl_1); err != nil { - return - } - clients = newWANIPv6FirewallControl1ClientsFromGenericClients(genericClients) - return -} - -// NewWANIPv6FirewallControl1ClientsByURL discovers instances of the service at the given -// URL, and returns clients to any that are found. An error is returned if -// there was an error probing the service. -// -// This is a typical entry calling point into this package when reusing an -// previously discovered service URL. -func NewWANIPv6FirewallControl1ClientsByURL(loc *url.URL) ([]*WANIPv6FirewallControl1, error) { - genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANIPv6FirewallControl_1) - if err != nil { - return nil, err - } - return newWANIPv6FirewallControl1ClientsFromGenericClients(genericClients), nil -} - -// NewWANIPv6FirewallControl1ClientsFromRootDevice discovers instances of the service in -// a given root device, and returns clients to any that are found. An error is -// returned if there was not at least one instance of the service within the -// device. The location parameter is simply assigned to the Location attribute -// of the wrapped ServiceClient(s). -// -// This is a typical entry calling point into this package when reusing an -// previously discovered root device. -func NewWANIPv6FirewallControl1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANIPv6FirewallControl1, error) { - genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANIPv6FirewallControl_1) - if err != nil { - return nil, err - } - return newWANIPv6FirewallControl1ClientsFromGenericClients(genericClients), nil -} - -func newWANIPv6FirewallControl1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANIPv6FirewallControl1 { - clients := make([]*WANIPv6FirewallControl1, len(genericClients)) - for i := range genericClients { - clients[i] = &WANIPv6FirewallControl1{genericClients[i]} - } - return clients -} - -func (client *WANIPv6FirewallControl1) GetFirewallStatus() (FirewallEnabled bool, InboundPinholeAllowed bool, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - FirewallEnabled string - InboundPinholeAllowed string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPv6FirewallControl_1, "GetFirewallStatus", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if FirewallEnabled, err = soap.UnmarshalBoolean(response.FirewallEnabled); err != nil { - return - } - if InboundPinholeAllowed, err = soap.UnmarshalBoolean(response.InboundPinholeAllowed); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANIPv6FirewallControl1) GetOutboundPinholeTimeout(RemoteHost string, RemotePort uint16, InternalClient string, InternalPort uint16, Protocol uint16) (OutboundPinholeTimeout uint32, err error) { - // Request structure. - request := &struct { - RemoteHost string - RemotePort string - InternalClient string - InternalPort string - Protocol string - }{} - // BEGIN Marshal arguments into request. - - if request.RemoteHost, err = soap.MarshalString(RemoteHost); err != nil { - return - } - if request.RemotePort, err = soap.MarshalUi2(RemotePort); err != nil { - return - } - if request.InternalClient, err = soap.MarshalString(InternalClient); err != nil { - return - } - if request.InternalPort, err = soap.MarshalUi2(InternalPort); err != nil { - return - } - if request.Protocol, err = soap.MarshalUi2(Protocol); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := &struct { - OutboundPinholeTimeout string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPv6FirewallControl_1, "GetOutboundPinholeTimeout", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if OutboundPinholeTimeout, err = soap.UnmarshalUi4(response.OutboundPinholeTimeout); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// -// Arguments: -// -// * LeaseTime: allowed value range: minimum=1, maximum=86400 - -func (client *WANIPv6FirewallControl1) AddPinhole(RemoteHost string, RemotePort uint16, InternalClient string, InternalPort uint16, Protocol uint16, LeaseTime uint32) (UniqueID uint16, err error) { - // Request structure. - request := &struct { - RemoteHost string - RemotePort string - InternalClient string - InternalPort string - Protocol string - LeaseTime string - }{} - // BEGIN Marshal arguments into request. - - if request.RemoteHost, err = soap.MarshalString(RemoteHost); err != nil { - return - } - if request.RemotePort, err = soap.MarshalUi2(RemotePort); err != nil { - return - } - if request.InternalClient, err = soap.MarshalString(InternalClient); err != nil { - return - } - if request.InternalPort, err = soap.MarshalUi2(InternalPort); err != nil { - return - } - if request.Protocol, err = soap.MarshalUi2(Protocol); err != nil { - return - } - if request.LeaseTime, err = soap.MarshalUi4(LeaseTime); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := &struct { - UniqueID string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPv6FirewallControl_1, "AddPinhole", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if UniqueID, err = soap.UnmarshalUi2(response.UniqueID); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// -// Arguments: -// -// * NewLeaseTime: allowed value range: minimum=1, maximum=86400 - -func (client *WANIPv6FirewallControl1) UpdatePinhole(UniqueID uint16, NewLeaseTime uint32) (err error) { - // Request structure. - request := &struct { - UniqueID string - NewLeaseTime string - }{} - // BEGIN Marshal arguments into request. - - if request.UniqueID, err = soap.MarshalUi2(UniqueID); err != nil { - return - } - if request.NewLeaseTime, err = soap.MarshalUi4(NewLeaseTime); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPv6FirewallControl_1, "UpdatePinhole", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANIPv6FirewallControl1) DeletePinhole(UniqueID uint16) (err error) { - // Request structure. - request := &struct { - UniqueID string - }{} - // BEGIN Marshal arguments into request. - - if request.UniqueID, err = soap.MarshalUi2(UniqueID); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPv6FirewallControl_1, "DeletePinhole", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANIPv6FirewallControl1) GetPinholePackets(UniqueID uint16) (PinholePackets uint32, err error) { - // Request structure. - request := &struct { - UniqueID string - }{} - // BEGIN Marshal arguments into request. - - if request.UniqueID, err = soap.MarshalUi2(UniqueID); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := &struct { - PinholePackets string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPv6FirewallControl_1, "GetPinholePackets", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if PinholePackets, err = soap.UnmarshalUi4(response.PinholePackets); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANIPv6FirewallControl1) CheckPinholeWorking(UniqueID uint16) (IsWorking bool, err error) { - // Request structure. - request := &struct { - UniqueID string - }{} - // BEGIN Marshal arguments into request. - - if request.UniqueID, err = soap.MarshalUi2(UniqueID); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := &struct { - IsWorking string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANIPv6FirewallControl_1, "CheckPinholeWorking", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if IsWorking, err = soap.UnmarshalBoolean(response.IsWorking); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// WANPOTSLinkConfig1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANPOTSLinkConfig:1". See -// goupnp.ServiceClient, which contains RootDevice and Service attributes which -// are provided for informational value. -type WANPOTSLinkConfig1 struct { - goupnp.ServiceClient -} - -// NewWANPOTSLinkConfig1Clients discovers instances of the service on the network, -// and returns clients to any that are found. errors will contain an error for -// any devices that replied but which could not be queried, and err will be set -// if the discovery process failed outright. -// -// This is a typical entry calling point into this package. -func NewWANPOTSLinkConfig1Clients() (clients []*WANPOTSLinkConfig1, errors []error, err error) { - var genericClients []goupnp.ServiceClient - if genericClients, errors, err = goupnp.NewServiceClients(URN_WANPOTSLinkConfig_1); err != nil { - return - } - clients = newWANPOTSLinkConfig1ClientsFromGenericClients(genericClients) - return -} - -// NewWANPOTSLinkConfig1ClientsByURL discovers instances of the service at the given -// URL, and returns clients to any that are found. An error is returned if -// there was an error probing the service. -// -// This is a typical entry calling point into this package when reusing an -// previously discovered service URL. -func NewWANPOTSLinkConfig1ClientsByURL(loc *url.URL) ([]*WANPOTSLinkConfig1, error) { - genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANPOTSLinkConfig_1) - if err != nil { - return nil, err - } - return newWANPOTSLinkConfig1ClientsFromGenericClients(genericClients), nil -} - -// NewWANPOTSLinkConfig1ClientsFromRootDevice discovers instances of the service in -// a given root device, and returns clients to any that are found. An error is -// returned if there was not at least one instance of the service within the -// device. The location parameter is simply assigned to the Location attribute -// of the wrapped ServiceClient(s). -// -// This is a typical entry calling point into this package when reusing an -// previously discovered root device. -func NewWANPOTSLinkConfig1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANPOTSLinkConfig1, error) { - genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANPOTSLinkConfig_1) - if err != nil { - return nil, err - } - return newWANPOTSLinkConfig1ClientsFromGenericClients(genericClients), nil -} - -func newWANPOTSLinkConfig1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANPOTSLinkConfig1 { - clients := make([]*WANPOTSLinkConfig1, len(genericClients)) - for i := range genericClients { - clients[i] = &WANPOTSLinkConfig1{genericClients[i]} - } - return clients -} - -// -// Arguments: -// -// * NewLinkType: allowed values: PPP_Dialup - -func (client *WANPOTSLinkConfig1) SetISPInfo(NewISPPhoneNumber string, NewISPInfo string, NewLinkType string) (err error) { - // Request structure. - request := &struct { - NewISPPhoneNumber string - NewISPInfo string - NewLinkType string - }{} - // BEGIN Marshal arguments into request. - - if request.NewISPPhoneNumber, err = soap.MarshalString(NewISPPhoneNumber); err != nil { - return - } - if request.NewISPInfo, err = soap.MarshalString(NewISPInfo); err != nil { - return - } - if request.NewLinkType, err = soap.MarshalString(NewLinkType); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "SetISPInfo", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANPOTSLinkConfig1) SetCallRetryInfo(NewNumberOfRetries uint32, NewDelayBetweenRetries uint32) (err error) { - // Request structure. - request := &struct { - NewNumberOfRetries string - NewDelayBetweenRetries string - }{} - // BEGIN Marshal arguments into request. - - if request.NewNumberOfRetries, err = soap.MarshalUi4(NewNumberOfRetries); err != nil { - return - } - if request.NewDelayBetweenRetries, err = soap.MarshalUi4(NewDelayBetweenRetries); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "SetCallRetryInfo", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -// -// Return values: -// -// * NewLinkType: allowed values: PPP_Dialup -func (client *WANPOTSLinkConfig1) GetISPInfo() (NewISPPhoneNumber string, NewISPInfo string, NewLinkType string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewISPPhoneNumber string - NewISPInfo string - NewLinkType string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "GetISPInfo", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewISPPhoneNumber, err = soap.UnmarshalString(response.NewISPPhoneNumber); err != nil { - return - } - if NewISPInfo, err = soap.UnmarshalString(response.NewISPInfo); err != nil { - return - } - if NewLinkType, err = soap.UnmarshalString(response.NewLinkType); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPOTSLinkConfig1) GetCallRetryInfo() (NewNumberOfRetries uint32, NewDelayBetweenRetries uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewNumberOfRetries string - NewDelayBetweenRetries string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "GetCallRetryInfo", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewNumberOfRetries, err = soap.UnmarshalUi4(response.NewNumberOfRetries); err != nil { - return - } - if NewDelayBetweenRetries, err = soap.UnmarshalUi4(response.NewDelayBetweenRetries); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPOTSLinkConfig1) GetFclass() (NewFclass string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewFclass string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "GetFclass", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewFclass, err = soap.UnmarshalString(response.NewFclass); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPOTSLinkConfig1) GetDataModulationSupported() (NewDataModulationSupported string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewDataModulationSupported string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "GetDataModulationSupported", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewDataModulationSupported, err = soap.UnmarshalString(response.NewDataModulationSupported); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPOTSLinkConfig1) GetDataProtocol() (NewDataProtocol string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewDataProtocol string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "GetDataProtocol", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewDataProtocol, err = soap.UnmarshalString(response.NewDataProtocol); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPOTSLinkConfig1) GetDataCompression() (NewDataCompression string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewDataCompression string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "GetDataCompression", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewDataCompression, err = soap.UnmarshalString(response.NewDataCompression); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPOTSLinkConfig1) GetPlusVTRCommandSupported() (NewPlusVTRCommandSupported bool, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewPlusVTRCommandSupported string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "GetPlusVTRCommandSupported", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewPlusVTRCommandSupported, err = soap.UnmarshalBoolean(response.NewPlusVTRCommandSupported); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// WANPPPConnection1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANPPPConnection:1". See -// goupnp.ServiceClient, which contains RootDevice and Service attributes which -// are provided for informational value. -type WANPPPConnection1 struct { - goupnp.ServiceClient -} - -// NewWANPPPConnection1Clients discovers instances of the service on the network, -// and returns clients to any that are found. errors will contain an error for -// any devices that replied but which could not be queried, and err will be set -// if the discovery process failed outright. -// -// This is a typical entry calling point into this package. -func NewWANPPPConnection1Clients() (clients []*WANPPPConnection1, errors []error, err error) { - var genericClients []goupnp.ServiceClient - if genericClients, errors, err = goupnp.NewServiceClients(URN_WANPPPConnection_1); err != nil { - return - } - clients = newWANPPPConnection1ClientsFromGenericClients(genericClients) - return -} - -// NewWANPPPConnection1ClientsByURL discovers instances of the service at the given -// URL, and returns clients to any that are found. An error is returned if -// there was an error probing the service. -// -// This is a typical entry calling point into this package when reusing an -// previously discovered service URL. -func NewWANPPPConnection1ClientsByURL(loc *url.URL) ([]*WANPPPConnection1, error) { - genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANPPPConnection_1) - if err != nil { - return nil, err - } - return newWANPPPConnection1ClientsFromGenericClients(genericClients), nil -} - -// NewWANPPPConnection1ClientsFromRootDevice discovers instances of the service in -// a given root device, and returns clients to any that are found. An error is -// returned if there was not at least one instance of the service within the -// device. The location parameter is simply assigned to the Location attribute -// of the wrapped ServiceClient(s). -// -// This is a typical entry calling point into this package when reusing an -// previously discovered root device. -func NewWANPPPConnection1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANPPPConnection1, error) { - genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANPPPConnection_1) - if err != nil { - return nil, err - } - return newWANPPPConnection1ClientsFromGenericClients(genericClients), nil -} - -func newWANPPPConnection1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANPPPConnection1 { - clients := make([]*WANPPPConnection1, len(genericClients)) - for i := range genericClients { - clients[i] = &WANPPPConnection1{genericClients[i]} - } - return clients -} - -func (client *WANPPPConnection1) SetConnectionType(NewConnectionType string) (err error) { - // Request structure. - request := &struct { - NewConnectionType string - }{} - // BEGIN Marshal arguments into request. - - if request.NewConnectionType, err = soap.MarshalString(NewConnectionType); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "SetConnectionType", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -// -// Return values: -// -// * NewPossibleConnectionTypes: allowed values: Unconfigured, IP_Routed, DHCP_Spoofed, PPPoE_Bridged, PPTP_Relay, L2TP_Relay, PPPoE_Relay -func (client *WANPPPConnection1) GetConnectionTypeInfo() (NewConnectionType string, NewPossibleConnectionTypes string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewConnectionType string - NewPossibleConnectionTypes string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetConnectionTypeInfo", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewConnectionType, err = soap.UnmarshalString(response.NewConnectionType); err != nil { - return - } - if NewPossibleConnectionTypes, err = soap.UnmarshalString(response.NewPossibleConnectionTypes); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) ConfigureConnection(NewUserName string, NewPassword string) (err error) { - // Request structure. - request := &struct { - NewUserName string - NewPassword string - }{} - // BEGIN Marshal arguments into request. - - if request.NewUserName, err = soap.MarshalString(NewUserName); err != nil { - return - } - if request.NewPassword, err = soap.MarshalString(NewPassword); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "ConfigureConnection", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) RequestConnection() (err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "RequestConnection", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) RequestTermination() (err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "RequestTermination", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) ForceTermination() (err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "ForceTermination", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) SetAutoDisconnectTime(NewAutoDisconnectTime uint32) (err error) { - // Request structure. - request := &struct { - NewAutoDisconnectTime string - }{} - // BEGIN Marshal arguments into request. - - if request.NewAutoDisconnectTime, err = soap.MarshalUi4(NewAutoDisconnectTime); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "SetAutoDisconnectTime", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) SetIdleDisconnectTime(NewIdleDisconnectTime uint32) (err error) { - // Request structure. - request := &struct { - NewIdleDisconnectTime string - }{} - // BEGIN Marshal arguments into request. - - if request.NewIdleDisconnectTime, err = soap.MarshalUi4(NewIdleDisconnectTime); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "SetIdleDisconnectTime", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) SetWarnDisconnectDelay(NewWarnDisconnectDelay uint32) (err error) { - // Request structure. - request := &struct { - NewWarnDisconnectDelay string - }{} - // BEGIN Marshal arguments into request. - - if request.NewWarnDisconnectDelay, err = soap.MarshalUi4(NewWarnDisconnectDelay); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "SetWarnDisconnectDelay", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -// -// Return values: -// -// * NewConnectionStatus: allowed values: Unconfigured, Connected, Disconnected -// -// * NewLastConnectionError: allowed values: ERROR_NONE -func (client *WANPPPConnection1) GetStatusInfo() (NewConnectionStatus string, NewLastConnectionError string, NewUptime uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewConnectionStatus string - NewLastConnectionError string - NewUptime string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetStatusInfo", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewConnectionStatus, err = soap.UnmarshalString(response.NewConnectionStatus); err != nil { - return - } - if NewLastConnectionError, err = soap.UnmarshalString(response.NewLastConnectionError); err != nil { - return - } - if NewUptime, err = soap.UnmarshalUi4(response.NewUptime); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) GetLinkLayerMaxBitRates() (NewUpstreamMaxBitRate uint32, NewDownstreamMaxBitRate uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewUpstreamMaxBitRate string - NewDownstreamMaxBitRate string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetLinkLayerMaxBitRates", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewUpstreamMaxBitRate, err = soap.UnmarshalUi4(response.NewUpstreamMaxBitRate); err != nil { - return - } - if NewDownstreamMaxBitRate, err = soap.UnmarshalUi4(response.NewDownstreamMaxBitRate); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) GetPPPEncryptionProtocol() (NewPPPEncryptionProtocol string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewPPPEncryptionProtocol string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetPPPEncryptionProtocol", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewPPPEncryptionProtocol, err = soap.UnmarshalString(response.NewPPPEncryptionProtocol); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) GetPPPCompressionProtocol() (NewPPPCompressionProtocol string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewPPPCompressionProtocol string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetPPPCompressionProtocol", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewPPPCompressionProtocol, err = soap.UnmarshalString(response.NewPPPCompressionProtocol); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) GetPPPAuthenticationProtocol() (NewPPPAuthenticationProtocol string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewPPPAuthenticationProtocol string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetPPPAuthenticationProtocol", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewPPPAuthenticationProtocol, err = soap.UnmarshalString(response.NewPPPAuthenticationProtocol); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) GetUserName() (NewUserName string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewUserName string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetUserName", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewUserName, err = soap.UnmarshalString(response.NewUserName); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) GetPassword() (NewPassword string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewPassword string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetPassword", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewPassword, err = soap.UnmarshalString(response.NewPassword); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) GetAutoDisconnectTime() (NewAutoDisconnectTime uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewAutoDisconnectTime string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetAutoDisconnectTime", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewAutoDisconnectTime, err = soap.UnmarshalUi4(response.NewAutoDisconnectTime); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) GetIdleDisconnectTime() (NewIdleDisconnectTime uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewIdleDisconnectTime string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetIdleDisconnectTime", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewIdleDisconnectTime, err = soap.UnmarshalUi4(response.NewIdleDisconnectTime); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) GetWarnDisconnectDelay() (NewWarnDisconnectDelay uint32, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewWarnDisconnectDelay string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetWarnDisconnectDelay", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewWarnDisconnectDelay, err = soap.UnmarshalUi4(response.NewWarnDisconnectDelay); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) GetNATRSIPStatus() (NewRSIPAvailable bool, NewNATEnabled bool, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewRSIPAvailable string - NewNATEnabled string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetNATRSIPStatus", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewRSIPAvailable, err = soap.UnmarshalBoolean(response.NewRSIPAvailable); err != nil { - return - } - if NewNATEnabled, err = soap.UnmarshalBoolean(response.NewNATEnabled); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// -// Return values: -// -// * NewProtocol: allowed values: TCP, UDP -func (client *WANPPPConnection1) GetGenericPortMappingEntry(NewPortMappingIndex uint16) (NewRemoteHost string, NewExternalPort uint16, NewProtocol string, NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32, err error) { - // Request structure. - request := &struct { - NewPortMappingIndex string - }{} - // BEGIN Marshal arguments into request. - - if request.NewPortMappingIndex, err = soap.MarshalUi2(NewPortMappingIndex); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewRemoteHost string - NewExternalPort string - NewProtocol string - NewInternalPort string - NewInternalClient string - NewEnabled string - NewPortMappingDescription string - NewLeaseDuration string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetGenericPortMappingEntry", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewRemoteHost, err = soap.UnmarshalString(response.NewRemoteHost); err != nil { - return - } - if NewExternalPort, err = soap.UnmarshalUi2(response.NewExternalPort); err != nil { - return - } - if NewProtocol, err = soap.UnmarshalString(response.NewProtocol); err != nil { - return - } - if NewInternalPort, err = soap.UnmarshalUi2(response.NewInternalPort); err != nil { - return - } - if NewInternalClient, err = soap.UnmarshalString(response.NewInternalClient); err != nil { - return - } - if NewEnabled, err = soap.UnmarshalBoolean(response.NewEnabled); err != nil { - return - } - if NewPortMappingDescription, err = soap.UnmarshalString(response.NewPortMappingDescription); err != nil { - return - } - if NewLeaseDuration, err = soap.UnmarshalUi4(response.NewLeaseDuration); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// -// Arguments: -// -// * NewProtocol: allowed values: TCP, UDP - -func (client *WANPPPConnection1) GetSpecificPortMappingEntry(NewRemoteHost string, NewExternalPort uint16, NewProtocol string) (NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32, err error) { - // Request structure. - request := &struct { - NewRemoteHost string - NewExternalPort string - NewProtocol string - }{} - // BEGIN Marshal arguments into request. - - if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil { - return - } - if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil { - return - } - if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewInternalPort string - NewInternalClient string - NewEnabled string - NewPortMappingDescription string - NewLeaseDuration string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetSpecificPortMappingEntry", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewInternalPort, err = soap.UnmarshalUi2(response.NewInternalPort); err != nil { - return - } - if NewInternalClient, err = soap.UnmarshalString(response.NewInternalClient); err != nil { - return - } - if NewEnabled, err = soap.UnmarshalBoolean(response.NewEnabled); err != nil { - return - } - if NewPortMappingDescription, err = soap.UnmarshalString(response.NewPortMappingDescription); err != nil { - return - } - if NewLeaseDuration, err = soap.UnmarshalUi4(response.NewLeaseDuration); err != nil { - return - } - // END Unmarshal arguments from response. - return -} - -// -// Arguments: -// -// * NewProtocol: allowed values: TCP, UDP - -func (client *WANPPPConnection1) AddPortMapping(NewRemoteHost string, NewExternalPort uint16, NewProtocol string, NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32) (err error) { - // Request structure. - request := &struct { - NewRemoteHost string - NewExternalPort string - NewProtocol string - NewInternalPort string - NewInternalClient string - NewEnabled string - NewPortMappingDescription string - NewLeaseDuration string - }{} - // BEGIN Marshal arguments into request. - - if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil { - return - } - if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil { - return - } - if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil { - return - } - if request.NewInternalPort, err = soap.MarshalUi2(NewInternalPort); err != nil { - return - } - if request.NewInternalClient, err = soap.MarshalString(NewInternalClient); err != nil { - return - } - if request.NewEnabled, err = soap.MarshalBoolean(NewEnabled); err != nil { - return - } - if request.NewPortMappingDescription, err = soap.MarshalString(NewPortMappingDescription); err != nil { - return - } - if request.NewLeaseDuration, err = soap.MarshalUi4(NewLeaseDuration); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "AddPortMapping", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -// -// Arguments: -// -// * NewProtocol: allowed values: TCP, UDP - -func (client *WANPPPConnection1) DeletePortMapping(NewRemoteHost string, NewExternalPort uint16, NewProtocol string) (err error) { - // Request structure. - request := &struct { - NewRemoteHost string - NewExternalPort string - NewProtocol string - }{} - // BEGIN Marshal arguments into request. - - if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil { - return - } - if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil { - return - } - if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil { - return - } - // END Marshal arguments into request. - - // Response structure. - response := interface{}(nil) - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "DeletePortMapping", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - // END Unmarshal arguments from response. - return -} - -func (client *WANPPPConnection1) GetExternalIPAddress() (NewExternalIPAddress string, err error) { - // Request structure. - request := interface{}(nil) - // BEGIN Marshal arguments into request. - - // END Marshal arguments into request. - - // Response structure. - response := &struct { - NewExternalIPAddress string - }{} - - // Perform the SOAP call. - if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetExternalIPAddress", request, response); err != nil { - return - } - - // BEGIN Unmarshal arguments from response. - - if NewExternalIPAddress, err = soap.UnmarshalString(response.NewExternalIPAddress); err != nil { - return - } - // END Unmarshal arguments from response. - return -} diff --git a/vendor/github.com/huin/goupnp/device.go b/vendor/github.com/huin/goupnp/device.go deleted file mode 100644 index 567ab4cf..00000000 --- a/vendor/github.com/huin/goupnp/device.go +++ /dev/null @@ -1,190 +0,0 @@ -// This file contains XML structures for communicating with UPnP devices. - -package goupnp - -import ( - "encoding/xml" - "errors" - "fmt" - "net/url" - - "github.com/huin/goupnp/scpd" - "github.com/huin/goupnp/soap" -) - -const ( - DeviceXMLNamespace = "urn:schemas-upnp-org:device-1-0" -) - -// RootDevice is the device description as described by section 2.3 "Device -// description" in -// http://upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.1.pdf -type RootDevice struct { - XMLName xml.Name `xml:"root"` - SpecVersion SpecVersion `xml:"specVersion"` - URLBase url.URL `xml:"-"` - URLBaseStr string `xml:"URLBase"` - Device Device `xml:"device"` -} - -// SetURLBase sets the URLBase for the RootDevice and its underlying components. -func (root *RootDevice) SetURLBase(urlBase *url.URL) { - root.URLBase = *urlBase - root.URLBaseStr = urlBase.String() - root.Device.SetURLBase(urlBase) -} - -// SpecVersion is part of a RootDevice, describes the version of the -// specification that the data adheres to. -type SpecVersion struct { - Major int32 `xml:"major"` - Minor int32 `xml:"minor"` -} - -// Device is a UPnP device. It can have child devices. -type Device struct { - DeviceType string `xml:"deviceType"` - FriendlyName string `xml:"friendlyName"` - Manufacturer string `xml:"manufacturer"` - ManufacturerURL URLField `xml:"manufacturerURL"` - ModelDescription string `xml:"modelDescription"` - ModelName string `xml:"modelName"` - ModelNumber string `xml:"modelNumber"` - ModelURL URLField `xml:"modelURL"` - SerialNumber string `xml:"serialNumber"` - UDN string `xml:"UDN"` - UPC string `xml:"UPC,omitempty"` - Icons []Icon `xml:"iconList>icon,omitempty"` - Services []Service `xml:"serviceList>service,omitempty"` - Devices []Device `xml:"deviceList>device,omitempty"` - - // Extra observed elements: - PresentationURL URLField `xml:"presentationURL"` -} - -// VisitDevices calls visitor for the device, and all its descendent devices. -func (device *Device) VisitDevices(visitor func(*Device)) { - visitor(device) - for i := range device.Devices { - device.Devices[i].VisitDevices(visitor) - } -} - -// VisitServices calls visitor for all Services under the device and all its -// descendent devices. -func (device *Device) VisitServices(visitor func(*Service)) { - device.VisitDevices(func(d *Device) { - for i := range d.Services { - visitor(&d.Services[i]) - } - }) -} - -// FindService finds all (if any) Services under the device and its descendents -// that have the given ServiceType. -func (device *Device) FindService(serviceType string) []*Service { - var services []*Service - device.VisitServices(func(s *Service) { - if s.ServiceType == serviceType { - services = append(services, s) - } - }) - return services -} - -// SetURLBase sets the URLBase for the Device and its underlying components. -func (device *Device) SetURLBase(urlBase *url.URL) { - device.ManufacturerURL.SetURLBase(urlBase) - device.ModelURL.SetURLBase(urlBase) - device.PresentationURL.SetURLBase(urlBase) - for i := range device.Icons { - device.Icons[i].SetURLBase(urlBase) - } - for i := range device.Services { - device.Services[i].SetURLBase(urlBase) - } - for i := range device.Devices { - device.Devices[i].SetURLBase(urlBase) - } -} - -func (device *Device) String() string { - return fmt.Sprintf("Device ID %s : %s (%s)", device.UDN, device.DeviceType, device.FriendlyName) -} - -// Icon is a representative image that a device might include in its -// description. -type Icon struct { - Mimetype string `xml:"mimetype"` - Width int32 `xml:"width"` - Height int32 `xml:"height"` - Depth int32 `xml:"depth"` - URL URLField `xml:"url"` -} - -// SetURLBase sets the URLBase for the Icon. -func (icon *Icon) SetURLBase(url *url.URL) { - icon.URL.SetURLBase(url) -} - -// Service is a service provided by a UPnP Device. -type Service struct { - ServiceType string `xml:"serviceType"` - ServiceId string `xml:"serviceId"` - SCPDURL URLField `xml:"SCPDURL"` - ControlURL URLField `xml:"controlURL"` - EventSubURL URLField `xml:"eventSubURL"` -} - -// SetURLBase sets the URLBase for the Service. -func (srv *Service) SetURLBase(urlBase *url.URL) { - srv.SCPDURL.SetURLBase(urlBase) - srv.ControlURL.SetURLBase(urlBase) - srv.EventSubURL.SetURLBase(urlBase) -} - -func (srv *Service) String() string { - return fmt.Sprintf("Service ID %s : %s", srv.ServiceId, srv.ServiceType) -} - -// RequestSCPD requests the SCPD (soap actions and state variables description) -// for the service. -func (srv *Service) RequestSCPD() (*scpd.SCPD, error) { - if !srv.SCPDURL.Ok { - return nil, errors.New("bad/missing SCPD URL, or no URLBase has been set") - } - s := new(scpd.SCPD) - if err := requestXml(srv.SCPDURL.URL.String(), scpd.SCPDXMLNamespace, s); err != nil { - return nil, err - } - return s, nil -} - -// RequestSCDP is for compatibility only, prefer RequestSCPD. This was a -// misspelling of RequestSCDP. -func (srv *Service) RequestSCDP() (*scpd.SCPD, error) { - return srv.RequestSCPD() -} - -func (srv *Service) NewSOAPClient() *soap.SOAPClient { - return soap.NewSOAPClient(srv.ControlURL.URL) -} - -// URLField is a URL that is part of a device description. -type URLField struct { - URL url.URL `xml:"-"` - Ok bool `xml:"-"` - Str string `xml:",chardata"` -} - -func (uf *URLField) SetURLBase(urlBase *url.URL) { - refUrl, err := url.Parse(uf.Str) - if err != nil { - uf.URL = url.URL{} - uf.Ok = false - return - } - - uf.URL = *urlBase.ResolveReference(refUrl) - uf.Ok = true -} diff --git a/vendor/github.com/huin/goupnp/goupnp.go b/vendor/github.com/huin/goupnp/goupnp.go deleted file mode 100644 index fcb8dcd2..00000000 --- a/vendor/github.com/huin/goupnp/goupnp.go +++ /dev/null @@ -1,131 +0,0 @@ -// goupnp is an implementation of a client for various UPnP services. -// -// For most uses, it is recommended to use the code-generated packages under -// github.com/huin/goupnp/dcps. Example use is shown at -// http://godoc.org/github.com/huin/goupnp/example -// -// A commonly used client is internetgateway1.WANPPPConnection1: -// http://godoc.org/github.com/huin/goupnp/dcps/internetgateway1#WANPPPConnection1 -// -// Currently only a couple of schemas have code generated for them from the -// UPnP example XML specifications. Not all methods will work on these clients, -// because the generated stubs contain the full set of specified methods from -// the XML specifications, and the discovered services will likely support a -// subset of those methods. -package goupnp - -import ( - "encoding/xml" - "fmt" - "net/http" - "net/url" - "time" - - "golang.org/x/net/html/charset" - - "github.com/huin/goupnp/httpu" - "github.com/huin/goupnp/ssdp" -) - -// ContextError is an error that wraps an error with some context information. -type ContextError struct { - Context string - Err error -} - -func (err ContextError) Error() string { - return fmt.Sprintf("%s: %v", err.Context, err.Err) -} - -// MaybeRootDevice contains either a RootDevice or an error. -type MaybeRootDevice struct { - // Set iff Err == nil. - Root *RootDevice - - // The location the device was discovered at. This can be used with - // DeviceByURL, assuming the device is still present. A location represents - // the discovery of a device, regardless of if there was an error probing it. - Location *url.URL - - // Any error encountered probing a discovered device. - Err error -} - -// DiscoverDevices attempts to find targets of the given type. This is -// typically the entry-point for this package. searchTarget is typically a URN -// in the form "urn:schemas-upnp-org:device:..." or -// "urn:schemas-upnp-org:service:...". A single error is returned for errors -// while attempting to send the query. An error or RootDevice is returned for -// each discovered RootDevice. -func DiscoverDevices(searchTarget string) ([]MaybeRootDevice, error) { - httpu, err := httpu.NewHTTPUClient() - if err != nil { - return nil, err - } - defer httpu.Close() - responses, err := ssdp.SSDPRawSearch(httpu, string(searchTarget), 2, 3) - if err != nil { - return nil, err - } - - results := make([]MaybeRootDevice, len(responses)) - for i, response := range responses { - maybe := &results[i] - loc, err := response.Location() - if err != nil { - maybe.Err = ContextError{"unexpected bad location from search", err} - continue - } - maybe.Location = loc - if root, err := DeviceByURL(loc); err != nil { - maybe.Err = err - } else { - maybe.Root = root - } - } - - return results, nil -} - -func DeviceByURL(loc *url.URL) (*RootDevice, error) { - locStr := loc.String() - root := new(RootDevice) - if err := requestXml(locStr, DeviceXMLNamespace, root); err != nil { - return nil, ContextError{fmt.Sprintf("error requesting root device details from %q", locStr), err} - } - var urlBaseStr string - if root.URLBaseStr != "" { - urlBaseStr = root.URLBaseStr - } else { - urlBaseStr = locStr - } - urlBase, err := url.Parse(urlBaseStr) - if err != nil { - return nil, ContextError{fmt.Sprintf("error parsing location URL %q", locStr), err} - } - root.SetURLBase(urlBase) - return root, nil -} - -func requestXml(url string, defaultSpace string, doc interface{}) error { - timeout := time.Duration(3 * time.Second) - client := http.Client{ - Timeout: timeout, - } - resp, err := client.Get(url) - if err != nil { - return err - } - defer resp.Body.Close() - - if resp.StatusCode != 200 { - return fmt.Errorf("goupnp: got response status %s from %q", - resp.Status, url) - } - - decoder := xml.NewDecoder(resp.Body) - decoder.DefaultSpace = defaultSpace - decoder.CharsetReader = charset.NewReaderLabel - - return decoder.Decode(doc) -} diff --git a/vendor/github.com/huin/goupnp/httpu/httpu.go b/vendor/github.com/huin/goupnp/httpu/httpu.go deleted file mode 100644 index 44b0c583..00000000 --- a/vendor/github.com/huin/goupnp/httpu/httpu.go +++ /dev/null @@ -1,134 +0,0 @@ -package httpu - -import ( - "bufio" - "bytes" - "errors" - "fmt" - "log" - "net" - "net/http" - "sync" - "time" -) - -// HTTPUClient is a client for dealing with HTTPU (HTTP over UDP). Its typical -// function is for HTTPMU, and particularly SSDP. -type HTTPUClient struct { - connLock sync.Mutex // Protects use of conn. - conn net.PacketConn -} - -// NewHTTPUClient creates a new HTTPUClient, opening up a new UDP socket for the -// purpose. -func NewHTTPUClient() (*HTTPUClient, error) { - conn, err := net.ListenPacket("udp", ":0") - if err != nil { - return nil, err - } - return &HTTPUClient{conn: conn}, nil -} - -// NewHTTPUClientAddr creates a new HTTPUClient which will broadcast packets -// from the specified address, opening up a new UDP socket for the purpose -func NewHTTPUClientAddr(addr string) (*HTTPUClient, error) { - ip := net.ParseIP(addr) - if ip == nil { - return nil, errors.New("Invalid listening address") - } - conn, err := net.ListenPacket("udp", ip.String()+":0") - if err != nil { - return nil, err - } - return &HTTPUClient{conn: conn}, nil -} - -// Close shuts down the client. The client will no longer be useful following -// this. -func (httpu *HTTPUClient) Close() error { - httpu.connLock.Lock() - defer httpu.connLock.Unlock() - return httpu.conn.Close() -} - -// Do performs a request. The timeout is how long to wait for before returning -// the responses that were received. An error is only returned for failing to -// send the request. Failures in receipt simply do not add to the resulting -// responses. -// -// Note that at present only one concurrent connection will happen per -// HTTPUClient. -func (httpu *HTTPUClient) Do(req *http.Request, timeout time.Duration, numSends int) ([]*http.Response, error) { - httpu.connLock.Lock() - defer httpu.connLock.Unlock() - - // Create the request. This is a subset of what http.Request.Write does - // deliberately to avoid creating extra fields which may confuse some - // devices. - var requestBuf bytes.Buffer - method := req.Method - if method == "" { - method = "GET" - } - if _, err := fmt.Fprintf(&requestBuf, "%s %s HTTP/1.1\r\n", method, req.URL.RequestURI()); err != nil { - return nil, err - } - if err := req.Header.Write(&requestBuf); err != nil { - return nil, err - } - if _, err := requestBuf.Write([]byte{'\r', '\n'}); err != nil { - return nil, err - } - - destAddr, err := net.ResolveUDPAddr("udp", req.Host) - if err != nil { - return nil, err - } - if err = httpu.conn.SetDeadline(time.Now().Add(timeout)); err != nil { - return nil, err - } - - // Send request. - for i := 0; i < numSends; i++ { - if n, err := httpu.conn.WriteTo(requestBuf.Bytes(), destAddr); err != nil { - return nil, err - } else if n < len(requestBuf.Bytes()) { - return nil, fmt.Errorf("httpu: wrote %d bytes rather than full %d in request", - n, len(requestBuf.Bytes())) - } - time.Sleep(5 * time.Millisecond) - } - - // Await responses until timeout. - var responses []*http.Response - responseBytes := make([]byte, 2048) - for { - // 2048 bytes should be sufficient for most networks. - n, _, err := httpu.conn.ReadFrom(responseBytes) - if err != nil { - if err, ok := err.(net.Error); ok { - if err.Timeout() { - break - } - if err.Temporary() { - // Sleep in case this is a persistent error to avoid pegging CPU until deadline. - time.Sleep(10 * time.Millisecond) - continue - } - } - return nil, err - } - - // Parse response. - response, err := http.ReadResponse(bufio.NewReader(bytes.NewBuffer(responseBytes[:n])), req) - if err != nil { - log.Printf("httpu: error while parsing response: %v", err) - continue - } - - responses = append(responses, response) - } - - // Timeout reached - return discovered responses. - return responses, nil -} diff --git a/vendor/github.com/huin/goupnp/httpu/serve.go b/vendor/github.com/huin/goupnp/httpu/serve.go deleted file mode 100644 index 9f67af85..00000000 --- a/vendor/github.com/huin/goupnp/httpu/serve.go +++ /dev/null @@ -1,108 +0,0 @@ -package httpu - -import ( - "bufio" - "bytes" - "log" - "net" - "net/http" - "regexp" -) - -const ( - DefaultMaxMessageBytes = 2048 -) - -var ( - trailingWhitespaceRx = regexp.MustCompile(" +\r\n") - crlf = []byte("\r\n") -) - -// Handler is the interface by which received HTTPU messages are passed to -// handling code. -type Handler interface { - // ServeMessage is called for each HTTPU message received. peerAddr contains - // the address that the message was received from. - ServeMessage(r *http.Request) -} - -// HandlerFunc is a function-to-Handler adapter. -type HandlerFunc func(r *http.Request) - -func (f HandlerFunc) ServeMessage(r *http.Request) { - f(r) -} - -// A Server defines parameters for running an HTTPU server. -type Server struct { - Addr string // UDP address to listen on - Multicast bool // Should listen for multicast? - Interface *net.Interface // Network interface to listen on for multicast, nil for default multicast interface - Handler Handler // handler to invoke - MaxMessageBytes int // maximum number of bytes to read from a packet, DefaultMaxMessageBytes if 0 -} - -// ListenAndServe listens on the UDP network address srv.Addr. If srv.Multicast -// is true, then a multicast UDP listener will be used on srv.Interface (or -// default interface if nil). -func (srv *Server) ListenAndServe() error { - var err error - - var addr *net.UDPAddr - if addr, err = net.ResolveUDPAddr("udp", srv.Addr); err != nil { - log.Fatal(err) - } - - var conn net.PacketConn - if srv.Multicast { - if conn, err = net.ListenMulticastUDP("udp", srv.Interface, addr); err != nil { - return err - } - } else { - if conn, err = net.ListenUDP("udp", addr); err != nil { - return err - } - } - - return srv.Serve(conn) -} - -// Serve messages received on the given packet listener to the srv.Handler. -func (srv *Server) Serve(l net.PacketConn) error { - maxMessageBytes := DefaultMaxMessageBytes - if srv.MaxMessageBytes != 0 { - maxMessageBytes = srv.MaxMessageBytes - } - for { - buf := make([]byte, maxMessageBytes) - n, peerAddr, err := l.ReadFrom(buf) - if err != nil { - return err - } - buf = buf[:n] - - go func(buf []byte, peerAddr net.Addr) { - // At least one router's UPnP implementation has added a trailing space - // after "HTTP/1.1" - trim it. - buf = trailingWhitespaceRx.ReplaceAllLiteral(buf, crlf) - - req, err := http.ReadRequest(bufio.NewReader(bytes.NewBuffer(buf))) - if err != nil { - log.Printf("httpu: Failed to parse request: %v", err) - return - } - req.RemoteAddr = peerAddr.String() - srv.Handler.ServeMessage(req) - // No need to call req.Body.Close - underlying reader is bytes.Buffer. - }(buf, peerAddr) - } -} - -// Serve messages received on the given packet listener to the given handler. -func Serve(l net.PacketConn, handler Handler) error { - srv := Server{ - Handler: handler, - MaxMessageBytes: DefaultMaxMessageBytes, - } - return srv.Serve(l) -} diff --git a/vendor/github.com/huin/goupnp/scpd/scpd.go b/vendor/github.com/huin/goupnp/scpd/scpd.go deleted file mode 100644 index c9d2e69e..00000000 --- a/vendor/github.com/huin/goupnp/scpd/scpd.go +++ /dev/null @@ -1,167 +0,0 @@ -package scpd - -import ( - "encoding/xml" - "strings" -) - -const ( - SCPDXMLNamespace = "urn:schemas-upnp-org:service-1-0" -) - -func cleanWhitespace(s *string) { - *s = strings.TrimSpace(*s) -} - -// SCPD is the service description as described by section 2.5 "Service -// description" in -// http://upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.1.pdf -type SCPD struct { - XMLName xml.Name `xml:"scpd"` - ConfigId string `xml:"configId,attr"` - SpecVersion SpecVersion `xml:"specVersion"` - Actions []Action `xml:"actionList>action"` - StateVariables []StateVariable `xml:"serviceStateTable>stateVariable"` -} - -// Clean attempts to remove stray whitespace etc. in the structure. It seems -// unfortunately common for stray whitespace to be present in SCPD documents, -// this method attempts to make it easy to clean them out. -func (scpd *SCPD) Clean() { - cleanWhitespace(&scpd.ConfigId) - for i := range scpd.Actions { - scpd.Actions[i].clean() - } - for i := range scpd.StateVariables { - scpd.StateVariables[i].clean() - } -} - -func (scpd *SCPD) GetStateVariable(variable string) *StateVariable { - for i := range scpd.StateVariables { - v := &scpd.StateVariables[i] - if v.Name == variable { - return v - } - } - return nil -} - -func (scpd *SCPD) GetAction(action string) *Action { - for i := range scpd.Actions { - a := &scpd.Actions[i] - if a.Name == action { - return a - } - } - return nil -} - -// SpecVersion is part of a SCPD document, describes the version of the -// specification that the data adheres to. -type SpecVersion struct { - Major int32 `xml:"major"` - Minor int32 `xml:"minor"` -} - -type Action struct { - Name string `xml:"name"` - Arguments []Argument `xml:"argumentList>argument"` -} - -func (action *Action) clean() { - cleanWhitespace(&action.Name) - for i := range action.Arguments { - action.Arguments[i].clean() - } -} - -func (action *Action) InputArguments() []*Argument { - var result []*Argument - for i := range action.Arguments { - arg := &action.Arguments[i] - if arg.IsInput() { - result = append(result, arg) - } - } - return result -} - -func (action *Action) OutputArguments() []*Argument { - var result []*Argument - for i := range action.Arguments { - arg := &action.Arguments[i] - if arg.IsOutput() { - result = append(result, arg) - } - } - return result -} - -type Argument struct { - Name string `xml:"name"` - Direction string `xml:"direction"` // in|out - RelatedStateVariable string `xml:"relatedStateVariable"` // ? - Retval string `xml:"retval"` // ? -} - -func (arg *Argument) clean() { - cleanWhitespace(&arg.Name) - cleanWhitespace(&arg.Direction) - cleanWhitespace(&arg.RelatedStateVariable) - cleanWhitespace(&arg.Retval) -} - -func (arg *Argument) IsInput() bool { - return arg.Direction == "in" -} - -func (arg *Argument) IsOutput() bool { - return arg.Direction == "out" -} - -type StateVariable struct { - Name string `xml:"name"` - SendEvents string `xml:"sendEvents,attr"` // yes|no - Multicast string `xml:"multicast,attr"` // yes|no - DataType DataType `xml:"dataType"` - DefaultValue string `xml:"defaultValue"` - AllowedValueRange *AllowedValueRange `xml:"allowedValueRange"` - AllowedValues []string `xml:"allowedValueList>allowedValue"` -} - -func (v *StateVariable) clean() { - cleanWhitespace(&v.Name) - cleanWhitespace(&v.SendEvents) - cleanWhitespace(&v.Multicast) - v.DataType.clean() - cleanWhitespace(&v.DefaultValue) - if v.AllowedValueRange != nil { - v.AllowedValueRange.clean() - } - for i := range v.AllowedValues { - cleanWhitespace(&v.AllowedValues[i]) - } -} - -type AllowedValueRange struct { - Minimum string `xml:"minimum"` - Maximum string `xml:"maximum"` - Step string `xml:"step"` -} - -func (r *AllowedValueRange) clean() { - cleanWhitespace(&r.Minimum) - cleanWhitespace(&r.Maximum) - cleanWhitespace(&r.Step) -} - -type DataType struct { - Name string `xml:",chardata"` - Type string `xml:"type,attr"` -} - -func (dt *DataType) clean() { - cleanWhitespace(&dt.Name) - cleanWhitespace(&dt.Type) -} diff --git a/vendor/github.com/huin/goupnp/service_client.go b/vendor/github.com/huin/goupnp/service_client.go deleted file mode 100644 index 9111c93c..00000000 --- a/vendor/github.com/huin/goupnp/service_client.go +++ /dev/null @@ -1,88 +0,0 @@ -package goupnp - -import ( - "fmt" - "net/url" - - "github.com/huin/goupnp/soap" -) - -// ServiceClient is a SOAP client, root device and the service for the SOAP -// client rolled into one value. The root device, location, and service are -// intended to be informational. Location can be used to later recreate a -// ServiceClient with NewServiceClientByURL if the service is still present; -// bypassing the discovery process. -type ServiceClient struct { - SOAPClient *soap.SOAPClient - RootDevice *RootDevice - Location *url.URL - Service *Service -} - -// NewServiceClients discovers services, and returns clients for them. err will -// report any error with the discovery process (blocking any device/service -// discovery), errors reports errors on a per-root-device basis. -func NewServiceClients(searchTarget string) (clients []ServiceClient, errors []error, err error) { - var maybeRootDevices []MaybeRootDevice - if maybeRootDevices, err = DiscoverDevices(searchTarget); err != nil { - return - } - - clients = make([]ServiceClient, 0, len(maybeRootDevices)) - - for _, maybeRootDevice := range maybeRootDevices { - if maybeRootDevice.Err != nil { - errors = append(errors, maybeRootDevice.Err) - continue - } - - deviceClients, err := NewServiceClientsFromRootDevice(maybeRootDevice.Root, maybeRootDevice.Location, searchTarget) - if err != nil { - errors = append(errors, err) - continue - } - clients = append(clients, deviceClients...) - } - - return -} - -// NewServiceClientsByURL creates client(s) for the given service URN, for a -// root device at the given URL. -func NewServiceClientsByURL(loc *url.URL, searchTarget string) ([]ServiceClient, error) { - rootDevice, err := DeviceByURL(loc) - if err != nil { - return nil, err - } - return NewServiceClientsFromRootDevice(rootDevice, loc, searchTarget) -} - -// NewServiceClientsFromDevice creates client(s) for the given service URN, in -// a given root device. The loc parameter is simply assigned to the -// Location attribute of the returned ServiceClient(s). -func NewServiceClientsFromRootDevice(rootDevice *RootDevice, loc *url.URL, searchTarget string) ([]ServiceClient, error) { - device := &rootDevice.Device - srvs := device.FindService(searchTarget) - if len(srvs) == 0 { - return nil, fmt.Errorf("goupnp: service %q not found within device %q (UDN=%q)", - searchTarget, device.FriendlyName, device.UDN) - } - - clients := make([]ServiceClient, 0, len(srvs)) - for _, srv := range srvs { - clients = append(clients, ServiceClient{ - SOAPClient: srv.NewSOAPClient(), - RootDevice: rootDevice, - Location: loc, - Service: srv, - }) - } - return clients, nil -} - -// GetServiceClient returns the ServiceClient itself. This is provided so that the -// service client attributes can be accessed via an interface method on a -// wrapping type. -func (client *ServiceClient) GetServiceClient() *ServiceClient { - return client -} diff --git a/vendor/github.com/huin/goupnp/soap/soap.go b/vendor/github.com/huin/goupnp/soap/soap.go deleted file mode 100644 index 29e89f2a..00000000 --- a/vendor/github.com/huin/goupnp/soap/soap.go +++ /dev/null @@ -1,193 +0,0 @@ -// Definition for the SOAP structure required for UPnP's SOAP usage. - -package soap - -import ( - "bytes" - "encoding/xml" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "reflect" - "regexp" -) - -const ( - soapEncodingStyle = "http://schemas.xmlsoap.org/soap/encoding/" - soapPrefix = xml.Header + `` - soapSuffix = `` -) - -type SOAPClient struct { - EndpointURL url.URL - HTTPClient http.Client -} - -func NewSOAPClient(endpointURL url.URL) *SOAPClient { - return &SOAPClient{ - EndpointURL: endpointURL, - } -} - -// PerformSOAPAction makes a SOAP request, with the given action. -// inAction and outAction must both be pointers to structs with string fields -// only. -func (client *SOAPClient) PerformAction(actionNamespace, actionName string, inAction interface{}, outAction interface{}) error { - requestBytes, err := encodeRequestAction(actionNamespace, actionName, inAction) - if err != nil { - return err - } - - response, err := client.HTTPClient.Do(&http.Request{ - Method: "POST", - URL: &client.EndpointURL, - Header: http.Header{ - "SOAPACTION": []string{`"` + actionNamespace + "#" + actionName + `"`}, - "CONTENT-TYPE": []string{"text/xml; charset=\"utf-8\""}, - }, - Body: ioutil.NopCloser(bytes.NewBuffer(requestBytes)), - // Set ContentLength to avoid chunked encoding - some servers might not support it. - ContentLength: int64(len(requestBytes)), - }) - if err != nil { - return fmt.Errorf("goupnp: error performing SOAP HTTP request: %v", err) - } - defer response.Body.Close() - if response.StatusCode != 200 { - return fmt.Errorf("goupnp: SOAP request got HTTP %s", response.Status) - } - - responseEnv := newSOAPEnvelope() - decoder := xml.NewDecoder(response.Body) - if err := decoder.Decode(responseEnv); err != nil { - return fmt.Errorf("goupnp: error decoding response body: %v", err) - } - - if responseEnv.Body.Fault != nil { - return responseEnv.Body.Fault - } - - if outAction != nil { - if err := xml.Unmarshal(responseEnv.Body.RawAction, outAction); err != nil { - return fmt.Errorf("goupnp: error unmarshalling out action: %v, %v", err, responseEnv.Body.RawAction) - } - } - - return nil -} - -// newSOAPAction creates a soapEnvelope with the given action and arguments. -func newSOAPEnvelope() *soapEnvelope { - return &soapEnvelope{ - EncodingStyle: soapEncodingStyle, - } -} - -// encodeRequestAction is a hacky way to create an encoded SOAP envelope -// containing the given action. Experiments with one router have shown that it -// 500s for requests where the outer default xmlns is set to the SOAP -// namespace, and then reassigning the default namespace within that to the -// service namespace. Hand-coding the outer XML to work-around this. -func encodeRequestAction(actionNamespace, actionName string, inAction interface{}) ([]byte, error) { - requestBuf := new(bytes.Buffer) - requestBuf.WriteString(soapPrefix) - requestBuf.WriteString(``) - if inAction != nil { - if err := encodeRequestArgs(requestBuf, inAction); err != nil { - return nil, err - } - } - requestBuf.WriteString(``) - requestBuf.WriteString(soapSuffix) - return requestBuf.Bytes(), nil -} - -func encodeRequestArgs(w *bytes.Buffer, inAction interface{}) error { - in := reflect.Indirect(reflect.ValueOf(inAction)) - if in.Kind() != reflect.Struct { - return fmt.Errorf("goupnp: SOAP inAction is not a struct but of type %v", in.Type()) - } - enc := xml.NewEncoder(w) - nFields := in.NumField() - inType := in.Type() - for i := 0; i < nFields; i++ { - field := inType.Field(i) - argName := field.Name - if nameOverride := field.Tag.Get("soap"); nameOverride != "" { - argName = nameOverride - } - value := in.Field(i) - if value.Kind() != reflect.String { - return fmt.Errorf("goupnp: SOAP arg %q is not of type string, but of type %v", argName, value.Type()) - } - elem := xml.StartElement{xml.Name{"", argName}, nil} - if err := enc.EncodeToken(elem); err != nil { - return fmt.Errorf("goupnp: error encoding start element for SOAP arg %q: %v", argName, err) - } - if err := enc.Flush(); err != nil { - return fmt.Errorf("goupnp: error flushing start element for SOAP arg %q: %v", argName, err) - } - if _, err := w.Write([]byte(escapeXMLText(value.Interface().(string)))); err != nil { - return fmt.Errorf("goupnp: error writing value for SOAP arg %q: %v", argName, err) - } - if err := enc.EncodeToken(elem.End()); err != nil { - return fmt.Errorf("goupnp: error encoding end element for SOAP arg %q: %v", argName, err) - } - } - enc.Flush() - return nil -} - -var xmlCharRx = regexp.MustCompile("[<>&]") - -// escapeXMLText is used by generated code to escape text in XML, but only -// escaping the characters `<`, `>`, and `&`. -// -// This is provided in order to work around SOAP server implementations that -// fail to decode XML correctly, specifically failing to decode `"`, `'`. Note -// that this can only be safely used for injecting into XML text, but not into -// attributes or other contexts. -func escapeXMLText(s string) string { - return xmlCharRx.ReplaceAllStringFunc(s, replaceEntity) -} - -func replaceEntity(s string) string { - switch s { - case "<": - return "<" - case ">": - return ">" - case "&": - return "&" - } - return s -} - -type soapEnvelope struct { - XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Envelope"` - EncodingStyle string `xml:"http://schemas.xmlsoap.org/soap/envelope/ encodingStyle,attr"` - Body soapBody `xml:"http://schemas.xmlsoap.org/soap/envelope/ Body"` -} - -type soapBody struct { - Fault *SOAPFaultError `xml:"Fault"` - RawAction []byte `xml:",innerxml"` -} - -// SOAPFaultError implements error, and contains SOAP fault information. -type SOAPFaultError struct { - FaultCode string `xml:"faultcode"` - FaultString string `xml:"faultstring"` - Detail string `xml:"detail"` -} - -func (err *SOAPFaultError) Error() string { - return fmt.Sprintf("SOAP fault: %s", err.FaultString) -} diff --git a/vendor/github.com/huin/goupnp/soap/types.go b/vendor/github.com/huin/goupnp/soap/types.go deleted file mode 100644 index 3e73d99d..00000000 --- a/vendor/github.com/huin/goupnp/soap/types.go +++ /dev/null @@ -1,528 +0,0 @@ -package soap - -import ( - "encoding/base64" - "encoding/hex" - "errors" - "fmt" - "net/url" - "regexp" - "strconv" - "strings" - "time" - "unicode/utf8" -) - -var ( - // localLoc acts like time.Local for this package, but is faked out by the - // unit tests to ensure that things stay constant (especially when running - // this test in a place where local time is UTC which might mask bugs). - localLoc = time.Local -) - -func MarshalUi1(v uint8) (string, error) { - return strconv.FormatUint(uint64(v), 10), nil -} - -func UnmarshalUi1(s string) (uint8, error) { - v, err := strconv.ParseUint(s, 10, 8) - return uint8(v), err -} - -func MarshalUi2(v uint16) (string, error) { - return strconv.FormatUint(uint64(v), 10), nil -} - -func UnmarshalUi2(s string) (uint16, error) { - v, err := strconv.ParseUint(s, 10, 16) - return uint16(v), err -} - -func MarshalUi4(v uint32) (string, error) { - return strconv.FormatUint(uint64(v), 10), nil -} - -func UnmarshalUi4(s string) (uint32, error) { - v, err := strconv.ParseUint(s, 10, 32) - return uint32(v), err -} - -func MarshalUi8(v uint64) (string, error) { - return strconv.FormatUint(v, 10), nil -} - -func UnmarshalUi8(s string) (uint64, error) { - v, err := strconv.ParseUint(s, 10, 64) - return uint64(v), err -} - -func MarshalI1(v int8) (string, error) { - return strconv.FormatInt(int64(v), 10), nil -} - -func UnmarshalI1(s string) (int8, error) { - v, err := strconv.ParseInt(s, 10, 8) - return int8(v), err -} - -func MarshalI2(v int16) (string, error) { - return strconv.FormatInt(int64(v), 10), nil -} - -func UnmarshalI2(s string) (int16, error) { - v, err := strconv.ParseInt(s, 10, 16) - return int16(v), err -} - -func MarshalI4(v int32) (string, error) { - return strconv.FormatInt(int64(v), 10), nil -} - -func UnmarshalI4(s string) (int32, error) { - v, err := strconv.ParseInt(s, 10, 32) - return int32(v), err -} - -func MarshalInt(v int64) (string, error) { - return strconv.FormatInt(v, 10), nil -} - -func UnmarshalInt(s string) (int64, error) { - return strconv.ParseInt(s, 10, 64) -} - -func MarshalR4(v float32) (string, error) { - return strconv.FormatFloat(float64(v), 'G', -1, 32), nil -} - -func UnmarshalR4(s string) (float32, error) { - v, err := strconv.ParseFloat(s, 32) - return float32(v), err -} - -func MarshalR8(v float64) (string, error) { - return strconv.FormatFloat(v, 'G', -1, 64), nil -} - -func UnmarshalR8(s string) (float64, error) { - v, err := strconv.ParseFloat(s, 64) - return float64(v), err -} - -// MarshalFixed14_4 marshals float64 to SOAP "fixed.14.4" type. -func MarshalFixed14_4(v float64) (string, error) { - if v >= 1e14 || v <= -1e14 { - return "", fmt.Errorf("soap fixed14.4: value %v out of bounds", v) - } - return strconv.FormatFloat(v, 'f', 4, 64), nil -} - -// UnmarshalFixed14_4 unmarshals float64 from SOAP "fixed.14.4" type. -func UnmarshalFixed14_4(s string) (float64, error) { - v, err := strconv.ParseFloat(s, 64) - if err != nil { - return 0, err - } - if v >= 1e14 || v <= -1e14 { - return 0, fmt.Errorf("soap fixed14.4: value %q out of bounds", s) - } - return v, nil -} - -// MarshalChar marshals rune to SOAP "char" type. -func MarshalChar(v rune) (string, error) { - if v == 0 { - return "", errors.New("soap char: rune 0 is not allowed") - } - return string(v), nil -} - -// UnmarshalChar unmarshals rune from SOAP "char" type. -func UnmarshalChar(s string) (rune, error) { - if len(s) == 0 { - return 0, errors.New("soap char: got empty string") - } - r, n := utf8.DecodeRune([]byte(s)) - if n != len(s) { - return 0, fmt.Errorf("soap char: value %q is not a single rune", s) - } - return r, nil -} - -func MarshalString(v string) (string, error) { - return v, nil -} - -func UnmarshalString(v string) (string, error) { - return v, nil -} - -func parseInt(s string, err *error) int { - v, parseErr := strconv.ParseInt(s, 10, 64) - if parseErr != nil { - *err = parseErr - } - return int(v) -} - -var dateRegexps = []*regexp.Regexp{ - // yyyy[-mm[-dd]] - regexp.MustCompile(`^(\d{4})(?:-(\d{2})(?:-(\d{2}))?)?$`), - // yyyy[mm[dd]] - regexp.MustCompile(`^(\d{4})(?:(\d{2})(?:(\d{2}))?)?$`), -} - -func parseDateParts(s string) (year, month, day int, err error) { - var parts []string - for _, re := range dateRegexps { - parts = re.FindStringSubmatch(s) - if parts != nil { - break - } - } - if parts == nil { - err = fmt.Errorf("soap date: value %q is not in a recognized ISO8601 date format", s) - return - } - - year = parseInt(parts[1], &err) - month = 1 - day = 1 - if len(parts[2]) != 0 { - month = parseInt(parts[2], &err) - if len(parts[3]) != 0 { - day = parseInt(parts[3], &err) - } - } - - if err != nil { - err = fmt.Errorf("soap date: %q: %v", s, err) - } - - return -} - -var timeRegexps = []*regexp.Regexp{ - // hh[:mm[:ss]] - regexp.MustCompile(`^(\d{2})(?::(\d{2})(?::(\d{2}))?)?$`), - // hh[mm[ss]] - regexp.MustCompile(`^(\d{2})(?:(\d{2})(?:(\d{2}))?)?$`), -} - -func parseTimeParts(s string) (hour, minute, second int, err error) { - var parts []string - for _, re := range timeRegexps { - parts = re.FindStringSubmatch(s) - if parts != nil { - break - } - } - if parts == nil { - err = fmt.Errorf("soap time: value %q is not in ISO8601 time format", s) - return - } - - hour = parseInt(parts[1], &err) - if len(parts[2]) != 0 { - minute = parseInt(parts[2], &err) - if len(parts[3]) != 0 { - second = parseInt(parts[3], &err) - } - } - - if err != nil { - err = fmt.Errorf("soap time: %q: %v", s, err) - } - - return -} - -// (+|-)hh[[:]mm] -var timezoneRegexp = regexp.MustCompile(`^([+-])(\d{2})(?::?(\d{2}))?$`) - -func parseTimezone(s string) (offset int, err error) { - if s == "Z" { - return 0, nil - } - parts := timezoneRegexp.FindStringSubmatch(s) - if parts == nil { - err = fmt.Errorf("soap timezone: value %q is not in ISO8601 timezone format", s) - return - } - - offset = parseInt(parts[2], &err) * 3600 - if len(parts[3]) != 0 { - offset += parseInt(parts[3], &err) * 60 - } - if parts[1] == "-" { - offset = -offset - } - - if err != nil { - err = fmt.Errorf("soap timezone: %q: %v", s, err) - } - - return -} - -var completeDateTimeZoneRegexp = regexp.MustCompile(`^([^T]+)(?:T([^-+Z]+)(.+)?)?$`) - -// splitCompleteDateTimeZone splits date, time and timezone apart from an -// ISO8601 string. It does not ensure that the contents of each part are -// correct, it merely splits on certain delimiters. -// e.g "2010-09-08T12:15:10+0700" => "2010-09-08", "12:15:10", "+0700". -// Timezone can only be present if time is also present. -func splitCompleteDateTimeZone(s string) (dateStr, timeStr, zoneStr string, err error) { - parts := completeDateTimeZoneRegexp.FindStringSubmatch(s) - if parts == nil { - err = fmt.Errorf("soap date/time/zone: value %q is not in ISO8601 datetime format", s) - return - } - dateStr = parts[1] - timeStr = parts[2] - zoneStr = parts[3] - return -} - -// MarshalDate marshals time.Time to SOAP "date" type. Note that this converts -// to local time, and discards the time-of-day components. -func MarshalDate(v time.Time) (string, error) { - return v.In(localLoc).Format("2006-01-02"), nil -} - -var dateFmts = []string{"2006-01-02", "20060102"} - -// UnmarshalDate unmarshals time.Time from SOAP "date" type. This outputs the -// date as midnight in the local time zone. -func UnmarshalDate(s string) (time.Time, error) { - year, month, day, err := parseDateParts(s) - if err != nil { - return time.Time{}, err - } - return time.Date(year, time.Month(month), day, 0, 0, 0, 0, localLoc), nil -} - -// TimeOfDay is used in cases where SOAP "time" or "time.tz" is used. -type TimeOfDay struct { - // Duration of time since midnight. - FromMidnight time.Duration - - // Set to true if Offset is specified. If false, then the timezone is - // unspecified (and by ISO8601 - implies some "local" time). - HasOffset bool - - // Offset is non-zero only if time.tz is used. It is otherwise ignored. If - // non-zero, then it is regarded as a UTC offset in seconds. Note that the - // sub-minutes is ignored by the marshal function. - Offset int -} - -// MarshalTimeOfDay marshals TimeOfDay to the "time" type. -func MarshalTimeOfDay(v TimeOfDay) (string, error) { - d := int64(v.FromMidnight / time.Second) - hour := d / 3600 - d = d % 3600 - minute := d / 60 - second := d % 60 - - return fmt.Sprintf("%02d:%02d:%02d", hour, minute, second), nil -} - -// UnmarshalTimeOfDay unmarshals TimeOfDay from the "time" type. -func UnmarshalTimeOfDay(s string) (TimeOfDay, error) { - t, err := UnmarshalTimeOfDayTz(s) - if err != nil { - return TimeOfDay{}, err - } else if t.HasOffset { - return TimeOfDay{}, fmt.Errorf("soap time: value %q contains unexpected timezone", s) - } - return t, nil -} - -// MarshalTimeOfDayTz marshals TimeOfDay to the "time.tz" type. -func MarshalTimeOfDayTz(v TimeOfDay) (string, error) { - d := int64(v.FromMidnight / time.Second) - hour := d / 3600 - d = d % 3600 - minute := d / 60 - second := d % 60 - - tz := "" - if v.HasOffset { - if v.Offset == 0 { - tz = "Z" - } else { - offsetMins := v.Offset / 60 - sign := '+' - if offsetMins < 1 { - offsetMins = -offsetMins - sign = '-' - } - tz = fmt.Sprintf("%c%02d:%02d", sign, offsetMins/60, offsetMins%60) - } - } - - return fmt.Sprintf("%02d:%02d:%02d%s", hour, minute, second, tz), nil -} - -// UnmarshalTimeOfDayTz unmarshals TimeOfDay from the "time.tz" type. -func UnmarshalTimeOfDayTz(s string) (tod TimeOfDay, err error) { - zoneIndex := strings.IndexAny(s, "Z+-") - var timePart string - var hasOffset bool - var offset int - if zoneIndex == -1 { - hasOffset = false - timePart = s - } else { - hasOffset = true - timePart = s[:zoneIndex] - if offset, err = parseTimezone(s[zoneIndex:]); err != nil { - return - } - } - - hour, minute, second, err := parseTimeParts(timePart) - if err != nil { - return - } - - fromMidnight := time.Duration(hour*3600+minute*60+second) * time.Second - - // ISO8601 special case - values up to 24:00:00 are allowed, so using - // strictly greater-than for the maximum value. - if fromMidnight > 24*time.Hour || minute >= 60 || second >= 60 { - return TimeOfDay{}, fmt.Errorf("soap time.tz: value %q has value(s) out of range", s) - } - - return TimeOfDay{ - FromMidnight: time.Duration(hour*3600+minute*60+second) * time.Second, - HasOffset: hasOffset, - Offset: offset, - }, nil -} - -// MarshalDateTime marshals time.Time to SOAP "dateTime" type. Note that this -// converts to local time. -func MarshalDateTime(v time.Time) (string, error) { - return v.In(localLoc).Format("2006-01-02T15:04:05"), nil -} - -// UnmarshalDateTime unmarshals time.Time from the SOAP "dateTime" type. This -// returns a value in the local timezone. -func UnmarshalDateTime(s string) (result time.Time, err error) { - dateStr, timeStr, zoneStr, err := splitCompleteDateTimeZone(s) - if err != nil { - return - } - - if len(zoneStr) != 0 { - err = fmt.Errorf("soap datetime: unexpected timezone in %q", s) - return - } - - year, month, day, err := parseDateParts(dateStr) - if err != nil { - return - } - - var hour, minute, second int - if len(timeStr) != 0 { - hour, minute, second, err = parseTimeParts(timeStr) - if err != nil { - return - } - } - - result = time.Date(year, time.Month(month), day, hour, minute, second, 0, localLoc) - return -} - -// MarshalDateTimeTz marshals time.Time to SOAP "dateTime.tz" type. -func MarshalDateTimeTz(v time.Time) (string, error) { - return v.Format("2006-01-02T15:04:05-07:00"), nil -} - -// UnmarshalDateTimeTz unmarshals time.Time from the SOAP "dateTime.tz" type. -// This returns a value in the local timezone when the timezone is unspecified. -func UnmarshalDateTimeTz(s string) (result time.Time, err error) { - dateStr, timeStr, zoneStr, err := splitCompleteDateTimeZone(s) - if err != nil { - return - } - - year, month, day, err := parseDateParts(dateStr) - if err != nil { - return - } - - var hour, minute, second int - var location *time.Location = localLoc - if len(timeStr) != 0 { - hour, minute, second, err = parseTimeParts(timeStr) - if err != nil { - return - } - if len(zoneStr) != 0 { - var offset int - offset, err = parseTimezone(zoneStr) - if offset == 0 { - location = time.UTC - } else { - location = time.FixedZone("", offset) - } - } - } - - result = time.Date(year, time.Month(month), day, hour, minute, second, 0, location) - return -} - -// MarshalBoolean marshals bool to SOAP "boolean" type. -func MarshalBoolean(v bool) (string, error) { - if v { - return "1", nil - } - return "0", nil -} - -// UnmarshalBoolean unmarshals bool from the SOAP "boolean" type. -func UnmarshalBoolean(s string) (bool, error) { - switch s { - case "0", "false", "no": - return false, nil - case "1", "true", "yes": - return true, nil - } - return false, fmt.Errorf("soap boolean: %q is not a valid boolean value", s) -} - -// MarshalBinBase64 marshals []byte to SOAP "bin.base64" type. -func MarshalBinBase64(v []byte) (string, error) { - return base64.StdEncoding.EncodeToString(v), nil -} - -// UnmarshalBinBase64 unmarshals []byte from the SOAP "bin.base64" type. -func UnmarshalBinBase64(s string) ([]byte, error) { - return base64.StdEncoding.DecodeString(s) -} - -// MarshalBinHex marshals []byte to SOAP "bin.hex" type. -func MarshalBinHex(v []byte) (string, error) { - return hex.EncodeToString(v), nil -} - -// UnmarshalBinHex unmarshals []byte from the SOAP "bin.hex" type. -func UnmarshalBinHex(s string) ([]byte, error) { - return hex.DecodeString(s) -} - -// MarshalURI marshals *url.URL to SOAP "uri" type. -func MarshalURI(v *url.URL) (string, error) { - return v.String(), nil -} - -// UnmarshalURI unmarshals *url.URL from the SOAP "uri" type. -func UnmarshalURI(s string) (*url.URL, error) { - return url.Parse(s) -} diff --git a/vendor/github.com/huin/goupnp/ssdp/registry.go b/vendor/github.com/huin/goupnp/ssdp/registry.go deleted file mode 100644 index d3bc1144..00000000 --- a/vendor/github.com/huin/goupnp/ssdp/registry.go +++ /dev/null @@ -1,312 +0,0 @@ -package ssdp - -import ( - "fmt" - "log" - "net/http" - "net/url" - "regexp" - "strconv" - "sync" - "time" - - "github.com/huin/goupnp/httpu" -) - -const ( - maxExpiryTimeSeconds = 24 * 60 * 60 -) - -var ( - maxAgeRx = regexp.MustCompile("max-age= *([0-9]+)") -) - -const ( - EventAlive = EventType(iota) - EventUpdate - EventByeBye -) - -type EventType int8 - -func (et EventType) String() string { - switch et { - case EventAlive: - return "EventAlive" - case EventUpdate: - return "EventUpdate" - case EventByeBye: - return "EventByeBye" - default: - return fmt.Sprintf("EventUnknown(%d)", int8(et)) - } -} - -type Update struct { - // The USN of the service. - USN string - // What happened. - EventType EventType - // The entry, which is nil if the service was not known and - // EventType==EventByeBye. The contents of this must not be modified as it is - // shared with the registry and other listeners. Once created, the Registry - // does not modify the Entry value - any updates are replaced with a new - // Entry value. - Entry *Entry -} - -type Entry struct { - // The address that the entry data was actually received from. - RemoteAddr string - // Unique Service Name. Identifies a unique instance of a device or service. - USN string - // Notfication Type. The type of device or service being announced. - NT string - // Server's self-identifying string. - Server string - Host string - // Location of the UPnP root device description. - Location url.URL - - // Despite BOOTID,CONFIGID being required fields, apparently they are not - // always set by devices. Set to -1 if not present. - - BootID int32 - ConfigID int32 - - SearchPort uint16 - - // When the last update was received for this entry identified by this USN. - LastUpdate time.Time - // When the last update's cached values are advised to expire. - CacheExpiry time.Time -} - -func newEntryFromRequest(r *http.Request) (*Entry, error) { - now := time.Now() - expiryDuration, err := parseCacheControlMaxAge(r.Header.Get("CACHE-CONTROL")) - if err != nil { - return nil, fmt.Errorf("ssdp: error parsing CACHE-CONTROL max age: %v", err) - } - - loc, err := url.Parse(r.Header.Get("LOCATION")) - if err != nil { - return nil, fmt.Errorf("ssdp: error parsing entry Location URL: %v", err) - } - - bootID, err := parseUpnpIntHeader(r.Header, "BOOTID.UPNP.ORG", -1) - if err != nil { - return nil, err - } - configID, err := parseUpnpIntHeader(r.Header, "CONFIGID.UPNP.ORG", -1) - if err != nil { - return nil, err - } - searchPort, err := parseUpnpIntHeader(r.Header, "SEARCHPORT.UPNP.ORG", ssdpSearchPort) - if err != nil { - return nil, err - } - - if searchPort < 1 || searchPort > 65535 { - return nil, fmt.Errorf("ssdp: search port %d is out of range", searchPort) - } - - return &Entry{ - RemoteAddr: r.RemoteAddr, - USN: r.Header.Get("USN"), - NT: r.Header.Get("NT"), - Server: r.Header.Get("SERVER"), - Host: r.Header.Get("HOST"), - Location: *loc, - BootID: bootID, - ConfigID: configID, - SearchPort: uint16(searchPort), - LastUpdate: now, - CacheExpiry: now.Add(expiryDuration), - }, nil -} - -func parseCacheControlMaxAge(cc string) (time.Duration, error) { - matches := maxAgeRx.FindStringSubmatch(cc) - if len(matches) != 2 { - return 0, fmt.Errorf("did not find exactly one max-age in cache control header: %q", cc) - } - expirySeconds, err := strconv.ParseInt(matches[1], 10, 16) - if err != nil { - return 0, err - } - if expirySeconds < 1 || expirySeconds > maxExpiryTimeSeconds { - return 0, fmt.Errorf("rejecting bad expiry time of %d seconds", expirySeconds) - } - return time.Duration(expirySeconds) * time.Second, nil -} - -// parseUpnpIntHeader is intended to parse the -// {BOOT,CONFIGID,SEARCHPORT}.UPNP.ORG header fields. It returns the def if -// the head is empty or missing. -func parseUpnpIntHeader(headers http.Header, headerName string, def int32) (int32, error) { - s := headers.Get(headerName) - if s == "" { - return def, nil - } - v, err := strconv.ParseInt(s, 10, 32) - if err != nil { - return 0, fmt.Errorf("ssdp: could not parse header %s: %v", headerName, err) - } - return int32(v), nil -} - -var _ httpu.Handler = new(Registry) - -// Registry maintains knowledge of discovered devices and services. -// -// NOTE: the interface for this is experimental and may change, or go away -// entirely. -type Registry struct { - lock sync.Mutex - byUSN map[string]*Entry - - listenersLock sync.RWMutex - listeners map[chan<- Update]struct{} -} - -func NewRegistry() *Registry { - return &Registry{ - byUSN: make(map[string]*Entry), - listeners: make(map[chan<- Update]struct{}), - } -} - -// NewServerAndRegistry is a convenience function to create a registry, and an -// httpu server to pass it messages. Call ListenAndServe on the server for -// messages to be processed. -func NewServerAndRegistry() (*httpu.Server, *Registry) { - reg := NewRegistry() - srv := &httpu.Server{ - Addr: ssdpUDP4Addr, - Multicast: true, - Handler: reg, - } - return srv, reg -} - -func (reg *Registry) AddListener(c chan<- Update) { - reg.listenersLock.Lock() - defer reg.listenersLock.Unlock() - reg.listeners[c] = struct{}{} -} - -func (reg *Registry) RemoveListener(c chan<- Update) { - reg.listenersLock.Lock() - defer reg.listenersLock.Unlock() - delete(reg.listeners, c) -} - -func (reg *Registry) sendUpdate(u Update) { - reg.listenersLock.RLock() - defer reg.listenersLock.RUnlock() - for c := range reg.listeners { - c <- u - } -} - -// GetService returns known service (or device) entries for the given service -// URN. -func (reg *Registry) GetService(serviceURN string) []*Entry { - // Currently assumes that the map is small, so we do a linear search rather - // than indexed to avoid maintaining two maps. - var results []*Entry - reg.lock.Lock() - defer reg.lock.Unlock() - for _, entry := range reg.byUSN { - if entry.NT == serviceURN { - results = append(results, entry) - } - } - return results -} - -// ServeMessage implements httpu.Handler, and uses SSDP NOTIFY requests to -// maintain the registry of devices and services. -func (reg *Registry) ServeMessage(r *http.Request) { - if r.Method != methodNotify { - return - } - - nts := r.Header.Get("nts") - - var err error - switch nts { - case ntsAlive: - err = reg.handleNTSAlive(r) - case ntsUpdate: - err = reg.handleNTSUpdate(r) - case ntsByebye: - err = reg.handleNTSByebye(r) - default: - err = fmt.Errorf("unknown NTS value: %q", nts) - } - if err != nil { - log.Printf("goupnp/ssdp: failed to handle %s message from %s: %v", nts, r.RemoteAddr, err) - } -} - -func (reg *Registry) handleNTSAlive(r *http.Request) error { - entry, err := newEntryFromRequest(r) - if err != nil { - return err - } - - reg.lock.Lock() - reg.byUSN[entry.USN] = entry - reg.lock.Unlock() - - reg.sendUpdate(Update{ - USN: entry.USN, - EventType: EventAlive, - Entry: entry, - }) - - return nil -} - -func (reg *Registry) handleNTSUpdate(r *http.Request) error { - entry, err := newEntryFromRequest(r) - if err != nil { - return err - } - nextBootID, err := parseUpnpIntHeader(r.Header, "NEXTBOOTID.UPNP.ORG", -1) - if err != nil { - return err - } - entry.BootID = nextBootID - - reg.lock.Lock() - reg.byUSN[entry.USN] = entry - reg.lock.Unlock() - - reg.sendUpdate(Update{ - USN: entry.USN, - EventType: EventUpdate, - Entry: entry, - }) - - return nil -} - -func (reg *Registry) handleNTSByebye(r *http.Request) error { - usn := r.Header.Get("USN") - - reg.lock.Lock() - entry := reg.byUSN[usn] - delete(reg.byUSN, usn) - reg.lock.Unlock() - - reg.sendUpdate(Update{ - USN: usn, - EventType: EventByeBye, - Entry: entry, - }) - - return nil -} diff --git a/vendor/github.com/huin/goupnp/ssdp/ssdp.go b/vendor/github.com/huin/goupnp/ssdp/ssdp.go deleted file mode 100644 index 4c03b255..00000000 --- a/vendor/github.com/huin/goupnp/ssdp/ssdp.go +++ /dev/null @@ -1,90 +0,0 @@ -package ssdp - -import ( - "errors" - "log" - "net/http" - "net/url" - "strconv" - "time" - - "github.com/huin/goupnp/httpu" -) - -const ( - ssdpDiscover = `"ssdp:discover"` - ntsAlive = `ssdp:alive` - ntsByebye = `ssdp:byebye` - ntsUpdate = `ssdp:update` - ssdpUDP4Addr = "239.255.255.250:1900" - ssdpSearchPort = 1900 - methodSearch = "M-SEARCH" - methodNotify = "NOTIFY" - - // SSDPAll is a value for searchTarget that searches for all devices and services. - SSDPAll = "ssdp:all" - // UPNPRootDevice is a value for searchTarget that searches for all root devices. - UPNPRootDevice = "upnp:rootdevice" -) - -// SSDPRawSearch performs a fairly raw SSDP search request, and returns the -// unique response(s) that it receives. Each response has the requested -// searchTarget, a USN, and a valid location. maxWaitSeconds states how long to -// wait for responses in seconds, and must be a minimum of 1 (the -// implementation waits an additional 100ms for responses to arrive), 2 is a -// reasonable value for this. numSends is the number of requests to send - 3 is -// a reasonable value for this. -func SSDPRawSearch(httpu *httpu.HTTPUClient, searchTarget string, maxWaitSeconds int, numSends int) ([]*http.Response, error) { - if maxWaitSeconds < 1 { - return nil, errors.New("ssdp: maxWaitSeconds must be >= 1") - } - - seenUsns := make(map[string]bool) - var responses []*http.Response - req := http.Request{ - Method: methodSearch, - // TODO: Support both IPv4 and IPv6. - Host: ssdpUDP4Addr, - URL: &url.URL{Opaque: "*"}, - Header: http.Header{ - // Putting headers in here avoids them being title-cased. - // (The UPnP discovery protocol uses case-sensitive headers) - "HOST": []string{ssdpUDP4Addr}, - "MX": []string{strconv.FormatInt(int64(maxWaitSeconds), 10)}, - "MAN": []string{ssdpDiscover}, - "ST": []string{searchTarget}, - }, - } - allResponses, err := httpu.Do(&req, time.Duration(maxWaitSeconds)*time.Second+100*time.Millisecond, numSends) - if err != nil { - return nil, err - } - - isExactSearch := searchTarget != SSDPAll && searchTarget != UPNPRootDevice - - for _, response := range allResponses { - if response.StatusCode != 200 { - log.Printf("ssdp: got response status code %q in search response", response.Status) - continue - } - if st := response.Header.Get("ST"); isExactSearch && st != searchTarget { - continue - } - location, err := response.Location() - if err != nil { - log.Printf("ssdp: no usable location in search response (discarding): %v", err) - continue - } - usn := response.Header.Get("USN") - if usn == "" { - log.Printf("ssdp: empty/missing USN in search response (using location instead): %v", err) - usn = location.String() - } - if _, alreadySeen := seenUsns[usn]; !alreadySeen { - seenUsns[usn] = true - responses = append(responses, response) - } - } - - return responses, nil -} diff --git a/vendor/github.com/jackpal/go-nat-pmp/LICENSE b/vendor/github.com/jackpal/go-nat-pmp/LICENSE deleted file mode 100644 index 249514b0..00000000 --- a/vendor/github.com/jackpal/go-nat-pmp/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ - Copyright 2013 John Howard Palevich - - 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. diff --git a/vendor/github.com/jackpal/go-nat-pmp/natpmp.go b/vendor/github.com/jackpal/go-nat-pmp/natpmp.go deleted file mode 100644 index e4206530..00000000 --- a/vendor/github.com/jackpal/go-nat-pmp/natpmp.go +++ /dev/null @@ -1,144 +0,0 @@ -package natpmp - -import ( - "fmt" - "net" -) - -// Implement the NAT-PMP protocol, typically supported by Apple routers and open source -// routers such as DD-WRT and Tomato. -// -// See http://tools.ietf.org/html/draft-cheshire-nat-pmp-03 -// -// Usage: -// -// client := natpmp.NewClient(gatewayIP) -// response, err := client.GetExternalAddress() - -// The recommended mapping lifetime for AddPortMapping -const RECOMMENDED_MAPPING_LIFETIME_SECONDS = 3600 - -// Interface used to make remote procedure calls. -type caller interface { - call(msg []byte) (result []byte, err error) -} - -// Client is a NAT-PMP protocol client. -type Client struct { - caller caller -} - -// Create a NAT-PMP client for the NAT-PMP server at the gateway. -func NewClient(gateway net.IP) (nat *Client) { - return &Client{&network{gateway}} -} - -// Results of the NAT-PMP GetExternalAddress operation. -type GetExternalAddressResult struct { - SecondsSinceStartOfEpoc uint32 - ExternalIPAddress [4]byte -} - -// Get the external address of the router. -func (n *Client) GetExternalAddress() (result *GetExternalAddressResult, err error) { - msg := make([]byte, 2) - msg[0] = 0 // Version 0 - msg[1] = 0 // OP Code 0 - response, err := n.rpc(msg, 12) - if err != nil { - return - } - result = &GetExternalAddressResult{} - result.SecondsSinceStartOfEpoc = readNetworkOrderUint32(response[4:8]) - copy(result.ExternalIPAddress[:], response[8:12]) - return -} - -// Results of the NAT-PMP AddPortMapping operation -type AddPortMappingResult struct { - SecondsSinceStartOfEpoc uint32 - InternalPort uint16 - MappedExternalPort uint16 - PortMappingLifetimeInSeconds uint32 -} - -// Add (or delete) a port mapping. To delete a mapping, set the requestedExternalPort and lifetime to 0 -func (n *Client) AddPortMapping(protocol string, internalPort, requestedExternalPort int, lifetime int) (result *AddPortMappingResult, err error) { - var opcode byte - if protocol == "udp" { - opcode = 1 - } else if protocol == "tcp" { - opcode = 2 - } else { - err = fmt.Errorf("unknown protocol %v", protocol) - return - } - msg := make([]byte, 12) - msg[0] = 0 // Version 0 - msg[1] = opcode - writeNetworkOrderUint16(msg[4:6], uint16(internalPort)) - writeNetworkOrderUint16(msg[6:8], uint16(requestedExternalPort)) - writeNetworkOrderUint32(msg[8:12], uint32(lifetime)) - response, err := n.rpc(msg, 16) - if err != nil { - return - } - result = &AddPortMappingResult{} - result.SecondsSinceStartOfEpoc = readNetworkOrderUint32(response[4:8]) - result.InternalPort = readNetworkOrderUint16(response[8:10]) - result.MappedExternalPort = readNetworkOrderUint16(response[10:12]) - result.PortMappingLifetimeInSeconds = readNetworkOrderUint32(response[12:16]) - return -} - -func (n *Client) rpc(msg []byte, resultSize int) (result []byte, err error) { - result, err = n.caller.call(msg) - if err != nil { - return - } - err = protocolChecks(msg, resultSize, result) - return -} - -func protocolChecks(msg []byte, resultSize int, result []byte) (err error) { - if len(result) != resultSize { - err = fmt.Errorf("unexpected result size %d, expected %d", len(result), resultSize) - return - } - if result[0] != 0 { - err = fmt.Errorf("unknown protocol version %d", result[0]) - return - } - expectedOp := msg[1] | 0x80 - if result[1] != expectedOp { - err = fmt.Errorf("Unexpected opcode %d. Expected %d", result[1], expectedOp) - return - } - resultCode := readNetworkOrderUint16(result[2:4]) - if resultCode != 0 { - err = fmt.Errorf("Non-zero result code %d", resultCode) - return - } - // If we got here the RPC is good. - return -} - -func writeNetworkOrderUint16(buf []byte, d uint16) { - buf[0] = byte(d >> 8) - buf[1] = byte(d) -} - -func writeNetworkOrderUint32(buf []byte, d uint32) { - buf[0] = byte(d >> 24) - buf[1] = byte(d >> 16) - buf[2] = byte(d >> 8) - buf[3] = byte(d) -} - -func readNetworkOrderUint16(buf []byte) uint16 { - return (uint16(buf[0]) << 8) | uint16(buf[1]) -} - -func readNetworkOrderUint32(buf []byte) uint32 { - return (uint32(buf[0]) << 24) | (uint32(buf[1]) << 16) | (uint32(buf[2]) << 8) | uint32(buf[3]) -} diff --git a/vendor/github.com/jackpal/go-nat-pmp/network.go b/vendor/github.com/jackpal/go-nat-pmp/network.go deleted file mode 100644 index 9def1acd..00000000 --- a/vendor/github.com/jackpal/go-nat-pmp/network.go +++ /dev/null @@ -1,72 +0,0 @@ -package natpmp - -import ( - "fmt" - "log" - "net" - "time" -) - -const nAT_PMP_PORT = 5351 -const nAT_TRIES = 9 -const nAT_INITIAL_MS = 250 - -// A caller that implements the NAT-PMP RPC protocol. -type network struct { - gateway net.IP -} - -func (n *network) call(msg []byte) (result []byte, err error) { - var server net.UDPAddr - server.IP = n.gateway - server.Port = nAT_PMP_PORT - conn, err := net.DialUDP("udp", nil, &server) - if err != nil { - return - } - defer conn.Close() - - // 16 bytes is the maximum result size. - result = make([]byte, 16) - - needNewDeadline := true - - var tries uint - for tries = 0; tries < nAT_TRIES; { - if needNewDeadline { - err = conn.SetDeadline(time.Now().Add((nAT_INITIAL_MS << tries) * time.Millisecond)) - if err != nil { - return - } - needNewDeadline = false - } - _, err = conn.Write(msg) - if err != nil { - return - } - var bytesRead int - var remoteAddr *net.UDPAddr - bytesRead, remoteAddr, err = conn.ReadFromUDP(result) - if err != nil { - if err.(net.Error).Timeout() { - tries++ - needNewDeadline = true - continue - } - return - } - if !remoteAddr.IP.Equal(n.gateway) { - log.Printf("Ignoring packet because IPs differ:", remoteAddr, n.gateway) - // Ignore this packet. - // Continue without increasing retransmission timeout or deadline. - continue - } - // Trim result to actual number of bytes received - if bytesRead < len(result) { - result = result[:bytesRead] - } - return - } - err = fmt.Errorf("Timed out trying to contact gateway") - return -} diff --git a/vendor/github.com/jackpal/go-nat-pmp/recorder.go b/vendor/github.com/jackpal/go-nat-pmp/recorder.go deleted file mode 100644 index e70a3c65..00000000 --- a/vendor/github.com/jackpal/go-nat-pmp/recorder.go +++ /dev/null @@ -1,17 +0,0 @@ -package natpmp - -type callObserver interface { - observeCall(msg []byte, result []byte, err error) -} - -// A caller that records the RPC call. -type recorder struct { - child caller - observer callObserver -} - -func (n *recorder) call(msg []byte) (result []byte, err error) { - result, err = n.child.call(msg) - n.observer.observeCall(msg, result, err) - return -} diff --git a/vendor/github.com/karalabe/hid/.travis.yml b/vendor/github.com/karalabe/hid/.travis.yml deleted file mode 100644 index 54c6bbdb..00000000 --- a/vendor/github.com/karalabe/hid/.travis.yml +++ /dev/null @@ -1,31 +0,0 @@ -language: go - -matrix: - include: - - os: linux - dist: trusty - go: 1.5.x - - os: linux - dist: trusty - go: 1.6.x - - os: linux - dist: trusty - go: 1.7.x - - os: linux - dist: trusty - go: 1.8.x - - os: linux - dist: trusty - go: 1.9.x - - os: linux - dist: precise - go: 1.9.x - - os: linux - dist: precise - go: 1.10.x - - os: osx - go: 1.10.x - -script: - - go install ./... - - go test -v ./... diff --git a/vendor/github.com/karalabe/hid/LICENSE.md b/vendor/github.com/karalabe/hid/LICENSE.md deleted file mode 100644 index 230d1dae..00000000 --- a/vendor/github.com/karalabe/hid/LICENSE.md +++ /dev/null @@ -1,8 +0,0 @@ -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 LGPL 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 LGPL 2.1 or later on Linux and 3-clause BSD on other platforms. diff --git a/vendor/github.com/karalabe/hid/README.md b/vendor/github.com/karalabe/hid/README.md deleted file mode 100644 index 2851ffe4..00000000 --- a/vendor/github.com/karalabe/hid/README.md +++ /dev/null @@ -1,53 +0,0 @@ -[![Travis][travisimg]][travisurl] -[![AppVeyor][appveyorimg]][appveyorurl] -[![GoDoc][docimg]][docurl] - -[travisimg]: https://travis-ci.org/karalabe/hid.svg?branch=master -[travisurl]: https://travis-ci.org/karalabe/hid -[appveyorimg]: https://ci.appveyor.com/api/projects/status/plroy54odykb0ch3/branch/master?svg=true -[appveyorurl]: https://ci.appveyor.com/project/karalabe/hid -[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). - -## Cross-compiling - -Using `go get` the embedded C library is compiled into the binary format of your host OS. Cross compiling to a different platform or architecture entails disabling CGO by default in Go, causing device enumeration `hid.Enumerate()` to yield no results. - -To cross compile a functional version of this library, you'll need to enable CGO during cross compilation via `CGO_ENABLED=1` and you'll need to install and set a cross compilation enabled C toolkit via `CC=your-cross-gcc`. - -## 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 LGPL 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 LGPL 2.1 or later on Linux and 3-clause BSD on other platforms. diff --git a/vendor/github.com/karalabe/hid/appveyor.yml b/vendor/github.com/karalabe/hid/appveyor.yml deleted file mode 100644 index 84b3c95f..00000000 --- a/vendor/github.com/karalabe/hid/appveyor.yml +++ /dev/null @@ -1,32 +0,0 @@ -os: Visual Studio 2015 - -# Clone directly into GOPATH. -clone_folder: C:\gopath\src\github.com\karalabe\hid -clone_depth: 1 -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.10.1.windows-%GOARCH%.zip - - 7z x go1.10.1.windows-%GOARCH%.zip -y -oC:\ > NUL - - go version - - gcc --version - -build_script: - - go install ./... - - go test -v ./... diff --git a/vendor/github.com/karalabe/hid/hid.go b/vendor/github.com/karalabe/hid/hid.go deleted file mode 100644 index 60a40b8c..00000000 --- a/vendor/github.com/karalabe/hid/hid.go +++ /dev/null @@ -1,37 +0,0 @@ -// 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 LGPL 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 -} diff --git a/vendor/github.com/karalabe/hid/hid_disabled.go b/vendor/github.com/karalabe/hid/hid_disabled.go deleted file mode 100644 index 0f266ba5..00000000 --- a/vendor/github.com/karalabe/hid/hid_disabled.go +++ /dev/null @@ -1,51 +0,0 @@ -// 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 LGPL 2.1 or later. - -// +build !linux,!darwin,!windows ios !cgo - -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() error { return nil } - -// 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 -} diff --git a/vendor/github.com/karalabe/hid/hid_enabled.go b/vendor/github.com/karalabe/hid/hid_enabled.go deleted file mode 100644 index 189ad2a5..00000000 --- a/vendor/github.com/karalabe/hid/hid_enabled.go +++ /dev/null @@ -1,229 +0,0 @@ -// 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 LGNU GPL 2.1 or later. - -// +build linux,cgo darwin,!ios,cgo windows,cgo - -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 linux,!android LDFLAGS: -lrt -#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 - #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" -) - -// enumerateLock is a mutex serializing access to USB device enumeration needed -// by the macOS USB HID system calls, which require 2 consecutive method calls -// for enumeration, causing crashes if called concurrently. -// -// For more details, see: -// https://developer.apple.com/documentation/iokit/1438371-iohidmanagersetdevicematching -// > "subsequent calls will cause the hid manager to release previously enumerated devices" -var enumerateLock sync.Mutex - -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 { - enumerateLock.Lock() - defer enumerateLock.Unlock() - - // 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() error { - dev.lock.Lock() - defer dev.lock.Unlock() - - if dev.device != nil { - C.hid_close(dev.device) - dev.device = nil - } - return 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 -} diff --git a/vendor/github.com/karalabe/hid/hidapi/AUTHORS.txt b/vendor/github.com/karalabe/hid/hidapi/AUTHORS.txt deleted file mode 100644 index 7acafd78..00000000 --- a/vendor/github.com/karalabe/hid/hidapi/AUTHORS.txt +++ /dev/null @@ -1,16 +0,0 @@ - -HIDAPI Authors: - -Alan Ott : - Original Author and Maintainer - Linux, Windows, and Mac implementations - -Ludovic Rousseau : - 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 - diff --git a/vendor/github.com/karalabe/hid/hidapi/LICENSE-bsd.txt b/vendor/github.com/karalabe/hid/hidapi/LICENSE-bsd.txt deleted file mode 100644 index 538cdf95..00000000 --- a/vendor/github.com/karalabe/hid/hidapi/LICENSE-bsd.txt +++ /dev/null @@ -1,26 +0,0 @@ -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. diff --git a/vendor/github.com/karalabe/hid/hidapi/LICENSE-gpl3.txt b/vendor/github.com/karalabe/hid/hidapi/LICENSE-gpl3.txt deleted file mode 100644 index 94a9ed02..00000000 --- a/vendor/github.com/karalabe/hid/hidapi/LICENSE-gpl3.txt +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/vendor/github.com/karalabe/hid/hidapi/LICENSE-orig.txt b/vendor/github.com/karalabe/hid/hidapi/LICENSE-orig.txt deleted file mode 100644 index e3f33808..00000000 --- a/vendor/github.com/karalabe/hid/hidapi/LICENSE-orig.txt +++ /dev/null @@ -1,9 +0,0 @@ - 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. diff --git a/vendor/github.com/karalabe/hid/hidapi/LICENSE.txt b/vendor/github.com/karalabe/hid/hidapi/LICENSE.txt deleted file mode 100644 index e1676d4c..00000000 --- a/vendor/github.com/karalabe/hid/hidapi/LICENSE.txt +++ /dev/null @@ -1,13 +0,0 @@ -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. - diff --git a/vendor/github.com/karalabe/hid/hidapi/README.txt b/vendor/github.com/karalabe/hid/hidapi/README.txt deleted file mode 100644 index f19dae4a..00000000 --- a/vendor/github.com/karalabe/hid/hidapi/README.txt +++ /dev/null @@ -1,339 +0,0 @@ - HIDAPI library for Windows, Linux, FreeBSD and Mac OS X - ========================================================= - -About -====== - -HIDAPI is a multi-platform library which allows an application to interface -with USB and Bluetooth HID-Class devices on Windows, Linux, FreeBSD, and Mac -OS X. HIDAPI can be either built as a shared library (.so or .dll) or -can be embedded directly into a target application by adding a single source -file (per platform) and a single header. - -HIDAPI has four back-ends: - * Windows (using hid.dll) - * Linux/hidraw (using the Kernel's hidraw driver) - * Linux/libusb (using libusb-1.0) - * FreeBSD (using libusb-1.0) - * Mac (using IOHidManager) - -On Linux, either the hidraw or the libusb back-end can be used. There are -tradeoffs, and the functionality supported is slightly different. - -Linux/hidraw (linux/hid.c): -This back-end uses the hidraw interface in the Linux kernel. While this -back-end will support both USB and Bluetooth, it has some limitations on -kernels prior to 2.6.39, including the inability to send or receive feature -reports. In addition, it will only communicate with devices which have -hidraw nodes associated with them. Keyboards, mice, and some other devices -which are blacklisted from having hidraw nodes will not work. Fortunately, -for nearly all the uses of hidraw, this is not a problem. - -Linux/FreeBSD/libusb (libusb/hid.c): -This back-end uses libusb-1.0 to communicate directly to a USB device. This -back-end will of course not work with Bluetooth devices. - -HIDAPI also comes with a Test GUI. The Test GUI is cross-platform and uses -Fox Toolkit (http://www.fox-toolkit.org). It will build on every platform -which HIDAPI supports. Since it relies on a 3rd party library, building it -is optional but recommended because it is so useful when debugging hardware. - -What Does the API Look Like? -============================= -The API provides the the most commonly used HID functions including sending -and receiving of input, output, and feature reports. The sample program, -which communicates with a heavily hacked up version of the Microchip USB -Generic HID sample looks like this (with error checking removed for -simplicity): - -#ifdef WIN32 -#include -#endif -#include -#include -#include "hidapi.h" - -#define MAX_STR 255 - -int main(int argc, char* argv[]) -{ - int res; - unsigned char buf[65]; - wchar_t wstr[MAX_STR]; - hid_device *handle; - int i; - - // Initialize the hidapi library - res = hid_init(); - - // Open the device using the VID, PID, - // and optionally the Serial number. - handle = hid_open(0x4d8, 0x3f, NULL); - - // Read the Manufacturer String - res = hid_get_manufacturer_string(handle, wstr, MAX_STR); - wprintf(L"Manufacturer String: %s\n", wstr); - - // Read the Product String - res = hid_get_product_string(handle, wstr, MAX_STR); - wprintf(L"Product String: %s\n", wstr); - - // Read the Serial Number String - res = hid_get_serial_number_string(handle, wstr, MAX_STR); - wprintf(L"Serial Number String: (%d) %s\n", wstr[0], wstr); - - // Read Indexed String 1 - res = hid_get_indexed_string(handle, 1, wstr, MAX_STR); - wprintf(L"Indexed String 1: %s\n", wstr); - - // Toggle LED (cmd 0x80). The first byte is the report number (0x0). - buf[0] = 0x0; - buf[1] = 0x80; - res = hid_write(handle, buf, 65); - - // Request state (cmd 0x81). The first byte is the report number (0x0). - buf[0] = 0x0; - buf[1] = 0x81; - res = hid_write(handle, buf, 65); - - // Read requested state - res = hid_read(handle, buf, 65); - - // Print out the returned buffer. - for (i = 0; i < 4; i++) - printf("buf[%d]: %d\n", i, buf[i]); - - // Finalize the hidapi library - res = hid_exit(); - - return 0; -} - -If you have your own simple test programs which communicate with standard -hardware development boards (such as those from Microchip, TI, Atmel, -FreeScale and others), please consider sending me something like the above -for inclusion into the HIDAPI source. This will help others who have the -same hardware as you do. - -License -======== -HIDAPI may be used by one of three licenses as outlined in LICENSE.txt. - -Download -========= -HIDAPI can be downloaded from github - git clone git://github.com/signal11/hidapi.git - -Build Instructions -=================== - -This section is long. Don't be put off by this. It's not long because it's -complicated to build HIDAPI; it's quite the opposite. This section is long -because of the flexibility of HIDAPI and the large number of ways in which -it can be built and used. You will likely pick a single build method. - -HIDAPI can be built in several different ways. If you elect to build a -shared library, you will need to build it from the HIDAPI source -distribution. If you choose instead to embed HIDAPI directly into your -application, you can skip the building and look at the provided platform -Makefiles for guidance. These platform Makefiles are located in linux/ -libusb/ mac/ and windows/ and are called Makefile-manual. In addition, -Visual Studio projects are provided. Even if you're going to embed HIDAPI -into your project, it is still beneficial to build the example programs. - - -Prerequisites: ---------------- - - Linux: - ------- - On Linux, you will need to install development packages for libudev, - libusb and optionally Fox-toolkit (for the test GUI). On - Debian/Ubuntu systems these can be installed by running: - sudo apt-get install libudev-dev libusb-1.0-0-dev libfox-1.6-dev - - If you downloaded the source directly from the git repository (using - git clone), you'll need Autotools: - sudo apt-get install autotools-dev autoconf automake libtool - - FreeBSD: - --------- - On FreeBSD you will need to install GNU make, libiconv, and - optionally Fox-Toolkit (for the test GUI). This is done by running - the following: - pkg_add -r gmake libiconv fox16 - - If you downloaded the source directly from the git repository (using - git clone), you'll need Autotools: - pkg_add -r autotools - - Mac: - ----- - On Mac, you will need to install Fox-Toolkit if you wish to build - the Test GUI. There are two ways to do this, and each has a slight - complication. Which method you use depends on your use case. - - If you wish to build the Test GUI just for your own testing on your - own computer, then the easiest method is to install Fox-Toolkit - using ports: - sudo port install fox - - If you wish to build the TestGUI app bundle to redistribute to - others, you will need to install Fox-toolkit from source. This is - because the version of fox that gets installed using ports uses the - ports X11 libraries which are not compatible with the Apple X11 - libraries. If you install Fox with ports and then try to distribute - your built app bundle, it will simply fail to run on other systems. - To install Fox-Toolkit manually, download the source package from - http://www.fox-toolkit.org, extract it, and run the following from - within the extracted source: - ./configure && make && make install - - Windows: - --------- - On Windows, if you want to build the test GUI, you will need to get - the hidapi-externals.zip package from the download site. This - contains pre-built binaries for Fox-toolkit. Extract - hidapi-externals.zip just outside of hidapi, so that - hidapi-externals and hidapi are on the same level, as shown: - - Parent_Folder - | - +hidapi - +hidapi-externals - - Again, this step is not required if you do not wish to build the - test GUI. - - -Building HIDAPI into a shared library on Unix Platforms: ---------------------------------------------------------- - -On Unix-like systems such as Linux, FreeBSD, Mac, and even Windows, using -Mingw or Cygwin, the easiest way to build a standard system-installed shared -library is to use the GNU Autotools build system. If you checked out the -source from the git repository, run the following: - - ./bootstrap - ./configure - make - make install <----- as root, or using sudo - -If you downloaded a source package (ie: if you did not run git clone), you -can skip the ./bootstrap step. - -./configure can take several arguments which control the build. The two most -likely to be used are: - --enable-testgui - Enable build of the Test GUI. This requires Fox toolkit to - be installed. Instructions for installing Fox-Toolkit on - each platform are in the Prerequisites section above. - - --prefix=/usr - Specify where you want the output headers and libraries to - be installed. The example above will put the headers in - /usr/include and the binaries in /usr/lib. The default is to - install into /usr/local which is fine on most systems. - -Building the manual way on Unix platforms: -------------------------------------------- - -Manual Makefiles are provided mostly to give the user and idea what it takes -to build a program which embeds HIDAPI directly inside of it. These should -really be used as examples only. If you want to build a system-wide shared -library, use the Autotools method described above. - - To build HIDAPI using the manual makefiles, change to the directory - of your platform and run make. For example, on Linux run: - cd linux/ - make -f Makefile-manual - - To build the Test GUI using the manual makefiles: - cd testgui/ - make -f Makefile-manual - -Building on Windows: ---------------------- - -To build the HIDAPI DLL on Windows using Visual Studio, build the .sln file -in the windows/ directory. - -To build the Test GUI on windows using Visual Studio, build the .sln file in -the testgui/ directory. - -To build HIDAPI using MinGW or Cygwin using Autotools, use the instructions -in the section titled "Building HIDAPI into a shared library on Unix -Platforms" above. Note that building the Test GUI with MinGW or Cygwin will -require the Windows procedure in the Prerequisites section above (ie: -hidapi-externals.zip). - -To build HIDAPI using MinGW using the Manual Makefiles, see the section -"Building the manual way on Unix platforms" above. - -HIDAPI can also be built using the Windows DDK (now also called the Windows -Driver Kit or WDK). This method was originally required for the HIDAPI build -but not anymore. However, some users still prefer this method. It is not as -well supported anymore but should still work. Patches are welcome if it does -not. To build using the DDK: - - 1. Install the Windows Driver Kit (WDK) from Microsoft. - 2. From the Start menu, in the Windows Driver Kits folder, select Build - Environments, then your operating system, then the x86 Free Build - Environment (or one that is appropriate for your system). - 3. From the console, change directory to the windows/ddk_build/ directory, - which is part of the HIDAPI distribution. - 4. Type build. - 5. You can find the output files (DLL and LIB) in a subdirectory created - by the build system which is appropriate for your environment. On - Windows XP, this directory is objfre_wxp_x86/i386. - -Cross Compiling -================ - -This section talks about cross compiling HIDAPI for Linux using autotools. -This is useful for using HIDAPI on embedded Linux targets. These -instructions assume the most raw kind of embedded Linux build, where all -prerequisites will need to be built first. This process will of course vary -based on your embedded Linux build system if you are using one, such as -OpenEmbedded or Buildroot. - -For the purpose of this section, it will be assumed that the following -environment variables are exported. - - $ export STAGING=$HOME/out - $ export HOST=arm-linux - -STAGING and HOST can be modified to suit your setup. - -Prerequisites --------------- - -Note that the build of libudev is the very basic configuration. - -Build Libusb. From the libusb source directory, run: - ./configure --host=$HOST --prefix=$STAGING - make - make install - -Build libudev. From the libudev source directory, run: - ./configure --disable-gudev --disable-introspection --disable-hwdb \ - --host=$HOST --prefix=$STAGING - make - make install - -Building HIDAPI ----------------- - -Build HIDAPI: - - PKG_CONFIG_DIR= \ - PKG_CONFIG_LIBDIR=$STAGING/lib/pkgconfig:$STAGING/share/pkgconfig \ - PKG_CONFIG_SYSROOT_DIR=$STAGING \ - ./configure --host=$HOST --prefix=$STAGING - - -Signal 11 Software - 2010-04-11 - 2010-07-28 - 2011-09-10 - 2012-05-01 - 2012-07-03 diff --git a/vendor/github.com/karalabe/hid/hidapi/hidapi/hidapi.h b/vendor/github.com/karalabe/hid/hidapi/hidapi/hidapi.h deleted file mode 100644 index e5bc2dc4..00000000 --- a/vendor/github.com/karalabe/hid/hidapi/hidapi/hidapi.h +++ /dev/null @@ -1,391 +0,0 @@ -/******************************************************* - HIDAPI - Multi-Platform library for - communication with HID devices. - - Alan Ott - Signal 11 Software - - 8/22/2009 - - Copyright 2009, All Rights Reserved. - - At the discretion of the user of this library, - this software may be licensed under the terms of the - GNU General Public License v3, a BSD-Style license, or the - original HIDAPI license as outlined in the LICENSE.txt, - LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt - files located at the root of the source distribution. - These files may also be found in the public source - code repository located at: - http://github.com/signal11/hidapi . -********************************************************/ - -/** @file - * @defgroup API hidapi API - */ - -#ifndef HIDAPI_H__ -#define HIDAPI_H__ - -#include - -#ifdef _WIN32 - #define HID_API_EXPORT __declspec(dllexport) - #define HID_API_CALL -#else - #define HID_API_EXPORT /**< API export macro */ - #define HID_API_CALL /**< API call macro */ -#endif - -#define HID_API_EXPORT_CALL HID_API_EXPORT HID_API_CALL /**< API export and call macro*/ - -#ifdef __cplusplus -extern "C" { -#endif - struct hid_device_; - typedef struct hid_device_ hid_device; /**< opaque hidapi structure */ - - /** hidapi info structure */ - struct hid_device_info { - /** Platform-specific device path */ - char *path; - /** Device Vendor ID */ - unsigned short vendor_id; - /** Device Product ID */ - unsigned short product_id; - /** Serial Number */ - wchar_t *serial_number; - /** Device Release Number in binary-coded decimal, - also known as Device Version Number */ - unsigned short release_number; - /** Manufacturer String */ - wchar_t *manufacturer_string; - /** Product string */ - wchar_t *product_string; - /** Usage Page for this Device/Interface - (Windows/Mac only). */ - unsigned short usage_page; - /** Usage for this Device/Interface - (Windows/Mac only).*/ - unsigned short usage; - /** 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. */ - int interface_number; - - /** Pointer to the next device */ - struct hid_device_info *next; - }; - - - /** @brief Initialize the HIDAPI library. - - This function initializes the HIDAPI library. Calling it is not - strictly necessary, as it will be called automatically by - hid_enumerate() and any of the hid_open_*() functions if it is - needed. This function should be called at the beginning of - execution however, if there is a chance of HIDAPI handles - being opened by different threads simultaneously. - - @ingroup API - - @returns - This function returns 0 on success and -1 on error. - */ - int HID_API_EXPORT HID_API_CALL hid_init(void); - - /** @brief Finalize the HIDAPI library. - - This function frees all of the static data associated with - HIDAPI. It should be called at the end of execution to avoid - memory leaks. - - @ingroup API - - @returns - This function returns 0 on success and -1 on error. - */ - int HID_API_EXPORT HID_API_CALL hid_exit(void); - - /** @brief Enumerate the HID Devices. - - This function returns a linked list of all the HID devices - attached to the system which match vendor_id and product_id. - If @p vendor_id is set to 0 then any vendor matches. - If @p product_id is set to 0 then any product matches. - If @p vendor_id and @p product_id are both set to 0, then - all HID devices will be returned. - - @ingroup API - @param vendor_id The Vendor ID (VID) of the types of device - to open. - @param product_id The Product ID (PID) of the types of - device to open. - - @returns - This function returns a pointer to a linked list of type - struct #hid_device, containing information about the HID devices - attached to the system, or NULL in the case of failure. Free - this linked list by calling hid_free_enumeration(). - */ - struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned short vendor_id, unsigned short product_id); - - /** @brief Free an enumeration Linked List - - This function frees a linked list created by hid_enumerate(). - - @ingroup API - @param devs Pointer to a list of struct_device returned from - hid_enumerate(). - */ - void HID_API_EXPORT HID_API_CALL hid_free_enumeration(struct hid_device_info *devs); - - /** @brief Open a HID device using a Vendor ID (VID), Product ID - (PID) and optionally a serial number. - - If @p serial_number is NULL, the first device with the - specified VID and PID is opened. - - @ingroup API - @param vendor_id The Vendor ID (VID) of the device to open. - @param product_id The Product ID (PID) of the device to open. - @param serial_number The Serial Number of the device to open - (Optionally NULL). - - @returns - This function returns a pointer to a #hid_device object on - success or NULL on failure. - */ - HID_API_EXPORT hid_device * HID_API_CALL hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number); - - /** @brief Open a HID device by its path name. - - The path name be determined by calling hid_enumerate(), or a - platform-specific path name can be used (eg: /dev/hidraw0 on - Linux). - - @ingroup API - @param path The path name of the device to open - - @returns - This function returns a pointer to a #hid_device object on - success or NULL on failure. - */ - HID_API_EXPORT hid_device * HID_API_CALL hid_open_path(const char *path); - - /** @brief Write an Output report to a HID device. - - The first byte of @p data[] must contain the Report ID. For - devices which only support a single report, this must be set - to 0x0. The remaining bytes contain the report data. Since - the Report ID is mandatory, calls to hid_write() will always - contain one more byte than the report contains. For example, - if a hid report is 16 bytes long, 17 bytes must be passed to - hid_write(), the Report ID (or 0x0, for devices with a - single report), followed by the report data (16 bytes). In - this example, the length passed in would be 17. - - hid_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). - - @ingroup API - @param device A device handle returned from hid_open(). - @param data The data to send, including the report number as - the first byte. - @param length The length in bytes of the data to send. - - @returns - This function returns the actual number of bytes written and - -1 on error. - */ - int HID_API_EXPORT HID_API_CALL hid_write(hid_device *device, const unsigned char *data, size_t length); - - /** @brief Read an Input report from a HID device with timeout. - - Input reports are returned - to the host through the INTERRUPT IN endpoint. The first byte will - contain the Report number if the device uses numbered reports. - - @ingroup API - @param device A device handle returned from hid_open(). - @param data A buffer to put the read data into. - @param length The number of bytes to read. For devices with - multiple reports, make sure to read an extra byte for - the report number. - @param milliseconds timeout in milliseconds or -1 for blocking wait. - - @returns - This function returns the actual number of bytes read and - -1 on error. If no packet was available to be read within - the timeout period, this function returns 0. - */ - int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds); - - /** @brief Read an Input report from a HID device. - - Input reports are returned - to the host through the INTERRUPT IN endpoint. The first byte will - contain the Report number if the device uses numbered reports. - - @ingroup API - @param device A device handle returned from hid_open(). - @param data A buffer to put the read data into. - @param length The number of bytes to read. For devices with - multiple reports, make sure to read an extra byte for - the report number. - - @returns - This function returns the actual number of bytes read and - -1 on error. If no packet was available to be read and - the handle is in non-blocking mode, this function returns 0. - */ - int HID_API_EXPORT HID_API_CALL hid_read(hid_device *device, unsigned char *data, size_t length); - - /** @brief Set the device handle to be non-blocking. - - In non-blocking mode calls to hid_read() will return - immediately with a value of 0 if there is no data to be - read. In blocking mode, hid_read() will wait (block) until - there is data to read before returning. - - Nonblocking can be turned on and off at any time. - - @ingroup API - @param device A device handle returned from hid_open(). - @param nonblock enable or not the nonblocking reads - - 1 to enable nonblocking - - 0 to disable nonblocking. - - @returns - This function returns 0 on success and -1 on error. - */ - int HID_API_EXPORT HID_API_CALL hid_set_nonblocking(hid_device *device, int nonblock); - - /** @brief Send a Feature report to the device. - - Feature reports are sent over the Control endpoint as a - Set_Report transfer. The first byte of @p data[] must - contain the Report ID. For devices which only support a - single report, this must be set to 0x0. The remaining bytes - contain the report data. Since the Report ID is mandatory, - calls to hid_send_feature_report() will always contain one - more byte than the report contains. For example, if a hid - report is 16 bytes long, 17 bytes must be passed to - hid_send_feature_report(): the Report ID (or 0x0, for - devices which do not use numbered reports), followed by the - report data (16 bytes). In this example, the length passed - in would be 17. - - @ingroup API - @param device A device handle returned from hid_open(). - @param data The data to send, including the report number as - the first byte. - @param length The length in bytes of the data to send, including - the report number. - - @returns - This function returns the actual number of bytes written and - -1 on error. - */ - int HID_API_EXPORT HID_API_CALL hid_send_feature_report(hid_device *device, const unsigned char *data, size_t length); - - /** @brief Get a feature report from a HID device. - - Set the first byte of @p data[] to the Report ID of the - report to be read. Make sure to allow space for this - extra byte in @p data[]. Upon return, the first byte will - still contain the Report ID, and the report data will - start in data[1]. - - @ingroup API - @param device A device handle returned from hid_open(). - @param data A buffer to put the read data into, including - the Report ID. Set the first byte of @p data[] to the - Report ID of the report to be read, or set it to zero - if your device does not use numbered reports. - @param length The number of bytes to read, including an - extra byte for the report ID. The buffer can be longer - than the actual report. - - @returns - This function returns the number of bytes read plus - one for the report ID (which is still in the first - byte), or -1 on error. - */ - int HID_API_EXPORT HID_API_CALL hid_get_feature_report(hid_device *device, unsigned char *data, size_t length); - - /** @brief Close a HID device. - - @ingroup API - @param device A device handle returned from hid_open(). - */ - void HID_API_EXPORT HID_API_CALL hid_close(hid_device *device); - - /** @brief Get The Manufacturer String from a HID device. - - @ingroup API - @param device A device handle returned from hid_open(). - @param string A wide string buffer to put the data into. - @param maxlen The length of the buffer in multiples of wchar_t. - - @returns - This function returns 0 on success and -1 on error. - */ - int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *device, wchar_t *string, size_t maxlen); - - /** @brief Get The Product String from a HID device. - - @ingroup API - @param device A device handle returned from hid_open(). - @param string A wide string buffer to put the data into. - @param maxlen The length of the buffer in multiples of wchar_t. - - @returns - This function returns 0 on success and -1 on error. - */ - int HID_API_EXPORT_CALL hid_get_product_string(hid_device *device, wchar_t *string, size_t maxlen); - - /** @brief Get The Serial Number String from a HID device. - - @ingroup API - @param device A device handle returned from hid_open(). - @param string A wide string buffer to put the data into. - @param maxlen The length of the buffer in multiples of wchar_t. - - @returns - This function returns 0 on success and -1 on error. - */ - int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *device, wchar_t *string, size_t maxlen); - - /** @brief Get a string from a HID device, based on its string index. - - @ingroup API - @param device A device handle returned from hid_open(). - @param string_index The index of the string to get. - @param string A wide string buffer to put the data into. - @param maxlen The length of the buffer in multiples of wchar_t. - - @returns - This function returns 0 on success and -1 on error. - */ - int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *device, int string_index, wchar_t *string, size_t maxlen); - - /** @brief Get a string describing the last error which occurred. - - @ingroup API - @param device A device handle returned from hid_open(). - - @returns - This function returns a string containing the last error - which occurred or NULL if none has occurred. - */ - HID_API_EXPORT const wchar_t* HID_API_CALL hid_error(hid_device *device); - -#ifdef __cplusplus -} -#endif - -#endif - diff --git a/vendor/github.com/karalabe/hid/hidapi/libusb/hid.c b/vendor/github.com/karalabe/hid/hidapi/libusb/hid.c deleted file mode 100644 index 474dff41..00000000 --- a/vendor/github.com/karalabe/hid/hidapi/libusb/hid.c +++ /dev/null @@ -1,1512 +0,0 @@ -/******************************************************* - HIDAPI - Multi-Platform library for - communication with HID devices. - - Alan Ott - Signal 11 Software - - 8/22/2009 - Linux Version - 6/2/2010 - Libusb Version - 8/13/2010 - FreeBSD Version - 11/1/2011 - - Copyright 2009, All Rights Reserved. - - At the discretion of the user of this library, - this software may be licensed under the terms of the - GNU General Public License v3, a BSD-Style license, or the - original HIDAPI license as outlined in the LICENSE.txt, - LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt - files located at the root of the source distribution. - These files may also be found in the public source - code repository located at: - http://github.com/signal11/hidapi . -********************************************************/ - -/* C */ -#include -#include -#include -#include -#include -#include - -/* Unix */ -#include -#include -#include -#include -#include -#include -#include -#include - -/* GNU / LibUSB */ -#include -#ifndef __ANDROID__ -#include -#endif - -#include "hidapi.h" - -#ifdef __ANDROID__ - -/* Barrier implementation because Android/Bionic don't have pthread_barrier. - This implementation came from Brent Priddy and was posted on - StackOverflow. It is used with his permission. */ -typedef int pthread_barrierattr_t; -typedef struct pthread_barrier { - pthread_mutex_t mutex; - pthread_cond_t cond; - int count; - int trip_count; -} pthread_barrier_t; - -static int pthread_barrier_init(pthread_barrier_t *barrier, const pthread_barrierattr_t *attr, unsigned int count) -{ - if(count == 0) { - errno = EINVAL; - return -1; - } - - if(pthread_mutex_init(&barrier->mutex, 0) < 0) { - return -1; - } - if(pthread_cond_init(&barrier->cond, 0) < 0) { - pthread_mutex_destroy(&barrier->mutex); - return -1; - } - barrier->trip_count = count; - barrier->count = 0; - - return 0; -} - -static int pthread_barrier_destroy(pthread_barrier_t *barrier) -{ - pthread_cond_destroy(&barrier->cond); - pthread_mutex_destroy(&barrier->mutex); - return 0; -} - -static int pthread_barrier_wait(pthread_barrier_t *barrier) -{ - pthread_mutex_lock(&barrier->mutex); - ++(barrier->count); - if(barrier->count >= barrier->trip_count) - { - barrier->count = 0; - pthread_cond_broadcast(&barrier->cond); - pthread_mutex_unlock(&barrier->mutex); - return 1; - } - else - { - pthread_cond_wait(&barrier->cond, &(barrier->mutex)); - pthread_mutex_unlock(&barrier->mutex); - return 0; - } -} - -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef DEBUG_PRINTF -#define LOG(...) fprintf(stderr, __VA_ARGS__) -#else -#define LOG(...) do {} while (0) -#endif - -#ifndef __FreeBSD__ -#define DETACH_KERNEL_DRIVER -#endif - -/* Uncomment to enable the retrieval of Usage and Usage Page in -hid_enumerate(). Warning, on platforms different from FreeBSD -this is very invasive as it requires the detach -and re-attach of the kernel driver. See comments inside hid_enumerate(). -libusb HIDAPI programs are encouraged to use the interface number -instead to differentiate between interfaces on a composite HID device. */ -/*#define INVASIVE_GET_USAGE*/ - -/* Linked List of input reports received from the device. */ -struct input_report { - uint8_t *data; - size_t len; - struct input_report *next; -}; - - -struct hid_device_ { - /* Handle to the actual device. */ - libusb_device_handle *device_handle; - - /* Endpoint information */ - int input_endpoint; - int output_endpoint; - int input_ep_max_packet_size; - - /* The interface number of the HID */ - int interface; - - /* Indexes of Strings */ - int manufacturer_index; - int product_index; - int serial_index; - - /* Whether blocking reads are used */ - int blocking; /* boolean */ - - /* Read thread objects */ - pthread_t thread; - pthread_mutex_t mutex; /* Protects input_reports */ - pthread_cond_t condition; - pthread_barrier_t barrier; /* Ensures correct startup sequence */ - int shutdown_thread; - int cancelled; - struct libusb_transfer *transfer; - - /* List of received input reports. */ - struct input_report *input_reports; -}; - -static libusb_context *usb_context = NULL; - -uint16_t get_usb_code_for_current_locale(void); -static int return_data(hid_device *dev, unsigned char *data, size_t length); - -static hid_device *new_hid_device(void) -{ - hid_device *dev = calloc(1, sizeof(hid_device)); - dev->blocking = 1; - - pthread_mutex_init(&dev->mutex, NULL); - pthread_cond_init(&dev->condition, NULL); - pthread_barrier_init(&dev->barrier, NULL, 2); - - return dev; -} - -static void free_hid_device(hid_device *dev) -{ - /* Clean up the thread objects */ - pthread_barrier_destroy(&dev->barrier); - pthread_cond_destroy(&dev->condition); - pthread_mutex_destroy(&dev->mutex); - - /* Free the device itself */ - free(dev); -} - -#if 0 -/*TODO: Implement this funciton on hidapi/libusb.. */ -static void register_error(hid_device *device, const char *op) -{ - -} -#endif - -#ifdef INVASIVE_GET_USAGE -/* Get bytes from a HID Report Descriptor. - Only call with a num_bytes of 0, 1, 2, or 4. */ -static uint32_t get_bytes(uint8_t *rpt, size_t len, size_t num_bytes, size_t cur) -{ - /* Return if there aren't enough bytes. */ - if (cur + num_bytes >= len) - return 0; - - if (num_bytes == 0) - return 0; - else if (num_bytes == 1) { - return rpt[cur+1]; - } - else if (num_bytes == 2) { - return (rpt[cur+2] * 256 + rpt[cur+1]); - } - else if (num_bytes == 4) { - return (rpt[cur+4] * 0x01000000 + - rpt[cur+3] * 0x00010000 + - rpt[cur+2] * 0x00000100 + - rpt[cur+1] * 0x00000001); - } - else - return 0; -} - -/* Retrieves the device's Usage Page and Usage from the report - descriptor. The algorithm is simple, as it just returns the first - Usage and Usage Page that it finds in the descriptor. - The return value is 0 on success and -1 on failure. */ -static int get_usage(uint8_t *report_descriptor, size_t size, - unsigned short *usage_page, unsigned short *usage) -{ - unsigned int i = 0; - int size_code; - int data_len, key_size; - int usage_found = 0, usage_page_found = 0; - - while (i < size) { - int key = report_descriptor[i]; - int key_cmd = key & 0xfc; - - //printf("key: %02hhx\n", key); - - if ((key & 0xf0) == 0xf0) { - /* This is a Long Item. The next byte contains the - length of the data section (value) for this key. - See the HID specification, version 1.11, section - 6.2.2.3, titled "Long Items." */ - if (i+1 < size) - data_len = report_descriptor[i+1]; - else - data_len = 0; /* malformed report */ - key_size = 3; - } - else { - /* This is a Short Item. The bottom two bits of the - key contain the size code for the data section - (value) for this key. Refer to the HID - specification, version 1.11, section 6.2.2.2, - titled "Short Items." */ - size_code = key & 0x3; - switch (size_code) { - case 0: - case 1: - case 2: - data_len = size_code; - break; - case 3: - data_len = 4; - break; - default: - /* Can't ever happen since size_code is & 0x3 */ - data_len = 0; - break; - }; - key_size = 1; - } - - if (key_cmd == 0x4) { - *usage_page = get_bytes(report_descriptor, size, data_len, i); - usage_page_found = 1; - //printf("Usage Page: %x\n", (uint32_t)*usage_page); - } - if (key_cmd == 0x8) { - *usage = get_bytes(report_descriptor, size, data_len, i); - usage_found = 1; - //printf("Usage: %x\n", (uint32_t)*usage); - } - - if (usage_page_found && usage_found) - return 0; /* success */ - - /* Skip over this key and it's associated data */ - i += data_len + key_size; - } - - return -1; /* failure */ -} -#endif /* INVASIVE_GET_USAGE */ - -#if defined(__FreeBSD__) && __FreeBSD__ < 10 -/* The libusb version included in FreeBSD < 10 doesn't have this function. In - mainline libusb, it's inlined in libusb.h. This function will bear a striking - resemblance to that one, because there's about one way to code it. - - Note that the data parameter is Unicode in UTF-16LE encoding. - Return value is the number of bytes in data, or LIBUSB_ERROR_*. - */ -static inline int libusb_get_string_descriptor(libusb_device_handle *dev, - uint8_t descriptor_index, uint16_t lang_id, - unsigned char *data, int length) -{ - return libusb_control_transfer(dev, - LIBUSB_ENDPOINT_IN | 0x0, /* Endpoint 0 IN */ - LIBUSB_REQUEST_GET_DESCRIPTOR, - (LIBUSB_DT_STRING << 8) | descriptor_index, - lang_id, data, (uint16_t) length, 1000); -} - -#endif - - -/* Get the first language the device says it reports. This comes from - USB string #0. */ -static uint16_t get_first_language(libusb_device_handle *dev) -{ - uint16_t buf[32]; - int len; - - /* Get the string from libusb. */ - len = libusb_get_string_descriptor(dev, - 0x0, /* String ID */ - 0x0, /* Language */ - (unsigned char*)buf, - sizeof(buf)); - if (len < 4) - return 0x0; - - return buf[1]; /* First two bytes are len and descriptor type. */ -} - -static int is_language_supported(libusb_device_handle *dev, uint16_t lang) -{ - uint16_t buf[32]; - int len; - int i; - - /* Get the string from libusb. */ - len = libusb_get_string_descriptor(dev, - 0x0, /* String ID */ - 0x0, /* Language */ - (unsigned char*)buf, - sizeof(buf)); - if (len < 4) - return 0x0; - - - len /= 2; /* language IDs are two-bytes each. */ - /* Start at index 1 because there are two bytes of protocol data. */ - for (i = 1; i < len; i++) { - if (buf[i] == lang) - return 1; - } - - return 0; -} - - -/* This function returns a newly allocated wide string containing the USB - device string numbered by the index. The returned string must be freed - by using free(). */ -static wchar_t *get_usb_string(libusb_device_handle *dev, uint8_t idx) -{ - char buf[512]; - int len; - wchar_t *str = NULL; - -#ifndef __ANDROID__ /* we don't use iconv on Android */ - wchar_t wbuf[256]; - /* iconv variables */ - iconv_t ic; - size_t inbytes; - size_t outbytes; - size_t res; -#ifdef __FreeBSD__ - const char *inptr; -#else - char *inptr; -#endif - char *outptr; -#endif - - /* Determine which language to use. */ - uint16_t lang; - lang = get_usb_code_for_current_locale(); - if (!is_language_supported(dev, lang)) - lang = get_first_language(dev); - - /* Get the string from libusb. */ - len = libusb_get_string_descriptor(dev, - idx, - lang, - (unsigned char*)buf, - sizeof(buf)); - if (len < 0) - return NULL; - -#ifdef __ANDROID__ - - /* Bionic does not have iconv support nor wcsdup() function, so it - has to be done manually. The following code will only work for - code points that can be represented as a single UTF-16 character, - and will incorrectly convert any code points which require more - than one UTF-16 character. - - Skip over the first character (2-bytes). */ - len -= 2; - str = malloc((len / 2 + 1) * sizeof(wchar_t)); - int i; - for (i = 0; i < len / 2; i++) { - str[i] = buf[i * 2 + 2] | (buf[i * 2 + 3] << 8); - } - str[len / 2] = 0x00000000; - -#else - - /* buf does not need to be explicitly NULL-terminated because - it is only passed into iconv() which does not need it. */ - - /* Initialize iconv. */ - ic = iconv_open("WCHAR_T", "UTF-16LE"); - if (ic == (iconv_t)-1) { - LOG("iconv_open() failed\n"); - return NULL; - } - - /* Convert to native wchar_t (UTF-32 on glibc/BSD systems). - Skip the first character (2-bytes). */ - inptr = buf+2; - inbytes = len-2; - outptr = (char*) wbuf; - outbytes = sizeof(wbuf); - res = iconv(ic, &inptr, &inbytes, &outptr, &outbytes); - if (res == (size_t)-1) { - LOG("iconv() failed\n"); - goto err; - } - - /* Write the terminating NULL. */ - wbuf[sizeof(wbuf)/sizeof(wbuf[0])-1] = 0x00000000; - if (outbytes >= sizeof(wbuf[0])) - *((wchar_t*)outptr) = 0x00000000; - - /* Allocate and copy the string. */ - str = wcsdup(wbuf); - -err: - iconv_close(ic); - -#endif - - return str; -} - -static char *make_path(libusb_device *dev, int interface_number) -{ - char str[64]; - snprintf(str, sizeof(str), "%04x:%04x:%02x", - libusb_get_bus_number(dev), - libusb_get_device_address(dev), - interface_number); - str[sizeof(str)-1] = '\0'; - - return strdup(str); -} - - -int HID_API_EXPORT hid_init(void) -{ - if (!usb_context) { - const char *locale; - - /* Init Libusb */ - if (libusb_init(&usb_context)) - return -1; - - /* Set the locale if it's not set. */ - locale = setlocale(LC_CTYPE, NULL); - if (!locale) - setlocale(LC_CTYPE, ""); - } - - return 0; -} - -int HID_API_EXPORT hid_exit(void) -{ - if (usb_context) { - libusb_exit(usb_context); - usb_context = NULL; - } - - return 0; -} - -struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id) -{ - libusb_device **devs; - libusb_device *dev; - libusb_device_handle *handle; - ssize_t num_devs; - int i = 0; - - struct hid_device_info *root = NULL; /* return object */ - struct hid_device_info *cur_dev = NULL; - - if(hid_init() < 0) - return NULL; - - num_devs = libusb_get_device_list(usb_context, &devs); - if (num_devs < 0) - return NULL; - while ((dev = devs[i++]) != NULL) { - struct libusb_device_descriptor desc; - struct libusb_config_descriptor *conf_desc = NULL; - int j, k; - int interface_num = 0; - - int res = libusb_get_device_descriptor(dev, &desc); - unsigned short dev_vid = desc.idVendor; - unsigned short dev_pid = desc.idProduct; - - res = libusb_get_active_config_descriptor(dev, &conf_desc); - if (res < 0) - libusb_get_config_descriptor(dev, 0, &conf_desc); - if (conf_desc) { - for (j = 0; j < conf_desc->bNumInterfaces; j++) { - const struct libusb_interface *intf = &conf_desc->interface[j]; - for (k = 0; k < intf->num_altsetting; k++) { - const struct libusb_interface_descriptor *intf_desc; - intf_desc = &intf->altsetting[k]; - if (intf_desc->bInterfaceClass == LIBUSB_CLASS_HID) { - interface_num = intf_desc->bInterfaceNumber; - - /* Check the VID/PID against the arguments */ - if ((vendor_id == 0x0 || vendor_id == dev_vid) && - (product_id == 0x0 || product_id == dev_pid)) { - struct hid_device_info *tmp; - - /* VID/PID match. Create the record. */ - tmp = calloc(1, sizeof(struct hid_device_info)); - if (cur_dev) { - cur_dev->next = tmp; - } - else { - root = tmp; - } - cur_dev = tmp; - - /* Fill out the record */ - cur_dev->next = NULL; - cur_dev->path = make_path(dev, interface_num); - - res = libusb_open(dev, &handle); - - if (res >= 0) { - /* Serial Number */ - if (desc.iSerialNumber > 0) - cur_dev->serial_number = - get_usb_string(handle, desc.iSerialNumber); - - /* Manufacturer and Product strings */ - if (desc.iManufacturer > 0) - cur_dev->manufacturer_string = - get_usb_string(handle, desc.iManufacturer); - if (desc.iProduct > 0) - cur_dev->product_string = - get_usb_string(handle, desc.iProduct); - -#ifdef INVASIVE_GET_USAGE -{ - /* - This section is removed because it is too - invasive on the system. Getting a Usage Page - and Usage requires parsing the HID Report - descriptor. Getting a HID Report descriptor - involves claiming the interface. Claiming the - interface involves detaching the kernel driver. - Detaching the kernel driver is hard on the system - because it will unclaim interfaces (if another - app has them claimed) and the re-attachment of - the driver will sometimes change /dev entry names. - It is for these reasons that this section is - #if 0. For composite devices, use the interface - field in the hid_device_info struct to distinguish - between interfaces. */ - unsigned char data[256]; -#ifdef DETACH_KERNEL_DRIVER - int detached = 0; - /* Usage Page and Usage */ - res = libusb_kernel_driver_active(handle, interface_num); - if (res == 1) { - res = libusb_detach_kernel_driver(handle, interface_num); - if (res < 0) - LOG("Couldn't detach kernel driver, even though a kernel driver was attached."); - else - detached = 1; - } -#endif - res = libusb_claim_interface(handle, interface_num); - if (res >= 0) { - /* Get the HID Report Descriptor. */ - res = libusb_control_transfer(handle, LIBUSB_ENDPOINT_IN|LIBUSB_RECIPIENT_INTERFACE, LIBUSB_REQUEST_GET_DESCRIPTOR, (LIBUSB_DT_REPORT << 8)|interface_num, 0, data, sizeof(data), 5000); - if (res >= 0) { - unsigned short page=0, usage=0; - /* Parse the usage and usage page - out of the report descriptor. */ - get_usage(data, res, &page, &usage); - cur_dev->usage_page = page; - cur_dev->usage = usage; - } - else - LOG("libusb_control_transfer() for getting the HID report failed with %d\n", res); - - /* Release the interface */ - res = libusb_release_interface(handle, interface_num); - if (res < 0) - LOG("Can't release the interface.\n"); - } - else - LOG("Can't claim interface %d\n", res); -#ifdef DETACH_KERNEL_DRIVER - /* Re-attach kernel driver if necessary. */ - if (detached) { - res = libusb_attach_kernel_driver(handle, interface_num); - if (res < 0) - LOG("Couldn't re-attach kernel driver.\n"); - } -#endif -} -#endif /* INVASIVE_GET_USAGE */ - - libusb_close(handle); - } - /* VID/PID */ - cur_dev->vendor_id = dev_vid; - cur_dev->product_id = dev_pid; - - /* Release Number */ - cur_dev->release_number = desc.bcdDevice; - - /* Interface Number */ - cur_dev->interface_number = interface_num; - } - } - } /* altsettings */ - } /* interfaces */ - libusb_free_config_descriptor(conf_desc); - } - } - - libusb_free_device_list(devs, 1); - - return root; -} - -void HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs) -{ - struct hid_device_info *d = devs; - while (d) { - struct hid_device_info *next = d->next; - free(d->path); - free(d->serial_number); - free(d->manufacturer_string); - free(d->product_string); - free(d); - d = next; - } -} - -hid_device * hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number) -{ - struct hid_device_info *devs, *cur_dev; - const char *path_to_open = NULL; - hid_device *handle = NULL; - - devs = hid_enumerate(vendor_id, product_id); - cur_dev = devs; - while (cur_dev) { - if (cur_dev->vendor_id == vendor_id && - cur_dev->product_id == product_id) { - if (serial_number) { - if (cur_dev->serial_number && - wcscmp(serial_number, cur_dev->serial_number) == 0) { - path_to_open = cur_dev->path; - break; - } - } - else { - path_to_open = cur_dev->path; - break; - } - } - cur_dev = cur_dev->next; - } - - if (path_to_open) { - /* Open the device */ - handle = hid_open_path(path_to_open); - } - - hid_free_enumeration(devs); - - return handle; -} - -static void read_callback(struct libusb_transfer *transfer) -{ - hid_device *dev = transfer->user_data; - int res; - - if (transfer->status == LIBUSB_TRANSFER_COMPLETED) { - - struct input_report *rpt = malloc(sizeof(*rpt)); - rpt->data = malloc(transfer->actual_length); - memcpy(rpt->data, transfer->buffer, transfer->actual_length); - rpt->len = transfer->actual_length; - rpt->next = NULL; - - pthread_mutex_lock(&dev->mutex); - - /* Attach the new report object to the end of the list. */ - if (dev->input_reports == NULL) { - /* The list is empty. Put it at the root. */ - dev->input_reports = rpt; - pthread_cond_signal(&dev->condition); - } - else { - /* Find the end of the list and attach. */ - struct input_report *cur = dev->input_reports; - int num_queued = 0; - while (cur->next != NULL) { - cur = cur->next; - num_queued++; - } - cur->next = rpt; - - /* Pop one off if we've reached 30 in the queue. This - way we don't grow forever if the user never reads - anything from the device. */ - if (num_queued > 30) { - return_data(dev, NULL, 0); - } - } - pthread_mutex_unlock(&dev->mutex); - } - else if (transfer->status == LIBUSB_TRANSFER_CANCELLED) { - dev->shutdown_thread = 1; - dev->cancelled = 1; - return; - } - else if (transfer->status == LIBUSB_TRANSFER_NO_DEVICE) { - dev->shutdown_thread = 1; - dev->cancelled = 1; - return; - } - else if (transfer->status == LIBUSB_TRANSFER_TIMED_OUT) { - //LOG("Timeout (normal)\n"); - } - else { - LOG("Unknown transfer code: %d\n", transfer->status); - } - - /* Re-submit the transfer object. */ - res = libusb_submit_transfer(transfer); - if (res != 0) { - LOG("Unable to submit URB. libusb error code: %d\n", res); - dev->shutdown_thread = 1; - dev->cancelled = 1; - } -} - - -static void *read_thread(void *param) -{ - hid_device *dev = param; - unsigned char *buf; - const size_t length = dev->input_ep_max_packet_size; - - /* Set up the transfer object. */ - buf = malloc(length); - dev->transfer = libusb_alloc_transfer(0); - libusb_fill_interrupt_transfer(dev->transfer, - dev->device_handle, - dev->input_endpoint, - buf, - length, - read_callback, - dev, - 5000/*timeout*/); - - /* Make the first submission. Further submissions are made - from inside read_callback() */ - libusb_submit_transfer(dev->transfer); - - /* Notify the main thread that the read thread is up and running. */ - pthread_barrier_wait(&dev->barrier); - - /* Handle all the events. */ - while (!dev->shutdown_thread) { - int res; - res = libusb_handle_events(usb_context); - if (res < 0) { - /* There was an error. */ - LOG("read_thread(): libusb reports error # %d\n", res); - - /* Break out of this loop only on fatal error.*/ - if (res != LIBUSB_ERROR_BUSY && - res != LIBUSB_ERROR_TIMEOUT && - res != LIBUSB_ERROR_OVERFLOW && - res != LIBUSB_ERROR_INTERRUPTED) { - break; - } - } - } - - /* Cancel any transfer that may be pending. This call will fail - if no transfers are pending, but that's OK. */ - libusb_cancel_transfer(dev->transfer); - - while (!dev->cancelled) - libusb_handle_events_completed(usb_context, &dev->cancelled); - - /* Now that the read thread is stopping, Wake any threads which are - waiting on data (in hid_read_timeout()). Do this under a mutex to - make sure that a thread which is about to go to sleep waiting on - the condition actually will go to sleep before the condition is - signaled. */ - pthread_mutex_lock(&dev->mutex); - pthread_cond_broadcast(&dev->condition); - pthread_mutex_unlock(&dev->mutex); - - /* The dev->transfer->buffer and dev->transfer objects are cleaned up - in hid_close(). They are not cleaned up here because this thread - could end either due to a disconnect or due to a user - call to hid_close(). In both cases the objects can be safely - cleaned up after the call to pthread_join() (in hid_close()), but - since hid_close() calls libusb_cancel_transfer(), on these objects, - they can not be cleaned up here. */ - - return NULL; -} - - -hid_device * HID_API_EXPORT hid_open_path(const char *path) -{ - hid_device *dev = NULL; - - libusb_device **devs; - libusb_device *usb_dev; - int res; - int d = 0; - int good_open = 0; - - if(hid_init() < 0) - return NULL; - - dev = new_hid_device(); - - libusb_get_device_list(usb_context, &devs); - while ((usb_dev = devs[d++]) != NULL) { - struct libusb_device_descriptor desc; - struct libusb_config_descriptor *conf_desc = NULL; - int i,j,k; - libusb_get_device_descriptor(usb_dev, &desc); - - if (libusb_get_active_config_descriptor(usb_dev, &conf_desc) < 0) - continue; - for (j = 0; j < conf_desc->bNumInterfaces; j++) { - const struct libusb_interface *intf = &conf_desc->interface[j]; - for (k = 0; k < intf->num_altsetting; k++) { - const struct libusb_interface_descriptor *intf_desc; - intf_desc = &intf->altsetting[k]; - if (intf_desc->bInterfaceClass == LIBUSB_CLASS_HID) { - char *dev_path = make_path(usb_dev, intf_desc->bInterfaceNumber); - if (!strcmp(dev_path, path)) { - /* Matched Paths. Open this device */ - - /* OPEN HERE */ - res = libusb_open(usb_dev, &dev->device_handle); - if (res < 0) { - LOG("can't open device\n"); - free(dev_path); - break; - } - good_open = 1; -#ifdef DETACH_KERNEL_DRIVER - /* Detach the kernel driver, but only if the - device is managed by the kernel */ - if (libusb_kernel_driver_active(dev->device_handle, intf_desc->bInterfaceNumber) == 1) { - res = libusb_detach_kernel_driver(dev->device_handle, intf_desc->bInterfaceNumber); - if (res < 0) { - libusb_close(dev->device_handle); - LOG("Unable to detach Kernel Driver\n"); - free(dev_path); - good_open = 0; - break; - } - } -#endif - res = libusb_claim_interface(dev->device_handle, intf_desc->bInterfaceNumber); - if (res < 0) { - LOG("can't claim interface %d: %d\n", intf_desc->bInterfaceNumber, res); - free(dev_path); - libusb_close(dev->device_handle); - good_open = 0; - break; - } - - /* Store off the string descriptor indexes */ - dev->manufacturer_index = desc.iManufacturer; - dev->product_index = desc.iProduct; - dev->serial_index = desc.iSerialNumber; - - /* Store off the interface number */ - dev->interface = intf_desc->bInterfaceNumber; - - /* Find the INPUT and OUTPUT endpoints. An - OUTPUT endpoint is not required. */ - for (i = 0; i < intf_desc->bNumEndpoints; i++) { - const struct libusb_endpoint_descriptor *ep - = &intf_desc->endpoint[i]; - - /* Determine the type and direction of this - endpoint. */ - int is_interrupt = - (ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) - == LIBUSB_TRANSFER_TYPE_INTERRUPT; - int is_output = - (ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) - == LIBUSB_ENDPOINT_OUT; - int is_input = - (ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) - == LIBUSB_ENDPOINT_IN; - - /* Decide whether to use it for input or output. */ - if (dev->input_endpoint == 0 && - is_interrupt && is_input) { - /* Use this endpoint for INPUT */ - dev->input_endpoint = ep->bEndpointAddress; - dev->input_ep_max_packet_size = ep->wMaxPacketSize; - } - if (dev->output_endpoint == 0 && - is_interrupt && is_output) { - /* Use this endpoint for OUTPUT */ - dev->output_endpoint = ep->bEndpointAddress; - } - } - - pthread_create(&dev->thread, NULL, read_thread, dev); - - /* Wait here for the read thread to be initialized. */ - pthread_barrier_wait(&dev->barrier); - - } - free(dev_path); - } - } - } - libusb_free_config_descriptor(conf_desc); - - } - - libusb_free_device_list(devs, 1); - - /* If we have a good handle, return it. */ - if (good_open) { - return dev; - } - else { - /* Unable to open any devices. */ - free_hid_device(dev); - return NULL; - } -} - - -int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length) -{ - int res; - int report_number = data[0]; - int skipped_report_id = 0; - - if (report_number == 0x0) { - data++; - length--; - skipped_report_id = 1; - } - - - if (dev->output_endpoint <= 0) { - /* No interrupt out endpoint. Use the Control Endpoint */ - res = libusb_control_transfer(dev->device_handle, - LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_OUT, - 0x09/*HID Set_Report*/, - (2/*HID output*/ << 8) | report_number, - dev->interface, - (unsigned char *)data, length, - 1000/*timeout millis*/); - - if (res < 0) - return -1; - - if (skipped_report_id) - length++; - - return length; - } - else { - /* Use the interrupt out endpoint */ - int actual_length; - res = libusb_interrupt_transfer(dev->device_handle, - dev->output_endpoint, - (unsigned char*)data, - length, - &actual_length, 1000); - - if (res < 0) - return -1; - - if (skipped_report_id) - actual_length++; - - return actual_length; - } -} - -/* Helper function, to simplify hid_read(). - This should be called with dev->mutex locked. */ -static int return_data(hid_device *dev, unsigned char *data, size_t length) -{ - /* Copy the data out of the linked list item (rpt) into the - return buffer (data), and delete the liked list item. */ - struct input_report *rpt = dev->input_reports; - size_t len = (length < rpt->len)? length: rpt->len; - if (len > 0) - memcpy(data, rpt->data, len); - dev->input_reports = rpt->next; - free(rpt->data); - free(rpt); - return len; -} - -static void cleanup_mutex(void *param) -{ - hid_device *dev = param; - pthread_mutex_unlock(&dev->mutex); -} - - -int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds) -{ - int bytes_read = -1; - -#if 0 - int transferred; - int res = libusb_interrupt_transfer(dev->device_handle, dev->input_endpoint, data, length, &transferred, 5000); - LOG("transferred: %d\n", transferred); - return transferred; -#endif - - pthread_mutex_lock(&dev->mutex); - pthread_cleanup_push(&cleanup_mutex, dev); - - /* There's an input report queued up. Return it. */ - if (dev->input_reports) { - /* Return the first one */ - bytes_read = return_data(dev, data, length); - goto ret; - } - - if (dev->shutdown_thread) { - /* This means the device has been disconnected. - An error code of -1 should be returned. */ - bytes_read = -1; - goto ret; - } - - if (milliseconds == -1) { - /* Blocking */ - while (!dev->input_reports && !dev->shutdown_thread) { - pthread_cond_wait(&dev->condition, &dev->mutex); - } - if (dev->input_reports) { - bytes_read = return_data(dev, data, length); - } - } - else if (milliseconds > 0) { - /* Non-blocking, but called with timeout. */ - int res; - struct timespec ts; - clock_gettime(CLOCK_REALTIME, &ts); - ts.tv_sec += milliseconds / 1000; - ts.tv_nsec += (milliseconds % 1000) * 1000000; - if (ts.tv_nsec >= 1000000000L) { - ts.tv_sec++; - ts.tv_nsec -= 1000000000L; - } - - while (!dev->input_reports && !dev->shutdown_thread) { - res = pthread_cond_timedwait(&dev->condition, &dev->mutex, &ts); - if (res == 0) { - if (dev->input_reports) { - bytes_read = return_data(dev, data, length); - break; - } - - /* If we're here, there was a spurious wake up - or the read thread was shutdown. Run the - loop again (ie: don't break). */ - } - else if (res == ETIMEDOUT) { - /* Timed out. */ - bytes_read = 0; - break; - } - else { - /* Error. */ - bytes_read = -1; - break; - } - } - } - else { - /* Purely non-blocking */ - bytes_read = 0; - } - -ret: - pthread_mutex_unlock(&dev->mutex); - pthread_cleanup_pop(0); - - return bytes_read; -} - -int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length) -{ - return hid_read_timeout(dev, data, length, dev->blocking ? -1 : 0); -} - -int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock) -{ - dev->blocking = !nonblock; - - return 0; -} - - -int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length) -{ - int res = -1; - int skipped_report_id = 0; - int report_number = data[0]; - - if (report_number == 0x0) { - data++; - length--; - skipped_report_id = 1; - } - - res = libusb_control_transfer(dev->device_handle, - LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_OUT, - 0x09/*HID set_report*/, - (3/*HID feature*/ << 8) | report_number, - dev->interface, - (unsigned char *)data, length, - 1000/*timeout millis*/); - - if (res < 0) - return -1; - - /* Account for the report ID */ - if (skipped_report_id) - length++; - - return length; -} - -int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length) -{ - int res = -1; - int skipped_report_id = 0; - int report_number = data[0]; - - if (report_number == 0x0) { - /* Offset the return buffer by 1, so that the report ID - will remain in byte 0. */ - data++; - length--; - skipped_report_id = 1; - } - res = libusb_control_transfer(dev->device_handle, - LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_IN, - 0x01/*HID get_report*/, - (3/*HID feature*/ << 8) | report_number, - dev->interface, - (unsigned char *)data, length, - 1000/*timeout millis*/); - - if (res < 0) - return -1; - - if (skipped_report_id) - res++; - - return res; -} - - -void HID_API_EXPORT hid_close(hid_device *dev) -{ - if (!dev) - return; - - /* Cause read_thread() to stop. */ - dev->shutdown_thread = 1; - libusb_cancel_transfer(dev->transfer); - - /* Wait for read_thread() to end. */ - pthread_join(dev->thread, NULL); - - /* Clean up the Transfer objects allocated in read_thread(). */ - free(dev->transfer->buffer); - libusb_free_transfer(dev->transfer); - - /* release the interface */ - libusb_release_interface(dev->device_handle, dev->interface); - - /* Close the handle */ - libusb_close(dev->device_handle); - - /* Clear out the queue of received reports. */ - pthread_mutex_lock(&dev->mutex); - while (dev->input_reports) { - return_data(dev, NULL, 0); - } - pthread_mutex_unlock(&dev->mutex); - - free_hid_device(dev); -} - - -int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen) -{ - return hid_get_indexed_string(dev, dev->manufacturer_index, string, maxlen); -} - -int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen) -{ - return hid_get_indexed_string(dev, dev->product_index, string, maxlen); -} - -int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen) -{ - return hid_get_indexed_string(dev, dev->serial_index, string, maxlen); -} - -int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen) -{ - wchar_t *str; - - str = get_usb_string(dev->device_handle, string_index); - if (str) { - wcsncpy(string, str, maxlen); - string[maxlen-1] = L'\0'; - free(str); - return 0; - } - else - return -1; -} - - -HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev) -{ - return NULL; -} - - -struct lang_map_entry { - const char *name; - const char *string_code; - uint16_t usb_code; -}; - -#define LANG(name,code,usb_code) { name, code, usb_code } -static struct lang_map_entry lang_map[] = { - LANG("Afrikaans", "af", 0x0436), - LANG("Albanian", "sq", 0x041C), - LANG("Arabic - United Arab Emirates", "ar_ae", 0x3801), - LANG("Arabic - Bahrain", "ar_bh", 0x3C01), - LANG("Arabic - Algeria", "ar_dz", 0x1401), - LANG("Arabic - Egypt", "ar_eg", 0x0C01), - LANG("Arabic - Iraq", "ar_iq", 0x0801), - LANG("Arabic - Jordan", "ar_jo", 0x2C01), - LANG("Arabic - Kuwait", "ar_kw", 0x3401), - LANG("Arabic - Lebanon", "ar_lb", 0x3001), - LANG("Arabic - Libya", "ar_ly", 0x1001), - LANG("Arabic - Morocco", "ar_ma", 0x1801), - LANG("Arabic - Oman", "ar_om", 0x2001), - LANG("Arabic - Qatar", "ar_qa", 0x4001), - LANG("Arabic - Saudi Arabia", "ar_sa", 0x0401), - LANG("Arabic - Syria", "ar_sy", 0x2801), - LANG("Arabic - Tunisia", "ar_tn", 0x1C01), - LANG("Arabic - Yemen", "ar_ye", 0x2401), - LANG("Armenian", "hy", 0x042B), - LANG("Azeri - Latin", "az_az", 0x042C), - LANG("Azeri - Cyrillic", "az_az", 0x082C), - LANG("Basque", "eu", 0x042D), - LANG("Belarusian", "be", 0x0423), - LANG("Bulgarian", "bg", 0x0402), - LANG("Catalan", "ca", 0x0403), - LANG("Chinese - China", "zh_cn", 0x0804), - LANG("Chinese - Hong Kong SAR", "zh_hk", 0x0C04), - LANG("Chinese - Macau SAR", "zh_mo", 0x1404), - LANG("Chinese - Singapore", "zh_sg", 0x1004), - LANG("Chinese - Taiwan", "zh_tw", 0x0404), - LANG("Croatian", "hr", 0x041A), - LANG("Czech", "cs", 0x0405), - LANG("Danish", "da", 0x0406), - LANG("Dutch - Netherlands", "nl_nl", 0x0413), - LANG("Dutch - Belgium", "nl_be", 0x0813), - LANG("English - Australia", "en_au", 0x0C09), - LANG("English - Belize", "en_bz", 0x2809), - LANG("English - Canada", "en_ca", 0x1009), - LANG("English - Caribbean", "en_cb", 0x2409), - LANG("English - Ireland", "en_ie", 0x1809), - LANG("English - Jamaica", "en_jm", 0x2009), - LANG("English - New Zealand", "en_nz", 0x1409), - LANG("English - Phillippines", "en_ph", 0x3409), - LANG("English - Southern Africa", "en_za", 0x1C09), - LANG("English - Trinidad", "en_tt", 0x2C09), - LANG("English - Great Britain", "en_gb", 0x0809), - LANG("English - United States", "en_us", 0x0409), - LANG("Estonian", "et", 0x0425), - LANG("Farsi", "fa", 0x0429), - LANG("Finnish", "fi", 0x040B), - LANG("Faroese", "fo", 0x0438), - LANG("French - France", "fr_fr", 0x040C), - LANG("French - Belgium", "fr_be", 0x080C), - LANG("French - Canada", "fr_ca", 0x0C0C), - LANG("French - Luxembourg", "fr_lu", 0x140C), - LANG("French - Switzerland", "fr_ch", 0x100C), - LANG("Gaelic - Ireland", "gd_ie", 0x083C), - LANG("Gaelic - Scotland", "gd", 0x043C), - LANG("German - Germany", "de_de", 0x0407), - LANG("German - Austria", "de_at", 0x0C07), - LANG("German - Liechtenstein", "de_li", 0x1407), - LANG("German - Luxembourg", "de_lu", 0x1007), - LANG("German - Switzerland", "de_ch", 0x0807), - LANG("Greek", "el", 0x0408), - LANG("Hebrew", "he", 0x040D), - LANG("Hindi", "hi", 0x0439), - LANG("Hungarian", "hu", 0x040E), - LANG("Icelandic", "is", 0x040F), - LANG("Indonesian", "id", 0x0421), - LANG("Italian - Italy", "it_it", 0x0410), - LANG("Italian - Switzerland", "it_ch", 0x0810), - LANG("Japanese", "ja", 0x0411), - LANG("Korean", "ko", 0x0412), - LANG("Latvian", "lv", 0x0426), - LANG("Lithuanian", "lt", 0x0427), - LANG("F.Y.R.O. Macedonia", "mk", 0x042F), - LANG("Malay - Malaysia", "ms_my", 0x043E), - LANG("Malay – Brunei", "ms_bn", 0x083E), - LANG("Maltese", "mt", 0x043A), - LANG("Marathi", "mr", 0x044E), - LANG("Norwegian - Bokml", "no_no", 0x0414), - LANG("Norwegian - Nynorsk", "no_no", 0x0814), - LANG("Polish", "pl", 0x0415), - LANG("Portuguese - Portugal", "pt_pt", 0x0816), - LANG("Portuguese - Brazil", "pt_br", 0x0416), - LANG("Raeto-Romance", "rm", 0x0417), - LANG("Romanian - Romania", "ro", 0x0418), - LANG("Romanian - Republic of Moldova", "ro_mo", 0x0818), - LANG("Russian", "ru", 0x0419), - LANG("Russian - Republic of Moldova", "ru_mo", 0x0819), - LANG("Sanskrit", "sa", 0x044F), - LANG("Serbian - Cyrillic", "sr_sp", 0x0C1A), - LANG("Serbian - Latin", "sr_sp", 0x081A), - LANG("Setsuana", "tn", 0x0432), - LANG("Slovenian", "sl", 0x0424), - LANG("Slovak", "sk", 0x041B), - LANG("Sorbian", "sb", 0x042E), - LANG("Spanish - Spain (Traditional)", "es_es", 0x040A), - LANG("Spanish - Argentina", "es_ar", 0x2C0A), - LANG("Spanish - Bolivia", "es_bo", 0x400A), - LANG("Spanish - Chile", "es_cl", 0x340A), - LANG("Spanish - Colombia", "es_co", 0x240A), - LANG("Spanish - Costa Rica", "es_cr", 0x140A), - LANG("Spanish - Dominican Republic", "es_do", 0x1C0A), - LANG("Spanish - Ecuador", "es_ec", 0x300A), - LANG("Spanish - Guatemala", "es_gt", 0x100A), - LANG("Spanish - Honduras", "es_hn", 0x480A), - LANG("Spanish - Mexico", "es_mx", 0x080A), - LANG("Spanish - Nicaragua", "es_ni", 0x4C0A), - LANG("Spanish - Panama", "es_pa", 0x180A), - LANG("Spanish - Peru", "es_pe", 0x280A), - LANG("Spanish - Puerto Rico", "es_pr", 0x500A), - LANG("Spanish - Paraguay", "es_py", 0x3C0A), - LANG("Spanish - El Salvador", "es_sv", 0x440A), - LANG("Spanish - Uruguay", "es_uy", 0x380A), - LANG("Spanish - Venezuela", "es_ve", 0x200A), - LANG("Southern Sotho", "st", 0x0430), - LANG("Swahili", "sw", 0x0441), - LANG("Swedish - Sweden", "sv_se", 0x041D), - LANG("Swedish - Finland", "sv_fi", 0x081D), - LANG("Tamil", "ta", 0x0449), - LANG("Tatar", "tt", 0X0444), - LANG("Thai", "th", 0x041E), - LANG("Turkish", "tr", 0x041F), - LANG("Tsonga", "ts", 0x0431), - LANG("Ukrainian", "uk", 0x0422), - LANG("Urdu", "ur", 0x0420), - LANG("Uzbek - Cyrillic", "uz_uz", 0x0843), - LANG("Uzbek – Latin", "uz_uz", 0x0443), - LANG("Vietnamese", "vi", 0x042A), - LANG("Xhosa", "xh", 0x0434), - LANG("Yiddish", "yi", 0x043D), - LANG("Zulu", "zu", 0x0435), - LANG(NULL, NULL, 0x0), -}; - -uint16_t get_usb_code_for_current_locale(void) -{ - char *locale; - char search_string[64]; - char *ptr; - struct lang_map_entry *lang; - - /* Get the current locale. */ - locale = setlocale(0, NULL); - if (!locale) - return 0x0; - - /* Make a copy of the current locale string. */ - strncpy(search_string, locale, sizeof(search_string)); - search_string[sizeof(search_string)-1] = '\0'; - - /* Chop off the encoding part, and make it lower case. */ - ptr = search_string; - while (*ptr) { - *ptr = tolower(*ptr); - if (*ptr == '.') { - *ptr = '\0'; - break; - } - ptr++; - } - - /* Find the entry which matches the string code of our locale. */ - lang = lang_map; - while (lang->string_code) { - if (!strcmp(lang->string_code, search_string)) { - return lang->usb_code; - } - lang++; - } - - /* There was no match. Find with just the language only. */ - /* Chop off the variant. Chop it off at the '_'. */ - ptr = search_string; - while (*ptr) { - *ptr = tolower(*ptr); - if (*ptr == '_') { - *ptr = '\0'; - break; - } - ptr++; - } - -#if 0 /* TODO: Do we need this? */ - /* Find the entry which matches the string code of our language. */ - lang = lang_map; - while (lang->string_code) { - if (!strcmp(lang->string_code, search_string)) { - return lang->usb_code; - } - lang++; - } -#endif - - /* Found nothing. */ - return 0x0; -} - -#ifdef __cplusplus -} -#endif diff --git a/vendor/github.com/karalabe/hid/hidapi/mac/hid.c b/vendor/github.com/karalabe/hid/hidapi/mac/hid.c deleted file mode 100644 index e0756a15..00000000 --- a/vendor/github.com/karalabe/hid/hidapi/mac/hid.c +++ /dev/null @@ -1,1110 +0,0 @@ -/******************************************************* - HIDAPI - Multi-Platform library for - communication with HID devices. - - Alan Ott - Signal 11 Software - - 2010-07-03 - - Copyright 2010, All Rights Reserved. - - At the discretion of the user of this library, - this software may be licensed under the terms of the - GNU General Public License v3, a BSD-Style license, or the - original HIDAPI license as outlined in the LICENSE.txt, - LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt - files located at the root of the source distribution. - These files may also be found in the public source - code repository located at: - http://github.com/signal11/hidapi . -********************************************************/ - -/* See Apple Technical Note TN2187 for details on IOHidManager. */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "hidapi.h" - -/* Barrier implementation because Mac OSX doesn't have pthread_barrier. - It also doesn't have clock_gettime(). So much for POSIX and SUSv2. - This implementation came from Brent Priddy and was posted on - StackOverflow. It is used with his permission. */ -typedef int pthread_barrierattr_t; -typedef struct pthread_barrier { - pthread_mutex_t mutex; - pthread_cond_t cond; - int count; - int trip_count; -} pthread_barrier_t; - -static int pthread_barrier_init(pthread_barrier_t *barrier, const pthread_barrierattr_t *attr, unsigned int count) -{ - if(count == 0) { - errno = EINVAL; - return -1; - } - - if(pthread_mutex_init(&barrier->mutex, 0) < 0) { - return -1; - } - if(pthread_cond_init(&barrier->cond, 0) < 0) { - pthread_mutex_destroy(&barrier->mutex); - return -1; - } - barrier->trip_count = count; - barrier->count = 0; - - return 0; -} - -static int pthread_barrier_destroy(pthread_barrier_t *barrier) -{ - pthread_cond_destroy(&barrier->cond); - pthread_mutex_destroy(&barrier->mutex); - return 0; -} - -static int pthread_barrier_wait(pthread_barrier_t *barrier) -{ - pthread_mutex_lock(&barrier->mutex); - ++(barrier->count); - if(barrier->count >= barrier->trip_count) - { - barrier->count = 0; - pthread_cond_broadcast(&barrier->cond); - pthread_mutex_unlock(&barrier->mutex); - return 1; - } - else - { - pthread_cond_wait(&barrier->cond, &(barrier->mutex)); - pthread_mutex_unlock(&barrier->mutex); - return 0; - } -} - -static int return_data(hid_device *dev, unsigned char *data, size_t length); - -/* Linked List of input reports received from the device. */ -struct input_report { - uint8_t *data; - size_t len; - struct input_report *next; -}; - -struct hid_device_ { - IOHIDDeviceRef device_handle; - int blocking; - int uses_numbered_reports; - int disconnected; - CFStringRef run_loop_mode; - CFRunLoopRef run_loop; - CFRunLoopSourceRef source; - uint8_t *input_report_buf; - CFIndex max_input_report_len; - struct input_report *input_reports; - - pthread_t thread; - pthread_mutex_t mutex; /* Protects input_reports */ - pthread_cond_t condition; - pthread_barrier_t barrier; /* Ensures correct startup sequence */ - pthread_barrier_t shutdown_barrier; /* Ensures correct shutdown sequence */ - int shutdown_thread; -}; - -static hid_device *new_hid_device(void) -{ - hid_device *dev = calloc(1, sizeof(hid_device)); - dev->device_handle = NULL; - dev->blocking = 1; - dev->uses_numbered_reports = 0; - dev->disconnected = 0; - dev->run_loop_mode = NULL; - dev->run_loop = NULL; - dev->source = NULL; - dev->input_report_buf = NULL; - dev->input_reports = NULL; - dev->shutdown_thread = 0; - - /* Thread objects */ - pthread_mutex_init(&dev->mutex, NULL); - pthread_cond_init(&dev->condition, NULL); - pthread_barrier_init(&dev->barrier, NULL, 2); - pthread_barrier_init(&dev->shutdown_barrier, NULL, 2); - - return dev; -} - -static void free_hid_device(hid_device *dev) -{ - if (!dev) - return; - - /* Delete any input reports still left over. */ - struct input_report *rpt = dev->input_reports; - while (rpt) { - struct input_report *next = rpt->next; - free(rpt->data); - free(rpt); - rpt = next; - } - - /* Free the string and the report buffer. The check for NULL - is necessary here as CFRelease() doesn't handle NULL like - free() and others do. */ - if (dev->run_loop_mode) - CFRelease(dev->run_loop_mode); - if (dev->source) - CFRelease(dev->source); - free(dev->input_report_buf); - - /* Clean up the thread objects */ - pthread_barrier_destroy(&dev->shutdown_barrier); - pthread_barrier_destroy(&dev->barrier); - pthread_cond_destroy(&dev->condition); - pthread_mutex_destroy(&dev->mutex); - - /* Free the structure itself. */ - free(dev); -} - -static IOHIDManagerRef hid_mgr = 0x0; - - -#if 0 -static void register_error(hid_device *device, const char *op) -{ - -} -#endif - - -static int32_t get_int_property(IOHIDDeviceRef device, CFStringRef key) -{ - CFTypeRef ref; - int32_t value; - - ref = IOHIDDeviceGetProperty(device, key); - if (ref) { - if (CFGetTypeID(ref) == CFNumberGetTypeID()) { - CFNumberGetValue((CFNumberRef) ref, kCFNumberSInt32Type, &value); - return value; - } - } - return 0; -} - -static unsigned short get_vendor_id(IOHIDDeviceRef device) -{ - return get_int_property(device, CFSTR(kIOHIDVendorIDKey)); -} - -static unsigned short get_product_id(IOHIDDeviceRef device) -{ - return get_int_property(device, CFSTR(kIOHIDProductIDKey)); -} - -static int32_t get_max_report_length(IOHIDDeviceRef device) -{ - return get_int_property(device, CFSTR(kIOHIDMaxInputReportSizeKey)); -} - -static int get_string_property(IOHIDDeviceRef device, CFStringRef prop, wchar_t *buf, size_t len) -{ - CFStringRef str; - - if (!len) - return 0; - - str = IOHIDDeviceGetProperty(device, prop); - - buf[0] = 0; - - if (str) { - CFIndex str_len = CFStringGetLength(str); - CFRange range; - CFIndex used_buf_len; - CFIndex chars_copied; - - len --; - - range.location = 0; - range.length = ((size_t)str_len > len)? len: (size_t)str_len; - chars_copied = CFStringGetBytes(str, - range, - kCFStringEncodingUTF32LE, - (char)'?', - FALSE, - (UInt8*)buf, - len * sizeof(wchar_t), - &used_buf_len); - - if (chars_copied == len) - buf[len] = 0; /* len is decremented above */ - else - buf[chars_copied] = 0; - - return 0; - } - else - return -1; - -} - -static int get_serial_number(IOHIDDeviceRef device, wchar_t *buf, size_t len) -{ - return get_string_property(device, CFSTR(kIOHIDSerialNumberKey), buf, len); -} - -static int get_manufacturer_string(IOHIDDeviceRef device, wchar_t *buf, size_t len) -{ - return get_string_property(device, CFSTR(kIOHIDManufacturerKey), buf, len); -} - -static int get_product_string(IOHIDDeviceRef device, wchar_t *buf, size_t len) -{ - return get_string_property(device, CFSTR(kIOHIDProductKey), buf, len); -} - - -/* Implementation of wcsdup() for Mac. */ -static wchar_t *dup_wcs(const wchar_t *s) -{ - size_t len = wcslen(s); - wchar_t *ret = malloc((len+1)*sizeof(wchar_t)); - wcscpy(ret, s); - - return ret; -} - -/* hidapi_IOHIDDeviceGetService() - * - * Return the io_service_t corresponding to a given IOHIDDeviceRef, either by: - * - on OS X 10.6 and above, calling IOHIDDeviceGetService() - * - on OS X 10.5, extract it from the IOHIDDevice struct - */ -static io_service_t hidapi_IOHIDDeviceGetService(IOHIDDeviceRef device) -{ - static void *iokit_framework = NULL; - static io_service_t (*dynamic_IOHIDDeviceGetService)(IOHIDDeviceRef device) = NULL; - - /* Use dlopen()/dlsym() to get a pointer to IOHIDDeviceGetService() if it exists. - * If any of these steps fail, dynamic_IOHIDDeviceGetService will be left NULL - * and the fallback method will be used. - */ - if (iokit_framework == NULL) { - iokit_framework = dlopen("/System/Library/IOKit.framework/IOKit", RTLD_LAZY); - - if (iokit_framework != NULL) - dynamic_IOHIDDeviceGetService = dlsym(iokit_framework, "IOHIDDeviceGetService"); - } - - if (dynamic_IOHIDDeviceGetService != NULL) { - /* Running on OS X 10.6 and above: IOHIDDeviceGetService() exists */ - return dynamic_IOHIDDeviceGetService(device); - } - else - { - /* Running on OS X 10.5: IOHIDDeviceGetService() doesn't exist. - * - * Be naughty and pull the service out of the IOHIDDevice. - * IOHIDDevice is an opaque struct not exposed to applications, but its - * layout is stable through all available versions of OS X. - * Tested and working on OS X 10.5.8 i386, x86_64, and ppc. - */ - struct IOHIDDevice_internal { - /* The first field of the IOHIDDevice struct is a - * CFRuntimeBase (which is a private CF struct). - * - * a, b, and c are the 3 fields that make up a CFRuntimeBase. - * See http://opensource.apple.com/source/CF/CF-476.18/CFRuntime.h - * - * The second field of the IOHIDDevice is the io_service_t we're looking for. - */ - uintptr_t a; - uint8_t b[4]; -#if __LP64__ - uint32_t c; -#endif - io_service_t service; - }; - struct IOHIDDevice_internal *tmp = (struct IOHIDDevice_internal *)device; - - return tmp->service; - } -} - -/* Initialize the IOHIDManager. Return 0 for success and -1 for failure. */ -static int init_hid_manager(void) -{ - /* Initialize all the HID Manager Objects */ - hid_mgr = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); - if (hid_mgr) { - IOHIDManagerSetDeviceMatching(hid_mgr, NULL); - IOHIDManagerScheduleWithRunLoop(hid_mgr, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); - return 0; - } - - return -1; -} - -/* Initialize the IOHIDManager if necessary. This is the public function, and - it is safe to call this function repeatedly. Return 0 for success and -1 - for failure. */ -int HID_API_EXPORT hid_init(void) -{ - if (!hid_mgr) { - return init_hid_manager(); - } - - /* Already initialized. */ - return 0; -} - -int HID_API_EXPORT hid_exit(void) -{ - if (hid_mgr) { - /* Close the HID manager. */ - IOHIDManagerClose(hid_mgr, kIOHIDOptionsTypeNone); - CFRelease(hid_mgr); - hid_mgr = NULL; - } - - return 0; -} - -static void process_pending_events(void) { - SInt32 res; - do { - res = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.001, FALSE); - } while(res != kCFRunLoopRunFinished && res != kCFRunLoopRunTimedOut); -} - -struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id) -{ - struct hid_device_info *root = NULL; /* return object */ - struct hid_device_info *cur_dev = NULL; - CFIndex num_devices; - int i; - - /* Set up the HID Manager if it hasn't been done */ - if (hid_init() < 0) - return NULL; - - /* give the IOHIDManager a chance to update itself */ - process_pending_events(); - - /* Get a list of the Devices */ - IOHIDManagerSetDeviceMatching(hid_mgr, NULL); - CFSetRef device_set = IOHIDManagerCopyDevices(hid_mgr); - - /* Convert the list into a C array so we can iterate easily. */ - num_devices = CFSetGetCount(device_set); - IOHIDDeviceRef *device_array = calloc(num_devices, sizeof(IOHIDDeviceRef)); - CFSetGetValues(device_set, (const void **) device_array); - - /* Iterate over each device, making an entry for it. */ - for (i = 0; i < num_devices; i++) { - unsigned short dev_vid; - unsigned short dev_pid; - #define BUF_LEN 256 - wchar_t buf[BUF_LEN]; - - IOHIDDeviceRef dev = device_array[i]; - - if (!dev) { - continue; - } - dev_vid = get_vendor_id(dev); - dev_pid = get_product_id(dev); - - /* Check the VID/PID against the arguments */ - if ((vendor_id == 0x0 || vendor_id == dev_vid) && - (product_id == 0x0 || product_id == dev_pid)) { - struct hid_device_info *tmp; - io_object_t iokit_dev; - kern_return_t res; - io_string_t path; - - /* VID/PID match. Create the record. */ - tmp = malloc(sizeof(struct hid_device_info)); - if (cur_dev) { - cur_dev->next = tmp; - } - else { - root = tmp; - } - cur_dev = tmp; - - /* Get the Usage Page and Usage for this device. */ - cur_dev->usage_page = get_int_property(dev, CFSTR(kIOHIDPrimaryUsagePageKey)); - cur_dev->usage = get_int_property(dev, CFSTR(kIOHIDPrimaryUsageKey)); - - /* Fill out the record */ - cur_dev->next = NULL; - - /* Fill in the path (IOService plane) */ - iokit_dev = hidapi_IOHIDDeviceGetService(dev); - res = IORegistryEntryGetPath(iokit_dev, kIOServicePlane, path); - if (res == KERN_SUCCESS) - cur_dev->path = strdup(path); - else - cur_dev->path = strdup(""); - - /* Serial Number */ - get_serial_number(dev, buf, BUF_LEN); - cur_dev->serial_number = dup_wcs(buf); - - /* Manufacturer and Product strings */ - get_manufacturer_string(dev, buf, BUF_LEN); - cur_dev->manufacturer_string = dup_wcs(buf); - get_product_string(dev, buf, BUF_LEN); - cur_dev->product_string = dup_wcs(buf); - - /* VID/PID */ - cur_dev->vendor_id = dev_vid; - cur_dev->product_id = dev_pid; - - /* Release Number */ - cur_dev->release_number = get_int_property(dev, CFSTR(kIOHIDVersionNumberKey)); - - /* Interface Number (Unsupported on Mac)*/ - cur_dev->interface_number = -1; - } - } - - free(device_array); - CFRelease(device_set); - - return root; -} - -void HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs) -{ - /* This function is identical to the Linux version. Platform independent. */ - struct hid_device_info *d = devs; - while (d) { - struct hid_device_info *next = d->next; - free(d->path); - free(d->serial_number); - free(d->manufacturer_string); - free(d->product_string); - free(d); - d = next; - } -} - -hid_device * HID_API_EXPORT hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number) -{ - /* This function is identical to the Linux version. Platform independent. */ - struct hid_device_info *devs, *cur_dev; - const char *path_to_open = NULL; - hid_device * handle = NULL; - - devs = hid_enumerate(vendor_id, product_id); - cur_dev = devs; - while (cur_dev) { - if (cur_dev->vendor_id == vendor_id && - cur_dev->product_id == product_id) { - if (serial_number) { - if (wcscmp(serial_number, cur_dev->serial_number) == 0) { - path_to_open = cur_dev->path; - break; - } - } - else { - path_to_open = cur_dev->path; - break; - } - } - cur_dev = cur_dev->next; - } - - if (path_to_open) { - /* Open the device */ - handle = hid_open_path(path_to_open); - } - - hid_free_enumeration(devs); - - return handle; -} - -static void hid_device_removal_callback(void *context, IOReturn result, - void *sender) -{ - /* Stop the Run Loop for this device. */ - hid_device *d = context; - - d->disconnected = 1; - CFRunLoopStop(d->run_loop); -} - -/* The Run Loop calls this function for each input report received. - This function puts the data into a linked list to be picked up by - hid_read(). */ -static void hid_report_callback(void *context, IOReturn result, void *sender, - IOHIDReportType report_type, uint32_t report_id, - uint8_t *report, CFIndex report_length) -{ - struct input_report *rpt; - hid_device *dev = context; - - /* Make a new Input Report object */ - rpt = calloc(1, sizeof(struct input_report)); - rpt->data = calloc(1, report_length); - memcpy(rpt->data, report, report_length); - rpt->len = report_length; - rpt->next = NULL; - - /* Lock this section */ - pthread_mutex_lock(&dev->mutex); - - /* Attach the new report object to the end of the list. */ - if (dev->input_reports == NULL) { - /* The list is empty. Put it at the root. */ - dev->input_reports = rpt; - } - else { - /* Find the end of the list and attach. */ - struct input_report *cur = dev->input_reports; - int num_queued = 0; - while (cur->next != NULL) { - cur = cur->next; - num_queued++; - } - cur->next = rpt; - - /* Pop one off if we've reached 30 in the queue. This - way we don't grow forever if the user never reads - anything from the device. */ - if (num_queued > 30) { - return_data(dev, NULL, 0); - } - } - - /* Signal a waiting thread that there is data. */ - pthread_cond_signal(&dev->condition); - - /* Unlock */ - pthread_mutex_unlock(&dev->mutex); - -} - -/* This gets called when the read_thread's run loop gets signaled by - hid_close(), and serves to stop the read_thread's run loop. */ -static void perform_signal_callback(void *context) -{ - hid_device *dev = context; - CFRunLoopStop(dev->run_loop); /*TODO: CFRunLoopGetCurrent()*/ -} - -static void *read_thread(void *param) -{ - hid_device *dev = param; - SInt32 code; - - /* Move the device's run loop to this thread. */ - IOHIDDeviceScheduleWithRunLoop(dev->device_handle, CFRunLoopGetCurrent(), dev->run_loop_mode); - - /* Create the RunLoopSource which is used to signal the - event loop to stop when hid_close() is called. */ - CFRunLoopSourceContext ctx; - memset(&ctx, 0, sizeof(ctx)); - ctx.version = 0; - ctx.info = dev; - ctx.perform = &perform_signal_callback; - dev->source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0/*order*/, &ctx); - CFRunLoopAddSource(CFRunLoopGetCurrent(), dev->source, dev->run_loop_mode); - - /* Store off the Run Loop so it can be stopped from hid_close() - and on device disconnection. */ - dev->run_loop = CFRunLoopGetCurrent(); - - /* Notify the main thread that the read thread is up and running. */ - pthread_barrier_wait(&dev->barrier); - - /* Run the Event Loop. CFRunLoopRunInMode() will dispatch HID input - reports into the hid_report_callback(). */ - while (!dev->shutdown_thread && !dev->disconnected) { - code = CFRunLoopRunInMode(dev->run_loop_mode, 1000/*sec*/, FALSE); - /* Return if the device has been disconnected */ - if (code == kCFRunLoopRunFinished) { - dev->disconnected = 1; - break; - } - - - /* Break if The Run Loop returns Finished or Stopped. */ - if (code != kCFRunLoopRunTimedOut && - code != kCFRunLoopRunHandledSource) { - /* There was some kind of error. Setting - shutdown seems to make sense, but - there may be something else more appropriate */ - dev->shutdown_thread = 1; - break; - } - } - - /* Now that the read thread is stopping, Wake any threads which are - waiting on data (in hid_read_timeout()). Do this under a mutex to - make sure that a thread which is about to go to sleep waiting on - the condition actually will go to sleep before the condition is - signaled. */ - pthread_mutex_lock(&dev->mutex); - pthread_cond_broadcast(&dev->condition); - pthread_mutex_unlock(&dev->mutex); - - /* Wait here until hid_close() is called and makes it past - the call to CFRunLoopWakeUp(). This thread still needs to - be valid when that function is called on the other thread. */ - pthread_barrier_wait(&dev->shutdown_barrier); - - return NULL; -} - -/* hid_open_path() - * - * path must be a valid path to an IOHIDDevice in the IOService plane - * Example: "IOService:/AppleACPIPlatformExpert/PCI0@0/AppleACPIPCI/EHC1@1D,7/AppleUSBEHCI/PLAYSTATION(R)3 Controller@fd120000/IOUSBInterface@0/IOUSBHIDDriver" - */ -hid_device * HID_API_EXPORT hid_open_path(const char *path) -{ - hid_device *dev = NULL; - io_registry_entry_t entry = MACH_PORT_NULL; - - dev = new_hid_device(); - - /* Set up the HID Manager if it hasn't been done */ - if (hid_init() < 0) - return NULL; - - /* Get the IORegistry entry for the given path */ - entry = IORegistryEntryFromPath(kIOMasterPortDefault, path); - if (entry == MACH_PORT_NULL) { - /* Path wasn't valid (maybe device was removed?) */ - goto return_error; - } - - /* Create an IOHIDDevice for the entry */ - dev->device_handle = IOHIDDeviceCreate(kCFAllocatorDefault, entry); - if (dev->device_handle == NULL) { - /* Error creating the HID device */ - goto return_error; - } - - /* Open the IOHIDDevice */ - IOReturn ret = IOHIDDeviceOpen(dev->device_handle, kIOHIDOptionsTypeSeizeDevice); - if (ret == kIOReturnSuccess) { - char str[32]; - - /* Create the buffers for receiving data */ - dev->max_input_report_len = (CFIndex) get_max_report_length(dev->device_handle); - dev->input_report_buf = calloc(dev->max_input_report_len, sizeof(uint8_t)); - - /* Create the Run Loop Mode for this device. - printing the reference seems to work. */ - sprintf(str, "HIDAPI_%p", dev->device_handle); - dev->run_loop_mode = - CFStringCreateWithCString(NULL, str, kCFStringEncodingASCII); - - /* Attach the device to a Run Loop */ - IOHIDDeviceRegisterInputReportCallback( - dev->device_handle, dev->input_report_buf, dev->max_input_report_len, - &hid_report_callback, dev); - IOHIDDeviceRegisterRemovalCallback(dev->device_handle, hid_device_removal_callback, dev); - - /* Start the read thread */ - pthread_create(&dev->thread, NULL, read_thread, dev); - - /* Wait here for the read thread to be initialized. */ - pthread_barrier_wait(&dev->barrier); - - IOObjectRelease(entry); - return dev; - } - else { - goto return_error; - } - -return_error: - if (dev->device_handle != NULL) - CFRelease(dev->device_handle); - - if (entry != MACH_PORT_NULL) - IOObjectRelease(entry); - - free_hid_device(dev); - return NULL; -} - -static int set_report(hid_device *dev, IOHIDReportType type, const unsigned char *data, size_t length) -{ - const unsigned char *data_to_send; - size_t length_to_send; - IOReturn res; - - /* Return if the device has been disconnected. */ - if (dev->disconnected) - return -1; - - if (data[0] == 0x0) { - /* Not using numbered Reports. - Don't send the report number. */ - data_to_send = data+1; - length_to_send = length-1; - } - else { - /* Using numbered Reports. - Send the Report Number */ - data_to_send = data; - length_to_send = length; - } - - if (!dev->disconnected) { - res = IOHIDDeviceSetReport(dev->device_handle, - type, - data[0], /* Report ID*/ - data_to_send, length_to_send); - - if (res == kIOReturnSuccess) { - return length; - } - else - return -1; - } - - return -1; -} - -int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length) -{ - return set_report(dev, kIOHIDReportTypeOutput, data, length); -} - -/* Helper function, so that this isn't duplicated in hid_read(). */ -static int return_data(hid_device *dev, unsigned char *data, size_t length) -{ - /* Copy the data out of the linked list item (rpt) into the - return buffer (data), and delete the liked list item. */ - struct input_report *rpt = dev->input_reports; - size_t len = (length < rpt->len)? length: rpt->len; - memcpy(data, rpt->data, len); - dev->input_reports = rpt->next; - free(rpt->data); - free(rpt); - return len; -} - -static int cond_wait(const hid_device *dev, pthread_cond_t *cond, pthread_mutex_t *mutex) -{ - while (!dev->input_reports) { - int res = pthread_cond_wait(cond, mutex); - if (res != 0) - return res; - - /* A res of 0 means we may have been signaled or it may - be a spurious wakeup. Check to see that there's acutally - data in the queue before returning, and if not, go back - to sleep. See the pthread_cond_timedwait() man page for - details. */ - - if (dev->shutdown_thread || dev->disconnected) - return -1; - } - - return 0; -} - -static int cond_timedwait(const hid_device *dev, pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime) -{ - while (!dev->input_reports) { - int res = pthread_cond_timedwait(cond, mutex, abstime); - if (res != 0) - return res; - - /* A res of 0 means we may have been signaled or it may - be a spurious wakeup. Check to see that there's acutally - data in the queue before returning, and if not, go back - to sleep. See the pthread_cond_timedwait() man page for - details. */ - - if (dev->shutdown_thread || dev->disconnected) - return -1; - } - - return 0; - -} - -int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds) -{ - int bytes_read = -1; - - /* Lock the access to the report list. */ - pthread_mutex_lock(&dev->mutex); - - /* There's an input report queued up. Return it. */ - if (dev->input_reports) { - /* Return the first one */ - bytes_read = return_data(dev, data, length); - goto ret; - } - - /* Return if the device has been disconnected. */ - if (dev->disconnected) { - bytes_read = -1; - goto ret; - } - - if (dev->shutdown_thread) { - /* This means the device has been closed (or there - has been an error. An error code of -1 should - be returned. */ - bytes_read = -1; - goto ret; - } - - /* There is no data. Go to sleep and wait for data. */ - - if (milliseconds == -1) { - /* Blocking */ - int res; - res = cond_wait(dev, &dev->condition, &dev->mutex); - if (res == 0) - bytes_read = return_data(dev, data, length); - else { - /* There was an error, or a device disconnection. */ - bytes_read = -1; - } - } - else if (milliseconds > 0) { - /* Non-blocking, but called with timeout. */ - int res; - struct timespec ts; - struct timeval tv; - gettimeofday(&tv, NULL); - TIMEVAL_TO_TIMESPEC(&tv, &ts); - ts.tv_sec += milliseconds / 1000; - ts.tv_nsec += (milliseconds % 1000) * 1000000; - if (ts.tv_nsec >= 1000000000L) { - ts.tv_sec++; - ts.tv_nsec -= 1000000000L; - } - - res = cond_timedwait(dev, &dev->condition, &dev->mutex, &ts); - if (res == 0) - bytes_read = return_data(dev, data, length); - else if (res == ETIMEDOUT) - bytes_read = 0; - else - bytes_read = -1; - } - else { - /* Purely non-blocking */ - bytes_read = 0; - } - -ret: - /* Unlock */ - pthread_mutex_unlock(&dev->mutex); - return bytes_read; -} - -int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length) -{ - return hid_read_timeout(dev, data, length, (dev->blocking)? -1: 0); -} - -int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock) -{ - /* All Nonblocking operation is handled by the library. */ - dev->blocking = !nonblock; - - return 0; -} - -int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length) -{ - return set_report(dev, kIOHIDReportTypeFeature, data, length); -} - -int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length) -{ - CFIndex len = length; - IOReturn res; - - /* Return if the device has been unplugged. */ - if (dev->disconnected) - return -1; - - res = IOHIDDeviceGetReport(dev->device_handle, - kIOHIDReportTypeFeature, - data[0], /* Report ID */ - data, &len); - if (res == kIOReturnSuccess) - return len; - else - return -1; -} - - -void HID_API_EXPORT hid_close(hid_device *dev) -{ - if (!dev) - return; - - /* Disconnect the report callback before close. */ - if (!dev->disconnected) { - IOHIDDeviceRegisterInputReportCallback( - dev->device_handle, dev->input_report_buf, dev->max_input_report_len, - NULL, dev); - IOHIDDeviceRegisterRemovalCallback(dev->device_handle, NULL, dev); - IOHIDDeviceUnscheduleFromRunLoop(dev->device_handle, dev->run_loop, dev->run_loop_mode); - IOHIDDeviceScheduleWithRunLoop(dev->device_handle, CFRunLoopGetMain(), kCFRunLoopDefaultMode); - } - - /* Cause read_thread() to stop. */ - dev->shutdown_thread = 1; - - /* Wake up the run thread's event loop so that the thread can exit. */ - CFRunLoopSourceSignal(dev->source); - CFRunLoopWakeUp(dev->run_loop); - - /* Notify the read thread that it can shut down now. */ - pthread_barrier_wait(&dev->shutdown_barrier); - - /* Wait for read_thread() to end. */ - pthread_join(dev->thread, NULL); - - /* Close the OS handle to the device, but only if it's not - been unplugged. If it's been unplugged, then calling - IOHIDDeviceClose() will crash. */ - if (!dev->disconnected) { - IOHIDDeviceClose(dev->device_handle, kIOHIDOptionsTypeSeizeDevice); - } - - /* Clear out the queue of received reports. */ - pthread_mutex_lock(&dev->mutex); - while (dev->input_reports) { - return_data(dev, NULL, 0); - } - pthread_mutex_unlock(&dev->mutex); - CFRelease(dev->device_handle); - - free_hid_device(dev); -} - -int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen) -{ - return get_manufacturer_string(dev->device_handle, string, maxlen); -} - -int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen) -{ - return get_product_string(dev->device_handle, string, maxlen); -} - -int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen) -{ - return get_serial_number(dev->device_handle, string, maxlen); -} - -int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen) -{ - /* TODO: */ - - return 0; -} - - -HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev) -{ - /* TODO: */ - - return NULL; -} - - - - - - - -#if 0 -static int32_t get_location_id(IOHIDDeviceRef device) -{ - return get_int_property(device, CFSTR(kIOHIDLocationIDKey)); -} - -static int32_t get_usage(IOHIDDeviceRef device) -{ - int32_t res; - res = get_int_property(device, CFSTR(kIOHIDDeviceUsageKey)); - if (!res) - res = get_int_property(device, CFSTR(kIOHIDPrimaryUsageKey)); - return res; -} - -static int32_t get_usage_page(IOHIDDeviceRef device) -{ - int32_t res; - res = get_int_property(device, CFSTR(kIOHIDDeviceUsagePageKey)); - if (!res) - res = get_int_property(device, CFSTR(kIOHIDPrimaryUsagePageKey)); - return res; -} - -static int get_transport(IOHIDDeviceRef device, wchar_t *buf, size_t len) -{ - return get_string_property(device, CFSTR(kIOHIDTransportKey), buf, len); -} - - -int main(void) -{ - IOHIDManagerRef mgr; - int i; - - mgr = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); - IOHIDManagerSetDeviceMatching(mgr, NULL); - IOHIDManagerOpen(mgr, kIOHIDOptionsTypeNone); - - CFSetRef device_set = IOHIDManagerCopyDevices(mgr); - - CFIndex num_devices = CFSetGetCount(device_set); - IOHIDDeviceRef *device_array = calloc(num_devices, sizeof(IOHIDDeviceRef)); - CFSetGetValues(device_set, (const void **) device_array); - - for (i = 0; i < num_devices; i++) { - IOHIDDeviceRef dev = device_array[i]; - printf("Device: %p\n", dev); - printf(" %04hx %04hx\n", get_vendor_id(dev), get_product_id(dev)); - - wchar_t serial[256], buf[256]; - char cbuf[256]; - get_serial_number(dev, serial, 256); - - - printf(" Serial: %ls\n", serial); - printf(" Loc: %ld\n", get_location_id(dev)); - get_transport(dev, buf, 256); - printf(" Trans: %ls\n", buf); - make_path(dev, cbuf, 256); - printf(" Path: %s\n", cbuf); - - } - - return 0; -} -#endif diff --git a/vendor/github.com/karalabe/hid/hidapi/windows/hid.c b/vendor/github.com/karalabe/hid/hidapi/windows/hid.c deleted file mode 100755 index 86810d7e..00000000 --- a/vendor/github.com/karalabe/hid/hidapi/windows/hid.c +++ /dev/null @@ -1,944 +0,0 @@ -/******************************************************* - HIDAPI - Multi-Platform library for - communication with HID devices. - - Alan Ott - Signal 11 Software - - 8/22/2009 - - Copyright 2009, All Rights Reserved. - - At the discretion of the user of this library, - this software may be licensed under the terms of the - GNU General Public License v3, a BSD-Style license, or the - original HIDAPI license as outlined in the LICENSE.txt, - LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt - files located at the root of the source distribution. - These files may also be found in the public source - code repository located at: - http://github.com/signal11/hidapi . -********************************************************/ - -#include - -#ifndef _NTDEF_ -typedef LONG NTSTATUS; -#endif - -#ifdef __MINGW32__ -#include -#include -#endif - -#ifdef __CYGWIN__ -#include -#define _wcsdup wcsdup -#endif - -/* The maximum number of characters that can be passed into the - HidD_Get*String() functions without it failing.*/ -#define MAX_STRING_WCHARS 0xFFF - -/*#define HIDAPI_USE_DDK*/ - -#ifdef __cplusplus -extern "C" { -#endif - #include - #include - #ifdef HIDAPI_USE_DDK - #include - #endif - - /* Copied from inc/ddk/hidclass.h, part of the Windows DDK. */ - #define HID_OUT_CTL_CODE(id) \ - CTL_CODE(FILE_DEVICE_KEYBOARD, (id), METHOD_OUT_DIRECT, FILE_ANY_ACCESS) - #define IOCTL_HID_GET_FEATURE HID_OUT_CTL_CODE(100) - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#include -#include - - -#include "hidapi.h" - -#undef MIN -#define MIN(x,y) ((x) < (y)? (x): (y)) - -#ifdef _MSC_VER - /* Thanks Microsoft, but I know how to use strncpy(). */ - #pragma warning(disable:4996) -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef HIDAPI_USE_DDK - /* Since we're not building with the DDK, and the HID header - files aren't part of the SDK, we have to define all this - stuff here. In lookup_functions(), the function pointers - defined below are set. */ - typedef struct _HIDD_ATTRIBUTES{ - ULONG Size; - USHORT VendorID; - USHORT ProductID; - USHORT VersionNumber; - } HIDD_ATTRIBUTES, *PHIDD_ATTRIBUTES; - - typedef USHORT USAGE; - typedef struct _HIDP_CAPS { - USAGE Usage; - USAGE UsagePage; - USHORT InputReportByteLength; - USHORT OutputReportByteLength; - USHORT FeatureReportByteLength; - USHORT Reserved[17]; - USHORT fields_not_used_by_hidapi[10]; - } HIDP_CAPS, *PHIDP_CAPS; - typedef void* PHIDP_PREPARSED_DATA; - #define HIDP_STATUS_SUCCESS 0x110000 - - typedef BOOLEAN (__stdcall *HidD_GetAttributes_)(HANDLE device, PHIDD_ATTRIBUTES attrib); - typedef BOOLEAN (__stdcall *HidD_GetSerialNumberString_)(HANDLE device, PVOID buffer, ULONG buffer_len); - typedef BOOLEAN (__stdcall *HidD_GetManufacturerString_)(HANDLE handle, PVOID buffer, ULONG buffer_len); - typedef BOOLEAN (__stdcall *HidD_GetProductString_)(HANDLE handle, PVOID buffer, ULONG buffer_len); - typedef BOOLEAN (__stdcall *HidD_SetFeature_)(HANDLE handle, PVOID data, ULONG length); - typedef BOOLEAN (__stdcall *HidD_GetFeature_)(HANDLE handle, PVOID data, ULONG length); - typedef BOOLEAN (__stdcall *HidD_GetIndexedString_)(HANDLE handle, ULONG string_index, PVOID buffer, ULONG buffer_len); - typedef BOOLEAN (__stdcall *HidD_GetPreparsedData_)(HANDLE handle, PHIDP_PREPARSED_DATA *preparsed_data); - typedef BOOLEAN (__stdcall *HidD_FreePreparsedData_)(PHIDP_PREPARSED_DATA preparsed_data); - typedef NTSTATUS (__stdcall *HidP_GetCaps_)(PHIDP_PREPARSED_DATA preparsed_data, HIDP_CAPS *caps); - typedef BOOLEAN (__stdcall *HidD_SetNumInputBuffers_)(HANDLE handle, ULONG number_buffers); - - static HidD_GetAttributes_ HidD_GetAttributes; - static HidD_GetSerialNumberString_ HidD_GetSerialNumberString; - static HidD_GetManufacturerString_ HidD_GetManufacturerString; - static HidD_GetProductString_ HidD_GetProductString; - static HidD_SetFeature_ HidD_SetFeature; - static HidD_GetFeature_ HidD_GetFeature; - static HidD_GetIndexedString_ HidD_GetIndexedString; - static HidD_GetPreparsedData_ HidD_GetPreparsedData; - static HidD_FreePreparsedData_ HidD_FreePreparsedData; - static HidP_GetCaps_ HidP_GetCaps; - static HidD_SetNumInputBuffers_ HidD_SetNumInputBuffers; - - static HMODULE lib_handle = NULL; - static BOOLEAN initialized = FALSE; -#endif /* HIDAPI_USE_DDK */ - -struct hid_device_ { - HANDLE device_handle; - BOOL blocking; - USHORT output_report_length; - size_t input_report_length; - void *last_error_str; - DWORD last_error_num; - BOOL read_pending; - char *read_buf; - OVERLAPPED ol; -}; - -static hid_device *new_hid_device() -{ - hid_device *dev = (hid_device*) calloc(1, sizeof(hid_device)); - dev->device_handle = INVALID_HANDLE_VALUE; - dev->blocking = TRUE; - dev->output_report_length = 0; - dev->input_report_length = 0; - dev->last_error_str = NULL; - dev->last_error_num = 0; - dev->read_pending = FALSE; - dev->read_buf = NULL; - memset(&dev->ol, 0, sizeof(dev->ol)); - dev->ol.hEvent = CreateEvent(NULL, FALSE, FALSE /*initial state f=nonsignaled*/, NULL); - - return dev; -} - -static void free_hid_device(hid_device *dev) -{ - CloseHandle(dev->ol.hEvent); - CloseHandle(dev->device_handle); - LocalFree(dev->last_error_str); - free(dev->read_buf); - free(dev); -} - -static void register_error(hid_device *device, const char *op) -{ - WCHAR *ptr, *msg; - - FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - GetLastError(), - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPVOID)&msg, 0/*sz*/, - NULL); - - /* Get rid of the CR and LF that FormatMessage() sticks at the - end of the message. Thanks Microsoft! */ - ptr = msg; - while (*ptr) { - if (*ptr == '\r') { - *ptr = 0x0000; - break; - } - ptr++; - } - - /* Store the message off in the Device entry so that - the hid_error() function can pick it up. */ - LocalFree(device->last_error_str); - device->last_error_str = msg; -} - -#ifndef HIDAPI_USE_DDK -static int lookup_functions() -{ - lib_handle = LoadLibraryA("hid.dll"); - if (lib_handle) { -#define RESOLVE(x) x = (x##_)GetProcAddress(lib_handle, #x); if (!x) return -1; - RESOLVE(HidD_GetAttributes); - RESOLVE(HidD_GetSerialNumberString); - RESOLVE(HidD_GetManufacturerString); - RESOLVE(HidD_GetProductString); - RESOLVE(HidD_SetFeature); - RESOLVE(HidD_GetFeature); - RESOLVE(HidD_GetIndexedString); - RESOLVE(HidD_GetPreparsedData); - RESOLVE(HidD_FreePreparsedData); - RESOLVE(HidP_GetCaps); - RESOLVE(HidD_SetNumInputBuffers); -#undef RESOLVE - } - else - return -1; - - return 0; -} -#endif - -static HANDLE open_device(const char *path, BOOL enumerate) -{ - HANDLE handle; - DWORD desired_access = (enumerate)? 0: (GENERIC_WRITE | GENERIC_READ); - DWORD share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE; - - handle = CreateFileA(path, - desired_access, - share_mode, - NULL, - OPEN_EXISTING, - FILE_FLAG_OVERLAPPED,/*FILE_ATTRIBUTE_NORMAL,*/ - 0); - - return handle; -} - -int HID_API_EXPORT hid_init(void) -{ -#ifndef HIDAPI_USE_DDK - if (!initialized) { - if (lookup_functions() < 0) { - hid_exit(); - return -1; - } - initialized = TRUE; - } -#endif - return 0; -} - -int HID_API_EXPORT hid_exit(void) -{ -#ifndef HIDAPI_USE_DDK - if (lib_handle) - FreeLibrary(lib_handle); - lib_handle = NULL; - initialized = FALSE; -#endif - return 0; -} - -struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned short vendor_id, unsigned short product_id) -{ - BOOL res; - struct hid_device_info *root = NULL; /* return object */ - struct hid_device_info *cur_dev = NULL; - - /* Windows objects for interacting with the driver. */ - GUID InterfaceClassGuid = {0x4d1e55b2, 0xf16f, 0x11cf, {0x88, 0xcb, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30} }; - SP_DEVINFO_DATA devinfo_data; - SP_DEVICE_INTERFACE_DATA device_interface_data; - SP_DEVICE_INTERFACE_DETAIL_DATA_A *device_interface_detail_data = NULL; - HDEVINFO device_info_set = INVALID_HANDLE_VALUE; - int device_index = 0; - int i; - - if (hid_init() < 0) - return NULL; - - /* Initialize the Windows objects. */ - memset(&devinfo_data, 0x0, sizeof(devinfo_data)); - devinfo_data.cbSize = sizeof(SP_DEVINFO_DATA); - device_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); - - /* Get information for all the devices belonging to the HID class. */ - device_info_set = SetupDiGetClassDevsA(&InterfaceClassGuid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); - - /* Iterate over each device in the HID class, looking for the right one. */ - - for (;;) { - HANDLE write_handle = INVALID_HANDLE_VALUE; - DWORD required_size = 0; - HIDD_ATTRIBUTES attrib; - - res = SetupDiEnumDeviceInterfaces(device_info_set, - NULL, - &InterfaceClassGuid, - device_index, - &device_interface_data); - - if (!res) { - /* A return of FALSE from this function means that - there are no more devices. */ - break; - } - - /* Call with 0-sized detail size, and let the function - tell us how long the detail struct needs to be. The - size is put in &required_size. */ - res = SetupDiGetDeviceInterfaceDetailA(device_info_set, - &device_interface_data, - NULL, - 0, - &required_size, - NULL); - - /* Allocate a long enough structure for device_interface_detail_data. */ - device_interface_detail_data = (SP_DEVICE_INTERFACE_DETAIL_DATA_A*) malloc(required_size); - device_interface_detail_data->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A); - - /* Get the detailed data for this device. The detail data gives us - the device path for this device, which is then passed into - CreateFile() to get a handle to the device. */ - res = SetupDiGetDeviceInterfaceDetailA(device_info_set, - &device_interface_data, - device_interface_detail_data, - required_size, - NULL, - NULL); - - if (!res) { - /* register_error(dev, "Unable to call SetupDiGetDeviceInterfaceDetail"); - Continue to the next device. */ - goto cont; - } - - /* Make sure this device is of Setup Class "HIDClass" and has a - driver bound to it. */ - for (i = 0; ; i++) { - char driver_name[256]; - - /* Populate devinfo_data. This function will return failure - when there are no more interfaces left. */ - res = SetupDiEnumDeviceInfo(device_info_set, i, &devinfo_data); - if (!res) - goto cont; - - res = SetupDiGetDeviceRegistryPropertyA(device_info_set, &devinfo_data, - SPDRP_CLASS, NULL, (PBYTE)driver_name, sizeof(driver_name), NULL); - if (!res) - goto cont; - - if (strcmp(driver_name, "HIDClass") == 0) { - /* See if there's a driver bound. */ - res = SetupDiGetDeviceRegistryPropertyA(device_info_set, &devinfo_data, - SPDRP_DRIVER, NULL, (PBYTE)driver_name, sizeof(driver_name), NULL); - if (res) - break; - } - } - - //wprintf(L"HandleName: %s\n", device_interface_detail_data->DevicePath); - - /* Open a handle to the device */ - write_handle = open_device(device_interface_detail_data->DevicePath, TRUE); - - /* Check validity of write_handle. */ - if (write_handle == INVALID_HANDLE_VALUE) { - /* Unable to open the device. */ - //register_error(dev, "CreateFile"); - goto cont_close; - } - - - /* Get the Vendor ID and Product ID for this device. */ - attrib.Size = sizeof(HIDD_ATTRIBUTES); - HidD_GetAttributes(write_handle, &attrib); - //wprintf(L"Product/Vendor: %x %x\n", attrib.ProductID, attrib.VendorID); - - /* Check the VID/PID to see if we should add this - device to the enumeration list. */ - if ((vendor_id == 0x0 || attrib.VendorID == vendor_id) && - (product_id == 0x0 || attrib.ProductID == product_id)) { - - #define WSTR_LEN 512 - const char *str; - struct hid_device_info *tmp; - PHIDP_PREPARSED_DATA pp_data = NULL; - HIDP_CAPS caps; - BOOLEAN res; - NTSTATUS nt_res; - wchar_t wstr[WSTR_LEN]; /* TODO: Determine Size */ - size_t len; - - /* VID/PID match. Create the record. */ - tmp = (struct hid_device_info*) calloc(1, sizeof(struct hid_device_info)); - if (cur_dev) { - cur_dev->next = tmp; - } - else { - root = tmp; - } - cur_dev = tmp; - - /* Get the Usage Page and Usage for this device. */ - res = HidD_GetPreparsedData(write_handle, &pp_data); - if (res) { - nt_res = HidP_GetCaps(pp_data, &caps); - if (nt_res == HIDP_STATUS_SUCCESS) { - cur_dev->usage_page = caps.UsagePage; - cur_dev->usage = caps.Usage; - } - - HidD_FreePreparsedData(pp_data); - } - - /* Fill out the record */ - cur_dev->next = NULL; - str = device_interface_detail_data->DevicePath; - if (str) { - len = strlen(str); - cur_dev->path = (char*) calloc(len+1, sizeof(char)); - strncpy(cur_dev->path, str, len+1); - cur_dev->path[len] = '\0'; - } - else - cur_dev->path = NULL; - - /* Serial Number */ - res = HidD_GetSerialNumberString(write_handle, wstr, sizeof(wstr)); - wstr[WSTR_LEN-1] = 0x0000; - if (res) { - cur_dev->serial_number = _wcsdup(wstr); - } - - /* Manufacturer String */ - res = HidD_GetManufacturerString(write_handle, wstr, sizeof(wstr)); - wstr[WSTR_LEN-1] = 0x0000; - if (res) { - cur_dev->manufacturer_string = _wcsdup(wstr); - } - - /* Product String */ - res = HidD_GetProductString(write_handle, wstr, sizeof(wstr)); - wstr[WSTR_LEN-1] = 0x0000; - if (res) { - cur_dev->product_string = _wcsdup(wstr); - } - - /* VID/PID */ - cur_dev->vendor_id = attrib.VendorID; - cur_dev->product_id = attrib.ProductID; - - /* Release Number */ - cur_dev->release_number = attrib.VersionNumber; - - /* Interface Number. It can sometimes be parsed out of the path - on Windows if a device has multiple interfaces. See - http://msdn.microsoft.com/en-us/windows/hardware/gg487473 or - search for "Hardware IDs for HID Devices" at MSDN. If it's not - in the path, it's set to -1. */ - cur_dev->interface_number = -1; - if (cur_dev->path) { - char *interface_component = strstr(cur_dev->path, "&mi_"); - if (interface_component) { - char *hex_str = interface_component + 4; - char *endptr = NULL; - cur_dev->interface_number = strtol(hex_str, &endptr, 16); - if (endptr == hex_str) { - /* The parsing failed. Set interface_number to -1. */ - cur_dev->interface_number = -1; - } - } - } - } - -cont_close: - CloseHandle(write_handle); -cont: - /* We no longer need the detail data. It can be freed */ - free(device_interface_detail_data); - - device_index++; - - } - - /* Close the device information handle. */ - SetupDiDestroyDeviceInfoList(device_info_set); - - return root; - -} - -void HID_API_EXPORT HID_API_CALL hid_free_enumeration(struct hid_device_info *devs) -{ - /* TODO: Merge this with the Linux version. This function is platform-independent. */ - struct hid_device_info *d = devs; - while (d) { - struct hid_device_info *next = d->next; - free(d->path); - free(d->serial_number); - free(d->manufacturer_string); - free(d->product_string); - free(d); - d = next; - } -} - - -HID_API_EXPORT hid_device * HID_API_CALL hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number) -{ - /* TODO: Merge this functions with the Linux version. This function should be platform independent. */ - struct hid_device_info *devs, *cur_dev; - const char *path_to_open = NULL; - hid_device *handle = NULL; - - devs = hid_enumerate(vendor_id, product_id); - cur_dev = devs; - while (cur_dev) { - if (cur_dev->vendor_id == vendor_id && - cur_dev->product_id == product_id) { - if (serial_number) { - if (wcscmp(serial_number, cur_dev->serial_number) == 0) { - path_to_open = cur_dev->path; - break; - } - } - else { - path_to_open = cur_dev->path; - break; - } - } - cur_dev = cur_dev->next; - } - - if (path_to_open) { - /* Open the device */ - handle = hid_open_path(path_to_open); - } - - hid_free_enumeration(devs); - - return handle; -} - -HID_API_EXPORT hid_device * HID_API_CALL hid_open_path(const char *path) -{ - hid_device *dev; - HIDP_CAPS caps; - PHIDP_PREPARSED_DATA pp_data = NULL; - BOOLEAN res; - NTSTATUS nt_res; - - if (hid_init() < 0) { - return NULL; - } - - dev = new_hid_device(); - - /* Open a handle to the device */ - dev->device_handle = open_device(path, FALSE); - - /* Check validity of write_handle. */ - if (dev->device_handle == INVALID_HANDLE_VALUE) { - /* Unable to open the device. */ - register_error(dev, "CreateFile"); - goto err; - } - - /* Set the Input Report buffer size to 64 reports. */ - res = HidD_SetNumInputBuffers(dev->device_handle, 64); - if (!res) { - register_error(dev, "HidD_SetNumInputBuffers"); - goto err; - } - - /* Get the Input Report length for the device. */ - res = HidD_GetPreparsedData(dev->device_handle, &pp_data); - if (!res) { - register_error(dev, "HidD_GetPreparsedData"); - goto err; - } - nt_res = HidP_GetCaps(pp_data, &caps); - if (nt_res != HIDP_STATUS_SUCCESS) { - register_error(dev, "HidP_GetCaps"); - goto err_pp_data; - } - dev->output_report_length = caps.OutputReportByteLength; - dev->input_report_length = caps.InputReportByteLength; - HidD_FreePreparsedData(pp_data); - - dev->read_buf = (char*) malloc(dev->input_report_length); - - return dev; - -err_pp_data: - HidD_FreePreparsedData(pp_data); -err: - free_hid_device(dev); - return NULL; -} - -int HID_API_EXPORT HID_API_CALL hid_write(hid_device *dev, const unsigned char *data, size_t length) -{ - DWORD bytes_written; - BOOL res; - - OVERLAPPED ol; - unsigned char *buf; - memset(&ol, 0, sizeof(ol)); - - /* Make sure the right number of bytes are passed to WriteFile. Windows - expects the number of bytes which are in the _longest_ report (plus - one for the report number) bytes even if the data is a report - which is shorter than that. Windows gives us this value in - caps.OutputReportByteLength. If a user passes in fewer bytes than this, - create a temporary buffer which is the proper size. */ - if (length >= dev->output_report_length) { - /* The user passed the right number of bytes. Use the buffer as-is. */ - buf = (unsigned char *) data; - } else { - /* Create a temporary buffer and copy the user's data - into it, padding the rest with zeros. */ - buf = (unsigned char *) malloc(dev->output_report_length); - memcpy(buf, data, length); - memset(buf + length, 0, dev->output_report_length - length); - length = dev->output_report_length; - } - - res = WriteFile(dev->device_handle, buf, length, NULL, &ol); - - if (!res) { - if (GetLastError() != ERROR_IO_PENDING) { - /* WriteFile() failed. Return error. */ - register_error(dev, "WriteFile"); - bytes_written = -1; - goto end_of_function; - } - } - - /* Wait here until the write is done. This makes - hid_write() synchronous. */ - res = GetOverlappedResult(dev->device_handle, &ol, &bytes_written, TRUE/*wait*/); - if (!res) { - /* The Write operation failed. */ - register_error(dev, "WriteFile"); - bytes_written = -1; - goto end_of_function; - } - -end_of_function: - if (buf != data) - free(buf); - - return bytes_written; -} - - -int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds) -{ - DWORD bytes_read = 0; - size_t copy_len = 0; - BOOL res; - - /* Copy the handle for convenience. */ - HANDLE ev = dev->ol.hEvent; - - if (!dev->read_pending) { - /* Start an Overlapped I/O read. */ - dev->read_pending = TRUE; - memset(dev->read_buf, 0, dev->input_report_length); - ResetEvent(ev); - res = ReadFile(dev->device_handle, dev->read_buf, dev->input_report_length, &bytes_read, &dev->ol); - - if (!res) { - if (GetLastError() != ERROR_IO_PENDING) { - /* ReadFile() has failed. - Clean up and return error. */ - CancelIo(dev->device_handle); - dev->read_pending = FALSE; - goto end_of_function; - } - } - } - - if (milliseconds >= 0) { - /* See if there is any data yet. */ - res = WaitForSingleObject(ev, milliseconds); - if (res != WAIT_OBJECT_0) { - /* There was no data this time. Return zero bytes available, - but leave the Overlapped I/O running. */ - return 0; - } - } - - /* Either WaitForSingleObject() told us that ReadFile has completed, or - we are in non-blocking mode. Get the number of bytes read. The actual - data has been copied to the data[] array which was passed to ReadFile(). */ - res = GetOverlappedResult(dev->device_handle, &dev->ol, &bytes_read, TRUE/*wait*/); - - /* Set pending back to false, even if GetOverlappedResult() returned error. */ - dev->read_pending = FALSE; - - if (res && bytes_read > 0) { - if (dev->read_buf[0] == 0x0) { - /* If report numbers aren't being used, but Windows sticks a report - number (0x0) on the beginning of the report anyway. To make this - work like the other platforms, and to make it work more like the - HID spec, we'll skip over this byte. */ - bytes_read--; - copy_len = length > bytes_read ? bytes_read : length; - memcpy(data, dev->read_buf+1, copy_len); - } - else { - /* Copy the whole buffer, report number and all. */ - copy_len = length > bytes_read ? bytes_read : length; - memcpy(data, dev->read_buf, copy_len); - } - } - -end_of_function: - if (!res) { - register_error(dev, "GetOverlappedResult"); - return -1; - } - - return copy_len; -} - -int HID_API_EXPORT HID_API_CALL hid_read(hid_device *dev, unsigned char *data, size_t length) -{ - return hid_read_timeout(dev, data, length, (dev->blocking)? -1: 0); -} - -int HID_API_EXPORT HID_API_CALL hid_set_nonblocking(hid_device *dev, int nonblock) -{ - dev->blocking = !nonblock; - return 0; /* Success */ -} - -int HID_API_EXPORT HID_API_CALL hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length) -{ - BOOL res = HidD_SetFeature(dev->device_handle, (PVOID)data, length); - if (!res) { - register_error(dev, "HidD_SetFeature"); - return -1; - } - - return length; -} - - -int HID_API_EXPORT HID_API_CALL hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length) -{ - BOOL res; -#if 0 - res = HidD_GetFeature(dev->device_handle, data, length); - if (!res) { - register_error(dev, "HidD_GetFeature"); - return -1; - } - return 0; /* HidD_GetFeature() doesn't give us an actual length, unfortunately */ -#else - DWORD bytes_returned; - - OVERLAPPED ol; - memset(&ol, 0, sizeof(ol)); - - res = DeviceIoControl(dev->device_handle, - IOCTL_HID_GET_FEATURE, - data, length, - data, length, - &bytes_returned, &ol); - - if (!res) { - if (GetLastError() != ERROR_IO_PENDING) { - /* DeviceIoControl() failed. Return error. */ - register_error(dev, "Send Feature Report DeviceIoControl"); - return -1; - } - } - - /* Wait here until the write is done. This makes - hid_get_feature_report() synchronous. */ - res = GetOverlappedResult(dev->device_handle, &ol, &bytes_returned, TRUE/*wait*/); - if (!res) { - /* The operation failed. */ - register_error(dev, "Send Feature Report GetOverLappedResult"); - return -1; - } - - /* bytes_returned does not include the first byte which contains the - report ID. The data buffer actually contains one more byte than - bytes_returned. */ - bytes_returned++; - - return bytes_returned; -#endif -} - -void HID_API_EXPORT HID_API_CALL hid_close(hid_device *dev) -{ - if (!dev) - return; - CancelIo(dev->device_handle); - free_hid_device(dev); -} - -int HID_API_EXPORT_CALL HID_API_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen) -{ - BOOL res; - - res = HidD_GetManufacturerString(dev->device_handle, string, sizeof(wchar_t) * MIN(maxlen, MAX_STRING_WCHARS)); - if (!res) { - register_error(dev, "HidD_GetManufacturerString"); - return -1; - } - - return 0; -} - -int HID_API_EXPORT_CALL HID_API_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen) -{ - BOOL res; - - res = HidD_GetProductString(dev->device_handle, string, sizeof(wchar_t) * MIN(maxlen, MAX_STRING_WCHARS)); - if (!res) { - register_error(dev, "HidD_GetProductString"); - return -1; - } - - return 0; -} - -int HID_API_EXPORT_CALL HID_API_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen) -{ - BOOL res; - - res = HidD_GetSerialNumberString(dev->device_handle, string, sizeof(wchar_t) * MIN(maxlen, MAX_STRING_WCHARS)); - if (!res) { - register_error(dev, "HidD_GetSerialNumberString"); - return -1; - } - - return 0; -} - -int HID_API_EXPORT_CALL HID_API_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen) -{ - BOOL res; - - res = HidD_GetIndexedString(dev->device_handle, string_index, string, sizeof(wchar_t) * MIN(maxlen, MAX_STRING_WCHARS)); - if (!res) { - register_error(dev, "HidD_GetIndexedString"); - return -1; - } - - return 0; -} - - -HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev) -{ - return (wchar_t*)dev->last_error_str; -} - - -/*#define PICPGM*/ -/*#define S11*/ -#define P32 -#ifdef S11 - unsigned short VendorID = 0xa0a0; - unsigned short ProductID = 0x0001; -#endif - -#ifdef P32 - unsigned short VendorID = 0x04d8; - unsigned short ProductID = 0x3f; -#endif - - -#ifdef PICPGM - unsigned short VendorID = 0x04d8; - unsigned short ProductID = 0x0033; -#endif - - -#if 0 -int __cdecl main(int argc, char* argv[]) -{ - int res; - unsigned char buf[65]; - - UNREFERENCED_PARAMETER(argc); - UNREFERENCED_PARAMETER(argv); - - /* Set up the command buffer. */ - memset(buf,0x00,sizeof(buf)); - buf[0] = 0; - buf[1] = 0x81; - - - /* Open the device. */ - int handle = open(VendorID, ProductID, L"12345"); - if (handle < 0) - printf("unable to open device\n"); - - - /* Toggle LED (cmd 0x80) */ - buf[1] = 0x80; - res = write(handle, buf, 65); - if (res < 0) - printf("Unable to write()\n"); - - /* Request state (cmd 0x81) */ - buf[1] = 0x81; - write(handle, buf, 65); - if (res < 0) - printf("Unable to write() (2)\n"); - - /* Read requested state */ - read(handle, buf, 65); - if (res < 0) - printf("Unable to read()\n"); - - /* Print out the returned buffer. */ - for (int i = 0; i < 4; i++) - printf("buf[%d]: %d\n", i, buf[i]); - - return 0; -} -#endif - -#ifdef __cplusplus -} /* extern "C" */ -#endif diff --git a/vendor/github.com/karalabe/hid/libusb/AUTHORS b/vendor/github.com/karalabe/hid/libusb/AUTHORS deleted file mode 100644 index 70d407bd..00000000 --- a/vendor/github.com/karalabe/hid/libusb/AUTHORS +++ /dev/null @@ -1,89 +0,0 @@ -Copyright © 2001 Johannes Erdfelt -Copyright © 2007-2009 Daniel Drake -Copyright © 2010-2012 Peter Stuge -Copyright © 2008-2016 Nathan Hjelm -Copyright © 2009-2013 Pete Batard -Copyright © 2009-2013 Ludovic Rousseau -Copyright © 2010-2012 Michael Plante -Copyright © 2011-2013 Hans de Goede -Copyright © 2012-2013 Martin Pieuchot -Copyright © 2012-2013 Toby Gray -Copyright © 2013-2015 Chris Dickens - -Other contributors: -Akshay Jaggi -Alan Ott -Alan Stern -Alex Vatchenko -Andrew Fernandes -Anthony Clay -Antonio Ospite -Artem Egorkine -Aurelien Jarno -Bastien Nocera -Bei Zhang -Benjamin Dobell -Carl Karsten -Colin Walters -Dave Camarillo -David Engraf -David Moore -Davidlohr Bueso -Federico Manzan -Felipe Balbi -Florian Albrechtskirchinger -Francesco Montorsi -Francisco Facioni -Gaurav Gupta -Graeme Gill -Gustavo Zacarias -Hans Ulrich Niedermann -Hector Martin -Hoi-Ho Chan -Ilya Konstantinov -James Hanko -John Sheu -Joshua Blake -Justin Bischoff -Karsten Koenig -Konrad Rzepecki -Kuangye Guo -Lars Kanis -Lars Wirzenius -Luca Longinotti -Marcus Meissner -Markus Heidelberg -Martin Ettl -Martin Koegler -Matthias Bolte -Mike Frysinger -Mikhail Gusarov -Moritz Fischer -Ларионов Даниил -Nicholas Corgan -Omri Iluz -Orin Eman -Paul Fertser -Pekka Nikander -Rob Walker -Sean McBride -Sebastian Pipping -Simon Haggett -Simon Newton -Thomas Röfer -Tim Hutt -Tim Roberts -Tobias Klauser -Toby Peterson -Tormod Volden -Trygve Laugstøl -Uri Lublin -Vasily Khoruzhick -Vegard Storheil Eriksen -Venkatesh Shukla -Vitali Lovich -Xiaofan Chen -Zoltán Kovács -Роман Донченко -parafin -xantares diff --git a/vendor/github.com/karalabe/hid/libusb/COPYING b/vendor/github.com/karalabe/hid/libusb/COPYING deleted file mode 100644 index 5ab7695a..00000000 --- a/vendor/github.com/karalabe/hid/libusb/COPYING +++ /dev/null @@ -1,504 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Libraries - - If you develop a new library, and you want it to be of the greatest -possible use to the public, we recommend making it free software that -everyone can redistribute and change. You can do so by permitting -redistribution under these terms (or, alternatively, under the terms of the -ordinary General Public License). - - To apply these terms, attach the following notices to the library. It is -safest to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least the -"copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This 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 2.1 of the License, or (at your option) any later version. - - This 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 this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - -Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the library, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the - library `Frob' (a library for tweaking knobs) written by James Random Hacker. - - , 1 April 1990 - Ty Coon, President of Vice - -That's all there is to it! - - diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/config.h b/vendor/github.com/karalabe/hid/libusb/libusb/config.h deleted file mode 100644 index e004f03c..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/config.h +++ /dev/null @@ -1,3 +0,0 @@ -#ifndef CONFIG_H -#define CONFIG_H -#endif diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/core.c b/vendor/github.com/karalabe/hid/libusb/libusb/core.c deleted file mode 100644 index d45bfe17..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/core.c +++ /dev/null @@ -1,2523 +0,0 @@ -/* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */ -/* - * Core functions for libusb - * Copyright © 2012-2013 Nathan Hjelm - * Copyright © 2007-2008 Daniel Drake - * Copyright © 2001 Johannes Erdfelt - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include "config.h" - -#include -#include -#include -#include -#include -#ifdef HAVE_SYS_TYPES_H -#include -#endif -#ifdef HAVE_SYS_TIME_H -#include -#endif -#ifdef HAVE_SYSLOG_H -#include -#endif - -#ifdef __ANDROID__ -#include -#endif - -#include "libusbi.h" -#include "hotplug.h" - -#if defined(OS_LINUX) -const struct usbi_os_backend * const usbi_backend = &linux_usbfs_backend; -#elif defined(OS_DARWIN) -const struct usbi_os_backend * const usbi_backend = &darwin_backend; -#elif defined(OS_OPENBSD) -const struct usbi_os_backend * const usbi_backend = &openbsd_backend; -#elif defined(OS_NETBSD) -const struct usbi_os_backend * const usbi_backend = &netbsd_backend; -#elif defined(OS_WINDOWS) - -#if defined(USE_USBDK) -const struct usbi_os_backend * const usbi_backend = &usbdk_backend; -#else -const struct usbi_os_backend * const usbi_backend = &windows_backend; -#endif - -#elif defined(OS_WINCE) -const struct usbi_os_backend * const usbi_backend = &wince_backend; -#elif defined(OS_HAIKU) -const struct usbi_os_backend * const usbi_backend = &haiku_usb_raw_backend; -#elif defined (OS_SUNOS) -const struct usbi_os_backend * const usbi_backend = &sunos_backend; -#else -#error "Unsupported OS" -#endif - -struct libusb_context *usbi_default_context = NULL; -static const struct libusb_version libusb_version_internal = - { LIBUSB_MAJOR, LIBUSB_MINOR, LIBUSB_MICRO, LIBUSB_NANO, - LIBUSB_RC, "http://libusb.info" }; -static int default_context_refcnt = 0; -static usbi_mutex_static_t default_context_lock = USBI_MUTEX_INITIALIZER; -static struct timespec timestamp_origin = { 0, 0 }; - -usbi_mutex_static_t active_contexts_lock = USBI_MUTEX_INITIALIZER; -struct list_head active_contexts_list; - -/** - * \mainpage libusb-1.0 API Reference - * - * \section intro Introduction - * - * libusb is an open source library that allows you to communicate with USB - * devices from userspace. For more info, see the - * libusb homepage. - * - * This documentation is aimed at application developers wishing to - * communicate with USB peripherals from their own software. After reviewing - * this documentation, feedback and questions can be sent to the - * libusb-devel mailing list. - * - * This documentation assumes knowledge of how to operate USB devices from - * a software standpoint (descriptors, configurations, interfaces, endpoints, - * control/bulk/interrupt/isochronous transfers, etc). Full information - * can be found in the USB 3.0 - * Specification which is available for free download. You can probably - * find less verbose introductions by searching the web. - * - * \section API Application Programming Interface (API) - * - * See the \ref libusb_api page for a complete list of the libusb functions. - * - * \section features Library features - * - * - All transfer types supported (control/bulk/interrupt/isochronous) - * - 2 transfer interfaces: - * -# Synchronous (simple) - * -# Asynchronous (more complicated, but more powerful) - * - Thread safe (although the asynchronous interface means that you - * usually won't need to thread) - * - Lightweight with lean API - * - Compatible with libusb-0.1 through the libusb-compat-0.1 translation layer - * - Hotplug support (on some platforms). See \ref libusb_hotplug. - * - * \section gettingstarted Getting Started - * - * To begin reading the API documentation, start with the Modules page which - * links to the different categories of libusb's functionality. - * - * One decision you will have to make is whether to use the synchronous - * or the asynchronous data transfer interface. The \ref libusb_io documentation - * provides some insight into this topic. - * - * Some example programs can be found in the libusb source distribution under - * the "examples" subdirectory. The libusb homepage includes a list of - * real-life project examples which use libusb. - * - * \section errorhandling Error handling - * - * libusb functions typically return 0 on success or a negative error code - * on failure. These negative error codes relate to LIBUSB_ERROR constants - * which are listed on the \ref libusb_misc "miscellaneous" documentation page. - * - * \section msglog Debug message logging - * - * libusb uses stderr for all logging. By default, logging is set to NONE, - * which means that no output will be produced. However, unless the library - * has been compiled with logging disabled, then any application calls to - * libusb_set_debug(), or the setting of the environmental variable - * LIBUSB_DEBUG outside of the application, can result in logging being - * produced. Your application should therefore not close stderr, but instead - * direct it to the null device if its output is undesirable. - * - * The libusb_set_debug() function can be used to enable logging of certain - * messages. Under standard configuration, libusb doesn't really log much - * so you are advised to use this function to enable all error/warning/ - * informational messages. It will help debug problems with your software. - * - * The logged messages are unstructured. There is no one-to-one correspondence - * between messages being logged and success or failure return codes from - * libusb functions. There is no format to the messages, so you should not - * try to capture or parse them. They are not and will not be localized. - * These messages are not intended to being passed to your application user; - * instead, you should interpret the error codes returned from libusb functions - * and provide appropriate notification to the user. The messages are simply - * there to aid you as a programmer, and if you're confused because you're - * getting a strange error code from a libusb function, enabling message - * logging may give you a suitable explanation. - * - * The LIBUSB_DEBUG environment variable can be used to enable message logging - * at run-time. This environment variable should be set to a log level number, - * which is interpreted the same as the libusb_set_debug() parameter. When this - * environment variable is set, the message logging verbosity level is fixed - * and libusb_set_debug() effectively does nothing. - * - * libusb can be compiled without any logging functions, useful for embedded - * systems. In this case, libusb_set_debug() and the LIBUSB_DEBUG environment - * variable have no effects. - * - * libusb can also be compiled with verbose debugging messages always. When - * the library is compiled in this way, all messages of all verbosities are - * always logged. libusb_set_debug() and the LIBUSB_DEBUG environment variable - * have no effects. - * - * \section remarks Other remarks - * - * libusb does have imperfections. The \ref libusb_caveats "caveats" page attempts - * to document these. - */ - -/** - * \page libusb_caveats Caveats - * - * \section devresets Device resets - * - * The libusb_reset_device() function allows you to reset a device. If your - * program has to call such a function, it should obviously be aware that - * the reset will cause device state to change (e.g. register values may be - * reset). - * - * The problem is that any other program could reset the device your program - * is working with, at any time. libusb does not offer a mechanism to inform - * you when this has happened, so if someone else resets your device it will - * not be clear to your own program why the device state has changed. - * - * Ultimately, this is a limitation of writing drivers in userspace. - * Separation from the USB stack in the underlying kernel makes it difficult - * for the operating system to deliver such notifications to your program. - * The Linux kernel USB stack allows such reset notifications to be delivered - * to in-kernel USB drivers, but it is not clear how such notifications could - * be delivered to second-class drivers that live in userspace. - * - * \section blockonly Blocking-only functionality - * - * The functionality listed below is only available through synchronous, - * blocking functions. There are no asynchronous/non-blocking alternatives, - * and no clear ways of implementing these. - * - * - Configuration activation (libusb_set_configuration()) - * - Interface/alternate setting activation (libusb_set_interface_alt_setting()) - * - Releasing of interfaces (libusb_release_interface()) - * - Clearing of halt/stall condition (libusb_clear_halt()) - * - Device resets (libusb_reset_device()) - * - * \section configsel Configuration selection and handling - * - * When libusb presents a device handle to an application, there is a chance - * that the corresponding device may be in unconfigured state. For devices - * with multiple configurations, there is also a chance that the configuration - * currently selected is not the one that the application wants to use. - * - * The obvious solution is to add a call to libusb_set_configuration() early - * on during your device initialization routines, but there are caveats to - * be aware of: - * -# If the device is already in the desired configuration, calling - * libusb_set_configuration() using the same configuration value will cause - * a lightweight device reset. This may not be desirable behaviour. - * -# In the case where the desired configuration is already active, libusb - * may not even be able to perform a lightweight device reset. For example, - * take my USB keyboard with fingerprint reader: I'm interested in driving - * the fingerprint reader interface through libusb, but the kernel's - * USB-HID driver will almost always have claimed the keyboard interface. - * Because the kernel has claimed an interface, it is not even possible to - * perform the lightweight device reset, so libusb_set_configuration() will - * fail. (Luckily the device in question only has a single configuration.) - * -# libusb will be unable to set a configuration if other programs or - * drivers have claimed interfaces. In particular, this means that kernel - * drivers must be detached from all the interfaces before - * libusb_set_configuration() may succeed. - * - * One solution to some of the above problems is to consider the currently - * active configuration. If the configuration we want is already active, then - * we don't have to select any configuration: -\code -cfg = -1; -libusb_get_configuration(dev, &cfg); -if (cfg != desired) - libusb_set_configuration(dev, desired); -\endcode - * - * This is probably suitable for most scenarios, but is inherently racy: - * another application or driver may change the selected configuration - * after the libusb_get_configuration() call. - * - * Even in cases where libusb_set_configuration() succeeds, consider that other - * applications or drivers may change configuration after your application - * calls libusb_set_configuration(). - * - * One possible way to lock your device into a specific configuration is as - * follows: - * -# Set the desired configuration (or use the logic above to realise that - * it is already in the desired configuration) - * -# Claim the interface that you wish to use - * -# Check that the currently active configuration is the one that you want - * to use. - * - * The above method works because once an interface is claimed, no application - * or driver is able to select another configuration. - * - * \section earlycomp Early transfer completion - * - * NOTE: This section is currently Linux-centric. I am not sure if any of these - * considerations apply to Darwin or other platforms. - * - * When a transfer completes early (i.e. when less data is received/sent in - * any one packet than the transfer buffer allows for) then libusb is designed - * to terminate the transfer immediately, not transferring or receiving any - * more data unless other transfers have been queued by the user. - * - * On legacy platforms, libusb is unable to do this in all situations. After - * the incomplete packet occurs, "surplus" data may be transferred. For recent - * versions of libusb, this information is kept (the data length of the - * transfer is updated) and, for device-to-host transfers, any surplus data was - * added to the buffer. Still, this is not a nice solution because it loses the - * information about the end of the short packet, and the user probably wanted - * that surplus data to arrive in the next logical transfer. - * - * - * \section zlp Zero length packets - * - * - libusb is able to send a packet of zero length to an endpoint simply by - * submitting a transfer of zero length. - * - The \ref libusb_transfer_flags::LIBUSB_TRANSFER_ADD_ZERO_PACKET - * "LIBUSB_TRANSFER_ADD_ZERO_PACKET" flag is currently only supported on Linux. - */ - -/** - * \page libusb_contexts Contexts - * - * It is possible that libusb may be used simultaneously from two independent - * libraries linked into the same executable. For example, if your application - * has a plugin-like system which allows the user to dynamically load a range - * of modules into your program, it is feasible that two independently - * developed modules may both use libusb. - * - * libusb is written to allow for these multiple user scenarios. The two - * "instances" of libusb will not interfere: libusb_set_debug() calls - * from one user will not affect the same settings for other users, other - * users can continue using libusb after one of them calls libusb_exit(), etc. - * - * This is made possible through libusb's context concept. When you - * call libusb_init(), you are (optionally) given a context. You can then pass - * this context pointer back into future libusb functions. - * - * In order to keep things simple for more simplistic applications, it is - * legal to pass NULL to all functions requiring a context pointer (as long as - * you're sure no other code will attempt to use libusb from the same process). - * When you pass NULL, the default context will be used. The default context - * is created the first time a process calls libusb_init() when no other - * context is alive. Contexts are destroyed during libusb_exit(). - * - * The default context is reference-counted and can be shared. That means that - * if libusb_init(NULL) is called twice within the same process, the two - * users end up sharing the same context. The deinitialization and freeing of - * the default context will only happen when the last user calls libusb_exit(). - * In other words, the default context is created and initialized when its - * reference count goes from 0 to 1, and is deinitialized and destroyed when - * its reference count goes from 1 to 0. - * - * You may be wondering why only a subset of libusb functions require a - * context pointer in their function definition. Internally, libusb stores - * context pointers in other objects (e.g. libusb_device instances) and hence - * can infer the context from those objects. - */ - - /** - * \page libusb_api Application Programming Interface - * - * This is the complete list of libusb functions, structures and - * enumerations in alphabetical order. - * - * \section Functions - * - libusb_alloc_streams() - * - libusb_alloc_transfer() - * - libusb_attach_kernel_driver() - * - libusb_bulk_transfer() - * - libusb_cancel_transfer() - * - libusb_claim_interface() - * - libusb_clear_halt() - * - libusb_close() - * - libusb_control_transfer() - * - libusb_control_transfer_get_data() - * - libusb_control_transfer_get_setup() - * - libusb_cpu_to_le16() - * - libusb_detach_kernel_driver() - * - libusb_dev_mem_alloc() - * - libusb_dev_mem_free() - * - libusb_error_name() - * - libusb_event_handler_active() - * - libusb_event_handling_ok() - * - libusb_exit() - * - libusb_fill_bulk_stream_transfer() - * - libusb_fill_bulk_transfer() - * - libusb_fill_control_setup() - * - libusb_fill_control_transfer() - * - libusb_fill_interrupt_transfer() - * - libusb_fill_iso_transfer() - * - libusb_free_bos_descriptor() - * - libusb_free_config_descriptor() - * - libusb_free_container_id_descriptor() - * - libusb_free_device_list() - * - libusb_free_pollfds() - * - libusb_free_ss_endpoint_companion_descriptor() - * - libusb_free_ss_usb_device_capability_descriptor() - * - libusb_free_streams() - * - libusb_free_transfer() - * - libusb_free_usb_2_0_extension_descriptor() - * - libusb_get_active_config_descriptor() - * - libusb_get_bos_descriptor() - * - libusb_get_bus_number() - * - libusb_get_config_descriptor() - * - libusb_get_config_descriptor_by_value() - * - libusb_get_configuration() - * - libusb_get_container_id_descriptor() - * - libusb_get_descriptor() - * - libusb_get_device() - * - libusb_get_device_address() - * - libusb_get_device_descriptor() - * - libusb_get_device_list() - * - libusb_get_device_speed() - * - libusb_get_iso_packet_buffer() - * - libusb_get_iso_packet_buffer_simple() - * - libusb_get_max_iso_packet_size() - * - libusb_get_max_packet_size() - * - libusb_get_next_timeout() - * - libusb_get_parent() - * - libusb_get_pollfds() - * - libusb_get_port_number() - * - libusb_get_port_numbers() - * - libusb_get_port_path() - * - libusb_get_ss_endpoint_companion_descriptor() - * - libusb_get_ss_usb_device_capability_descriptor() - * - libusb_get_string_descriptor() - * - libusb_get_string_descriptor_ascii() - * - libusb_get_usb_2_0_extension_descriptor() - * - libusb_get_version() - * - libusb_handle_events() - * - libusb_handle_events_completed() - * - libusb_handle_events_locked() - * - libusb_handle_events_timeout() - * - libusb_handle_events_timeout_completed() - * - libusb_has_capability() - * - libusb_hotplug_deregister_callback() - * - libusb_hotplug_register_callback() - * - libusb_init() - * - libusb_interrupt_event_handler() - * - libusb_interrupt_transfer() - * - libusb_kernel_driver_active() - * - libusb_lock_events() - * - libusb_lock_event_waiters() - * - libusb_open() - * - libusb_open_device_with_vid_pid() - * - libusb_pollfds_handle_timeouts() - * - libusb_ref_device() - * - libusb_release_interface() - * - libusb_reset_device() - * - libusb_set_auto_detach_kernel_driver() - * - libusb_set_configuration() - * - libusb_set_debug() - * - libusb_set_interface_alt_setting() - * - libusb_set_iso_packet_lengths() - * - libusb_setlocale() - * - libusb_set_pollfd_notifiers() - * - libusb_strerror() - * - libusb_submit_transfer() - * - libusb_transfer_get_stream_id() - * - libusb_transfer_set_stream_id() - * - libusb_try_lock_events() - * - libusb_unlock_events() - * - libusb_unlock_event_waiters() - * - libusb_unref_device() - * - libusb_wait_for_event() - * - * \section Structures - * - libusb_bos_descriptor - * - libusb_bos_dev_capability_descriptor - * - libusb_config_descriptor - * - libusb_container_id_descriptor - * - \ref libusb_context - * - libusb_control_setup - * - \ref libusb_device - * - libusb_device_descriptor - * - \ref libusb_device_handle - * - libusb_endpoint_descriptor - * - libusb_interface - * - libusb_interface_descriptor - * - libusb_iso_packet_descriptor - * - libusb_pollfd - * - libusb_ss_endpoint_companion_descriptor - * - libusb_ss_usb_device_capability_descriptor - * - libusb_transfer - * - libusb_usb_2_0_extension_descriptor - * - libusb_version - * - * \section Enums - * - \ref libusb_bos_type - * - \ref libusb_capability - * - \ref libusb_class_code - * - \ref libusb_descriptor_type - * - \ref libusb_endpoint_direction - * - \ref libusb_error - * - \ref libusb_iso_sync_type - * - \ref libusb_iso_usage_type - * - \ref libusb_log_level - * - \ref libusb_request_recipient - * - \ref libusb_request_type - * - \ref libusb_speed - * - \ref libusb_ss_usb_device_capability_attributes - * - \ref libusb_standard_request - * - \ref libusb_supported_speed - * - \ref libusb_transfer_flags - * - \ref libusb_transfer_status - * - \ref libusb_transfer_type - * - \ref libusb_usb_2_0_extension_attributes - */ - -/** - * @defgroup libusb_lib Library initialization/deinitialization - * This page details how to initialize and deinitialize libusb. Initialization - * must be performed before using any libusb functionality, and similarly you - * must not call any libusb functions after deinitialization. - */ - -/** - * @defgroup libusb_dev Device handling and enumeration - * The functionality documented below is designed to help with the following - * operations: - * - Enumerating the USB devices currently attached to the system - * - Choosing a device to operate from your software - * - Opening and closing the chosen device - * - * \section nutshell In a nutshell... - * - * The description below really makes things sound more complicated than they - * actually are. The following sequence of function calls will be suitable - * for almost all scenarios and does not require you to have such a deep - * understanding of the resource management issues: - * \code -// discover devices -libusb_device **list; -libusb_device *found = NULL; -ssize_t cnt = libusb_get_device_list(NULL, &list); -ssize_t i = 0; -int err = 0; -if (cnt < 0) - error(); - -for (i = 0; i < cnt; i++) { - libusb_device *device = list[i]; - if (is_interesting(device)) { - found = device; - break; - } -} - -if (found) { - libusb_device_handle *handle; - - err = libusb_open(found, &handle); - if (err) - error(); - // etc -} - -libusb_free_device_list(list, 1); -\endcode - * - * The two important points: - * - You asked libusb_free_device_list() to unreference the devices (2nd - * parameter) - * - You opened the device before freeing the list and unreferencing the - * devices - * - * If you ended up with a handle, you can now proceed to perform I/O on the - * device. - * - * \section devshandles Devices and device handles - * libusb has a concept of a USB device, represented by the - * \ref libusb_device opaque type. A device represents a USB device that - * is currently or was previously connected to the system. Using a reference - * to a device, you can determine certain information about the device (e.g. - * you can read the descriptor data). - * - * The libusb_get_device_list() function can be used to obtain a list of - * devices currently connected to the system. This is known as device - * discovery. - * - * Just because you have a reference to a device does not mean it is - * necessarily usable. The device may have been unplugged, you may not have - * permission to operate such device, or another program or driver may be - * using the device. - * - * When you've found a device that you'd like to operate, you must ask - * libusb to open the device using the libusb_open() function. Assuming - * success, libusb then returns you a device handle - * (a \ref libusb_device_handle pointer). All "real" I/O operations then - * operate on the handle rather than the original device pointer. - * - * \section devref Device discovery and reference counting - * - * Device discovery (i.e. calling libusb_get_device_list()) returns a - * freshly-allocated list of devices. The list itself must be freed when - * you are done with it. libusb also needs to know when it is OK to free - * the contents of the list - the devices themselves. - * - * To handle these issues, libusb provides you with two separate items: - * - A function to free the list itself - * - A reference counting system for the devices inside - * - * New devices presented by the libusb_get_device_list() function all have a - * reference count of 1. You can increase and decrease reference count using - * libusb_ref_device() and libusb_unref_device(). A device is destroyed when - * its reference count reaches 0. - * - * With the above information in mind, the process of opening a device can - * be viewed as follows: - * -# Discover devices using libusb_get_device_list(). - * -# Choose the device that you want to operate, and call libusb_open(). - * -# Unref all devices in the discovered device list. - * -# Free the discovered device list. - * - * The order is important - you must not unreference the device before - * attempting to open it, because unreferencing it may destroy the device. - * - * For convenience, the libusb_free_device_list() function includes a - * parameter to optionally unreference all the devices in the list before - * freeing the list itself. This combines steps 3 and 4 above. - * - * As an implementation detail, libusb_open() actually adds a reference to - * the device in question. This is because the device remains available - * through the handle via libusb_get_device(). The reference is deleted during - * libusb_close(). - */ - -/** @defgroup libusb_misc Miscellaneous */ - -/* we traverse usbfs without knowing how many devices we are going to find. - * so we create this discovered_devs model which is similar to a linked-list - * which grows when required. it can be freed once discovery has completed, - * eliminating the need for a list node in the libusb_device structure - * itself. */ -#define DISCOVERED_DEVICES_SIZE_STEP 8 - -static struct discovered_devs *discovered_devs_alloc(void) -{ - struct discovered_devs *ret = - malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP)); - - if (ret) { - ret->len = 0; - ret->capacity = DISCOVERED_DEVICES_SIZE_STEP; - } - return ret; -} - -static void discovered_devs_free(struct discovered_devs *discdevs) -{ - size_t i; - - for (i = 0; i < discdevs->len; i++) - libusb_unref_device(discdevs->devices[i]); - - free(discdevs); -} - -/* append a device to the discovered devices collection. may realloc itself, - * returning new discdevs. returns NULL on realloc failure. */ -struct discovered_devs *discovered_devs_append( - struct discovered_devs *discdevs, struct libusb_device *dev) -{ - size_t len = discdevs->len; - size_t capacity; - struct discovered_devs *new_discdevs; - - /* if there is space, just append the device */ - if (len < discdevs->capacity) { - discdevs->devices[len] = libusb_ref_device(dev); - discdevs->len++; - return discdevs; - } - - /* exceeded capacity, need to grow */ - usbi_dbg("need to increase capacity"); - capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP; - /* can't use usbi_reallocf here because in failure cases it would - * free the existing discdevs without unreferencing its devices. */ - new_discdevs = realloc(discdevs, - sizeof(*discdevs) + (sizeof(void *) * capacity)); - if (!new_discdevs) { - discovered_devs_free(discdevs); - return NULL; - } - - discdevs = new_discdevs; - discdevs->capacity = capacity; - discdevs->devices[len] = libusb_ref_device(dev); - discdevs->len++; - - return discdevs; -} - -/* Allocate a new device with a specific session ID. The returned device has - * a reference count of 1. */ -struct libusb_device *usbi_alloc_device(struct libusb_context *ctx, - unsigned long session_id) -{ - size_t priv_size = usbi_backend->device_priv_size; - struct libusb_device *dev = calloc(1, sizeof(*dev) + priv_size); - int r; - - if (!dev) - return NULL; - - r = usbi_mutex_init(&dev->lock); - if (r) { - free(dev); - return NULL; - } - - dev->ctx = ctx; - dev->refcnt = 1; - dev->session_data = session_id; - dev->speed = LIBUSB_SPEED_UNKNOWN; - - if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) { - usbi_connect_device (dev); - } - - return dev; -} - -void usbi_connect_device(struct libusb_device *dev) -{ - struct libusb_context *ctx = DEVICE_CTX(dev); - - dev->attached = 1; - - usbi_mutex_lock(&dev->ctx->usb_devs_lock); - list_add(&dev->list, &dev->ctx->usb_devs); - usbi_mutex_unlock(&dev->ctx->usb_devs_lock); - - /* Signal that an event has occurred for this device if we support hotplug AND - * the hotplug message list is ready. This prevents an event from getting raised - * during initial enumeration. */ - if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG) && dev->ctx->hotplug_msgs.next) { - usbi_hotplug_notification(ctx, dev, LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED); - } -} - -void usbi_disconnect_device(struct libusb_device *dev) -{ - struct libusb_context *ctx = DEVICE_CTX(dev); - - usbi_mutex_lock(&dev->lock); - dev->attached = 0; - usbi_mutex_unlock(&dev->lock); - - usbi_mutex_lock(&ctx->usb_devs_lock); - list_del(&dev->list); - usbi_mutex_unlock(&ctx->usb_devs_lock); - - /* Signal that an event has occurred for this device if we support hotplug AND - * the hotplug message list is ready. This prevents an event from getting raised - * during initial enumeration. libusb_handle_events will take care of dereferencing - * the device. */ - if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG) && dev->ctx->hotplug_msgs.next) { - usbi_hotplug_notification(ctx, dev, LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT); - } -} - -/* Perform some final sanity checks on a newly discovered device. If this - * function fails (negative return code), the device should not be added - * to the discovered device list. */ -int usbi_sanitize_device(struct libusb_device *dev) -{ - int r; - uint8_t num_configurations; - - r = usbi_device_cache_descriptor(dev); - if (r < 0) - return r; - - num_configurations = dev->device_descriptor.bNumConfigurations; - if (num_configurations > USB_MAXCONFIG) { - usbi_err(DEVICE_CTX(dev), "too many configurations"); - return LIBUSB_ERROR_IO; - } else if (0 == num_configurations) - usbi_dbg("zero configurations, maybe an unauthorized device"); - - dev->num_configurations = num_configurations; - return 0; -} - -/* Examine libusb's internal list of known devices, looking for one with - * a specific session ID. Returns the matching device if it was found, and - * NULL otherwise. */ -struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx, - unsigned long session_id) -{ - struct libusb_device *dev; - struct libusb_device *ret = NULL; - - usbi_mutex_lock(&ctx->usb_devs_lock); - list_for_each_entry(dev, &ctx->usb_devs, list, struct libusb_device) - if (dev->session_data == session_id) { - ret = libusb_ref_device(dev); - break; - } - usbi_mutex_unlock(&ctx->usb_devs_lock); - - return ret; -} - -/** @ingroup libusb_dev - * Returns a list of USB devices currently attached to the system. This is - * your entry point into finding a USB device to operate. - * - * You are expected to unreference all the devices when you are done with - * them, and then free the list with libusb_free_device_list(). Note that - * libusb_free_device_list() can unref all the devices for you. Be careful - * not to unreference a device you are about to open until after you have - * opened it. - * - * This return value of this function indicates the number of devices in - * the resultant list. The list is actually one element larger, as it is - * NULL-terminated. - * - * \param ctx the context to operate on, or NULL for the default context - * \param list output location for a list of devices. Must be later freed with - * libusb_free_device_list(). - * \returns the number of devices in the outputted list, or any - * \ref libusb_error according to errors encountered by the backend. - */ -ssize_t API_EXPORTED libusb_get_device_list(libusb_context *ctx, - libusb_device ***list) -{ - struct discovered_devs *discdevs = discovered_devs_alloc(); - struct libusb_device **ret; - int r = 0; - ssize_t i, len; - USBI_GET_CONTEXT(ctx); - usbi_dbg(""); - - if (!discdevs) - return LIBUSB_ERROR_NO_MEM; - - if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) { - /* backend provides hotplug support */ - struct libusb_device *dev; - - if (usbi_backend->hotplug_poll) - usbi_backend->hotplug_poll(); - - usbi_mutex_lock(&ctx->usb_devs_lock); - list_for_each_entry(dev, &ctx->usb_devs, list, struct libusb_device) { - discdevs = discovered_devs_append(discdevs, dev); - - if (!discdevs) { - r = LIBUSB_ERROR_NO_MEM; - break; - } - } - usbi_mutex_unlock(&ctx->usb_devs_lock); - } else { - /* backend does not provide hotplug support */ - r = usbi_backend->get_device_list(ctx, &discdevs); - } - - if (r < 0) { - len = r; - goto out; - } - - /* convert discovered_devs into a list */ - len = discdevs->len; - ret = calloc(len + 1, sizeof(struct libusb_device *)); - if (!ret) { - len = LIBUSB_ERROR_NO_MEM; - goto out; - } - - ret[len] = NULL; - for (i = 0; i < len; i++) { - struct libusb_device *dev = discdevs->devices[i]; - ret[i] = libusb_ref_device(dev); - } - *list = ret; - -out: - if (discdevs) - discovered_devs_free(discdevs); - return len; -} - -/** \ingroup libusb_dev - * Frees a list of devices previously discovered using - * libusb_get_device_list(). If the unref_devices parameter is set, the - * reference count of each device in the list is decremented by 1. - * \param list the list to free - * \param unref_devices whether to unref the devices in the list - */ -void API_EXPORTED libusb_free_device_list(libusb_device **list, - int unref_devices) -{ - if (!list) - return; - - if (unref_devices) { - int i = 0; - struct libusb_device *dev; - - while ((dev = list[i++]) != NULL) - libusb_unref_device(dev); - } - free(list); -} - -/** \ingroup libusb_dev - * Get the number of the bus that a device is connected to. - * \param dev a device - * \returns the bus number - */ -uint8_t API_EXPORTED libusb_get_bus_number(libusb_device *dev) -{ - return dev->bus_number; -} - -/** \ingroup libusb_dev - * Get the number of the port that a device is connected to. - * Unless the OS does something funky, or you are hot-plugging USB extension cards, - * the port number returned by this call is usually guaranteed to be uniquely tied - * to a physical port, meaning that different devices plugged on the same physical - * port should return the same port number. - * - * But outside of this, there is no guarantee that the port number returned by this - * call will remain the same, or even match the order in which ports have been - * numbered by the HUB/HCD manufacturer. - * - * \param dev a device - * \returns the port number (0 if not available) - */ -uint8_t API_EXPORTED libusb_get_port_number(libusb_device *dev) -{ - return dev->port_number; -} - -/** \ingroup libusb_dev - * Get the list of all port numbers from root for the specified device - * - * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102 - * \param dev a device - * \param port_numbers the array that should contain the port numbers - * \param port_numbers_len the maximum length of the array. As per the USB 3.0 - * specs, the current maximum limit for the depth is 7. - * \returns the number of elements filled - * \returns LIBUSB_ERROR_OVERFLOW if the array is too small - */ -int API_EXPORTED libusb_get_port_numbers(libusb_device *dev, - uint8_t* port_numbers, int port_numbers_len) -{ - int i = port_numbers_len; - struct libusb_context *ctx = DEVICE_CTX(dev); - - if (port_numbers_len <= 0) - return LIBUSB_ERROR_INVALID_PARAM; - - // HCDs can be listed as devices with port #0 - while((dev) && (dev->port_number != 0)) { - if (--i < 0) { - usbi_warn(ctx, "port numbers array is too small"); - return LIBUSB_ERROR_OVERFLOW; - } - port_numbers[i] = dev->port_number; - dev = dev->parent_dev; - } - if (i < port_numbers_len) - memmove(port_numbers, &port_numbers[i], port_numbers_len - i); - return port_numbers_len - i; -} - -/** \ingroup libusb_dev - * Deprecated please use libusb_get_port_numbers instead. - */ -int API_EXPORTED libusb_get_port_path(libusb_context *ctx, libusb_device *dev, - uint8_t* port_numbers, uint8_t port_numbers_len) -{ - UNUSED(ctx); - - return libusb_get_port_numbers(dev, port_numbers, port_numbers_len); -} - -/** \ingroup libusb_dev - * Get the the parent from the specified device. - * \param dev a device - * \returns the device parent or NULL if not available - * You should issue a \ref libusb_get_device_list() before calling this - * function and make sure that you only access the parent before issuing - * \ref libusb_free_device_list(). The reason is that libusb currently does - * not maintain a permanent list of device instances, and therefore can - * only guarantee that parents are fully instantiated within a - * libusb_get_device_list() - libusb_free_device_list() block. - */ -DEFAULT_VISIBILITY -libusb_device * LIBUSB_CALL libusb_get_parent(libusb_device *dev) -{ - return dev->parent_dev; -} - -/** \ingroup libusb_dev - * Get the address of the device on the bus it is connected to. - * \param dev a device - * \returns the device address - */ -uint8_t API_EXPORTED libusb_get_device_address(libusb_device *dev) -{ - return dev->device_address; -} - -/** \ingroup libusb_dev - * Get the negotiated connection speed for a device. - * \param dev a device - * \returns a \ref libusb_speed code, where LIBUSB_SPEED_UNKNOWN means that - * the OS doesn't know or doesn't support returning the negotiated speed. - */ -int API_EXPORTED libusb_get_device_speed(libusb_device *dev) -{ - return dev->speed; -} - -static const struct libusb_endpoint_descriptor *find_endpoint( - struct libusb_config_descriptor *config, unsigned char endpoint) -{ - int iface_idx; - for (iface_idx = 0; iface_idx < config->bNumInterfaces; iface_idx++) { - const struct libusb_interface *iface = &config->interface[iface_idx]; - int altsetting_idx; - - for (altsetting_idx = 0; altsetting_idx < iface->num_altsetting; - altsetting_idx++) { - const struct libusb_interface_descriptor *altsetting - = &iface->altsetting[altsetting_idx]; - int ep_idx; - - for (ep_idx = 0; ep_idx < altsetting->bNumEndpoints; ep_idx++) { - const struct libusb_endpoint_descriptor *ep = - &altsetting->endpoint[ep_idx]; - if (ep->bEndpointAddress == endpoint) - return ep; - } - } - } - return NULL; -} - -/** \ingroup libusb_dev - * Convenience function to retrieve the wMaxPacketSize value for a particular - * endpoint in the active device configuration. - * - * This function was originally intended to be of assistance when setting up - * isochronous transfers, but a design mistake resulted in this function - * instead. It simply returns the wMaxPacketSize value without considering - * its contents. If you're dealing with isochronous transfers, you probably - * want libusb_get_max_iso_packet_size() instead. - * - * \param dev a device - * \param endpoint address of the endpoint in question - * \returns the wMaxPacketSize value - * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist - * \returns LIBUSB_ERROR_OTHER on other failure - */ -int API_EXPORTED libusb_get_max_packet_size(libusb_device *dev, - unsigned char endpoint) -{ - struct libusb_config_descriptor *config; - const struct libusb_endpoint_descriptor *ep; - int r; - - r = libusb_get_active_config_descriptor(dev, &config); - if (r < 0) { - usbi_err(DEVICE_CTX(dev), - "could not retrieve active config descriptor"); - return LIBUSB_ERROR_OTHER; - } - - ep = find_endpoint(config, endpoint); - if (!ep) { - r = LIBUSB_ERROR_NOT_FOUND; - goto out; - } - - r = ep->wMaxPacketSize; - -out: - libusb_free_config_descriptor(config); - return r; -} - -/** \ingroup libusb_dev - * Calculate the maximum packet size which a specific endpoint is capable is - * sending or receiving in the duration of 1 microframe - * - * Only the active configuration is examined. The calculation is based on the - * wMaxPacketSize field in the endpoint descriptor as described in section - * 9.6.6 in the USB 2.0 specifications. - * - * If acting on an isochronous or interrupt endpoint, this function will - * multiply the value found in bits 0:10 by the number of transactions per - * microframe (determined by bits 11:12). Otherwise, this function just - * returns the numeric value found in bits 0:10. - * - * This function is useful for setting up isochronous transfers, for example - * you might pass the return value from this function to - * libusb_set_iso_packet_lengths() in order to set the length field of every - * isochronous packet in a transfer. - * - * Since v1.0.3. - * - * \param dev a device - * \param endpoint address of the endpoint in question - * \returns the maximum packet size which can be sent/received on this endpoint - * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist - * \returns LIBUSB_ERROR_OTHER on other failure - */ -int API_EXPORTED libusb_get_max_iso_packet_size(libusb_device *dev, - unsigned char endpoint) -{ - struct libusb_config_descriptor *config; - const struct libusb_endpoint_descriptor *ep; - enum libusb_transfer_type ep_type; - uint16_t val; - int r; - - r = libusb_get_active_config_descriptor(dev, &config); - if (r < 0) { - usbi_err(DEVICE_CTX(dev), - "could not retrieve active config descriptor"); - return LIBUSB_ERROR_OTHER; - } - - ep = find_endpoint(config, endpoint); - if (!ep) { - r = LIBUSB_ERROR_NOT_FOUND; - goto out; - } - - val = ep->wMaxPacketSize; - ep_type = (enum libusb_transfer_type) (ep->bmAttributes & 0x3); - - r = val & 0x07ff; - if (ep_type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS - || ep_type == LIBUSB_TRANSFER_TYPE_INTERRUPT) - r *= (1 + ((val >> 11) & 3)); - -out: - libusb_free_config_descriptor(config); - return r; -} - -/** \ingroup libusb_dev - * Increment the reference count of a device. - * \param dev the device to reference - * \returns the same device - */ -DEFAULT_VISIBILITY -libusb_device * LIBUSB_CALL libusb_ref_device(libusb_device *dev) -{ - usbi_mutex_lock(&dev->lock); - dev->refcnt++; - usbi_mutex_unlock(&dev->lock); - return dev; -} - -/** \ingroup libusb_dev - * Decrement the reference count of a device. If the decrement operation - * causes the reference count to reach zero, the device shall be destroyed. - * \param dev the device to unreference - */ -void API_EXPORTED libusb_unref_device(libusb_device *dev) -{ - int refcnt; - - if (!dev) - return; - - usbi_mutex_lock(&dev->lock); - refcnt = --dev->refcnt; - usbi_mutex_unlock(&dev->lock); - - if (refcnt == 0) { - usbi_dbg("destroy device %d.%d", dev->bus_number, dev->device_address); - - libusb_unref_device(dev->parent_dev); - - if (usbi_backend->destroy_device) - usbi_backend->destroy_device(dev); - - if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) { - /* backend does not support hotplug */ - usbi_disconnect_device(dev); - } - - usbi_mutex_destroy(&dev->lock); - free(dev); - } -} - -/* - * Signal the event pipe so that the event handling thread will be - * interrupted to process an internal event. - */ -int usbi_signal_event(struct libusb_context *ctx) -{ - unsigned char dummy = 1; - ssize_t r; - - /* write some data on event pipe to interrupt event handlers */ - r = usbi_write(ctx->event_pipe[1], &dummy, sizeof(dummy)); - if (r != sizeof(dummy)) { - usbi_warn(ctx, "internal signalling write failed"); - return LIBUSB_ERROR_IO; - } - - return 0; -} - -/* - * Clear the event pipe so that the event handling will no longer be - * interrupted. - */ -int usbi_clear_event(struct libusb_context *ctx) -{ - unsigned char dummy; - ssize_t r; - - /* read some data on event pipe to clear it */ - r = usbi_read(ctx->event_pipe[0], &dummy, sizeof(dummy)); - if (r != sizeof(dummy)) { - usbi_warn(ctx, "internal signalling read failed"); - return LIBUSB_ERROR_IO; - } - - return 0; -} - -/** \ingroup libusb_dev - * Open a device and obtain a device handle. A handle allows you to perform - * I/O on the device in question. - * - * Internally, this function adds a reference to the device and makes it - * available to you through libusb_get_device(). This reference is removed - * during libusb_close(). - * - * This is a non-blocking function; no requests are sent over the bus. - * - * \param dev the device to open - * \param dev_handle output location for the returned device handle pointer. Only - * populated when the return code is 0. - * \returns 0 on success - * \returns LIBUSB_ERROR_NO_MEM on memory allocation failure - * \returns LIBUSB_ERROR_ACCESS if the user has insufficient permissions - * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected - * \returns another LIBUSB_ERROR code on other failure - */ -int API_EXPORTED libusb_open(libusb_device *dev, - libusb_device_handle **dev_handle) -{ - struct libusb_context *ctx = DEVICE_CTX(dev); - struct libusb_device_handle *_dev_handle; - size_t priv_size = usbi_backend->device_handle_priv_size; - int r; - usbi_dbg("open %d.%d", dev->bus_number, dev->device_address); - - if (!dev->attached) { - return LIBUSB_ERROR_NO_DEVICE; - } - - _dev_handle = malloc(sizeof(*_dev_handle) + priv_size); - if (!_dev_handle) - return LIBUSB_ERROR_NO_MEM; - - r = usbi_mutex_init(&_dev_handle->lock); - if (r) { - free(_dev_handle); - return LIBUSB_ERROR_OTHER; - } - - _dev_handle->dev = libusb_ref_device(dev); - _dev_handle->auto_detach_kernel_driver = 0; - _dev_handle->claimed_interfaces = 0; - memset(&_dev_handle->os_priv, 0, priv_size); - - r = usbi_backend->open(_dev_handle); - if (r < 0) { - usbi_dbg("open %d.%d returns %d", dev->bus_number, dev->device_address, r); - libusb_unref_device(dev); - usbi_mutex_destroy(&_dev_handle->lock); - free(_dev_handle); - return r; - } - - usbi_mutex_lock(&ctx->open_devs_lock); - list_add(&_dev_handle->list, &ctx->open_devs); - usbi_mutex_unlock(&ctx->open_devs_lock); - *dev_handle = _dev_handle; - - return 0; -} - -/** \ingroup libusb_dev - * Convenience function for finding a device with a particular - * idVendor/idProduct combination. This function is intended - * for those scenarios where you are using libusb to knock up a quick test - * application - it allows you to avoid calling libusb_get_device_list() and - * worrying about traversing/freeing the list. - * - * This function has limitations and is hence not intended for use in real - * applications: if multiple devices have the same IDs it will only - * give you the first one, etc. - * - * \param ctx the context to operate on, or NULL for the default context - * \param vendor_id the idVendor value to search for - * \param product_id the idProduct value to search for - * \returns a device handle for the first found device, or NULL on error - * or if the device could not be found. */ -DEFAULT_VISIBILITY -libusb_device_handle * LIBUSB_CALL libusb_open_device_with_vid_pid( - libusb_context *ctx, uint16_t vendor_id, uint16_t product_id) -{ - struct libusb_device **devs; - struct libusb_device *found = NULL; - struct libusb_device *dev; - struct libusb_device_handle *dev_handle = NULL; - size_t i = 0; - int r; - - if (libusb_get_device_list(ctx, &devs) < 0) - return NULL; - - while ((dev = devs[i++]) != NULL) { - struct libusb_device_descriptor desc; - r = libusb_get_device_descriptor(dev, &desc); - if (r < 0) - goto out; - if (desc.idVendor == vendor_id && desc.idProduct == product_id) { - found = dev; - break; - } - } - - if (found) { - r = libusb_open(found, &dev_handle); - if (r < 0) - dev_handle = NULL; - } - -out: - libusb_free_device_list(devs, 1); - return dev_handle; -} - -static void do_close(struct libusb_context *ctx, - struct libusb_device_handle *dev_handle) -{ - struct usbi_transfer *itransfer; - struct usbi_transfer *tmp; - - /* remove any transfers in flight that are for this device */ - usbi_mutex_lock(&ctx->flying_transfers_lock); - - /* safe iteration because transfers may be being deleted */ - list_for_each_entry_safe(itransfer, tmp, &ctx->flying_transfers, list, struct usbi_transfer) { - struct libusb_transfer *transfer = - USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - - if (transfer->dev_handle != dev_handle) - continue; - - usbi_mutex_lock(&itransfer->lock); - if (!(itransfer->state_flags & USBI_TRANSFER_DEVICE_DISAPPEARED)) { - usbi_err(ctx, "Device handle closed while transfer was still being processed, but the device is still connected as far as we know"); - - if (itransfer->state_flags & USBI_TRANSFER_CANCELLING) - usbi_warn(ctx, "A cancellation for an in-flight transfer hasn't completed but closing the device handle"); - else - usbi_err(ctx, "A cancellation hasn't even been scheduled on the transfer for which the device is closing"); - } - usbi_mutex_unlock(&itransfer->lock); - - /* remove from the list of in-flight transfers and make sure - * we don't accidentally use the device handle in the future - * (or that such accesses will be easily caught and identified as a crash) - */ - list_del(&itransfer->list); - transfer->dev_handle = NULL; - - /* it is up to the user to free up the actual transfer struct. this is - * just making sure that we don't attempt to process the transfer after - * the device handle is invalid - */ - usbi_dbg("Removed transfer %p from the in-flight list because device handle %p closed", - transfer, dev_handle); - } - usbi_mutex_unlock(&ctx->flying_transfers_lock); - - usbi_mutex_lock(&ctx->open_devs_lock); - list_del(&dev_handle->list); - usbi_mutex_unlock(&ctx->open_devs_lock); - - usbi_backend->close(dev_handle); - libusb_unref_device(dev_handle->dev); - usbi_mutex_destroy(&dev_handle->lock); - free(dev_handle); -} - -/** \ingroup libusb_dev - * Close a device handle. Should be called on all open handles before your - * application exits. - * - * Internally, this function destroys the reference that was added by - * libusb_open() on the given device. - * - * This is a non-blocking function; no requests are sent over the bus. - * - * \param dev_handle the device handle to close - */ -void API_EXPORTED libusb_close(libusb_device_handle *dev_handle) -{ - struct libusb_context *ctx; - int handling_events; - int pending_events; - - if (!dev_handle) - return; - usbi_dbg(""); - - ctx = HANDLE_CTX(dev_handle); - handling_events = usbi_handling_events(ctx); - - /* Similarly to libusb_open(), we want to interrupt all event handlers - * at this point. More importantly, we want to perform the actual close of - * the device while holding the event handling lock (preventing any other - * thread from doing event handling) because we will be removing a file - * descriptor from the polling loop. If this is being called by the current - * event handler, we can bypass the interruption code because we already - * hold the event handling lock. */ - - if (!handling_events) { - /* Record that we are closing a device. - * Only signal an event if there are no prior pending events. */ - usbi_mutex_lock(&ctx->event_data_lock); - pending_events = usbi_pending_events(ctx); - ctx->device_close++; - if (!pending_events) - usbi_signal_event(ctx); - usbi_mutex_unlock(&ctx->event_data_lock); - - /* take event handling lock */ - libusb_lock_events(ctx); - } - - /* Close the device */ - do_close(ctx, dev_handle); - - if (!handling_events) { - /* We're done with closing this device. - * Clear the event pipe if there are no further pending events. */ - usbi_mutex_lock(&ctx->event_data_lock); - ctx->device_close--; - pending_events = usbi_pending_events(ctx); - if (!pending_events) - usbi_clear_event(ctx); - usbi_mutex_unlock(&ctx->event_data_lock); - - /* Release event handling lock and wake up event waiters */ - libusb_unlock_events(ctx); - } -} - -/** \ingroup libusb_dev - * Get the underlying device for a device handle. This function does not modify - * the reference count of the returned device, so do not feel compelled to - * unreference it when you are done. - * \param dev_handle a device handle - * \returns the underlying device - */ -DEFAULT_VISIBILITY -libusb_device * LIBUSB_CALL libusb_get_device(libusb_device_handle *dev_handle) -{ - return dev_handle->dev; -} - -/** \ingroup libusb_dev - * Determine the bConfigurationValue of the currently active configuration. - * - * You could formulate your own control request to obtain this information, - * but this function has the advantage that it may be able to retrieve the - * information from operating system caches (no I/O involved). - * - * If the OS does not cache this information, then this function will block - * while a control transfer is submitted to retrieve the information. - * - * This function will return a value of 0 in the config output - * parameter if the device is in unconfigured state. - * - * \param dev_handle a device handle - * \param config output location for the bConfigurationValue of the active - * configuration (only valid for return code 0) - * \returns 0 on success - * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected - * \returns another LIBUSB_ERROR code on other failure - */ -int API_EXPORTED libusb_get_configuration(libusb_device_handle *dev_handle, - int *config) -{ - int r = LIBUSB_ERROR_NOT_SUPPORTED; - - usbi_dbg(""); - if (usbi_backend->get_configuration) - r = usbi_backend->get_configuration(dev_handle, config); - - if (r == LIBUSB_ERROR_NOT_SUPPORTED) { - uint8_t tmp = 0; - usbi_dbg("falling back to control message"); - r = libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_IN, - LIBUSB_REQUEST_GET_CONFIGURATION, 0, 0, &tmp, 1, 1000); - if (r == 0) { - usbi_err(HANDLE_CTX(dev_handle), "zero bytes returned in ctrl transfer?"); - r = LIBUSB_ERROR_IO; - } else if (r == 1) { - r = 0; - *config = tmp; - } else { - usbi_dbg("control failed, error %d", r); - } - } - - if (r == 0) - usbi_dbg("active config %d", *config); - - return r; -} - -/** \ingroup libusb_dev - * Set the active configuration for a device. - * - * The operating system may or may not have already set an active - * configuration on the device. It is up to your application to ensure the - * correct configuration is selected before you attempt to claim interfaces - * and perform other operations. - * - * If you call this function on a device already configured with the selected - * configuration, then this function will act as a lightweight device reset: - * it will issue a SET_CONFIGURATION request using the current configuration, - * causing most USB-related device state to be reset (altsetting reset to zero, - * endpoint halts cleared, toggles reset). - * - * You cannot change/reset configuration if your application has claimed - * interfaces. It is advised to set the desired configuration before claiming - * interfaces. - * - * Alternatively you can call libusb_release_interface() first. Note if you - * do things this way you must ensure that auto_detach_kernel_driver for - * dev is 0, otherwise the kernel driver will be re-attached when you - * release the interface(s). - * - * You cannot change/reset configuration if other applications or drivers have - * claimed interfaces. - * - * A configuration value of -1 will put the device in unconfigured state. - * The USB specifications state that a configuration value of 0 does this, - * however buggy devices exist which actually have a configuration 0. - * - * You should always use this function rather than formulating your own - * SET_CONFIGURATION control request. This is because the underlying operating - * system needs to know when such changes happen. - * - * This is a blocking function. - * - * \param dev_handle a device handle - * \param configuration the bConfigurationValue of the configuration you - * wish to activate, or -1 if you wish to put the device in an unconfigured - * state - * \returns 0 on success - * \returns LIBUSB_ERROR_NOT_FOUND if the requested configuration does not exist - * \returns LIBUSB_ERROR_BUSY if interfaces are currently claimed - * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected - * \returns another LIBUSB_ERROR code on other failure - * \see libusb_set_auto_detach_kernel_driver() - */ -int API_EXPORTED libusb_set_configuration(libusb_device_handle *dev_handle, - int configuration) -{ - usbi_dbg("configuration %d", configuration); - return usbi_backend->set_configuration(dev_handle, configuration); -} - -/** \ingroup libusb_dev - * Claim an interface on a given device handle. You must claim the interface - * you wish to use before you can perform I/O on any of its endpoints. - * - * It is legal to attempt to claim an already-claimed interface, in which - * case libusb just returns 0 without doing anything. - * - * If auto_detach_kernel_driver is set to 1 for dev, the kernel driver - * will be detached if necessary, on failure the detach error is returned. - * - * Claiming of interfaces is a purely logical operation; it does not cause - * any requests to be sent over the bus. Interface claiming is used to - * instruct the underlying operating system that your application wishes - * to take ownership of the interface. - * - * This is a non-blocking function. - * - * \param dev_handle a device handle - * \param interface_number the bInterfaceNumber of the interface you - * wish to claim - * \returns 0 on success - * \returns LIBUSB_ERROR_NOT_FOUND if the requested interface does not exist - * \returns LIBUSB_ERROR_BUSY if another program or driver has claimed the - * interface - * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected - * \returns a LIBUSB_ERROR code on other failure - * \see libusb_set_auto_detach_kernel_driver() - */ -int API_EXPORTED libusb_claim_interface(libusb_device_handle *dev_handle, - int interface_number) -{ - int r = 0; - - usbi_dbg("interface %d", interface_number); - if (interface_number >= USB_MAXINTERFACES) - return LIBUSB_ERROR_INVALID_PARAM; - - if (!dev_handle->dev->attached) - return LIBUSB_ERROR_NO_DEVICE; - - usbi_mutex_lock(&dev_handle->lock); - if (dev_handle->claimed_interfaces & (1 << interface_number)) - goto out; - - r = usbi_backend->claim_interface(dev_handle, interface_number); - if (r == 0) - dev_handle->claimed_interfaces |= 1 << interface_number; - -out: - usbi_mutex_unlock(&dev_handle->lock); - return r; -} - -/** \ingroup libusb_dev - * Release an interface previously claimed with libusb_claim_interface(). You - * should release all claimed interfaces before closing a device handle. - * - * This is a blocking function. A SET_INTERFACE control request will be sent - * to the device, resetting interface state to the first alternate setting. - * - * If auto_detach_kernel_driver is set to 1 for dev, the kernel - * driver will be re-attached after releasing the interface. - * - * \param dev_handle a device handle - * \param interface_number the bInterfaceNumber of the - * previously-claimed interface - * \returns 0 on success - * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed - * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected - * \returns another LIBUSB_ERROR code on other failure - * \see libusb_set_auto_detach_kernel_driver() - */ -int API_EXPORTED libusb_release_interface(libusb_device_handle *dev_handle, - int interface_number) -{ - int r; - - usbi_dbg("interface %d", interface_number); - if (interface_number >= USB_MAXINTERFACES) - return LIBUSB_ERROR_INVALID_PARAM; - - usbi_mutex_lock(&dev_handle->lock); - if (!(dev_handle->claimed_interfaces & (1 << interface_number))) { - r = LIBUSB_ERROR_NOT_FOUND; - goto out; - } - - r = usbi_backend->release_interface(dev_handle, interface_number); - if (r == 0) - dev_handle->claimed_interfaces &= ~(1 << interface_number); - -out: - usbi_mutex_unlock(&dev_handle->lock); - return r; -} - -/** \ingroup libusb_dev - * Activate an alternate setting for an interface. The interface must have - * been previously claimed with libusb_claim_interface(). - * - * You should always use this function rather than formulating your own - * SET_INTERFACE control request. This is because the underlying operating - * system needs to know when such changes happen. - * - * This is a blocking function. - * - * \param dev_handle a device handle - * \param interface_number the bInterfaceNumber of the - * previously-claimed interface - * \param alternate_setting the bAlternateSetting of the alternate - * setting to activate - * \returns 0 on success - * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed, or the - * requested alternate setting does not exist - * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected - * \returns another LIBUSB_ERROR code on other failure - */ -int API_EXPORTED libusb_set_interface_alt_setting(libusb_device_handle *dev_handle, - int interface_number, int alternate_setting) -{ - usbi_dbg("interface %d altsetting %d", - interface_number, alternate_setting); - if (interface_number >= USB_MAXINTERFACES) - return LIBUSB_ERROR_INVALID_PARAM; - - usbi_mutex_lock(&dev_handle->lock); - if (!dev_handle->dev->attached) { - usbi_mutex_unlock(&dev_handle->lock); - return LIBUSB_ERROR_NO_DEVICE; - } - - if (!(dev_handle->claimed_interfaces & (1 << interface_number))) { - usbi_mutex_unlock(&dev_handle->lock); - return LIBUSB_ERROR_NOT_FOUND; - } - usbi_mutex_unlock(&dev_handle->lock); - - return usbi_backend->set_interface_altsetting(dev_handle, interface_number, - alternate_setting); -} - -/** \ingroup libusb_dev - * Clear the halt/stall condition for an endpoint. Endpoints with halt status - * are unable to receive or transmit data until the halt condition is stalled. - * - * You should cancel all pending transfers before attempting to clear the halt - * condition. - * - * This is a blocking function. - * - * \param dev_handle a device handle - * \param endpoint the endpoint to clear halt status - * \returns 0 on success - * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist - * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected - * \returns another LIBUSB_ERROR code on other failure - */ -int API_EXPORTED libusb_clear_halt(libusb_device_handle *dev_handle, - unsigned char endpoint) -{ - usbi_dbg("endpoint %x", endpoint); - if (!dev_handle->dev->attached) - return LIBUSB_ERROR_NO_DEVICE; - - return usbi_backend->clear_halt(dev_handle, endpoint); -} - -/** \ingroup libusb_dev - * Perform a USB port reset to reinitialize a device. The system will attempt - * to restore the previous configuration and alternate settings after the - * reset has completed. - * - * If the reset fails, the descriptors change, or the previous state cannot be - * restored, the device will appear to be disconnected and reconnected. This - * means that the device handle is no longer valid (you should close it) and - * rediscover the device. A return code of LIBUSB_ERROR_NOT_FOUND indicates - * when this is the case. - * - * This is a blocking function which usually incurs a noticeable delay. - * - * \param dev_handle a handle of the device to reset - * \returns 0 on success - * \returns LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the - * device has been disconnected - * \returns another LIBUSB_ERROR code on other failure - */ -int API_EXPORTED libusb_reset_device(libusb_device_handle *dev_handle) -{ - usbi_dbg(""); - if (!dev_handle->dev->attached) - return LIBUSB_ERROR_NO_DEVICE; - - return usbi_backend->reset_device(dev_handle); -} - -/** \ingroup libusb_asyncio - * Allocate up to num_streams usb bulk streams on the specified endpoints. This - * function takes an array of endpoints rather then a single endpoint because - * some protocols require that endpoints are setup with similar stream ids. - * All endpoints passed in must belong to the same interface. - * - * Note this function may return less streams then requested. Also note that the - * same number of streams are allocated for each endpoint in the endpoint array. - * - * Stream id 0 is reserved, and should not be used to communicate with devices. - * If libusb_alloc_streams() returns with a value of N, you may use stream ids - * 1 to N. - * - * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103 - * - * \param dev_handle a device handle - * \param num_streams number of streams to try to allocate - * \param endpoints array of endpoints to allocate streams on - * \param num_endpoints length of the endpoints array - * \returns number of streams allocated, or a LIBUSB_ERROR code on failure - */ -int API_EXPORTED libusb_alloc_streams(libusb_device_handle *dev_handle, - uint32_t num_streams, unsigned char *endpoints, int num_endpoints) -{ - usbi_dbg("streams %u eps %d", (unsigned) num_streams, num_endpoints); - - if (!dev_handle->dev->attached) - return LIBUSB_ERROR_NO_DEVICE; - - if (usbi_backend->alloc_streams) - return usbi_backend->alloc_streams(dev_handle, num_streams, endpoints, - num_endpoints); - else - return LIBUSB_ERROR_NOT_SUPPORTED; -} - -/** \ingroup libusb_asyncio - * Free usb bulk streams allocated with libusb_alloc_streams(). - * - * Note streams are automatically free-ed when releasing an interface. - * - * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103 - * - * \param dev_handle a device handle - * \param endpoints array of endpoints to free streams on - * \param num_endpoints length of the endpoints array - * \returns LIBUSB_SUCCESS, or a LIBUSB_ERROR code on failure - */ -int API_EXPORTED libusb_free_streams(libusb_device_handle *dev_handle, - unsigned char *endpoints, int num_endpoints) -{ - usbi_dbg("eps %d", num_endpoints); - - if (!dev_handle->dev->attached) - return LIBUSB_ERROR_NO_DEVICE; - - if (usbi_backend->free_streams) - return usbi_backend->free_streams(dev_handle, endpoints, - num_endpoints); - else - return LIBUSB_ERROR_NOT_SUPPORTED; -} - -/** \ingroup libusb_asyncio - * Attempts to allocate a block of persistent DMA memory suitable for transfers - * against the given device. If successful, will return a block of memory - * that is suitable for use as "buffer" in \ref libusb_transfer against this - * device. Using this memory instead of regular memory means that the host - * controller can use DMA directly into the buffer to increase performance, and - * also that transfers can no longer fail due to kernel memory fragmentation. - * - * Note that this means you should not modify this memory (or even data on - * the same cache lines) when a transfer is in progress, although it is legal - * to have several transfers going on within the same memory block. - * - * Will return NULL on failure. Many systems do not support such zerocopy - * and will always return NULL. Memory allocated with this function must be - * freed with \ref libusb_dev_mem_free. Specifically, this means that the - * flag \ref LIBUSB_TRANSFER_FREE_BUFFER cannot be used to free memory allocated - * with this function. - * - * Since version 1.0.21, \ref LIBUSB_API_VERSION >= 0x01000105 - * - * \param dev_handle a device handle - * \param length size of desired data buffer - * \returns a pointer to the newly allocated memory, or NULL on failure - */ -DEFAULT_VISIBILITY -unsigned char * LIBUSB_CALL libusb_dev_mem_alloc(libusb_device_handle *dev_handle, - size_t length) -{ - if (!dev_handle->dev->attached) - return NULL; - - if (usbi_backend->dev_mem_alloc) - return usbi_backend->dev_mem_alloc(dev_handle, length); - else - return NULL; -} - -/** \ingroup libusb_asyncio - * Free device memory allocated with libusb_dev_mem_alloc(). - * - * \param dev_handle a device handle - * \param buffer pointer to the previously allocated memory - * \param length size of previously allocated memory - * \returns LIBUSB_SUCCESS, or a LIBUSB_ERROR code on failure - */ -int API_EXPORTED libusb_dev_mem_free(libusb_device_handle *dev_handle, - unsigned char *buffer, size_t length) -{ - if (usbi_backend->dev_mem_free) - return usbi_backend->dev_mem_free(dev_handle, buffer, length); - else - return LIBUSB_ERROR_NOT_SUPPORTED; -} - -/** \ingroup libusb_dev - * Determine if a kernel driver is active on an interface. If a kernel driver - * is active, you cannot claim the interface, and libusb will be unable to - * perform I/O. - * - * This functionality is not available on Windows. - * - * \param dev_handle a device handle - * \param interface_number the interface to check - * \returns 0 if no kernel driver is active - * \returns 1 if a kernel driver is active - * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected - * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality - * is not available - * \returns another LIBUSB_ERROR code on other failure - * \see libusb_detach_kernel_driver() - */ -int API_EXPORTED libusb_kernel_driver_active(libusb_device_handle *dev_handle, - int interface_number) -{ - usbi_dbg("interface %d", interface_number); - - if (!dev_handle->dev->attached) - return LIBUSB_ERROR_NO_DEVICE; - - if (usbi_backend->kernel_driver_active) - return usbi_backend->kernel_driver_active(dev_handle, interface_number); - else - return LIBUSB_ERROR_NOT_SUPPORTED; -} - -/** \ingroup libusb_dev - * Detach a kernel driver from an interface. If successful, you will then be - * able to claim the interface and perform I/O. - * - * This functionality is not available on Darwin or Windows. - * - * Note that libusb itself also talks to the device through a special kernel - * driver, if this driver is already attached to the device, this call will - * not detach it and return LIBUSB_ERROR_NOT_FOUND. - * - * \param dev_handle a device handle - * \param interface_number the interface to detach the driver from - * \returns 0 on success - * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active - * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist - * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected - * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality - * is not available - * \returns another LIBUSB_ERROR code on other failure - * \see libusb_kernel_driver_active() - */ -int API_EXPORTED libusb_detach_kernel_driver(libusb_device_handle *dev_handle, - int interface_number) -{ - usbi_dbg("interface %d", interface_number); - - if (!dev_handle->dev->attached) - return LIBUSB_ERROR_NO_DEVICE; - - if (usbi_backend->detach_kernel_driver) - return usbi_backend->detach_kernel_driver(dev_handle, interface_number); - else - return LIBUSB_ERROR_NOT_SUPPORTED; -} - -/** \ingroup libusb_dev - * Re-attach an interface's kernel driver, which was previously detached - * using libusb_detach_kernel_driver(). This call is only effective on - * Linux and returns LIBUSB_ERROR_NOT_SUPPORTED on all other platforms. - * - * This functionality is not available on Darwin or Windows. - * - * \param dev_handle a device handle - * \param interface_number the interface to attach the driver from - * \returns 0 on success - * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active - * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist - * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected - * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality - * is not available - * \returns LIBUSB_ERROR_BUSY if the driver cannot be attached because the - * interface is claimed by a program or driver - * \returns another LIBUSB_ERROR code on other failure - * \see libusb_kernel_driver_active() - */ -int API_EXPORTED libusb_attach_kernel_driver(libusb_device_handle *dev_handle, - int interface_number) -{ - usbi_dbg("interface %d", interface_number); - - if (!dev_handle->dev->attached) - return LIBUSB_ERROR_NO_DEVICE; - - if (usbi_backend->attach_kernel_driver) - return usbi_backend->attach_kernel_driver(dev_handle, interface_number); - else - return LIBUSB_ERROR_NOT_SUPPORTED; -} - -/** \ingroup libusb_dev - * Enable/disable libusb's automatic kernel driver detachment. When this is - * enabled libusb will automatically detach the kernel driver on an interface - * when claiming the interface, and attach it when releasing the interface. - * - * Automatic kernel driver detachment is disabled on newly opened device - * handles by default. - * - * On platforms which do not have LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER - * this function will return LIBUSB_ERROR_NOT_SUPPORTED, and libusb will - * continue as if this function was never called. - * - * \param dev_handle a device handle - * \param enable whether to enable or disable auto kernel driver detachment - * - * \returns LIBUSB_SUCCESS on success - * \returns LIBUSB_ERROR_NOT_SUPPORTED on platforms where the functionality - * is not available - * \see libusb_claim_interface() - * \see libusb_release_interface() - * \see libusb_set_configuration() - */ -int API_EXPORTED libusb_set_auto_detach_kernel_driver( - libusb_device_handle *dev_handle, int enable) -{ - if (!(usbi_backend->caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER)) - return LIBUSB_ERROR_NOT_SUPPORTED; - - dev_handle->auto_detach_kernel_driver = enable; - return LIBUSB_SUCCESS; -} - -/** \ingroup libusb_lib - * Set log message verbosity. - * - * The default level is LIBUSB_LOG_LEVEL_NONE, which means no messages are ever - * printed. If you choose to increase the message verbosity level, ensure - * that your application does not close the stdout/stderr file descriptors. - * - * You are advised to use level LIBUSB_LOG_LEVEL_WARNING. libusb is conservative - * with its message logging and most of the time, will only log messages that - * explain error conditions and other oddities. This will help you debug - * your software. - * - * If the LIBUSB_DEBUG environment variable was set when libusb was - * initialized, this function does nothing: the message verbosity is fixed - * to the value in the environment variable. - * - * If libusb was compiled without any message logging, this function does - * nothing: you'll never get any messages. - * - * If libusb was compiled with verbose debug message logging, this function - * does nothing: you'll always get messages from all levels. - * - * \param ctx the context to operate on, or NULL for the default context - * \param level debug level to set - */ -void API_EXPORTED libusb_set_debug(libusb_context *ctx, int level) -{ - USBI_GET_CONTEXT(ctx); - if (!ctx->debug_fixed) - ctx->debug = level; -} - -/** \ingroup libusb_lib - * Initialize libusb. This function must be called before calling any other - * libusb function. - * - * If you do not provide an output location for a context pointer, a default - * context will be created. If there was already a default context, it will - * be reused (and nothing will be initialized/reinitialized). - * - * \param context Optional output location for context pointer. - * Only valid on return code 0. - * \returns 0 on success, or a LIBUSB_ERROR code on failure - * \see libusb_contexts - */ -int API_EXPORTED libusb_init(libusb_context **context) -{ - struct libusb_device *dev, *next; - char *dbg = getenv("LIBUSB_DEBUG"); - struct libusb_context *ctx; - static int first_init = 1; - int r = 0; - - usbi_mutex_static_lock(&default_context_lock); - - if (!timestamp_origin.tv_sec) { - usbi_backend->clock_gettime(USBI_CLOCK_REALTIME, ×tamp_origin); - } - - if (!context && usbi_default_context) { - usbi_dbg("reusing default context"); - default_context_refcnt++; - usbi_mutex_static_unlock(&default_context_lock); - return 0; - } - - ctx = calloc(1, sizeof(*ctx)); - if (!ctx) { - r = LIBUSB_ERROR_NO_MEM; - goto err_unlock; - } - -#ifdef ENABLE_DEBUG_LOGGING - ctx->debug = LIBUSB_LOG_LEVEL_DEBUG; -#endif - - if (dbg) { - ctx->debug = atoi(dbg); - if (ctx->debug) - ctx->debug_fixed = 1; - } - - /* default context should be initialized before calling usbi_dbg */ - if (!usbi_default_context) { - usbi_default_context = ctx; - default_context_refcnt++; - usbi_dbg("created default context"); - } - - usbi_dbg("libusb v%u.%u.%u.%u%s", libusb_version_internal.major, libusb_version_internal.minor, - libusb_version_internal.micro, libusb_version_internal.nano, libusb_version_internal.rc); - - usbi_mutex_init(&ctx->usb_devs_lock); - usbi_mutex_init(&ctx->open_devs_lock); - usbi_mutex_init(&ctx->hotplug_cbs_lock); - list_init(&ctx->usb_devs); - list_init(&ctx->open_devs); - list_init(&ctx->hotplug_cbs); - - usbi_mutex_static_lock(&active_contexts_lock); - if (first_init) { - first_init = 0; - list_init (&active_contexts_list); - } - list_add (&ctx->list, &active_contexts_list); - usbi_mutex_static_unlock(&active_contexts_lock); - - if (usbi_backend->init) { - r = usbi_backend->init(ctx); - if (r) - goto err_free_ctx; - } - - r = usbi_io_init(ctx); - if (r < 0) - goto err_backend_exit; - - usbi_mutex_static_unlock(&default_context_lock); - - if (context) - *context = ctx; - - return 0; - -err_backend_exit: - if (usbi_backend->exit) - usbi_backend->exit(); -err_free_ctx: - if (ctx == usbi_default_context) { - usbi_default_context = NULL; - default_context_refcnt--; - } - - usbi_mutex_static_lock(&active_contexts_lock); - list_del (&ctx->list); - usbi_mutex_static_unlock(&active_contexts_lock); - - usbi_mutex_lock(&ctx->usb_devs_lock); - list_for_each_entry_safe(dev, next, &ctx->usb_devs, list, struct libusb_device) { - list_del(&dev->list); - libusb_unref_device(dev); - } - usbi_mutex_unlock(&ctx->usb_devs_lock); - - usbi_mutex_destroy(&ctx->open_devs_lock); - usbi_mutex_destroy(&ctx->usb_devs_lock); - usbi_mutex_destroy(&ctx->hotplug_cbs_lock); - - free(ctx); -err_unlock: - usbi_mutex_static_unlock(&default_context_lock); - return r; -} - -/** \ingroup libusb_lib - * Deinitialize libusb. Should be called after closing all open devices and - * before your application terminates. - * \param ctx the context to deinitialize, or NULL for the default context - */ -void API_EXPORTED libusb_exit(struct libusb_context *ctx) -{ - struct libusb_device *dev, *next; - struct timeval tv = { 0, 0 }; - - usbi_dbg(""); - USBI_GET_CONTEXT(ctx); - - /* if working with default context, only actually do the deinitialization - * if we're the last user */ - usbi_mutex_static_lock(&default_context_lock); - if (ctx == usbi_default_context) { - if (--default_context_refcnt > 0) { - usbi_dbg("not destroying default context"); - usbi_mutex_static_unlock(&default_context_lock); - return; - } - usbi_dbg("destroying default context"); - usbi_default_context = NULL; - } - usbi_mutex_static_unlock(&default_context_lock); - - usbi_mutex_static_lock(&active_contexts_lock); - list_del (&ctx->list); - usbi_mutex_static_unlock(&active_contexts_lock); - - if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) { - usbi_hotplug_deregister_all(ctx); - - /* - * Ensure any pending unplug events are read from the hotplug - * pipe. The usb_device-s hold in the events are no longer part - * of usb_devs, but the events still hold a reference! - * - * Note we don't do this if the application has left devices - * open (which implies a buggy app) to avoid packet completion - * handlers running when the app does not expect them to run. - */ - if (list_empty(&ctx->open_devs)) - libusb_handle_events_timeout(ctx, &tv); - - usbi_mutex_lock(&ctx->usb_devs_lock); - list_for_each_entry_safe(dev, next, &ctx->usb_devs, list, struct libusb_device) { - list_del(&dev->list); - libusb_unref_device(dev); - } - usbi_mutex_unlock(&ctx->usb_devs_lock); - } - - /* a few sanity checks. don't bother with locking because unless - * there is an application bug, nobody will be accessing these. */ - if (!list_empty(&ctx->usb_devs)) - usbi_warn(ctx, "some libusb_devices were leaked"); - if (!list_empty(&ctx->open_devs)) - usbi_warn(ctx, "application left some devices open"); - - usbi_io_exit(ctx); - if (usbi_backend->exit) - usbi_backend->exit(); - - usbi_mutex_destroy(&ctx->open_devs_lock); - usbi_mutex_destroy(&ctx->usb_devs_lock); - usbi_mutex_destroy(&ctx->hotplug_cbs_lock); - free(ctx); -} - -/** \ingroup libusb_misc - * Check at runtime if the loaded library has a given capability. - * This call should be performed after \ref libusb_init(), to ensure the - * backend has updated its capability set. - * - * \param capability the \ref libusb_capability to check for - * \returns nonzero if the running library has the capability, 0 otherwise - */ -int API_EXPORTED libusb_has_capability(uint32_t capability) -{ - switch (capability) { - case LIBUSB_CAP_HAS_CAPABILITY: - return 1; - case LIBUSB_CAP_HAS_HOTPLUG: - return !(usbi_backend->get_device_list); - case LIBUSB_CAP_HAS_HID_ACCESS: - return (usbi_backend->caps & USBI_CAP_HAS_HID_ACCESS); - case LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER: - return (usbi_backend->caps & USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER); - } - return 0; -} - -/* this is defined in libusbi.h if needed */ -#ifdef LIBUSB_PRINTF_WIN32 -/* - * Prior to VS2015, Microsoft did not provide the snprintf() function and - * provided a vsnprintf() that did not guarantee NULL-terminated output. - * Microsoft did provide a _snprintf() function, but again it did not - * guarantee NULL-terminated output. - * - * The below implementations guarantee NULL-terminated output and are - * C99 compliant. - */ - -int usbi_snprintf(char *str, size_t size, const char *format, ...) -{ - va_list ap; - int ret; - - va_start(ap, format); - ret = usbi_vsnprintf(str, size, format, ap); - va_end(ap); - - return ret; -} - -int usbi_vsnprintf(char *str, size_t size, const char *format, va_list ap) -{ - int ret; - - ret = _vsnprintf(str, size, format, ap); - if (ret < 0 || ret == (int)size) { - /* Output is truncated, ensure buffer is NULL-terminated and - * determine how many characters would have been written. */ - str[size - 1] = '\0'; - if (ret < 0) - ret = _vsnprintf(NULL, 0, format, ap); - } - - return ret; -} -#endif - -static void usbi_log_str(struct libusb_context *ctx, - enum libusb_log_level level, const char * str) -{ -#if defined(USE_SYSTEM_LOGGING_FACILITY) -#if defined(OS_WINDOWS) - OutputDebugString(str); -#elif defined(OS_WINCE) - /* Windows CE only supports the Unicode version of OutputDebugString. */ - WCHAR wbuf[USBI_MAX_LOG_LEN]; - MultiByteToWideChar(CP_UTF8, 0, str, -1, wbuf, sizeof(wbuf)); - OutputDebugStringW(wbuf); -#elif defined(__ANDROID__) - int priority = ANDROID_LOG_UNKNOWN; - switch (level) { - case LIBUSB_LOG_LEVEL_INFO: priority = ANDROID_LOG_INFO; break; - case LIBUSB_LOG_LEVEL_WARNING: priority = ANDROID_LOG_WARN; break; - case LIBUSB_LOG_LEVEL_ERROR: priority = ANDROID_LOG_ERROR; break; - case LIBUSB_LOG_LEVEL_DEBUG: priority = ANDROID_LOG_DEBUG; break; - } - __android_log_write(priority, "libusb", str); -#elif defined(HAVE_SYSLOG_FUNC) - int syslog_level = LOG_INFO; - switch (level) { - case LIBUSB_LOG_LEVEL_INFO: syslog_level = LOG_INFO; break; - case LIBUSB_LOG_LEVEL_WARNING: syslog_level = LOG_WARNING; break; - case LIBUSB_LOG_LEVEL_ERROR: syslog_level = LOG_ERR; break; - case LIBUSB_LOG_LEVEL_DEBUG: syslog_level = LOG_DEBUG; break; - } - syslog(syslog_level, "%s", str); -#else /* All of gcc, Clang, XCode seem to use #warning */ -#warning System logging is not supported on this platform. Logging to stderr will be used instead. - fputs(str, stderr); -#endif -#else - fputs(str, stderr); -#endif /* USE_SYSTEM_LOGGING_FACILITY */ - UNUSED(ctx); - UNUSED(level); -} - -void usbi_log_v(struct libusb_context *ctx, enum libusb_log_level level, - const char *function, const char *format, va_list args) -{ - const char *prefix = ""; - char buf[USBI_MAX_LOG_LEN]; - struct timespec now; - int global_debug, header_len, text_len; - static int has_debug_header_been_displayed = 0; - -#ifdef ENABLE_DEBUG_LOGGING - global_debug = 1; - UNUSED(ctx); -#else - int ctx_level = 0; - - USBI_GET_CONTEXT(ctx); - if (ctx) { - ctx_level = ctx->debug; - } else { - char *dbg = getenv("LIBUSB_DEBUG"); - if (dbg) - ctx_level = atoi(dbg); - } - global_debug = (ctx_level == LIBUSB_LOG_LEVEL_DEBUG); - if (!ctx_level) - return; - if (level == LIBUSB_LOG_LEVEL_WARNING && ctx_level < LIBUSB_LOG_LEVEL_WARNING) - return; - if (level == LIBUSB_LOG_LEVEL_INFO && ctx_level < LIBUSB_LOG_LEVEL_INFO) - return; - if (level == LIBUSB_LOG_LEVEL_DEBUG && ctx_level < LIBUSB_LOG_LEVEL_DEBUG) - return; -#endif - - usbi_backend->clock_gettime(USBI_CLOCK_REALTIME, &now); - if ((global_debug) && (!has_debug_header_been_displayed)) { - has_debug_header_been_displayed = 1; - usbi_log_str(ctx, LIBUSB_LOG_LEVEL_DEBUG, "[timestamp] [threadID] facility level [function call] " USBI_LOG_LINE_END); - usbi_log_str(ctx, LIBUSB_LOG_LEVEL_DEBUG, "--------------------------------------------------------------------------------" USBI_LOG_LINE_END); - } - if (now.tv_nsec < timestamp_origin.tv_nsec) { - now.tv_sec--; - now.tv_nsec += 1000000000L; - } - now.tv_sec -= timestamp_origin.tv_sec; - now.tv_nsec -= timestamp_origin.tv_nsec; - - switch (level) { - case LIBUSB_LOG_LEVEL_INFO: - prefix = "info"; - break; - case LIBUSB_LOG_LEVEL_WARNING: - prefix = "warning"; - break; - case LIBUSB_LOG_LEVEL_ERROR: - prefix = "error"; - break; - case LIBUSB_LOG_LEVEL_DEBUG: - prefix = "debug"; - break; - case LIBUSB_LOG_LEVEL_NONE: - return; - default: - prefix = "unknown"; - break; - } - - if (global_debug) { - header_len = snprintf(buf, sizeof(buf), - "[%2d.%06d] [%08x] libusb: %s [%s] ", - (int)now.tv_sec, (int)(now.tv_nsec / 1000L), usbi_get_tid(), prefix, function); - } else { - header_len = snprintf(buf, sizeof(buf), - "libusb: %s [%s] ", prefix, function); - } - - if (header_len < 0 || header_len >= (int)sizeof(buf)) { - /* Somehow snprintf failed to write to the buffer, - * remove the header so something useful is output. */ - header_len = 0; - } - /* Make sure buffer is NUL terminated */ - buf[header_len] = '\0'; - text_len = vsnprintf(buf + header_len, sizeof(buf) - header_len, - format, args); - if (text_len < 0 || text_len + header_len >= (int)sizeof(buf)) { - /* Truncated log output. On some platforms a -1 return value means - * that the output was truncated. */ - text_len = sizeof(buf) - header_len; - } - if (header_len + text_len + sizeof(USBI_LOG_LINE_END) >= sizeof(buf)) { - /* Need to truncate the text slightly to fit on the terminator. */ - text_len -= (header_len + text_len + sizeof(USBI_LOG_LINE_END)) - sizeof(buf); - } - strcpy(buf + header_len + text_len, USBI_LOG_LINE_END); - - usbi_log_str(ctx, level, buf); -} - -void usbi_log(struct libusb_context *ctx, enum libusb_log_level level, - const char *function, const char *format, ...) -{ - va_list args; - - va_start (args, format); - usbi_log_v(ctx, level, function, format, args); - va_end (args); -} - -/** \ingroup libusb_misc - * Returns a constant NULL-terminated string with the ASCII name of a libusb - * error or transfer status code. The caller must not free() the returned - * string. - * - * \param error_code The \ref libusb_error or libusb_transfer_status code to - * return the name of. - * \returns The error name, or the string **UNKNOWN** if the value of - * error_code is not a known error / status code. - */ -DEFAULT_VISIBILITY const char * LIBUSB_CALL libusb_error_name(int error_code) -{ - switch (error_code) { - case LIBUSB_ERROR_IO: - return "LIBUSB_ERROR_IO"; - case LIBUSB_ERROR_INVALID_PARAM: - return "LIBUSB_ERROR_INVALID_PARAM"; - case LIBUSB_ERROR_ACCESS: - return "LIBUSB_ERROR_ACCESS"; - case LIBUSB_ERROR_NO_DEVICE: - return "LIBUSB_ERROR_NO_DEVICE"; - case LIBUSB_ERROR_NOT_FOUND: - return "LIBUSB_ERROR_NOT_FOUND"; - case LIBUSB_ERROR_BUSY: - return "LIBUSB_ERROR_BUSY"; - case LIBUSB_ERROR_TIMEOUT: - return "LIBUSB_ERROR_TIMEOUT"; - case LIBUSB_ERROR_OVERFLOW: - return "LIBUSB_ERROR_OVERFLOW"; - case LIBUSB_ERROR_PIPE: - return "LIBUSB_ERROR_PIPE"; - case LIBUSB_ERROR_INTERRUPTED: - return "LIBUSB_ERROR_INTERRUPTED"; - case LIBUSB_ERROR_NO_MEM: - return "LIBUSB_ERROR_NO_MEM"; - case LIBUSB_ERROR_NOT_SUPPORTED: - return "LIBUSB_ERROR_NOT_SUPPORTED"; - case LIBUSB_ERROR_OTHER: - return "LIBUSB_ERROR_OTHER"; - - case LIBUSB_TRANSFER_ERROR: - return "LIBUSB_TRANSFER_ERROR"; - case LIBUSB_TRANSFER_TIMED_OUT: - return "LIBUSB_TRANSFER_TIMED_OUT"; - case LIBUSB_TRANSFER_CANCELLED: - return "LIBUSB_TRANSFER_CANCELLED"; - case LIBUSB_TRANSFER_STALL: - return "LIBUSB_TRANSFER_STALL"; - case LIBUSB_TRANSFER_NO_DEVICE: - return "LIBUSB_TRANSFER_NO_DEVICE"; - case LIBUSB_TRANSFER_OVERFLOW: - return "LIBUSB_TRANSFER_OVERFLOW"; - - case 0: - return "LIBUSB_SUCCESS / LIBUSB_TRANSFER_COMPLETED"; - default: - return "**UNKNOWN**"; - } -} - -/** \ingroup libusb_misc - * Returns a pointer to const struct libusb_version with the version - * (major, minor, micro, nano and rc) of the running library. - */ -DEFAULT_VISIBILITY -const struct libusb_version * LIBUSB_CALL libusb_get_version(void) -{ - return &libusb_version_internal; -} diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/descriptor.c b/vendor/github.com/karalabe/hid/libusb/libusb/descriptor.c deleted file mode 100644 index 4c9435ff..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/descriptor.c +++ /dev/null @@ -1,1191 +0,0 @@ -/* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */ -/* - * USB descriptor handling functions for libusb - * Copyright © 2007 Daniel Drake - * Copyright © 2001 Johannes Erdfelt - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include - -#include -#include -#include -#include - -#include "libusbi.h" - -#define DESC_HEADER_LENGTH 2 -#define DEVICE_DESC_LENGTH 18 -#define CONFIG_DESC_LENGTH 9 -#define INTERFACE_DESC_LENGTH 9 -#define ENDPOINT_DESC_LENGTH 7 -#define ENDPOINT_AUDIO_DESC_LENGTH 9 - -/** @defgroup libusb_desc USB descriptors - * This page details how to examine the various standard USB descriptors - * for detected devices - */ - -/* set host_endian if the w values are already in host endian format, - * as opposed to bus endian. */ -int usbi_parse_descriptor(const unsigned char *source, const char *descriptor, - void *dest, int host_endian) -{ - const unsigned char *sp = source; - unsigned char *dp = dest; - uint16_t w; - const char *cp; - uint32_t d; - - for (cp = descriptor; *cp; cp++) { - switch (*cp) { - case 'b': /* 8-bit byte */ - *dp++ = *sp++; - break; - case 'w': /* 16-bit word, convert from little endian to CPU */ - dp += ((uintptr_t)dp & 1); /* Align to word boundary */ - - if (host_endian) { - memcpy(dp, sp, 2); - } else { - w = (sp[1] << 8) | sp[0]; - *((uint16_t *)dp) = w; - } - sp += 2; - dp += 2; - break; - case 'd': /* 32-bit word, convert from little endian to CPU */ - dp += ((uintptr_t)dp & 1); /* Align to word boundary */ - - if (host_endian) { - memcpy(dp, sp, 4); - } else { - d = (sp[3] << 24) | (sp[2] << 16) | - (sp[1] << 8) | sp[0]; - *((uint32_t *)dp) = d; - } - sp += 4; - dp += 4; - break; - case 'u': /* 16 byte UUID */ - memcpy(dp, sp, 16); - sp += 16; - dp += 16; - break; - } - } - - return (int) (sp - source); -} - -static void clear_endpoint(struct libusb_endpoint_descriptor *endpoint) -{ - free((void *) endpoint->extra); -} - -static int parse_endpoint(struct libusb_context *ctx, - struct libusb_endpoint_descriptor *endpoint, unsigned char *buffer, - int size, int host_endian) -{ - struct usb_descriptor_header header; - unsigned char *extra; - unsigned char *begin; - int parsed = 0; - int len; - - if (size < DESC_HEADER_LENGTH) { - usbi_err(ctx, "short endpoint descriptor read %d/%d", - size, DESC_HEADER_LENGTH); - return LIBUSB_ERROR_IO; - } - - usbi_parse_descriptor(buffer, "bb", &header, 0); - if (header.bDescriptorType != LIBUSB_DT_ENDPOINT) { - usbi_err(ctx, "unexpected descriptor %x (expected %x)", - header.bDescriptorType, LIBUSB_DT_ENDPOINT); - return parsed; - } - if (header.bLength > size) { - usbi_warn(ctx, "short endpoint descriptor read %d/%d", - size, header.bLength); - return parsed; - } - if (header.bLength >= ENDPOINT_AUDIO_DESC_LENGTH) - usbi_parse_descriptor(buffer, "bbbbwbbb", endpoint, host_endian); - else if (header.bLength >= ENDPOINT_DESC_LENGTH) - usbi_parse_descriptor(buffer, "bbbbwb", endpoint, host_endian); - else { - usbi_err(ctx, "invalid endpoint bLength (%d)", header.bLength); - return LIBUSB_ERROR_IO; - } - - buffer += header.bLength; - size -= header.bLength; - parsed += header.bLength; - - /* Skip over the rest of the Class Specific or Vendor Specific */ - /* descriptors */ - begin = buffer; - while (size >= DESC_HEADER_LENGTH) { - usbi_parse_descriptor(buffer, "bb", &header, 0); - if (header.bLength < DESC_HEADER_LENGTH) { - usbi_err(ctx, "invalid extra ep desc len (%d)", - header.bLength); - return LIBUSB_ERROR_IO; - } else if (header.bLength > size) { - usbi_warn(ctx, "short extra ep desc read %d/%d", - size, header.bLength); - return parsed; - } - - /* If we find another "proper" descriptor then we're done */ - if ((header.bDescriptorType == LIBUSB_DT_ENDPOINT) || - (header.bDescriptorType == LIBUSB_DT_INTERFACE) || - (header.bDescriptorType == LIBUSB_DT_CONFIG) || - (header.bDescriptorType == LIBUSB_DT_DEVICE)) - break; - - usbi_dbg("skipping descriptor %x", header.bDescriptorType); - buffer += header.bLength; - size -= header.bLength; - parsed += header.bLength; - } - - /* Copy any unknown descriptors into a storage area for drivers */ - /* to later parse */ - len = (int)(buffer - begin); - if (!len) { - endpoint->extra = NULL; - endpoint->extra_length = 0; - return parsed; - } - - extra = malloc(len); - endpoint->extra = extra; - if (!extra) { - endpoint->extra_length = 0; - return LIBUSB_ERROR_NO_MEM; - } - - memcpy(extra, begin, len); - endpoint->extra_length = len; - - return parsed; -} - -static void clear_interface(struct libusb_interface *usb_interface) -{ - int i; - int j; - - if (usb_interface->altsetting) { - for (i = 0; i < usb_interface->num_altsetting; i++) { - struct libusb_interface_descriptor *ifp = - (struct libusb_interface_descriptor *) - usb_interface->altsetting + i; - free((void *) ifp->extra); - if (ifp->endpoint) { - for (j = 0; j < ifp->bNumEndpoints; j++) - clear_endpoint((struct libusb_endpoint_descriptor *) - ifp->endpoint + j); - } - free((void *) ifp->endpoint); - } - } - free((void *) usb_interface->altsetting); - usb_interface->altsetting = NULL; -} - -static int parse_interface(libusb_context *ctx, - struct libusb_interface *usb_interface, unsigned char *buffer, int size, - int host_endian) -{ - int i; - int len; - int r; - int parsed = 0; - int interface_number = -1; - struct usb_descriptor_header header; - struct libusb_interface_descriptor *ifp; - unsigned char *begin; - - usb_interface->num_altsetting = 0; - - while (size >= INTERFACE_DESC_LENGTH) { - struct libusb_interface_descriptor *altsetting = - (struct libusb_interface_descriptor *) usb_interface->altsetting; - altsetting = usbi_reallocf(altsetting, - sizeof(struct libusb_interface_descriptor) * - (usb_interface->num_altsetting + 1)); - if (!altsetting) { - r = LIBUSB_ERROR_NO_MEM; - goto err; - } - usb_interface->altsetting = altsetting; - - ifp = altsetting + usb_interface->num_altsetting; - usbi_parse_descriptor(buffer, "bbbbbbbbb", ifp, 0); - if (ifp->bDescriptorType != LIBUSB_DT_INTERFACE) { - usbi_err(ctx, "unexpected descriptor %x (expected %x)", - ifp->bDescriptorType, LIBUSB_DT_INTERFACE); - return parsed; - } - if (ifp->bLength < INTERFACE_DESC_LENGTH) { - usbi_err(ctx, "invalid interface bLength (%d)", - ifp->bLength); - r = LIBUSB_ERROR_IO; - goto err; - } - if (ifp->bLength > size) { - usbi_warn(ctx, "short intf descriptor read %d/%d", - size, ifp->bLength); - return parsed; - } - if (ifp->bNumEndpoints > USB_MAXENDPOINTS) { - usbi_err(ctx, "too many endpoints (%d)", ifp->bNumEndpoints); - r = LIBUSB_ERROR_IO; - goto err; - } - - usb_interface->num_altsetting++; - ifp->extra = NULL; - ifp->extra_length = 0; - ifp->endpoint = NULL; - - if (interface_number == -1) - interface_number = ifp->bInterfaceNumber; - - /* Skip over the interface */ - buffer += ifp->bLength; - parsed += ifp->bLength; - size -= ifp->bLength; - - begin = buffer; - - /* Skip over any interface, class or vendor descriptors */ - while (size >= DESC_HEADER_LENGTH) { - usbi_parse_descriptor(buffer, "bb", &header, 0); - if (header.bLength < DESC_HEADER_LENGTH) { - usbi_err(ctx, - "invalid extra intf desc len (%d)", - header.bLength); - r = LIBUSB_ERROR_IO; - goto err; - } else if (header.bLength > size) { - usbi_warn(ctx, - "short extra intf desc read %d/%d", - size, header.bLength); - return parsed; - } - - /* If we find another "proper" descriptor then we're done */ - if ((header.bDescriptorType == LIBUSB_DT_INTERFACE) || - (header.bDescriptorType == LIBUSB_DT_ENDPOINT) || - (header.bDescriptorType == LIBUSB_DT_CONFIG) || - (header.bDescriptorType == LIBUSB_DT_DEVICE)) - break; - - buffer += header.bLength; - parsed += header.bLength; - size -= header.bLength; - } - - /* Copy any unknown descriptors into a storage area for */ - /* drivers to later parse */ - len = (int)(buffer - begin); - if (len) { - ifp->extra = malloc(len); - if (!ifp->extra) { - r = LIBUSB_ERROR_NO_MEM; - goto err; - } - memcpy((unsigned char *) ifp->extra, begin, len); - ifp->extra_length = len; - } - - if (ifp->bNumEndpoints > 0) { - struct libusb_endpoint_descriptor *endpoint; - endpoint = calloc(ifp->bNumEndpoints, sizeof(struct libusb_endpoint_descriptor)); - ifp->endpoint = endpoint; - if (!endpoint) { - r = LIBUSB_ERROR_NO_MEM; - goto err; - } - - for (i = 0; i < ifp->bNumEndpoints; i++) { - r = parse_endpoint(ctx, endpoint + i, buffer, size, - host_endian); - if (r < 0) - goto err; - if (r == 0) { - ifp->bNumEndpoints = (uint8_t)i; - break;; - } - - buffer += r; - parsed += r; - size -= r; - } - } - - /* We check to see if it's an alternate to this one */ - ifp = (struct libusb_interface_descriptor *) buffer; - if (size < LIBUSB_DT_INTERFACE_SIZE || - ifp->bDescriptorType != LIBUSB_DT_INTERFACE || - ifp->bInterfaceNumber != interface_number) - return parsed; - } - - return parsed; -err: - clear_interface(usb_interface); - return r; -} - -static void clear_configuration(struct libusb_config_descriptor *config) -{ - int i; - if (config->interface) { - for (i = 0; i < config->bNumInterfaces; i++) - clear_interface((struct libusb_interface *) - config->interface + i); - } - free((void *) config->interface); - free((void *) config->extra); -} - -static int parse_configuration(struct libusb_context *ctx, - struct libusb_config_descriptor *config, unsigned char *buffer, - int size, int host_endian) -{ - int i; - int r; - struct usb_descriptor_header header; - struct libusb_interface *usb_interface; - - if (size < LIBUSB_DT_CONFIG_SIZE) { - usbi_err(ctx, "short config descriptor read %d/%d", - size, LIBUSB_DT_CONFIG_SIZE); - return LIBUSB_ERROR_IO; - } - - usbi_parse_descriptor(buffer, "bbwbbbbb", config, host_endian); - if (config->bDescriptorType != LIBUSB_DT_CONFIG) { - usbi_err(ctx, "unexpected descriptor %x (expected %x)", - config->bDescriptorType, LIBUSB_DT_CONFIG); - return LIBUSB_ERROR_IO; - } - if (config->bLength < LIBUSB_DT_CONFIG_SIZE) { - usbi_err(ctx, "invalid config bLength (%d)", config->bLength); - return LIBUSB_ERROR_IO; - } - if (config->bLength > size) { - usbi_err(ctx, "short config descriptor read %d/%d", - size, config->bLength); - return LIBUSB_ERROR_IO; - } - if (config->bNumInterfaces > USB_MAXINTERFACES) { - usbi_err(ctx, "too many interfaces (%d)", config->bNumInterfaces); - return LIBUSB_ERROR_IO; - } - - usb_interface = calloc(config->bNumInterfaces, sizeof(struct libusb_interface)); - config->interface = usb_interface; - if (!usb_interface) - return LIBUSB_ERROR_NO_MEM; - - buffer += config->bLength; - size -= config->bLength; - - config->extra = NULL; - config->extra_length = 0; - - for (i = 0; i < config->bNumInterfaces; i++) { - int len; - unsigned char *begin; - - /* Skip over the rest of the Class Specific or Vendor */ - /* Specific descriptors */ - begin = buffer; - while (size >= DESC_HEADER_LENGTH) { - usbi_parse_descriptor(buffer, "bb", &header, 0); - - if (header.bLength < DESC_HEADER_LENGTH) { - usbi_err(ctx, - "invalid extra config desc len (%d)", - header.bLength); - r = LIBUSB_ERROR_IO; - goto err; - } else if (header.bLength > size) { - usbi_warn(ctx, - "short extra config desc read %d/%d", - size, header.bLength); - config->bNumInterfaces = (uint8_t)i; - return size; - } - - /* If we find another "proper" descriptor then we're done */ - if ((header.bDescriptorType == LIBUSB_DT_ENDPOINT) || - (header.bDescriptorType == LIBUSB_DT_INTERFACE) || - (header.bDescriptorType == LIBUSB_DT_CONFIG) || - (header.bDescriptorType == LIBUSB_DT_DEVICE)) - break; - - usbi_dbg("skipping descriptor 0x%x", header.bDescriptorType); - buffer += header.bLength; - size -= header.bLength; - } - - /* Copy any unknown descriptors into a storage area for */ - /* drivers to later parse */ - len = (int)(buffer - begin); - if (len) { - /* FIXME: We should realloc and append here */ - if (!config->extra_length) { - config->extra = malloc(len); - if (!config->extra) { - r = LIBUSB_ERROR_NO_MEM; - goto err; - } - - memcpy((unsigned char *) config->extra, begin, len); - config->extra_length = len; - } - } - - r = parse_interface(ctx, usb_interface + i, buffer, size, host_endian); - if (r < 0) - goto err; - if (r == 0) { - config->bNumInterfaces = (uint8_t)i; - break; - } - - buffer += r; - size -= r; - } - - return size; - -err: - clear_configuration(config); - return r; -} - -static int raw_desc_to_config(struct libusb_context *ctx, - unsigned char *buf, int size, int host_endian, - struct libusb_config_descriptor **config) -{ - struct libusb_config_descriptor *_config = malloc(sizeof(*_config)); - int r; - - if (!_config) - return LIBUSB_ERROR_NO_MEM; - - r = parse_configuration(ctx, _config, buf, size, host_endian); - if (r < 0) { - usbi_err(ctx, "parse_configuration failed with error %d", r); - free(_config); - return r; - } else if (r > 0) { - usbi_warn(ctx, "still %d bytes of descriptor data left", r); - } - - *config = _config; - return LIBUSB_SUCCESS; -} - -int usbi_device_cache_descriptor(libusb_device *dev) -{ - int r, host_endian = 0; - - r = usbi_backend->get_device_descriptor(dev, (unsigned char *) &dev->device_descriptor, - &host_endian); - if (r < 0) - return r; - - if (!host_endian) { - dev->device_descriptor.bcdUSB = libusb_le16_to_cpu(dev->device_descriptor.bcdUSB); - dev->device_descriptor.idVendor = libusb_le16_to_cpu(dev->device_descriptor.idVendor); - dev->device_descriptor.idProduct = libusb_le16_to_cpu(dev->device_descriptor.idProduct); - dev->device_descriptor.bcdDevice = libusb_le16_to_cpu(dev->device_descriptor.bcdDevice); - } - - return LIBUSB_SUCCESS; -} - -/** \ingroup libusb_desc - * Get the USB device descriptor for a given device. - * - * This is a non-blocking function; the device descriptor is cached in memory. - * - * Note since libusb-1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102, this - * function always succeeds. - * - * \param dev the device - * \param desc output location for the descriptor data - * \returns 0 on success or a LIBUSB_ERROR code on failure - */ -int API_EXPORTED libusb_get_device_descriptor(libusb_device *dev, - struct libusb_device_descriptor *desc) -{ - usbi_dbg(""); - memcpy((unsigned char *) desc, (unsigned char *) &dev->device_descriptor, - sizeof (dev->device_descriptor)); - return 0; -} - -/** \ingroup libusb_desc - * Get the USB configuration descriptor for the currently active configuration. - * This is a non-blocking function which does not involve any requests being - * sent to the device. - * - * \param dev a device - * \param config output location for the USB configuration descriptor. Only - * valid if 0 was returned. Must be freed with libusb_free_config_descriptor() - * after use. - * \returns 0 on success - * \returns LIBUSB_ERROR_NOT_FOUND if the device is in unconfigured state - * \returns another LIBUSB_ERROR code on error - * \see libusb_get_config_descriptor - */ -int API_EXPORTED libusb_get_active_config_descriptor(libusb_device *dev, - struct libusb_config_descriptor **config) -{ - struct libusb_config_descriptor _config; - unsigned char tmp[LIBUSB_DT_CONFIG_SIZE]; - unsigned char *buf = NULL; - int host_endian = 0; - int r; - - r = usbi_backend->get_active_config_descriptor(dev, tmp, - LIBUSB_DT_CONFIG_SIZE, &host_endian); - if (r < 0) - return r; - if (r < LIBUSB_DT_CONFIG_SIZE) { - usbi_err(dev->ctx, "short config descriptor read %d/%d", - r, LIBUSB_DT_CONFIG_SIZE); - return LIBUSB_ERROR_IO; - } - - usbi_parse_descriptor(tmp, "bbw", &_config, host_endian); - buf = malloc(_config.wTotalLength); - if (!buf) - return LIBUSB_ERROR_NO_MEM; - - r = usbi_backend->get_active_config_descriptor(dev, buf, - _config.wTotalLength, &host_endian); - if (r >= 0) - r = raw_desc_to_config(dev->ctx, buf, r, host_endian, config); - - free(buf); - return r; -} - -/** \ingroup libusb_desc - * Get a USB configuration descriptor based on its index. - * This is a non-blocking function which does not involve any requests being - * sent to the device. - * - * \param dev a device - * \param config_index the index of the configuration you wish to retrieve - * \param config output location for the USB configuration descriptor. Only - * valid if 0 was returned. Must be freed with libusb_free_config_descriptor() - * after use. - * \returns 0 on success - * \returns LIBUSB_ERROR_NOT_FOUND if the configuration does not exist - * \returns another LIBUSB_ERROR code on error - * \see libusb_get_active_config_descriptor() - * \see libusb_get_config_descriptor_by_value() - */ -int API_EXPORTED libusb_get_config_descriptor(libusb_device *dev, - uint8_t config_index, struct libusb_config_descriptor **config) -{ - struct libusb_config_descriptor _config; - unsigned char tmp[LIBUSB_DT_CONFIG_SIZE]; - unsigned char *buf = NULL; - int host_endian = 0; - int r; - - usbi_dbg("index %d", config_index); - if (config_index >= dev->num_configurations) - return LIBUSB_ERROR_NOT_FOUND; - - r = usbi_backend->get_config_descriptor(dev, config_index, tmp, - LIBUSB_DT_CONFIG_SIZE, &host_endian); - if (r < 0) - return r; - if (r < LIBUSB_DT_CONFIG_SIZE) { - usbi_err(dev->ctx, "short config descriptor read %d/%d", - r, LIBUSB_DT_CONFIG_SIZE); - return LIBUSB_ERROR_IO; - } - - usbi_parse_descriptor(tmp, "bbw", &_config, host_endian); - buf = malloc(_config.wTotalLength); - if (!buf) - return LIBUSB_ERROR_NO_MEM; - - r = usbi_backend->get_config_descriptor(dev, config_index, buf, - _config.wTotalLength, &host_endian); - if (r >= 0) - r = raw_desc_to_config(dev->ctx, buf, r, host_endian, config); - - free(buf); - return r; -} - -/* iterate through all configurations, returning the index of the configuration - * matching a specific bConfigurationValue in the idx output parameter, or -1 - * if the config was not found. - * returns 0 on success or a LIBUSB_ERROR code - */ -int usbi_get_config_index_by_value(struct libusb_device *dev, - uint8_t bConfigurationValue, int *idx) -{ - uint8_t i; - - usbi_dbg("value %d", bConfigurationValue); - for (i = 0; i < dev->num_configurations; i++) { - unsigned char tmp[6]; - int host_endian; - int r = usbi_backend->get_config_descriptor(dev, i, tmp, sizeof(tmp), - &host_endian); - if (r < 0) { - *idx = -1; - return r; - } - if (tmp[5] == bConfigurationValue) { - *idx = i; - return 0; - } - } - - *idx = -1; - return 0; -} - -/** \ingroup libusb_desc - * Get a USB configuration descriptor with a specific bConfigurationValue. - * This is a non-blocking function which does not involve any requests being - * sent to the device. - * - * \param dev a device - * \param bConfigurationValue the bConfigurationValue of the configuration you - * wish to retrieve - * \param config output location for the USB configuration descriptor. Only - * valid if 0 was returned. Must be freed with libusb_free_config_descriptor() - * after use. - * \returns 0 on success - * \returns LIBUSB_ERROR_NOT_FOUND if the configuration does not exist - * \returns another LIBUSB_ERROR code on error - * \see libusb_get_active_config_descriptor() - * \see libusb_get_config_descriptor() - */ -int API_EXPORTED libusb_get_config_descriptor_by_value(libusb_device *dev, - uint8_t bConfigurationValue, struct libusb_config_descriptor **config) -{ - int r, idx, host_endian; - unsigned char *buf = NULL; - - if (usbi_backend->get_config_descriptor_by_value) { - r = usbi_backend->get_config_descriptor_by_value(dev, - bConfigurationValue, &buf, &host_endian); - if (r < 0) - return r; - return raw_desc_to_config(dev->ctx, buf, r, host_endian, config); - } - - r = usbi_get_config_index_by_value(dev, bConfigurationValue, &idx); - if (r < 0) - return r; - else if (idx == -1) - return LIBUSB_ERROR_NOT_FOUND; - else - return libusb_get_config_descriptor(dev, (uint8_t) idx, config); -} - -/** \ingroup libusb_desc - * Free a configuration descriptor obtained from - * libusb_get_active_config_descriptor() or libusb_get_config_descriptor(). - * It is safe to call this function with a NULL config parameter, in which - * case the function simply returns. - * - * \param config the configuration descriptor to free - */ -void API_EXPORTED libusb_free_config_descriptor( - struct libusb_config_descriptor *config) -{ - if (!config) - return; - - clear_configuration(config); - free(config); -} - -/** \ingroup libusb_desc - * Get an endpoints superspeed endpoint companion descriptor (if any) - * - * \param ctx the context to operate on, or NULL for the default context - * \param endpoint endpoint descriptor from which to get the superspeed - * endpoint companion descriptor - * \param ep_comp output location for the superspeed endpoint companion - * descriptor. Only valid if 0 was returned. Must be freed with - * libusb_free_ss_endpoint_companion_descriptor() after use. - * \returns 0 on success - * \returns LIBUSB_ERROR_NOT_FOUND if the configuration does not exist - * \returns another LIBUSB_ERROR code on error - */ -int API_EXPORTED libusb_get_ss_endpoint_companion_descriptor( - struct libusb_context *ctx, - const struct libusb_endpoint_descriptor *endpoint, - struct libusb_ss_endpoint_companion_descriptor **ep_comp) -{ - struct usb_descriptor_header header; - int size = endpoint->extra_length; - const unsigned char *buffer = endpoint->extra; - - *ep_comp = NULL; - - while (size >= DESC_HEADER_LENGTH) { - usbi_parse_descriptor(buffer, "bb", &header, 0); - if (header.bLength < 2 || header.bLength > size) { - usbi_err(ctx, "invalid descriptor length %d", - header.bLength); - return LIBUSB_ERROR_IO; - } - if (header.bDescriptorType != LIBUSB_DT_SS_ENDPOINT_COMPANION) { - buffer += header.bLength; - size -= header.bLength; - continue; - } - if (header.bLength < LIBUSB_DT_SS_ENDPOINT_COMPANION_SIZE) { - usbi_err(ctx, "invalid ss-ep-comp-desc length %d", - header.bLength); - return LIBUSB_ERROR_IO; - } - *ep_comp = malloc(sizeof(**ep_comp)); - if (*ep_comp == NULL) - return LIBUSB_ERROR_NO_MEM; - usbi_parse_descriptor(buffer, "bbbbw", *ep_comp, 0); - return LIBUSB_SUCCESS; - } - return LIBUSB_ERROR_NOT_FOUND; -} - -/** \ingroup libusb_desc - * Free a superspeed endpoint companion descriptor obtained from - * libusb_get_ss_endpoint_companion_descriptor(). - * It is safe to call this function with a NULL ep_comp parameter, in which - * case the function simply returns. - * - * \param ep_comp the superspeed endpoint companion descriptor to free - */ -void API_EXPORTED libusb_free_ss_endpoint_companion_descriptor( - struct libusb_ss_endpoint_companion_descriptor *ep_comp) -{ - free(ep_comp); -} - -static int parse_bos(struct libusb_context *ctx, - struct libusb_bos_descriptor **bos, - unsigned char *buffer, int size, int host_endian) -{ - struct libusb_bos_descriptor bos_header, *_bos; - struct libusb_bos_dev_capability_descriptor dev_cap; - int i; - - if (size < LIBUSB_DT_BOS_SIZE) { - usbi_err(ctx, "short bos descriptor read %d/%d", - size, LIBUSB_DT_BOS_SIZE); - return LIBUSB_ERROR_IO; - } - - usbi_parse_descriptor(buffer, "bbwb", &bos_header, host_endian); - if (bos_header.bDescriptorType != LIBUSB_DT_BOS) { - usbi_err(ctx, "unexpected descriptor %x (expected %x)", - bos_header.bDescriptorType, LIBUSB_DT_BOS); - return LIBUSB_ERROR_IO; - } - if (bos_header.bLength < LIBUSB_DT_BOS_SIZE) { - usbi_err(ctx, "invalid bos bLength (%d)", bos_header.bLength); - return LIBUSB_ERROR_IO; - } - if (bos_header.bLength > size) { - usbi_err(ctx, "short bos descriptor read %d/%d", - size, bos_header.bLength); - return LIBUSB_ERROR_IO; - } - - _bos = calloc (1, - sizeof(*_bos) + bos_header.bNumDeviceCaps * sizeof(void *)); - if (!_bos) - return LIBUSB_ERROR_NO_MEM; - - usbi_parse_descriptor(buffer, "bbwb", _bos, host_endian); - buffer += bos_header.bLength; - size -= bos_header.bLength; - - /* Get the device capability descriptors */ - for (i = 0; i < bos_header.bNumDeviceCaps; i++) { - if (size < LIBUSB_DT_DEVICE_CAPABILITY_SIZE) { - usbi_warn(ctx, "short dev-cap descriptor read %d/%d", - size, LIBUSB_DT_DEVICE_CAPABILITY_SIZE); - break; - } - usbi_parse_descriptor(buffer, "bbb", &dev_cap, host_endian); - if (dev_cap.bDescriptorType != LIBUSB_DT_DEVICE_CAPABILITY) { - usbi_warn(ctx, "unexpected descriptor %x (expected %x)", - dev_cap.bDescriptorType, LIBUSB_DT_DEVICE_CAPABILITY); - break; - } - if (dev_cap.bLength < LIBUSB_DT_DEVICE_CAPABILITY_SIZE) { - usbi_err(ctx, "invalid dev-cap bLength (%d)", - dev_cap.bLength); - libusb_free_bos_descriptor(_bos); - return LIBUSB_ERROR_IO; - } - if (dev_cap.bLength > size) { - usbi_warn(ctx, "short dev-cap descriptor read %d/%d", - size, dev_cap.bLength); - break; - } - - _bos->dev_capability[i] = malloc(dev_cap.bLength); - if (!_bos->dev_capability[i]) { - libusb_free_bos_descriptor(_bos); - return LIBUSB_ERROR_NO_MEM; - } - memcpy(_bos->dev_capability[i], buffer, dev_cap.bLength); - buffer += dev_cap.bLength; - size -= dev_cap.bLength; - } - _bos->bNumDeviceCaps = (uint8_t)i; - *bos = _bos; - - return LIBUSB_SUCCESS; -} - -/** \ingroup libusb_desc - * Get a Binary Object Store (BOS) descriptor - * This is a BLOCKING function, which will send requests to the device. - * - * \param dev_handle the handle of an open libusb device - * \param bos output location for the BOS descriptor. Only valid if 0 was returned. - * Must be freed with \ref libusb_free_bos_descriptor() after use. - * \returns 0 on success - * \returns LIBUSB_ERROR_NOT_FOUND if the device doesn't have a BOS descriptor - * \returns another LIBUSB_ERROR code on error - */ -int API_EXPORTED libusb_get_bos_descriptor(libusb_device_handle *dev_handle, - struct libusb_bos_descriptor **bos) -{ - struct libusb_bos_descriptor _bos; - uint8_t bos_header[LIBUSB_DT_BOS_SIZE] = {0}; - unsigned char *bos_data = NULL; - const int host_endian = 0; - int r; - - /* Read the BOS. This generates 2 requests on the bus, - * one for the header, and one for the full BOS */ - r = libusb_get_descriptor(dev_handle, LIBUSB_DT_BOS, 0, bos_header, - LIBUSB_DT_BOS_SIZE); - if (r < 0) { - if (r != LIBUSB_ERROR_PIPE) - usbi_err(HANDLE_CTX(dev_handle), "failed to read BOS (%d)", r); - return r; - } - if (r < LIBUSB_DT_BOS_SIZE) { - usbi_err(HANDLE_CTX(dev_handle), "short BOS read %d/%d", - r, LIBUSB_DT_BOS_SIZE); - return LIBUSB_ERROR_IO; - } - - usbi_parse_descriptor(bos_header, "bbwb", &_bos, host_endian); - usbi_dbg("found BOS descriptor: size %d bytes, %d capabilities", - _bos.wTotalLength, _bos.bNumDeviceCaps); - bos_data = calloc(_bos.wTotalLength, 1); - if (bos_data == NULL) - return LIBUSB_ERROR_NO_MEM; - - r = libusb_get_descriptor(dev_handle, LIBUSB_DT_BOS, 0, bos_data, - _bos.wTotalLength); - if (r >= 0) - r = parse_bos(HANDLE_CTX(dev_handle), bos, bos_data, r, host_endian); - else - usbi_err(HANDLE_CTX(dev_handle), "failed to read BOS (%d)", r); - - free(bos_data); - return r; -} - -/** \ingroup libusb_desc - * Free a BOS descriptor obtained from libusb_get_bos_descriptor(). - * It is safe to call this function with a NULL bos parameter, in which - * case the function simply returns. - * - * \param bos the BOS descriptor to free - */ -void API_EXPORTED libusb_free_bos_descriptor(struct libusb_bos_descriptor *bos) -{ - int i; - - if (!bos) - return; - - for (i = 0; i < bos->bNumDeviceCaps; i++) - free(bos->dev_capability[i]); - free(bos); -} - -/** \ingroup libusb_desc - * Get an USB 2.0 Extension descriptor - * - * \param ctx the context to operate on, or NULL for the default context - * \param dev_cap Device Capability descriptor with a bDevCapabilityType of - * \ref libusb_capability_type::LIBUSB_BT_USB_2_0_EXTENSION - * LIBUSB_BT_USB_2_0_EXTENSION - * \param usb_2_0_extension output location for the USB 2.0 Extension - * descriptor. Only valid if 0 was returned. Must be freed with - * libusb_free_usb_2_0_extension_descriptor() after use. - * \returns 0 on success - * \returns a LIBUSB_ERROR code on error - */ -int API_EXPORTED libusb_get_usb_2_0_extension_descriptor( - struct libusb_context *ctx, - struct libusb_bos_dev_capability_descriptor *dev_cap, - struct libusb_usb_2_0_extension_descriptor **usb_2_0_extension) -{ - struct libusb_usb_2_0_extension_descriptor *_usb_2_0_extension; - const int host_endian = 0; - - if (dev_cap->bDevCapabilityType != LIBUSB_BT_USB_2_0_EXTENSION) { - usbi_err(ctx, "unexpected bDevCapabilityType %x (expected %x)", - dev_cap->bDevCapabilityType, - LIBUSB_BT_USB_2_0_EXTENSION); - return LIBUSB_ERROR_INVALID_PARAM; - } - if (dev_cap->bLength < LIBUSB_BT_USB_2_0_EXTENSION_SIZE) { - usbi_err(ctx, "short dev-cap descriptor read %d/%d", - dev_cap->bLength, LIBUSB_BT_USB_2_0_EXTENSION_SIZE); - return LIBUSB_ERROR_IO; - } - - _usb_2_0_extension = malloc(sizeof(*_usb_2_0_extension)); - if (!_usb_2_0_extension) - return LIBUSB_ERROR_NO_MEM; - - usbi_parse_descriptor((unsigned char *)dev_cap, "bbbd", - _usb_2_0_extension, host_endian); - - *usb_2_0_extension = _usb_2_0_extension; - return LIBUSB_SUCCESS; -} - -/** \ingroup libusb_desc - * Free a USB 2.0 Extension descriptor obtained from - * libusb_get_usb_2_0_extension_descriptor(). - * It is safe to call this function with a NULL usb_2_0_extension parameter, - * in which case the function simply returns. - * - * \param usb_2_0_extension the USB 2.0 Extension descriptor to free - */ -void API_EXPORTED libusb_free_usb_2_0_extension_descriptor( - struct libusb_usb_2_0_extension_descriptor *usb_2_0_extension) -{ - free(usb_2_0_extension); -} - -/** \ingroup libusb_desc - * Get a SuperSpeed USB Device Capability descriptor - * - * \param ctx the context to operate on, or NULL for the default context - * \param dev_cap Device Capability descriptor with a bDevCapabilityType of - * \ref libusb_capability_type::LIBUSB_BT_SS_USB_DEVICE_CAPABILITY - * LIBUSB_BT_SS_USB_DEVICE_CAPABILITY - * \param ss_usb_device_cap output location for the SuperSpeed USB Device - * Capability descriptor. Only valid if 0 was returned. Must be freed with - * libusb_free_ss_usb_device_capability_descriptor() after use. - * \returns 0 on success - * \returns a LIBUSB_ERROR code on error - */ -int API_EXPORTED libusb_get_ss_usb_device_capability_descriptor( - struct libusb_context *ctx, - struct libusb_bos_dev_capability_descriptor *dev_cap, - struct libusb_ss_usb_device_capability_descriptor **ss_usb_device_cap) -{ - struct libusb_ss_usb_device_capability_descriptor *_ss_usb_device_cap; - const int host_endian = 0; - - if (dev_cap->bDevCapabilityType != LIBUSB_BT_SS_USB_DEVICE_CAPABILITY) { - usbi_err(ctx, "unexpected bDevCapabilityType %x (expected %x)", - dev_cap->bDevCapabilityType, - LIBUSB_BT_SS_USB_DEVICE_CAPABILITY); - return LIBUSB_ERROR_INVALID_PARAM; - } - if (dev_cap->bLength < LIBUSB_BT_SS_USB_DEVICE_CAPABILITY_SIZE) { - usbi_err(ctx, "short dev-cap descriptor read %d/%d", - dev_cap->bLength, LIBUSB_BT_SS_USB_DEVICE_CAPABILITY_SIZE); - return LIBUSB_ERROR_IO; - } - - _ss_usb_device_cap = malloc(sizeof(*_ss_usb_device_cap)); - if (!_ss_usb_device_cap) - return LIBUSB_ERROR_NO_MEM; - - usbi_parse_descriptor((unsigned char *)dev_cap, "bbbbwbbw", - _ss_usb_device_cap, host_endian); - - *ss_usb_device_cap = _ss_usb_device_cap; - return LIBUSB_SUCCESS; -} - -/** \ingroup libusb_desc - * Free a SuperSpeed USB Device Capability descriptor obtained from - * libusb_get_ss_usb_device_capability_descriptor(). - * It is safe to call this function with a NULL ss_usb_device_cap - * parameter, in which case the function simply returns. - * - * \param ss_usb_device_cap the USB 2.0 Extension descriptor to free - */ -void API_EXPORTED libusb_free_ss_usb_device_capability_descriptor( - struct libusb_ss_usb_device_capability_descriptor *ss_usb_device_cap) -{ - free(ss_usb_device_cap); -} - -/** \ingroup libusb_desc - * Get a Container ID descriptor - * - * \param ctx the context to operate on, or NULL for the default context - * \param dev_cap Device Capability descriptor with a bDevCapabilityType of - * \ref libusb_capability_type::LIBUSB_BT_CONTAINER_ID - * LIBUSB_BT_CONTAINER_ID - * \param container_id output location for the Container ID descriptor. - * Only valid if 0 was returned. Must be freed with - * libusb_free_container_id_descriptor() after use. - * \returns 0 on success - * \returns a LIBUSB_ERROR code on error - */ -int API_EXPORTED libusb_get_container_id_descriptor(struct libusb_context *ctx, - struct libusb_bos_dev_capability_descriptor *dev_cap, - struct libusb_container_id_descriptor **container_id) -{ - struct libusb_container_id_descriptor *_container_id; - const int host_endian = 0; - - if (dev_cap->bDevCapabilityType != LIBUSB_BT_CONTAINER_ID) { - usbi_err(ctx, "unexpected bDevCapabilityType %x (expected %x)", - dev_cap->bDevCapabilityType, - LIBUSB_BT_CONTAINER_ID); - return LIBUSB_ERROR_INVALID_PARAM; - } - if (dev_cap->bLength < LIBUSB_BT_CONTAINER_ID_SIZE) { - usbi_err(ctx, "short dev-cap descriptor read %d/%d", - dev_cap->bLength, LIBUSB_BT_CONTAINER_ID_SIZE); - return LIBUSB_ERROR_IO; - } - - _container_id = malloc(sizeof(*_container_id)); - if (!_container_id) - return LIBUSB_ERROR_NO_MEM; - - usbi_parse_descriptor((unsigned char *)dev_cap, "bbbbu", - _container_id, host_endian); - - *container_id = _container_id; - return LIBUSB_SUCCESS; -} - -/** \ingroup libusb_desc - * Free a Container ID descriptor obtained from - * libusb_get_container_id_descriptor(). - * It is safe to call this function with a NULL container_id parameter, - * in which case the function simply returns. - * - * \param container_id the USB 2.0 Extension descriptor to free - */ -void API_EXPORTED libusb_free_container_id_descriptor( - struct libusb_container_id_descriptor *container_id) -{ - free(container_id); -} - -/** \ingroup libusb_desc - * Retrieve a string descriptor in C style ASCII. - * - * Wrapper around libusb_get_string_descriptor(). Uses the first language - * supported by the device. - * - * \param dev_handle a device handle - * \param desc_index the index of the descriptor to retrieve - * \param data output buffer for ASCII string descriptor - * \param length size of data buffer - * \returns number of bytes returned in data, or LIBUSB_ERROR code on failure - */ -int API_EXPORTED libusb_get_string_descriptor_ascii(libusb_device_handle *dev_handle, - uint8_t desc_index, unsigned char *data, int length) -{ - unsigned char tbuf[255]; /* Some devices choke on size > 255 */ - int r, si, di; - uint16_t langid; - - /* Asking for the zero'th index is special - it returns a string - * descriptor that contains all the language IDs supported by the - * device. Typically there aren't many - often only one. Language - * IDs are 16 bit numbers, and they start at the third byte in the - * descriptor. There's also no point in trying to read descriptor 0 - * with this function. See USB 2.0 specification section 9.6.7 for - * more information. - */ - - if (desc_index == 0) - return LIBUSB_ERROR_INVALID_PARAM; - - r = libusb_get_string_descriptor(dev_handle, 0, 0, tbuf, sizeof(tbuf)); - if (r < 0) - return r; - - if (r < 4) - return LIBUSB_ERROR_IO; - - langid = tbuf[2] | (tbuf[3] << 8); - - r = libusb_get_string_descriptor(dev_handle, desc_index, langid, tbuf, - sizeof(tbuf)); - if (r < 0) - return r; - - if (tbuf[1] != LIBUSB_DT_STRING) - return LIBUSB_ERROR_IO; - - if (tbuf[0] > r) - return LIBUSB_ERROR_IO; - - for (di = 0, si = 2; si < tbuf[0]; si += 2) { - if (di >= (length - 1)) - break; - - if ((tbuf[si] & 0x80) || (tbuf[si + 1])) /* non-ASCII */ - data[di++] = '?'; - else - data[di++] = tbuf[si]; - } - - data[di] = 0; - return di; -} diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/hotplug.c b/vendor/github.com/karalabe/hid/libusb/libusb/hotplug.c deleted file mode 100644 index bbfd6e79..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/hotplug.c +++ /dev/null @@ -1,350 +0,0 @@ -/* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */ -/* - * Hotplug functions for libusb - * Copyright © 2012-2013 Nathan Hjelm - * Copyright © 2012-2013 Peter Stuge - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include - -#include -#include -#include -#include -#ifdef HAVE_SYS_TYPES_H -#include -#endif -#include - -#include "libusbi.h" -#include "hotplug.h" - -/** - * @defgroup libusb_hotplug Device hotplug event notification - * This page details how to use the libusb hotplug interface, where available. - * - * Be mindful that not all platforms currently implement hotplug notification and - * that you should first call on \ref libusb_has_capability() with parameter - * \ref LIBUSB_CAP_HAS_HOTPLUG to confirm that hotplug support is available. - * - * \page libusb_hotplug Device hotplug event notification - * - * \section hotplug_intro Introduction - * - * Version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102, has added support - * for hotplug events on some platforms (you should test if your platform - * supports hotplug notification by calling \ref libusb_has_capability() with - * parameter \ref LIBUSB_CAP_HAS_HOTPLUG). - * - * This interface allows you to request notification for the arrival and departure - * of matching USB devices. - * - * To receive hotplug notification you register a callback by calling - * \ref libusb_hotplug_register_callback(). This function will optionally return - * a callback handle that can be passed to \ref libusb_hotplug_deregister_callback(). - * - * A callback function must return an int (0 or 1) indicating whether the callback is - * expecting additional events. Returning 0 will rearm the callback and 1 will cause - * the callback to be deregistered. Note that when callbacks are called from - * libusb_hotplug_register_callback() because of the \ref LIBUSB_HOTPLUG_ENUMERATE - * flag, the callback return value is ignored, iow you cannot cause a callback - * to be deregistered by returning 1 when it is called from - * libusb_hotplug_register_callback(). - * - * Callbacks for a particular context are automatically deregistered by libusb_exit(). - * - * As of 1.0.16 there are two supported hotplug events: - * - LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED: A device has arrived and is ready to use - * - LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT: A device has left and is no longer available - * - * A hotplug event can listen for either or both of these events. - * - * Note: If you receive notification that a device has left and you have any - * a libusb_device_handles for the device it is up to you to call libusb_close() - * on each device handle to free up any remaining resources associated with the device. - * Once a device has left any libusb_device_handle associated with the device - * are invalid and will remain so even if the device comes back. - * - * When handling a LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED event it is considered - * safe to call any libusb function that takes a libusb_device. It also safe to - * open a device and submit asynchronous transfers. However, most other functions - * that take a libusb_device_handle are not safe to call. Examples of such - * functions are any of the \ref libusb_syncio "synchronous API" functions or the blocking - * functions that retrieve various \ref libusb_desc "USB descriptors". These functions must - * be used outside of the context of the hotplug callback. - * - * When handling a LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT event the only safe function - * is libusb_get_device_descriptor(). - * - * The following code provides an example of the usage of the hotplug interface: -\code -#include -#include -#include -#include - -static int count = 0; - -int hotplug_callback(struct libusb_context *ctx, struct libusb_device *dev, - libusb_hotplug_event event, void *user_data) { - static libusb_device_handle *dev_handle = NULL; - struct libusb_device_descriptor desc; - int rc; - - (void)libusb_get_device_descriptor(dev, &desc); - - if (LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED == event) { - rc = libusb_open(dev, &dev_handle); - if (LIBUSB_SUCCESS != rc) { - printf("Could not open USB device\n"); - } - } else if (LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT == event) { - if (dev_handle) { - libusb_close(dev_handle); - dev_handle = NULL; - } - } else { - printf("Unhandled event %d\n", event); - } - count++; - - return 0; -} - -int main (void) { - libusb_hotplug_callback_handle callback_handle; - int rc; - - libusb_init(NULL); - - rc = libusb_hotplug_register_callback(NULL, LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED | - LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT, 0, 0x045a, 0x5005, - LIBUSB_HOTPLUG_MATCH_ANY, hotplug_callback, NULL, - &callback_handle); - if (LIBUSB_SUCCESS != rc) { - printf("Error creating a hotplug callback\n"); - libusb_exit(NULL); - return EXIT_FAILURE; - } - - while (count < 2) { - libusb_handle_events_completed(NULL, NULL); - nanosleep(&(struct timespec){0, 10000000UL}, NULL); - } - - libusb_hotplug_deregister_callback(NULL, callback_handle); - libusb_exit(NULL); - - return 0; -} -\endcode - */ - -static int usbi_hotplug_match_cb (struct libusb_context *ctx, - struct libusb_device *dev, libusb_hotplug_event event, - struct libusb_hotplug_callback *hotplug_cb) -{ - /* Handle lazy deregistration of callback */ - if (hotplug_cb->needs_free) { - /* Free callback */ - return 1; - } - - if (!(hotplug_cb->events & event)) { - return 0; - } - - if (LIBUSB_HOTPLUG_MATCH_ANY != hotplug_cb->vendor_id && - hotplug_cb->vendor_id != dev->device_descriptor.idVendor) { - return 0; - } - - if (LIBUSB_HOTPLUG_MATCH_ANY != hotplug_cb->product_id && - hotplug_cb->product_id != dev->device_descriptor.idProduct) { - return 0; - } - - if (LIBUSB_HOTPLUG_MATCH_ANY != hotplug_cb->dev_class && - hotplug_cb->dev_class != dev->device_descriptor.bDeviceClass) { - return 0; - } - - return hotplug_cb->cb (ctx, dev, event, hotplug_cb->user_data); -} - -void usbi_hotplug_match(struct libusb_context *ctx, struct libusb_device *dev, - libusb_hotplug_event event) -{ - struct libusb_hotplug_callback *hotplug_cb, *next; - int ret; - - usbi_mutex_lock(&ctx->hotplug_cbs_lock); - - list_for_each_entry_safe(hotplug_cb, next, &ctx->hotplug_cbs, list, struct libusb_hotplug_callback) { - usbi_mutex_unlock(&ctx->hotplug_cbs_lock); - ret = usbi_hotplug_match_cb (ctx, dev, event, hotplug_cb); - usbi_mutex_lock(&ctx->hotplug_cbs_lock); - - if (ret) { - list_del(&hotplug_cb->list); - free(hotplug_cb); - } - } - - usbi_mutex_unlock(&ctx->hotplug_cbs_lock); - - /* the backend is expected to call the callback for each active transfer */ -} - -void usbi_hotplug_notification(struct libusb_context *ctx, struct libusb_device *dev, - libusb_hotplug_event event) -{ - int pending_events; - libusb_hotplug_message *message = calloc(1, sizeof(*message)); - - if (!message) { - usbi_err(ctx, "error allocating hotplug message"); - return; - } - - message->event = event; - message->device = dev; - - /* Take the event data lock and add this message to the list. - * Only signal an event if there are no prior pending events. */ - usbi_mutex_lock(&ctx->event_data_lock); - pending_events = usbi_pending_events(ctx); - list_add_tail(&message->list, &ctx->hotplug_msgs); - if (!pending_events) - usbi_signal_event(ctx); - usbi_mutex_unlock(&ctx->event_data_lock); -} - -int API_EXPORTED libusb_hotplug_register_callback(libusb_context *ctx, - libusb_hotplug_event events, libusb_hotplug_flag flags, - int vendor_id, int product_id, int dev_class, - libusb_hotplug_callback_fn cb_fn, void *user_data, - libusb_hotplug_callback_handle *callback_handle) -{ - libusb_hotplug_callback *new_callback; - static int handle_id = 1; - - /* check for hotplug support */ - if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) { - return LIBUSB_ERROR_NOT_SUPPORTED; - } - - /* check for sane values */ - if ((LIBUSB_HOTPLUG_MATCH_ANY != vendor_id && (~0xffff & vendor_id)) || - (LIBUSB_HOTPLUG_MATCH_ANY != product_id && (~0xffff & product_id)) || - (LIBUSB_HOTPLUG_MATCH_ANY != dev_class && (~0xff & dev_class)) || - !cb_fn) { - return LIBUSB_ERROR_INVALID_PARAM; - } - - USBI_GET_CONTEXT(ctx); - - new_callback = (libusb_hotplug_callback *)calloc(1, sizeof (*new_callback)); - if (!new_callback) { - return LIBUSB_ERROR_NO_MEM; - } - - new_callback->ctx = ctx; - new_callback->vendor_id = vendor_id; - new_callback->product_id = product_id; - new_callback->dev_class = dev_class; - new_callback->flags = flags; - new_callback->events = events; - new_callback->cb = cb_fn; - new_callback->user_data = user_data; - new_callback->needs_free = 0; - - usbi_mutex_lock(&ctx->hotplug_cbs_lock); - - /* protect the handle by the context hotplug lock. it doesn't matter if the same handle - * is used for different contexts only that the handle is unique for this context */ - new_callback->handle = handle_id++; - - list_add(&new_callback->list, &ctx->hotplug_cbs); - - usbi_mutex_unlock(&ctx->hotplug_cbs_lock); - - - if (flags & LIBUSB_HOTPLUG_ENUMERATE) { - int i, len; - struct libusb_device **devs; - - len = (int) libusb_get_device_list(ctx, &devs); - if (len < 0) { - libusb_hotplug_deregister_callback(ctx, - new_callback->handle); - return len; - } - - for (i = 0; i < len; i++) { - usbi_hotplug_match_cb(ctx, devs[i], - LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED, - new_callback); - } - - libusb_free_device_list(devs, 1); - } - - - if (callback_handle) - *callback_handle = new_callback->handle; - - return LIBUSB_SUCCESS; -} - -void API_EXPORTED libusb_hotplug_deregister_callback (struct libusb_context *ctx, - libusb_hotplug_callback_handle callback_handle) -{ - struct libusb_hotplug_callback *hotplug_cb; - - /* check for hotplug support */ - if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) { - return; - } - - USBI_GET_CONTEXT(ctx); - - usbi_mutex_lock(&ctx->hotplug_cbs_lock); - list_for_each_entry(hotplug_cb, &ctx->hotplug_cbs, list, - struct libusb_hotplug_callback) { - if (callback_handle == hotplug_cb->handle) { - /* Mark this callback for deregistration */ - hotplug_cb->needs_free = 1; - } - } - usbi_mutex_unlock(&ctx->hotplug_cbs_lock); - - usbi_hotplug_notification(ctx, NULL, 0); -} - -void usbi_hotplug_deregister_all(struct libusb_context *ctx) { - struct libusb_hotplug_callback *hotplug_cb, *next; - - usbi_mutex_lock(&ctx->hotplug_cbs_lock); - list_for_each_entry_safe(hotplug_cb, next, &ctx->hotplug_cbs, list, - struct libusb_hotplug_callback) { - list_del(&hotplug_cb->list); - free(hotplug_cb); - } - - usbi_mutex_unlock(&ctx->hotplug_cbs_lock); -} diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/hotplug.h b/vendor/github.com/karalabe/hid/libusb/libusb/hotplug.h deleted file mode 100644 index 2bec81b0..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/hotplug.h +++ /dev/null @@ -1,90 +0,0 @@ -/* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */ -/* - * Hotplug support for libusb - * Copyright © 2012-2013 Nathan Hjelm - * Copyright © 2012-2013 Peter Stuge - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#if !defined(USBI_HOTPLUG_H) -#define USBI_HOTPLUG_H - -#ifndef LIBUSBI_H -#include "libusbi.h" -#endif - -/** \ingroup hotplug - * The hotplug callback structure. The user populates this structure with - * libusb_hotplug_prepare_callback() and then calls libusb_hotplug_register_callback() - * to receive notification of hotplug events. - */ -struct libusb_hotplug_callback { - /** Context this callback is associated with */ - struct libusb_context *ctx; - - /** Vendor ID to match or LIBUSB_HOTPLUG_MATCH_ANY */ - int vendor_id; - - /** Product ID to match or LIBUSB_HOTPLUG_MATCH_ANY */ - int product_id; - - /** Device class to match or LIBUSB_HOTPLUG_MATCH_ANY */ - int dev_class; - - /** Hotplug callback flags */ - libusb_hotplug_flag flags; - - /** Event(s) that will trigger this callback */ - libusb_hotplug_event events; - - /** Callback function to invoke for matching event/device */ - libusb_hotplug_callback_fn cb; - - /** Handle for this callback (used to match on deregister) */ - libusb_hotplug_callback_handle handle; - - /** User data that will be passed to the callback function */ - void *user_data; - - /** Callback is marked for deletion */ - int needs_free; - - /** List this callback is registered in (ctx->hotplug_cbs) */ - struct list_head list; -}; - -typedef struct libusb_hotplug_callback libusb_hotplug_callback; - -struct libusb_hotplug_message { - /** The hotplug event that occurred */ - libusb_hotplug_event event; - - /** The device for which this hotplug event occurred */ - struct libusb_device *device; - - /** List this message is contained in (ctx->hotplug_msgs) */ - struct list_head list; -}; - -typedef struct libusb_hotplug_message libusb_hotplug_message; - -void usbi_hotplug_deregister_all(struct libusb_context *ctx); -void usbi_hotplug_match(struct libusb_context *ctx, struct libusb_device *dev, - libusb_hotplug_event event); -void usbi_hotplug_notification(struct libusb_context *ctx, struct libusb_device *dev, - libusb_hotplug_event event); - -#endif diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/io.c b/vendor/github.com/karalabe/hid/libusb/libusb/io.c deleted file mode 100644 index eb1eabf1..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/io.c +++ /dev/null @@ -1,2819 +0,0 @@ -/* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */ -/* - * I/O functions for libusb - * Copyright © 2007-2009 Daniel Drake - * Copyright © 2001 Johannes Erdfelt - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include - -#include -#include -#include -#include -#include -#include -#ifdef HAVE_SYS_TIME_H -#include -#endif -#ifdef USBI_TIMERFD_AVAILABLE -#include -#endif - -#include "libusbi.h" -#include "hotplug.h" - -/** - * \page libusb_io Synchronous and asynchronous device I/O - * - * \section io_intro Introduction - * - * If you're using libusb in your application, you're probably wanting to - * perform I/O with devices - you want to perform USB data transfers. - * - * libusb offers two separate interfaces for device I/O. This page aims to - * introduce the two in order to help you decide which one is more suitable - * for your application. You can also choose to use both interfaces in your - * application by considering each transfer on a case-by-case basis. - * - * Once you have read through the following discussion, you should consult the - * detailed API documentation pages for the details: - * - \ref libusb_syncio - * - \ref libusb_asyncio - * - * \section theory Transfers at a logical level - * - * At a logical level, USB transfers typically happen in two parts. For - * example, when reading data from a endpoint: - * -# A request for data is sent to the device - * -# Some time later, the incoming data is received by the host - * - * or when writing data to an endpoint: - * - * -# The data is sent to the device - * -# Some time later, the host receives acknowledgement from the device that - * the data has been transferred. - * - * There may be an indefinite delay between the two steps. Consider a - * fictional USB input device with a button that the user can press. In order - * to determine when the button is pressed, you would likely submit a request - * to read data on a bulk or interrupt endpoint and wait for data to arrive. - * Data will arrive when the button is pressed by the user, which is - * potentially hours later. - * - * libusb offers both a synchronous and an asynchronous interface to performing - * USB transfers. The main difference is that the synchronous interface - * combines both steps indicated above into a single function call, whereas - * the asynchronous interface separates them. - * - * \section sync The synchronous interface - * - * The synchronous I/O interface allows you to perform a USB transfer with - * a single function call. When the function call returns, the transfer has - * completed and you can parse the results. - * - * If you have used the libusb-0.1 before, this I/O style will seem familar to - * you. libusb-0.1 only offered a synchronous interface. - * - * In our input device example, to read button presses you might write code - * in the following style: -\code -unsigned char data[4]; -int actual_length; -int r = libusb_bulk_transfer(dev_handle, LIBUSB_ENDPOINT_IN, data, sizeof(data), &actual_length, 0); -if (r == 0 && actual_length == sizeof(data)) { - // results of the transaction can now be found in the data buffer - // parse them here and report button press -} else { - error(); -} -\endcode - * - * The main advantage of this model is simplicity: you did everything with - * a single simple function call. - * - * However, this interface has its limitations. Your application will sleep - * inside libusb_bulk_transfer() until the transaction has completed. If it - * takes the user 3 hours to press the button, your application will be - * sleeping for that long. Execution will be tied up inside the library - - * the entire thread will be useless for that duration. - * - * Another issue is that by tieing up the thread with that single transaction - * there is no possibility of performing I/O with multiple endpoints and/or - * multiple devices simultaneously, unless you resort to creating one thread - * per transaction. - * - * Additionally, there is no opportunity to cancel the transfer after the - * request has been submitted. - * - * For details on how to use the synchronous API, see the - * \ref libusb_syncio "synchronous I/O API documentation" pages. - * - * \section async The asynchronous interface - * - * Asynchronous I/O is the most significant new feature in libusb-1.0. - * Although it is a more complex interface, it solves all the issues detailed - * above. - * - * Instead of providing which functions that block until the I/O has complete, - * libusb's asynchronous interface presents non-blocking functions which - * begin a transfer and then return immediately. Your application passes a - * callback function pointer to this non-blocking function, which libusb will - * call with the results of the transaction when it has completed. - * - * Transfers which have been submitted through the non-blocking functions - * can be cancelled with a separate function call. - * - * The non-blocking nature of this interface allows you to be simultaneously - * performing I/O to multiple endpoints on multiple devices, without having - * to use threads. - * - * This added flexibility does come with some complications though: - * - In the interest of being a lightweight library, libusb does not create - * threads and can only operate when your application is calling into it. Your - * application must call into libusb from it's main loop when events are ready - * to be handled, or you must use some other scheme to allow libusb to - * undertake whatever work needs to be done. - * - libusb also needs to be called into at certain fixed points in time in - * order to accurately handle transfer timeouts. - * - Memory handling becomes more complex. You cannot use stack memory unless - * the function with that stack is guaranteed not to return until the transfer - * callback has finished executing. - * - You generally lose some linearity from your code flow because submitting - * the transfer request is done in a separate function from where the transfer - * results are handled. This becomes particularly obvious when you want to - * submit a second transfer based on the results of an earlier transfer. - * - * Internally, libusb's synchronous interface is expressed in terms of function - * calls to the asynchronous interface. - * - * For details on how to use the asynchronous API, see the - * \ref libusb_asyncio "asynchronous I/O API" documentation pages. - */ - - -/** - * \page libusb_packetoverflow Packets and overflows - * - * \section packets Packet abstraction - * - * The USB specifications describe how data is transmitted in packets, with - * constraints on packet size defined by endpoint descriptors. The host must - * not send data payloads larger than the endpoint's maximum packet size. - * - * libusb and the underlying OS abstract out the packet concept, allowing you - * to request transfers of any size. Internally, the request will be divided - * up into correctly-sized packets. You do not have to be concerned with - * packet sizes, but there is one exception when considering overflows. - * - * \section overflow Bulk/interrupt transfer overflows - * - * When requesting data on a bulk endpoint, libusb requires you to supply a - * buffer and the maximum number of bytes of data that libusb can put in that - * buffer. However, the size of the buffer is not communicated to the device - - * the device is just asked to send any amount of data. - * - * There is no problem if the device sends an amount of data that is less than - * or equal to the buffer size. libusb reports this condition to you through - * the \ref libusb_transfer::actual_length "libusb_transfer.actual_length" - * field. - * - * Problems may occur if the device attempts to send more data than can fit in - * the buffer. libusb reports LIBUSB_TRANSFER_OVERFLOW for this condition but - * other behaviour is largely undefined: actual_length may or may not be - * accurate, the chunk of data that can fit in the buffer (before overflow) - * may or may not have been transferred. - * - * Overflows are nasty, but can be avoided. Even though you were told to - * ignore packets above, think about the lower level details: each transfer is - * split into packets (typically small, with a maximum size of 512 bytes). - * Overflows can only happen if the final packet in an incoming data transfer - * is smaller than the actual packet that the device wants to transfer. - * Therefore, you will never see an overflow if your transfer buffer size is a - * multiple of the endpoint's packet size: the final packet will either - * fill up completely or will be only partially filled. - */ - -/** - * @defgroup libusb_asyncio Asynchronous device I/O - * - * This page details libusb's asynchronous (non-blocking) API for USB device - * I/O. This interface is very powerful but is also quite complex - you will - * need to read this page carefully to understand the necessary considerations - * and issues surrounding use of this interface. Simplistic applications - * may wish to consider the \ref libusb_syncio "synchronous I/O API" instead. - * - * The asynchronous interface is built around the idea of separating transfer - * submission and handling of transfer completion (the synchronous model - * combines both of these into one). There may be a long delay between - * submission and completion, however the asynchronous submission function - * is non-blocking so will return control to your application during that - * potentially long delay. - * - * \section asyncabstraction Transfer abstraction - * - * For the asynchronous I/O, libusb implements the concept of a generic - * transfer entity for all types of I/O (control, bulk, interrupt, - * isochronous). The generic transfer object must be treated slightly - * differently depending on which type of I/O you are performing with it. - * - * This is represented by the public libusb_transfer structure type. - * - * \section asynctrf Asynchronous transfers - * - * We can view asynchronous I/O as a 5 step process: - * -# Allocation: allocate a libusb_transfer - * -# Filling: populate the libusb_transfer instance with information - * about the transfer you wish to perform - * -# Submission: ask libusb to submit the transfer - * -# Completion handling: examine transfer results in the - * libusb_transfer structure - * -# Deallocation: clean up resources - * - * - * \subsection asyncalloc Allocation - * - * This step involves allocating memory for a USB transfer. This is the - * generic transfer object mentioned above. At this stage, the transfer - * is "blank" with no details about what type of I/O it will be used for. - * - * Allocation is done with the libusb_alloc_transfer() function. You must use - * this function rather than allocating your own transfers. - * - * \subsection asyncfill Filling - * - * This step is where you take a previously allocated transfer and fill it - * with information to determine the message type and direction, data buffer, - * callback function, etc. - * - * You can either fill the required fields yourself or you can use the - * helper functions: libusb_fill_control_transfer(), libusb_fill_bulk_transfer() - * and libusb_fill_interrupt_transfer(). - * - * \subsection asyncsubmit Submission - * - * When you have allocated a transfer and filled it, you can submit it using - * libusb_submit_transfer(). This function returns immediately but can be - * regarded as firing off the I/O request in the background. - * - * \subsection asynccomplete Completion handling - * - * After a transfer has been submitted, one of four things can happen to it: - * - * - The transfer completes (i.e. some data was transferred) - * - The transfer has a timeout and the timeout expires before all data is - * transferred - * - The transfer fails due to an error - * - The transfer is cancelled - * - * Each of these will cause the user-specified transfer callback function to - * be invoked. It is up to the callback function to determine which of the - * above actually happened and to act accordingly. - * - * The user-specified callback is passed a pointer to the libusb_transfer - * structure which was used to setup and submit the transfer. At completion - * time, libusb has populated this structure with results of the transfer: - * success or failure reason, number of bytes of data transferred, etc. See - * the libusb_transfer structure documentation for more information. - * - * Important Note: The user-specified callback is called from an event - * handling context. It is therefore important that no calls are made into - * libusb that will attempt to perform any event handling. Examples of such - * functions are any listed in the \ref libusb_syncio "synchronous API" and any of - * the blocking functions that retrieve \ref libusb_desc "USB descriptors". - * - * \subsection Deallocation - * - * When a transfer has completed (i.e. the callback function has been invoked), - * you are advised to free the transfer (unless you wish to resubmit it, see - * below). Transfers are deallocated with libusb_free_transfer(). - * - * It is undefined behaviour to free a transfer which has not completed. - * - * \section asyncresubmit Resubmission - * - * You may be wondering why allocation, filling, and submission are all - * separated above where they could reasonably be combined into a single - * operation. - * - * The reason for separation is to allow you to resubmit transfers without - * having to allocate new ones every time. This is especially useful for - * common situations dealing with interrupt endpoints - you allocate one - * transfer, fill and submit it, and when it returns with results you just - * resubmit it for the next interrupt. - * - * \section asynccancel Cancellation - * - * Another advantage of using the asynchronous interface is that you have - * the ability to cancel transfers which have not yet completed. This is - * done by calling the libusb_cancel_transfer() function. - * - * libusb_cancel_transfer() is asynchronous/non-blocking in itself. When the - * cancellation actually completes, the transfer's callback function will - * be invoked, and the callback function should check the transfer status to - * determine that it was cancelled. - * - * Freeing the transfer after it has been cancelled but before cancellation - * has completed will result in undefined behaviour. - * - * When a transfer is cancelled, some of the data may have been transferred. - * libusb will communicate this to you in the transfer callback. Do not assume - * that no data was transferred. - * - * \section bulk_overflows Overflows on device-to-host bulk/interrupt endpoints - * - * If your device does not have predictable transfer sizes (or it misbehaves), - * your application may submit a request for data on an IN endpoint which is - * smaller than the data that the device wishes to send. In some circumstances - * this will cause an overflow, which is a nasty condition to deal with. See - * the \ref libusb_packetoverflow page for discussion. - * - * \section asyncctrl Considerations for control transfers - * - * The libusb_transfer structure is generic and hence does not - * include specific fields for the control-specific setup packet structure. - * - * In order to perform a control transfer, you must place the 8-byte setup - * packet at the start of the data buffer. To simplify this, you could - * cast the buffer pointer to type struct libusb_control_setup, or you can - * use the helper function libusb_fill_control_setup(). - * - * The wLength field placed in the setup packet must be the length you would - * expect to be sent in the setup packet: the length of the payload that - * follows (or the expected maximum number of bytes to receive). However, - * the length field of the libusb_transfer object must be the length of - * the data buffer - i.e. it should be wLength plus the size of - * the setup packet (LIBUSB_CONTROL_SETUP_SIZE). - * - * If you use the helper functions, this is simplified for you: - * -# Allocate a buffer of size LIBUSB_CONTROL_SETUP_SIZE plus the size of the - * data you are sending/requesting. - * -# Call libusb_fill_control_setup() on the data buffer, using the transfer - * request size as the wLength value (i.e. do not include the extra space you - * allocated for the control setup). - * -# If this is a host-to-device transfer, place the data to be transferred - * in the data buffer, starting at offset LIBUSB_CONTROL_SETUP_SIZE. - * -# Call libusb_fill_control_transfer() to associate the data buffer with - * the transfer (and to set the remaining details such as callback and timeout). - * - Note that there is no parameter to set the length field of the transfer. - * The length is automatically inferred from the wLength field of the setup - * packet. - * -# Submit the transfer. - * - * The multi-byte control setup fields (wValue, wIndex and wLength) must - * be given in little-endian byte order (the endianness of the USB bus). - * Endianness conversion is transparently handled by - * libusb_fill_control_setup() which is documented to accept host-endian - * values. - * - * Further considerations are needed when handling transfer completion in - * your callback function: - * - As you might expect, the setup packet will still be sitting at the start - * of the data buffer. - * - If this was a device-to-host transfer, the received data will be sitting - * at offset LIBUSB_CONTROL_SETUP_SIZE into the buffer. - * - The actual_length field of the transfer structure is relative to the - * wLength of the setup packet, rather than the size of the data buffer. So, - * if your wLength was 4, your transfer's length was 12, then you - * should expect an actual_length of 4 to indicate that the data was - * transferred in entirity. - * - * To simplify parsing of setup packets and obtaining the data from the - * correct offset, you may wish to use the libusb_control_transfer_get_data() - * and libusb_control_transfer_get_setup() functions within your transfer - * callback. - * - * Even though control endpoints do not halt, a completed control transfer - * may have a LIBUSB_TRANSFER_STALL status code. This indicates the control - * request was not supported. - * - * \section asyncintr Considerations for interrupt transfers - * - * All interrupt transfers are performed using the polling interval presented - * by the bInterval value of the endpoint descriptor. - * - * \section asynciso Considerations for isochronous transfers - * - * Isochronous transfers are more complicated than transfers to - * non-isochronous endpoints. - * - * To perform I/O to an isochronous endpoint, allocate the transfer by calling - * libusb_alloc_transfer() with an appropriate number of isochronous packets. - * - * During filling, set \ref libusb_transfer::type "type" to - * \ref libusb_transfer_type::LIBUSB_TRANSFER_TYPE_ISOCHRONOUS - * "LIBUSB_TRANSFER_TYPE_ISOCHRONOUS", and set - * \ref libusb_transfer::num_iso_packets "num_iso_packets" to a value less than - * or equal to the number of packets you requested during allocation. - * libusb_alloc_transfer() does not set either of these fields for you, given - * that you might not even use the transfer on an isochronous endpoint. - * - * Next, populate the length field for the first num_iso_packets entries in - * the \ref libusb_transfer::iso_packet_desc "iso_packet_desc" array. Section - * 5.6.3 of the USB2 specifications describe how the maximum isochronous - * packet length is determined by the wMaxPacketSize field in the endpoint - * descriptor. - * Two functions can help you here: - * - * - libusb_get_max_iso_packet_size() is an easy way to determine the max - * packet size for an isochronous endpoint. Note that the maximum packet - * size is actually the maximum number of bytes that can be transmitted in - * a single microframe, therefore this function multiplies the maximum number - * of bytes per transaction by the number of transaction opportunities per - * microframe. - * - libusb_set_iso_packet_lengths() assigns the same length to all packets - * within a transfer, which is usually what you want. - * - * For outgoing transfers, you'll obviously fill the buffer and populate the - * packet descriptors in hope that all the data gets transferred. For incoming - * transfers, you must ensure the buffer has sufficient capacity for - * the situation where all packets transfer the full amount of requested data. - * - * Completion handling requires some extra consideration. The - * \ref libusb_transfer::actual_length "actual_length" field of the transfer - * is meaningless and should not be examined; instead you must refer to the - * \ref libusb_iso_packet_descriptor::actual_length "actual_length" field of - * each individual packet. - * - * The \ref libusb_transfer::status "status" field of the transfer is also a - * little misleading: - * - If the packets were submitted and the isochronous data microframes - * completed normally, status will have value - * \ref libusb_transfer_status::LIBUSB_TRANSFER_COMPLETED - * "LIBUSB_TRANSFER_COMPLETED". Note that bus errors and software-incurred - * delays are not counted as transfer errors; the transfer.status field may - * indicate COMPLETED even if some or all of the packets failed. Refer to - * the \ref libusb_iso_packet_descriptor::status "status" field of each - * individual packet to determine packet failures. - * - The status field will have value - * \ref libusb_transfer_status::LIBUSB_TRANSFER_ERROR - * "LIBUSB_TRANSFER_ERROR" only when serious errors were encountered. - * - Other transfer status codes occur with normal behaviour. - * - * The data for each packet will be found at an offset into the buffer that - * can be calculated as if each prior packet completed in full. The - * libusb_get_iso_packet_buffer() and libusb_get_iso_packet_buffer_simple() - * functions may help you here. - * - * Note: Some operating systems (e.g. Linux) may impose limits on the - * length of individual isochronous packets and/or the total length of the - * isochronous transfer. Such limits can be difficult for libusb to detect, - * so the library will simply try and submit the transfer as set up by you. - * If the transfer fails to submit because it is too large, - * libusb_submit_transfer() will return - * \ref libusb_error::LIBUSB_ERROR_INVALID_PARAM "LIBUSB_ERROR_INVALID_PARAM". - * - * \section asyncmem Memory caveats - * - * In most circumstances, it is not safe to use stack memory for transfer - * buffers. This is because the function that fired off the asynchronous - * transfer may return before libusb has finished using the buffer, and when - * the function returns it's stack gets destroyed. This is true for both - * host-to-device and device-to-host transfers. - * - * The only case in which it is safe to use stack memory is where you can - * guarantee that the function owning the stack space for the buffer does not - * return until after the transfer's callback function has completed. In every - * other case, you need to use heap memory instead. - * - * \section asyncflags Fine control - * - * Through using this asynchronous interface, you may find yourself repeating - * a few simple operations many times. You can apply a bitwise OR of certain - * flags to a transfer to simplify certain things: - * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_SHORT_NOT_OK - * "LIBUSB_TRANSFER_SHORT_NOT_OK" results in transfers which transferred - * less than the requested amount of data being marked with status - * \ref libusb_transfer_status::LIBUSB_TRANSFER_ERROR "LIBUSB_TRANSFER_ERROR" - * (they would normally be regarded as COMPLETED) - * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_BUFFER - * "LIBUSB_TRANSFER_FREE_BUFFER" allows you to ask libusb to free the transfer - * buffer when freeing the transfer. - * - \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_TRANSFER - * "LIBUSB_TRANSFER_FREE_TRANSFER" causes libusb to automatically free the - * transfer after the transfer callback returns. - * - * \section asyncevent Event handling - * - * An asynchronous model requires that libusb perform work at various - * points in time - namely processing the results of previously-submitted - * transfers and invoking the user-supplied callback function. - * - * This gives rise to the libusb_handle_events() function which your - * application must call into when libusb has work do to. This gives libusb - * the opportunity to reap pending transfers, invoke callbacks, etc. - * - * There are 2 different approaches to dealing with libusb_handle_events: - * - * -# Repeatedly call libusb_handle_events() in blocking mode from a dedicated - * thread. - * -# Integrate libusb with your application's main event loop. libusb - * exposes a set of file descriptors which allow you to do this. - * - * The first approach has the big advantage that it will also work on Windows - * were libusb' poll API for select / poll integration is not available. So - * if you want to support Windows and use the async API, you must use this - * approach, see the \ref eventthread "Using an event handling thread" section - * below for details. - * - * If you prefer a single threaded approach with a single central event loop, - * see the \ref libusb_poll "polling and timing" section for how to integrate libusb - * into your application's main event loop. - * - * \section eventthread Using an event handling thread - * - * Lets begin with stating the obvious: If you're going to use a separate - * thread for libusb event handling, your callback functions MUST be - * threadsafe. - * - * Other then that doing event handling from a separate thread, is mostly - * simple. You can use an event thread function as follows: -\code -void *event_thread_func(void *ctx) -{ - while (event_thread_run) - libusb_handle_events(ctx); - - return NULL; -} -\endcode - * - * There is one caveat though, stopping this thread requires setting the - * event_thread_run variable to 0, and after that libusb_handle_events() needs - * to return control to event_thread_func. But unless some event happens, - * libusb_handle_events() will not return. - * - * There are 2 different ways of dealing with this, depending on if your - * application uses libusb' \ref libusb_hotplug "hotplug" support or not. - * - * Applications which do not use hotplug support, should not start the event - * thread until after their first call to libusb_open(), and should stop the - * thread when closing the last open device as follows: -\code -void my_close_handle(libusb_device_handle *dev_handle) -{ - if (open_devs == 1) - event_thread_run = 0; - - libusb_close(dev_handle); // This wakes up libusb_handle_events() - - if (open_devs == 1) - pthread_join(event_thread); - - open_devs--; -} -\endcode - * - * Applications using hotplug support should start the thread at program init, - * after having successfully called libusb_hotplug_register_callback(), and - * should stop the thread at program exit as follows: -\code -void my_libusb_exit(void) -{ - event_thread_run = 0; - libusb_hotplug_deregister_callback(ctx, hotplug_cb_handle); // This wakes up libusb_handle_events() - pthread_join(event_thread); - libusb_exit(ctx); -} -\endcode - */ - -/** - * @defgroup libusb_poll Polling and timing - * - * This page documents libusb's functions for polling events and timing. - * These functions are only necessary for users of the - * \ref libusb_asyncio "asynchronous API". If you are only using the simpler - * \ref libusb_syncio "synchronous API" then you do not need to ever call these - * functions. - * - * The justification for the functionality described here has already been - * discussed in the \ref asyncevent "event handling" section of the - * asynchronous API documentation. In summary, libusb does not create internal - * threads for event processing and hence relies on your application calling - * into libusb at certain points in time so that pending events can be handled. - * - * Your main loop is probably already calling poll() or select() or a - * variant on a set of file descriptors for other event sources (e.g. keyboard - * button presses, mouse movements, network sockets, etc). You then add - * libusb's file descriptors to your poll()/select() calls, and when activity - * is detected on such descriptors you know it is time to call - * libusb_handle_events(). - * - * There is one final event handling complication. libusb supports - * asynchronous transfers which time out after a specified time period. - * - * On some platforms a timerfd is used, so the timeout handling is just another - * fd, on other platforms this requires that libusb is called into at or after - * the timeout to handle it. So, in addition to considering libusb's file - * descriptors in your main event loop, you must also consider that libusb - * sometimes needs to be called into at fixed points in time even when there - * is no file descriptor activity, see \ref polltime details. - * - * In order to know precisely when libusb needs to be called into, libusb - * offers you a set of pollable file descriptors and information about when - * the next timeout expires. - * - * If you are using the asynchronous I/O API, you must take one of the two - * following options, otherwise your I/O will not complete. - * - * \section pollsimple The simple option - * - * If your application revolves solely around libusb and does not need to - * handle other event sources, you can have a program structure as follows: -\code -// initialize libusb -// find and open device -// maybe fire off some initial async I/O - -while (user_has_not_requested_exit) - libusb_handle_events(ctx); - -// clean up and exit -\endcode - * - * With such a simple main loop, you do not have to worry about managing - * sets of file descriptors or handling timeouts. libusb_handle_events() will - * handle those details internally. - * - * \section libusb_pollmain The more advanced option - * - * \note This functionality is currently only available on Unix-like platforms. - * On Windows, libusb_get_pollfds() simply returns NULL. Applications which - * want to support Windows are advised to use an \ref eventthread - * "event handling thread" instead. - * - * In more advanced applications, you will already have a main loop which - * is monitoring other event sources: network sockets, X11 events, mouse - * movements, etc. Through exposing a set of file descriptors, libusb is - * designed to cleanly integrate into such main loops. - * - * In addition to polling file descriptors for the other event sources, you - * take a set of file descriptors from libusb and monitor those too. When you - * detect activity on libusb's file descriptors, you call - * libusb_handle_events_timeout() in non-blocking mode. - * - * What's more, libusb may also need to handle events at specific moments in - * time. No file descriptor activity is generated at these times, so your - * own application needs to be continually aware of when the next one of these - * moments occurs (through calling libusb_get_next_timeout()), and then it - * needs to call libusb_handle_events_timeout() in non-blocking mode when - * these moments occur. This means that you need to adjust your - * poll()/select() timeout accordingly. - * - * libusb provides you with a set of file descriptors to poll and expects you - * to poll all of them, treating them as a single entity. The meaning of each - * file descriptor in the set is an internal implementation detail, - * platform-dependent and may vary from release to release. Don't try and - * interpret the meaning of the file descriptors, just do as libusb indicates, - * polling all of them at once. - * - * In pseudo-code, you want something that looks like: -\code -// initialise libusb - -libusb_get_pollfds(ctx) -while (user has not requested application exit) { - libusb_get_next_timeout(ctx); - poll(on libusb file descriptors plus any other event sources of interest, - using a timeout no larger than the value libusb just suggested) - if (poll() indicated activity on libusb file descriptors) - libusb_handle_events_timeout(ctx, &zero_tv); - if (time has elapsed to or beyond the libusb timeout) - libusb_handle_events_timeout(ctx, &zero_tv); - // handle events from other sources here -} - -// clean up and exit -\endcode - * - * \subsection polltime Notes on time-based events - * - * The above complication with having to track time and call into libusb at - * specific moments is a bit of a headache. For maximum compatibility, you do - * need to write your main loop as above, but you may decide that you can - * restrict the supported platforms of your application and get away with - * a more simplistic scheme. - * - * These time-based event complications are \b not required on the following - * platforms: - * - Darwin - * - Linux, provided that the following version requirements are satisfied: - * - Linux v2.6.27 or newer, compiled with timerfd support - * - glibc v2.9 or newer - * - libusb v1.0.5 or newer - * - * Under these configurations, libusb_get_next_timeout() will \em always return - * 0, so your main loop can be simplified to: -\code -// initialise libusb - -libusb_get_pollfds(ctx) -while (user has not requested application exit) { - poll(on libusb file descriptors plus any other event sources of interest, - using any timeout that you like) - if (poll() indicated activity on libusb file descriptors) - libusb_handle_events_timeout(ctx, &zero_tv); - // handle events from other sources here -} - -// clean up and exit -\endcode - * - * Do remember that if you simplify your main loop to the above, you will - * lose compatibility with some platforms (including legacy Linux platforms, - * and any future platforms supported by libusb which may have time-based - * event requirements). The resultant problems will likely appear as - * strange bugs in your application. - * - * You can use the libusb_pollfds_handle_timeouts() function to do a runtime - * check to see if it is safe to ignore the time-based event complications. - * If your application has taken the shortcut of ignoring libusb's next timeout - * in your main loop, then you are advised to check the return value of - * libusb_pollfds_handle_timeouts() during application startup, and to abort - * if the platform does suffer from these timing complications. - * - * \subsection fdsetchange Changes in the file descriptor set - * - * The set of file descriptors that libusb uses as event sources may change - * during the life of your application. Rather than having to repeatedly - * call libusb_get_pollfds(), you can set up notification functions for when - * the file descriptor set changes using libusb_set_pollfd_notifiers(). - * - * \subsection mtissues Multi-threaded considerations - * - * Unfortunately, the situation is complicated further when multiple threads - * come into play. If two threads are monitoring the same file descriptors, - * the fact that only one thread will be woken up when an event occurs causes - * some headaches. - * - * The events lock, event waiters lock, and libusb_handle_events_locked() - * entities are added to solve these problems. You do not need to be concerned - * with these entities otherwise. - * - * See the extra documentation: \ref libusb_mtasync - */ - -/** \page libusb_mtasync Multi-threaded applications and asynchronous I/O - * - * libusb is a thread-safe library, but extra considerations must be applied - * to applications which interact with libusb from multiple threads. - * - * The underlying issue that must be addressed is that all libusb I/O - * revolves around monitoring file descriptors through the poll()/select() - * system calls. This is directly exposed at the - * \ref libusb_asyncio "asynchronous interface" but it is important to note that the - * \ref libusb_syncio "synchronous interface" is implemented on top of the - * asynchonrous interface, therefore the same considerations apply. - * - * The issue is that if two or more threads are concurrently calling poll() - * or select() on libusb's file descriptors then only one of those threads - * will be woken up when an event arrives. The others will be completely - * oblivious that anything has happened. - * - * Consider the following pseudo-code, which submits an asynchronous transfer - * then waits for its completion. This style is one way you could implement a - * synchronous interface on top of the asynchronous interface (and libusb - * does something similar, albeit more advanced due to the complications - * explained on this page). - * -\code -void cb(struct libusb_transfer *transfer) -{ - int *completed = transfer->user_data; - *completed = 1; -} - -void myfunc() { - struct libusb_transfer *transfer; - unsigned char buffer[LIBUSB_CONTROL_SETUP_SIZE] __attribute__ ((aligned (2))); - int completed = 0; - - transfer = libusb_alloc_transfer(0); - libusb_fill_control_setup(buffer, - LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_OUT, 0x04, 0x01, 0, 0); - libusb_fill_control_transfer(transfer, dev, buffer, cb, &completed, 1000); - libusb_submit_transfer(transfer); - - while (!completed) { - poll(libusb file descriptors, 120*1000); - if (poll indicates activity) - libusb_handle_events_timeout(ctx, &zero_tv); - } - printf("completed!"); - // other code here -} -\endcode - * - * Here we are serializing completion of an asynchronous event - * against a condition - the condition being completion of a specific transfer. - * The poll() loop has a long timeout to minimize CPU usage during situations - * when nothing is happening (it could reasonably be unlimited). - * - * If this is the only thread that is polling libusb's file descriptors, there - * is no problem: there is no danger that another thread will swallow up the - * event that we are interested in. On the other hand, if there is another - * thread polling the same descriptors, there is a chance that it will receive - * the event that we were interested in. In this situation, myfunc() - * will only realise that the transfer has completed on the next iteration of - * the loop, up to 120 seconds later. Clearly a two-minute delay is - * undesirable, and don't even think about using short timeouts to circumvent - * this issue! - * - * The solution here is to ensure that no two threads are ever polling the - * file descriptors at the same time. A naive implementation of this would - * impact the capabilities of the library, so libusb offers the scheme - * documented below to ensure no loss of functionality. - * - * Before we go any further, it is worth mentioning that all libusb-wrapped - * event handling procedures fully adhere to the scheme documented below. - * This includes libusb_handle_events() and its variants, and all the - * synchronous I/O functions - libusb hides this headache from you. - * - * \section Using libusb_handle_events() from multiple threads - * - * Even when only using libusb_handle_events() and synchronous I/O functions, - * you can still have a race condition. You might be tempted to solve the - * above with libusb_handle_events() like so: - * -\code - libusb_submit_transfer(transfer); - - while (!completed) { - libusb_handle_events(ctx); - } - printf("completed!"); -\endcode - * - * This however has a race between the checking of completed and - * libusb_handle_events() acquiring the events lock, so another thread - * could have completed the transfer, resulting in this thread hanging - * until either a timeout or another event occurs. See also commit - * 6696512aade99bb15d6792af90ae329af270eba6 which fixes this in the - * synchronous API implementation of libusb. - * - * Fixing this race requires checking the variable completed only after - * taking the event lock, which defeats the concept of just calling - * libusb_handle_events() without worrying about locking. This is why - * libusb-1.0.9 introduces the new libusb_handle_events_timeout_completed() - * and libusb_handle_events_completed() functions, which handles doing the - * completion check for you after they have acquired the lock: - * -\code - libusb_submit_transfer(transfer); - - while (!completed) { - libusb_handle_events_completed(ctx, &completed); - } - printf("completed!"); -\endcode - * - * This nicely fixes the race in our example. Note that if all you want to - * do is submit a single transfer and wait for its completion, then using - * one of the synchronous I/O functions is much easier. - * - * \section eventlock The events lock - * - * The problem is when we consider the fact that libusb exposes file - * descriptors to allow for you to integrate asynchronous USB I/O into - * existing main loops, effectively allowing you to do some work behind - * libusb's back. If you do take libusb's file descriptors and pass them to - * poll()/select() yourself, you need to be aware of the associated issues. - * - * The first concept to be introduced is the events lock. The events lock - * is used to serialize threads that want to handle events, such that only - * one thread is handling events at any one time. - * - * You must take the events lock before polling libusb file descriptors, - * using libusb_lock_events(). You must release the lock as soon as you have - * aborted your poll()/select() loop, using libusb_unlock_events(). - * - * \section threadwait Letting other threads do the work for you - * - * Although the events lock is a critical part of the solution, it is not - * enough on it's own. You might wonder if the following is sufficient... -\code - libusb_lock_events(ctx); - while (!completed) { - poll(libusb file descriptors, 120*1000); - if (poll indicates activity) - libusb_handle_events_timeout(ctx, &zero_tv); - } - libusb_unlock_events(ctx); -\endcode - * ...and the answer is that it is not. This is because the transfer in the - * code shown above may take a long time (say 30 seconds) to complete, and - * the lock is not released until the transfer is completed. - * - * Another thread with similar code that wants to do event handling may be - * working with a transfer that completes after a few milliseconds. Despite - * having such a quick completion time, the other thread cannot check that - * status of its transfer until the code above has finished (30 seconds later) - * due to contention on the lock. - * - * To solve this, libusb offers you a mechanism to determine when another - * thread is handling events. It also offers a mechanism to block your thread - * until the event handling thread has completed an event (and this mechanism - * does not involve polling of file descriptors). - * - * After determining that another thread is currently handling events, you - * obtain the event waiters lock using libusb_lock_event_waiters(). - * You then re-check that some other thread is still handling events, and if - * so, you call libusb_wait_for_event(). - * - * libusb_wait_for_event() puts your application to sleep until an event - * occurs, or until a thread releases the events lock. When either of these - * things happen, your thread is woken up, and should re-check the condition - * it was waiting on. It should also re-check that another thread is handling - * events, and if not, it should start handling events itself. - * - * This looks like the following, as pseudo-code: -\code -retry: -if (libusb_try_lock_events(ctx) == 0) { - // we obtained the event lock: do our own event handling - while (!completed) { - if (!libusb_event_handling_ok(ctx)) { - libusb_unlock_events(ctx); - goto retry; - } - poll(libusb file descriptors, 120*1000); - if (poll indicates activity) - libusb_handle_events_locked(ctx, 0); - } - libusb_unlock_events(ctx); -} else { - // another thread is doing event handling. wait for it to signal us that - // an event has completed - libusb_lock_event_waiters(ctx); - - while (!completed) { - // now that we have the event waiters lock, double check that another - // thread is still handling events for us. (it may have ceased handling - // events in the time it took us to reach this point) - if (!libusb_event_handler_active(ctx)) { - // whoever was handling events is no longer doing so, try again - libusb_unlock_event_waiters(ctx); - goto retry; - } - - libusb_wait_for_event(ctx, NULL); - } - libusb_unlock_event_waiters(ctx); -} -printf("completed!\n"); -\endcode - * - * A naive look at the above code may suggest that this can only support - * one event waiter (hence a total of 2 competing threads, the other doing - * event handling), because the event waiter seems to have taken the event - * waiters lock while waiting for an event. However, the system does support - * multiple event waiters, because libusb_wait_for_event() actually drops - * the lock while waiting, and reaquires it before continuing. - * - * We have now implemented code which can dynamically handle situations where - * nobody is handling events (so we should do it ourselves), and it can also - * handle situations where another thread is doing event handling (so we can - * piggyback onto them). It is also equipped to handle a combination of - * the two, for example, another thread is doing event handling, but for - * whatever reason it stops doing so before our condition is met, so we take - * over the event handling. - * - * Four functions were introduced in the above pseudo-code. Their importance - * should be apparent from the code shown above. - * -# libusb_try_lock_events() is a non-blocking function which attempts - * to acquire the events lock but returns a failure code if it is contended. - * -# libusb_event_handling_ok() checks that libusb is still happy for your - * thread to be performing event handling. Sometimes, libusb needs to - * interrupt the event handler, and this is how you can check if you have - * been interrupted. If this function returns 0, the correct behaviour is - * for you to give up the event handling lock, and then to repeat the cycle. - * The following libusb_try_lock_events() will fail, so you will become an - * events waiter. For more information on this, read \ref fullstory below. - * -# libusb_handle_events_locked() is a variant of - * libusb_handle_events_timeout() that you can call while holding the - * events lock. libusb_handle_events_timeout() itself implements similar - * logic to the above, so be sure not to call it when you are - * "working behind libusb's back", as is the case here. - * -# libusb_event_handler_active() determines if someone is currently - * holding the events lock - * - * You might be wondering why there is no function to wake up all threads - * blocked on libusb_wait_for_event(). This is because libusb can do this - * internally: it will wake up all such threads when someone calls - * libusb_unlock_events() or when a transfer completes (at the point after its - * callback has returned). - * - * \subsection fullstory The full story - * - * The above explanation should be enough to get you going, but if you're - * really thinking through the issues then you may be left with some more - * questions regarding libusb's internals. If you're curious, read on, and if - * not, skip to the next section to avoid confusing yourself! - * - * The immediate question that may spring to mind is: what if one thread - * modifies the set of file descriptors that need to be polled while another - * thread is doing event handling? - * - * There are 2 situations in which this may happen. - * -# libusb_open() will add another file descriptor to the poll set, - * therefore it is desirable to interrupt the event handler so that it - * restarts, picking up the new descriptor. - * -# libusb_close() will remove a file descriptor from the poll set. There - * are all kinds of race conditions that could arise here, so it is - * important that nobody is doing event handling at this time. - * - * libusb handles these issues internally, so application developers do not - * have to stop their event handlers while opening/closing devices. Here's how - * it works, focusing on the libusb_close() situation first: - * - * -# During initialization, libusb opens an internal pipe, and it adds the read - * end of this pipe to the set of file descriptors to be polled. - * -# During libusb_close(), libusb writes some dummy data on this event pipe. - * This immediately interrupts the event handler. libusb also records - * internally that it is trying to interrupt event handlers for this - * high-priority event. - * -# At this point, some of the functions described above start behaving - * differently: - * - libusb_event_handling_ok() starts returning 1, indicating that it is NOT - * OK for event handling to continue. - * - libusb_try_lock_events() starts returning 1, indicating that another - * thread holds the event handling lock, even if the lock is uncontended. - * - libusb_event_handler_active() starts returning 1, indicating that - * another thread is doing event handling, even if that is not true. - * -# The above changes in behaviour result in the event handler stopping and - * giving up the events lock very quickly, giving the high-priority - * libusb_close() operation a "free ride" to acquire the events lock. All - * threads that are competing to do event handling become event waiters. - * -# With the events lock held inside libusb_close(), libusb can safely remove - * a file descriptor from the poll set, in the safety of knowledge that - * nobody is polling those descriptors or trying to access the poll set. - * -# After obtaining the events lock, the close operation completes very - * quickly (usually a matter of milliseconds) and then immediately releases - * the events lock. - * -# At the same time, the behaviour of libusb_event_handling_ok() and friends - * reverts to the original, documented behaviour. - * -# The release of the events lock causes the threads that are waiting for - * events to be woken up and to start competing to become event handlers - * again. One of them will succeed; it will then re-obtain the list of poll - * descriptors, and USB I/O will then continue as normal. - * - * libusb_open() is similar, and is actually a more simplistic case. Upon a - * call to libusb_open(): - * - * -# The device is opened and a file descriptor is added to the poll set. - * -# libusb sends some dummy data on the event pipe, and records that it - * is trying to modify the poll descriptor set. - * -# The event handler is interrupted, and the same behaviour change as for - * libusb_close() takes effect, causing all event handling threads to become - * event waiters. - * -# The libusb_open() implementation takes its free ride to the events lock. - * -# Happy that it has successfully paused the events handler, libusb_open() - * releases the events lock. - * -# The event waiter threads are all woken up and compete to become event - * handlers again. The one that succeeds will obtain the list of poll - * descriptors again, which will include the addition of the new device. - * - * \subsection concl Closing remarks - * - * The above may seem a little complicated, but hopefully I have made it clear - * why such complications are necessary. Also, do not forget that this only - * applies to applications that take libusb's file descriptors and integrate - * them into their own polling loops. - * - * You may decide that it is OK for your multi-threaded application to ignore - * some of the rules and locks detailed above, because you don't think that - * two threads can ever be polling the descriptors at the same time. If that - * is the case, then that's good news for you because you don't have to worry. - * But be careful here; remember that the synchronous I/O functions do event - * handling internally. If you have one thread doing event handling in a loop - * (without implementing the rules and locking semantics documented above) - * and another trying to send a synchronous USB transfer, you will end up with - * two threads monitoring the same descriptors, and the above-described - * undesirable behaviour occurring. The solution is for your polling thread to - * play by the rules; the synchronous I/O functions do so, and this will result - * in them getting along in perfect harmony. - * - * If you do have a dedicated thread doing event handling, it is perfectly - * legal for it to take the event handling lock for long periods of time. Any - * synchronous I/O functions you call from other threads will transparently - * fall back to the "event waiters" mechanism detailed above. The only - * consideration that your event handling thread must apply is the one related - * to libusb_event_handling_ok(): you must call this before every poll(), and - * give up the events lock if instructed. - */ - -int usbi_io_init(struct libusb_context *ctx) -{ - int r; - - usbi_mutex_init(&ctx->flying_transfers_lock); - usbi_mutex_init(&ctx->events_lock); - usbi_mutex_init(&ctx->event_waiters_lock); - usbi_cond_init(&ctx->event_waiters_cond); - usbi_mutex_init(&ctx->event_data_lock); - usbi_tls_key_create(&ctx->event_handling_key); - list_init(&ctx->flying_transfers); - list_init(&ctx->ipollfds); - list_init(&ctx->hotplug_msgs); - list_init(&ctx->completed_transfers); - - /* FIXME should use an eventfd on kernels that support it */ - r = usbi_pipe(ctx->event_pipe); - if (r < 0) { - r = LIBUSB_ERROR_OTHER; - goto err; - } - - r = usbi_add_pollfd(ctx, ctx->event_pipe[0], POLLIN); - if (r < 0) - goto err_close_pipe; - -#ifdef USBI_TIMERFD_AVAILABLE - ctx->timerfd = timerfd_create(usbi_backend->get_timerfd_clockid(), - TFD_NONBLOCK); - if (ctx->timerfd >= 0) { - usbi_dbg("using timerfd for timeouts"); - r = usbi_add_pollfd(ctx, ctx->timerfd, POLLIN); - if (r < 0) - goto err_close_timerfd; - } else { - usbi_dbg("timerfd not available (code %d error %d)", ctx->timerfd, errno); - ctx->timerfd = -1; - } -#endif - - return 0; - -#ifdef USBI_TIMERFD_AVAILABLE -err_close_timerfd: - close(ctx->timerfd); - usbi_remove_pollfd(ctx, ctx->event_pipe[0]); -#endif -err_close_pipe: - usbi_close(ctx->event_pipe[0]); - usbi_close(ctx->event_pipe[1]); -err: - usbi_mutex_destroy(&ctx->flying_transfers_lock); - usbi_mutex_destroy(&ctx->events_lock); - usbi_mutex_destroy(&ctx->event_waiters_lock); - usbi_cond_destroy(&ctx->event_waiters_cond); - usbi_mutex_destroy(&ctx->event_data_lock); - usbi_tls_key_delete(ctx->event_handling_key); - return r; -} - -void usbi_io_exit(struct libusb_context *ctx) -{ - usbi_remove_pollfd(ctx, ctx->event_pipe[0]); - usbi_close(ctx->event_pipe[0]); - usbi_close(ctx->event_pipe[1]); -#ifdef USBI_TIMERFD_AVAILABLE - if (usbi_using_timerfd(ctx)) { - usbi_remove_pollfd(ctx, ctx->timerfd); - close(ctx->timerfd); - } -#endif - usbi_mutex_destroy(&ctx->flying_transfers_lock); - usbi_mutex_destroy(&ctx->events_lock); - usbi_mutex_destroy(&ctx->event_waiters_lock); - usbi_cond_destroy(&ctx->event_waiters_cond); - usbi_mutex_destroy(&ctx->event_data_lock); - usbi_tls_key_delete(ctx->event_handling_key); - if (ctx->pollfds) - free(ctx->pollfds); -} - -static int calculate_timeout(struct usbi_transfer *transfer) -{ - int r; - struct timespec current_time; - unsigned int timeout = - USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)->timeout; - - if (!timeout) - return 0; - - r = usbi_backend->clock_gettime(USBI_CLOCK_MONOTONIC, ¤t_time); - if (r < 0) { - usbi_err(ITRANSFER_CTX(transfer), - "failed to read monotonic clock, errno=%d", errno); - return r; - } - - current_time.tv_sec += timeout / 1000; - current_time.tv_nsec += (timeout % 1000) * 1000000; - - while (current_time.tv_nsec >= 1000000000) { - current_time.tv_nsec -= 1000000000; - current_time.tv_sec++; - } - - TIMESPEC_TO_TIMEVAL(&transfer->timeout, ¤t_time); - return 0; -} - -/** \ingroup libusb_asyncio - * Allocate a libusb transfer with a specified number of isochronous packet - * descriptors. The returned transfer is pre-initialized for you. When the new - * transfer is no longer needed, it should be freed with - * libusb_free_transfer(). - * - * Transfers intended for non-isochronous endpoints (e.g. control, bulk, - * interrupt) should specify an iso_packets count of zero. - * - * For transfers intended for isochronous endpoints, specify an appropriate - * number of packet descriptors to be allocated as part of the transfer. - * The returned transfer is not specially initialized for isochronous I/O; - * you are still required to set the - * \ref libusb_transfer::num_iso_packets "num_iso_packets" and - * \ref libusb_transfer::type "type" fields accordingly. - * - * It is safe to allocate a transfer with some isochronous packets and then - * use it on a non-isochronous endpoint. If you do this, ensure that at time - * of submission, num_iso_packets is 0 and that type is set appropriately. - * - * \param iso_packets number of isochronous packet descriptors to allocate - * \returns a newly allocated transfer, or NULL on error - */ -DEFAULT_VISIBILITY -struct libusb_transfer * LIBUSB_CALL libusb_alloc_transfer( - int iso_packets) -{ - struct libusb_transfer *transfer; - size_t os_alloc_size = usbi_backend->transfer_priv_size; - size_t alloc_size = sizeof(struct usbi_transfer) - + sizeof(struct libusb_transfer) - + (sizeof(struct libusb_iso_packet_descriptor) * iso_packets) - + os_alloc_size; - struct usbi_transfer *itransfer = calloc(1, alloc_size); - if (!itransfer) - return NULL; - - itransfer->num_iso_packets = iso_packets; - usbi_mutex_init(&itransfer->lock); - transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - usbi_dbg("transfer %p", transfer); - return transfer; -} - -/** \ingroup libusb_asyncio - * Free a transfer structure. This should be called for all transfers - * allocated with libusb_alloc_transfer(). - * - * If the \ref libusb_transfer_flags::LIBUSB_TRANSFER_FREE_BUFFER - * "LIBUSB_TRANSFER_FREE_BUFFER" flag is set and the transfer buffer is - * non-NULL, this function will also free the transfer buffer using the - * standard system memory allocator (e.g. free()). - * - * It is legal to call this function with a NULL transfer. In this case, - * the function will simply return safely. - * - * It is not legal to free an active transfer (one which has been submitted - * and has not yet completed). - * - * \param transfer the transfer to free - */ -void API_EXPORTED libusb_free_transfer(struct libusb_transfer *transfer) -{ - struct usbi_transfer *itransfer; - if (!transfer) - return; - - usbi_dbg("transfer %p", transfer); - if (transfer->flags & LIBUSB_TRANSFER_FREE_BUFFER && transfer->buffer) - free(transfer->buffer); - - itransfer = LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer); - usbi_mutex_destroy(&itransfer->lock); - free(itransfer); -} - -#ifdef USBI_TIMERFD_AVAILABLE -static int disarm_timerfd(struct libusb_context *ctx) -{ - const struct itimerspec disarm_timer = { { 0, 0 }, { 0, 0 } }; - int r; - - usbi_dbg(""); - r = timerfd_settime(ctx->timerfd, 0, &disarm_timer, NULL); - if (r < 0) - return LIBUSB_ERROR_OTHER; - else - return 0; -} - -/* iterates through the flying transfers, and rearms the timerfd based on the - * next upcoming timeout. - * must be called with flying_list locked. - * returns 0 on success or a LIBUSB_ERROR code on failure. - */ -static int arm_timerfd_for_next_timeout(struct libusb_context *ctx) -{ - struct usbi_transfer *transfer; - - list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) { - struct timeval *cur_tv = &transfer->timeout; - - /* if we've reached transfers of infinite timeout, then we have no - * arming to do */ - if (!timerisset(cur_tv)) - goto disarm; - - /* act on first transfer that has not already been handled */ - if (!(transfer->timeout_flags & (USBI_TRANSFER_TIMEOUT_HANDLED | USBI_TRANSFER_OS_HANDLES_TIMEOUT))) { - int r; - const struct itimerspec it = { {0, 0}, - { cur_tv->tv_sec, cur_tv->tv_usec * 1000 } }; - usbi_dbg("next timeout originally %dms", USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)->timeout); - r = timerfd_settime(ctx->timerfd, TFD_TIMER_ABSTIME, &it, NULL); - if (r < 0) - return LIBUSB_ERROR_OTHER; - return 0; - } - } - -disarm: - return disarm_timerfd(ctx); -} -#else -static int arm_timerfd_for_next_timeout(struct libusb_context *ctx) -{ - UNUSED(ctx); - return 0; -} -#endif - -/* add a transfer to the (timeout-sorted) active transfers list. - * This function will return non 0 if fails to update the timer, - * in which case the transfer is *not* on the flying_transfers list. */ -static int add_to_flying_list(struct usbi_transfer *transfer) -{ - struct usbi_transfer *cur; - struct timeval *timeout = &transfer->timeout; - struct libusb_context *ctx = ITRANSFER_CTX(transfer); - int r; - int first = 1; - - r = calculate_timeout(transfer); - if (r) - return r; - - /* if we have no other flying transfers, start the list with this one */ - if (list_empty(&ctx->flying_transfers)) { - list_add(&transfer->list, &ctx->flying_transfers); - goto out; - } - - /* if we have infinite timeout, append to end of list */ - if (!timerisset(timeout)) { - list_add_tail(&transfer->list, &ctx->flying_transfers); - /* first is irrelevant in this case */ - goto out; - } - - /* otherwise, find appropriate place in list */ - list_for_each_entry(cur, &ctx->flying_transfers, list, struct usbi_transfer) { - /* find first timeout that occurs after the transfer in question */ - struct timeval *cur_tv = &cur->timeout; - - if (!timerisset(cur_tv) || (cur_tv->tv_sec > timeout->tv_sec) || - (cur_tv->tv_sec == timeout->tv_sec && - cur_tv->tv_usec > timeout->tv_usec)) { - list_add_tail(&transfer->list, &cur->list); - goto out; - } - first = 0; - } - /* first is 0 at this stage (list not empty) */ - - /* otherwise we need to be inserted at the end */ - list_add_tail(&transfer->list, &ctx->flying_transfers); -out: -#ifdef USBI_TIMERFD_AVAILABLE - if (first && usbi_using_timerfd(ctx) && timerisset(timeout)) { - /* if this transfer has the lowest timeout of all active transfers, - * rearm the timerfd with this transfer's timeout */ - const struct itimerspec it = { {0, 0}, - { timeout->tv_sec, timeout->tv_usec * 1000 } }; - usbi_dbg("arm timerfd for timeout in %dms (first in line)", - USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)->timeout); - r = timerfd_settime(ctx->timerfd, TFD_TIMER_ABSTIME, &it, NULL); - if (r < 0) { - usbi_warn(ctx, "failed to arm first timerfd (errno %d)", errno); - r = LIBUSB_ERROR_OTHER; - } - } -#else - UNUSED(first); -#endif - - if (r) - list_del(&transfer->list); - - return r; -} - -/* remove a transfer from the active transfers list. - * This function will *always* remove the transfer from the - * flying_transfers list. It will return a LIBUSB_ERROR code - * if it fails to update the timer for the next timeout. */ -static int remove_from_flying_list(struct usbi_transfer *transfer) -{ - struct libusb_context *ctx = ITRANSFER_CTX(transfer); - int rearm_timerfd; - int r = 0; - - usbi_mutex_lock(&ctx->flying_transfers_lock); - rearm_timerfd = (timerisset(&transfer->timeout) && - list_first_entry(&ctx->flying_transfers, struct usbi_transfer, list) == transfer); - list_del(&transfer->list); - if (usbi_using_timerfd(ctx) && rearm_timerfd) - r = arm_timerfd_for_next_timeout(ctx); - usbi_mutex_unlock(&ctx->flying_transfers_lock); - - return r; -} - -/** \ingroup libusb_asyncio - * Submit a transfer. This function will fire off the USB transfer and then - * return immediately. - * - * \param transfer the transfer to submit - * \returns 0 on success - * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected - * \returns LIBUSB_ERROR_BUSY if the transfer has already been submitted. - * \returns LIBUSB_ERROR_NOT_SUPPORTED if the transfer flags are not supported - * by the operating system. - * \returns LIBUSB_ERROR_INVALID_PARAM if the transfer size is larger than - * the operating system and/or hardware can support - * \returns another LIBUSB_ERROR code on other failure - */ -int API_EXPORTED libusb_submit_transfer(struct libusb_transfer *transfer) -{ - struct usbi_transfer *itransfer = - LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer); - struct libusb_context *ctx = TRANSFER_CTX(transfer); - int r; - - usbi_dbg("transfer %p", transfer); - - /* - * Important note on locking, this function takes / releases locks - * in the following order: - * take flying_transfers_lock - * take itransfer->lock - * clear transfer - * add to flying_transfers list - * release flying_transfers_lock - * submit transfer - * release itransfer->lock - * if submit failed: - * take flying_transfers_lock - * remove from flying_transfers list - * release flying_transfers_lock - * - * Note that it takes locks in the order a-b and then releases them - * in the same order a-b. This is somewhat unusual but not wrong, - * release order is not important as long as *all* locks are released - * before re-acquiring any locks. - * - * This means that the ordering of first releasing itransfer->lock - * and then re-acquiring the flying_transfers_list on error is - * important and must not be changed! - * - * This is done this way because when we take both locks we must always - * take flying_transfers_lock first to avoid ab-ba style deadlocks with - * the timeout handling and usbi_handle_disconnect paths. - * - * And we cannot release itransfer->lock before the submission is - * complete otherwise timeout handling for transfers with short - * timeouts may run before submission. - */ - usbi_mutex_lock(&ctx->flying_transfers_lock); - usbi_mutex_lock(&itransfer->lock); - if (itransfer->state_flags & USBI_TRANSFER_IN_FLIGHT) { - usbi_mutex_unlock(&ctx->flying_transfers_lock); - usbi_mutex_unlock(&itransfer->lock); - return LIBUSB_ERROR_BUSY; - } - itransfer->transferred = 0; - itransfer->state_flags = 0; - itransfer->timeout_flags = 0; - r = add_to_flying_list(itransfer); - if (r) { - usbi_mutex_unlock(&ctx->flying_transfers_lock); - usbi_mutex_unlock(&itransfer->lock); - return r; - } - /* - * We must release the flying transfers lock here, because with - * some backends the submit_transfer method is synchroneous. - */ - usbi_mutex_unlock(&ctx->flying_transfers_lock); - - r = usbi_backend->submit_transfer(itransfer); - if (r == LIBUSB_SUCCESS) { - itransfer->state_flags |= USBI_TRANSFER_IN_FLIGHT; - /* keep a reference to this device */ - libusb_ref_device(transfer->dev_handle->dev); - } - usbi_mutex_unlock(&itransfer->lock); - - if (r != LIBUSB_SUCCESS) - remove_from_flying_list(itransfer); - - return r; -} - -/** \ingroup libusb_asyncio - * Asynchronously cancel a previously submitted transfer. - * This function returns immediately, but this does not indicate cancellation - * is complete. Your callback function will be invoked at some later time - * with a transfer status of - * \ref libusb_transfer_status::LIBUSB_TRANSFER_CANCELLED - * "LIBUSB_TRANSFER_CANCELLED." - * - * \param transfer the transfer to cancel - * \returns 0 on success - * \returns LIBUSB_ERROR_NOT_FOUND if the transfer is not in progress, - * already complete, or already cancelled. - * \returns a LIBUSB_ERROR code on failure - */ -int API_EXPORTED libusb_cancel_transfer(struct libusb_transfer *transfer) -{ - struct usbi_transfer *itransfer = - LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer); - int r; - - usbi_dbg("transfer %p", transfer ); - usbi_mutex_lock(&itransfer->lock); - if (!(itransfer->state_flags & USBI_TRANSFER_IN_FLIGHT) - || (itransfer->state_flags & USBI_TRANSFER_CANCELLING)) { - r = LIBUSB_ERROR_NOT_FOUND; - goto out; - } - r = usbi_backend->cancel_transfer(itransfer); - if (r < 0) { - if (r != LIBUSB_ERROR_NOT_FOUND && - r != LIBUSB_ERROR_NO_DEVICE) - usbi_err(TRANSFER_CTX(transfer), - "cancel transfer failed error %d", r); - else - usbi_dbg("cancel transfer failed error %d", r); - - if (r == LIBUSB_ERROR_NO_DEVICE) - itransfer->state_flags |= USBI_TRANSFER_DEVICE_DISAPPEARED; - } - - itransfer->state_flags |= USBI_TRANSFER_CANCELLING; - -out: - usbi_mutex_unlock(&itransfer->lock); - return r; -} - -/** \ingroup libusb_asyncio - * Set a transfers bulk stream id. Note users are advised to use - * libusb_fill_bulk_stream_transfer() instead of calling this function - * directly. - * - * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103 - * - * \param transfer the transfer to set the stream id for - * \param stream_id the stream id to set - * \see libusb_alloc_streams() - */ -void API_EXPORTED libusb_transfer_set_stream_id( - struct libusb_transfer *transfer, uint32_t stream_id) -{ - struct usbi_transfer *itransfer = - LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer); - - itransfer->stream_id = stream_id; -} - -/** \ingroup libusb_asyncio - * Get a transfers bulk stream id. - * - * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103 - * - * \param transfer the transfer to get the stream id for - * \returns the stream id for the transfer - */ -uint32_t API_EXPORTED libusb_transfer_get_stream_id( - struct libusb_transfer *transfer) -{ - struct usbi_transfer *itransfer = - LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer); - - return itransfer->stream_id; -} - -/* Handle completion of a transfer (completion might be an error condition). - * This will invoke the user-supplied callback function, which may end up - * freeing the transfer. Therefore you cannot use the transfer structure - * after calling this function, and you should free all backend-specific - * data before calling it. - * Do not call this function with the usbi_transfer lock held. User-specified - * callback functions may attempt to directly resubmit the transfer, which - * will attempt to take the lock. */ -int usbi_handle_transfer_completion(struct usbi_transfer *itransfer, - enum libusb_transfer_status status) -{ - struct libusb_transfer *transfer = - USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct libusb_device_handle *dev_handle = transfer->dev_handle; - uint8_t flags; - int r; - - r = remove_from_flying_list(itransfer); - if (r < 0) - usbi_err(ITRANSFER_CTX(itransfer), "failed to set timer for next timeout, errno=%d", errno); - - usbi_mutex_lock(&itransfer->lock); - itransfer->state_flags &= ~USBI_TRANSFER_IN_FLIGHT; - usbi_mutex_unlock(&itransfer->lock); - - if (status == LIBUSB_TRANSFER_COMPLETED - && transfer->flags & LIBUSB_TRANSFER_SHORT_NOT_OK) { - int rqlen = transfer->length; - if (transfer->type == LIBUSB_TRANSFER_TYPE_CONTROL) - rqlen -= LIBUSB_CONTROL_SETUP_SIZE; - if (rqlen != itransfer->transferred) { - usbi_dbg("interpreting short transfer as error"); - status = LIBUSB_TRANSFER_ERROR; - } - } - - flags = transfer->flags; - transfer->status = status; - transfer->actual_length = itransfer->transferred; - usbi_dbg("transfer %p has callback %p", transfer, transfer->callback); - if (transfer->callback) - transfer->callback(transfer); - /* transfer might have been freed by the above call, do not use from - * this point. */ - if (flags & LIBUSB_TRANSFER_FREE_TRANSFER) - libusb_free_transfer(transfer); - libusb_unref_device(dev_handle->dev); - return r; -} - -/* Similar to usbi_handle_transfer_completion() but exclusively for transfers - * that were asynchronously cancelled. The same concerns w.r.t. freeing of - * transfers exist here. - * Do not call this function with the usbi_transfer lock held. User-specified - * callback functions may attempt to directly resubmit the transfer, which - * will attempt to take the lock. */ -int usbi_handle_transfer_cancellation(struct usbi_transfer *transfer) -{ - struct libusb_context *ctx = ITRANSFER_CTX(transfer); - uint8_t timed_out; - - usbi_mutex_lock(&ctx->flying_transfers_lock); - timed_out = transfer->timeout_flags & USBI_TRANSFER_TIMED_OUT; - usbi_mutex_unlock(&ctx->flying_transfers_lock); - - /* if the URB was cancelled due to timeout, report timeout to the user */ - if (timed_out) { - usbi_dbg("detected timeout cancellation"); - return usbi_handle_transfer_completion(transfer, LIBUSB_TRANSFER_TIMED_OUT); - } - - /* otherwise its a normal async cancel */ - return usbi_handle_transfer_completion(transfer, LIBUSB_TRANSFER_CANCELLED); -} - -/* Add a completed transfer to the completed_transfers list of the - * context and signal the event. The backend's handle_transfer_completion() - * function will be called the next time an event handler runs. */ -void usbi_signal_transfer_completion(struct usbi_transfer *transfer) -{ - struct libusb_context *ctx = ITRANSFER_CTX(transfer); - int pending_events; - - usbi_mutex_lock(&ctx->event_data_lock); - pending_events = usbi_pending_events(ctx); - list_add_tail(&transfer->completed_list, &ctx->completed_transfers); - if (!pending_events) - usbi_signal_event(ctx); - usbi_mutex_unlock(&ctx->event_data_lock); -} - -/** \ingroup libusb_poll - * Attempt to acquire the event handling lock. This lock is used to ensure that - * only one thread is monitoring libusb event sources at any one time. - * - * You only need to use this lock if you are developing an application - * which calls poll() or select() on libusb's file descriptors directly. - * If you stick to libusb's event handling loop functions (e.g. - * libusb_handle_events()) then you do not need to be concerned with this - * locking. - * - * While holding this lock, you are trusted to actually be handling events. - * If you are no longer handling events, you must call libusb_unlock_events() - * as soon as possible. - * - * \param ctx the context to operate on, or NULL for the default context - * \returns 0 if the lock was obtained successfully - * \returns 1 if the lock was not obtained (i.e. another thread holds the lock) - * \ref libusb_mtasync - */ -int API_EXPORTED libusb_try_lock_events(libusb_context *ctx) -{ - int r; - unsigned int ru; - USBI_GET_CONTEXT(ctx); - - /* is someone else waiting to close a device? if so, don't let this thread - * start event handling */ - usbi_mutex_lock(&ctx->event_data_lock); - ru = ctx->device_close; - usbi_mutex_unlock(&ctx->event_data_lock); - if (ru) { - usbi_dbg("someone else is closing a device"); - return 1; - } - - r = usbi_mutex_trylock(&ctx->events_lock); - if (r) - return 1; - - ctx->event_handler_active = 1; - return 0; -} - -/** \ingroup libusb_poll - * Acquire the event handling lock, blocking until successful acquisition if - * it is contended. This lock is used to ensure that only one thread is - * monitoring libusb event sources at any one time. - * - * You only need to use this lock if you are developing an application - * which calls poll() or select() on libusb's file descriptors directly. - * If you stick to libusb's event handling loop functions (e.g. - * libusb_handle_events()) then you do not need to be concerned with this - * locking. - * - * While holding this lock, you are trusted to actually be handling events. - * If you are no longer handling events, you must call libusb_unlock_events() - * as soon as possible. - * - * \param ctx the context to operate on, or NULL for the default context - * \ref libusb_mtasync - */ -void API_EXPORTED libusb_lock_events(libusb_context *ctx) -{ - USBI_GET_CONTEXT(ctx); - usbi_mutex_lock(&ctx->events_lock); - ctx->event_handler_active = 1; -} - -/** \ingroup libusb_poll - * Release the lock previously acquired with libusb_try_lock_events() or - * libusb_lock_events(). Releasing this lock will wake up any threads blocked - * on libusb_wait_for_event(). - * - * \param ctx the context to operate on, or NULL for the default context - * \ref libusb_mtasync - */ -void API_EXPORTED libusb_unlock_events(libusb_context *ctx) -{ - USBI_GET_CONTEXT(ctx); - ctx->event_handler_active = 0; - usbi_mutex_unlock(&ctx->events_lock); - - /* FIXME: perhaps we should be a bit more efficient by not broadcasting - * the availability of the events lock when we are modifying pollfds - * (check ctx->device_close)? */ - usbi_mutex_lock(&ctx->event_waiters_lock); - usbi_cond_broadcast(&ctx->event_waiters_cond); - usbi_mutex_unlock(&ctx->event_waiters_lock); -} - -/** \ingroup libusb_poll - * Determine if it is still OK for this thread to be doing event handling. - * - * Sometimes, libusb needs to temporarily pause all event handlers, and this - * is the function you should use before polling file descriptors to see if - * this is the case. - * - * If this function instructs your thread to give up the events lock, you - * should just continue the usual logic that is documented in \ref libusb_mtasync. - * On the next iteration, your thread will fail to obtain the events lock, - * and will hence become an event waiter. - * - * This function should be called while the events lock is held: you don't - * need to worry about the results of this function if your thread is not - * the current event handler. - * - * \param ctx the context to operate on, or NULL for the default context - * \returns 1 if event handling can start or continue - * \returns 0 if this thread must give up the events lock - * \ref fullstory "Multi-threaded I/O: the full story" - */ -int API_EXPORTED libusb_event_handling_ok(libusb_context *ctx) -{ - unsigned int r; - USBI_GET_CONTEXT(ctx); - - /* is someone else waiting to close a device? if so, don't let this thread - * continue event handling */ - usbi_mutex_lock(&ctx->event_data_lock); - r = ctx->device_close; - usbi_mutex_unlock(&ctx->event_data_lock); - if (r) { - usbi_dbg("someone else is closing a device"); - return 0; - } - - return 1; -} - - -/** \ingroup libusb_poll - * Determine if an active thread is handling events (i.e. if anyone is holding - * the event handling lock). - * - * \param ctx the context to operate on, or NULL for the default context - * \returns 1 if a thread is handling events - * \returns 0 if there are no threads currently handling events - * \ref libusb_mtasync - */ -int API_EXPORTED libusb_event_handler_active(libusb_context *ctx) -{ - unsigned int r; - USBI_GET_CONTEXT(ctx); - - /* is someone else waiting to close a device? if so, don't let this thread - * start event handling -- indicate that event handling is happening */ - usbi_mutex_lock(&ctx->event_data_lock); - r = ctx->device_close; - usbi_mutex_unlock(&ctx->event_data_lock); - if (r) { - usbi_dbg("someone else is closing a device"); - return 1; - } - - return ctx->event_handler_active; -} - -/** \ingroup libusb_poll - * Interrupt any active thread that is handling events. This is mainly useful - * for interrupting a dedicated event handling thread when an application - * wishes to call libusb_exit(). - * - * Since version 1.0.21, \ref LIBUSB_API_VERSION >= 0x01000105 - * - * \param ctx the context to operate on, or NULL for the default context - * \ref libusb_mtasync - */ -void API_EXPORTED libusb_interrupt_event_handler(libusb_context *ctx) -{ - int pending_events; - USBI_GET_CONTEXT(ctx); - - usbi_dbg(""); - usbi_mutex_lock(&ctx->event_data_lock); - - pending_events = usbi_pending_events(ctx); - ctx->event_flags |= USBI_EVENT_USER_INTERRUPT; - if (!pending_events) - usbi_signal_event(ctx); - - usbi_mutex_unlock(&ctx->event_data_lock); -} - -/** \ingroup libusb_poll - * Acquire the event waiters lock. This lock is designed to be obtained under - * the situation where you want to be aware when events are completed, but - * some other thread is event handling so calling libusb_handle_events() is not - * allowed. - * - * You then obtain this lock, re-check that another thread is still handling - * events, then call libusb_wait_for_event(). - * - * You only need to use this lock if you are developing an application - * which calls poll() or select() on libusb's file descriptors directly, - * and may potentially be handling events from 2 threads simultaenously. - * If you stick to libusb's event handling loop functions (e.g. - * libusb_handle_events()) then you do not need to be concerned with this - * locking. - * - * \param ctx the context to operate on, or NULL for the default context - * \ref libusb_mtasync - */ -void API_EXPORTED libusb_lock_event_waiters(libusb_context *ctx) -{ - USBI_GET_CONTEXT(ctx); - usbi_mutex_lock(&ctx->event_waiters_lock); -} - -/** \ingroup libusb_poll - * Release the event waiters lock. - * \param ctx the context to operate on, or NULL for the default context - * \ref libusb_mtasync - */ -void API_EXPORTED libusb_unlock_event_waiters(libusb_context *ctx) -{ - USBI_GET_CONTEXT(ctx); - usbi_mutex_unlock(&ctx->event_waiters_lock); -} - -/** \ingroup libusb_poll - * Wait for another thread to signal completion of an event. Must be called - * with the event waiters lock held, see libusb_lock_event_waiters(). - * - * This function will block until any of the following conditions are met: - * -# The timeout expires - * -# A transfer completes - * -# A thread releases the event handling lock through libusb_unlock_events() - * - * Condition 1 is obvious. Condition 2 unblocks your thread after - * the callback for the transfer has completed. Condition 3 is important - * because it means that the thread that was previously handling events is no - * longer doing so, so if any events are to complete, another thread needs to - * step up and start event handling. - * - * This function releases the event waiters lock before putting your thread - * to sleep, and reacquires the lock as it is being woken up. - * - * \param ctx the context to operate on, or NULL for the default context - * \param tv maximum timeout for this blocking function. A NULL value - * indicates unlimited timeout. - * \returns 0 after a transfer completes or another thread stops event handling - * \returns 1 if the timeout expired - * \ref libusb_mtasync - */ -int API_EXPORTED libusb_wait_for_event(libusb_context *ctx, struct timeval *tv) -{ - int r; - - USBI_GET_CONTEXT(ctx); - if (tv == NULL) { - usbi_cond_wait(&ctx->event_waiters_cond, &ctx->event_waiters_lock); - return 0; - } - - r = usbi_cond_timedwait(&ctx->event_waiters_cond, - &ctx->event_waiters_lock, tv); - - if (r < 0) - return r; - else - return (r == ETIMEDOUT); -} - -static void handle_timeout(struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer = - USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - int r; - - itransfer->timeout_flags |= USBI_TRANSFER_TIMEOUT_HANDLED; - r = libusb_cancel_transfer(transfer); - if (r == LIBUSB_SUCCESS) - itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT; - else - usbi_warn(TRANSFER_CTX(transfer), - "async cancel failed %d errno=%d", r, errno); -} - -static int handle_timeouts_locked(struct libusb_context *ctx) -{ - int r; - struct timespec systime_ts; - struct timeval systime; - struct usbi_transfer *transfer; - - if (list_empty(&ctx->flying_transfers)) - return 0; - - /* get current time */ - r = usbi_backend->clock_gettime(USBI_CLOCK_MONOTONIC, &systime_ts); - if (r < 0) - return r; - - TIMESPEC_TO_TIMEVAL(&systime, &systime_ts); - - /* iterate through flying transfers list, finding all transfers that - * have expired timeouts */ - list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) { - struct timeval *cur_tv = &transfer->timeout; - - /* if we've reached transfers of infinite timeout, we're all done */ - if (!timerisset(cur_tv)) - return 0; - - /* ignore timeouts we've already handled */ - if (transfer->timeout_flags & (USBI_TRANSFER_TIMEOUT_HANDLED | USBI_TRANSFER_OS_HANDLES_TIMEOUT)) - continue; - - /* if transfer has non-expired timeout, nothing more to do */ - if ((cur_tv->tv_sec > systime.tv_sec) || - (cur_tv->tv_sec == systime.tv_sec && - cur_tv->tv_usec > systime.tv_usec)) - return 0; - - /* otherwise, we've got an expired timeout to handle */ - handle_timeout(transfer); - } - return 0; -} - -static int handle_timeouts(struct libusb_context *ctx) -{ - int r; - USBI_GET_CONTEXT(ctx); - usbi_mutex_lock(&ctx->flying_transfers_lock); - r = handle_timeouts_locked(ctx); - usbi_mutex_unlock(&ctx->flying_transfers_lock); - return r; -} - -#ifdef USBI_TIMERFD_AVAILABLE -static int handle_timerfd_trigger(struct libusb_context *ctx) -{ - int r; - - usbi_mutex_lock(&ctx->flying_transfers_lock); - - /* process the timeout that just happened */ - r = handle_timeouts_locked(ctx); - if (r < 0) - goto out; - - /* arm for next timeout*/ - r = arm_timerfd_for_next_timeout(ctx); - -out: - usbi_mutex_unlock(&ctx->flying_transfers_lock); - return r; -} -#endif - -/* do the actual event handling. assumes that no other thread is concurrently - * doing the same thing. */ -static int handle_events(struct libusb_context *ctx, struct timeval *tv) -{ - int r; - struct usbi_pollfd *ipollfd; - POLL_NFDS_TYPE nfds = 0; - POLL_NFDS_TYPE internal_nfds; - struct pollfd *fds = NULL; - int i = -1; - int timeout_ms; - int special_event; - - /* prevent attempts to recursively handle events (e.g. calling into - * libusb_handle_events() from within a hotplug or transfer callback) */ - if (usbi_handling_events(ctx)) - return LIBUSB_ERROR_BUSY; - usbi_start_event_handling(ctx); - - /* there are certain fds that libusb uses internally, currently: - * - * 1) event pipe - * 2) timerfd - * - * the backend will never need to attempt to handle events on these fds, so - * we determine how many fds are in use internally for this context and when - * handle_events() is called in the backend, the pollfd list and count will - * be adjusted to skip over these internal fds */ - if (usbi_using_timerfd(ctx)) - internal_nfds = 2; - else - internal_nfds = 1; - - /* only reallocate the poll fds when the list of poll fds has been modified - * since the last poll, otherwise reuse them to save the additional overhead */ - usbi_mutex_lock(&ctx->event_data_lock); - if (ctx->event_flags & USBI_EVENT_POLLFDS_MODIFIED) { - usbi_dbg("poll fds modified, reallocating"); - - if (ctx->pollfds) { - free(ctx->pollfds); - ctx->pollfds = NULL; - } - - /* sanity check - it is invalid for a context to have fewer than the - * required internal fds (memory corruption?) */ - assert(ctx->pollfds_cnt >= internal_nfds); - - ctx->pollfds = calloc(ctx->pollfds_cnt, sizeof(*ctx->pollfds)); - if (!ctx->pollfds) { - usbi_mutex_unlock(&ctx->event_data_lock); - r = LIBUSB_ERROR_NO_MEM; - goto done; - } - - list_for_each_entry(ipollfd, &ctx->ipollfds, list, struct usbi_pollfd) { - struct libusb_pollfd *pollfd = &ipollfd->pollfd; - i++; - ctx->pollfds[i].fd = pollfd->fd; - ctx->pollfds[i].events = pollfd->events; - } - - /* reset the flag now that we have the updated list */ - ctx->event_flags &= ~USBI_EVENT_POLLFDS_MODIFIED; - - /* if no further pending events, clear the event pipe so that we do - * not immediately return from poll */ - if (!usbi_pending_events(ctx)) - usbi_clear_event(ctx); - } - fds = ctx->pollfds; - nfds = ctx->pollfds_cnt; - usbi_mutex_unlock(&ctx->event_data_lock); - - timeout_ms = (int)(tv->tv_sec * 1000) + (tv->tv_usec / 1000); - - /* round up to next millisecond */ - if (tv->tv_usec % 1000) - timeout_ms++; - -redo_poll: - usbi_dbg("poll() %d fds with timeout in %dms", nfds, timeout_ms); - r = usbi_poll(fds, nfds, timeout_ms); - usbi_dbg("poll() returned %d", r); - if (r == 0) { - r = handle_timeouts(ctx); - goto done; - } - else if (r == -1 && errno == EINTR) { - r = LIBUSB_ERROR_INTERRUPTED; - goto done; - } - else if (r < 0) { - usbi_err(ctx, "poll failed %d err=%d", r, errno); - r = LIBUSB_ERROR_IO; - goto done; - } - - special_event = 0; - - /* fds[0] is always the event pipe */ - if (fds[0].revents) { - libusb_hotplug_message *message = NULL; - struct usbi_transfer *itransfer; - int ret = 0; - - usbi_dbg("caught a fish on the event pipe"); - - /* take the the event data lock while processing events */ - usbi_mutex_lock(&ctx->event_data_lock); - - /* check if someone added a new poll fd */ - if (ctx->event_flags & USBI_EVENT_POLLFDS_MODIFIED) - usbi_dbg("someone updated the poll fds"); - - if (ctx->event_flags & USBI_EVENT_USER_INTERRUPT) { - usbi_dbg("someone purposely interrupted"); - ctx->event_flags &= ~USBI_EVENT_USER_INTERRUPT; - } - - /* check if someone is closing a device */ - if (ctx->device_close) - usbi_dbg("someone is closing a device"); - - /* check for any pending hotplug messages */ - if (!list_empty(&ctx->hotplug_msgs)) { - usbi_dbg("hotplug message received"); - special_event = 1; - message = list_first_entry(&ctx->hotplug_msgs, libusb_hotplug_message, list); - list_del(&message->list); - } - - /* complete any pending transfers */ - while (ret == 0 && !list_empty(&ctx->completed_transfers)) { - itransfer = list_first_entry(&ctx->completed_transfers, struct usbi_transfer, completed_list); - list_del(&itransfer->completed_list); - usbi_mutex_unlock(&ctx->event_data_lock); - ret = usbi_backend->handle_transfer_completion(itransfer); - if (ret) - usbi_err(ctx, "backend handle_transfer_completion failed with error %d", ret); - usbi_mutex_lock(&ctx->event_data_lock); - } - - /* if no further pending events, clear the event pipe */ - if (!usbi_pending_events(ctx)) - usbi_clear_event(ctx); - - usbi_mutex_unlock(&ctx->event_data_lock); - - /* process the hotplug message, if any */ - if (message) { - usbi_hotplug_match(ctx, message->device, message->event); - - /* the device left, dereference the device */ - if (LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT == message->event) - libusb_unref_device(message->device); - - free(message); - } - - if (ret) { - /* return error code */ - r = ret; - goto done; - } - - if (0 == --r) - goto handled; - } - -#ifdef USBI_TIMERFD_AVAILABLE - /* on timerfd configurations, fds[1] is the timerfd */ - if (usbi_using_timerfd(ctx) && fds[1].revents) { - /* timerfd indicates that a timeout has expired */ - int ret; - usbi_dbg("timerfd triggered"); - special_event = 1; - - ret = handle_timerfd_trigger(ctx); - if (ret < 0) { - /* return error code */ - r = ret; - goto done; - } - - if (0 == --r) - goto handled; - } -#endif - - r = usbi_backend->handle_events(ctx, fds + internal_nfds, nfds - internal_nfds, r); - if (r) - usbi_err(ctx, "backend handle_events failed with error %d", r); - -handled: - if (r == 0 && special_event) { - timeout_ms = 0; - goto redo_poll; - } - -done: - usbi_end_event_handling(ctx); - return r; -} - -/* returns the smallest of: - * 1. timeout of next URB - * 2. user-supplied timeout - * returns 1 if there is an already-expired timeout, otherwise returns 0 - * and populates out - */ -static int get_next_timeout(libusb_context *ctx, struct timeval *tv, - struct timeval *out) -{ - struct timeval timeout; - int r = libusb_get_next_timeout(ctx, &timeout); - if (r) { - /* timeout already expired? */ - if (!timerisset(&timeout)) - return 1; - - /* choose the smallest of next URB timeout or user specified timeout */ - if (timercmp(&timeout, tv, <)) - *out = timeout; - else - *out = *tv; - } else { - *out = *tv; - } - return 0; -} - -/** \ingroup libusb_poll - * Handle any pending events. - * - * libusb determines "pending events" by checking if any timeouts have expired - * and by checking the set of file descriptors for activity. - * - * If a zero timeval is passed, this function will handle any already-pending - * events and then immediately return in non-blocking style. - * - * If a non-zero timeval is passed and no events are currently pending, this - * function will block waiting for events to handle up until the specified - * timeout. If an event arrives or a signal is raised, this function will - * return early. - * - * If the parameter completed is not NULL then after obtaining the event - * handling lock this function will return immediately if the integer - * pointed to is not 0. This allows for race free waiting for the completion - * of a specific transfer. - * - * \param ctx the context to operate on, or NULL for the default context - * \param tv the maximum time to block waiting for events, or an all zero - * timeval struct for non-blocking mode - * \param completed pointer to completion integer to check, or NULL - * \returns 0 on success, or a LIBUSB_ERROR code on failure - * \ref libusb_mtasync - */ -int API_EXPORTED libusb_handle_events_timeout_completed(libusb_context *ctx, - struct timeval *tv, int *completed) -{ - int r; - struct timeval poll_timeout; - - USBI_GET_CONTEXT(ctx); - r = get_next_timeout(ctx, tv, &poll_timeout); - if (r) { - /* timeout already expired */ - return handle_timeouts(ctx); - } - -retry: - if (libusb_try_lock_events(ctx) == 0) { - if (completed == NULL || !*completed) { - /* we obtained the event lock: do our own event handling */ - usbi_dbg("doing our own event handling"); - r = handle_events(ctx, &poll_timeout); - } - libusb_unlock_events(ctx); - return r; - } - - /* another thread is doing event handling. wait for thread events that - * notify event completion. */ - libusb_lock_event_waiters(ctx); - - if (completed && *completed) - goto already_done; - - if (!libusb_event_handler_active(ctx)) { - /* we hit a race: whoever was event handling earlier finished in the - * time it took us to reach this point. try the cycle again. */ - libusb_unlock_event_waiters(ctx); - usbi_dbg("event handler was active but went away, retrying"); - goto retry; - } - - usbi_dbg("another thread is doing event handling"); - r = libusb_wait_for_event(ctx, &poll_timeout); - -already_done: - libusb_unlock_event_waiters(ctx); - - if (r < 0) - return r; - else if (r == 1) - return handle_timeouts(ctx); - else - return 0; -} - -/** \ingroup libusb_poll - * Handle any pending events - * - * Like libusb_handle_events_timeout_completed(), but without the completed - * parameter, calling this function is equivalent to calling - * libusb_handle_events_timeout_completed() with a NULL completed parameter. - * - * This function is kept primarily for backwards compatibility. - * All new code should call libusb_handle_events_completed() or - * libusb_handle_events_timeout_completed() to avoid race conditions. - * - * \param ctx the context to operate on, or NULL for the default context - * \param tv the maximum time to block waiting for events, or an all zero - * timeval struct for non-blocking mode - * \returns 0 on success, or a LIBUSB_ERROR code on failure - */ -int API_EXPORTED libusb_handle_events_timeout(libusb_context *ctx, - struct timeval *tv) -{ - return libusb_handle_events_timeout_completed(ctx, tv, NULL); -} - -/** \ingroup libusb_poll - * Handle any pending events in blocking mode. There is currently a timeout - * hardcoded at 60 seconds but we plan to make it unlimited in future. For - * finer control over whether this function is blocking or non-blocking, or - * for control over the timeout, use libusb_handle_events_timeout_completed() - * instead. - * - * This function is kept primarily for backwards compatibility. - * All new code should call libusb_handle_events_completed() or - * libusb_handle_events_timeout_completed() to avoid race conditions. - * - * \param ctx the context to operate on, or NULL for the default context - * \returns 0 on success, or a LIBUSB_ERROR code on failure - */ -int API_EXPORTED libusb_handle_events(libusb_context *ctx) -{ - struct timeval tv; - tv.tv_sec = 60; - tv.tv_usec = 0; - return libusb_handle_events_timeout_completed(ctx, &tv, NULL); -} - -/** \ingroup libusb_poll - * Handle any pending events in blocking mode. - * - * Like libusb_handle_events(), with the addition of a completed parameter - * to allow for race free waiting for the completion of a specific transfer. - * - * See libusb_handle_events_timeout_completed() for details on the completed - * parameter. - * - * \param ctx the context to operate on, or NULL for the default context - * \param completed pointer to completion integer to check, or NULL - * \returns 0 on success, or a LIBUSB_ERROR code on failure - * \ref libusb_mtasync - */ -int API_EXPORTED libusb_handle_events_completed(libusb_context *ctx, - int *completed) -{ - struct timeval tv; - tv.tv_sec = 60; - tv.tv_usec = 0; - return libusb_handle_events_timeout_completed(ctx, &tv, completed); -} - -/** \ingroup libusb_poll - * Handle any pending events by polling file descriptors, without checking if - * any other threads are already doing so. Must be called with the event lock - * held, see libusb_lock_events(). - * - * This function is designed to be called under the situation where you have - * taken the event lock and are calling poll()/select() directly on libusb's - * file descriptors (as opposed to using libusb_handle_events() or similar). - * You detect events on libusb's descriptors, so you then call this function - * with a zero timeout value (while still holding the event lock). - * - * \param ctx the context to operate on, or NULL for the default context - * \param tv the maximum time to block waiting for events, or zero for - * non-blocking mode - * \returns 0 on success, or a LIBUSB_ERROR code on failure - * \ref libusb_mtasync - */ -int API_EXPORTED libusb_handle_events_locked(libusb_context *ctx, - struct timeval *tv) -{ - int r; - struct timeval poll_timeout; - - USBI_GET_CONTEXT(ctx); - r = get_next_timeout(ctx, tv, &poll_timeout); - if (r) { - /* timeout already expired */ - return handle_timeouts(ctx); - } - - return handle_events(ctx, &poll_timeout); -} - -/** \ingroup libusb_poll - * Determines whether your application must apply special timing considerations - * when monitoring libusb's file descriptors. - * - * This function is only useful for applications which retrieve and poll - * libusb's file descriptors in their own main loop (\ref libusb_pollmain). - * - * Ordinarily, libusb's event handler needs to be called into at specific - * moments in time (in addition to times when there is activity on the file - * descriptor set). The usual approach is to use libusb_get_next_timeout() - * to learn about when the next timeout occurs, and to adjust your - * poll()/select() timeout accordingly so that you can make a call into the - * library at that time. - * - * Some platforms supported by libusb do not come with this baggage - any - * events relevant to timing will be represented by activity on the file - * descriptor set, and libusb_get_next_timeout() will always return 0. - * This function allows you to detect whether you are running on such a - * platform. - * - * Since v1.0.5. - * - * \param ctx the context to operate on, or NULL for the default context - * \returns 0 if you must call into libusb at times determined by - * libusb_get_next_timeout(), or 1 if all timeout events are handled internally - * or through regular activity on the file descriptors. - * \ref libusb_pollmain "Polling libusb file descriptors for event handling" - */ -int API_EXPORTED libusb_pollfds_handle_timeouts(libusb_context *ctx) -{ -#if defined(USBI_TIMERFD_AVAILABLE) - USBI_GET_CONTEXT(ctx); - return usbi_using_timerfd(ctx); -#else - UNUSED(ctx); - return 0; -#endif -} - -/** \ingroup libusb_poll - * Determine the next internal timeout that libusb needs to handle. You only - * need to use this function if you are calling poll() or select() or similar - * on libusb's file descriptors yourself - you do not need to use it if you - * are calling libusb_handle_events() or a variant directly. - * - * You should call this function in your main loop in order to determine how - * long to wait for select() or poll() to return results. libusb needs to be - * called into at this timeout, so you should use it as an upper bound on - * your select() or poll() call. - * - * When the timeout has expired, call into libusb_handle_events_timeout() - * (perhaps in non-blocking mode) so that libusb can handle the timeout. - * - * This function may return 1 (success) and an all-zero timeval. If this is - * the case, it indicates that libusb has a timeout that has already expired - * so you should call libusb_handle_events_timeout() or similar immediately. - * A return code of 0 indicates that there are no pending timeouts. - * - * On some platforms, this function will always returns 0 (no pending - * timeouts). See \ref polltime. - * - * \param ctx the context to operate on, or NULL for the default context - * \param tv output location for a relative time against the current - * clock in which libusb must be called into in order to process timeout events - * \returns 0 if there are no pending timeouts, 1 if a timeout was returned, - * or LIBUSB_ERROR_OTHER on failure - */ -int API_EXPORTED libusb_get_next_timeout(libusb_context *ctx, - struct timeval *tv) -{ - struct usbi_transfer *transfer; - struct timespec cur_ts; - struct timeval cur_tv; - struct timeval next_timeout = { 0, 0 }; - int r; - - USBI_GET_CONTEXT(ctx); - if (usbi_using_timerfd(ctx)) - return 0; - - usbi_mutex_lock(&ctx->flying_transfers_lock); - if (list_empty(&ctx->flying_transfers)) { - usbi_mutex_unlock(&ctx->flying_transfers_lock); - usbi_dbg("no URBs, no timeout!"); - return 0; - } - - /* find next transfer which hasn't already been processed as timed out */ - list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) { - if (transfer->timeout_flags & (USBI_TRANSFER_TIMEOUT_HANDLED | USBI_TRANSFER_OS_HANDLES_TIMEOUT)) - continue; - - /* if we've reached transfers of infinte timeout, we're done looking */ - if (!timerisset(&transfer->timeout)) - break; - - next_timeout = transfer->timeout; - break; - } - usbi_mutex_unlock(&ctx->flying_transfers_lock); - - if (!timerisset(&next_timeout)) { - usbi_dbg("no URB with timeout or all handled by OS; no timeout!"); - return 0; - } - - r = usbi_backend->clock_gettime(USBI_CLOCK_MONOTONIC, &cur_ts); - if (r < 0) { - usbi_err(ctx, "failed to read monotonic clock, errno=%d", errno); - return 0; - } - TIMESPEC_TO_TIMEVAL(&cur_tv, &cur_ts); - - if (!timercmp(&cur_tv, &next_timeout, <)) { - usbi_dbg("first timeout already expired"); - timerclear(tv); - } else { - timersub(&next_timeout, &cur_tv, tv); - usbi_dbg("next timeout in %d.%06ds", tv->tv_sec, tv->tv_usec); - } - - return 1; -} - -/** \ingroup libusb_poll - * Register notification functions for file descriptor additions/removals. - * These functions will be invoked for every new or removed file descriptor - * that libusb uses as an event source. - * - * To remove notifiers, pass NULL values for the function pointers. - * - * Note that file descriptors may have been added even before you register - * these notifiers (e.g. at libusb_init() time). - * - * Additionally, note that the removal notifier may be called during - * libusb_exit() (e.g. when it is closing file descriptors that were opened - * and added to the poll set at libusb_init() time). If you don't want this, - * remove the notifiers immediately before calling libusb_exit(). - * - * \param ctx the context to operate on, or NULL for the default context - * \param added_cb pointer to function for addition notifications - * \param removed_cb pointer to function for removal notifications - * \param user_data User data to be passed back to callbacks (useful for - * passing context information) - */ -void API_EXPORTED libusb_set_pollfd_notifiers(libusb_context *ctx, - libusb_pollfd_added_cb added_cb, libusb_pollfd_removed_cb removed_cb, - void *user_data) -{ - USBI_GET_CONTEXT(ctx); - ctx->fd_added_cb = added_cb; - ctx->fd_removed_cb = removed_cb; - ctx->fd_cb_user_data = user_data; -} - -/* - * Interrupt the iteration of the event handling thread, so that it picks - * up the fd change. Callers of this function must hold the event_data_lock. - */ -static void usbi_fd_notification(struct libusb_context *ctx) -{ - int pending_events; - - /* Record that there is a new poll fd. - * Only signal an event if there are no prior pending events. */ - pending_events = usbi_pending_events(ctx); - ctx->event_flags |= USBI_EVENT_POLLFDS_MODIFIED; - if (!pending_events) - usbi_signal_event(ctx); -} - -/* Add a file descriptor to the list of file descriptors to be monitored. - * events should be specified as a bitmask of events passed to poll(), e.g. - * POLLIN and/or POLLOUT. */ -int usbi_add_pollfd(struct libusb_context *ctx, int fd, short events) -{ - struct usbi_pollfd *ipollfd = malloc(sizeof(*ipollfd)); - if (!ipollfd) - return LIBUSB_ERROR_NO_MEM; - - usbi_dbg("add fd %d events %d", fd, events); - ipollfd->pollfd.fd = fd; - ipollfd->pollfd.events = events; - usbi_mutex_lock(&ctx->event_data_lock); - list_add_tail(&ipollfd->list, &ctx->ipollfds); - ctx->pollfds_cnt++; - usbi_fd_notification(ctx); - usbi_mutex_unlock(&ctx->event_data_lock); - - if (ctx->fd_added_cb) - ctx->fd_added_cb(fd, events, ctx->fd_cb_user_data); - return 0; -} - -/* Remove a file descriptor from the list of file descriptors to be polled. */ -void usbi_remove_pollfd(struct libusb_context *ctx, int fd) -{ - struct usbi_pollfd *ipollfd; - int found = 0; - - usbi_dbg("remove fd %d", fd); - usbi_mutex_lock(&ctx->event_data_lock); - list_for_each_entry(ipollfd, &ctx->ipollfds, list, struct usbi_pollfd) - if (ipollfd->pollfd.fd == fd) { - found = 1; - break; - } - - if (!found) { - usbi_dbg("couldn't find fd %d to remove", fd); - usbi_mutex_unlock(&ctx->event_data_lock); - return; - } - - list_del(&ipollfd->list); - ctx->pollfds_cnt--; - usbi_fd_notification(ctx); - usbi_mutex_unlock(&ctx->event_data_lock); - free(ipollfd); - if (ctx->fd_removed_cb) - ctx->fd_removed_cb(fd, ctx->fd_cb_user_data); -} - -/** \ingroup libusb_poll - * Retrieve a list of file descriptors that should be polled by your main loop - * as libusb event sources. - * - * The returned list is NULL-terminated and should be freed with libusb_free_pollfds() - * when done. The actual list contents must not be touched. - * - * As file descriptors are a Unix-specific concept, this function is not - * available on Windows and will always return NULL. - * - * \param ctx the context to operate on, or NULL for the default context - * \returns a NULL-terminated list of libusb_pollfd structures - * \returns NULL on error - * \returns NULL on platforms where the functionality is not available - */ -DEFAULT_VISIBILITY -const struct libusb_pollfd ** LIBUSB_CALL libusb_get_pollfds( - libusb_context *ctx) -{ -#ifndef OS_WINDOWS - struct libusb_pollfd **ret = NULL; - struct usbi_pollfd *ipollfd; - size_t i = 0; - USBI_GET_CONTEXT(ctx); - - usbi_mutex_lock(&ctx->event_data_lock); - - ret = calloc(ctx->pollfds_cnt + 1, sizeof(struct libusb_pollfd *)); - if (!ret) - goto out; - - list_for_each_entry(ipollfd, &ctx->ipollfds, list, struct usbi_pollfd) - ret[i++] = (struct libusb_pollfd *) ipollfd; - ret[ctx->pollfds_cnt] = NULL; - -out: - usbi_mutex_unlock(&ctx->event_data_lock); - return (const struct libusb_pollfd **) ret; -#else - usbi_err(ctx, "external polling of libusb's internal descriptors "\ - "is not yet supported on Windows platforms"); - return NULL; -#endif -} - -/** \ingroup libusb_poll - * Free a list of libusb_pollfd structures. This should be called for all - * pollfd lists allocated with libusb_get_pollfds(). - * - * Since version 1.0.20, \ref LIBUSB_API_VERSION >= 0x01000104 - * - * It is legal to call this function with a NULL pollfd list. In this case, - * the function will simply return safely. - * - * \param pollfds the list of libusb_pollfd structures to free - */ -void API_EXPORTED libusb_free_pollfds(const struct libusb_pollfd **pollfds) -{ - if (!pollfds) - return; - - free((void *)pollfds); -} - -/* Backends may call this from handle_events to report disconnection of a - * device. This function ensures transfers get cancelled appropriately. - * Callers of this function must hold the events_lock. - */ -void usbi_handle_disconnect(struct libusb_device_handle *dev_handle) -{ - struct usbi_transfer *cur; - struct usbi_transfer *to_cancel; - - usbi_dbg("device %d.%d", - dev_handle->dev->bus_number, dev_handle->dev->device_address); - - /* terminate all pending transfers with the LIBUSB_TRANSFER_NO_DEVICE - * status code. - * - * when we find a transfer for this device on the list, there are two - * possible scenarios: - * 1. the transfer is currently in-flight, in which case we terminate the - * transfer here - * 2. the transfer has been added to the flying transfer list by - * libusb_submit_transfer, has failed to submit and - * libusb_submit_transfer is waiting for us to release the - * flying_transfers_lock to remove it, so we ignore it - */ - - while (1) { - to_cancel = NULL; - usbi_mutex_lock(&HANDLE_CTX(dev_handle)->flying_transfers_lock); - list_for_each_entry(cur, &HANDLE_CTX(dev_handle)->flying_transfers, list, struct usbi_transfer) - if (USBI_TRANSFER_TO_LIBUSB_TRANSFER(cur)->dev_handle == dev_handle) { - usbi_mutex_lock(&cur->lock); - if (cur->state_flags & USBI_TRANSFER_IN_FLIGHT) - to_cancel = cur; - usbi_mutex_unlock(&cur->lock); - - if (to_cancel) - break; - } - usbi_mutex_unlock(&HANDLE_CTX(dev_handle)->flying_transfers_lock); - - if (!to_cancel) - break; - - usbi_dbg("cancelling transfer %p from disconnect", - USBI_TRANSFER_TO_LIBUSB_TRANSFER(to_cancel)); - - usbi_mutex_lock(&to_cancel->lock); - usbi_backend->clear_transfer_priv(to_cancel); - usbi_mutex_unlock(&to_cancel->lock); - usbi_handle_transfer_completion(to_cancel, LIBUSB_TRANSFER_NO_DEVICE); - } - -} diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/libusb.h b/vendor/github.com/karalabe/hid/libusb/libusb/libusb.h deleted file mode 100644 index c562690f..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/libusb.h +++ /dev/null @@ -1,2008 +0,0 @@ -/* - * Public libusb header file - * Copyright © 2001 Johannes Erdfelt - * Copyright © 2007-2008 Daniel Drake - * Copyright © 2012 Pete Batard - * Copyright © 2012 Nathan Hjelm - * For more information, please visit: http://libusb.info - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef LIBUSB_H -#define LIBUSB_H - -#ifdef _MSC_VER -/* on MS environments, the inline keyword is available in C++ only */ -#if !defined(__cplusplus) -#define inline __inline -#endif -/* ssize_t is also not available (copy/paste from MinGW) */ -#ifndef _SSIZE_T_DEFINED -#define _SSIZE_T_DEFINED -#undef ssize_t -#ifdef _WIN64 - typedef __int64 ssize_t; -#else - typedef int ssize_t; -#endif /* _WIN64 */ -#endif /* _SSIZE_T_DEFINED */ -#endif /* _MSC_VER */ - -/* stdint.h is not available on older MSVC */ -#if defined(_MSC_VER) && (_MSC_VER < 1600) && (!defined(_STDINT)) && (!defined(_STDINT_H)) -typedef unsigned __int8 uint8_t; -typedef unsigned __int16 uint16_t; -typedef unsigned __int32 uint32_t; -#else -#include -#endif - -#if !defined(_WIN32_WCE) -#include -#endif - -#if defined(__linux) || defined(__APPLE__) || defined(__CYGWIN__) || defined(__HAIKU__) -#include -#endif - -#include -#include - -/* 'interface' might be defined as a macro on Windows, so we need to - * undefine it so as not to break the current libusb API, because - * libusb_config_descriptor has an 'interface' member - * As this can be problematic if you include windows.h after libusb.h - * in your sources, we force windows.h to be included first. */ -#if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE) -#include -#if defined(interface) -#undef interface -#endif -#if !defined(__CYGWIN__) -#include -#endif -#endif - -#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) -#define LIBUSB_DEPRECATED_FOR(f) \ - __attribute__((deprecated("Use " #f " instead"))) -#else -#define LIBUSB_DEPRECATED_FOR(f) -#endif /* __GNUC__ */ - -/** \def LIBUSB_CALL - * \ingroup libusb_misc - * libusb's Windows calling convention. - * - * Under Windows, the selection of available compilers and configurations - * means that, unlike other platforms, there is not one true calling - * convention (calling convention: the manner in which parameters are - * passed to functions in the generated assembly code). - * - * Matching the Windows API itself, libusb uses the WINAPI convention (which - * translates to the stdcall convention) and guarantees that the - * library is compiled in this way. The public header file also includes - * appropriate annotations so that your own software will use the right - * convention, even if another convention is being used by default within - * your codebase. - * - * The one consideration that you must apply in your software is to mark - * all functions which you use as libusb callbacks with this LIBUSB_CALL - * annotation, so that they too get compiled for the correct calling - * convention. - * - * On non-Windows operating systems, this macro is defined as nothing. This - * means that you can apply it to your code without worrying about - * cross-platform compatibility. - */ -/* LIBUSB_CALL must be defined on both definition and declaration of libusb - * functions. You'd think that declaration would be enough, but cygwin will - * complain about conflicting types unless both are marked this way. - * The placement of this macro is important too; it must appear after the - * return type, before the function name. See internal documentation for - * API_EXPORTED. - */ -#if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE) -#define LIBUSB_CALL WINAPI -#else -#define LIBUSB_CALL -#endif - -/** \def LIBUSB_API_VERSION - * \ingroup libusb_misc - * libusb's API version. - * - * Since version 1.0.13, to help with feature detection, libusb defines - * a LIBUSB_API_VERSION macro that gets increased every time there is a - * significant change to the API, such as the introduction of a new call, - * the definition of a new macro/enum member, or any other element that - * libusb applications may want to detect at compilation time. - * - * The macro is typically used in an application as follows: - * \code - * #if defined(LIBUSB_API_VERSION) && (LIBUSB_API_VERSION >= 0x01001234) - * // Use one of the newer features from the libusb API - * #endif - * \endcode - * - * Internally, LIBUSB_API_VERSION is defined as follows: - * (libusb major << 24) | (libusb minor << 16) | (16 bit incremental) - */ -#define LIBUSB_API_VERSION 0x01000105 - -/* The following is kept for compatibility, but will be deprecated in the future */ -#define LIBUSBX_API_VERSION LIBUSB_API_VERSION - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \ingroup libusb_misc - * Convert a 16-bit value from host-endian to little-endian format. On - * little endian systems, this function does nothing. On big endian systems, - * the bytes are swapped. - * \param x the host-endian value to convert - * \returns the value in little-endian byte order - */ -static inline uint16_t libusb_cpu_to_le16(const uint16_t x) -{ - union { - uint8_t b8[2]; - uint16_t b16; - } _tmp; - _tmp.b8[1] = (uint8_t) (x >> 8); - _tmp.b8[0] = (uint8_t) (x & 0xff); - return _tmp.b16; -} - -/** \def libusb_le16_to_cpu - * \ingroup libusb_misc - * Convert a 16-bit value from little-endian to host-endian format. On - * little endian systems, this function does nothing. On big endian systems, - * the bytes are swapped. - * \param x the little-endian value to convert - * \returns the value in host-endian byte order - */ -#define libusb_le16_to_cpu libusb_cpu_to_le16 - -/* standard USB stuff */ - -/** \ingroup libusb_desc - * Device and/or Interface Class codes */ -enum libusb_class_code { - /** In the context of a \ref libusb_device_descriptor "device descriptor", - * this bDeviceClass value indicates that each interface specifies its - * own class information and all interfaces operate independently. - */ - LIBUSB_CLASS_PER_INTERFACE = 0, - - /** Audio class */ - LIBUSB_CLASS_AUDIO = 1, - - /** Communications class */ - LIBUSB_CLASS_COMM = 2, - - /** Human Interface Device class */ - LIBUSB_CLASS_HID = 3, - - /** Physical */ - LIBUSB_CLASS_PHYSICAL = 5, - - /** Printer class */ - LIBUSB_CLASS_PRINTER = 7, - - /** Image class */ - LIBUSB_CLASS_PTP = 6, /* legacy name from libusb-0.1 usb.h */ - LIBUSB_CLASS_IMAGE = 6, - - /** Mass storage class */ - LIBUSB_CLASS_MASS_STORAGE = 8, - - /** Hub class */ - LIBUSB_CLASS_HUB = 9, - - /** Data class */ - LIBUSB_CLASS_DATA = 10, - - /** Smart Card */ - LIBUSB_CLASS_SMART_CARD = 0x0b, - - /** Content Security */ - LIBUSB_CLASS_CONTENT_SECURITY = 0x0d, - - /** Video */ - LIBUSB_CLASS_VIDEO = 0x0e, - - /** Personal Healthcare */ - LIBUSB_CLASS_PERSONAL_HEALTHCARE = 0x0f, - - /** Diagnostic Device */ - LIBUSB_CLASS_DIAGNOSTIC_DEVICE = 0xdc, - - /** Wireless class */ - LIBUSB_CLASS_WIRELESS = 0xe0, - - /** Application class */ - LIBUSB_CLASS_APPLICATION = 0xfe, - - /** Class is vendor-specific */ - LIBUSB_CLASS_VENDOR_SPEC = 0xff -}; - -/** \ingroup libusb_desc - * Descriptor types as defined by the USB specification. */ -enum libusb_descriptor_type { - /** Device descriptor. See libusb_device_descriptor. */ - LIBUSB_DT_DEVICE = 0x01, - - /** Configuration descriptor. See libusb_config_descriptor. */ - LIBUSB_DT_CONFIG = 0x02, - - /** String descriptor */ - LIBUSB_DT_STRING = 0x03, - - /** Interface descriptor. See libusb_interface_descriptor. */ - LIBUSB_DT_INTERFACE = 0x04, - - /** Endpoint descriptor. See libusb_endpoint_descriptor. */ - LIBUSB_DT_ENDPOINT = 0x05, - - /** BOS descriptor */ - LIBUSB_DT_BOS = 0x0f, - - /** Device Capability descriptor */ - LIBUSB_DT_DEVICE_CAPABILITY = 0x10, - - /** HID descriptor */ - LIBUSB_DT_HID = 0x21, - - /** HID report descriptor */ - LIBUSB_DT_REPORT = 0x22, - - /** Physical descriptor */ - LIBUSB_DT_PHYSICAL = 0x23, - - /** Hub descriptor */ - LIBUSB_DT_HUB = 0x29, - - /** SuperSpeed Hub descriptor */ - LIBUSB_DT_SUPERSPEED_HUB = 0x2a, - - /** SuperSpeed Endpoint Companion descriptor */ - LIBUSB_DT_SS_ENDPOINT_COMPANION = 0x30 -}; - -/* Descriptor sizes per descriptor type */ -#define LIBUSB_DT_DEVICE_SIZE 18 -#define LIBUSB_DT_CONFIG_SIZE 9 -#define LIBUSB_DT_INTERFACE_SIZE 9 -#define LIBUSB_DT_ENDPOINT_SIZE 7 -#define LIBUSB_DT_ENDPOINT_AUDIO_SIZE 9 /* Audio extension */ -#define LIBUSB_DT_HUB_NONVAR_SIZE 7 -#define LIBUSB_DT_SS_ENDPOINT_COMPANION_SIZE 6 -#define LIBUSB_DT_BOS_SIZE 5 -#define LIBUSB_DT_DEVICE_CAPABILITY_SIZE 3 - -/* BOS descriptor sizes */ -#define LIBUSB_BT_USB_2_0_EXTENSION_SIZE 7 -#define LIBUSB_BT_SS_USB_DEVICE_CAPABILITY_SIZE 10 -#define LIBUSB_BT_CONTAINER_ID_SIZE 20 - -/* We unwrap the BOS => define its max size */ -#define LIBUSB_DT_BOS_MAX_SIZE ((LIBUSB_DT_BOS_SIZE) +\ - (LIBUSB_BT_USB_2_0_EXTENSION_SIZE) +\ - (LIBUSB_BT_SS_USB_DEVICE_CAPABILITY_SIZE) +\ - (LIBUSB_BT_CONTAINER_ID_SIZE)) - -#define LIBUSB_ENDPOINT_ADDRESS_MASK 0x0f /* in bEndpointAddress */ -#define LIBUSB_ENDPOINT_DIR_MASK 0x80 - -/** \ingroup libusb_desc - * Endpoint direction. Values for bit 7 of the - * \ref libusb_endpoint_descriptor::bEndpointAddress "endpoint address" scheme. - */ -enum libusb_endpoint_direction { - /** In: device-to-host */ - LIBUSB_ENDPOINT_IN = 0x80, - - /** Out: host-to-device */ - LIBUSB_ENDPOINT_OUT = 0x00 -}; - -#define LIBUSB_TRANSFER_TYPE_MASK 0x03 /* in bmAttributes */ - -/** \ingroup libusb_desc - * Endpoint transfer type. Values for bits 0:1 of the - * \ref libusb_endpoint_descriptor::bmAttributes "endpoint attributes" field. - */ -enum libusb_transfer_type { - /** Control endpoint */ - LIBUSB_TRANSFER_TYPE_CONTROL = 0, - - /** Isochronous endpoint */ - LIBUSB_TRANSFER_TYPE_ISOCHRONOUS = 1, - - /** Bulk endpoint */ - LIBUSB_TRANSFER_TYPE_BULK = 2, - - /** Interrupt endpoint */ - LIBUSB_TRANSFER_TYPE_INTERRUPT = 3, - - /** Stream endpoint */ - LIBUSB_TRANSFER_TYPE_BULK_STREAM = 4, -}; - -/** \ingroup libusb_misc - * Standard requests, as defined in table 9-5 of the USB 3.0 specifications */ -enum libusb_standard_request { - /** Request status of the specific recipient */ - LIBUSB_REQUEST_GET_STATUS = 0x00, - - /** Clear or disable a specific feature */ - LIBUSB_REQUEST_CLEAR_FEATURE = 0x01, - - /* 0x02 is reserved */ - - /** Set or enable a specific feature */ - LIBUSB_REQUEST_SET_FEATURE = 0x03, - - /* 0x04 is reserved */ - - /** Set device address for all future accesses */ - LIBUSB_REQUEST_SET_ADDRESS = 0x05, - - /** Get the specified descriptor */ - LIBUSB_REQUEST_GET_DESCRIPTOR = 0x06, - - /** Used to update existing descriptors or add new descriptors */ - LIBUSB_REQUEST_SET_DESCRIPTOR = 0x07, - - /** Get the current device configuration value */ - LIBUSB_REQUEST_GET_CONFIGURATION = 0x08, - - /** Set device configuration */ - LIBUSB_REQUEST_SET_CONFIGURATION = 0x09, - - /** Return the selected alternate setting for the specified interface */ - LIBUSB_REQUEST_GET_INTERFACE = 0x0A, - - /** Select an alternate interface for the specified interface */ - LIBUSB_REQUEST_SET_INTERFACE = 0x0B, - - /** Set then report an endpoint's synchronization frame */ - LIBUSB_REQUEST_SYNCH_FRAME = 0x0C, - - /** Sets both the U1 and U2 Exit Latency */ - LIBUSB_REQUEST_SET_SEL = 0x30, - - /** Delay from the time a host transmits a packet to the time it is - * received by the device. */ - LIBUSB_SET_ISOCH_DELAY = 0x31, -}; - -/** \ingroup libusb_misc - * Request type bits of the - * \ref libusb_control_setup::bmRequestType "bmRequestType" field in control - * transfers. */ -enum libusb_request_type { - /** Standard */ - LIBUSB_REQUEST_TYPE_STANDARD = (0x00 << 5), - - /** Class */ - LIBUSB_REQUEST_TYPE_CLASS = (0x01 << 5), - - /** Vendor */ - LIBUSB_REQUEST_TYPE_VENDOR = (0x02 << 5), - - /** Reserved */ - LIBUSB_REQUEST_TYPE_RESERVED = (0x03 << 5) -}; - -/** \ingroup libusb_misc - * Recipient bits of the - * \ref libusb_control_setup::bmRequestType "bmRequestType" field in control - * transfers. Values 4 through 31 are reserved. */ -enum libusb_request_recipient { - /** Device */ - LIBUSB_RECIPIENT_DEVICE = 0x00, - - /** Interface */ - LIBUSB_RECIPIENT_INTERFACE = 0x01, - - /** Endpoint */ - LIBUSB_RECIPIENT_ENDPOINT = 0x02, - - /** Other */ - LIBUSB_RECIPIENT_OTHER = 0x03, -}; - -#define LIBUSB_ISO_SYNC_TYPE_MASK 0x0C - -/** \ingroup libusb_desc - * Synchronization type for isochronous endpoints. Values for bits 2:3 of the - * \ref libusb_endpoint_descriptor::bmAttributes "bmAttributes" field in - * libusb_endpoint_descriptor. - */ -enum libusb_iso_sync_type { - /** No synchronization */ - LIBUSB_ISO_SYNC_TYPE_NONE = 0, - - /** Asynchronous */ - LIBUSB_ISO_SYNC_TYPE_ASYNC = 1, - - /** Adaptive */ - LIBUSB_ISO_SYNC_TYPE_ADAPTIVE = 2, - - /** Synchronous */ - LIBUSB_ISO_SYNC_TYPE_SYNC = 3 -}; - -#define LIBUSB_ISO_USAGE_TYPE_MASK 0x30 - -/** \ingroup libusb_desc - * Usage type for isochronous endpoints. Values for bits 4:5 of the - * \ref libusb_endpoint_descriptor::bmAttributes "bmAttributes" field in - * libusb_endpoint_descriptor. - */ -enum libusb_iso_usage_type { - /** Data endpoint */ - LIBUSB_ISO_USAGE_TYPE_DATA = 0, - - /** Feedback endpoint */ - LIBUSB_ISO_USAGE_TYPE_FEEDBACK = 1, - - /** Implicit feedback Data endpoint */ - LIBUSB_ISO_USAGE_TYPE_IMPLICIT = 2, -}; - -/** \ingroup libusb_desc - * A structure representing the standard USB device descriptor. This - * descriptor is documented in section 9.6.1 of the USB 3.0 specification. - * All multiple-byte fields are represented in host-endian format. - */ -struct libusb_device_descriptor { - /** Size of this descriptor (in bytes) */ - uint8_t bLength; - - /** Descriptor type. Will have value - * \ref libusb_descriptor_type::LIBUSB_DT_DEVICE LIBUSB_DT_DEVICE in this - * context. */ - uint8_t bDescriptorType; - - /** USB specification release number in binary-coded decimal. A value of - * 0x0200 indicates USB 2.0, 0x0110 indicates USB 1.1, etc. */ - uint16_t bcdUSB; - - /** USB-IF class code for the device. See \ref libusb_class_code. */ - uint8_t bDeviceClass; - - /** USB-IF subclass code for the device, qualified by the bDeviceClass - * value */ - uint8_t bDeviceSubClass; - - /** USB-IF protocol code for the device, qualified by the bDeviceClass and - * bDeviceSubClass values */ - uint8_t bDeviceProtocol; - - /** Maximum packet size for endpoint 0 */ - uint8_t bMaxPacketSize0; - - /** USB-IF vendor ID */ - uint16_t idVendor; - - /** USB-IF product ID */ - uint16_t idProduct; - - /** Device release number in binary-coded decimal */ - uint16_t bcdDevice; - - /** Index of string descriptor describing manufacturer */ - uint8_t iManufacturer; - - /** Index of string descriptor describing product */ - uint8_t iProduct; - - /** Index of string descriptor containing device serial number */ - uint8_t iSerialNumber; - - /** Number of possible configurations */ - uint8_t bNumConfigurations; -}; - -/** \ingroup libusb_desc - * A structure representing the standard USB endpoint descriptor. This - * descriptor is documented in section 9.6.6 of the USB 3.0 specification. - * All multiple-byte fields are represented in host-endian format. - */ -struct libusb_endpoint_descriptor { - /** Size of this descriptor (in bytes) */ - uint8_t bLength; - - /** Descriptor type. Will have value - * \ref libusb_descriptor_type::LIBUSB_DT_ENDPOINT LIBUSB_DT_ENDPOINT in - * this context. */ - uint8_t bDescriptorType; - - /** The address of the endpoint described by this descriptor. Bits 0:3 are - * the endpoint number. Bits 4:6 are reserved. Bit 7 indicates direction, - * see \ref libusb_endpoint_direction. - */ - uint8_t bEndpointAddress; - - /** Attributes which apply to the endpoint when it is configured using - * the bConfigurationValue. Bits 0:1 determine the transfer type and - * correspond to \ref libusb_transfer_type. Bits 2:3 are only used for - * isochronous endpoints and correspond to \ref libusb_iso_sync_type. - * Bits 4:5 are also only used for isochronous endpoints and correspond to - * \ref libusb_iso_usage_type. Bits 6:7 are reserved. - */ - uint8_t bmAttributes; - - /** Maximum packet size this endpoint is capable of sending/receiving. */ - uint16_t wMaxPacketSize; - - /** Interval for polling endpoint for data transfers. */ - uint8_t bInterval; - - /** For audio devices only: the rate at which synchronization feedback - * is provided. */ - uint8_t bRefresh; - - /** For audio devices only: the address if the synch endpoint */ - uint8_t bSynchAddress; - - /** Extra descriptors. If libusb encounters unknown endpoint descriptors, - * it will store them here, should you wish to parse them. */ - const unsigned char *extra; - - /** Length of the extra descriptors, in bytes. */ - int extra_length; -}; - -/** \ingroup libusb_desc - * A structure representing the standard USB interface descriptor. This - * descriptor is documented in section 9.6.5 of the USB 3.0 specification. - * All multiple-byte fields are represented in host-endian format. - */ -struct libusb_interface_descriptor { - /** Size of this descriptor (in bytes) */ - uint8_t bLength; - - /** Descriptor type. Will have value - * \ref libusb_descriptor_type::LIBUSB_DT_INTERFACE LIBUSB_DT_INTERFACE - * in this context. */ - uint8_t bDescriptorType; - - /** Number of this interface */ - uint8_t bInterfaceNumber; - - /** Value used to select this alternate setting for this interface */ - uint8_t bAlternateSetting; - - /** Number of endpoints used by this interface (excluding the control - * endpoint). */ - uint8_t bNumEndpoints; - - /** USB-IF class code for this interface. See \ref libusb_class_code. */ - uint8_t bInterfaceClass; - - /** USB-IF subclass code for this interface, qualified by the - * bInterfaceClass value */ - uint8_t bInterfaceSubClass; - - /** USB-IF protocol code for this interface, qualified by the - * bInterfaceClass and bInterfaceSubClass values */ - uint8_t bInterfaceProtocol; - - /** Index of string descriptor describing this interface */ - uint8_t iInterface; - - /** Array of endpoint descriptors. This length of this array is determined - * by the bNumEndpoints field. */ - const struct libusb_endpoint_descriptor *endpoint; - - /** Extra descriptors. If libusb encounters unknown interface descriptors, - * it will store them here, should you wish to parse them. */ - const unsigned char *extra; - - /** Length of the extra descriptors, in bytes. */ - int extra_length; -}; - -/** \ingroup libusb_desc - * A collection of alternate settings for a particular USB interface. - */ -struct libusb_interface { - /** Array of interface descriptors. The length of this array is determined - * by the num_altsetting field. */ - const struct libusb_interface_descriptor *altsetting; - - /** The number of alternate settings that belong to this interface */ - int num_altsetting; -}; - -/** \ingroup libusb_desc - * A structure representing the standard USB configuration descriptor. This - * descriptor is documented in section 9.6.3 of the USB 3.0 specification. - * All multiple-byte fields are represented in host-endian format. - */ -struct libusb_config_descriptor { - /** Size of this descriptor (in bytes) */ - uint8_t bLength; - - /** Descriptor type. Will have value - * \ref libusb_descriptor_type::LIBUSB_DT_CONFIG LIBUSB_DT_CONFIG - * in this context. */ - uint8_t bDescriptorType; - - /** Total length of data returned for this configuration */ - uint16_t wTotalLength; - - /** Number of interfaces supported by this configuration */ - uint8_t bNumInterfaces; - - /** Identifier value for this configuration */ - uint8_t bConfigurationValue; - - /** Index of string descriptor describing this configuration */ - uint8_t iConfiguration; - - /** Configuration characteristics */ - uint8_t bmAttributes; - - /** Maximum power consumption of the USB device from this bus in this - * configuration when the device is fully operation. Expressed in units - * of 2 mA when the device is operating in high-speed mode and in units - * of 8 mA when the device is operating in super-speed mode. */ - uint8_t MaxPower; - - /** Array of interfaces supported by this configuration. The length of - * this array is determined by the bNumInterfaces field. */ - const struct libusb_interface *interface; - - /** Extra descriptors. If libusb encounters unknown configuration - * descriptors, it will store them here, should you wish to parse them. */ - const unsigned char *extra; - - /** Length of the extra descriptors, in bytes. */ - int extra_length; -}; - -/** \ingroup libusb_desc - * A structure representing the superspeed endpoint companion - * descriptor. This descriptor is documented in section 9.6.7 of - * the USB 3.0 specification. All multiple-byte fields are represented in - * host-endian format. - */ -struct libusb_ss_endpoint_companion_descriptor { - - /** Size of this descriptor (in bytes) */ - uint8_t bLength; - - /** Descriptor type. Will have value - * \ref libusb_descriptor_type::LIBUSB_DT_SS_ENDPOINT_COMPANION in - * this context. */ - uint8_t bDescriptorType; - - - /** The maximum number of packets the endpoint can send or - * receive as part of a burst. */ - uint8_t bMaxBurst; - - /** In bulk EP: bits 4:0 represents the maximum number of - * streams the EP supports. In isochronous EP: bits 1:0 - * represents the Mult - a zero based value that determines - * the maximum number of packets within a service interval */ - uint8_t bmAttributes; - - /** The total number of bytes this EP will transfer every - * service interval. valid only for periodic EPs. */ - uint16_t wBytesPerInterval; -}; - -/** \ingroup libusb_desc - * A generic representation of a BOS Device Capability descriptor. It is - * advised to check bDevCapabilityType and call the matching - * libusb_get_*_descriptor function to get a structure fully matching the type. - */ -struct libusb_bos_dev_capability_descriptor { - /** Size of this descriptor (in bytes) */ - uint8_t bLength; - /** Descriptor type. Will have value - * \ref libusb_descriptor_type::LIBUSB_DT_DEVICE_CAPABILITY - * LIBUSB_DT_DEVICE_CAPABILITY in this context. */ - uint8_t bDescriptorType; - /** Device Capability type */ - uint8_t bDevCapabilityType; - /** Device Capability data (bLength - 3 bytes) */ - uint8_t dev_capability_data -#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) - [] /* valid C99 code */ -#else - [0] /* non-standard, but usually working code */ -#endif - ; -}; - -/** \ingroup libusb_desc - * A structure representing the Binary Device Object Store (BOS) descriptor. - * This descriptor is documented in section 9.6.2 of the USB 3.0 specification. - * All multiple-byte fields are represented in host-endian format. - */ -struct libusb_bos_descriptor { - /** Size of this descriptor (in bytes) */ - uint8_t bLength; - - /** Descriptor type. Will have value - * \ref libusb_descriptor_type::LIBUSB_DT_BOS LIBUSB_DT_BOS - * in this context. */ - uint8_t bDescriptorType; - - /** Length of this descriptor and all of its sub descriptors */ - uint16_t wTotalLength; - - /** The number of separate device capability descriptors in - * the BOS */ - uint8_t bNumDeviceCaps; - - /** bNumDeviceCap Device Capability Descriptors */ - struct libusb_bos_dev_capability_descriptor *dev_capability -#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) - [] /* valid C99 code */ -#else - [0] /* non-standard, but usually working code */ -#endif - ; -}; - -/** \ingroup libusb_desc - * A structure representing the USB 2.0 Extension descriptor - * This descriptor is documented in section 9.6.2.1 of the USB 3.0 specification. - * All multiple-byte fields are represented in host-endian format. - */ -struct libusb_usb_2_0_extension_descriptor { - /** Size of this descriptor (in bytes) */ - uint8_t bLength; - - /** Descriptor type. Will have value - * \ref libusb_descriptor_type::LIBUSB_DT_DEVICE_CAPABILITY - * LIBUSB_DT_DEVICE_CAPABILITY in this context. */ - uint8_t bDescriptorType; - - /** Capability type. Will have value - * \ref libusb_capability_type::LIBUSB_BT_USB_2_0_EXTENSION - * LIBUSB_BT_USB_2_0_EXTENSION in this context. */ - uint8_t bDevCapabilityType; - - /** Bitmap encoding of supported device level features. - * A value of one in a bit location indicates a feature is - * supported; a value of zero indicates it is not supported. - * See \ref libusb_usb_2_0_extension_attributes. */ - uint32_t bmAttributes; -}; - -/** \ingroup libusb_desc - * A structure representing the SuperSpeed USB Device Capability descriptor - * This descriptor is documented in section 9.6.2.2 of the USB 3.0 specification. - * All multiple-byte fields are represented in host-endian format. - */ -struct libusb_ss_usb_device_capability_descriptor { - /** Size of this descriptor (in bytes) */ - uint8_t bLength; - - /** Descriptor type. Will have value - * \ref libusb_descriptor_type::LIBUSB_DT_DEVICE_CAPABILITY - * LIBUSB_DT_DEVICE_CAPABILITY in this context. */ - uint8_t bDescriptorType; - - /** Capability type. Will have value - * \ref libusb_capability_type::LIBUSB_BT_SS_USB_DEVICE_CAPABILITY - * LIBUSB_BT_SS_USB_DEVICE_CAPABILITY in this context. */ - uint8_t bDevCapabilityType; - - /** Bitmap encoding of supported device level features. - * A value of one in a bit location indicates a feature is - * supported; a value of zero indicates it is not supported. - * See \ref libusb_ss_usb_device_capability_attributes. */ - uint8_t bmAttributes; - - /** Bitmap encoding of the speed supported by this device when - * operating in SuperSpeed mode. See \ref libusb_supported_speed. */ - uint16_t wSpeedSupported; - - /** The lowest speed at which all the functionality supported - * by the device is available to the user. For example if the - * device supports all its functionality when connected at - * full speed and above then it sets this value to 1. */ - uint8_t bFunctionalitySupport; - - /** U1 Device Exit Latency. */ - uint8_t bU1DevExitLat; - - /** U2 Device Exit Latency. */ - uint16_t bU2DevExitLat; -}; - -/** \ingroup libusb_desc - * A structure representing the Container ID descriptor. - * This descriptor is documented in section 9.6.2.3 of the USB 3.0 specification. - * All multiple-byte fields, except UUIDs, are represented in host-endian format. - */ -struct libusb_container_id_descriptor { - /** Size of this descriptor (in bytes) */ - uint8_t bLength; - - /** Descriptor type. Will have value - * \ref libusb_descriptor_type::LIBUSB_DT_DEVICE_CAPABILITY - * LIBUSB_DT_DEVICE_CAPABILITY in this context. */ - uint8_t bDescriptorType; - - /** Capability type. Will have value - * \ref libusb_capability_type::LIBUSB_BT_CONTAINER_ID - * LIBUSB_BT_CONTAINER_ID in this context. */ - uint8_t bDevCapabilityType; - - /** Reserved field */ - uint8_t bReserved; - - /** 128 bit UUID */ - uint8_t ContainerID[16]; -}; - -/** \ingroup libusb_asyncio - * Setup packet for control transfers. */ -struct libusb_control_setup { - /** Request type. Bits 0:4 determine recipient, see - * \ref libusb_request_recipient. Bits 5:6 determine type, see - * \ref libusb_request_type. Bit 7 determines data transfer direction, see - * \ref libusb_endpoint_direction. - */ - uint8_t bmRequestType; - - /** Request. If the type bits of bmRequestType are equal to - * \ref libusb_request_type::LIBUSB_REQUEST_TYPE_STANDARD - * "LIBUSB_REQUEST_TYPE_STANDARD" then this field refers to - * \ref libusb_standard_request. For other cases, use of this field is - * application-specific. */ - uint8_t bRequest; - - /** Value. Varies according to request */ - uint16_t wValue; - - /** Index. Varies according to request, typically used to pass an index - * or offset */ - uint16_t wIndex; - - /** Number of bytes to transfer */ - uint16_t wLength; -}; - -#define LIBUSB_CONTROL_SETUP_SIZE (sizeof(struct libusb_control_setup)) - -/* libusb */ - -struct libusb_context; -struct libusb_device; -struct libusb_device_handle; - -/** \ingroup libusb_lib - * Structure providing the version of the libusb runtime - */ -struct libusb_version { - /** Library major version. */ - const uint16_t major; - - /** Library minor version. */ - const uint16_t minor; - - /** Library micro version. */ - const uint16_t micro; - - /** Library nano version. */ - const uint16_t nano; - - /** Library release candidate suffix string, e.g. "-rc4". */ - const char *rc; - - /** For ABI compatibility only. */ - const char* describe; -}; - -/** \ingroup libusb_lib - * Structure representing a libusb session. The concept of individual libusb - * sessions allows for your program to use two libraries (or dynamically - * load two modules) which both independently use libusb. This will prevent - * interference between the individual libusb users - for example - * libusb_set_debug() will not affect the other user of the library, and - * libusb_exit() will not destroy resources that the other user is still - * using. - * - * Sessions are created by libusb_init() and destroyed through libusb_exit(). - * If your application is guaranteed to only ever include a single libusb - * user (i.e. you), you do not have to worry about contexts: pass NULL in - * every function call where a context is required. The default context - * will be used. - * - * For more information, see \ref libusb_contexts. - */ -typedef struct libusb_context libusb_context; - -/** \ingroup libusb_dev - * Structure representing a USB device detected on the system. This is an - * opaque type for which you are only ever provided with a pointer, usually - * originating from libusb_get_device_list(). - * - * Certain operations can be performed on a device, but in order to do any - * I/O you will have to first obtain a device handle using libusb_open(). - * - * Devices are reference counted with libusb_ref_device() and - * libusb_unref_device(), and are freed when the reference count reaches 0. - * New devices presented by libusb_get_device_list() have a reference count of - * 1, and libusb_free_device_list() can optionally decrease the reference count - * on all devices in the list. libusb_open() adds another reference which is - * later destroyed by libusb_close(). - */ -typedef struct libusb_device libusb_device; - - -/** \ingroup libusb_dev - * Structure representing a handle on a USB device. This is an opaque type for - * which you are only ever provided with a pointer, usually originating from - * libusb_open(). - * - * A device handle is used to perform I/O and other operations. When finished - * with a device handle, you should call libusb_close(). - */ -typedef struct libusb_device_handle libusb_device_handle; - -/** \ingroup libusb_dev - * Speed codes. Indicates the speed at which the device is operating. - */ -enum libusb_speed { - /** The OS doesn't report or know the device speed. */ - LIBUSB_SPEED_UNKNOWN = 0, - - /** The device is operating at low speed (1.5MBit/s). */ - LIBUSB_SPEED_LOW = 1, - - /** The device is operating at full speed (12MBit/s). */ - LIBUSB_SPEED_FULL = 2, - - /** The device is operating at high speed (480MBit/s). */ - LIBUSB_SPEED_HIGH = 3, - - /** The device is operating at super speed (5000MBit/s). */ - LIBUSB_SPEED_SUPER = 4, -}; - -/** \ingroup libusb_dev - * Supported speeds (wSpeedSupported) bitfield. Indicates what - * speeds the device supports. - */ -enum libusb_supported_speed { - /** Low speed operation supported (1.5MBit/s). */ - LIBUSB_LOW_SPEED_OPERATION = 1, - - /** Full speed operation supported (12MBit/s). */ - LIBUSB_FULL_SPEED_OPERATION = 2, - - /** High speed operation supported (480MBit/s). */ - LIBUSB_HIGH_SPEED_OPERATION = 4, - - /** Superspeed operation supported (5000MBit/s). */ - LIBUSB_SUPER_SPEED_OPERATION = 8, -}; - -/** \ingroup libusb_dev - * Masks for the bits of the - * \ref libusb_usb_2_0_extension_descriptor::bmAttributes "bmAttributes" field - * of the USB 2.0 Extension descriptor. - */ -enum libusb_usb_2_0_extension_attributes { - /** Supports Link Power Management (LPM) */ - LIBUSB_BM_LPM_SUPPORT = 2, -}; - -/** \ingroup libusb_dev - * Masks for the bits of the - * \ref libusb_ss_usb_device_capability_descriptor::bmAttributes "bmAttributes" field - * field of the SuperSpeed USB Device Capability descriptor. - */ -enum libusb_ss_usb_device_capability_attributes { - /** Supports Latency Tolerance Messages (LTM) */ - LIBUSB_BM_LTM_SUPPORT = 2, -}; - -/** \ingroup libusb_dev - * USB capability types - */ -enum libusb_bos_type { - /** Wireless USB device capability */ - LIBUSB_BT_WIRELESS_USB_DEVICE_CAPABILITY = 1, - - /** USB 2.0 extensions */ - LIBUSB_BT_USB_2_0_EXTENSION = 2, - - /** SuperSpeed USB device capability */ - LIBUSB_BT_SS_USB_DEVICE_CAPABILITY = 3, - - /** Container ID type */ - LIBUSB_BT_CONTAINER_ID = 4, -}; - -/** \ingroup libusb_misc - * Error codes. Most libusb functions return 0 on success or one of these - * codes on failure. - * You can call libusb_error_name() to retrieve a string representation of an - * error code or libusb_strerror() to get an end-user suitable description of - * an error code. - */ -enum libusb_error { - /** Success (no error) */ - LIBUSB_SUCCESS = 0, - - /** Input/output error */ - LIBUSB_ERROR_IO = -1, - - /** Invalid parameter */ - LIBUSB_ERROR_INVALID_PARAM = -2, - - /** Access denied (insufficient permissions) */ - LIBUSB_ERROR_ACCESS = -3, - - /** No such device (it may have been disconnected) */ - LIBUSB_ERROR_NO_DEVICE = -4, - - /** Entity not found */ - LIBUSB_ERROR_NOT_FOUND = -5, - - /** Resource busy */ - LIBUSB_ERROR_BUSY = -6, - - /** Operation timed out */ - LIBUSB_ERROR_TIMEOUT = -7, - - /** Overflow */ - LIBUSB_ERROR_OVERFLOW = -8, - - /** Pipe error */ - LIBUSB_ERROR_PIPE = -9, - - /** System call interrupted (perhaps due to signal) */ - LIBUSB_ERROR_INTERRUPTED = -10, - - /** Insufficient memory */ - LIBUSB_ERROR_NO_MEM = -11, - - /** Operation not supported or unimplemented on this platform */ - LIBUSB_ERROR_NOT_SUPPORTED = -12, - - /* NB: Remember to update LIBUSB_ERROR_COUNT below as well as the - message strings in strerror.c when adding new error codes here. */ - - /** Other error */ - LIBUSB_ERROR_OTHER = -99, -}; - -/* Total number of error codes in enum libusb_error */ -#define LIBUSB_ERROR_COUNT 14 - -/** \ingroup libusb_asyncio - * Transfer status codes */ -enum libusb_transfer_status { - /** Transfer completed without error. Note that this does not indicate - * that the entire amount of requested data was transferred. */ - LIBUSB_TRANSFER_COMPLETED, - - /** Transfer failed */ - LIBUSB_TRANSFER_ERROR, - - /** Transfer timed out */ - LIBUSB_TRANSFER_TIMED_OUT, - - /** Transfer was cancelled */ - LIBUSB_TRANSFER_CANCELLED, - - /** For bulk/interrupt endpoints: halt condition detected (endpoint - * stalled). For control endpoints: control request not supported. */ - LIBUSB_TRANSFER_STALL, - - /** Device was disconnected */ - LIBUSB_TRANSFER_NO_DEVICE, - - /** Device sent more data than requested */ - LIBUSB_TRANSFER_OVERFLOW, - - /* NB! Remember to update libusb_error_name() - when adding new status codes here. */ -}; - -/** \ingroup libusb_asyncio - * libusb_transfer.flags values */ -enum libusb_transfer_flags { - /** Report short frames as errors */ - LIBUSB_TRANSFER_SHORT_NOT_OK = 1<<0, - - /** Automatically free() transfer buffer during libusb_free_transfer(). - * Note that buffers allocated with libusb_dev_mem_alloc() should not - * be attempted freed in this way, since free() is not an appropriate - * way to release such memory. */ - LIBUSB_TRANSFER_FREE_BUFFER = 1<<1, - - /** Automatically call libusb_free_transfer() after callback returns. - * If this flag is set, it is illegal to call libusb_free_transfer() - * from your transfer callback, as this will result in a double-free - * when this flag is acted upon. */ - LIBUSB_TRANSFER_FREE_TRANSFER = 1<<2, - - /** Terminate transfers that are a multiple of the endpoint's - * wMaxPacketSize with an extra zero length packet. This is useful - * when a device protocol mandates that each logical request is - * terminated by an incomplete packet (i.e. the logical requests are - * not separated by other means). - * - * This flag only affects host-to-device transfers to bulk and interrupt - * endpoints. In other situations, it is ignored. - * - * This flag only affects transfers with a length that is a multiple of - * the endpoint's wMaxPacketSize. On transfers of other lengths, this - * flag has no effect. Therefore, if you are working with a device that - * needs a ZLP whenever the end of the logical request falls on a packet - * boundary, then it is sensible to set this flag on every - * transfer (you do not have to worry about only setting it on transfers - * that end on the boundary). - * - * This flag is currently only supported on Linux. - * On other systems, libusb_submit_transfer() will return - * LIBUSB_ERROR_NOT_SUPPORTED for every transfer where this flag is set. - * - * Available since libusb-1.0.9. - */ - LIBUSB_TRANSFER_ADD_ZERO_PACKET = 1 << 3, -}; - -/** \ingroup libusb_asyncio - * Isochronous packet descriptor. */ -struct libusb_iso_packet_descriptor { - /** Length of data to request in this packet */ - unsigned int length; - - /** Amount of data that was actually transferred */ - unsigned int actual_length; - - /** Status code for this packet */ - enum libusb_transfer_status status; -}; - -struct libusb_transfer; - -/** \ingroup libusb_asyncio - * Asynchronous transfer callback function type. When submitting asynchronous - * transfers, you pass a pointer to a callback function of this type via the - * \ref libusb_transfer::callback "callback" member of the libusb_transfer - * structure. libusb will call this function later, when the transfer has - * completed or failed. See \ref libusb_asyncio for more information. - * \param transfer The libusb_transfer struct the callback function is being - * notified about. - */ -typedef void (LIBUSB_CALL *libusb_transfer_cb_fn)(struct libusb_transfer *transfer); - -/** \ingroup libusb_asyncio - * The generic USB transfer structure. The user populates this structure and - * then submits it in order to request a transfer. After the transfer has - * completed, the library populates the transfer with the results and passes - * it back to the user. - */ -struct libusb_transfer { - /** Handle of the device that this transfer will be submitted to */ - libusb_device_handle *dev_handle; - - /** A bitwise OR combination of \ref libusb_transfer_flags. */ - uint8_t flags; - - /** Address of the endpoint where this transfer will be sent. */ - unsigned char endpoint; - - /** Type of the endpoint from \ref libusb_transfer_type */ - unsigned char type; - - /** Timeout for this transfer in milliseconds. A value of 0 indicates no - * timeout. */ - unsigned int timeout; - - /** The status of the transfer. Read-only, and only for use within - * transfer callback function. - * - * If this is an isochronous transfer, this field may read COMPLETED even - * if there were errors in the frames. Use the - * \ref libusb_iso_packet_descriptor::status "status" field in each packet - * to determine if errors occurred. */ - enum libusb_transfer_status status; - - /** Length of the data buffer */ - int length; - - /** Actual length of data that was transferred. Read-only, and only for - * use within transfer callback function. Not valid for isochronous - * endpoint transfers. */ - int actual_length; - - /** Callback function. This will be invoked when the transfer completes, - * fails, or is cancelled. */ - libusb_transfer_cb_fn callback; - - /** User context data to pass to the callback function. */ - void *user_data; - - /** Data buffer */ - unsigned char *buffer; - - /** Number of isochronous packets. Only used for I/O with isochronous - * endpoints. */ - int num_iso_packets; - - /** Isochronous packet descriptors, for isochronous transfers only. */ - struct libusb_iso_packet_descriptor iso_packet_desc -#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) - [] /* valid C99 code */ -#else - [0] /* non-standard, but usually working code */ -#endif - ; -}; - -/** \ingroup libusb_misc - * Capabilities supported by an instance of libusb on the current running - * platform. Test if the loaded library supports a given capability by calling - * \ref libusb_has_capability(). - */ -enum libusb_capability { - /** The libusb_has_capability() API is available. */ - LIBUSB_CAP_HAS_CAPABILITY = 0x0000, - /** Hotplug support is available on this platform. */ - LIBUSB_CAP_HAS_HOTPLUG = 0x0001, - /** The library can access HID devices without requiring user intervention. - * Note that before being able to actually access an HID device, you may - * still have to call additional libusb functions such as - * \ref libusb_detach_kernel_driver(). */ - LIBUSB_CAP_HAS_HID_ACCESS = 0x0100, - /** The library supports detaching of the default USB driver, using - * \ref libusb_detach_kernel_driver(), if one is set by the OS kernel */ - LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER = 0x0101 -}; - -/** \ingroup libusb_lib - * Log message levels. - * - LIBUSB_LOG_LEVEL_NONE (0) : no messages ever printed by the library (default) - * - LIBUSB_LOG_LEVEL_ERROR (1) : error messages are printed to stderr - * - LIBUSB_LOG_LEVEL_WARNING (2) : warning and error messages are printed to stderr - * - LIBUSB_LOG_LEVEL_INFO (3) : informational messages are printed to stdout, warning - * and error messages are printed to stderr - * - LIBUSB_LOG_LEVEL_DEBUG (4) : debug and informational messages are printed to stdout, - * warnings and errors to stderr - */ -enum libusb_log_level { - LIBUSB_LOG_LEVEL_NONE = 0, - LIBUSB_LOG_LEVEL_ERROR, - LIBUSB_LOG_LEVEL_WARNING, - LIBUSB_LOG_LEVEL_INFO, - LIBUSB_LOG_LEVEL_DEBUG, -}; - -int LIBUSB_CALL libusb_init(libusb_context **ctx); -void LIBUSB_CALL libusb_exit(libusb_context *ctx); -void LIBUSB_CALL libusb_set_debug(libusb_context *ctx, int level); -const struct libusb_version * LIBUSB_CALL libusb_get_version(void); -int LIBUSB_CALL libusb_has_capability(uint32_t capability); -const char * LIBUSB_CALL libusb_error_name(int errcode); -int LIBUSB_CALL libusb_setlocale(const char *locale); -const char * LIBUSB_CALL libusb_strerror(enum libusb_error errcode); - -ssize_t LIBUSB_CALL libusb_get_device_list(libusb_context *ctx, - libusb_device ***list); -void LIBUSB_CALL libusb_free_device_list(libusb_device **list, - int unref_devices); -libusb_device * LIBUSB_CALL libusb_ref_device(libusb_device *dev); -void LIBUSB_CALL libusb_unref_device(libusb_device *dev); - -int LIBUSB_CALL libusb_get_configuration(libusb_device_handle *dev, - int *config); -int LIBUSB_CALL libusb_get_device_descriptor(libusb_device *dev, - struct libusb_device_descriptor *desc); -int LIBUSB_CALL libusb_get_active_config_descriptor(libusb_device *dev, - struct libusb_config_descriptor **config); -int LIBUSB_CALL libusb_get_config_descriptor(libusb_device *dev, - uint8_t config_index, struct libusb_config_descriptor **config); -int LIBUSB_CALL libusb_get_config_descriptor_by_value(libusb_device *dev, - uint8_t bConfigurationValue, struct libusb_config_descriptor **config); -void LIBUSB_CALL libusb_free_config_descriptor( - struct libusb_config_descriptor *config); -int LIBUSB_CALL libusb_get_ss_endpoint_companion_descriptor( - struct libusb_context *ctx, - const struct libusb_endpoint_descriptor *endpoint, - struct libusb_ss_endpoint_companion_descriptor **ep_comp); -void LIBUSB_CALL libusb_free_ss_endpoint_companion_descriptor( - struct libusb_ss_endpoint_companion_descriptor *ep_comp); -int LIBUSB_CALL libusb_get_bos_descriptor(libusb_device_handle *dev_handle, - struct libusb_bos_descriptor **bos); -void LIBUSB_CALL libusb_free_bos_descriptor(struct libusb_bos_descriptor *bos); -int LIBUSB_CALL libusb_get_usb_2_0_extension_descriptor( - struct libusb_context *ctx, - struct libusb_bos_dev_capability_descriptor *dev_cap, - struct libusb_usb_2_0_extension_descriptor **usb_2_0_extension); -void LIBUSB_CALL libusb_free_usb_2_0_extension_descriptor( - struct libusb_usb_2_0_extension_descriptor *usb_2_0_extension); -int LIBUSB_CALL libusb_get_ss_usb_device_capability_descriptor( - struct libusb_context *ctx, - struct libusb_bos_dev_capability_descriptor *dev_cap, - struct libusb_ss_usb_device_capability_descriptor **ss_usb_device_cap); -void LIBUSB_CALL libusb_free_ss_usb_device_capability_descriptor( - struct libusb_ss_usb_device_capability_descriptor *ss_usb_device_cap); -int LIBUSB_CALL libusb_get_container_id_descriptor(struct libusb_context *ctx, - struct libusb_bos_dev_capability_descriptor *dev_cap, - struct libusb_container_id_descriptor **container_id); -void LIBUSB_CALL libusb_free_container_id_descriptor( - struct libusb_container_id_descriptor *container_id); -uint8_t LIBUSB_CALL libusb_get_bus_number(libusb_device *dev); -uint8_t LIBUSB_CALL libusb_get_port_number(libusb_device *dev); -int LIBUSB_CALL libusb_get_port_numbers(libusb_device *dev, uint8_t* port_numbers, int port_numbers_len); -LIBUSB_DEPRECATED_FOR(libusb_get_port_numbers) -int LIBUSB_CALL libusb_get_port_path(libusb_context *ctx, libusb_device *dev, uint8_t* path, uint8_t path_length); -libusb_device * LIBUSB_CALL libusb_get_parent(libusb_device *dev); -uint8_t LIBUSB_CALL libusb_get_device_address(libusb_device *dev); -int LIBUSB_CALL libusb_get_device_speed(libusb_device *dev); -int LIBUSB_CALL libusb_get_max_packet_size(libusb_device *dev, - unsigned char endpoint); -int LIBUSB_CALL libusb_get_max_iso_packet_size(libusb_device *dev, - unsigned char endpoint); - -int LIBUSB_CALL libusb_open(libusb_device *dev, libusb_device_handle **dev_handle); -void LIBUSB_CALL libusb_close(libusb_device_handle *dev_handle); -libusb_device * LIBUSB_CALL libusb_get_device(libusb_device_handle *dev_handle); - -int LIBUSB_CALL libusb_set_configuration(libusb_device_handle *dev_handle, - int configuration); -int LIBUSB_CALL libusb_claim_interface(libusb_device_handle *dev_handle, - int interface_number); -int LIBUSB_CALL libusb_release_interface(libusb_device_handle *dev_handle, - int interface_number); - -libusb_device_handle * LIBUSB_CALL libusb_open_device_with_vid_pid( - libusb_context *ctx, uint16_t vendor_id, uint16_t product_id); - -int LIBUSB_CALL libusb_set_interface_alt_setting(libusb_device_handle *dev_handle, - int interface_number, int alternate_setting); -int LIBUSB_CALL libusb_clear_halt(libusb_device_handle *dev_handle, - unsigned char endpoint); -int LIBUSB_CALL libusb_reset_device(libusb_device_handle *dev_handle); - -int LIBUSB_CALL libusb_alloc_streams(libusb_device_handle *dev_handle, - uint32_t num_streams, unsigned char *endpoints, int num_endpoints); -int LIBUSB_CALL libusb_free_streams(libusb_device_handle *dev_handle, - unsigned char *endpoints, int num_endpoints); - -unsigned char * LIBUSB_CALL libusb_dev_mem_alloc(libusb_device_handle *dev_handle, - size_t length); -int LIBUSB_CALL libusb_dev_mem_free(libusb_device_handle *dev_handle, - unsigned char *buffer, size_t length); - -int LIBUSB_CALL libusb_kernel_driver_active(libusb_device_handle *dev_handle, - int interface_number); -int LIBUSB_CALL libusb_detach_kernel_driver(libusb_device_handle *dev_handle, - int interface_number); -int LIBUSB_CALL libusb_attach_kernel_driver(libusb_device_handle *dev_handle, - int interface_number); -int LIBUSB_CALL libusb_set_auto_detach_kernel_driver( - libusb_device_handle *dev_handle, int enable); - -/* async I/O */ - -/** \ingroup libusb_asyncio - * Get the data section of a control transfer. This convenience function is here - * to remind you that the data does not start until 8 bytes into the actual - * buffer, as the setup packet comes first. - * - * Calling this function only makes sense from a transfer callback function, - * or situations where you have already allocated a suitably sized buffer at - * transfer->buffer. - * - * \param transfer a transfer - * \returns pointer to the first byte of the data section - */ -static inline unsigned char *libusb_control_transfer_get_data( - struct libusb_transfer *transfer) -{ - return transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE; -} - -/** \ingroup libusb_asyncio - * Get the control setup packet of a control transfer. This convenience - * function is here to remind you that the control setup occupies the first - * 8 bytes of the transfer data buffer. - * - * Calling this function only makes sense from a transfer callback function, - * or situations where you have already allocated a suitably sized buffer at - * transfer->buffer. - * - * \param transfer a transfer - * \returns a casted pointer to the start of the transfer data buffer - */ -static inline struct libusb_control_setup *libusb_control_transfer_get_setup( - struct libusb_transfer *transfer) -{ - return (struct libusb_control_setup *)(void *) transfer->buffer; -} - -/** \ingroup libusb_asyncio - * Helper function to populate the setup packet (first 8 bytes of the data - * buffer) for a control transfer. The wIndex, wValue and wLength values should - * be given in host-endian byte order. - * - * \param buffer buffer to output the setup packet into - * This pointer must be aligned to at least 2 bytes boundary. - * \param bmRequestType see the - * \ref libusb_control_setup::bmRequestType "bmRequestType" field of - * \ref libusb_control_setup - * \param bRequest see the - * \ref libusb_control_setup::bRequest "bRequest" field of - * \ref libusb_control_setup - * \param wValue see the - * \ref libusb_control_setup::wValue "wValue" field of - * \ref libusb_control_setup - * \param wIndex see the - * \ref libusb_control_setup::wIndex "wIndex" field of - * \ref libusb_control_setup - * \param wLength see the - * \ref libusb_control_setup::wLength "wLength" field of - * \ref libusb_control_setup - */ -static inline void libusb_fill_control_setup(unsigned char *buffer, - uint8_t bmRequestType, uint8_t bRequest, uint16_t wValue, uint16_t wIndex, - uint16_t wLength) -{ - struct libusb_control_setup *setup = (struct libusb_control_setup *)(void *) buffer; - setup->bmRequestType = bmRequestType; - setup->bRequest = bRequest; - setup->wValue = libusb_cpu_to_le16(wValue); - setup->wIndex = libusb_cpu_to_le16(wIndex); - setup->wLength = libusb_cpu_to_le16(wLength); -} - -struct libusb_transfer * LIBUSB_CALL libusb_alloc_transfer(int iso_packets); -int LIBUSB_CALL libusb_submit_transfer(struct libusb_transfer *transfer); -int LIBUSB_CALL libusb_cancel_transfer(struct libusb_transfer *transfer); -void LIBUSB_CALL libusb_free_transfer(struct libusb_transfer *transfer); -void LIBUSB_CALL libusb_transfer_set_stream_id( - struct libusb_transfer *transfer, uint32_t stream_id); -uint32_t LIBUSB_CALL libusb_transfer_get_stream_id( - struct libusb_transfer *transfer); - -/** \ingroup libusb_asyncio - * Helper function to populate the required \ref libusb_transfer fields - * for a control transfer. - * - * If you pass a transfer buffer to this function, the first 8 bytes will - * be interpreted as a control setup packet, and the wLength field will be - * used to automatically populate the \ref libusb_transfer::length "length" - * field of the transfer. Therefore the recommended approach is: - * -# Allocate a suitably sized data buffer (including space for control setup) - * -# Call libusb_fill_control_setup() - * -# If this is a host-to-device transfer with a data stage, put the data - * in place after the setup packet - * -# Call this function - * -# Call libusb_submit_transfer() - * - * It is also legal to pass a NULL buffer to this function, in which case this - * function will not attempt to populate the length field. Remember that you - * must then populate the buffer and length fields later. - * - * \param transfer the transfer to populate - * \param dev_handle handle of the device that will handle the transfer - * \param buffer data buffer. If provided, this function will interpret the - * first 8 bytes as a setup packet and infer the transfer length from that. - * This pointer must be aligned to at least 2 bytes boundary. - * \param callback callback function to be invoked on transfer completion - * \param user_data user data to pass to callback function - * \param timeout timeout for the transfer in milliseconds - */ -static inline void libusb_fill_control_transfer( - struct libusb_transfer *transfer, libusb_device_handle *dev_handle, - unsigned char *buffer, libusb_transfer_cb_fn callback, void *user_data, - unsigned int timeout) -{ - struct libusb_control_setup *setup = (struct libusb_control_setup *)(void *) buffer; - transfer->dev_handle = dev_handle; - transfer->endpoint = 0; - transfer->type = LIBUSB_TRANSFER_TYPE_CONTROL; - transfer->timeout = timeout; - transfer->buffer = buffer; - if (setup) - transfer->length = (int) (LIBUSB_CONTROL_SETUP_SIZE - + libusb_le16_to_cpu(setup->wLength)); - transfer->user_data = user_data; - transfer->callback = callback; -} - -/** \ingroup libusb_asyncio - * Helper function to populate the required \ref libusb_transfer fields - * for a bulk transfer. - * - * \param transfer the transfer to populate - * \param dev_handle handle of the device that will handle the transfer - * \param endpoint address of the endpoint where this transfer will be sent - * \param buffer data buffer - * \param length length of data buffer - * \param callback callback function to be invoked on transfer completion - * \param user_data user data to pass to callback function - * \param timeout timeout for the transfer in milliseconds - */ -static inline void libusb_fill_bulk_transfer(struct libusb_transfer *transfer, - libusb_device_handle *dev_handle, unsigned char endpoint, - unsigned char *buffer, int length, libusb_transfer_cb_fn callback, - void *user_data, unsigned int timeout) -{ - transfer->dev_handle = dev_handle; - transfer->endpoint = endpoint; - transfer->type = LIBUSB_TRANSFER_TYPE_BULK; - transfer->timeout = timeout; - transfer->buffer = buffer; - transfer->length = length; - transfer->user_data = user_data; - transfer->callback = callback; -} - -/** \ingroup libusb_asyncio - * Helper function to populate the required \ref libusb_transfer fields - * for a bulk transfer using bulk streams. - * - * Since version 1.0.19, \ref LIBUSB_API_VERSION >= 0x01000103 - * - * \param transfer the transfer to populate - * \param dev_handle handle of the device that will handle the transfer - * \param endpoint address of the endpoint where this transfer will be sent - * \param stream_id bulk stream id for this transfer - * \param buffer data buffer - * \param length length of data buffer - * \param callback callback function to be invoked on transfer completion - * \param user_data user data to pass to callback function - * \param timeout timeout for the transfer in milliseconds - */ -static inline void libusb_fill_bulk_stream_transfer( - struct libusb_transfer *transfer, libusb_device_handle *dev_handle, - unsigned char endpoint, uint32_t stream_id, - unsigned char *buffer, int length, libusb_transfer_cb_fn callback, - void *user_data, unsigned int timeout) -{ - libusb_fill_bulk_transfer(transfer, dev_handle, endpoint, buffer, - length, callback, user_data, timeout); - transfer->type = LIBUSB_TRANSFER_TYPE_BULK_STREAM; - libusb_transfer_set_stream_id(transfer, stream_id); -} - -/** \ingroup libusb_asyncio - * Helper function to populate the required \ref libusb_transfer fields - * for an interrupt transfer. - * - * \param transfer the transfer to populate - * \param dev_handle handle of the device that will handle the transfer - * \param endpoint address of the endpoint where this transfer will be sent - * \param buffer data buffer - * \param length length of data buffer - * \param callback callback function to be invoked on transfer completion - * \param user_data user data to pass to callback function - * \param timeout timeout for the transfer in milliseconds - */ -static inline void libusb_fill_interrupt_transfer( - struct libusb_transfer *transfer, libusb_device_handle *dev_handle, - unsigned char endpoint, unsigned char *buffer, int length, - libusb_transfer_cb_fn callback, void *user_data, unsigned int timeout) -{ - transfer->dev_handle = dev_handle; - transfer->endpoint = endpoint; - transfer->type = LIBUSB_TRANSFER_TYPE_INTERRUPT; - transfer->timeout = timeout; - transfer->buffer = buffer; - transfer->length = length; - transfer->user_data = user_data; - transfer->callback = callback; -} - -/** \ingroup libusb_asyncio - * Helper function to populate the required \ref libusb_transfer fields - * for an isochronous transfer. - * - * \param transfer the transfer to populate - * \param dev_handle handle of the device that will handle the transfer - * \param endpoint address of the endpoint where this transfer will be sent - * \param buffer data buffer - * \param length length of data buffer - * \param num_iso_packets the number of isochronous packets - * \param callback callback function to be invoked on transfer completion - * \param user_data user data to pass to callback function - * \param timeout timeout for the transfer in milliseconds - */ -static inline void libusb_fill_iso_transfer(struct libusb_transfer *transfer, - libusb_device_handle *dev_handle, unsigned char endpoint, - unsigned char *buffer, int length, int num_iso_packets, - libusb_transfer_cb_fn callback, void *user_data, unsigned int timeout) -{ - transfer->dev_handle = dev_handle; - transfer->endpoint = endpoint; - transfer->type = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS; - transfer->timeout = timeout; - transfer->buffer = buffer; - transfer->length = length; - transfer->num_iso_packets = num_iso_packets; - transfer->user_data = user_data; - transfer->callback = callback; -} - -/** \ingroup libusb_asyncio - * Convenience function to set the length of all packets in an isochronous - * transfer, based on the num_iso_packets field in the transfer structure. - * - * \param transfer a transfer - * \param length the length to set in each isochronous packet descriptor - * \see libusb_get_max_packet_size() - */ -static inline void libusb_set_iso_packet_lengths( - struct libusb_transfer *transfer, unsigned int length) -{ - int i; - for (i = 0; i < transfer->num_iso_packets; i++) - transfer->iso_packet_desc[i].length = length; -} - -/** \ingroup libusb_asyncio - * Convenience function to locate the position of an isochronous packet - * within the buffer of an isochronous transfer. - * - * This is a thorough function which loops through all preceding packets, - * accumulating their lengths to find the position of the specified packet. - * Typically you will assign equal lengths to each packet in the transfer, - * and hence the above method is sub-optimal. You may wish to use - * libusb_get_iso_packet_buffer_simple() instead. - * - * \param transfer a transfer - * \param packet the packet to return the address of - * \returns the base address of the packet buffer inside the transfer buffer, - * or NULL if the packet does not exist. - * \see libusb_get_iso_packet_buffer_simple() - */ -static inline unsigned char *libusb_get_iso_packet_buffer( - struct libusb_transfer *transfer, unsigned int packet) -{ - int i; - size_t offset = 0; - int _packet; - - /* oops..slight bug in the API. packet is an unsigned int, but we use - * signed integers almost everywhere else. range-check and convert to - * signed to avoid compiler warnings. FIXME for libusb-2. */ - if (packet > INT_MAX) - return NULL; - _packet = (int) packet; - - if (_packet >= transfer->num_iso_packets) - return NULL; - - for (i = 0; i < _packet; i++) - offset += transfer->iso_packet_desc[i].length; - - return transfer->buffer + offset; -} - -/** \ingroup libusb_asyncio - * Convenience function to locate the position of an isochronous packet - * within the buffer of an isochronous transfer, for transfers where each - * packet is of identical size. - * - * This function relies on the assumption that every packet within the transfer - * is of identical size to the first packet. Calculating the location of - * the packet buffer is then just a simple calculation: - * buffer + (packet_size * packet) - * - * Do not use this function on transfers other than those that have identical - * packet lengths for each packet. - * - * \param transfer a transfer - * \param packet the packet to return the address of - * \returns the base address of the packet buffer inside the transfer buffer, - * or NULL if the packet does not exist. - * \see libusb_get_iso_packet_buffer() - */ -static inline unsigned char *libusb_get_iso_packet_buffer_simple( - struct libusb_transfer *transfer, unsigned int packet) -{ - int _packet; - - /* oops..slight bug in the API. packet is an unsigned int, but we use - * signed integers almost everywhere else. range-check and convert to - * signed to avoid compiler warnings. FIXME for libusb-2. */ - if (packet > INT_MAX) - return NULL; - _packet = (int) packet; - - if (_packet >= transfer->num_iso_packets) - return NULL; - - return transfer->buffer + ((int) transfer->iso_packet_desc[0].length * _packet); -} - -/* sync I/O */ - -int LIBUSB_CALL libusb_control_transfer(libusb_device_handle *dev_handle, - uint8_t request_type, uint8_t bRequest, uint16_t wValue, uint16_t wIndex, - unsigned char *data, uint16_t wLength, unsigned int timeout); - -int LIBUSB_CALL libusb_bulk_transfer(libusb_device_handle *dev_handle, - unsigned char endpoint, unsigned char *data, int length, - int *actual_length, unsigned int timeout); - -int LIBUSB_CALL libusb_interrupt_transfer(libusb_device_handle *dev_handle, - unsigned char endpoint, unsigned char *data, int length, - int *actual_length, unsigned int timeout); - -/** \ingroup libusb_desc - * Retrieve a descriptor from the default control pipe. - * This is a convenience function which formulates the appropriate control - * message to retrieve the descriptor. - * - * \param dev_handle a device handle - * \param desc_type the descriptor type, see \ref libusb_descriptor_type - * \param desc_index the index of the descriptor to retrieve - * \param data output buffer for descriptor - * \param length size of data buffer - * \returns number of bytes returned in data, or LIBUSB_ERROR code on failure - */ -static inline int libusb_get_descriptor(libusb_device_handle *dev_handle, - uint8_t desc_type, uint8_t desc_index, unsigned char *data, int length) -{ - return libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_IN, - LIBUSB_REQUEST_GET_DESCRIPTOR, (uint16_t) ((desc_type << 8) | desc_index), - 0, data, (uint16_t) length, 1000); -} - -/** \ingroup libusb_desc - * Retrieve a descriptor from a device. - * This is a convenience function which formulates the appropriate control - * message to retrieve the descriptor. The string returned is Unicode, as - * detailed in the USB specifications. - * - * \param dev_handle a device handle - * \param desc_index the index of the descriptor to retrieve - * \param langid the language ID for the string descriptor - * \param data output buffer for descriptor - * \param length size of data buffer - * \returns number of bytes returned in data, or LIBUSB_ERROR code on failure - * \see libusb_get_string_descriptor_ascii() - */ -static inline int libusb_get_string_descriptor(libusb_device_handle *dev_handle, - uint8_t desc_index, uint16_t langid, unsigned char *data, int length) -{ - return libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_IN, - LIBUSB_REQUEST_GET_DESCRIPTOR, (uint16_t)((LIBUSB_DT_STRING << 8) | desc_index), - langid, data, (uint16_t) length, 1000); -} - -int LIBUSB_CALL libusb_get_string_descriptor_ascii(libusb_device_handle *dev_handle, - uint8_t desc_index, unsigned char *data, int length); - -/* polling and timeouts */ - -int LIBUSB_CALL libusb_try_lock_events(libusb_context *ctx); -void LIBUSB_CALL libusb_lock_events(libusb_context *ctx); -void LIBUSB_CALL libusb_unlock_events(libusb_context *ctx); -int LIBUSB_CALL libusb_event_handling_ok(libusb_context *ctx); -int LIBUSB_CALL libusb_event_handler_active(libusb_context *ctx); -void LIBUSB_CALL libusb_interrupt_event_handler(libusb_context *ctx); -void LIBUSB_CALL libusb_lock_event_waiters(libusb_context *ctx); -void LIBUSB_CALL libusb_unlock_event_waiters(libusb_context *ctx); -int LIBUSB_CALL libusb_wait_for_event(libusb_context *ctx, struct timeval *tv); - -int LIBUSB_CALL libusb_handle_events_timeout(libusb_context *ctx, - struct timeval *tv); -int LIBUSB_CALL libusb_handle_events_timeout_completed(libusb_context *ctx, - struct timeval *tv, int *completed); -int LIBUSB_CALL libusb_handle_events(libusb_context *ctx); -int LIBUSB_CALL libusb_handle_events_completed(libusb_context *ctx, int *completed); -int LIBUSB_CALL libusb_handle_events_locked(libusb_context *ctx, - struct timeval *tv); -int LIBUSB_CALL libusb_pollfds_handle_timeouts(libusb_context *ctx); -int LIBUSB_CALL libusb_get_next_timeout(libusb_context *ctx, - struct timeval *tv); - -/** \ingroup libusb_poll - * File descriptor for polling - */ -struct libusb_pollfd { - /** Numeric file descriptor */ - int fd; - - /** Event flags to poll for from . POLLIN indicates that you - * should monitor this file descriptor for becoming ready to read from, - * and POLLOUT indicates that you should monitor this file descriptor for - * nonblocking write readiness. */ - short events; -}; - -/** \ingroup libusb_poll - * Callback function, invoked when a new file descriptor should be added - * to the set of file descriptors monitored for events. - * \param fd the new file descriptor - * \param events events to monitor for, see \ref libusb_pollfd for a - * description - * \param user_data User data pointer specified in - * libusb_set_pollfd_notifiers() call - * \see libusb_set_pollfd_notifiers() - */ -typedef void (LIBUSB_CALL *libusb_pollfd_added_cb)(int fd, short events, - void *user_data); - -/** \ingroup libusb_poll - * Callback function, invoked when a file descriptor should be removed from - * the set of file descriptors being monitored for events. After returning - * from this callback, do not use that file descriptor again. - * \param fd the file descriptor to stop monitoring - * \param user_data User data pointer specified in - * libusb_set_pollfd_notifiers() call - * \see libusb_set_pollfd_notifiers() - */ -typedef void (LIBUSB_CALL *libusb_pollfd_removed_cb)(int fd, void *user_data); - -const struct libusb_pollfd ** LIBUSB_CALL libusb_get_pollfds( - libusb_context *ctx); -void LIBUSB_CALL libusb_free_pollfds(const struct libusb_pollfd **pollfds); -void LIBUSB_CALL libusb_set_pollfd_notifiers(libusb_context *ctx, - libusb_pollfd_added_cb added_cb, libusb_pollfd_removed_cb removed_cb, - void *user_data); - -/** \ingroup libusb_hotplug - * Callback handle. - * - * Callbacks handles are generated by libusb_hotplug_register_callback() - * and can be used to deregister callbacks. Callback handles are unique - * per libusb_context and it is safe to call libusb_hotplug_deregister_callback() - * on an already deregisted callback. - * - * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102 - * - * For more information, see \ref libusb_hotplug. - */ -typedef int libusb_hotplug_callback_handle; - -/** \ingroup libusb_hotplug - * - * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102 - * - * Flags for hotplug events */ -typedef enum { - /** Default value when not using any flags. */ - LIBUSB_HOTPLUG_NO_FLAGS = 0, - - /** Arm the callback and fire it for all matching currently attached devices. */ - LIBUSB_HOTPLUG_ENUMERATE = 1<<0, -} libusb_hotplug_flag; - -/** \ingroup libusb_hotplug - * - * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102 - * - * Hotplug events */ -typedef enum { - /** A device has been plugged in and is ready to use */ - LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED = 0x01, - - /** A device has left and is no longer available. - * It is the user's responsibility to call libusb_close on any handle associated with a disconnected device. - * It is safe to call libusb_get_device_descriptor on a device that has left */ - LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT = 0x02, -} libusb_hotplug_event; - -/** \ingroup libusb_hotplug - * Wildcard matching for hotplug events */ -#define LIBUSB_HOTPLUG_MATCH_ANY -1 - -/** \ingroup libusb_hotplug - * Hotplug callback function type. When requesting hotplug event notifications, - * you pass a pointer to a callback function of this type. - * - * This callback may be called by an internal event thread and as such it is - * recommended the callback do minimal processing before returning. - * - * libusb will call this function later, when a matching event had happened on - * a matching device. See \ref libusb_hotplug for more information. - * - * It is safe to call either libusb_hotplug_register_callback() or - * libusb_hotplug_deregister_callback() from within a callback function. - * - * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102 - * - * \param ctx context of this notification - * \param device libusb_device this event occurred on - * \param event event that occurred - * \param user_data user data provided when this callback was registered - * \returns bool whether this callback is finished processing events. - * returning 1 will cause this callback to be deregistered - */ -typedef int (LIBUSB_CALL *libusb_hotplug_callback_fn)(libusb_context *ctx, - libusb_device *device, - libusb_hotplug_event event, - void *user_data); - -/** \ingroup libusb_hotplug - * Register a hotplug callback function - * - * Register a callback with the libusb_context. The callback will fire - * when a matching event occurs on a matching device. The callback is - * armed until either it is deregistered with libusb_hotplug_deregister_callback() - * or the supplied callback returns 1 to indicate it is finished processing events. - * - * If the \ref LIBUSB_HOTPLUG_ENUMERATE is passed the callback will be - * called with a \ref LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED for all devices - * already plugged into the machine. Note that libusb modifies its internal - * device list from a separate thread, while calling hotplug callbacks from - * libusb_handle_events(), so it is possible for a device to already be present - * on, or removed from, its internal device list, while the hotplug callbacks - * still need to be dispatched. This means that when using \ref - * LIBUSB_HOTPLUG_ENUMERATE, your callback may be called twice for the arrival - * of the same device, once from libusb_hotplug_register_callback() and once - * from libusb_handle_events(); and/or your callback may be called for the - * removal of a device for which an arrived call was never made. - * - * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102 - * - * \param[in] ctx context to register this callback with - * \param[in] events bitwise or of events that will trigger this callback. See \ref - * libusb_hotplug_event - * \param[in] flags hotplug callback flags. See \ref libusb_hotplug_flag - * \param[in] vendor_id the vendor id to match or \ref LIBUSB_HOTPLUG_MATCH_ANY - * \param[in] product_id the product id to match or \ref LIBUSB_HOTPLUG_MATCH_ANY - * \param[in] dev_class the device class to match or \ref LIBUSB_HOTPLUG_MATCH_ANY - * \param[in] cb_fn the function to be invoked on a matching event/device - * \param[in] user_data user data to pass to the callback function - * \param[out] callback_handle pointer to store the handle of the allocated callback (can be NULL) - * \returns LIBUSB_SUCCESS on success LIBUSB_ERROR code on failure - */ -int LIBUSB_CALL libusb_hotplug_register_callback(libusb_context *ctx, - libusb_hotplug_event events, - libusb_hotplug_flag flags, - int vendor_id, int product_id, - int dev_class, - libusb_hotplug_callback_fn cb_fn, - void *user_data, - libusb_hotplug_callback_handle *callback_handle); - -/** \ingroup libusb_hotplug - * Deregisters a hotplug callback. - * - * Deregister a callback from a libusb_context. This function is safe to call from within - * a hotplug callback. - * - * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102 - * - * \param[in] ctx context this callback is registered with - * \param[in] callback_handle the handle of the callback to deregister - */ -void LIBUSB_CALL libusb_hotplug_deregister_callback(libusb_context *ctx, - libusb_hotplug_callback_handle callback_handle); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/libusbi.h b/vendor/github.com/karalabe/hid/libusb/libusb/libusbi.h deleted file mode 100644 index 752e3988..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/libusbi.h +++ /dev/null @@ -1,1149 +0,0 @@ -/* - * Internal header for libusb - * Copyright © 2007-2009 Daniel Drake - * Copyright © 2001 Johannes Erdfelt - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef LIBUSBI_H -#define LIBUSBI_H - -#include - -#include - -#include -#include -#include -#include -#ifdef HAVE_POLL_H -#include -#endif -#ifdef HAVE_MISSING_H -#include -#endif - -#include "libusb.h" -#include "version.h" - -/* Inside the libusb code, mark all public functions as follows: - * return_type API_EXPORTED function_name(params) { ... } - * But if the function returns a pointer, mark it as follows: - * DEFAULT_VISIBILITY return_type * LIBUSB_CALL function_name(params) { ... } - * In the libusb public header, mark all declarations as: - * return_type LIBUSB_CALL function_name(params); - */ -#define API_EXPORTED LIBUSB_CALL DEFAULT_VISIBILITY - -#ifdef __cplusplus -extern "C" { -#endif - -#define DEVICE_DESC_LENGTH 18 - -#define USB_MAXENDPOINTS 32 -#define USB_MAXINTERFACES 32 -#define USB_MAXCONFIG 8 - -/* Backend specific capabilities */ -#define USBI_CAP_HAS_HID_ACCESS 0x00010000 -#define USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER 0x00020000 - -/* Maximum number of bytes in a log line */ -#define USBI_MAX_LOG_LEN 1024 -/* Terminator for log lines */ -#define USBI_LOG_LINE_END "\n" - -/* The following is used to silence warnings for unused variables */ -#define UNUSED(var) do { (void)(var); } while(0) - -#if !defined(ARRAYSIZE) -#define ARRAYSIZE(array) (sizeof(array) / sizeof(array[0])) -#endif - -struct list_head { - struct list_head *prev, *next; -}; - -/* Get an entry from the list - * ptr - the address of this list_head element in "type" - * type - the data type that contains "member" - * member - the list_head element in "type" - */ -#define list_entry(ptr, type, member) \ - ((type *)((uintptr_t)(ptr) - (uintptr_t)offsetof(type, member))) - -#define list_first_entry(ptr, type, member) \ - list_entry((ptr)->next, type, member) - -/* Get each entry from a list - * pos - A structure pointer has a "member" element - * head - list head - * member - the list_head element in "pos" - * type - the type of the first parameter - */ -#define list_for_each_entry(pos, head, member, type) \ - for (pos = list_entry((head)->next, type, member); \ - &pos->member != (head); \ - pos = list_entry(pos->member.next, type, member)) - -#define list_for_each_entry_safe(pos, n, head, member, type) \ - for (pos = list_entry((head)->next, type, member), \ - n = list_entry(pos->member.next, type, member); \ - &pos->member != (head); \ - pos = n, n = list_entry(n->member.next, type, member)) - -#define list_empty(entry) ((entry)->next == (entry)) - -static inline void list_init(struct list_head *entry) -{ - entry->prev = entry->next = entry; -} - -static inline void list_add(struct list_head *entry, struct list_head *head) -{ - entry->next = head->next; - entry->prev = head; - - head->next->prev = entry; - head->next = entry; -} - -static inline void list_add_tail(struct list_head *entry, - struct list_head *head) -{ - entry->next = head; - entry->prev = head->prev; - - head->prev->next = entry; - head->prev = entry; -} - -static inline void list_del(struct list_head *entry) -{ - entry->next->prev = entry->prev; - entry->prev->next = entry->next; - entry->next = entry->prev = NULL; -} - -static inline void *usbi_reallocf(void *ptr, size_t size) -{ - void *ret = realloc(ptr, size); - if (!ret) - free(ptr); - return ret; -} - -#define container_of(ptr, type, member) ({ \ - const typeof( ((type *)0)->member ) *mptr = (ptr); \ - (type *)( (char *)mptr - offsetof(type,member) );}) - -#ifndef MIN -#define MIN(a, b) ((a) < (b) ? (a) : (b)) -#endif -#ifndef MAX -#define MAX(a, b) ((a) > (b) ? (a) : (b)) -#endif - -#define TIMESPEC_IS_SET(ts) ((ts)->tv_sec != 0 || (ts)->tv_nsec != 0) - -#if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE) -#define TIMEVAL_TV_SEC_TYPE long -#else -#define TIMEVAL_TV_SEC_TYPE time_t -#endif - -/* Some platforms don't have this define */ -#ifndef TIMESPEC_TO_TIMEVAL -#define TIMESPEC_TO_TIMEVAL(tv, ts) \ - do { \ - (tv)->tv_sec = (TIMEVAL_TV_SEC_TYPE) (ts)->tv_sec; \ - (tv)->tv_usec = (ts)->tv_nsec / 1000; \ - } while (0) -#endif - -void usbi_log(struct libusb_context *ctx, enum libusb_log_level level, - const char *function, const char *format, ...); - -void usbi_log_v(struct libusb_context *ctx, enum libusb_log_level level, - const char *function, const char *format, va_list args); - -#if !defined(_MSC_VER) || _MSC_VER >= 1400 - -#ifdef ENABLE_LOGGING -#define _usbi_log(ctx, level, ...) usbi_log(ctx, level, __FUNCTION__, __VA_ARGS__) -#define usbi_dbg(...) _usbi_log(NULL, LIBUSB_LOG_LEVEL_DEBUG, __VA_ARGS__) -#else -#define _usbi_log(ctx, level, ...) do { (void)(ctx); } while(0) -#define usbi_dbg(...) do {} while(0) -#endif - -#define usbi_info(ctx, ...) _usbi_log(ctx, LIBUSB_LOG_LEVEL_INFO, __VA_ARGS__) -#define usbi_warn(ctx, ...) _usbi_log(ctx, LIBUSB_LOG_LEVEL_WARNING, __VA_ARGS__) -#define usbi_err(ctx, ...) _usbi_log(ctx, LIBUSB_LOG_LEVEL_ERROR, __VA_ARGS__) - -#else /* !defined(_MSC_VER) || _MSC_VER >= 1400 */ - -#ifdef ENABLE_LOGGING -#define LOG_BODY(ctxt, level) \ -{ \ - va_list args; \ - va_start(args, format); \ - usbi_log_v(ctxt, level, "", format, args); \ - va_end(args); \ -} -#else -#define LOG_BODY(ctxt, level) \ -{ \ - (void)(ctxt); \ -} -#endif - -static inline void usbi_info(struct libusb_context *ctx, const char *format, ...) - LOG_BODY(ctx, LIBUSB_LOG_LEVEL_INFO) -static inline void usbi_warn(struct libusb_context *ctx, const char *format, ...) - LOG_BODY(ctx, LIBUSB_LOG_LEVEL_WARNING) -static inline void usbi_err(struct libusb_context *ctx, const char *format, ...) - LOG_BODY(ctx, LIBUSB_LOG_LEVEL_ERROR) - -static inline void usbi_dbg(const char *format, ...) - LOG_BODY(NULL, LIBUSB_LOG_LEVEL_DEBUG) - -#endif /* !defined(_MSC_VER) || _MSC_VER >= 1400 */ - -#define USBI_GET_CONTEXT(ctx) \ - do { \ - if (!(ctx)) \ - (ctx) = usbi_default_context; \ - } while(0) - -#define DEVICE_CTX(dev) ((dev)->ctx) -#define HANDLE_CTX(handle) (DEVICE_CTX((handle)->dev)) -#define TRANSFER_CTX(transfer) (HANDLE_CTX((transfer)->dev_handle)) -#define ITRANSFER_CTX(transfer) \ - (TRANSFER_CTX(USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer))) - -#define IS_EPIN(ep) (0 != ((ep) & LIBUSB_ENDPOINT_IN)) -#define IS_EPOUT(ep) (!IS_EPIN(ep)) -#define IS_XFERIN(xfer) (0 != ((xfer)->endpoint & LIBUSB_ENDPOINT_IN)) -#define IS_XFEROUT(xfer) (!IS_XFERIN(xfer)) - -/* Internal abstraction for thread synchronization */ -#if defined(THREADS_POSIX) -#include "os/threads_posix.h" -#elif defined(OS_WINDOWS) || defined(OS_WINCE) -#include "os/threads_windows.h" -#endif - -extern struct libusb_context *usbi_default_context; - -/* Forward declaration for use in context (fully defined inside poll abstraction) */ -struct pollfd; - -struct libusb_context { - int debug; - int debug_fixed; - - /* internal event pipe, used for signalling occurrence of an internal event. */ - int event_pipe[2]; - - struct list_head usb_devs; - usbi_mutex_t usb_devs_lock; - - /* A list of open handles. Backends are free to traverse this if required. - */ - struct list_head open_devs; - usbi_mutex_t open_devs_lock; - - /* A list of registered hotplug callbacks */ - struct list_head hotplug_cbs; - usbi_mutex_t hotplug_cbs_lock; - - /* this is a list of in-flight transfer handles, sorted by timeout - * expiration. URBs to timeout the soonest are placed at the beginning of - * the list, URBs that will time out later are placed after, and urbs with - * infinite timeout are always placed at the very end. */ - struct list_head flying_transfers; - /* Note paths taking both this and usbi_transfer->lock must always - * take this lock first */ - usbi_mutex_t flying_transfers_lock; - - /* user callbacks for pollfd changes */ - libusb_pollfd_added_cb fd_added_cb; - libusb_pollfd_removed_cb fd_removed_cb; - void *fd_cb_user_data; - - /* ensures that only one thread is handling events at any one time */ - usbi_mutex_t events_lock; - - /* used to see if there is an active thread doing event handling */ - int event_handler_active; - - /* A thread-local storage key to track which thread is performing event - * handling */ - usbi_tls_key_t event_handling_key; - - /* used to wait for event completion in threads other than the one that is - * event handling */ - usbi_mutex_t event_waiters_lock; - usbi_cond_t event_waiters_cond; - - /* A lock to protect internal context event data. */ - usbi_mutex_t event_data_lock; - - /* A bitmask of flags that are set to indicate specific events that need to - * be handled. Protected by event_data_lock. */ - unsigned int event_flags; - - /* A counter that is set when we want to interrupt and prevent event handling, - * in order to safely close a device. Protected by event_data_lock. */ - unsigned int device_close; - - /* list and count of poll fds and an array of poll fd structures that is - * (re)allocated as necessary prior to polling. Protected by event_data_lock. */ - struct list_head ipollfds; - struct pollfd *pollfds; - POLL_NFDS_TYPE pollfds_cnt; - - /* A list of pending hotplug messages. Protected by event_data_lock. */ - struct list_head hotplug_msgs; - - /* A list of pending completed transfers. Protected by event_data_lock. */ - struct list_head completed_transfers; - -#ifdef USBI_TIMERFD_AVAILABLE - /* used for timeout handling, if supported by OS. - * this timerfd is maintained to trigger on the next pending timeout */ - int timerfd; -#endif - - struct list_head list; -}; - -enum usbi_event_flags { - /* The list of pollfds has been modified */ - USBI_EVENT_POLLFDS_MODIFIED = 1 << 0, - - /* The user has interrupted the event handler */ - USBI_EVENT_USER_INTERRUPT = 1 << 1, -}; - -/* Macros for managing event handling state */ -#define usbi_handling_events(ctx) \ - (usbi_tls_key_get((ctx)->event_handling_key) != NULL) - -#define usbi_start_event_handling(ctx) \ - usbi_tls_key_set((ctx)->event_handling_key, ctx) - -#define usbi_end_event_handling(ctx) \ - usbi_tls_key_set((ctx)->event_handling_key, NULL) - -/* Update the following macro if new event sources are added */ -#define usbi_pending_events(ctx) \ - ((ctx)->event_flags || (ctx)->device_close \ - || !list_empty(&(ctx)->hotplug_msgs) || !list_empty(&(ctx)->completed_transfers)) - -#ifdef USBI_TIMERFD_AVAILABLE -#define usbi_using_timerfd(ctx) ((ctx)->timerfd >= 0) -#else -#define usbi_using_timerfd(ctx) (0) -#endif - -struct libusb_device { - /* lock protects refcnt, everything else is finalized at initialization - * time */ - usbi_mutex_t lock; - int refcnt; - - struct libusb_context *ctx; - - uint8_t bus_number; - uint8_t port_number; - struct libusb_device* parent_dev; - uint8_t device_address; - uint8_t num_configurations; - enum libusb_speed speed; - - struct list_head list; - unsigned long session_data; - - struct libusb_device_descriptor device_descriptor; - int attached; - - unsigned char os_priv -#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) - [] /* valid C99 code */ -#else - [0] /* non-standard, but usually working code */ -#endif -#if defined(OS_SUNOS) - __attribute__ ((aligned (8))); -#else - ; -#endif -}; - -struct libusb_device_handle { - /* lock protects claimed_interfaces */ - usbi_mutex_t lock; - unsigned long claimed_interfaces; - - struct list_head list; - struct libusb_device *dev; - int auto_detach_kernel_driver; - unsigned char os_priv -#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) - [] /* valid C99 code */ -#else - [0] /* non-standard, but usually working code */ -#endif -#if defined(OS_SUNOS) - __attribute__ ((aligned (8))); -#else - ; -#endif -}; - -enum { - USBI_CLOCK_MONOTONIC, - USBI_CLOCK_REALTIME -}; - -/* in-memory transfer layout: - * - * 1. struct usbi_transfer - * 2. struct libusb_transfer (which includes iso packets) [variable size] - * 3. os private data [variable size] - * - * from a libusb_transfer, you can get the usbi_transfer by rewinding the - * appropriate number of bytes. - * the usbi_transfer includes the number of allocated packets, so you can - * determine the size of the transfer and hence the start and length of the - * OS-private data. - */ - -struct usbi_transfer { - int num_iso_packets; - struct list_head list; - struct list_head completed_list; - struct timeval timeout; - int transferred; - uint32_t stream_id; - uint8_t state_flags; /* Protected by usbi_transfer->lock */ - uint8_t timeout_flags; /* Protected by the flying_stransfers_lock */ - - /* this lock is held during libusb_submit_transfer() and - * libusb_cancel_transfer() (allowing the OS backend to prevent duplicate - * cancellation, submission-during-cancellation, etc). the OS backend - * should also take this lock in the handle_events path, to prevent the user - * cancelling the transfer from another thread while you are processing - * its completion (presumably there would be races within your OS backend - * if this were possible). - * Note paths taking both this and the flying_transfers_lock must - * always take the flying_transfers_lock first */ - usbi_mutex_t lock; -}; - -enum usbi_transfer_state_flags { - /* Transfer successfully submitted by backend */ - USBI_TRANSFER_IN_FLIGHT = 1 << 0, - - /* Cancellation was requested via libusb_cancel_transfer() */ - USBI_TRANSFER_CANCELLING = 1 << 1, - - /* Operation on the transfer failed because the device disappeared */ - USBI_TRANSFER_DEVICE_DISAPPEARED = 1 << 2, -}; - -enum usbi_transfer_timeout_flags { - /* Set by backend submit_transfer() if the OS handles timeout */ - USBI_TRANSFER_OS_HANDLES_TIMEOUT = 1 << 0, - - /* The transfer timeout has been handled */ - USBI_TRANSFER_TIMEOUT_HANDLED = 1 << 1, - - /* The transfer timeout was successfully processed */ - USBI_TRANSFER_TIMED_OUT = 1 << 2, -}; - -#define USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer) \ - ((struct libusb_transfer *)(((unsigned char *)(transfer)) \ - + sizeof(struct usbi_transfer))) -#define LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer) \ - ((struct usbi_transfer *)(((unsigned char *)(transfer)) \ - - sizeof(struct usbi_transfer))) - -static inline void *usbi_transfer_get_os_priv(struct usbi_transfer *transfer) -{ - return ((unsigned char *)transfer) + sizeof(struct usbi_transfer) - + sizeof(struct libusb_transfer) - + (transfer->num_iso_packets - * sizeof(struct libusb_iso_packet_descriptor)); -} - -/* bus structures */ - -/* All standard descriptors have these 2 fields in common */ -struct usb_descriptor_header { - uint8_t bLength; - uint8_t bDescriptorType; -}; - -/* shared data and functions */ - -int usbi_io_init(struct libusb_context *ctx); -void usbi_io_exit(struct libusb_context *ctx); - -struct libusb_device *usbi_alloc_device(struct libusb_context *ctx, - unsigned long session_id); -struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx, - unsigned long session_id); -int usbi_sanitize_device(struct libusb_device *dev); -void usbi_handle_disconnect(struct libusb_device_handle *dev_handle); - -int usbi_handle_transfer_completion(struct usbi_transfer *itransfer, - enum libusb_transfer_status status); -int usbi_handle_transfer_cancellation(struct usbi_transfer *transfer); -void usbi_signal_transfer_completion(struct usbi_transfer *transfer); - -int usbi_parse_descriptor(const unsigned char *source, const char *descriptor, - void *dest, int host_endian); -int usbi_device_cache_descriptor(libusb_device *dev); -int usbi_get_config_index_by_value(struct libusb_device *dev, - uint8_t bConfigurationValue, int *idx); - -void usbi_connect_device (struct libusb_device *dev); -void usbi_disconnect_device (struct libusb_device *dev); - -int usbi_signal_event(struct libusb_context *ctx); -int usbi_clear_event(struct libusb_context *ctx); - -/* Internal abstraction for poll (needs struct usbi_transfer on Windows) */ -#if defined(OS_LINUX) || defined(OS_DARWIN) || defined(OS_OPENBSD) || defined(OS_NETBSD) ||\ - defined(OS_HAIKU) || defined(OS_SUNOS) -#include -#include "os/poll_posix.h" -#elif defined(OS_WINDOWS) || defined(OS_WINCE) -#include "os/poll_windows.h" -#endif - -#if defined(_MSC_VER) && (_MSC_VER < 1900) -#define snprintf usbi_snprintf -#define vsnprintf usbi_vsnprintf -int usbi_snprintf(char *dst, size_t size, const char *format, ...); -int usbi_vsnprintf(char *dst, size_t size, const char *format, va_list ap); -#define LIBUSB_PRINTF_WIN32 -#endif - -struct usbi_pollfd { - /* must come first */ - struct libusb_pollfd pollfd; - - struct list_head list; -}; - -int usbi_add_pollfd(struct libusb_context *ctx, int fd, short events); -void usbi_remove_pollfd(struct libusb_context *ctx, int fd); - -/* device discovery */ - -/* we traverse usbfs without knowing how many devices we are going to find. - * so we create this discovered_devs model which is similar to a linked-list - * which grows when required. it can be freed once discovery has completed, - * eliminating the need for a list node in the libusb_device structure - * itself. */ -struct discovered_devs { - size_t len; - size_t capacity; - struct libusb_device *devices -#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) - [] /* valid C99 code */ -#else - [0] /* non-standard, but usually working code */ -#endif - ; -}; - -struct discovered_devs *discovered_devs_append( - struct discovered_devs *discdevs, struct libusb_device *dev); - -/* OS abstraction */ - -/* This is the interface that OS backends need to implement. - * All fields are mandatory, except ones explicitly noted as optional. */ -struct usbi_os_backend { - /* A human-readable name for your backend, e.g. "Linux usbfs" */ - const char *name; - - /* Binary mask for backend specific capabilities */ - uint32_t caps; - - /* Perform initialization of your backend. You might use this function - * to determine specific capabilities of the system, allocate required - * data structures for later, etc. - * - * This function is called when a libusb user initializes the library - * prior to use. - * - * Return 0 on success, or a LIBUSB_ERROR code on failure. - */ - int (*init)(struct libusb_context *ctx); - - /* Deinitialization. Optional. This function should destroy anything - * that was set up by init. - * - * This function is called when the user deinitializes the library. - */ - void (*exit)(void); - - /* Enumerate all the USB devices on the system, returning them in a list - * of discovered devices. - * - * Your implementation should enumerate all devices on the system, - * regardless of whether they have been seen before or not. - * - * When you have found a device, compute a session ID for it. The session - * ID should uniquely represent that particular device for that particular - * connection session since boot (i.e. if you disconnect and reconnect a - * device immediately after, it should be assigned a different session ID). - * If your OS cannot provide a unique session ID as described above, - * presenting a session ID of (bus_number << 8 | device_address) should - * be sufficient. Bus numbers and device addresses wrap and get reused, - * but that is an unlikely case. - * - * After computing a session ID for a device, call - * usbi_get_device_by_session_id(). This function checks if libusb already - * knows about the device, and if so, it provides you with a reference - * to a libusb_device structure for it. - * - * If usbi_get_device_by_session_id() returns NULL, it is time to allocate - * a new device structure for the device. Call usbi_alloc_device() to - * obtain a new libusb_device structure with reference count 1. Populate - * the bus_number and device_address attributes of the new device, and - * perform any other internal backend initialization you need to do. At - * this point, you should be ready to provide device descriptors and so - * on through the get_*_descriptor functions. Finally, call - * usbi_sanitize_device() to perform some final sanity checks on the - * device. Assuming all of the above succeeded, we can now continue. - * If any of the above failed, remember to unreference the device that - * was returned by usbi_alloc_device(). - * - * At this stage we have a populated libusb_device structure (either one - * that was found earlier, or one that we have just allocated and - * populated). This can now be added to the discovered devices list - * using discovered_devs_append(). Note that discovered_devs_append() - * may reallocate the list, returning a new location for it, and also - * note that reallocation can fail. Your backend should handle these - * error conditions appropriately. - * - * This function should not generate any bus I/O and should not block. - * If I/O is required (e.g. reading the active configuration value), it is - * OK to ignore these suggestions :) - * - * This function is executed when the user wishes to retrieve a list - * of USB devices connected to the system. - * - * If the backend has hotplug support, this function is not used! - * - * Return 0 on success, or a LIBUSB_ERROR code on failure. - */ - int (*get_device_list)(struct libusb_context *ctx, - struct discovered_devs **discdevs); - - /* Apps which were written before hotplug support, may listen for - * hotplug events on their own and call libusb_get_device_list on - * device addition. In this case libusb_get_device_list will likely - * return a list without the new device in there, as the hotplug - * event thread will still be busy enumerating the device, which may - * take a while, or may not even have seen the event yet. - * - * To avoid this libusb_get_device_list will call this optional - * function for backends with hotplug support before copying - * ctx->usb_devs to the user. In this function the backend should - * ensure any pending hotplug events are fully processed before - * returning. - * - * Optional, should be implemented by backends with hotplug support. - */ - void (*hotplug_poll)(void); - - /* Open a device for I/O and other USB operations. The device handle - * is preallocated for you, you can retrieve the device in question - * through handle->dev. - * - * Your backend should allocate any internal resources required for I/O - * and other operations so that those operations can happen (hopefully) - * without hiccup. This is also a good place to inform libusb that it - * should monitor certain file descriptors related to this device - - * see the usbi_add_pollfd() function. - * - * This function should not generate any bus I/O and should not block. - * - * This function is called when the user attempts to obtain a device - * handle for a device. - * - * Return: - * - 0 on success - * - LIBUSB_ERROR_ACCESS if the user has insufficient permissions - * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since - * discovery - * - another LIBUSB_ERROR code on other failure - * - * Do not worry about freeing the handle on failed open, the upper layers - * do this for you. - */ - int (*open)(struct libusb_device_handle *dev_handle); - - /* Close a device such that the handle cannot be used again. Your backend - * should destroy any resources that were allocated in the open path. - * This may also be a good place to call usbi_remove_pollfd() to inform - * libusb of any file descriptors associated with this device that should - * no longer be monitored. - * - * This function is called when the user closes a device handle. - */ - void (*close)(struct libusb_device_handle *dev_handle); - - /* Retrieve the device descriptor from a device. - * - * The descriptor should be retrieved from memory, NOT via bus I/O to the - * device. This means that you may have to cache it in a private structure - * during get_device_list enumeration. Alternatively, you may be able - * to retrieve it from a kernel interface (some Linux setups can do this) - * still without generating bus I/O. - * - * This function is expected to write DEVICE_DESC_LENGTH (18) bytes into - * buffer, which is guaranteed to be big enough. - * - * This function is called when sanity-checking a device before adding - * it to the list of discovered devices, and also when the user requests - * to read the device descriptor. - * - * This function is expected to return the descriptor in bus-endian format - * (LE). If it returns the multi-byte values in host-endian format, - * set the host_endian output parameter to "1". - * - * Return 0 on success or a LIBUSB_ERROR code on failure. - */ - int (*get_device_descriptor)(struct libusb_device *device, - unsigned char *buffer, int *host_endian); - - /* Get the ACTIVE configuration descriptor for a device. - * - * The descriptor should be retrieved from memory, NOT via bus I/O to the - * device. This means that you may have to cache it in a private structure - * during get_device_list enumeration. You may also have to keep track - * of which configuration is active when the user changes it. - * - * This function is expected to write len bytes of data into buffer, which - * is guaranteed to be big enough. If you can only do a partial write, - * return an error code. - * - * This function is expected to return the descriptor in bus-endian format - * (LE). If it returns the multi-byte values in host-endian format, - * set the host_endian output parameter to "1". - * - * Return: - * - 0 on success - * - LIBUSB_ERROR_NOT_FOUND if the device is in unconfigured state - * - another LIBUSB_ERROR code on other failure - */ - int (*get_active_config_descriptor)(struct libusb_device *device, - unsigned char *buffer, size_t len, int *host_endian); - - /* Get a specific configuration descriptor for a device. - * - * The descriptor should be retrieved from memory, NOT via bus I/O to the - * device. This means that you may have to cache it in a private structure - * during get_device_list enumeration. - * - * The requested descriptor is expressed as a zero-based index (i.e. 0 - * indicates that we are requesting the first descriptor). The index does - * not (necessarily) equal the bConfigurationValue of the configuration - * being requested. - * - * This function is expected to write len bytes of data into buffer, which - * is guaranteed to be big enough. If you can only do a partial write, - * return an error code. - * - * This function is expected to return the descriptor in bus-endian format - * (LE). If it returns the multi-byte values in host-endian format, - * set the host_endian output parameter to "1". - * - * Return the length read on success or a LIBUSB_ERROR code on failure. - */ - int (*get_config_descriptor)(struct libusb_device *device, - uint8_t config_index, unsigned char *buffer, size_t len, - int *host_endian); - - /* Like get_config_descriptor but then by bConfigurationValue instead - * of by index. - * - * Optional, if not present the core will call get_config_descriptor - * for all configs until it finds the desired bConfigurationValue. - * - * Returns a pointer to the raw-descriptor in *buffer, this memory - * is valid as long as device is valid. - * - * Returns the length of the returned raw-descriptor on success, - * or a LIBUSB_ERROR code on failure. - */ - int (*get_config_descriptor_by_value)(struct libusb_device *device, - uint8_t bConfigurationValue, unsigned char **buffer, - int *host_endian); - - /* Get the bConfigurationValue for the active configuration for a device. - * Optional. This should only be implemented if you can retrieve it from - * cache (don't generate I/O). - * - * If you cannot retrieve this from cache, either do not implement this - * function, or return LIBUSB_ERROR_NOT_SUPPORTED. This will cause - * libusb to retrieve the information through a standard control transfer. - * - * This function must be non-blocking. - * Return: - * - 0 on success - * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it - * was opened - * - LIBUSB_ERROR_NOT_SUPPORTED if the value cannot be retrieved without - * blocking - * - another LIBUSB_ERROR code on other failure. - */ - int (*get_configuration)(struct libusb_device_handle *dev_handle, int *config); - - /* Set the active configuration for a device. - * - * A configuration value of -1 should put the device in unconfigured state. - * - * This function can block. - * - * Return: - * - 0 on success - * - LIBUSB_ERROR_NOT_FOUND if the configuration does not exist - * - LIBUSB_ERROR_BUSY if interfaces are currently claimed (and hence - * configuration cannot be changed) - * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it - * was opened - * - another LIBUSB_ERROR code on other failure. - */ - int (*set_configuration)(struct libusb_device_handle *dev_handle, int config); - - /* Claim an interface. When claimed, the application can then perform - * I/O to an interface's endpoints. - * - * This function should not generate any bus I/O and should not block. - * Interface claiming is a logical operation that simply ensures that - * no other drivers/applications are using the interface, and after - * claiming, no other drivers/applications can use the interface because - * we now "own" it. - * - * Return: - * - 0 on success - * - LIBUSB_ERROR_NOT_FOUND if the interface does not exist - * - LIBUSB_ERROR_BUSY if the interface is in use by another driver/app - * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it - * was opened - * - another LIBUSB_ERROR code on other failure - */ - int (*claim_interface)(struct libusb_device_handle *dev_handle, int interface_number); - - /* Release a previously claimed interface. - * - * This function should also generate a SET_INTERFACE control request, - * resetting the alternate setting of that interface to 0. It's OK for - * this function to block as a result. - * - * You will only ever be asked to release an interface which was - * successfully claimed earlier. - * - * Return: - * - 0 on success - * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it - * was opened - * - another LIBUSB_ERROR code on other failure - */ - int (*release_interface)(struct libusb_device_handle *dev_handle, int interface_number); - - /* Set the alternate setting for an interface. - * - * You will only ever be asked to set the alternate setting for an - * interface which was successfully claimed earlier. - * - * It's OK for this function to block. - * - * Return: - * - 0 on success - * - LIBUSB_ERROR_NOT_FOUND if the alternate setting does not exist - * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it - * was opened - * - another LIBUSB_ERROR code on other failure - */ - int (*set_interface_altsetting)(struct libusb_device_handle *dev_handle, - int interface_number, int altsetting); - - /* Clear a halt/stall condition on an endpoint. - * - * It's OK for this function to block. - * - * Return: - * - 0 on success - * - LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist - * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it - * was opened - * - another LIBUSB_ERROR code on other failure - */ - int (*clear_halt)(struct libusb_device_handle *dev_handle, - unsigned char endpoint); - - /* Perform a USB port reset to reinitialize a device. - * - * If possible, the device handle should still be usable after the reset - * completes, assuming that the device descriptors did not change during - * reset and all previous interface state can be restored. - * - * If something changes, or you cannot easily locate/verify the resetted - * device, return LIBUSB_ERROR_NOT_FOUND. This prompts the application - * to close the old handle and re-enumerate the device. - * - * Return: - * - 0 on success - * - LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the device - * has been disconnected since it was opened - * - another LIBUSB_ERROR code on other failure - */ - int (*reset_device)(struct libusb_device_handle *dev_handle); - - /* Alloc num_streams usb3 bulk streams on the passed in endpoints */ - int (*alloc_streams)(struct libusb_device_handle *dev_handle, - uint32_t num_streams, unsigned char *endpoints, int num_endpoints); - - /* Free usb3 bulk streams allocated with alloc_streams */ - int (*free_streams)(struct libusb_device_handle *dev_handle, - unsigned char *endpoints, int num_endpoints); - - /* Allocate persistent DMA memory for the given device, suitable for - * zerocopy. May return NULL on failure. Optional to implement. - */ - unsigned char *(*dev_mem_alloc)(struct libusb_device_handle *handle, - size_t len); - - /* Free memory allocated by dev_mem_alloc. */ - int (*dev_mem_free)(struct libusb_device_handle *handle, - unsigned char *buffer, size_t len); - - /* Determine if a kernel driver is active on an interface. Optional. - * - * The presence of a kernel driver on an interface indicates that any - * calls to claim_interface would fail with the LIBUSB_ERROR_BUSY code. - * - * Return: - * - 0 if no driver is active - * - 1 if a driver is active - * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it - * was opened - * - another LIBUSB_ERROR code on other failure - */ - int (*kernel_driver_active)(struct libusb_device_handle *dev_handle, - int interface_number); - - /* Detach a kernel driver from an interface. Optional. - * - * After detaching a kernel driver, the interface should be available - * for claim. - * - * Return: - * - 0 on success - * - LIBUSB_ERROR_NOT_FOUND if no kernel driver was active - * - LIBUSB_ERROR_INVALID_PARAM if the interface does not exist - * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it - * was opened - * - another LIBUSB_ERROR code on other failure - */ - int (*detach_kernel_driver)(struct libusb_device_handle *dev_handle, - int interface_number); - - /* Attach a kernel driver to an interface. Optional. - * - * Reattach a kernel driver to the device. - * - * Return: - * - 0 on success - * - LIBUSB_ERROR_NOT_FOUND if no kernel driver was active - * - LIBUSB_ERROR_INVALID_PARAM if the interface does not exist - * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected since it - * was opened - * - LIBUSB_ERROR_BUSY if a program or driver has claimed the interface, - * preventing reattachment - * - another LIBUSB_ERROR code on other failure - */ - int (*attach_kernel_driver)(struct libusb_device_handle *dev_handle, - int interface_number); - - /* Destroy a device. Optional. - * - * This function is called when the last reference to a device is - * destroyed. It should free any resources allocated in the get_device_list - * path. - */ - void (*destroy_device)(struct libusb_device *dev); - - /* Submit a transfer. Your implementation should take the transfer, - * morph it into whatever form your platform requires, and submit it - * asynchronously. - * - * This function must not block. - * - * This function gets called with the flying_transfers_lock locked! - * - * Return: - * - 0 on success - * - LIBUSB_ERROR_NO_DEVICE if the device has been disconnected - * - another LIBUSB_ERROR code on other failure - */ - int (*submit_transfer)(struct usbi_transfer *itransfer); - - /* Cancel a previously submitted transfer. - * - * This function must not block. The transfer cancellation must complete - * later, resulting in a call to usbi_handle_transfer_cancellation() - * from the context of handle_events. - */ - int (*cancel_transfer)(struct usbi_transfer *itransfer); - - /* Clear a transfer as if it has completed or cancelled, but do not - * report any completion/cancellation to the library. You should free - * all private data from the transfer as if you were just about to report - * completion or cancellation. - * - * This function might seem a bit out of place. It is used when libusb - * detects a disconnected device - it calls this function for all pending - * transfers before reporting completion (with the disconnect code) to - * the user. Maybe we can improve upon this internal interface in future. - */ - void (*clear_transfer_priv)(struct usbi_transfer *itransfer); - - /* Handle any pending events on file descriptors. Optional. - * - * Provide this function when file descriptors directly indicate device - * or transfer activity. If your backend does not have such file descriptors, - * implement the handle_transfer_completion function below. - * - * This involves monitoring any active transfers and processing their - * completion or cancellation. - * - * The function is passed an array of pollfd structures (size nfds) - * as a result of the poll() system call. The num_ready parameter - * indicates the number of file descriptors that have reported events - * (i.e. the poll() return value). This should be enough information - * for you to determine which actions need to be taken on the currently - * active transfers. - * - * For any cancelled transfers, call usbi_handle_transfer_cancellation(). - * For completed transfers, call usbi_handle_transfer_completion(). - * For control/bulk/interrupt transfers, populate the "transferred" - * element of the appropriate usbi_transfer structure before calling the - * above functions. For isochronous transfers, populate the status and - * transferred fields of the iso packet descriptors of the transfer. - * - * This function should also be able to detect disconnection of the - * device, reporting that situation with usbi_handle_disconnect(). - * - * When processing an event related to a transfer, you probably want to - * take usbi_transfer.lock to prevent races. See the documentation for - * the usbi_transfer structure. - * - * Return 0 on success, or a LIBUSB_ERROR code on failure. - */ - int (*handle_events)(struct libusb_context *ctx, - struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready); - - /* Handle transfer completion. Optional. - * - * Provide this function when there are no file descriptors available - * that directly indicate device or transfer activity. If your backend does - * have such file descriptors, implement the handle_events function above. - * - * Your backend must tell the library when a transfer has completed by - * calling usbi_signal_transfer_completion(). You should store any private - * information about the transfer and its completion status in the transfer's - * private backend data. - * - * During event handling, this function will be called on each transfer for - * which usbi_signal_transfer_completion() was called. - * - * For any cancelled transfers, call usbi_handle_transfer_cancellation(). - * For completed transfers, call usbi_handle_transfer_completion(). - * For control/bulk/interrupt transfers, populate the "transferred" - * element of the appropriate usbi_transfer structure before calling the - * above functions. For isochronous transfers, populate the status and - * transferred fields of the iso packet descriptors of the transfer. - * - * Return 0 on success, or a LIBUSB_ERROR code on failure. - */ - int (*handle_transfer_completion)(struct usbi_transfer *itransfer); - - /* Get time from specified clock. At least two clocks must be implemented - by the backend: USBI_CLOCK_REALTIME, and USBI_CLOCK_MONOTONIC. - - Description of clocks: - USBI_CLOCK_REALTIME : clock returns time since system epoch. - USBI_CLOCK_MONOTONIC: clock returns time since unspecified start - time (usually boot). - */ - int (*clock_gettime)(int clkid, struct timespec *tp); - -#ifdef USBI_TIMERFD_AVAILABLE - /* clock ID of the clock that should be used for timerfd */ - clockid_t (*get_timerfd_clockid)(void); -#endif - - /* Number of bytes to reserve for per-device private backend data. - * This private data area is accessible through the "os_priv" field of - * struct libusb_device. */ - size_t device_priv_size; - - /* Number of bytes to reserve for per-handle private backend data. - * This private data area is accessible through the "os_priv" field of - * struct libusb_device. */ - size_t device_handle_priv_size; - - /* Number of bytes to reserve for per-transfer private backend data. - * This private data area is accessible by calling - * usbi_transfer_get_os_priv() on the appropriate usbi_transfer instance. - */ - size_t transfer_priv_size; -}; - -extern const struct usbi_os_backend * const usbi_backend; - -extern const struct usbi_os_backend linux_usbfs_backend; -extern const struct usbi_os_backend darwin_backend; -extern const struct usbi_os_backend openbsd_backend; -extern const struct usbi_os_backend netbsd_backend; -extern const struct usbi_os_backend windows_backend; -extern const struct usbi_os_backend usbdk_backend; -extern const struct usbi_os_backend wince_backend; -extern const struct usbi_os_backend haiku_usb_raw_backend; -extern const struct usbi_os_backend sunos_backend; - -extern struct list_head active_contexts_list; -extern usbi_mutex_static_t active_contexts_lock; - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/darwin_usb.c b/vendor/github.com/karalabe/hid/libusb/libusb/os/darwin_usb.c deleted file mode 100644 index b0219d1b..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/darwin_usb.c +++ /dev/null @@ -1,2094 +0,0 @@ -/* -*- Mode: C; indent-tabs-mode:nil -*- */ -/* - * darwin backend for libusb 1.0 - * Copyright © 2008-2016 Nathan Hjelm - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include "config.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include -#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200 - #include -#endif - -#if MAC_OS_X_VERSION_MIN_REQUIRED >= 101200 -/* Apple deprecated the darwin atomics in 10.12 in favor of C11 atomics */ -#include -#define libusb_darwin_atomic_fetch_add(x, y) atomic_fetch_add(x, y) - -_Atomic int32_t initCount = ATOMIC_VAR_INIT(0); -#else -/* use darwin atomics if the target is older than 10.12 */ -#include - -/* OSAtomicAdd32Barrier returns the new value */ -#define libusb_darwin_atomic_fetch_add(x, y) (OSAtomicAdd32Barrier(y, x) - y) - -static volatile int32_t initCount = 0; -#endif - -#include "darwin_usb.h" - -/* async event thread */ -static pthread_mutex_t libusb_darwin_at_mutex = PTHREAD_MUTEX_INITIALIZER; -static pthread_cond_t libusb_darwin_at_cond = PTHREAD_COND_INITIALIZER; - -static pthread_once_t darwin_init_once = PTHREAD_ONCE_INIT; - -static clock_serv_t clock_realtime; -static clock_serv_t clock_monotonic; - -static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */ -static CFRunLoopSourceRef libusb_darwin_acfls = NULL; /* shutdown signal for event cf loop */ - -static usbi_mutex_t darwin_cached_devices_lock = PTHREAD_MUTEX_INITIALIZER; -static struct list_head darwin_cached_devices = {&darwin_cached_devices, &darwin_cached_devices}; -static char *darwin_device_class = kIOUSBDeviceClassName; - -#define DARWIN_CACHED_DEVICE(a) ((struct darwin_cached_device *) (((struct darwin_device_priv *)((a)->os_priv))->dev)) - -/* async event thread */ -static pthread_t libusb_darwin_at; - -static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian); -static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface); -static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface); -static int darwin_reset_device(struct libusb_device_handle *dev_handle); -static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0); - -static int darwin_scan_devices(struct libusb_context *ctx); -static int process_new_device (struct libusb_context *ctx, io_service_t service); - -#if defined(ENABLE_LOGGING) -static const char *darwin_error_str (int result) { - static char string_buffer[50]; - switch (result) { - case kIOReturnSuccess: - return "no error"; - case kIOReturnNotOpen: - return "device not opened for exclusive access"; - case kIOReturnNoDevice: - return "no connection to an IOService"; - case kIOUSBNoAsyncPortErr: - return "no async port has been opened for interface"; - case kIOReturnExclusiveAccess: - return "another process has device opened for exclusive access"; - case kIOUSBPipeStalled: - return "pipe is stalled"; - case kIOReturnError: - return "could not establish a connection to the Darwin kernel"; - case kIOUSBTransactionTimeout: - return "transaction timed out"; - case kIOReturnBadArgument: - return "invalid argument"; - case kIOReturnAborted: - return "transaction aborted"; - case kIOReturnNotResponding: - return "device not responding"; - case kIOReturnOverrun: - return "data overrun"; - case kIOReturnCannotWire: - return "physical memory can not be wired down"; - case kIOReturnNoResources: - return "out of resources"; - case kIOUSBHighSpeedSplitError: - return "high speed split error"; - default: - snprintf(string_buffer, sizeof(string_buffer), "unknown error (0x%x)", result); - return string_buffer; - } -} -#endif - -static int darwin_to_libusb (int result) { - switch (result) { - case kIOReturnUnderrun: - case kIOReturnSuccess: - return LIBUSB_SUCCESS; - case kIOReturnNotOpen: - case kIOReturnNoDevice: - return LIBUSB_ERROR_NO_DEVICE; - case kIOReturnExclusiveAccess: - return LIBUSB_ERROR_ACCESS; - case kIOUSBPipeStalled: - return LIBUSB_ERROR_PIPE; - case kIOReturnBadArgument: - return LIBUSB_ERROR_INVALID_PARAM; - case kIOUSBTransactionTimeout: - return LIBUSB_ERROR_TIMEOUT; - case kIOReturnNotResponding: - case kIOReturnAborted: - case kIOReturnError: - case kIOUSBNoAsyncPortErr: - default: - return LIBUSB_ERROR_OTHER; - } -} - -/* this function must be called with the darwin_cached_devices_lock held */ -static void darwin_deref_cached_device(struct darwin_cached_device *cached_dev) { - cached_dev->refcount--; - /* free the device and remove it from the cache */ - if (0 == cached_dev->refcount) { - list_del(&cached_dev->list); - - (*(cached_dev->device))->Release(cached_dev->device); - free (cached_dev); - } -} - -static void darwin_ref_cached_device(struct darwin_cached_device *cached_dev) { - cached_dev->refcount++; -} - -static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp, struct darwin_interface **interface_out) { - struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv; - - /* current interface */ - struct darwin_interface *cInterface; - - int8_t i, iface; - - usbi_dbg ("converting ep address 0x%02x to pipeRef and interface", ep); - - for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) { - cInterface = &priv->interfaces[iface]; - - if (dev_handle->claimed_interfaces & (1 << iface)) { - for (i = 0 ; i < cInterface->num_endpoints ; i++) { - if (cInterface->endpoint_addrs[i] == ep) { - *pipep = i + 1; - - if (ifcp) - *ifcp = iface; - - if (interface_out) - *interface_out = cInterface; - - usbi_dbg ("pipe %d on interface %d matches", *pipep, iface); - return 0; - } - } - } - } - - /* No pipe found with the correct endpoint address */ - usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep); - - return LIBUSB_ERROR_NOT_FOUND; -} - -static int usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) { - CFMutableDictionaryRef matchingDict = IOServiceMatching(darwin_device_class); - - if (!matchingDict) - return kIOReturnError; - - if (location) { - CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, - &kCFTypeDictionaryKeyCallBacks, - &kCFTypeDictionaryValueCallBacks); - - if (propertyMatchDict) { - /* there are no unsigned CFNumber types so treat the value as signed. the os seems to do this - internally (CFNumberType of locationID is 3) */ - CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location); - - CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF); - /* release our reference to the CFNumber (CFDictionarySetValue retains it) */ - CFRelease (locationCF); - - CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict); - /* release out reference to the CFMutableDictionaryRef (CFDictionarySetValue retains it) */ - CFRelease (propertyMatchDict); - } - /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */ - } - - return IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, deviceIterator); -} - -/* Returns 1 on success, 0 on failure. */ -static int get_ioregistry_value_number (io_service_t service, CFStringRef property, CFNumberType type, void *p) { - CFTypeRef cfNumber = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0); - int ret = 0; - - if (cfNumber) { - if (CFGetTypeID(cfNumber) == CFNumberGetTypeID()) { - ret = CFNumberGetValue(cfNumber, type, p); - } - - CFRelease (cfNumber); - } - - return ret; -} - -static int get_ioregistry_value_data (io_service_t service, CFStringRef property, ssize_t size, void *p) { - CFTypeRef cfData = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0); - int ret = 0; - - if (cfData) { - if (CFGetTypeID (cfData) == CFDataGetTypeID ()) { - CFIndex length = CFDataGetLength (cfData); - if (length < size) { - size = length; - } - - CFDataGetBytes (cfData, CFRangeMake(0, size), p); - ret = 1; - } - - CFRelease (cfData); - } - - return ret; -} - -static usb_device_t **darwin_device_from_service (io_service_t service) -{ - io_cf_plugin_ref_t *plugInInterface = NULL; - usb_device_t **device; - kern_return_t result; - SInt32 score; - - result = IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID, - kIOCFPlugInInterfaceID, &plugInInterface, - &score); - - if (kIOReturnSuccess != result || !plugInInterface) { - usbi_dbg ("could not set up plugin for service: %s", darwin_error_str (result)); - return NULL; - } - - (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(DeviceInterfaceID), - (LPVOID)&device); - /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */ - (*plugInInterface)->Release (plugInInterface); - - return device; -} - -static void darwin_devices_attached (void *ptr, io_iterator_t add_devices) { - struct libusb_context *ctx; - io_service_t service; - - usbi_mutex_lock(&active_contexts_lock); - - while ((service = IOIteratorNext(add_devices))) { - /* add this device to each active context's device list */ - list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) { - process_new_device (ctx, service);; - } - - IOObjectRelease(service); - } - - usbi_mutex_unlock(&active_contexts_lock); -} - -static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) { - struct libusb_device *dev = NULL; - struct libusb_context *ctx; - struct darwin_cached_device *old_device; - - io_service_t device; - UInt64 session; - int ret; - - usbi_mutex_lock(&active_contexts_lock); - - while ((device = IOIteratorNext (rem_devices)) != 0) { - /* get the location from the i/o registry */ - ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session); - IOObjectRelease (device); - if (!ret) - continue; - - /* we need to match darwin_ref_cached_device call made in darwin_get_cached_device function - otherwise no cached device will ever get freed */ - usbi_mutex_lock(&darwin_cached_devices_lock); - list_for_each_entry(old_device, &darwin_cached_devices, list, struct darwin_cached_device) { - if (old_device->session == session) { - darwin_deref_cached_device (old_device); - break; - } - } - usbi_mutex_unlock(&darwin_cached_devices_lock); - - list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) { - usbi_dbg ("notifying context %p of device disconnect", ctx); - - dev = usbi_get_device_by_session_id(ctx, (unsigned long) session); - if (dev) { - /* signal the core that this device has been disconnected. the core will tear down this device - when the reference count reaches 0 */ - usbi_disconnect_device(dev); - libusb_unref_device(dev); - } - } - } - - usbi_mutex_unlock(&active_contexts_lock); -} - -static void darwin_hotplug_poll (void) -{ - /* not sure if 5 seconds will be too long/short but it should work ok */ - mach_timespec_t timeout = {.tv_sec = 5, .tv_nsec = 0}; - - /* since a kernel thread may nodify the IOInterators used for - * hotplug notidication we can't just clear the iterators. - * instead just wait until all IOService providers are quiet */ - (void) IOKitWaitQuiet (kIOMasterPortDefault, &timeout); -} - -static void darwin_clear_iterator (io_iterator_t iter) { - io_service_t device; - - while ((device = IOIteratorNext (iter)) != 0) - IOObjectRelease (device); -} - -static void *darwin_event_thread_main (void *arg0) { - IOReturn kresult; - struct libusb_context *ctx = (struct libusb_context *)arg0; - CFRunLoopRef runloop; - -#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 - /* Set this thread's name, so it can be seen in the debugger - and crash reports. */ - pthread_setname_np ("org.libusb.device-hotplug"); -#endif - -#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200 - /* Tell the Objective-C garbage collector about this thread. - This is required because, unlike NSThreads, pthreads are - not automatically registered. Although we don't use - Objective-C, we use CoreFoundation, which does. - Garbage collection support was entirely removed in 10.12, - so don't bother there. */ - objc_registerThreadWithCollector(); -#endif - - /* hotplug (device arrival/removal) sources */ - CFRunLoopSourceContext libusb_shutdown_cfsourcectx; - CFRunLoopSourceRef libusb_notification_cfsource; - io_notification_port_t libusb_notification_port; - io_iterator_t libusb_rem_device_iterator; - io_iterator_t libusb_add_device_iterator; - - usbi_dbg ("creating hotplug event source"); - - runloop = CFRunLoopGetCurrent (); - CFRetain (runloop); - - /* add the shutdown cfsource to the run loop */ - memset(&libusb_shutdown_cfsourcectx, 0, sizeof(libusb_shutdown_cfsourcectx)); - libusb_shutdown_cfsourcectx.info = runloop; - libusb_shutdown_cfsourcectx.perform = (void (*)(void *))CFRunLoopStop; - libusb_darwin_acfls = CFRunLoopSourceCreate(NULL, 0, &libusb_shutdown_cfsourcectx); - CFRunLoopAddSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode); - - /* add the notification port to the run loop */ - libusb_notification_port = IONotificationPortCreate (kIOMasterPortDefault); - libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port); - CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode); - - /* create notifications for removed devices */ - kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification, - IOServiceMatching(darwin_device_class), - darwin_devices_detached, - ctx, &libusb_rem_device_iterator); - - if (kresult != kIOReturnSuccess) { - usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult)); - - pthread_exit (NULL); - } - - /* create notifications for attached devices */ - kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification, - IOServiceMatching(darwin_device_class), - darwin_devices_attached, - ctx, &libusb_add_device_iterator); - - if (kresult != kIOReturnSuccess) { - usbi_err (ctx, "could not add hotplug event source: %s", darwin_error_str (kresult)); - - pthread_exit (NULL); - } - - /* arm notifiers */ - darwin_clear_iterator (libusb_rem_device_iterator); - darwin_clear_iterator (libusb_add_device_iterator); - - usbi_dbg ("darwin event thread ready to receive events"); - - /* signal the main thread that the hotplug runloop has been created. */ - pthread_mutex_lock (&libusb_darwin_at_mutex); - libusb_darwin_acfl = runloop; - pthread_cond_signal (&libusb_darwin_at_cond); - pthread_mutex_unlock (&libusb_darwin_at_mutex); - - /* run the runloop */ - CFRunLoopRun(); - - usbi_dbg ("darwin event thread exiting"); - - /* remove the notification cfsource */ - CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode); - - /* remove the shutdown cfsource */ - CFRunLoopRemoveSource(runloop, libusb_darwin_acfls, kCFRunLoopDefaultMode); - - /* delete notification port */ - IONotificationPortDestroy (libusb_notification_port); - - /* delete iterators */ - IOObjectRelease (libusb_rem_device_iterator); - IOObjectRelease (libusb_add_device_iterator); - - CFRelease (libusb_darwin_acfls); - CFRelease (runloop); - - libusb_darwin_acfls = NULL; - libusb_darwin_acfl = NULL; - - pthread_exit (NULL); -} - -/* cleanup function to destroy cached devices */ -static void __attribute__((destructor)) _darwin_finalize(void) { - struct darwin_cached_device *dev, *next; - - usbi_mutex_lock(&darwin_cached_devices_lock); - list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) { - darwin_deref_cached_device(dev); - } - usbi_mutex_unlock(&darwin_cached_devices_lock); -} - -static void darwin_check_version (void) { - /* adjust for changes in the USB stack in xnu 15 */ - int sysctl_args[] = {CTL_KERN, KERN_OSRELEASE}; - long version; - char version_string[256] = {'\0',}; - size_t length = 256; - - sysctl(sysctl_args, 2, version_string, &length, NULL, 0); - - errno = 0; - version = strtol (version_string, NULL, 10); - if (0 == errno && version >= 15) { - darwin_device_class = "IOUSBHostDevice"; - } -} - -static int darwin_init(struct libusb_context *ctx) { - host_name_port_t host_self; - int rc; - - rc = pthread_once (&darwin_init_once, darwin_check_version); - if (rc) { - return LIBUSB_ERROR_OTHER; - } - - rc = darwin_scan_devices (ctx); - if (LIBUSB_SUCCESS != rc) { - return rc; - } - - if (libusb_darwin_atomic_fetch_add (&initCount, 1) == 0) { - /* create the clocks that will be used */ - - host_self = mach_host_self(); - host_get_clock_service(host_self, CALENDAR_CLOCK, &clock_realtime); - host_get_clock_service(host_self, SYSTEM_CLOCK, &clock_monotonic); - mach_port_deallocate(mach_task_self(), host_self); - - pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, ctx); - - pthread_mutex_lock (&libusb_darwin_at_mutex); - while (!libusb_darwin_acfl) - pthread_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex); - pthread_mutex_unlock (&libusb_darwin_at_mutex); - } - - return rc; -} - -static void darwin_exit (void) { - if (libusb_darwin_atomic_fetch_add (&initCount, -1) == 1) { - mach_port_deallocate(mach_task_self(), clock_realtime); - mach_port_deallocate(mach_task_self(), clock_monotonic); - - /* stop the event runloop and wait for the thread to terminate. */ - CFRunLoopSourceSignal(libusb_darwin_acfls); - CFRunLoopWakeUp (libusb_darwin_acfl); - pthread_join (libusb_darwin_at, NULL); - } -} - -static int darwin_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) { - struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev); - - /* return cached copy */ - memmove (buffer, &(priv->dev_descriptor), DEVICE_DESC_LENGTH); - - *host_endian = 0; - - return 0; -} - -static int get_configuration_index (struct libusb_device *dev, int config_value) { - struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev); - UInt8 i, numConfig; - IOUSBConfigurationDescriptorPtr desc; - IOReturn kresult; - - /* is there a simpler way to determine the index? */ - kresult = (*(priv->device))->GetNumberOfConfigurations (priv->device, &numConfig); - if (kresult != kIOReturnSuccess) - return darwin_to_libusb (kresult); - - for (i = 0 ; i < numConfig ; i++) { - (*(priv->device))->GetConfigurationDescriptorPtr (priv->device, i, &desc); - - if (desc->bConfigurationValue == config_value) - return i; - } - - /* configuration not found */ - return LIBUSB_ERROR_NOT_FOUND; -} - -static int darwin_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) { - struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev); - int config_index; - - if (0 == priv->active_config) - return LIBUSB_ERROR_NOT_FOUND; - - config_index = get_configuration_index (dev, priv->active_config); - if (config_index < 0) - return config_index; - - return darwin_get_config_descriptor (dev, config_index, buffer, len, host_endian); -} - -static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) { - struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev); - IOUSBConfigurationDescriptorPtr desc; - IOReturn kresult; - int ret; - - if (!priv || !priv->device) - return LIBUSB_ERROR_OTHER; - - kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc); - if (kresult == kIOReturnSuccess) { - /* copy descriptor */ - if (libusb_le16_to_cpu(desc->wTotalLength) < len) - len = libusb_le16_to_cpu(desc->wTotalLength); - - memmove (buffer, desc, len); - - /* GetConfigurationDescriptorPtr returns the descriptor in USB bus order */ - *host_endian = 0; - } - - ret = darwin_to_libusb (kresult); - if (ret != LIBUSB_SUCCESS) - return ret; - - return (int) len; -} - -/* check whether the os has configured the device */ -static int darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) { - usb_device_t **darwin_device = dev->device; - - IOUSBConfigurationDescriptorPtr configDesc; - IOUSBFindInterfaceRequest request; - kern_return_t kresult; - io_iterator_t interface_iterator; - io_service_t firstInterface; - - if (dev->dev_descriptor.bNumConfigurations < 1) { - usbi_err (ctx, "device has no configurations"); - return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */ - } - - /* checking the configuration of a root hub simulation takes ~1 s in 10.11. the device is - not usable anyway */ - if (0x05ac == dev->dev_descriptor.idVendor && 0x8005 == dev->dev_descriptor.idProduct) { - usbi_dbg ("ignoring configuration on root hub simulation"); - dev->active_config = 0; - return 0; - } - - /* find the first configuration */ - kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc); - dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1; - - /* check if the device is already configured. there is probably a better way than iterating over the - to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices - might lock up on the device request) */ - - /* Setup the Interface Request */ - request.bInterfaceClass = kIOUSBFindInterfaceDontCare; - request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare; - request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare; - request.bAlternateSetting = kIOUSBFindInterfaceDontCare; - - kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator); - if (kresult) - return darwin_to_libusb (kresult); - - /* iterate once */ - firstInterface = IOIteratorNext(interface_iterator); - - /* done with the interface iterator */ - IOObjectRelease(interface_iterator); - - if (firstInterface) { - IOObjectRelease (firstInterface); - - /* device is configured */ - if (dev->dev_descriptor.bNumConfigurations == 1) - /* to avoid problems with some devices get the configurations value from the configuration descriptor */ - dev->active_config = dev->first_config; - else - /* devices with more than one configuration should work with GetConfiguration */ - (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config); - } else - /* not configured */ - dev->active_config = 0; - - usbi_dbg ("active config: %u, first config: %u", dev->active_config, dev->first_config); - - return 0; -} - -static int darwin_request_descriptor (usb_device_t **device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) { - IOUSBDevRequestTO req; - - memset (buffer, 0, buffer_size); - - /* Set up request for descriptor/ */ - req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice); - req.bRequest = kUSBRqGetDescriptor; - req.wValue = desc << 8; - req.wIndex = desc_index; - req.wLength = buffer_size; - req.pData = buffer; - req.noDataTimeout = 20; - req.completionTimeout = 100; - - return (*device)->DeviceRequestTO (device, &req); -} - -static int darwin_cache_device_descriptor (struct libusb_context *ctx, struct darwin_cached_device *dev) { - usb_device_t **device = dev->device; - int retries = 1, delay = 30000; - int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1; - int is_open = 0; - int ret = 0, ret2; - UInt8 bDeviceClass; - UInt16 idProduct, idVendor; - - dev->can_enumerate = 0; - - (*device)->GetDeviceClass (device, &bDeviceClass); - (*device)->GetDeviceProduct (device, &idProduct); - (*device)->GetDeviceVendor (device, &idVendor); - - /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some - * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still, - * to follow the spec as closely as possible, try opening the device */ - is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess); - - do { - /**** retrieve device descriptor ****/ - ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor)); - - if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType) - /* received an overrun error but we still received a device descriptor */ - ret = kIOReturnSuccess; - - if (kIOUSBVendorIDAppleComputer == idVendor) { - /* NTH: don't bother retrying or unsuspending Apple devices */ - break; - } - - if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations || - 0 == dev->dev_descriptor.bcdUSB)) { - /* work around for incorrectly configured devices */ - if (try_reconfigure && is_open) { - usbi_dbg("descriptor appears to be invalid. resetting configuration before trying again..."); - - /* set the first configuration */ - (*device)->SetConfiguration(device, 1); - - /* don't try to reconfigure again */ - try_reconfigure = 0; - } - - ret = kIOUSBPipeStalled; - } - - if (kIOReturnSuccess != ret && is_open && try_unsuspend) { - /* device may be suspended. unsuspend it and try again */ -#if DeviceVersion >= 320 - UInt32 info = 0; - - /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */ - (void)(*device)->GetUSBDeviceInformation (device, &info); - - /* note that the device was suspended */ - if (info & (1 << kUSBInformationDeviceIsSuspendedBit) || 0 == info) - try_unsuspend = 1; -#endif - - if (try_unsuspend) { - /* try to unsuspend the device */ - ret2 = (*device)->USBDeviceSuspend (device, 0); - if (kIOReturnSuccess != ret2) { - /* prevent log spew from poorly behaving devices. this indicates the - os actually had trouble communicating with the device */ - usbi_dbg("could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2)); - } else - unsuspended = 1; - - try_unsuspend = 0; - } - } - - if (kIOReturnSuccess != ret) { - usbi_dbg("kernel responded with code: 0x%08x. sleeping for %d ms before trying again", ret, delay/1000); - /* sleep for a little while before trying again */ - nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000UL}, NULL); - } - } while (kIOReturnSuccess != ret && retries--); - - if (unsuspended) - /* resuspend the device */ - (void)(*device)->USBDeviceSuspend (device, 1); - - if (is_open) - (void) (*device)->USBDeviceClose (device); - - if (ret != kIOReturnSuccess) { - /* a debug message was already printed out for this error */ - if (LIBUSB_CLASS_HUB == bDeviceClass) - usbi_dbg ("could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device", - idVendor, idProduct, darwin_error_str (ret), ret); - else - usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device", - idVendor, idProduct, darwin_error_str (ret), ret); - return darwin_to_libusb (ret); - } - - /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */ - if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) { - /* not a valid device */ - usbi_warn (ctx, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device", - idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct)); - return LIBUSB_ERROR_NO_DEVICE; - } - - usbi_dbg ("cached device descriptor:"); - usbi_dbg (" bDescriptorType: 0x%02x", dev->dev_descriptor.bDescriptorType); - usbi_dbg (" bcdUSB: 0x%04x", dev->dev_descriptor.bcdUSB); - usbi_dbg (" bDeviceClass: 0x%02x", dev->dev_descriptor.bDeviceClass); - usbi_dbg (" bDeviceSubClass: 0x%02x", dev->dev_descriptor.bDeviceSubClass); - usbi_dbg (" bDeviceProtocol: 0x%02x", dev->dev_descriptor.bDeviceProtocol); - usbi_dbg (" bMaxPacketSize0: 0x%02x", dev->dev_descriptor.bMaxPacketSize0); - usbi_dbg (" idVendor: 0x%04x", dev->dev_descriptor.idVendor); - usbi_dbg (" idProduct: 0x%04x", dev->dev_descriptor.idProduct); - usbi_dbg (" bcdDevice: 0x%04x", dev->dev_descriptor.bcdDevice); - usbi_dbg (" iManufacturer: 0x%02x", dev->dev_descriptor.iManufacturer); - usbi_dbg (" iProduct: 0x%02x", dev->dev_descriptor.iProduct); - usbi_dbg (" iSerialNumber: 0x%02x", dev->dev_descriptor.iSerialNumber); - usbi_dbg (" bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations); - - dev->can_enumerate = 1; - - return LIBUSB_SUCCESS; -} - -static int get_device_port (io_service_t service, UInt8 *port) { - kern_return_t result; - io_service_t parent; - int ret = 0; - - if (get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, port)) { - return 1; - } - - result = IORegistryEntryGetParentEntry (service, kIOServicePlane, &parent); - if (kIOReturnSuccess == result) { - ret = get_ioregistry_value_data (parent, CFSTR("port"), 1, port); - IOObjectRelease (parent); - } - - return ret; -} - -static int darwin_get_cached_device(struct libusb_context *ctx, io_service_t service, - struct darwin_cached_device **cached_out) { - struct darwin_cached_device *new_device; - UInt64 sessionID = 0, parent_sessionID = 0; - int ret = LIBUSB_SUCCESS; - usb_device_t **device; - io_service_t parent; - kern_return_t result; - UInt8 port = 0; - - /* get some info from the io registry */ - (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID); - if (!get_device_port (service, &port)) { - usbi_dbg("could not get connected port number"); - } - - usbi_dbg("finding cached device for sessionID 0x%" PRIx64, sessionID); - - result = IORegistryEntryGetParentEntry (service, kIOUSBPlane, &parent); - - if (kIOReturnSuccess == result) { - (void) get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, &parent_sessionID); - IOObjectRelease(parent); - } - - usbi_mutex_lock(&darwin_cached_devices_lock); - do { - *cached_out = NULL; - - list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) { - usbi_dbg("matching sessionID 0x%" PRIx64 " against cached device with sessionID 0x%" PRIx64, sessionID, new_device->session); - if (new_device->session == sessionID) { - usbi_dbg("using cached device for device"); - *cached_out = new_device; - break; - } - } - - if (*cached_out) - break; - - usbi_dbg("caching new device with sessionID 0x%" PRIx64, sessionID); - - device = darwin_device_from_service (service); - if (!device) { - ret = LIBUSB_ERROR_NO_DEVICE; - break; - } - - new_device = calloc (1, sizeof (*new_device)); - if (!new_device) { - ret = LIBUSB_ERROR_NO_MEM; - break; - } - - /* add this device to the cached device list */ - list_add(&new_device->list, &darwin_cached_devices); - - (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address); - - /* keep a reference to this device */ - darwin_ref_cached_device(new_device); - - new_device->device = device; - new_device->session = sessionID; - (*device)->GetLocationID (device, &new_device->location); - new_device->port = port; - new_device->parent_session = parent_sessionID; - - /* cache the device descriptor */ - ret = darwin_cache_device_descriptor(ctx, new_device); - if (ret) - break; - - if (new_device->can_enumerate) { - snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address, - new_device->dev_descriptor.idVendor, new_device->dev_descriptor.idProduct, - new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass); - } - } while (0); - - usbi_mutex_unlock(&darwin_cached_devices_lock); - - /* keep track of devices regardless of if we successfully enumerate them to - prevent them from being enumerated multiple times */ - - *cached_out = new_device; - - return ret; -} - -static int process_new_device (struct libusb_context *ctx, io_service_t service) { - struct darwin_device_priv *priv; - struct libusb_device *dev = NULL; - struct darwin_cached_device *cached_device; - UInt8 devSpeed; - int ret = 0; - - do { - ret = darwin_get_cached_device (ctx, service, &cached_device); - - if (ret < 0 || !cached_device->can_enumerate) { - return ret; - } - - /* check current active configuration (and cache the first configuration value-- - which may be used by claim_interface) */ - ret = darwin_check_configuration (ctx, cached_device); - if (ret) - break; - - usbi_dbg ("allocating new device in context %p for with session 0x%" PRIx64, - ctx, cached_device->session); - - dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session); - if (!dev) { - return LIBUSB_ERROR_NO_MEM; - } - - priv = (struct darwin_device_priv *)dev->os_priv; - - priv->dev = cached_device; - darwin_ref_cached_device (priv->dev); - - if (cached_device->parent_session > 0) { - dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session); - } else { - dev->parent_dev = NULL; - } - dev->port_number = cached_device->port; - dev->bus_number = cached_device->location >> 24; - dev->device_address = cached_device->address; - - (*(priv->dev->device))->GetDeviceSpeed (priv->dev->device, &devSpeed); - - switch (devSpeed) { - case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break; - case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break; - case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break; -#if DeviceVersion >= 500 - case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break; -#endif - default: - usbi_warn (ctx, "Got unknown device speed %d", devSpeed); - } - - ret = usbi_sanitize_device (dev); - if (ret < 0) - break; - - usbi_dbg ("found device with address %d port = %d parent = %p at %p", dev->device_address, - dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path); - } while (0); - - if (0 == ret) { - usbi_connect_device (dev); - } else { - libusb_unref_device (dev); - } - - return ret; -} - -static int darwin_scan_devices(struct libusb_context *ctx) { - io_iterator_t deviceIterator; - io_service_t service; - kern_return_t kresult; - - kresult = usb_setup_device_iterator (&deviceIterator, 0); - if (kresult != kIOReturnSuccess) - return darwin_to_libusb (kresult); - - while ((service = IOIteratorNext (deviceIterator))) { - (void) process_new_device (ctx, service); - - IOObjectRelease(service); - } - - IOObjectRelease(deviceIterator); - - return 0; -} - -static int darwin_open (struct libusb_device_handle *dev_handle) { - struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv; - struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev); - IOReturn kresult; - - if (0 == dpriv->open_count) { - /* try to open the device */ - kresult = (*(dpriv->device))->USBDeviceOpenSeize (dpriv->device); - if (kresult != kIOReturnSuccess) { - usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult)); - - if (kIOReturnExclusiveAccess != kresult) { - return darwin_to_libusb (kresult); - } - - /* it is possible to perform some actions on a device that is not open so do not return an error */ - priv->is_open = 0; - } else { - priv->is_open = 1; - } - - /* create async event source */ - kresult = (*(dpriv->device))->CreateDeviceAsyncEventSource (dpriv->device, &priv->cfSource); - if (kresult != kIOReturnSuccess) { - usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult)); - - if (priv->is_open) { - (*(dpriv->device))->USBDeviceClose (dpriv->device); - } - - priv->is_open = 0; - - return darwin_to_libusb (kresult); - } - - CFRetain (libusb_darwin_acfl); - - /* add the cfSource to the aync run loop */ - CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes); - } - - /* device opened successfully */ - dpriv->open_count++; - - usbi_dbg ("device open for access"); - - return 0; -} - -static void darwin_close (struct libusb_device_handle *dev_handle) { - struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv; - struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev); - IOReturn kresult; - int i; - - if (dpriv->open_count == 0) { - /* something is probably very wrong if this is the case */ - usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!"); - return; - } - - dpriv->open_count--; - - /* make sure all interfaces are released */ - for (i = 0 ; i < USB_MAXINTERFACES ; i++) - if (dev_handle->claimed_interfaces & (1 << i)) - libusb_release_interface (dev_handle, i); - - if (0 == dpriv->open_count) { - /* delete the device's async event source */ - if (priv->cfSource) { - CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode); - CFRelease (priv->cfSource); - priv->cfSource = NULL; - CFRelease (libusb_darwin_acfl); - } - - if (priv->is_open) { - /* close the device */ - kresult = (*(dpriv->device))->USBDeviceClose(dpriv->device); - if (kresult) { - /* Log the fact that we had a problem closing the file, however failing a - * close isn't really an error, so return success anyway */ - usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult)); - } - } - } -} - -static int darwin_get_configuration(struct libusb_device_handle *dev_handle, int *config) { - struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev); - - *config = (int) dpriv->active_config; - - return 0; -} - -static int darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) { - struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev); - IOReturn kresult; - int i; - - /* Setting configuration will invalidate the interface, so we need - to reclaim it. First, dispose of existing interfaces, if any. */ - for (i = 0 ; i < USB_MAXINTERFACES ; i++) - if (dev_handle->claimed_interfaces & (1 << i)) - darwin_release_interface (dev_handle, i); - - kresult = (*(dpriv->device))->SetConfiguration (dpriv->device, config); - if (kresult != kIOReturnSuccess) - return darwin_to_libusb (kresult); - - /* Reclaim any interfaces. */ - for (i = 0 ; i < USB_MAXINTERFACES ; i++) - if (dev_handle->claimed_interfaces & (1 << i)) - darwin_claim_interface (dev_handle, i); - - dpriv->active_config = config; - - return 0; -} - -static int darwin_get_interface (usb_device_t **darwin_device, uint8_t ifc, io_service_t *usbInterfacep) { - IOUSBFindInterfaceRequest request; - kern_return_t kresult; - io_iterator_t interface_iterator; - UInt8 bInterfaceNumber; - int ret; - - *usbInterfacep = IO_OBJECT_NULL; - - /* Setup the Interface Request */ - request.bInterfaceClass = kIOUSBFindInterfaceDontCare; - request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare; - request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare; - request.bAlternateSetting = kIOUSBFindInterfaceDontCare; - - kresult = (*(darwin_device))->CreateInterfaceIterator(darwin_device, &request, &interface_iterator); - if (kresult) - return kresult; - - while ((*usbInterfacep = IOIteratorNext(interface_iterator))) { - /* find the interface number */ - ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type, - &bInterfaceNumber); - - if (ret && bInterfaceNumber == ifc) { - break; - } - - (void) IOObjectRelease (*usbInterfacep); - } - - /* done with the interface iterator */ - IOObjectRelease(interface_iterator); - - return 0; -} - -static int get_endpoints (struct libusb_device_handle *dev_handle, int iface) { - struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv; - - /* current interface */ - struct darwin_interface *cInterface = &priv->interfaces[iface]; - - kern_return_t kresult; - - u_int8_t numep, direction, number; - u_int8_t dont_care1, dont_care3; - u_int16_t dont_care2; - int rc; - - usbi_dbg ("building table of endpoints."); - - /* retrieve the total number of endpoints on this interface */ - kresult = (*(cInterface->interface))->GetNumEndpoints(cInterface->interface, &numep); - if (kresult) { - usbi_err (HANDLE_CTX (dev_handle), "can't get number of endpoints for interface: %s", darwin_error_str(kresult)); - return darwin_to_libusb (kresult); - } - - /* iterate through pipe references */ - for (int i = 1 ; i <= numep ; i++) { - kresult = (*(cInterface->interface))->GetPipeProperties(cInterface->interface, i, &direction, &number, &dont_care1, - &dont_care2, &dont_care3); - - if (kresult != kIOReturnSuccess) { - /* probably a buggy device. try to get the endpoint address from the descriptors */ - struct libusb_config_descriptor *config; - const struct libusb_endpoint_descriptor *endpoint_desc; - UInt8 alt_setting; - - kresult = (*(cInterface->interface))->GetAlternateSetting (cInterface->interface, &alt_setting); - if (kresult) { - usbi_err (HANDLE_CTX (dev_handle), "can't get alternate setting for interface"); - return darwin_to_libusb (kresult); - } - - rc = libusb_get_active_config_descriptor (dev_handle->dev, &config); - if (LIBUSB_SUCCESS != rc) { - return rc; - } - - endpoint_desc = config->interface[iface].altsetting[alt_setting].endpoint + i - 1; - - cInterface->endpoint_addrs[i - 1] = endpoint_desc->bEndpointAddress; - } else { - cInterface->endpoint_addrs[i - 1] = (((kUSBIn == direction) << kUSBRqDirnShift) | (number & LIBUSB_ENDPOINT_ADDRESS_MASK)); - } - - usbi_dbg ("interface: %i pipe %i: dir: %i number: %i", iface, i, cInterface->endpoint_addrs[i - 1] >> kUSBRqDirnShift, - cInterface->endpoint_addrs[i - 1] & LIBUSB_ENDPOINT_ADDRESS_MASK); - } - - cInterface->num_endpoints = numep; - - return 0; -} - -static int darwin_claim_interface(struct libusb_device_handle *dev_handle, int iface) { - struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev); - struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv; - io_service_t usbInterface = IO_OBJECT_NULL; - IOReturn kresult; - IOCFPlugInInterface **plugInInterface = NULL; - SInt32 score; - - /* current interface */ - struct darwin_interface *cInterface = &priv->interfaces[iface]; - - kresult = darwin_get_interface (dpriv->device, iface, &usbInterface); - if (kresult != kIOReturnSuccess) - return darwin_to_libusb (kresult); - - /* make sure we have an interface */ - if (!usbInterface && dpriv->first_config != 0) { - usbi_info (HANDLE_CTX (dev_handle), "no interface found; setting configuration: %d", dpriv->first_config); - - /* set the configuration */ - kresult = darwin_set_configuration (dev_handle, dpriv->first_config); - if (kresult != LIBUSB_SUCCESS) { - usbi_err (HANDLE_CTX (dev_handle), "could not set configuration"); - return kresult; - } - - kresult = darwin_get_interface (dpriv->device, iface, &usbInterface); - if (kresult) { - usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult)); - return darwin_to_libusb (kresult); - } - } - - if (!usbInterface) { - usbi_err (HANDLE_CTX (dev_handle), "interface not found"); - return LIBUSB_ERROR_NOT_FOUND; - } - - /* get an interface to the device's interface */ - kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID, - kIOCFPlugInInterfaceID, &plugInInterface, &score); - - /* ignore release error */ - (void)IOObjectRelease (usbInterface); - - if (kresult) { - usbi_err (HANDLE_CTX (dev_handle), "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult)); - return darwin_to_libusb (kresult); - } - - if (!plugInInterface) { - usbi_err (HANDLE_CTX (dev_handle), "plugin interface not found"); - return LIBUSB_ERROR_NOT_FOUND; - } - - /* Do the actual claim */ - kresult = (*plugInInterface)->QueryInterface(plugInInterface, - CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID), - (LPVOID)&cInterface->interface); - /* We no longer need the intermediate plug-in */ - /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */ - (*plugInInterface)->Release (plugInInterface); - if (kresult || !cInterface->interface) { - usbi_err (HANDLE_CTX (dev_handle), "QueryInterface: %s", darwin_error_str(kresult)); - return darwin_to_libusb (kresult); - } - - /* claim the interface */ - kresult = (*(cInterface->interface))->USBInterfaceOpen(cInterface->interface); - if (kresult) { - usbi_err (HANDLE_CTX (dev_handle), "USBInterfaceOpen: %s", darwin_error_str(kresult)); - return darwin_to_libusb (kresult); - } - - /* update list of endpoints */ - kresult = get_endpoints (dev_handle, iface); - if (kresult) { - /* this should not happen */ - darwin_release_interface (dev_handle, iface); - usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table"); - return kresult; - } - - cInterface->cfSource = NULL; - - /* create async event source */ - kresult = (*(cInterface->interface))->CreateInterfaceAsyncEventSource (cInterface->interface, &cInterface->cfSource); - if (kresult != kIOReturnSuccess) { - usbi_err (HANDLE_CTX (dev_handle), "could not create async event source"); - - /* can't continue without an async event source */ - (void)darwin_release_interface (dev_handle, iface); - - return darwin_to_libusb (kresult); - } - - /* add the cfSource to the async thread's run loop */ - CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode); - - usbi_dbg ("interface opened"); - - return 0; -} - -static int darwin_release_interface(struct libusb_device_handle *dev_handle, int iface) { - struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv; - IOReturn kresult; - - /* current interface */ - struct darwin_interface *cInterface = &priv->interfaces[iface]; - - /* Check to see if an interface is open */ - if (!cInterface->interface) - return LIBUSB_SUCCESS; - - /* clean up endpoint data */ - cInterface->num_endpoints = 0; - - /* delete the interface's async event source */ - if (cInterface->cfSource) { - CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode); - CFRelease (cInterface->cfSource); - } - - kresult = (*(cInterface->interface))->USBInterfaceClose(cInterface->interface); - if (kresult) - usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult)); - - kresult = (*(cInterface->interface))->Release(cInterface->interface); - if (kresult != kIOReturnSuccess) - usbi_warn (HANDLE_CTX (dev_handle), "Release: %s", darwin_error_str(kresult)); - - cInterface->interface = (usb_interface_t **) IO_OBJECT_NULL; - - return darwin_to_libusb (kresult); -} - -static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) { - struct darwin_device_handle_priv *priv = (struct darwin_device_handle_priv *)dev_handle->os_priv; - IOReturn kresult; - - /* current interface */ - struct darwin_interface *cInterface = &priv->interfaces[iface]; - - if (!cInterface->interface) - return LIBUSB_ERROR_NO_DEVICE; - - kresult = (*(cInterface->interface))->SetAlternateInterface (cInterface->interface, altsetting); - if (kresult != kIOReturnSuccess) - darwin_reset_device (dev_handle); - - /* update list of endpoints */ - kresult = get_endpoints (dev_handle, iface); - if (kresult) { - /* this should not happen */ - darwin_release_interface (dev_handle, iface); - usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table"); - return kresult; - } - - return darwin_to_libusb (kresult); -} - -static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) { - /* current interface */ - struct darwin_interface *cInterface; - IOReturn kresult; - uint8_t pipeRef; - - /* determine the interface/endpoint to use */ - if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) { - usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface"); - - return LIBUSB_ERROR_NOT_FOUND; - } - - /* newer versions of darwin support clearing additional bits on the device's endpoint */ - kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef); - if (kresult) - usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult)); - - return darwin_to_libusb (kresult); -} - -static int darwin_reset_device(struct libusb_device_handle *dev_handle) { - struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev); - IOUSBDeviceDescriptor descriptor; - IOUSBConfigurationDescriptorPtr cached_configuration; - IOUSBConfigurationDescriptor configuration; - bool reenumerate = false; - IOReturn kresult; - int i; - - kresult = (*(dpriv->device))->ResetDevice (dpriv->device); - if (kresult) { - usbi_err (HANDLE_CTX (dev_handle), "ResetDevice: %s", darwin_error_str (kresult)); - return darwin_to_libusb (kresult); - } - - do { - usbi_dbg ("darwin/reset_device: checking if device descriptor changed"); - - /* ignore return code. if we can't get a descriptor it might be worthwhile re-enumerating anway */ - (void) darwin_request_descriptor (dpriv->device, kUSBDeviceDesc, 0, &descriptor, sizeof (descriptor)); - - /* check if the device descriptor has changed */ - if (0 != memcmp (&dpriv->dev_descriptor, &descriptor, sizeof (descriptor))) { - reenumerate = true; - break; - } - - /* check if any configuration descriptor has changed */ - for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) { - usbi_dbg ("darwin/reset_device: checking if configuration descriptor %d changed", i); - - (void) darwin_request_descriptor (dpriv->device, kUSBConfDesc, i, &configuration, sizeof (configuration)); - (*(dpriv->device))->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration); - - if (!cached_configuration || 0 != memcmp (cached_configuration, &configuration, sizeof (configuration))) { - reenumerate = true; - break; - } - } - } while (0); - - if (reenumerate) { - usbi_dbg ("darwin/reset_device: device requires reenumeration"); - (void) (*(dpriv->device))->USBDeviceReEnumerate (dpriv->device, 0); - return LIBUSB_ERROR_NOT_FOUND; - } - - usbi_dbg ("darwin/reset_device: device reset complete"); - - return LIBUSB_SUCCESS; -} - -static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, int interface) { - struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev); - io_service_t usbInterface; - CFTypeRef driver; - IOReturn kresult; - - kresult = darwin_get_interface (dpriv->device, interface, &usbInterface); - if (kresult) { - usbi_err (HANDLE_CTX (dev_handle), "darwin_get_interface: %s", darwin_error_str(kresult)); - - return darwin_to_libusb (kresult); - } - - driver = IORegistryEntryCreateCFProperty (usbInterface, kIOBundleIdentifierKey, kCFAllocatorDefault, 0); - IOObjectRelease (usbInterface); - - if (driver) { - CFRelease (driver); - - return 1; - } - - /* no driver */ - return 0; -} - -/* attaching/detaching kernel drivers is not currently supported (maybe in the future?) */ -static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) { - UNUSED(dev_handle); - UNUSED(interface); - return LIBUSB_ERROR_NOT_SUPPORTED; -} - -static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, int interface) { - UNUSED(dev_handle); - UNUSED(interface); - return LIBUSB_ERROR_NOT_SUPPORTED; -} - -static void darwin_destroy_device(struct libusb_device *dev) { - struct darwin_device_priv *dpriv = (struct darwin_device_priv *) dev->os_priv; - - if (dpriv->dev) { - /* need to hold the lock in case this is the last reference to the device */ - usbi_mutex_lock(&darwin_cached_devices_lock); - darwin_deref_cached_device (dpriv->dev); - dpriv->dev = NULL; - usbi_mutex_unlock(&darwin_cached_devices_lock); - } -} - -static int submit_bulk_transfer(struct usbi_transfer *itransfer) { - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - - IOReturn ret; - uint8_t transferType; - /* None of the values below are used in libusbx for bulk transfers */ - uint8_t direction, number, interval, pipeRef; - uint16_t maxPacketSize; - - struct darwin_interface *cInterface; - - if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) { - usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface"); - - return LIBUSB_ERROR_NOT_FOUND; - } - - ret = (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number, - &transferType, &maxPacketSize, &interval); - - if (ret) { - usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out", - darwin_error_str(ret), ret); - return darwin_to_libusb (ret); - } - - if (0 != (transfer->length % maxPacketSize)) { - /* do not need a zero packet */ - transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET; - } - - /* submit the request */ - /* timeouts are unavailable on interrupt endpoints */ - if (transferType == kUSBInterrupt) { - if (IS_XFERIN(transfer)) - ret = (*(cInterface->interface))->ReadPipeAsync(cInterface->interface, pipeRef, transfer->buffer, - transfer->length, darwin_async_io_callback, itransfer); - else - ret = (*(cInterface->interface))->WritePipeAsync(cInterface->interface, pipeRef, transfer->buffer, - transfer->length, darwin_async_io_callback, itransfer); - } else { - itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT; - - if (IS_XFERIN(transfer)) - ret = (*(cInterface->interface))->ReadPipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer, - transfer->length, transfer->timeout, transfer->timeout, - darwin_async_io_callback, (void *)itransfer); - else - ret = (*(cInterface->interface))->WritePipeAsyncTO(cInterface->interface, pipeRef, transfer->buffer, - transfer->length, transfer->timeout, transfer->timeout, - darwin_async_io_callback, (void *)itransfer); - } - - if (ret) - usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out", - darwin_error_str(ret), ret); - - return darwin_to_libusb (ret); -} - -#if InterfaceVersion >= 550 -static int submit_stream_transfer(struct usbi_transfer *itransfer) { - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct darwin_interface *cInterface; - uint8_t pipeRef; - IOReturn ret; - - if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) { - usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface"); - - return LIBUSB_ERROR_NOT_FOUND; - } - - itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT; - - if (IS_XFERIN(transfer)) - ret = (*(cInterface->interface))->ReadStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id, - transfer->buffer, transfer->length, transfer->timeout, - transfer->timeout, darwin_async_io_callback, (void *)itransfer); - else - ret = (*(cInterface->interface))->WriteStreamsPipeAsyncTO(cInterface->interface, pipeRef, itransfer->stream_id, - transfer->buffer, transfer->length, transfer->timeout, - transfer->timeout, darwin_async_io_callback, (void *)itransfer); - - if (ret) - usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out", - darwin_error_str(ret), ret); - - return darwin_to_libusb (ret); -} -#endif - -static int submit_iso_transfer(struct usbi_transfer *itransfer) { - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer); - - IOReturn kresult; - uint8_t direction, number, interval, pipeRef, transferType; - uint16_t maxPacketSize; - UInt64 frame; - AbsoluteTime atTime; - int i; - - struct darwin_interface *cInterface; - - /* construct an array of IOUSBIsocFrames, reuse the old one if possible */ - if (tpriv->isoc_framelist && tpriv->num_iso_packets != transfer->num_iso_packets) { - free(tpriv->isoc_framelist); - tpriv->isoc_framelist = NULL; - } - - if (!tpriv->isoc_framelist) { - tpriv->num_iso_packets = transfer->num_iso_packets; - tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc (transfer->num_iso_packets, sizeof(IOUSBIsocFrame)); - if (!tpriv->isoc_framelist) - return LIBUSB_ERROR_NO_MEM; - } - - /* copy the frame list from the libusb descriptor (the structures differ only is member order) */ - for (i = 0 ; i < transfer->num_iso_packets ; i++) - tpriv->isoc_framelist[i].frReqCount = transfer->iso_packet_desc[i].length; - - /* determine the interface/endpoint to use */ - if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) { - usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface"); - - return LIBUSB_ERROR_NOT_FOUND; - } - - /* determine the properties of this endpoint and the speed of the device */ - (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number, - &transferType, &maxPacketSize, &interval); - - /* Last but not least we need the bus frame number */ - kresult = (*(cInterface->interface))->GetBusFrameNumber(cInterface->interface, &frame, &atTime); - if (kresult) { - usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult); - free(tpriv->isoc_framelist); - tpriv->isoc_framelist = NULL; - - return darwin_to_libusb (kresult); - } - - (*(cInterface->interface))->GetPipeProperties (cInterface->interface, pipeRef, &direction, &number, - &transferType, &maxPacketSize, &interval); - - /* schedule for a frame a little in the future */ - frame += 4; - - if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint]) - frame = cInterface->frames[transfer->endpoint]; - - /* submit the request */ - if (IS_XFERIN(transfer)) - kresult = (*(cInterface->interface))->ReadIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame, - transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback, - itransfer); - else - kresult = (*(cInterface->interface))->WriteIsochPipeAsync(cInterface->interface, pipeRef, transfer->buffer, frame, - transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback, - itransfer); - - if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed) - /* Full speed */ - cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1)); - else - /* High/super speed */ - cInterface->frames[transfer->endpoint] = frame + transfer->num_iso_packets * (1 << (interval - 1)) / 8; - - if (kresult != kIOReturnSuccess) { - usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out", - darwin_error_str(kresult)); - free (tpriv->isoc_framelist); - tpriv->isoc_framelist = NULL; - } - - return darwin_to_libusb (kresult); -} - -static int submit_control_transfer(struct usbi_transfer *itransfer) { - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer; - struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev); - struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer); - - IOReturn kresult; - - memset(&tpriv->req, 0, sizeof(tpriv->req)); - - /* IOUSBDeviceInterface expects the request in cpu endianness */ - tpriv->req.bmRequestType = setup->bmRequestType; - tpriv->req.bRequest = setup->bRequest; - /* these values should be in bus order from libusb_fill_control_setup */ - tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue); - tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex); - tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength); - /* data is stored after the libusb control block */ - tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE; - tpriv->req.completionTimeout = transfer->timeout; - tpriv->req.noDataTimeout = transfer->timeout; - - itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT; - - /* all transfers in libusb-1.0 are async */ - - if (transfer->endpoint) { - struct darwin_interface *cInterface; - uint8_t pipeRef; - - if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) { - usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface"); - - return LIBUSB_ERROR_NOT_FOUND; - } - - kresult = (*(cInterface->interface))->ControlRequestAsyncTO (cInterface->interface, pipeRef, &(tpriv->req), darwin_async_io_callback, itransfer); - } else - /* control request on endpoint 0 */ - kresult = (*(dpriv->device))->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer); - - if (kresult != kIOReturnSuccess) - usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult)); - - return darwin_to_libusb (kresult); -} - -static int darwin_submit_transfer(struct usbi_transfer *itransfer) { - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - - switch (transfer->type) { - case LIBUSB_TRANSFER_TYPE_CONTROL: - return submit_control_transfer(itransfer); - case LIBUSB_TRANSFER_TYPE_BULK: - case LIBUSB_TRANSFER_TYPE_INTERRUPT: - return submit_bulk_transfer(itransfer); - case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS: - return submit_iso_transfer(itransfer); - case LIBUSB_TRANSFER_TYPE_BULK_STREAM: -#if InterfaceVersion >= 550 - return submit_stream_transfer(itransfer); -#else - usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers"); - return LIBUSB_ERROR_NOT_SUPPORTED; -#endif - default: - usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type); - return LIBUSB_ERROR_INVALID_PARAM; - } -} - -static int cancel_control_transfer(struct usbi_transfer *itransfer) { - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev); - IOReturn kresult; - - usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe"); - - if (!dpriv->device) - return LIBUSB_ERROR_NO_DEVICE; - - kresult = (*(dpriv->device))->USBDeviceAbortPipeZero (dpriv->device); - - return darwin_to_libusb (kresult); -} - -static int darwin_abort_transfers (struct usbi_transfer *itransfer) { - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev); - struct darwin_interface *cInterface; - uint8_t pipeRef, iface; - IOReturn kresult; - - if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) { - usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface"); - - return LIBUSB_ERROR_NOT_FOUND; - } - - if (!dpriv->device) - return LIBUSB_ERROR_NO_DEVICE; - - usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions on interface %d pipe %d", iface, pipeRef); - - /* abort transactions */ -#if InterfaceVersion >= 550 - if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type) - (*(cInterface->interface))->AbortStreamsPipe (cInterface->interface, pipeRef, itransfer->stream_id); - else -#endif - (*(cInterface->interface))->AbortPipe (cInterface->interface, pipeRef); - - usbi_dbg ("calling clear pipe stall to clear the data toggle bit"); - - /* newer versions of darwin support clearing additional bits on the device's endpoint */ - kresult = (*(cInterface->interface))->ClearPipeStallBothEnds(cInterface->interface, pipeRef); - - return darwin_to_libusb (kresult); -} - -static int darwin_cancel_transfer(struct usbi_transfer *itransfer) { - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - - switch (transfer->type) { - case LIBUSB_TRANSFER_TYPE_CONTROL: - return cancel_control_transfer(itransfer); - case LIBUSB_TRANSFER_TYPE_BULK: - case LIBUSB_TRANSFER_TYPE_INTERRUPT: - case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS: - return darwin_abort_transfers (itransfer); - default: - usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type); - return LIBUSB_ERROR_INVALID_PARAM; - } -} - -static void darwin_clear_transfer_priv (struct usbi_transfer *itransfer) { - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer); - - if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && tpriv->isoc_framelist) { - free (tpriv->isoc_framelist); - tpriv->isoc_framelist = NULL; - } -} - -static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) { - struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon; - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer); - - usbi_dbg ("an async io operation has completed"); - - /* if requested write a zero packet */ - if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) { - struct darwin_interface *cInterface; - uint8_t pipeRef; - - (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface); - - (*(cInterface->interface))->WritePipe (cInterface->interface, pipeRef, transfer->buffer, 0); - } - - tpriv->result = result; - tpriv->size = (UInt32) (uintptr_t) arg0; - - /* signal the core that this transfer is complete */ - usbi_signal_transfer_completion(itransfer); -} - -static int darwin_transfer_status (struct usbi_transfer *itransfer, kern_return_t result) { - if (itransfer->timeout_flags & USBI_TRANSFER_TIMED_OUT) - result = kIOUSBTransactionTimeout; - - switch (result) { - case kIOReturnUnderrun: - case kIOReturnSuccess: - return LIBUSB_TRANSFER_COMPLETED; - case kIOReturnAborted: - return LIBUSB_TRANSFER_CANCELLED; - case kIOUSBPipeStalled: - usbi_dbg ("transfer error: pipe is stalled"); - return LIBUSB_TRANSFER_STALL; - case kIOReturnOverrun: - usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: data overrun"); - return LIBUSB_TRANSFER_OVERFLOW; - case kIOUSBTransactionTimeout: - usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: timed out"); - itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT; - return LIBUSB_TRANSFER_TIMED_OUT; - default: - usbi_warn (ITRANSFER_CTX (itransfer), "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result); - return LIBUSB_TRANSFER_ERROR; - } -} - -static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) { - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct darwin_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer); - int isIsoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type; - int isBulk = LIBUSB_TRANSFER_TYPE_BULK == transfer->type; - int isControl = LIBUSB_TRANSFER_TYPE_CONTROL == transfer->type; - int isInterrupt = LIBUSB_TRANSFER_TYPE_INTERRUPT == transfer->type; - int i; - - if (!isIsoc && !isBulk && !isControl && !isInterrupt) { - usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type); - return LIBUSB_ERROR_INVALID_PARAM; - } - - usbi_dbg ("handling %s completion with kernel status %d", - isControl ? "control" : isBulk ? "bulk" : isIsoc ? "isoc" : "interrupt", tpriv->result); - - if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result) { - if (isIsoc && tpriv->isoc_framelist) { - /* copy isochronous results back */ - - for (i = 0; i < transfer->num_iso_packets ; i++) { - struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i]; - lib_desc->status = darwin_to_libusb (tpriv->isoc_framelist[i].frStatus); - lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount; - } - } else if (!isIsoc) - itransfer->transferred += tpriv->size; - } - - /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */ - return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result)); -} - -static int darwin_clock_gettime(int clk_id, struct timespec *tp) { - mach_timespec_t sys_time; - clock_serv_t clock_ref; - - switch (clk_id) { - case USBI_CLOCK_REALTIME: - /* CLOCK_REALTIME represents time since the epoch */ - clock_ref = clock_realtime; - break; - case USBI_CLOCK_MONOTONIC: - /* use system boot time as reference for the monotonic clock */ - clock_ref = clock_monotonic; - break; - default: - return LIBUSB_ERROR_INVALID_PARAM; - } - - clock_get_time (clock_ref, &sys_time); - - tp->tv_sec = sys_time.tv_sec; - tp->tv_nsec = sys_time.tv_nsec; - - return 0; -} - -#if InterfaceVersion >= 550 -static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints, - int num_endpoints) { - struct darwin_interface *cInterface; - UInt32 supportsStreams; - uint8_t pipeRef; - int rc, i; - - /* find the mimimum number of supported streams on the endpoint list */ - for (i = 0 ; i < num_endpoints ; ++i) { - if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) { - return rc; - } - - (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams); - if (num_streams > supportsStreams) - num_streams = supportsStreams; - } - - /* it is an error if any endpoint in endpoints does not support streams */ - if (0 == num_streams) - return LIBUSB_ERROR_INVALID_PARAM; - - /* create the streams */ - for (i = 0 ; i < num_endpoints ; ++i) { - (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface); - - rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, num_streams); - if (kIOReturnSuccess != rc) - return darwin_to_libusb(rc); - } - - return num_streams; -} - -static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) { - struct darwin_interface *cInterface; - UInt32 supportsStreams; - uint8_t pipeRef; - int rc; - - for (int i = 0 ; i < num_endpoints ; ++i) { - if (0 != (rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface))) - return rc; - - (*(cInterface->interface))->SupportsStreams (cInterface->interface, pipeRef, &supportsStreams); - if (0 == supportsStreams) - return LIBUSB_ERROR_INVALID_PARAM; - - rc = (*(cInterface->interface))->CreateStreams (cInterface->interface, pipeRef, 0); - if (kIOReturnSuccess != rc) - return darwin_to_libusb(rc); - } - - return LIBUSB_SUCCESS; -} -#endif - -const struct usbi_os_backend darwin_backend = { - .name = "Darwin", - .caps = 0, - .init = darwin_init, - .exit = darwin_exit, - .get_device_list = NULL, /* not needed */ - .get_device_descriptor = darwin_get_device_descriptor, - .get_active_config_descriptor = darwin_get_active_config_descriptor, - .get_config_descriptor = darwin_get_config_descriptor, - .hotplug_poll = darwin_hotplug_poll, - - .open = darwin_open, - .close = darwin_close, - .get_configuration = darwin_get_configuration, - .set_configuration = darwin_set_configuration, - .claim_interface = darwin_claim_interface, - .release_interface = darwin_release_interface, - - .set_interface_altsetting = darwin_set_interface_altsetting, - .clear_halt = darwin_clear_halt, - .reset_device = darwin_reset_device, - -#if InterfaceVersion >= 550 - .alloc_streams = darwin_alloc_streams, - .free_streams = darwin_free_streams, -#endif - - .kernel_driver_active = darwin_kernel_driver_active, - .detach_kernel_driver = darwin_detach_kernel_driver, - .attach_kernel_driver = darwin_attach_kernel_driver, - - .destroy_device = darwin_destroy_device, - - .submit_transfer = darwin_submit_transfer, - .cancel_transfer = darwin_cancel_transfer, - .clear_transfer_priv = darwin_clear_transfer_priv, - - .handle_transfer_completion = darwin_handle_transfer_completion, - - .clock_gettime = darwin_clock_gettime, - - .device_priv_size = sizeof(struct darwin_device_priv), - .device_handle_priv_size = sizeof(struct darwin_device_handle_priv), - .transfer_priv_size = sizeof(struct darwin_transfer_priv), -}; diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/darwin_usb.h b/vendor/github.com/karalabe/hid/libusb/libusb/os/darwin_usb.h deleted file mode 100644 index 11804342..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/darwin_usb.h +++ /dev/null @@ -1,164 +0,0 @@ -/* - * darwin backend for libusb 1.0 - * Copyright © 2008-2015 Nathan Hjelm - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#if !defined(LIBUSB_DARWIN_H) -#define LIBUSB_DARWIN_H - -#include "libusbi.h" - -#include -#include -#include -#include - -/* IOUSBInterfaceInferface */ -#if defined (kIOUSBInterfaceInterfaceID700) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_9 - -#define usb_interface_t IOUSBInterfaceInterface700 -#define InterfaceInterfaceID kIOUSBInterfaceInterfaceID700 -#define InterfaceVersion 700 - -#elif defined (kIOUSBInterfaceInterfaceID550) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_9 - -#define usb_interface_t IOUSBInterfaceInterface550 -#define InterfaceInterfaceID kIOUSBInterfaceInterfaceID550 -#define InterfaceVersion 550 - -#elif defined (kIOUSBInterfaceInterfaceID500) - -#define usb_interface_t IOUSBInterfaceInterface500 -#define InterfaceInterfaceID kIOUSBInterfaceInterfaceID500 -#define InterfaceVersion 500 - -#elif defined (kIOUSBInterfaceInterfaceID300) - -#define usb_interface_t IOUSBInterfaceInterface300 -#define InterfaceInterfaceID kIOUSBInterfaceInterfaceID300 -#define InterfaceVersion 300 - -#elif defined (kIOUSBInterfaceInterfaceID245) - -#define usb_interface_t IOUSBInterfaceInterface245 -#define InterfaceInterfaceID kIOUSBInterfaceInterfaceID245 -#define InterfaceVersion 245 - -#elif defined (kIOUSBInterfaceInterfaceID220) - -#define usb_interface_t IOUSBInterfaceInterface220 -#define InterfaceInterfaceID kIOUSBInterfaceInterfaceID220 -#define InterfaceVersion 220 - -#else - -#error "IOUSBFamily is too old. Please upgrade your OS" - -#endif - -/* IOUSBDeviceInterface */ -#if defined (kIOUSBDeviceInterfaceID500) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_9 - -#define usb_device_t IOUSBDeviceInterface500 -#define DeviceInterfaceID kIOUSBDeviceInterfaceID500 -#define DeviceVersion 500 - -#elif defined (kIOUSBDeviceInterfaceID320) - -#define usb_device_t IOUSBDeviceInterface320 -#define DeviceInterfaceID kIOUSBDeviceInterfaceID320 -#define DeviceVersion 320 - -#elif defined (kIOUSBDeviceInterfaceID300) - -#define usb_device_t IOUSBDeviceInterface300 -#define DeviceInterfaceID kIOUSBDeviceInterfaceID300 -#define DeviceVersion 300 - -#elif defined (kIOUSBDeviceInterfaceID245) - -#define usb_device_t IOUSBDeviceInterface245 -#define DeviceInterfaceID kIOUSBDeviceInterfaceID245 -#define DeviceVersion 245 - -#elif defined (kIOUSBDeviceInterfaceID220) -#define usb_device_t IOUSBDeviceInterface197 -#define DeviceInterfaceID kIOUSBDeviceInterfaceID197 -#define DeviceVersion 197 - -#else - -#error "IOUSBFamily is too old. Please upgrade your OS" - -#endif - -#if !defined(IO_OBJECT_NULL) -#define IO_OBJECT_NULL ((io_object_t) 0) -#endif - -typedef IOCFPlugInInterface *io_cf_plugin_ref_t; -typedef IONotificationPortRef io_notification_port_t; - -/* private structures */ -struct darwin_cached_device { - struct list_head list; - IOUSBDeviceDescriptor dev_descriptor; - UInt32 location; - UInt64 parent_session; - UInt64 session; - UInt16 address; - char sys_path[21]; - usb_device_t **device; - int open_count; - UInt8 first_config, active_config, port; - int can_enumerate; - int refcount; -}; - -struct darwin_device_priv { - struct darwin_cached_device *dev; -}; - -struct darwin_device_handle_priv { - int is_open; - CFRunLoopSourceRef cfSource; - - struct darwin_interface { - usb_interface_t **interface; - uint8_t num_endpoints; - CFRunLoopSourceRef cfSource; - uint64_t frames[256]; - uint8_t endpoint_addrs[USB_MAXENDPOINTS]; - } interfaces[USB_MAXINTERFACES]; -}; - -struct darwin_transfer_priv { - /* Isoc */ - IOUSBIsocFrame *isoc_framelist; - int num_iso_packets; - - /* Control */ - IOUSBDevRequestTO req; - - /* Bulk */ - - /* Completion status */ - IOReturn result; - UInt32 size; -}; - -#endif diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/haiku_pollfs.cpp b/vendor/github.com/karalabe/hid/libusb/libusb/os/haiku_pollfs.cpp deleted file mode 100644 index e0c77132..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/haiku_pollfs.cpp +++ /dev/null @@ -1,367 +0,0 @@ -/* - * Copyright 2007-2008, Haiku Inc. All rights reserved. - * Distributed under the terms of the MIT License. - * - * Authors: - * Michael Lotz - */ - -#include "haiku_usb.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include - -class WatchedEntry { -public: - WatchedEntry(BMessenger *, entry_ref *); - ~WatchedEntry(); - bool EntryCreated(entry_ref *ref); - bool EntryRemoved(ino_t node); - bool InitCheck(); - -private: - BMessenger* fMessenger; - node_ref fNode; - bool fIsDirectory; - USBDevice* fDevice; - WatchedEntry* fEntries; - WatchedEntry* fLink; - bool fInitCheck; -}; - - -class RosterLooper : public BLooper { -public: - RosterLooper(USBRoster *); - void Stop(); - virtual void MessageReceived(BMessage *); - bool InitCheck(); - -private: - USBRoster* fRoster; - WatchedEntry* fRoot; - BMessenger* fMessenger; - bool fInitCheck; -}; - - -WatchedEntry::WatchedEntry(BMessenger *messenger, entry_ref *ref) - : fMessenger(messenger), - fIsDirectory(false), - fDevice(NULL), - fEntries(NULL), - fLink(NULL), - fInitCheck(false) -{ - BEntry entry(ref); - entry.GetNodeRef(&fNode); - - BDirectory directory; - if (entry.IsDirectory() && directory.SetTo(ref) >= B_OK) { - fIsDirectory = true; - - while (directory.GetNextEntry(&entry) >= B_OK) { - if (entry.GetRef(ref) < B_OK) - continue; - - WatchedEntry *child = new(std::nothrow) WatchedEntry(fMessenger, ref); - if (child == NULL) - continue; - if (child->InitCheck() == false) { - delete child; - continue; - } - - child->fLink = fEntries; - fEntries = child; - } - - watch_node(&fNode, B_WATCH_DIRECTORY, *fMessenger); - } - else { - if (strncmp(ref->name, "raw", 3) == 0) - return; - - BPath path, parent_path; - entry.GetPath(&path); - fDevice = new(std::nothrow) USBDevice(path.Path()); - if (fDevice != NULL && fDevice->InitCheck() == true) { - // Add this new device to each active context's device list - struct libusb_context *ctx; - unsigned long session_id = (unsigned long)&fDevice; - - usbi_mutex_lock(&active_contexts_lock); - list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) { - struct libusb_device *dev = usbi_get_device_by_session_id(ctx, session_id); - if (dev) { - usbi_dbg("using previously allocated device with location %lu", session_id); - libusb_unref_device(dev); - continue; - } - usbi_dbg("allocating new device with location %lu", session_id); - dev = usbi_alloc_device(ctx, session_id); - if (!dev) { - usbi_dbg("device allocation failed"); - continue; - } - *((USBDevice **)dev->os_priv) = fDevice; - - // Calculate pseudo-device-address - int addr, tmp; - if (strcmp(path.Leaf(), "hub") == 0) - tmp = 100; //Random Number - else - sscanf(path.Leaf(), "%d", &tmp); - addr = tmp + 1; - path.GetParent(&parent_path); - while (strcmp(parent_path.Leaf(), "usb") != 0) { - sscanf(parent_path.Leaf(), "%d", &tmp); - addr += tmp + 1; - parent_path.GetParent(&parent_path); - } - sscanf(path.Path(), "/dev/bus/usb/%d", &dev->bus_number); - dev->device_address = addr - (dev->bus_number + 1); - - if (usbi_sanitize_device(dev) < 0) { - usbi_dbg("device sanitization failed"); - libusb_unref_device(dev); - continue; - } - usbi_connect_device(dev); - } - usbi_mutex_unlock(&active_contexts_lock); - } - else if (fDevice) { - delete fDevice; - fDevice = NULL; - return; - } - } - fInitCheck = true; -} - - -WatchedEntry::~WatchedEntry() -{ - if (fIsDirectory) { - watch_node(&fNode, B_STOP_WATCHING, *fMessenger); - - WatchedEntry *child = fEntries; - while (child) { - WatchedEntry *next = child->fLink; - delete child; - child = next; - } - } - - if (fDevice) { - // Remove this device from each active context's device list - struct libusb_context *ctx; - struct libusb_device *dev; - unsigned long session_id = (unsigned long)&fDevice; - - usbi_mutex_lock(&active_contexts_lock); - list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) { - dev = usbi_get_device_by_session_id(ctx, session_id); - if (dev != NULL) { - usbi_disconnect_device(dev); - libusb_unref_device(dev); - } else { - usbi_dbg("device with location %lu not found", session_id); - } - } - usbi_mutex_static_unlock(&active_contexts_lock); - delete fDevice; - } -} - - -bool -WatchedEntry::EntryCreated(entry_ref *ref) -{ - if (!fIsDirectory) - return false; - - if (ref->directory != fNode.node) { - WatchedEntry *child = fEntries; - while (child) { - if (child->EntryCreated(ref)) - return true; - child = child->fLink; - } - return false; - } - - WatchedEntry *child = new(std::nothrow) WatchedEntry(fMessenger, ref); - if (child == NULL) - return false; - child->fLink = fEntries; - fEntries = child; - return true; -} - - -bool -WatchedEntry::EntryRemoved(ino_t node) -{ - if (!fIsDirectory) - return false; - - WatchedEntry *child = fEntries; - WatchedEntry *lastChild = NULL; - while (child) { - if (child->fNode.node == node) { - if (lastChild) - lastChild->fLink = child->fLink; - else - fEntries = child->fLink; - delete child; - return true; - } - - if (child->EntryRemoved(node)) - return true; - - lastChild = child; - child = child->fLink; - } - return false; -} - - -bool -WatchedEntry::InitCheck() -{ - return fInitCheck; -} - - -RosterLooper::RosterLooper(USBRoster *roster) - : BLooper("LibusbRoster Looper"), - fRoster(roster), - fRoot(NULL), - fMessenger(NULL), - fInitCheck(false) -{ - BEntry entry("/dev/bus/usb"); - if (!entry.Exists()) { - usbi_err(NULL, "usb_raw not published"); - return; - } - - Run(); - fMessenger = new(std::nothrow) BMessenger(this); - if (fMessenger == NULL) { - usbi_err(NULL, "error creating BMessenger object"); - return; - } - - if (Lock()) { - entry_ref ref; - entry.GetRef(&ref); - fRoot = new(std::nothrow) WatchedEntry(fMessenger, &ref); - Unlock(); - if (fRoot == NULL) - return; - if (fRoot->InitCheck() == false) { - delete fRoot; - fRoot = NULL; - return; - } - } - fInitCheck = true; -} - - -void -RosterLooper::Stop() -{ - Lock(); - delete fRoot; - delete fMessenger; - Quit(); -} - - -void -RosterLooper::MessageReceived(BMessage *message) -{ - int32 opcode; - if (message->FindInt32("opcode", &opcode) < B_OK) - return; - - switch (opcode) { - case B_ENTRY_CREATED: - { - dev_t device; - ino_t directory; - const char *name; - if (message->FindInt32("device", &device) < B_OK || - message->FindInt64("directory", &directory) < B_OK || - message->FindString("name", &name) < B_OK) - break; - - entry_ref ref(device, directory, name); - fRoot->EntryCreated(&ref); - break; - } - case B_ENTRY_REMOVED: - { - ino_t node; - if (message->FindInt64("node", &node) < B_OK) - break; - fRoot->EntryRemoved(node); - break; - } - } -} - - -bool -RosterLooper::InitCheck() -{ - return fInitCheck; -} - - -USBRoster::USBRoster() - : fLooper(NULL) -{ -} - - -USBRoster::~USBRoster() -{ - Stop(); -} - - -int -USBRoster::Start() -{ - if (fLooper == NULL) { - fLooper = new(std::nothrow) RosterLooper(this); - if (fLooper == NULL || ((RosterLooper *)fLooper)->InitCheck() == false) { - if (fLooper) - fLooper = NULL; - return LIBUSB_ERROR_OTHER; - } - } - return LIBUSB_SUCCESS; -} - - -void -USBRoster::Stop() -{ - if (fLooper) { - ((RosterLooper *)fLooper)->Stop(); - fLooper = NULL; - } -} diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/haiku_usb.h b/vendor/github.com/karalabe/hid/libusb/libusb/os/haiku_usb.h deleted file mode 100644 index d51ae9ea..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/haiku_usb.h +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Haiku Backend for libusb - * Copyright © 2014 Akshay Jaggi - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include -#include -#include -#include -#include -#include "libusbi.h" -#include "haiku_usb_raw.h" - -using namespace std; - -class USBDevice; -class USBDeviceHandle; -class USBTransfer; - -class USBDevice { -public: - USBDevice(const char *); - virtual ~USBDevice(); - const char* Location() const; - uint8 CountConfigurations() const; - const usb_device_descriptor* Descriptor() const; - const usb_configuration_descriptor* ConfigurationDescriptor(uint32) const; - const usb_configuration_descriptor* ActiveConfiguration() const; - uint8 EndpointToIndex(uint8) const; - uint8 EndpointToInterface(uint8) const; - int ClaimInterface(int); - int ReleaseInterface(int); - int CheckInterfacesFree(int); - int SetActiveConfiguration(int); - int ActiveConfigurationIndex() const; - bool InitCheck(); -private: - int Initialise(); - unsigned int fClaimedInterfaces; // Max Interfaces can be 32. Using a bitmask - usb_device_descriptor fDeviceDescriptor; - unsigned char** fConfigurationDescriptors; - int fActiveConfiguration; - char* fPath; - map fConfigToIndex; - map* fEndpointToIndex; - map* fEndpointToInterface; - bool fInitCheck; -}; - -class USBDeviceHandle { -public: - USBDeviceHandle(USBDevice *dev); - virtual ~USBDeviceHandle(); - int ClaimInterface(int); - int ReleaseInterface(int); - int SetConfiguration(int); - int SetAltSetting(int, int); - status_t SubmitTransfer(struct usbi_transfer *); - status_t CancelTransfer(USBTransfer *); - bool InitCheck(); -private: - int fRawFD; - static status_t TransfersThread(void *); - void TransfersWorker(); - USBDevice* fUSBDevice; - unsigned int fClaimedInterfaces; - BList fTransfers; - BLocker fTransfersLock; - sem_id fTransfersSem; - thread_id fTransfersThread; - bool fInitCheck; -}; - -class USBTransfer { -public: - USBTransfer(struct usbi_transfer *, USBDevice *); - virtual ~USBTransfer(); - void Do(int); - struct usbi_transfer* UsbiTransfer(); - void SetCancelled(); - bool IsCancelled(); -private: - struct usbi_transfer* fUsbiTransfer; - struct libusb_transfer* fLibusbTransfer; - USBDevice* fUSBDevice; - BLocker fStatusLock; - bool fCancelled; -}; - -class USBRoster { -public: - USBRoster(); - virtual ~USBRoster(); - int Start(); - void Stop(); -private: - void* fLooper; -}; diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/haiku_usb_backend.cpp b/vendor/github.com/karalabe/hid/libusb/libusb/os/haiku_usb_backend.cpp deleted file mode 100644 index d3de8cc0..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/haiku_usb_backend.cpp +++ /dev/null @@ -1,517 +0,0 @@ -/* - * Haiku Backend for libusb - * Copyright © 2014 Akshay Jaggi - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - - -#include -#include -#include -#include -#include - -#include "haiku_usb.h" - -int _errno_to_libusb(int status) -{ - return status; -} - -USBTransfer::USBTransfer(struct usbi_transfer *itransfer, USBDevice *device) -{ - fUsbiTransfer = itransfer; - fLibusbTransfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - fUSBDevice = device; - fCancelled = false; -} - -USBTransfer::~USBTransfer() -{ -} - -struct usbi_transfer * -USBTransfer::UsbiTransfer() -{ - return fUsbiTransfer; -} - -void -USBTransfer::SetCancelled() -{ - fCancelled = true; -} - -bool -USBTransfer::IsCancelled() -{ - return fCancelled; -} - -void -USBTransfer::Do(int fRawFD) -{ - switch (fLibusbTransfer->type) { - case LIBUSB_TRANSFER_TYPE_CONTROL: - { - struct libusb_control_setup *setup = (struct libusb_control_setup *)fLibusbTransfer->buffer; - usb_raw_command command; - command.control.request_type = setup->bmRequestType; - command.control.request = setup->bRequest; - command.control.value = setup->wValue; - command.control.index = setup->wIndex; - command.control.length = setup->wLength; - command.control.data = fLibusbTransfer->buffer + LIBUSB_CONTROL_SETUP_SIZE; - if (fCancelled) - break; - if (ioctl(fRawFD, B_USB_RAW_COMMAND_CONTROL_TRANSFER, &command, sizeof(command)) || - command.control.status != B_USB_RAW_STATUS_SUCCESS) { - fUsbiTransfer->transferred = -1; - usbi_err(TRANSFER_CTX(fLibusbTransfer), "failed control transfer"); - break; - } - fUsbiTransfer->transferred = command.control.length; - } - break; - case LIBUSB_TRANSFER_TYPE_BULK: - case LIBUSB_TRANSFER_TYPE_INTERRUPT: - { - usb_raw_command command; - command.transfer.interface = fUSBDevice->EndpointToInterface(fLibusbTransfer->endpoint); - command.transfer.endpoint = fUSBDevice->EndpointToIndex(fLibusbTransfer->endpoint); - command.transfer.data = fLibusbTransfer->buffer; - command.transfer.length = fLibusbTransfer->length; - if (fCancelled) - break; - if (fLibusbTransfer->type == LIBUSB_TRANSFER_TYPE_BULK) { - if (ioctl(fRawFD, B_USB_RAW_COMMAND_BULK_TRANSFER, &command, sizeof(command)) || - command.transfer.status != B_USB_RAW_STATUS_SUCCESS) { - fUsbiTransfer->transferred = -1; - usbi_err(TRANSFER_CTX(fLibusbTransfer), "failed bulk transfer"); - break; - } - } - else { - if (ioctl(fRawFD, B_USB_RAW_COMMAND_INTERRUPT_TRANSFER, &command, sizeof(command)) || - command.transfer.status != B_USB_RAW_STATUS_SUCCESS) { - fUsbiTransfer->transferred = -1; - usbi_err(TRANSFER_CTX(fLibusbTransfer), "failed interrupt transfer"); - break; - } - } - fUsbiTransfer->transferred = command.transfer.length; - } - break; - // IsochronousTransfers not tested - case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS: - { - usb_raw_command command; - command.isochronous.interface = fUSBDevice->EndpointToInterface(fLibusbTransfer->endpoint); - command.isochronous.endpoint = fUSBDevice->EndpointToIndex(fLibusbTransfer->endpoint); - command.isochronous.data = fLibusbTransfer->buffer; - command.isochronous.length = fLibusbTransfer->length; - command.isochronous.packet_count = fLibusbTransfer->num_iso_packets; - int i; - usb_iso_packet_descriptor *packetDescriptors = new usb_iso_packet_descriptor[fLibusbTransfer->num_iso_packets]; - for (i = 0; i < fLibusbTransfer->num_iso_packets; i++) { - if ((int16)(fLibusbTransfer->iso_packet_desc[i]).length != (fLibusbTransfer->iso_packet_desc[i]).length) { - fUsbiTransfer->transferred = -1; - usbi_err(TRANSFER_CTX(fLibusbTransfer), "failed isochronous transfer"); - break; - } - packetDescriptors[i].request_length = (int16)(fLibusbTransfer->iso_packet_desc[i]).length; - } - if (i < fLibusbTransfer->num_iso_packets) - break; // TODO Handle this error - command.isochronous.packet_descriptors = packetDescriptors; - if (fCancelled) - break; - if (ioctl(fRawFD, B_USB_RAW_COMMAND_ISOCHRONOUS_TRANSFER, &command, sizeof(command)) || - command.isochronous.status != B_USB_RAW_STATUS_SUCCESS) { - fUsbiTransfer->transferred = -1; - usbi_err(TRANSFER_CTX(fLibusbTransfer), "failed isochronous transfer"); - break; - } - for (i = 0; i < fLibusbTransfer->num_iso_packets; i++) { - (fLibusbTransfer->iso_packet_desc[i]).actual_length = packetDescriptors[i].actual_length; - switch (packetDescriptors[i].status) { - case B_OK: - (fLibusbTransfer->iso_packet_desc[i]).status = LIBUSB_TRANSFER_COMPLETED; - break; - default: - (fLibusbTransfer->iso_packet_desc[i]).status = LIBUSB_TRANSFER_ERROR; - break; - } - } - delete[] packetDescriptors; - // Do we put the length of transfer here, for isochronous transfers? - fUsbiTransfer->transferred = command.transfer.length; - } - break; - default: - usbi_err(TRANSFER_CTX(fLibusbTransfer), "Unknown type of transfer"); - } -} - -bool -USBDeviceHandle::InitCheck() -{ - return fInitCheck; -} - -status_t -USBDeviceHandle::TransfersThread(void *self) -{ - USBDeviceHandle *handle = (USBDeviceHandle *)self; - handle->TransfersWorker(); - return B_OK; -} - -void -USBDeviceHandle::TransfersWorker() -{ - while (true) { - status_t status = acquire_sem(fTransfersSem); - if (status == B_BAD_SEM_ID) - break; - if (status == B_INTERRUPTED) - continue; - fTransfersLock.Lock(); - USBTransfer *fPendingTransfer = (USBTransfer *) fTransfers.RemoveItem((int32)0); - fTransfersLock.Unlock(); - fPendingTransfer->Do(fRawFD); - usbi_signal_transfer_completion(fPendingTransfer->UsbiTransfer()); - } -} - -status_t -USBDeviceHandle::SubmitTransfer(struct usbi_transfer *itransfer) -{ - USBTransfer *transfer = new USBTransfer(itransfer, fUSBDevice); - *((USBTransfer **)usbi_transfer_get_os_priv(itransfer)) = transfer; - BAutolock locker(fTransfersLock); - fTransfers.AddItem(transfer); - release_sem(fTransfersSem); - return LIBUSB_SUCCESS; -} - -status_t -USBDeviceHandle::CancelTransfer(USBTransfer *transfer) -{ - transfer->SetCancelled(); - fTransfersLock.Lock(); - bool removed = fTransfers.RemoveItem(transfer); - fTransfersLock.Unlock(); - if(removed) - usbi_signal_transfer_completion(transfer->UsbiTransfer()); - return LIBUSB_SUCCESS; -} - -USBDeviceHandle::USBDeviceHandle(USBDevice *dev) - : - fTransfersThread(-1), - fUSBDevice(dev), - fClaimedInterfaces(0), - fInitCheck(false) -{ - fRawFD = open(dev->Location(), O_RDWR | O_CLOEXEC); - if (fRawFD < 0) { - usbi_err(NULL,"failed to open device"); - return; - } - fTransfersSem = create_sem(0, "Transfers Queue Sem"); - fTransfersThread = spawn_thread(TransfersThread, "Transfer Worker", B_NORMAL_PRIORITY, this); - resume_thread(fTransfersThread); - fInitCheck = true; -} - -USBDeviceHandle::~USBDeviceHandle() -{ - if (fRawFD > 0) - close(fRawFD); - for(int i = 0; i < 32; i++) { - if (fClaimedInterfaces & (1 << i)) - ReleaseInterface(i); - } - delete_sem(fTransfersSem); - if (fTransfersThread > 0) - wait_for_thread(fTransfersThread, NULL); -} - -int -USBDeviceHandle::ClaimInterface(int inumber) -{ - int status = fUSBDevice->ClaimInterface(inumber); - if (status == LIBUSB_SUCCESS) - fClaimedInterfaces |= (1 << inumber); - return status; -} - -int -USBDeviceHandle::ReleaseInterface(int inumber) -{ - fUSBDevice->ReleaseInterface(inumber); - fClaimedInterfaces &= ~(1 << inumber); - return LIBUSB_SUCCESS; -} - -int -USBDeviceHandle::SetConfiguration(int config) -{ - int config_index = fUSBDevice->CheckInterfacesFree(config); - if(config_index == LIBUSB_ERROR_BUSY || config_index == LIBUSB_ERROR_NOT_FOUND) - return config_index; - usb_raw_command command; - command.config.config_index = config_index; - if (ioctl(fRawFD, B_USB_RAW_COMMAND_SET_CONFIGURATION, &command, sizeof(command)) || - command.config.status != B_USB_RAW_STATUS_SUCCESS) { - return _errno_to_libusb(command.config.status); - } - fUSBDevice->SetActiveConfiguration(config_index); - return LIBUSB_SUCCESS; -} - -int -USBDeviceHandle::SetAltSetting(int inumber, int alt) -{ - usb_raw_command command; - command.alternate.config_index = fUSBDevice->ActiveConfigurationIndex(); - command.alternate.interface_index = inumber; - if (ioctl(fRawFD, B_USB_RAW_COMMAND_GET_ACTIVE_ALT_INTERFACE_INDEX, &command, sizeof(command)) || - command.alternate.status != B_USB_RAW_STATUS_SUCCESS) { - usbi_err(NULL, "Error retrieving active alternate interface"); - return _errno_to_libusb(command.alternate.status); - } - if (command.alternate.alternate_info == alt) { - usbi_dbg("Setting alternate interface successful"); - return LIBUSB_SUCCESS; - } - command.alternate.alternate_info = alt; - if (ioctl(fRawFD, B_USB_RAW_COMMAND_SET_ALT_INTERFACE, &command, sizeof(command)) || - command.alternate.status != B_USB_RAW_STATUS_SUCCESS) { //IF IOCTL FAILS DEVICE DISONNECTED PROBABLY - usbi_err(NULL, "Error setting alternate interface"); - return _errno_to_libusb(command.alternate.status); - } - usbi_dbg("Setting alternate interface successful"); - return LIBUSB_SUCCESS; -} - - -USBDevice::USBDevice(const char *path) - : - fPath(NULL), - fActiveConfiguration(0), //0? - fConfigurationDescriptors(NULL), - fClaimedInterfaces(0), - fEndpointToIndex(NULL), - fEndpointToInterface(NULL), - fInitCheck(false) -{ - fPath=strdup(path); - Initialise(); -} - -USBDevice::~USBDevice() -{ - free(fPath); - if (fConfigurationDescriptors) { - for(int i = 0; i < fDeviceDescriptor.num_configurations; i++) { - if (fConfigurationDescriptors[i]) - delete fConfigurationDescriptors[i]; - } - delete[] fConfigurationDescriptors; - } - if (fEndpointToIndex) - delete[] fEndpointToIndex; - if (fEndpointToInterface) - delete[] fEndpointToInterface; -} - -bool -USBDevice::InitCheck() -{ - return fInitCheck; -} - -const char * -USBDevice::Location() const -{ - return fPath; -} - -uint8 -USBDevice::CountConfigurations() const -{ - return fDeviceDescriptor.num_configurations; -} - -const usb_device_descriptor * -USBDevice::Descriptor() const -{ - return &fDeviceDescriptor; -} - -const usb_configuration_descriptor * -USBDevice::ConfigurationDescriptor(uint32 index) const -{ - if (index > CountConfigurations()) - return NULL; - return (usb_configuration_descriptor *) fConfigurationDescriptors[index]; -} - -const usb_configuration_descriptor * -USBDevice::ActiveConfiguration() const -{ - return (usb_configuration_descriptor *) fConfigurationDescriptors[fActiveConfiguration]; -} - -int -USBDevice::ActiveConfigurationIndex() const -{ - return fActiveConfiguration; -} - -int USBDevice::ClaimInterface(int interface) -{ - if (interface > ActiveConfiguration()->number_interfaces) - return LIBUSB_ERROR_NOT_FOUND; - if (fClaimedInterfaces & (1 << interface)) - return LIBUSB_ERROR_BUSY; - fClaimedInterfaces |= (1 << interface); - return LIBUSB_SUCCESS; -} - -int USBDevice::ReleaseInterface(int interface) -{ - fClaimedInterfaces &= ~(1 << interface); - return LIBUSB_SUCCESS; -} - -int -USBDevice::CheckInterfacesFree(int config) -{ - if (fConfigToIndex.count(config) == 0) - return LIBUSB_ERROR_NOT_FOUND; - if (fClaimedInterfaces == 0) - return fConfigToIndex[(uint8)config]; - return LIBUSB_ERROR_BUSY; -} - -int -USBDevice::SetActiveConfiguration(int config_index) -{ - fActiveConfiguration = config_index; - return LIBUSB_SUCCESS; -} - -uint8 -USBDevice::EndpointToIndex(uint8 address) const -{ - return fEndpointToIndex[fActiveConfiguration][address]; -} - -uint8 -USBDevice::EndpointToInterface(uint8 address) const -{ - return fEndpointToInterface[fActiveConfiguration][address]; -} - -int -USBDevice::Initialise() //Do we need more error checking, etc? How to report? -{ - int fRawFD = open(fPath, O_RDWR | O_CLOEXEC); - if (fRawFD < 0) - return B_ERROR; - usb_raw_command command; - command.device.descriptor = &fDeviceDescriptor; - if (ioctl(fRawFD, B_USB_RAW_COMMAND_GET_DEVICE_DESCRIPTOR, &command, sizeof(command)) || - command.device.status != B_USB_RAW_STATUS_SUCCESS) { - close(fRawFD); - return B_ERROR; - } - - fConfigurationDescriptors = new(std::nothrow) unsigned char *[fDeviceDescriptor.num_configurations]; - fEndpointToIndex = new(std::nothrow) map [fDeviceDescriptor.num_configurations]; - fEndpointToInterface = new(std::nothrow) map [fDeviceDescriptor.num_configurations]; - for (int i = 0; i < fDeviceDescriptor.num_configurations; i++) { - usb_configuration_descriptor tmp_config; - command.config.descriptor = &tmp_config; - command.config.config_index = i; - if (ioctl(fRawFD, B_USB_RAW_COMMAND_GET_CONFIGURATION_DESCRIPTOR, &command, sizeof(command)) || - command.config.status != B_USB_RAW_STATUS_SUCCESS) { - usbi_err(NULL, "failed retrieving configuration descriptor"); - close(fRawFD); - return B_ERROR; - } - fConfigToIndex[tmp_config.configuration_value] = i; - fConfigurationDescriptors[i] = new(std::nothrow) unsigned char[tmp_config.total_length]; - command.control.request_type = 128; - command.control.request = 6; - command.control.value = (2 << 8) | i; - command.control.index = 0; - command.control.length = tmp_config.total_length; - command.control.data = fConfigurationDescriptors[i]; - if (ioctl(fRawFD, B_USB_RAW_COMMAND_CONTROL_TRANSFER, &command, sizeof(command)) || - command.control.status!=B_USB_RAW_STATUS_SUCCESS) { - usbi_err(NULL, "failed retrieving full configuration descriptor"); - close(fRawFD); - return B_ERROR; - } - for (int j = 0; j < tmp_config.number_interfaces; j++) { - command.alternate.config_index = i; - command.alternate.interface_index = j; - if (ioctl(fRawFD, B_USB_RAW_COMMAND_GET_ALT_INTERFACE_COUNT, &command, sizeof(command)) || - command.config.status != B_USB_RAW_STATUS_SUCCESS) { - usbi_err(NULL, "failed retrieving number of alternate interfaces"); - close(fRawFD); - return B_ERROR; - } - int num_alternate = command.alternate.alternate_info; - for (int k = 0; k < num_alternate; k++) { - usb_interface_descriptor tmp_interface; - command.interface_etc.config_index = i; - command.interface_etc.interface_index = j; - command.interface_etc.alternate_index = k; - command.interface_etc.descriptor = &tmp_interface; - if (ioctl(fRawFD, B_USB_RAW_COMMAND_GET_INTERFACE_DESCRIPTOR_ETC, &command, sizeof(command)) || - command.config.status != B_USB_RAW_STATUS_SUCCESS) { - usbi_err(NULL, "failed retrieving interface descriptor"); - close(fRawFD); - return B_ERROR; - } - for (int l = 0; l < tmp_interface.num_endpoints; l++) { - usb_endpoint_descriptor tmp_endpoint; - command.endpoint_etc.config_index = i; - command.endpoint_etc.interface_index = j; - command.endpoint_etc.alternate_index = k; - command.endpoint_etc.endpoint_index = l; - command.endpoint_etc.descriptor = &tmp_endpoint; - if (ioctl(fRawFD, B_USB_RAW_COMMAND_GET_ENDPOINT_DESCRIPTOR_ETC, &command, sizeof(command)) || - command.config.status != B_USB_RAW_STATUS_SUCCESS) { - usbi_err(NULL, "failed retrieving endpoint descriptor"); - close(fRawFD); - return B_ERROR; - } - fEndpointToIndex[i][tmp_endpoint.endpoint_address] = l; - fEndpointToInterface[i][tmp_endpoint.endpoint_address] = j; - } - } - } - } - close(fRawFD); - fInitCheck = true; - return B_OK; -} diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/haiku_usb_raw.cpp b/vendor/github.com/karalabe/hid/libusb/libusb/os/haiku_usb_raw.cpp deleted file mode 100644 index 77adbd1e..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/haiku_usb_raw.cpp +++ /dev/null @@ -1,250 +0,0 @@ -/* - * Haiku Backend for libusb - * Copyright © 2014 Akshay Jaggi - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - - -#include -#include -#include -#include -#include - -#include "haiku_usb.h" - -USBRoster gUsbRoster; -int32 gInitCount = 0; - -static int -haiku_init(struct libusb_context *ctx) -{ - if (atomic_add(&gInitCount, 1) == 0) - return gUsbRoster.Start(); - return LIBUSB_SUCCESS; -} - -static void -haiku_exit(void) -{ - if (atomic_add(&gInitCount, -1) == 1) - gUsbRoster.Stop(); -} - -static int -haiku_open(struct libusb_device_handle *dev_handle) -{ - USBDevice *dev = *((USBDevice **)dev_handle->dev->os_priv); - USBDeviceHandle *handle = new(std::nothrow) USBDeviceHandle(dev); - if (handle == NULL) - return LIBUSB_ERROR_NO_MEM; - if (handle->InitCheck() == false) { - delete handle; - return LIBUSB_ERROR_NO_DEVICE; - } - *((USBDeviceHandle **)dev_handle->os_priv) = handle; - return LIBUSB_SUCCESS; -} - -static void -haiku_close(struct libusb_device_handle *dev_handle) -{ - USBDeviceHandle *handle = *((USBDeviceHandle **)dev_handle->os_priv); - if (handle == NULL) - return; - delete handle; - *((USBDeviceHandle **)dev_handle->os_priv) = NULL; -} - -static int -haiku_get_device_descriptor(struct libusb_device *device, unsigned char *buffer, int *host_endian) -{ - USBDevice *dev = *((USBDevice **)device->os_priv); - memcpy(buffer, dev->Descriptor(), DEVICE_DESC_LENGTH); - *host_endian = 0; - return LIBUSB_SUCCESS; -} - -static int -haiku_get_active_config_descriptor(struct libusb_device *device, unsigned char *buffer, size_t len, int *host_endian) -{ - USBDevice *dev = *((USBDevice **)device->os_priv); - const usb_configuration_descriptor *act_config = dev->ActiveConfiguration(); - if (len > act_config->total_length) - return LIBUSB_ERROR_OVERFLOW; - memcpy(buffer, act_config, len); - *host_endian = 0; - return LIBUSB_SUCCESS; -} - -static int -haiku_get_config_descriptor(struct libusb_device *device, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) -{ - USBDevice *dev = *((USBDevice **)device->os_priv); - const usb_configuration_descriptor *config = dev->ConfigurationDescriptor(config_index); - if (config == NULL) { - usbi_err(DEVICE_CTX(device), "failed getting configuration descriptor"); - return LIBUSB_ERROR_INVALID_PARAM; - } - if (len > config->total_length) - len = config->total_length; - memcpy(buffer, config, len); - *host_endian = 0; - return len; -} - -static int -haiku_set_configuration(struct libusb_device_handle *dev_handle, int config) -{ - USBDeviceHandle *handle= *((USBDeviceHandle **)dev_handle->os_priv); - return handle->SetConfiguration(config); -} - -static int -haiku_claim_interface(struct libusb_device_handle *dev_handle, int interface_number) -{ - USBDeviceHandle *handle = *((USBDeviceHandle **)dev_handle->os_priv); - return handle->ClaimInterface(interface_number); -} - -static int -haiku_set_altsetting(struct libusb_device_handle *dev_handle, int interface_number, int altsetting) -{ - USBDeviceHandle *handle = *((USBDeviceHandle **)dev_handle->os_priv); - return handle->SetAltSetting(interface_number, altsetting); -} - -static int -haiku_release_interface(struct libusb_device_handle *dev_handle, int interface_number) -{ - USBDeviceHandle *handle = *((USBDeviceHandle **)dev_handle->os_priv); - haiku_set_altsetting(dev_handle,interface_number, 0); - return handle->ReleaseInterface(interface_number); -} - -static int -haiku_submit_transfer(struct usbi_transfer *itransfer) -{ - struct libusb_transfer *fLibusbTransfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - USBDeviceHandle *fDeviceHandle = *((USBDeviceHandle **)fLibusbTransfer->dev_handle->os_priv); - return fDeviceHandle->SubmitTransfer(itransfer); -} - -static int -haiku_cancel_transfer(struct usbi_transfer *itransfer) -{ - struct libusb_transfer *fLibusbTransfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - USBDeviceHandle *fDeviceHandle = *((USBDeviceHandle **)fLibusbTransfer->dev_handle->os_priv); - return fDeviceHandle->CancelTransfer(*((USBTransfer **)usbi_transfer_get_os_priv(itransfer))); -} - -static void -haiku_clear_transfer_priv(struct usbi_transfer *itransfer) -{ - USBTransfer *transfer = *((USBTransfer **)usbi_transfer_get_os_priv(itransfer)); - delete transfer; - *((USBTransfer **)usbi_transfer_get_os_priv(itransfer)) = NULL; -} - -static int -haiku_handle_transfer_completion(struct usbi_transfer *itransfer) -{ - USBTransfer *transfer = *((USBTransfer **)usbi_transfer_get_os_priv(itransfer)); - - usbi_mutex_lock(&itransfer->lock); - if (transfer->IsCancelled()) { - delete transfer; - *((USBTransfer **)usbi_transfer_get_os_priv(itransfer)) = NULL; - usbi_mutex_unlock(&itransfer->lock); - if (itransfer->transferred < 0) - itransfer->transferred = 0; - return usbi_handle_transfer_cancellation(itransfer); - } - libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED; - if (itransfer->transferred < 0) { - usbi_err(ITRANSFER_CTX(itransfer), "error in transfer"); - status = LIBUSB_TRANSFER_ERROR; - itransfer->transferred = 0; - } - delete transfer; - *((USBTransfer **)usbi_transfer_get_os_priv(itransfer)) = NULL; - usbi_mutex_unlock(&itransfer->lock); - return usbi_handle_transfer_completion(itransfer, status); -} - -static int -haiku_clock_gettime(int clkid, struct timespec *tp) -{ - if (clkid == USBI_CLOCK_REALTIME) - return clock_gettime(CLOCK_REALTIME, tp); - if (clkid == USBI_CLOCK_MONOTONIC) - return clock_gettime(CLOCK_MONOTONIC, tp); - return LIBUSB_ERROR_INVALID_PARAM; -} - -const struct usbi_os_backend haiku_usb_raw_backend = { - /*.name =*/ "Haiku usbfs", - /*.caps =*/ 0, - /*.init =*/ haiku_init, - /*.exit =*/ haiku_exit, - /*.get_device_list =*/ NULL, - /*.hotplug_poll =*/ NULL, - /*.open =*/ haiku_open, - /*.close =*/ haiku_close, - /*.get_device_descriptor =*/ haiku_get_device_descriptor, - /*.get_active_config_descriptor =*/ haiku_get_active_config_descriptor, - /*.get_config_descriptor =*/ haiku_get_config_descriptor, - /*.get_config_descriptor_by_value =*/ NULL, - - - /*.get_configuration =*/ NULL, - /*.set_configuration =*/ haiku_set_configuration, - /*.claim_interface =*/ haiku_claim_interface, - /*.release_interface =*/ haiku_release_interface, - - /*.set_interface_altsetting =*/ haiku_set_altsetting, - /*.clear_halt =*/ NULL, - /*.reset_device =*/ NULL, - - /*.alloc_streams =*/ NULL, - /*.free_streams =*/ NULL, - - /*.dev_mem_alloc =*/ NULL, - /*.dev_mem_free =*/ NULL, - - /*.kernel_driver_active =*/ NULL, - /*.detach_kernel_driver =*/ NULL, - /*.attach_kernel_driver =*/ NULL, - - /*.destroy_device =*/ NULL, - - /*.submit_transfer =*/ haiku_submit_transfer, - /*.cancel_transfer =*/ haiku_cancel_transfer, - /*.clear_transfer_priv =*/ haiku_clear_transfer_priv, - - /*.handle_events =*/ NULL, - /*.handle_transfer_completion =*/ haiku_handle_transfer_completion, - - /*.clock_gettime =*/ haiku_clock_gettime, - -#ifdef USBI_TIMERFD_AVAILABLE - /*.get_timerfd_clockid =*/ NULL, -#endif - - /*.device_priv_size =*/ sizeof(USBDevice *), - /*.device_handle_priv_size =*/ sizeof(USBDeviceHandle *), - /*.transfer_priv_size =*/ sizeof(USBTransfer *), -}; diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/haiku_usb_raw.h b/vendor/github.com/karalabe/hid/libusb/libusb/os/haiku_usb_raw.h deleted file mode 100644 index 5baf53d7..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/haiku_usb_raw.h +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright 2006-2008, Haiku Inc. All rights reserved. - * Distributed under the terms of the MIT License. - */ - -#ifndef _USB_RAW_H_ -#define _USB_RAW_H_ - -#include - -#define B_USB_RAW_PROTOCOL_VERSION 0x0015 -#define B_USB_RAW_ACTIVE_ALTERNATE 0xffffffff - -typedef enum { - B_USB_RAW_COMMAND_GET_VERSION = 0x1000, - - B_USB_RAW_COMMAND_GET_DEVICE_DESCRIPTOR = 0x2000, - B_USB_RAW_COMMAND_GET_CONFIGURATION_DESCRIPTOR, - B_USB_RAW_COMMAND_GET_INTERFACE_DESCRIPTOR, - B_USB_RAW_COMMAND_GET_ENDPOINT_DESCRIPTOR, - B_USB_RAW_COMMAND_GET_STRING_DESCRIPTOR, - B_USB_RAW_COMMAND_GET_GENERIC_DESCRIPTOR, - B_USB_RAW_COMMAND_GET_ALT_INTERFACE_COUNT, - B_USB_RAW_COMMAND_GET_ACTIVE_ALT_INTERFACE_INDEX, - B_USB_RAW_COMMAND_GET_INTERFACE_DESCRIPTOR_ETC, - B_USB_RAW_COMMAND_GET_ENDPOINT_DESCRIPTOR_ETC, - B_USB_RAW_COMMAND_GET_GENERIC_DESCRIPTOR_ETC, - - B_USB_RAW_COMMAND_SET_CONFIGURATION = 0x3000, - B_USB_RAW_COMMAND_SET_FEATURE, - B_USB_RAW_COMMAND_CLEAR_FEATURE, - B_USB_RAW_COMMAND_GET_STATUS, - B_USB_RAW_COMMAND_GET_DESCRIPTOR, - B_USB_RAW_COMMAND_SET_ALT_INTERFACE, - - B_USB_RAW_COMMAND_CONTROL_TRANSFER = 0x4000, - B_USB_RAW_COMMAND_INTERRUPT_TRANSFER, - B_USB_RAW_COMMAND_BULK_TRANSFER, - B_USB_RAW_COMMAND_ISOCHRONOUS_TRANSFER -} usb_raw_command_id; - - -typedef enum { - B_USB_RAW_STATUS_SUCCESS = 0, - - B_USB_RAW_STATUS_FAILED, - B_USB_RAW_STATUS_ABORTED, - B_USB_RAW_STATUS_STALLED, - B_USB_RAW_STATUS_CRC_ERROR, - B_USB_RAW_STATUS_TIMEOUT, - - B_USB_RAW_STATUS_INVALID_CONFIGURATION, - B_USB_RAW_STATUS_INVALID_INTERFACE, - B_USB_RAW_STATUS_INVALID_ENDPOINT, - B_USB_RAW_STATUS_INVALID_STRING, - - B_USB_RAW_STATUS_NO_MEMORY -} usb_raw_command_status; - - -typedef union { - struct { - status_t status; - } version; - - struct { - status_t status; - usb_device_descriptor *descriptor; - } device; - - struct { - status_t status; - usb_configuration_descriptor *descriptor; - uint32 config_index; - } config; - - struct { - status_t status; - uint32 alternate_info; - uint32 config_index; - uint32 interface_index; - } alternate; - - struct { - status_t status; - usb_interface_descriptor *descriptor; - uint32 config_index; - uint32 interface_index; - } interface; - - struct { - status_t status; - usb_interface_descriptor *descriptor; - uint32 config_index; - uint32 interface_index; - uint32 alternate_index; - } interface_etc; - - struct { - status_t status; - usb_endpoint_descriptor *descriptor; - uint32 config_index; - uint32 interface_index; - uint32 endpoint_index; - } endpoint; - - struct { - status_t status; - usb_endpoint_descriptor *descriptor; - uint32 config_index; - uint32 interface_index; - uint32 alternate_index; - uint32 endpoint_index; - } endpoint_etc; - - struct { - status_t status; - usb_descriptor *descriptor; - uint32 config_index; - uint32 interface_index; - uint32 generic_index; - size_t length; - } generic; - - struct { - status_t status; - usb_descriptor *descriptor; - uint32 config_index; - uint32 interface_index; - uint32 alternate_index; - uint32 generic_index; - size_t length; - } generic_etc; - - struct { - status_t status; - usb_string_descriptor *descriptor; - uint32 string_index; - size_t length; - } string; - - struct { - status_t status; - uint8 type; - uint8 index; - uint16 language_id; - void *data; - size_t length; - } descriptor; - - struct { - status_t status; - uint8 request_type; - uint8 request; - uint16 value; - uint16 index; - uint16 length; - void *data; - } control; - - struct { - status_t status; - uint32 interface; - uint32 endpoint; - void *data; - size_t length; - } transfer; - - struct { - status_t status; - uint32 interface; - uint32 endpoint; - void *data; - size_t length; - usb_iso_packet_descriptor *packet_descriptors; - uint32 packet_count; - } isochronous; -} usb_raw_command; - -#endif // _USB_RAW_H_ diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/linux_netlink.c b/vendor/github.com/karalabe/hid/libusb/libusb/os/linux_netlink.c deleted file mode 100644 index 60cf3ad1..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/linux_netlink.c +++ /dev/null @@ -1,400 +0,0 @@ -/* -*- Mode: C; c-basic-offset:8 ; indent-tabs-mode:t -*- */ -/* - * Linux usbfs backend for libusb - * Copyright (C) 2007-2009 Daniel Drake - * Copyright (c) 2001 Johannes Erdfelt - * Copyright (c) 2013 Nathan Hjelm - * Copyright (c) 2016 Chris Dickens - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef HAVE_ASM_TYPES_H -#include -#endif - -#include -#include - -#include "libusbi.h" -#include "linux_usbfs.h" - -#define NL_GROUP_KERNEL 1 - -static int linux_netlink_socket = -1; -static int netlink_control_pipe[2] = { -1, -1 }; -static pthread_t libusb_linux_event_thread; - -static void *linux_netlink_event_thread_main(void *arg); - -static int set_fd_cloexec_nb(int fd) -{ - int flags; - -#if defined(FD_CLOEXEC) - flags = fcntl(fd, F_GETFD); - if (flags == -1) { - usbi_err(NULL, "failed to get netlink fd flags (%d)", errno); - return -1; - } - - if (!(flags & FD_CLOEXEC)) { - if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) { - usbi_err(NULL, "failed to set netlink fd flags (%d)", errno); - return -1; - } - } -#endif - - flags = fcntl(fd, F_GETFL); - if (flags == -1) { - usbi_err(NULL, "failed to get netlink fd status flags (%d)", errno); - return -1; - } - - if (!(flags & O_NONBLOCK)) { - if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) { - usbi_err(NULL, "failed to set netlink fd status flags (%d)", errno); - return -1; - } - } - - return 0; -} - -int linux_netlink_start_event_monitor(void) -{ - struct sockaddr_nl sa_nl = { .nl_family = AF_NETLINK, .nl_groups = NL_GROUP_KERNEL }; - int socktype = SOCK_RAW; - int opt = 1; - int ret; - -#if defined(SOCK_CLOEXEC) - socktype |= SOCK_CLOEXEC; -#endif -#if defined(SOCK_NONBLOCK) - socktype |= SOCK_NONBLOCK; -#endif - - linux_netlink_socket = socket(PF_NETLINK, socktype, NETLINK_KOBJECT_UEVENT); - if (linux_netlink_socket == -1 && errno == EINVAL) { - usbi_dbg("failed to create netlink socket of type %d, attempting SOCK_RAW", socktype); - linux_netlink_socket = socket(PF_NETLINK, SOCK_RAW, NETLINK_KOBJECT_UEVENT); - } - - if (linux_netlink_socket == -1) { - usbi_err(NULL, "failed to create netlink socket (%d)", errno); - goto err; - } - - ret = set_fd_cloexec_nb(linux_netlink_socket); - if (ret == -1) - goto err_close_socket; - - ret = bind(linux_netlink_socket, (struct sockaddr *)&sa_nl, sizeof(sa_nl)); - if (ret == -1) { - usbi_err(NULL, "failed to bind netlink socket (%d)", errno); - goto err_close_socket; - } - - ret = setsockopt(linux_netlink_socket, SOL_SOCKET, SO_PASSCRED, &opt, sizeof(opt)); - if (ret == -1) { - usbi_err(NULL, "failed to set netlink socket SO_PASSCRED option (%d)", errno); - goto err_close_socket; - } - - ret = usbi_pipe(netlink_control_pipe); - if (ret) { - usbi_err(NULL, "failed to create netlink control pipe"); - goto err_close_socket; - } - - ret = pthread_create(&libusb_linux_event_thread, NULL, linux_netlink_event_thread_main, NULL); - if (ret != 0) { - usbi_err(NULL, "failed to create netlink event thread (%d)", ret); - goto err_close_pipe; - } - - return LIBUSB_SUCCESS; - -err_close_pipe: - close(netlink_control_pipe[0]); - close(netlink_control_pipe[1]); - netlink_control_pipe[0] = -1; - netlink_control_pipe[1] = -1; -err_close_socket: - close(linux_netlink_socket); - linux_netlink_socket = -1; -err: - return LIBUSB_ERROR_OTHER; -} - -int linux_netlink_stop_event_monitor(void) -{ - char dummy = 1; - ssize_t r; - - assert(linux_netlink_socket != -1); - - /* Write some dummy data to the control pipe and - * wait for the thread to exit */ - r = usbi_write(netlink_control_pipe[1], &dummy, sizeof(dummy)); - if (r <= 0) - usbi_warn(NULL, "netlink control pipe signal failed"); - - pthread_join(libusb_linux_event_thread, NULL); - - close(linux_netlink_socket); - linux_netlink_socket = -1; - - /* close and reset control pipe */ - close(netlink_control_pipe[0]); - close(netlink_control_pipe[1]); - netlink_control_pipe[0] = -1; - netlink_control_pipe[1] = -1; - - return LIBUSB_SUCCESS; -} - -static const char *netlink_message_parse(const char *buffer, size_t len, const char *key) -{ - const char *end = buffer + len; - size_t keylen = strlen(key); - - while (buffer < end && *buffer) { - if (strncmp(buffer, key, keylen) == 0 && buffer[keylen] == '=') - return buffer + keylen + 1; - buffer += strlen(buffer) + 1; - } - - return NULL; -} - -/* parse parts of netlink message common to both libudev and the kernel */ -static int linux_netlink_parse(const char *buffer, size_t len, int *detached, - const char **sys_name, uint8_t *busnum, uint8_t *devaddr) -{ - const char *tmp, *slash; - - errno = 0; - - *sys_name = NULL; - *detached = 0; - *busnum = 0; - *devaddr = 0; - - tmp = netlink_message_parse(buffer, len, "ACTION"); - if (!tmp) { - return -1; - } else if (strcmp(tmp, "remove") == 0) { - *detached = 1; - } else if (strcmp(tmp, "add") != 0) { - usbi_dbg("unknown device action %s", tmp); - return -1; - } - - /* check that this is a usb message */ - tmp = netlink_message_parse(buffer, len, "SUBSYSTEM"); - if (!tmp || strcmp(tmp, "usb") != 0) { - /* not usb. ignore */ - return -1; - } - - /* check that this is an actual usb device */ - tmp = netlink_message_parse(buffer, len, "DEVTYPE"); - if (!tmp || strcmp(tmp, "usb_device") != 0) { - /* not usb. ignore */ - return -1; - } - - tmp = netlink_message_parse(buffer, len, "BUSNUM"); - if (tmp) { - *busnum = (uint8_t)(strtoul(tmp, NULL, 10) & 0xff); - if (errno) { - errno = 0; - return -1; - } - - tmp = netlink_message_parse(buffer, len, "DEVNUM"); - if (NULL == tmp) - return -1; - - *devaddr = (uint8_t)(strtoul(tmp, NULL, 10) & 0xff); - if (errno) { - errno = 0; - return -1; - } - } else { - /* no bus number. try "DEVICE" */ - tmp = netlink_message_parse(buffer, len, "DEVICE"); - if (!tmp) { - /* not usb. ignore */ - return -1; - } - - /* Parse a device path such as /dev/bus/usb/003/004 */ - slash = strrchr(tmp, '/'); - if (!slash) - return -1; - - *busnum = (uint8_t)(strtoul(slash - 3, NULL, 10) & 0xff); - if (errno) { - errno = 0; - return -1; - } - - *devaddr = (uint8_t)(strtoul(slash + 1, NULL, 10) & 0xff); - if (errno) { - errno = 0; - return -1; - } - - return 0; - } - - tmp = netlink_message_parse(buffer, len, "DEVPATH"); - if (!tmp) - return -1; - - slash = strrchr(tmp, '/'); - if (slash) - *sys_name = slash + 1; - - /* found a usb device */ - return 0; -} - -static int linux_netlink_read_message(void) -{ - char cred_buffer[CMSG_SPACE(sizeof(struct ucred))]; - char msg_buffer[2048]; - const char *sys_name = NULL; - uint8_t busnum, devaddr; - int detached, r; - ssize_t len; - struct cmsghdr *cmsg; - struct ucred *cred; - struct sockaddr_nl sa_nl; - struct iovec iov = { .iov_base = msg_buffer, .iov_len = sizeof(msg_buffer) }; - struct msghdr msg = { - .msg_iov = &iov, .msg_iovlen = 1, - .msg_control = cred_buffer, .msg_controllen = sizeof(cred_buffer), - .msg_name = &sa_nl, .msg_namelen = sizeof(sa_nl) - }; - - /* read netlink message */ - len = recvmsg(linux_netlink_socket, &msg, 0); - if (len == -1) { - if (errno != EAGAIN && errno != EINTR) - usbi_err(NULL, "error receiving message from netlink (%d)", errno); - return -1; - } - - if (len < 32 || (msg.msg_flags & MSG_TRUNC)) { - usbi_err(NULL, "invalid netlink message length"); - return -1; - } - - if (sa_nl.nl_groups != NL_GROUP_KERNEL || sa_nl.nl_pid != 0) { - usbi_dbg("ignoring netlink message from unknown group/PID (%u/%u)", - (unsigned int)sa_nl.nl_groups, (unsigned int)sa_nl.nl_pid); - return -1; - } - - cmsg = CMSG_FIRSTHDR(&msg); - if (!cmsg || cmsg->cmsg_type != SCM_CREDENTIALS) { - usbi_dbg("ignoring netlink message with no sender credentials"); - return -1; - } - - cred = (struct ucred *)CMSG_DATA(cmsg); - if (cred->uid != 0) { - usbi_dbg("ignoring netlink message with non-zero sender UID %u", (unsigned int)cred->uid); - return -1; - } - - r = linux_netlink_parse(msg_buffer, (size_t)len, &detached, &sys_name, &busnum, &devaddr); - if (r) - return r; - - usbi_dbg("netlink hotplug found device busnum: %hhu, devaddr: %hhu, sys_name: %s, removed: %s", - busnum, devaddr, sys_name, detached ? "yes" : "no"); - - /* signal device is available (or not) to all contexts */ - if (detached) - linux_device_disconnected(busnum, devaddr); - else - linux_hotplug_enumerate(busnum, devaddr, sys_name); - - return 0; -} - -static void *linux_netlink_event_thread_main(void *arg) -{ - char dummy; - ssize_t r; - struct pollfd fds[] = { - { .fd = netlink_control_pipe[0], - .events = POLLIN }, - { .fd = linux_netlink_socket, - .events = POLLIN }, - }; - - UNUSED(arg); - - usbi_dbg("netlink event thread entering"); - - while (poll(fds, 2, -1) >= 0) { - if (fds[0].revents & POLLIN) { - /* activity on control pipe, read the byte and exit */ - r = usbi_read(netlink_control_pipe[0], &dummy, sizeof(dummy)); - if (r <= 0) - usbi_warn(NULL, "netlink control pipe read failed"); - break; - } - if (fds[1].revents & POLLIN) { - usbi_mutex_static_lock(&linux_hotplug_lock); - linux_netlink_read_message(); - usbi_mutex_static_unlock(&linux_hotplug_lock); - } - } - - usbi_dbg("netlink event thread exiting"); - - return NULL; -} - -void linux_netlink_hotplug_poll(void) -{ - int r; - - usbi_mutex_static_lock(&linux_hotplug_lock); - do { - r = linux_netlink_read_message(); - } while (r == 0); - usbi_mutex_static_unlock(&linux_hotplug_lock); -} diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/linux_udev.c b/vendor/github.com/karalabe/hid/libusb/libusb/os/linux_udev.c deleted file mode 100644 index 61d953d8..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/linux_udev.c +++ /dev/null @@ -1,311 +0,0 @@ -/* -*- Mode: C; c-basic-offset:8 ; indent-tabs-mode:t -*- */ -/* - * Linux usbfs backend for libusb - * Copyright (C) 2007-2009 Daniel Drake - * Copyright (c) 2001 Johannes Erdfelt - * Copyright (c) 2012-2013 Nathan Hjelm - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "libusbi.h" -#include "linux_usbfs.h" - -/* udev context */ -static struct udev *udev_ctx = NULL; -static int udev_monitor_fd = -1; -static int udev_control_pipe[2] = {-1, -1}; -static struct udev_monitor *udev_monitor = NULL; -static pthread_t linux_event_thread; - -static void udev_hotplug_event(struct udev_device* udev_dev); -static void *linux_udev_event_thread_main(void *arg); - -int linux_udev_start_event_monitor(void) -{ - int r; - - assert(udev_ctx == NULL); - udev_ctx = udev_new(); - if (!udev_ctx) { - usbi_err(NULL, "could not create udev context"); - goto err; - } - - udev_monitor = udev_monitor_new_from_netlink(udev_ctx, "udev"); - if (!udev_monitor) { - usbi_err(NULL, "could not initialize udev monitor"); - goto err_free_ctx; - } - - r = udev_monitor_filter_add_match_subsystem_devtype(udev_monitor, "usb", "usb_device"); - if (r) { - usbi_err(NULL, "could not initialize udev monitor filter for \"usb\" subsystem"); - goto err_free_monitor; - } - - if (udev_monitor_enable_receiving(udev_monitor)) { - usbi_err(NULL, "failed to enable the udev monitor"); - goto err_free_monitor; - } - - udev_monitor_fd = udev_monitor_get_fd(udev_monitor); - - /* Some older versions of udev are not non-blocking by default, - * so make sure this is set */ - r = fcntl(udev_monitor_fd, F_GETFL); - if (r == -1) { - usbi_err(NULL, "getting udev monitor fd flags (%d)", errno); - goto err_free_monitor; - } - r = fcntl(udev_monitor_fd, F_SETFL, r | O_NONBLOCK); - if (r) { - usbi_err(NULL, "setting udev monitor fd flags (%d)", errno); - goto err_free_monitor; - } - - r = usbi_pipe(udev_control_pipe); - if (r) { - usbi_err(NULL, "could not create udev control pipe"); - goto err_free_monitor; - } - - r = pthread_create(&linux_event_thread, NULL, linux_udev_event_thread_main, NULL); - if (r) { - usbi_err(NULL, "creating hotplug event thread (%d)", r); - goto err_close_pipe; - } - - return LIBUSB_SUCCESS; - -err_close_pipe: - close(udev_control_pipe[0]); - close(udev_control_pipe[1]); -err_free_monitor: - udev_monitor_unref(udev_monitor); - udev_monitor = NULL; - udev_monitor_fd = -1; -err_free_ctx: - udev_unref(udev_ctx); -err: - udev_ctx = NULL; - return LIBUSB_ERROR_OTHER; -} - -int linux_udev_stop_event_monitor(void) -{ - char dummy = 1; - int r; - - assert(udev_ctx != NULL); - assert(udev_monitor != NULL); - assert(udev_monitor_fd != -1); - - /* Write some dummy data to the control pipe and - * wait for the thread to exit */ - r = usbi_write(udev_control_pipe[1], &dummy, sizeof(dummy)); - if (r <= 0) { - usbi_warn(NULL, "udev control pipe signal failed"); - } - pthread_join(linux_event_thread, NULL); - - /* Release the udev monitor */ - udev_monitor_unref(udev_monitor); - udev_monitor = NULL; - udev_monitor_fd = -1; - - /* Clean up the udev context */ - udev_unref(udev_ctx); - udev_ctx = NULL; - - /* close and reset control pipe */ - close(udev_control_pipe[0]); - close(udev_control_pipe[1]); - udev_control_pipe[0] = -1; - udev_control_pipe[1] = -1; - - return LIBUSB_SUCCESS; -} - -static void *linux_udev_event_thread_main(void *arg) -{ - char dummy; - int r; - struct udev_device* udev_dev; - struct pollfd fds[] = { - {.fd = udev_control_pipe[0], - .events = POLLIN}, - {.fd = udev_monitor_fd, - .events = POLLIN}, - }; - - usbi_dbg("udev event thread entering."); - - while ((r = poll(fds, 2, -1)) >= 0 || errno == EINTR) { - if (r < 0) { - /* temporary failure */ - continue; - } - if (fds[0].revents & POLLIN) { - /* activity on control pipe, read the byte and exit */ - r = usbi_read(udev_control_pipe[0], &dummy, sizeof(dummy)); - if (r <= 0) { - usbi_warn(NULL, "udev control pipe read failed"); - } - break; - } - if (fds[1].revents & POLLIN) { - usbi_mutex_static_lock(&linux_hotplug_lock); - udev_dev = udev_monitor_receive_device(udev_monitor); - if (udev_dev) - udev_hotplug_event(udev_dev); - usbi_mutex_static_unlock(&linux_hotplug_lock); - } - } - - usbi_dbg("udev event thread exiting"); - - return NULL; -} - -static int udev_device_info(struct libusb_context *ctx, int detached, - struct udev_device *udev_dev, uint8_t *busnum, - uint8_t *devaddr, const char **sys_name) { - const char *dev_node; - - dev_node = udev_device_get_devnode(udev_dev); - if (!dev_node) { - return LIBUSB_ERROR_OTHER; - } - - *sys_name = udev_device_get_sysname(udev_dev); - if (!*sys_name) { - return LIBUSB_ERROR_OTHER; - } - - return linux_get_device_address(ctx, detached, busnum, devaddr, - dev_node, *sys_name); -} - -static void udev_hotplug_event(struct udev_device* udev_dev) -{ - const char* udev_action; - const char* sys_name = NULL; - uint8_t busnum = 0, devaddr = 0; - int detached; - int r; - - do { - udev_action = udev_device_get_action(udev_dev); - if (!udev_action) { - break; - } - - detached = !strncmp(udev_action, "remove", 6); - - r = udev_device_info(NULL, detached, udev_dev, &busnum, &devaddr, &sys_name); - if (LIBUSB_SUCCESS != r) { - break; - } - - usbi_dbg("udev hotplug event. action: %s.", udev_action); - - if (strncmp(udev_action, "add", 3) == 0) { - linux_hotplug_enumerate(busnum, devaddr, sys_name); - } else if (detached) { - linux_device_disconnected(busnum, devaddr); - } else { - usbi_err(NULL, "ignoring udev action %s", udev_action); - } - } while (0); - - udev_device_unref(udev_dev); -} - -int linux_udev_scan_devices(struct libusb_context *ctx) -{ - struct udev_enumerate *enumerator; - struct udev_list_entry *devices, *entry; - struct udev_device *udev_dev; - const char *sys_name; - int r; - - assert(udev_ctx != NULL); - - enumerator = udev_enumerate_new(udev_ctx); - if (NULL == enumerator) { - usbi_err(ctx, "error creating udev enumerator"); - return LIBUSB_ERROR_OTHER; - } - - udev_enumerate_add_match_subsystem(enumerator, "usb"); - udev_enumerate_add_match_property(enumerator, "DEVTYPE", "usb_device"); - udev_enumerate_scan_devices(enumerator); - devices = udev_enumerate_get_list_entry(enumerator); - - udev_list_entry_foreach(entry, devices) { - const char *path = udev_list_entry_get_name(entry); - uint8_t busnum = 0, devaddr = 0; - - udev_dev = udev_device_new_from_syspath(udev_ctx, path); - - r = udev_device_info(ctx, 0, udev_dev, &busnum, &devaddr, &sys_name); - if (r) { - udev_device_unref(udev_dev); - continue; - } - - linux_enumerate_device(ctx, busnum, devaddr, sys_name); - udev_device_unref(udev_dev); - } - - udev_enumerate_unref(enumerator); - - return LIBUSB_SUCCESS; -} - -void linux_udev_hotplug_poll(void) -{ - struct udev_device* udev_dev; - - usbi_mutex_static_lock(&linux_hotplug_lock); - do { - udev_dev = udev_monitor_receive_device(udev_monitor); - if (udev_dev) { - usbi_dbg("Handling hotplug event from hotplug_poll"); - udev_hotplug_event(udev_dev); - } - } while (udev_dev); - usbi_mutex_static_unlock(&linux_hotplug_lock); -} diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/linux_usbfs.c b/vendor/github.com/karalabe/hid/libusb/libusb/os/linux_usbfs.c deleted file mode 100644 index 6b89ba28..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/linux_usbfs.c +++ /dev/null @@ -1,2738 +0,0 @@ -/* -*- Mode: C; c-basic-offset:8 ; indent-tabs-mode:t -*- */ -/* - * Linux usbfs backend for libusb - * Copyright © 2007-2009 Daniel Drake - * Copyright © 2001 Johannes Erdfelt - * Copyright © 2013 Nathan Hjelm - * Copyright © 2012-2013 Hans de Goede - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include "config.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "libusbi.h" -#include "linux_usbfs.h" - -/* sysfs vs usbfs: - * opening a usbfs node causes the device to be resumed, so we attempt to - * avoid this during enumeration. - * - * sysfs allows us to read the kernel's in-memory copies of device descriptors - * and so forth, avoiding the need to open the device: - * - The binary "descriptors" file contains all config descriptors since - * 2.6.26, commit 217a9081d8e69026186067711131b77f0ce219ed - * - The binary "descriptors" file was added in 2.6.23, commit - * 69d42a78f935d19384d1f6e4f94b65bb162b36df, but it only contains the - * active config descriptors - * - The "busnum" file was added in 2.6.22, commit - * 83f7d958eab2fbc6b159ee92bf1493924e1d0f72 - * - The "devnum" file has been present since pre-2.6.18 - * - the "bConfigurationValue" file has been present since pre-2.6.18 - * - * If we have bConfigurationValue, busnum, and devnum, then we can determine - * the active configuration without having to open the usbfs node in RDWR mode. - * The busnum file is important as that is the only way we can relate sysfs - * devices to usbfs nodes. - * - * If we also have all descriptors, we can obtain the device descriptor and - * configuration without touching usbfs at all. - */ - -/* endianness for multi-byte fields: - * - * Descriptors exposed by usbfs have the multi-byte fields in the device - * descriptor as host endian. Multi-byte fields in the other descriptors are - * bus-endian. The kernel documentation says otherwise, but it is wrong. - * - * In sysfs all descriptors are bus-endian. - */ - -static const char *usbfs_path = NULL; - -/* use usbdev*.* device names in /dev instead of the usbfs bus directories */ -static int usbdev_names = 0; - -/* Linux 2.6.32 adds support for a bulk continuation URB flag. this basically - * allows us to mark URBs as being part of a specific logical transfer when - * we submit them to the kernel. then, on any error except a cancellation, all - * URBs within that transfer will be cancelled and no more URBs will be - * accepted for the transfer, meaning that no more data can creep in. - * - * The BULK_CONTINUATION flag must be set on all URBs within a bulk transfer - * (in either direction) except the first. - * For IN transfers, we must also set SHORT_NOT_OK on all URBs except the - * last; it means that the kernel should treat a short reply as an error. - * For OUT transfers, SHORT_NOT_OK must not be set. it isn't needed (OUT - * transfers can't be short unless there's already some sort of error), and - * setting this flag is disallowed (a kernel with USB debugging enabled will - * reject such URBs). - */ -static int supports_flag_bulk_continuation = -1; - -/* Linux 2.6.31 fixes support for the zero length packet URB flag. This - * allows us to mark URBs that should be followed by a zero length data - * packet, which can be required by device- or class-specific protocols. - */ -static int supports_flag_zero_packet = -1; - -/* clock ID for monotonic clock, as not all clock sources are available on all - * systems. appropriate choice made at initialization time. */ -static clockid_t monotonic_clkid = -1; - -/* Linux 2.6.22 (commit 83f7d958eab2fbc6b159ee92bf1493924e1d0f72) adds a busnum - * to sysfs, so we can relate devices. This also implies that we can read - * the active configuration through bConfigurationValue */ -static int sysfs_can_relate_devices = -1; - -/* Linux 2.6.26 (commit 217a9081d8e69026186067711131b77f0ce219ed) adds all - * config descriptors (rather then just the active config) to the sysfs - * descriptors file, so from then on we can use them. */ -static int sysfs_has_descriptors = -1; - -/* how many times have we initted (and not exited) ? */ -static int init_count = 0; - -/* Serialize hotplug start/stop */ -static usbi_mutex_static_t linux_hotplug_startstop_lock = USBI_MUTEX_INITIALIZER; -/* Serialize scan-devices, event-thread, and poll */ -usbi_mutex_static_t linux_hotplug_lock = USBI_MUTEX_INITIALIZER; - -static int linux_start_event_monitor(void); -static int linux_stop_event_monitor(void); -static int linux_scan_devices(struct libusb_context *ctx); -static int sysfs_scan_device(struct libusb_context *ctx, const char *devname); -static int detach_kernel_driver_and_claim(struct libusb_device_handle *, int); - -#if !defined(USE_UDEV) -static int linux_default_scan_devices (struct libusb_context *ctx); -#endif - -struct linux_device_priv { - char *sysfs_dir; - unsigned char *descriptors; - int descriptors_len; - int active_config; /* cache val for !sysfs_can_relate_devices */ -}; - -struct linux_device_handle_priv { - int fd; - int fd_removed; - uint32_t caps; -}; - -enum reap_action { - NORMAL = 0, - /* submission failed after the first URB, so await cancellation/completion - * of all the others */ - SUBMIT_FAILED, - - /* cancelled by user or timeout */ - CANCELLED, - - /* completed multi-URB transfer in non-final URB */ - COMPLETED_EARLY, - - /* one or more urbs encountered a low-level error */ - ERROR, -}; - -struct linux_transfer_priv { - union { - struct usbfs_urb *urbs; - struct usbfs_urb **iso_urbs; - }; - - enum reap_action reap_action; - int num_urbs; - int num_retired; - enum libusb_transfer_status reap_status; - - /* next iso packet in user-supplied transfer to be populated */ - int iso_packet_offset; -}; - -static int _get_usbfs_fd(struct libusb_device *dev, mode_t mode, int silent) -{ - struct libusb_context *ctx = DEVICE_CTX(dev); - char path[PATH_MAX]; - int fd; - int delay = 10000; - - if (usbdev_names) - snprintf(path, PATH_MAX, "%s/usbdev%d.%d", - usbfs_path, dev->bus_number, dev->device_address); - else - snprintf(path, PATH_MAX, "%s/%03d/%03d", - usbfs_path, dev->bus_number, dev->device_address); - - fd = open(path, mode); - if (fd != -1) - return fd; /* Success */ - - if (errno == ENOENT) { - if (!silent) - usbi_err(ctx, "File doesn't exist, wait %d ms and try again", delay/1000); - - /* Wait 10ms for USB device path creation.*/ - nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000UL}, NULL); - - fd = open(path, mode); - if (fd != -1) - return fd; /* Success */ - } - - if (!silent) { - usbi_err(ctx, "libusb couldn't open USB device %s: %s", - path, strerror(errno)); - if (errno == EACCES && mode == O_RDWR) - usbi_err(ctx, "libusb requires write access to USB " - "device nodes."); - } - - if (errno == EACCES) - return LIBUSB_ERROR_ACCESS; - if (errno == ENOENT) - return LIBUSB_ERROR_NO_DEVICE; - return LIBUSB_ERROR_IO; -} - -static struct linux_device_priv *_device_priv(struct libusb_device *dev) -{ - return (struct linux_device_priv *) dev->os_priv; -} - -static struct linux_device_handle_priv *_device_handle_priv( - struct libusb_device_handle *handle) -{ - return (struct linux_device_handle_priv *) handle->os_priv; -} - -/* check dirent for a /dev/usbdev%d.%d name - * optionally return bus/device on success */ -static int _is_usbdev_entry(struct dirent *entry, int *bus_p, int *dev_p) -{ - int busnum, devnum; - - if (sscanf(entry->d_name, "usbdev%d.%d", &busnum, &devnum) != 2) - return 0; - - usbi_dbg("found: %s", entry->d_name); - if (bus_p != NULL) - *bus_p = busnum; - if (dev_p != NULL) - *dev_p = devnum; - return 1; -} - -static int check_usb_vfs(const char *dirname) -{ - DIR *dir; - struct dirent *entry; - int found = 0; - - dir = opendir(dirname); - if (!dir) - return 0; - - while ((entry = readdir(dir)) != NULL) { - if (entry->d_name[0] == '.') - continue; - - /* We assume if we find any files that it must be the right place */ - found = 1; - break; - } - - closedir(dir); - return found; -} - -static const char *find_usbfs_path(void) -{ - const char *path = "/dev/bus/usb"; - const char *ret = NULL; - - if (check_usb_vfs(path)) { - ret = path; - } else { - path = "/proc/bus/usb"; - if (check_usb_vfs(path)) - ret = path; - } - - /* look for /dev/usbdev*.* if the normal places fail */ - if (ret == NULL) { - struct dirent *entry; - DIR *dir; - - path = "/dev"; - dir = opendir(path); - if (dir != NULL) { - while ((entry = readdir(dir)) != NULL) { - if (_is_usbdev_entry(entry, NULL, NULL)) { - /* found one; that's enough */ - ret = path; - usbdev_names = 1; - break; - } - } - closedir(dir); - } - } - -/* On udev based systems without any usb-devices /dev/bus/usb will not - * exist. So if we've not found anything and we're using udev for hotplug - * simply assume /dev/bus/usb rather then making libusb_init fail. */ -#if defined(USE_UDEV) - if (ret == NULL) - ret = "/dev/bus/usb"; -#endif - - if (ret != NULL) - usbi_dbg("found usbfs at %s", ret); - - return ret; -} - -/* the monotonic clock is not usable on all systems (e.g. embedded ones often - * seem to lack it). fall back to REALTIME if we have to. */ -static clockid_t find_monotonic_clock(void) -{ -#ifdef CLOCK_MONOTONIC - struct timespec ts; - int r; - - /* Linux 2.6.28 adds CLOCK_MONOTONIC_RAW but we don't use it - * because it's not available through timerfd */ - r = clock_gettime(CLOCK_MONOTONIC, &ts); - if (r == 0) - return CLOCK_MONOTONIC; - usbi_dbg("monotonic clock doesn't work, errno %d", errno); -#endif - - return CLOCK_REALTIME; -} - -static int kernel_version_ge(int major, int minor, int sublevel) -{ - struct utsname uts; - int atoms, kmajor, kminor, ksublevel; - - if (uname(&uts) < 0) - return -1; - atoms = sscanf(uts.release, "%d.%d.%d", &kmajor, &kminor, &ksublevel); - if (atoms < 1) - return -1; - - if (kmajor > major) - return 1; - if (kmajor < major) - return 0; - - /* kmajor == major */ - if (atoms < 2) - return 0 == minor && 0 == sublevel; - if (kminor > minor) - return 1; - if (kminor < minor) - return 0; - - /* kminor == minor */ - if (atoms < 3) - return 0 == sublevel; - - return ksublevel >= sublevel; -} - -static int op_init(struct libusb_context *ctx) -{ - struct stat statbuf; - int r; - - usbfs_path = find_usbfs_path(); - if (!usbfs_path) { - usbi_err(ctx, "could not find usbfs"); - return LIBUSB_ERROR_OTHER; - } - - if (monotonic_clkid == -1) - monotonic_clkid = find_monotonic_clock(); - - if (supports_flag_bulk_continuation == -1) { - /* bulk continuation URB flag available from Linux 2.6.32 */ - supports_flag_bulk_continuation = kernel_version_ge(2,6,32); - if (supports_flag_bulk_continuation == -1) { - usbi_err(ctx, "error checking for bulk continuation support"); - return LIBUSB_ERROR_OTHER; - } - } - - if (supports_flag_bulk_continuation) - usbi_dbg("bulk continuation flag supported"); - - if (-1 == supports_flag_zero_packet) { - /* zero length packet URB flag fixed since Linux 2.6.31 */ - supports_flag_zero_packet = kernel_version_ge(2,6,31); - if (-1 == supports_flag_zero_packet) { - usbi_err(ctx, "error checking for zero length packet support"); - return LIBUSB_ERROR_OTHER; - } - } - - if (supports_flag_zero_packet) - usbi_dbg("zero length packet flag supported"); - - if (-1 == sysfs_has_descriptors) { - /* sysfs descriptors has all descriptors since Linux 2.6.26 */ - sysfs_has_descriptors = kernel_version_ge(2,6,26); - if (-1 == sysfs_has_descriptors) { - usbi_err(ctx, "error checking for sysfs descriptors"); - return LIBUSB_ERROR_OTHER; - } - } - - if (-1 == sysfs_can_relate_devices) { - /* sysfs has busnum since Linux 2.6.22 */ - sysfs_can_relate_devices = kernel_version_ge(2,6,22); - if (-1 == sysfs_can_relate_devices) { - usbi_err(ctx, "error checking for sysfs busnum"); - return LIBUSB_ERROR_OTHER; - } - } - - if (sysfs_can_relate_devices || sysfs_has_descriptors) { - r = stat(SYSFS_DEVICE_PATH, &statbuf); - if (r != 0 || !S_ISDIR(statbuf.st_mode)) { - usbi_warn(ctx, "sysfs not mounted"); - sysfs_can_relate_devices = 0; - sysfs_has_descriptors = 0; - } - } - - if (sysfs_can_relate_devices) - usbi_dbg("sysfs can relate devices"); - - if (sysfs_has_descriptors) - usbi_dbg("sysfs has complete descriptors"); - - usbi_mutex_static_lock(&linux_hotplug_startstop_lock); - r = LIBUSB_SUCCESS; - if (init_count == 0) { - /* start up hotplug event handler */ - r = linux_start_event_monitor(); - } - if (r == LIBUSB_SUCCESS) { - r = linux_scan_devices(ctx); - if (r == LIBUSB_SUCCESS) - init_count++; - else if (init_count == 0) - linux_stop_event_monitor(); - } else - usbi_err(ctx, "error starting hotplug event monitor"); - usbi_mutex_static_unlock(&linux_hotplug_startstop_lock); - - return r; -} - -static void op_exit(void) -{ - usbi_mutex_static_lock(&linux_hotplug_startstop_lock); - assert(init_count != 0); - if (!--init_count) { - /* tear down event handler */ - (void)linux_stop_event_monitor(); - } - usbi_mutex_static_unlock(&linux_hotplug_startstop_lock); -} - -static int linux_start_event_monitor(void) -{ -#if defined(USE_UDEV) - return linux_udev_start_event_monitor(); -#else - return linux_netlink_start_event_monitor(); -#endif -} - -static int linux_stop_event_monitor(void) -{ -#if defined(USE_UDEV) - return linux_udev_stop_event_monitor(); -#else - return linux_netlink_stop_event_monitor(); -#endif -} - -static int linux_scan_devices(struct libusb_context *ctx) -{ - int ret; - - usbi_mutex_static_lock(&linux_hotplug_lock); - -#if defined(USE_UDEV) - ret = linux_udev_scan_devices(ctx); -#else - ret = linux_default_scan_devices(ctx); -#endif - - usbi_mutex_static_unlock(&linux_hotplug_lock); - - return ret; -} - -static void op_hotplug_poll(void) -{ -#if defined(USE_UDEV) - linux_udev_hotplug_poll(); -#else - linux_netlink_hotplug_poll(); -#endif -} - -static int _open_sysfs_attr(struct libusb_device *dev, const char *attr) -{ - struct linux_device_priv *priv = _device_priv(dev); - char filename[PATH_MAX]; - int fd; - - snprintf(filename, PATH_MAX, "%s/%s/%s", - SYSFS_DEVICE_PATH, priv->sysfs_dir, attr); - fd = open(filename, O_RDONLY); - if (fd < 0) { - usbi_err(DEVICE_CTX(dev), - "open %s failed ret=%d errno=%d", filename, fd, errno); - return LIBUSB_ERROR_IO; - } - - return fd; -} - -/* Note only suitable for attributes which always read >= 0, < 0 is error */ -static int __read_sysfs_attr(struct libusb_context *ctx, - const char *devname, const char *attr) -{ - char filename[PATH_MAX]; - FILE *f; - int r, value; - - snprintf(filename, PATH_MAX, "%s/%s/%s", SYSFS_DEVICE_PATH, - devname, attr); - f = fopen(filename, "r"); - if (f == NULL) { - if (errno == ENOENT) { - /* File doesn't exist. Assume the device has been - disconnected (see trac ticket #70). */ - return LIBUSB_ERROR_NO_DEVICE; - } - usbi_err(ctx, "open %s failed errno=%d", filename, errno); - return LIBUSB_ERROR_IO; - } - - r = fscanf(f, "%d", &value); - fclose(f); - if (r != 1) { - usbi_err(ctx, "fscanf %s returned %d, errno=%d", attr, r, errno); - return LIBUSB_ERROR_NO_DEVICE; /* For unplug race (trac #70) */ - } - if (value < 0) { - usbi_err(ctx, "%s contains a negative value", filename); - return LIBUSB_ERROR_IO; - } - - return value; -} - -static int op_get_device_descriptor(struct libusb_device *dev, - unsigned char *buffer, int *host_endian) -{ - struct linux_device_priv *priv = _device_priv(dev); - - *host_endian = sysfs_has_descriptors ? 0 : 1; - memcpy(buffer, priv->descriptors, DEVICE_DESC_LENGTH); - - return 0; -} - -/* read the bConfigurationValue for a device */ -static int sysfs_get_active_config(struct libusb_device *dev, int *config) -{ - char *endptr; - char tmp[5] = {0, 0, 0, 0, 0}; - long num; - int fd; - ssize_t r; - - fd = _open_sysfs_attr(dev, "bConfigurationValue"); - if (fd < 0) - return fd; - - r = read(fd, tmp, sizeof(tmp)); - close(fd); - if (r < 0) { - usbi_err(DEVICE_CTX(dev), - "read bConfigurationValue failed ret=%d errno=%d", r, errno); - return LIBUSB_ERROR_IO; - } else if (r == 0) { - usbi_dbg("device unconfigured"); - *config = -1; - return 0; - } - - if (tmp[sizeof(tmp) - 1] != 0) { - usbi_err(DEVICE_CTX(dev), "not null-terminated?"); - return LIBUSB_ERROR_IO; - } else if (tmp[0] == 0) { - usbi_err(DEVICE_CTX(dev), "no configuration value?"); - return LIBUSB_ERROR_IO; - } - - num = strtol(tmp, &endptr, 10); - if (endptr == tmp) { - usbi_err(DEVICE_CTX(dev), "error converting '%s' to integer", tmp); - return LIBUSB_ERROR_IO; - } - - *config = (int) num; - return 0; -} - -int linux_get_device_address (struct libusb_context *ctx, int detached, - uint8_t *busnum, uint8_t *devaddr,const char *dev_node, - const char *sys_name) -{ - int sysfs_attr; - - usbi_dbg("getting address for device: %s detached: %d", sys_name, detached); - /* can't use sysfs to read the bus and device number if the - * device has been detached */ - if (!sysfs_can_relate_devices || detached || NULL == sys_name) { - if (NULL == dev_node) { - return LIBUSB_ERROR_OTHER; - } - - /* will this work with all supported kernel versions? */ - if (!strncmp(dev_node, "/dev/bus/usb", 12)) { - sscanf (dev_node, "/dev/bus/usb/%hhu/%hhu", busnum, devaddr); - } else if (!strncmp(dev_node, "/proc/bus/usb", 13)) { - sscanf (dev_node, "/proc/bus/usb/%hhu/%hhu", busnum, devaddr); - } - - return LIBUSB_SUCCESS; - } - - usbi_dbg("scan %s", sys_name); - - sysfs_attr = __read_sysfs_attr(ctx, sys_name, "busnum"); - if (0 > sysfs_attr) - return sysfs_attr; - if (sysfs_attr > 255) - return LIBUSB_ERROR_INVALID_PARAM; - *busnum = (uint8_t) sysfs_attr; - - sysfs_attr = __read_sysfs_attr(ctx, sys_name, "devnum"); - if (0 > sysfs_attr) - return sysfs_attr; - if (sysfs_attr > 255) - return LIBUSB_ERROR_INVALID_PARAM; - - *devaddr = (uint8_t) sysfs_attr; - - usbi_dbg("bus=%d dev=%d", *busnum, *devaddr); - - return LIBUSB_SUCCESS; -} - -/* Return offset of the next descriptor with the given type */ -static int seek_to_next_descriptor(struct libusb_context *ctx, - uint8_t descriptor_type, unsigned char *buffer, int size) -{ - struct usb_descriptor_header header; - int i; - - for (i = 0; size >= 0; i += header.bLength, size -= header.bLength) { - if (size == 0) - return LIBUSB_ERROR_NOT_FOUND; - - if (size < 2) { - usbi_err(ctx, "short descriptor read %d/2", size); - return LIBUSB_ERROR_IO; - } - usbi_parse_descriptor(buffer + i, "bb", &header, 0); - - if (i && header.bDescriptorType == descriptor_type) - return i; - } - usbi_err(ctx, "bLength overflow by %d bytes", -size); - return LIBUSB_ERROR_IO; -} - -/* Return offset to next config */ -static int seek_to_next_config(struct libusb_context *ctx, - unsigned char *buffer, int size) -{ - struct libusb_config_descriptor config; - - if (size == 0) - return LIBUSB_ERROR_NOT_FOUND; - - if (size < LIBUSB_DT_CONFIG_SIZE) { - usbi_err(ctx, "short descriptor read %d/%d", - size, LIBUSB_DT_CONFIG_SIZE); - return LIBUSB_ERROR_IO; - } - - usbi_parse_descriptor(buffer, "bbwbbbbb", &config, 0); - if (config.bDescriptorType != LIBUSB_DT_CONFIG) { - usbi_err(ctx, "descriptor is not a config desc (type 0x%02x)", - config.bDescriptorType); - return LIBUSB_ERROR_IO; - } - - /* - * In usbfs the config descriptors are config.wTotalLength bytes apart, - * with any short reads from the device appearing as holes in the file. - * - * In sysfs wTotalLength is ignored, instead the kernel returns a - * config descriptor with verified bLength fields, with descriptors - * with an invalid bLength removed. - */ - if (sysfs_has_descriptors) { - int next = seek_to_next_descriptor(ctx, LIBUSB_DT_CONFIG, - buffer, size); - if (next == LIBUSB_ERROR_NOT_FOUND) - next = size; - if (next < 0) - return next; - - if (next != config.wTotalLength) - usbi_warn(ctx, "config length mismatch wTotalLength " - "%d real %d", config.wTotalLength, next); - return next; - } else { - if (config.wTotalLength < LIBUSB_DT_CONFIG_SIZE) { - usbi_err(ctx, "invalid wTotalLength %d", - config.wTotalLength); - return LIBUSB_ERROR_IO; - } else if (config.wTotalLength > size) { - usbi_warn(ctx, "short descriptor read %d/%d", - size, config.wTotalLength); - return size; - } else - return config.wTotalLength; - } -} - -static int op_get_config_descriptor_by_value(struct libusb_device *dev, - uint8_t value, unsigned char **buffer, int *host_endian) -{ - struct libusb_context *ctx = DEVICE_CTX(dev); - struct linux_device_priv *priv = _device_priv(dev); - unsigned char *descriptors = priv->descriptors; - int size = priv->descriptors_len; - struct libusb_config_descriptor *config; - - *buffer = NULL; - /* Unlike the device desc. config descs. are always in raw format */ - *host_endian = 0; - - /* Skip device header */ - descriptors += DEVICE_DESC_LENGTH; - size -= DEVICE_DESC_LENGTH; - - /* Seek till the config is found, or till "EOF" */ - while (1) { - int next = seek_to_next_config(ctx, descriptors, size); - if (next < 0) - return next; - config = (struct libusb_config_descriptor *)descriptors; - if (config->bConfigurationValue == value) { - *buffer = descriptors; - return next; - } - size -= next; - descriptors += next; - } -} - -static int op_get_active_config_descriptor(struct libusb_device *dev, - unsigned char *buffer, size_t len, int *host_endian) -{ - int r, config; - unsigned char *config_desc; - - if (sysfs_can_relate_devices) { - r = sysfs_get_active_config(dev, &config); - if (r < 0) - return r; - } else { - /* Use cached bConfigurationValue */ - struct linux_device_priv *priv = _device_priv(dev); - config = priv->active_config; - } - if (config == -1) - return LIBUSB_ERROR_NOT_FOUND; - - r = op_get_config_descriptor_by_value(dev, config, &config_desc, - host_endian); - if (r < 0) - return r; - - len = MIN(len, r); - memcpy(buffer, config_desc, len); - return len; -} - -static int op_get_config_descriptor(struct libusb_device *dev, - uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) -{ - struct linux_device_priv *priv = _device_priv(dev); - unsigned char *descriptors = priv->descriptors; - int i, r, size = priv->descriptors_len; - - /* Unlike the device desc. config descs. are always in raw format */ - *host_endian = 0; - - /* Skip device header */ - descriptors += DEVICE_DESC_LENGTH; - size -= DEVICE_DESC_LENGTH; - - /* Seek till the config is found, or till "EOF" */ - for (i = 0; ; i++) { - r = seek_to_next_config(DEVICE_CTX(dev), descriptors, size); - if (r < 0) - return r; - if (i == config_index) - break; - size -= r; - descriptors += r; - } - - len = MIN(len, r); - memcpy(buffer, descriptors, len); - return len; -} - -/* send a control message to retrieve active configuration */ -static int usbfs_get_active_config(struct libusb_device *dev, int fd) -{ - struct linux_device_priv *priv = _device_priv(dev); - unsigned char active_config = 0; - int r; - - struct usbfs_ctrltransfer ctrl = { - .bmRequestType = LIBUSB_ENDPOINT_IN, - .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION, - .wValue = 0, - .wIndex = 0, - .wLength = 1, - .timeout = 1000, - .data = &active_config - }; - - r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl); - if (r < 0) { - if (errno == ENODEV) - return LIBUSB_ERROR_NO_DEVICE; - - /* we hit this error path frequently with buggy devices :( */ - usbi_warn(DEVICE_CTX(dev), - "get_configuration failed ret=%d errno=%d", r, errno); - priv->active_config = -1; - } else { - if (active_config > 0) { - priv->active_config = active_config; - } else { - /* some buggy devices have a configuration 0, but we're - * reaching into the corner of a corner case here, so let's - * not support buggy devices in these circumstances. - * stick to the specs: a configuration value of 0 means - * unconfigured. */ - usbi_warn(DEVICE_CTX(dev), - "active cfg 0? assuming unconfigured device"); - priv->active_config = -1; - } - } - - return LIBUSB_SUCCESS; -} - -static int initialize_device(struct libusb_device *dev, uint8_t busnum, - uint8_t devaddr, const char *sysfs_dir) -{ - struct linux_device_priv *priv = _device_priv(dev); - struct libusb_context *ctx = DEVICE_CTX(dev); - int descriptors_size = 512; /* Begin with a 1024 byte alloc */ - int fd, speed; - ssize_t r; - - dev->bus_number = busnum; - dev->device_address = devaddr; - - if (sysfs_dir) { - priv->sysfs_dir = strdup(sysfs_dir); - if (!priv->sysfs_dir) - return LIBUSB_ERROR_NO_MEM; - - /* Note speed can contain 1.5, in this case __read_sysfs_attr - will stop parsing at the '.' and return 1 */ - speed = __read_sysfs_attr(DEVICE_CTX(dev), sysfs_dir, "speed"); - if (speed >= 0) { - switch (speed) { - case 1: dev->speed = LIBUSB_SPEED_LOW; break; - case 12: dev->speed = LIBUSB_SPEED_FULL; break; - case 480: dev->speed = LIBUSB_SPEED_HIGH; break; - case 5000: dev->speed = LIBUSB_SPEED_SUPER; break; - default: - usbi_warn(DEVICE_CTX(dev), "Unknown device speed: %d Mbps", speed); - } - } - } - - /* cache descriptors in memory */ - if (sysfs_has_descriptors) - fd = _open_sysfs_attr(dev, "descriptors"); - else - fd = _get_usbfs_fd(dev, O_RDONLY, 0); - if (fd < 0) - return fd; - - do { - descriptors_size *= 2; - priv->descriptors = usbi_reallocf(priv->descriptors, - descriptors_size); - if (!priv->descriptors) { - close(fd); - return LIBUSB_ERROR_NO_MEM; - } - /* usbfs has holes in the file */ - if (!sysfs_has_descriptors) { - memset(priv->descriptors + priv->descriptors_len, - 0, descriptors_size - priv->descriptors_len); - } - r = read(fd, priv->descriptors + priv->descriptors_len, - descriptors_size - priv->descriptors_len); - if (r < 0) { - usbi_err(ctx, "read descriptor failed ret=%d errno=%d", - fd, errno); - close(fd); - return LIBUSB_ERROR_IO; - } - priv->descriptors_len += r; - } while (priv->descriptors_len == descriptors_size); - - close(fd); - - if (priv->descriptors_len < DEVICE_DESC_LENGTH) { - usbi_err(ctx, "short descriptor read (%d)", - priv->descriptors_len); - return LIBUSB_ERROR_IO; - } - - if (sysfs_can_relate_devices) - return LIBUSB_SUCCESS; - - /* cache active config */ - fd = _get_usbfs_fd(dev, O_RDWR, 1); - if (fd < 0) { - /* cannot send a control message to determine the active - * config. just assume the first one is active. */ - usbi_warn(ctx, "Missing rw usbfs access; cannot determine " - "active configuration descriptor"); - if (priv->descriptors_len >= - (DEVICE_DESC_LENGTH + LIBUSB_DT_CONFIG_SIZE)) { - struct libusb_config_descriptor config; - usbi_parse_descriptor( - priv->descriptors + DEVICE_DESC_LENGTH, - "bbwbbbbb", &config, 0); - priv->active_config = config.bConfigurationValue; - } else - priv->active_config = -1; /* No config dt */ - - return LIBUSB_SUCCESS; - } - - r = usbfs_get_active_config(dev, fd); - close(fd); - - return r; -} - -static int linux_get_parent_info(struct libusb_device *dev, const char *sysfs_dir) -{ - struct libusb_context *ctx = DEVICE_CTX(dev); - struct libusb_device *it; - char *parent_sysfs_dir, *tmp; - int ret, add_parent = 1; - - /* XXX -- can we figure out the topology when using usbfs? */ - if (NULL == sysfs_dir || 0 == strncmp(sysfs_dir, "usb", 3)) { - /* either using usbfs or finding the parent of a root hub */ - return LIBUSB_SUCCESS; - } - - parent_sysfs_dir = strdup(sysfs_dir); - if (NULL == parent_sysfs_dir) { - return LIBUSB_ERROR_NO_MEM; - } - if (NULL != (tmp = strrchr(parent_sysfs_dir, '.')) || - NULL != (tmp = strrchr(parent_sysfs_dir, '-'))) { - dev->port_number = atoi(tmp + 1); - *tmp = '\0'; - } else { - usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info", - parent_sysfs_dir); - free (parent_sysfs_dir); - return LIBUSB_SUCCESS; - } - - /* is the parent a root hub? */ - if (NULL == strchr(parent_sysfs_dir, '-')) { - tmp = parent_sysfs_dir; - ret = asprintf (&parent_sysfs_dir, "usb%s", tmp); - free (tmp); - if (0 > ret) { - return LIBUSB_ERROR_NO_MEM; - } - } - -retry: - /* find the parent in the context */ - usbi_mutex_lock(&ctx->usb_devs_lock); - list_for_each_entry(it, &ctx->usb_devs, list, struct libusb_device) { - struct linux_device_priv *priv = _device_priv(it); - if (priv->sysfs_dir) { - if (0 == strcmp (priv->sysfs_dir, parent_sysfs_dir)) { - dev->parent_dev = libusb_ref_device(it); - break; - } - } - } - usbi_mutex_unlock(&ctx->usb_devs_lock); - - if (!dev->parent_dev && add_parent) { - usbi_dbg("parent_dev %s not enumerated yet, enumerating now", - parent_sysfs_dir); - sysfs_scan_device(ctx, parent_sysfs_dir); - add_parent = 0; - goto retry; - } - - usbi_dbg("Dev %p (%s) has parent %p (%s) port %d", dev, sysfs_dir, - dev->parent_dev, parent_sysfs_dir, dev->port_number); - - free (parent_sysfs_dir); - - return LIBUSB_SUCCESS; -} - -int linux_enumerate_device(struct libusb_context *ctx, - uint8_t busnum, uint8_t devaddr, const char *sysfs_dir) -{ - unsigned long session_id; - struct libusb_device *dev; - int r = 0; - - /* FIXME: session ID is not guaranteed unique as addresses can wrap and - * will be reused. instead we should add a simple sysfs attribute with - * a session ID. */ - session_id = busnum << 8 | devaddr; - usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr, - session_id); - - dev = usbi_get_device_by_session_id(ctx, session_id); - if (dev) { - /* device already exists in the context */ - usbi_dbg("session_id %ld already exists", session_id); - libusb_unref_device(dev); - return LIBUSB_SUCCESS; - } - - usbi_dbg("allocating new device for %d/%d (session %ld)", - busnum, devaddr, session_id); - dev = usbi_alloc_device(ctx, session_id); - if (!dev) - return LIBUSB_ERROR_NO_MEM; - - r = initialize_device(dev, busnum, devaddr, sysfs_dir); - if (r < 0) - goto out; - r = usbi_sanitize_device(dev); - if (r < 0) - goto out; - - r = linux_get_parent_info(dev, sysfs_dir); - if (r < 0) - goto out; -out: - if (r < 0) - libusb_unref_device(dev); - else - usbi_connect_device(dev); - - return r; -} - -void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name) -{ - struct libusb_context *ctx; - - usbi_mutex_static_lock(&active_contexts_lock); - list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) { - linux_enumerate_device(ctx, busnum, devaddr, sys_name); - } - usbi_mutex_static_unlock(&active_contexts_lock); -} - -void linux_device_disconnected(uint8_t busnum, uint8_t devaddr) -{ - struct libusb_context *ctx; - struct libusb_device *dev; - unsigned long session_id = busnum << 8 | devaddr; - - usbi_mutex_static_lock(&active_contexts_lock); - list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) { - dev = usbi_get_device_by_session_id (ctx, session_id); - if (NULL != dev) { - usbi_disconnect_device (dev); - libusb_unref_device(dev); - } else { - usbi_dbg("device not found for session %x", session_id); - } - } - usbi_mutex_static_unlock(&active_contexts_lock); -} - -#if !defined(USE_UDEV) -/* open a bus directory and adds all discovered devices to the context */ -static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum) -{ - DIR *dir; - char dirpath[PATH_MAX]; - struct dirent *entry; - int r = LIBUSB_ERROR_IO; - - snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum); - usbi_dbg("%s", dirpath); - dir = opendir(dirpath); - if (!dir) { - usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno); - /* FIXME: should handle valid race conditions like hub unplugged - * during directory iteration - this is not an error */ - return r; - } - - while ((entry = readdir(dir))) { - int devaddr; - - if (entry->d_name[0] == '.') - continue; - - devaddr = atoi(entry->d_name); - if (devaddr == 0) { - usbi_dbg("unknown dir entry %s", entry->d_name); - continue; - } - - if (linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL)) { - usbi_dbg("failed to enumerate dir entry %s", entry->d_name); - continue; - } - - r = 0; - } - - closedir(dir); - return r; -} - -static int usbfs_get_device_list(struct libusb_context *ctx) -{ - struct dirent *entry; - DIR *buses = opendir(usbfs_path); - int r = 0; - - if (!buses) { - usbi_err(ctx, "opendir buses failed errno=%d", errno); - return LIBUSB_ERROR_IO; - } - - while ((entry = readdir(buses))) { - int busnum; - - if (entry->d_name[0] == '.') - continue; - - if (usbdev_names) { - int devaddr; - if (!_is_usbdev_entry(entry, &busnum, &devaddr)) - continue; - - r = linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL); - if (r < 0) { - usbi_dbg("failed to enumerate dir entry %s", entry->d_name); - continue; - } - } else { - busnum = atoi(entry->d_name); - if (busnum == 0) { - usbi_dbg("unknown dir entry %s", entry->d_name); - continue; - } - - r = usbfs_scan_busdir(ctx, busnum); - if (r < 0) - break; - } - } - - closedir(buses); - return r; - -} -#endif - -static int sysfs_scan_device(struct libusb_context *ctx, const char *devname) -{ - uint8_t busnum, devaddr; - int ret; - - ret = linux_get_device_address (ctx, 0, &busnum, &devaddr, NULL, devname); - if (LIBUSB_SUCCESS != ret) { - return ret; - } - - return linux_enumerate_device(ctx, busnum & 0xff, devaddr & 0xff, - devname); -} - -#if !defined(USE_UDEV) -static int sysfs_get_device_list(struct libusb_context *ctx) -{ - DIR *devices = opendir(SYSFS_DEVICE_PATH); - struct dirent *entry; - int r = LIBUSB_ERROR_IO; - - if (!devices) { - usbi_err(ctx, "opendir devices failed errno=%d", errno); - return r; - } - - while ((entry = readdir(devices))) { - if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3)) - || strchr(entry->d_name, ':')) - continue; - - if (sysfs_scan_device(ctx, entry->d_name)) { - usbi_dbg("failed to enumerate dir entry %s", entry->d_name); - continue; - } - - r = 0; - } - - closedir(devices); - return r; -} - -static int linux_default_scan_devices (struct libusb_context *ctx) -{ - /* we can retrieve device list and descriptors from sysfs or usbfs. - * sysfs is preferable, because if we use usbfs we end up resuming - * any autosuspended USB devices. however, sysfs is not available - * everywhere, so we need a usbfs fallback too. - * - * as described in the "sysfs vs usbfs" comment at the top of this - * file, sometimes we have sysfs but not enough information to - * relate sysfs devices to usbfs nodes. op_init() determines the - * adequacy of sysfs and sets sysfs_can_relate_devices. - */ - if (sysfs_can_relate_devices != 0) - return sysfs_get_device_list(ctx); - else - return usbfs_get_device_list(ctx); -} -#endif - -static int op_open(struct libusb_device_handle *handle) -{ - struct linux_device_handle_priv *hpriv = _device_handle_priv(handle); - int r; - - hpriv->fd = _get_usbfs_fd(handle->dev, O_RDWR, 0); - if (hpriv->fd < 0) { - if (hpriv->fd == LIBUSB_ERROR_NO_DEVICE) { - /* device will still be marked as attached if hotplug monitor thread - * hasn't processed remove event yet */ - usbi_mutex_static_lock(&linux_hotplug_lock); - if (handle->dev->attached) { - usbi_dbg("open failed with no device, but device still attached"); - linux_device_disconnected(handle->dev->bus_number, - handle->dev->device_address); - } - usbi_mutex_static_unlock(&linux_hotplug_lock); - } - return hpriv->fd; - } - - r = ioctl(hpriv->fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps); - if (r < 0) { - if (errno == ENOTTY) - usbi_dbg("getcap not available"); - else - usbi_err(HANDLE_CTX(handle), "getcap failed (%d)", errno); - hpriv->caps = 0; - if (supports_flag_zero_packet) - hpriv->caps |= USBFS_CAP_ZERO_PACKET; - if (supports_flag_bulk_continuation) - hpriv->caps |= USBFS_CAP_BULK_CONTINUATION; - } - - r = usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT); - if (r < 0) - close(hpriv->fd); - - return r; -} - -static void op_close(struct libusb_device_handle *dev_handle) -{ - struct linux_device_handle_priv *hpriv = _device_handle_priv(dev_handle); - /* fd may have already been removed by POLLERR condition in op_handle_events() */ - if (!hpriv->fd_removed) - usbi_remove_pollfd(HANDLE_CTX(dev_handle), hpriv->fd); - close(hpriv->fd); -} - -static int op_get_configuration(struct libusb_device_handle *handle, - int *config) -{ - int r; - - if (sysfs_can_relate_devices) { - r = sysfs_get_active_config(handle->dev, config); - } else { - r = usbfs_get_active_config(handle->dev, - _device_handle_priv(handle)->fd); - if (r == LIBUSB_SUCCESS) - *config = _device_priv(handle->dev)->active_config; - } - if (r < 0) - return r; - - if (*config == -1) { - usbi_err(HANDLE_CTX(handle), "device unconfigured"); - *config = 0; - } - - return 0; -} - -static int op_set_configuration(struct libusb_device_handle *handle, int config) -{ - struct linux_device_priv *priv = _device_priv(handle->dev); - int fd = _device_handle_priv(handle)->fd; - int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config); - if (r) { - if (errno == EINVAL) - return LIBUSB_ERROR_NOT_FOUND; - else if (errno == EBUSY) - return LIBUSB_ERROR_BUSY; - else if (errno == ENODEV) - return LIBUSB_ERROR_NO_DEVICE; - - usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno); - return LIBUSB_ERROR_OTHER; - } - - /* update our cached active config descriptor */ - priv->active_config = config; - - return LIBUSB_SUCCESS; -} - -static int claim_interface(struct libusb_device_handle *handle, int iface) -{ - int fd = _device_handle_priv(handle)->fd; - int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface); - if (r) { - if (errno == ENOENT) - return LIBUSB_ERROR_NOT_FOUND; - else if (errno == EBUSY) - return LIBUSB_ERROR_BUSY; - else if (errno == ENODEV) - return LIBUSB_ERROR_NO_DEVICE; - - usbi_err(HANDLE_CTX(handle), - "claim interface failed, error %d errno %d", r, errno); - return LIBUSB_ERROR_OTHER; - } - return 0; -} - -static int release_interface(struct libusb_device_handle *handle, int iface) -{ - int fd = _device_handle_priv(handle)->fd; - int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface); - if (r) { - if (errno == ENODEV) - return LIBUSB_ERROR_NO_DEVICE; - - usbi_err(HANDLE_CTX(handle), - "release interface failed, error %d errno %d", r, errno); - return LIBUSB_ERROR_OTHER; - } - return 0; -} - -static int op_set_interface(struct libusb_device_handle *handle, int iface, - int altsetting) -{ - int fd = _device_handle_priv(handle)->fd; - struct usbfs_setinterface setintf; - int r; - - setintf.interface = iface; - setintf.altsetting = altsetting; - r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf); - if (r) { - if (errno == EINVAL) - return LIBUSB_ERROR_NOT_FOUND; - else if (errno == ENODEV) - return LIBUSB_ERROR_NO_DEVICE; - - usbi_err(HANDLE_CTX(handle), - "setintf failed error %d errno %d", r, errno); - return LIBUSB_ERROR_OTHER; - } - - return 0; -} - -static int op_clear_halt(struct libusb_device_handle *handle, - unsigned char endpoint) -{ - int fd = _device_handle_priv(handle)->fd; - unsigned int _endpoint = endpoint; - int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint); - if (r) { - if (errno == ENOENT) - return LIBUSB_ERROR_NOT_FOUND; - else if (errno == ENODEV) - return LIBUSB_ERROR_NO_DEVICE; - - usbi_err(HANDLE_CTX(handle), - "clear_halt failed error %d errno %d", r, errno); - return LIBUSB_ERROR_OTHER; - } - - return 0; -} - -static int op_reset_device(struct libusb_device_handle *handle) -{ - int fd = _device_handle_priv(handle)->fd; - int i, r, ret = 0; - - /* Doing a device reset will cause the usbfs driver to get unbound - from any interfaces it is bound to. By voluntarily unbinding - the usbfs driver ourself, we stop the kernel from rebinding - the interface after reset (which would end up with the interface - getting bound to the in kernel driver if any). */ - for (i = 0; i < USB_MAXINTERFACES; i++) { - if (handle->claimed_interfaces & (1L << i)) { - release_interface(handle, i); - } - } - - usbi_mutex_lock(&handle->lock); - r = ioctl(fd, IOCTL_USBFS_RESET, NULL); - if (r) { - if (errno == ENODEV) { - ret = LIBUSB_ERROR_NOT_FOUND; - goto out; - } - - usbi_err(HANDLE_CTX(handle), - "reset failed error %d errno %d", r, errno); - ret = LIBUSB_ERROR_OTHER; - goto out; - } - - /* And re-claim any interfaces which were claimed before the reset */ - for (i = 0; i < USB_MAXINTERFACES; i++) { - if (handle->claimed_interfaces & (1L << i)) { - /* - * A driver may have completed modprobing during - * IOCTL_USBFS_RESET, and bound itself as soon as - * IOCTL_USBFS_RESET released the device lock - */ - r = detach_kernel_driver_and_claim(handle, i); - if (r) { - usbi_warn(HANDLE_CTX(handle), - "failed to re-claim interface %d after reset: %s", - i, libusb_error_name(r)); - handle->claimed_interfaces &= ~(1L << i); - ret = LIBUSB_ERROR_NOT_FOUND; - } - } - } -out: - usbi_mutex_unlock(&handle->lock); - return ret; -} - -static int do_streams_ioctl(struct libusb_device_handle *handle, long req, - uint32_t num_streams, unsigned char *endpoints, int num_endpoints) -{ - int r, fd = _device_handle_priv(handle)->fd; - struct usbfs_streams *streams; - - if (num_endpoints > 30) /* Max 15 in + 15 out eps */ - return LIBUSB_ERROR_INVALID_PARAM; - - streams = malloc(sizeof(struct usbfs_streams) + num_endpoints); - if (!streams) - return LIBUSB_ERROR_NO_MEM; - - streams->num_streams = num_streams; - streams->num_eps = num_endpoints; - memcpy(streams->eps, endpoints, num_endpoints); - - r = ioctl(fd, req, streams); - - free(streams); - - if (r < 0) { - if (errno == ENOTTY) - return LIBUSB_ERROR_NOT_SUPPORTED; - else if (errno == EINVAL) - return LIBUSB_ERROR_INVALID_PARAM; - else if (errno == ENODEV) - return LIBUSB_ERROR_NO_DEVICE; - - usbi_err(HANDLE_CTX(handle), - "streams-ioctl failed error %d errno %d", r, errno); - return LIBUSB_ERROR_OTHER; - } - return r; -} - -static int op_alloc_streams(struct libusb_device_handle *handle, - uint32_t num_streams, unsigned char *endpoints, int num_endpoints) -{ - return do_streams_ioctl(handle, IOCTL_USBFS_ALLOC_STREAMS, - num_streams, endpoints, num_endpoints); -} - -static int op_free_streams(struct libusb_device_handle *handle, - unsigned char *endpoints, int num_endpoints) -{ - return do_streams_ioctl(handle, IOCTL_USBFS_FREE_STREAMS, 0, - endpoints, num_endpoints); -} - -static unsigned char *op_dev_mem_alloc(struct libusb_device_handle *handle, - size_t len) -{ - struct linux_device_handle_priv *hpriv = _device_handle_priv(handle); - unsigned char *buffer = (unsigned char *)mmap(NULL, len, - PROT_READ | PROT_WRITE, MAP_SHARED, hpriv->fd, 0); - if (buffer == MAP_FAILED) { - usbi_err(HANDLE_CTX(handle), "alloc dev mem failed errno %d", - errno); - return NULL; - } - return buffer; -} - -static int op_dev_mem_free(struct libusb_device_handle *handle, - unsigned char *buffer, size_t len) -{ - if (munmap(buffer, len) != 0) { - usbi_err(HANDLE_CTX(handle), "free dev mem failed errno %d", - errno); - return LIBUSB_ERROR_OTHER; - } else { - return LIBUSB_SUCCESS; - } -} - -static int op_kernel_driver_active(struct libusb_device_handle *handle, - int interface) -{ - int fd = _device_handle_priv(handle)->fd; - struct usbfs_getdriver getdrv; - int r; - - getdrv.interface = interface; - r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv); - if (r) { - if (errno == ENODATA) - return 0; - else if (errno == ENODEV) - return LIBUSB_ERROR_NO_DEVICE; - - usbi_err(HANDLE_CTX(handle), - "get driver failed error %d errno %d", r, errno); - return LIBUSB_ERROR_OTHER; - } - - return (strcmp(getdrv.driver, "usbfs") == 0) ? 0 : 1; -} - -static int op_detach_kernel_driver(struct libusb_device_handle *handle, - int interface) -{ - int fd = _device_handle_priv(handle)->fd; - struct usbfs_ioctl command; - struct usbfs_getdriver getdrv; - int r; - - command.ifno = interface; - command.ioctl_code = IOCTL_USBFS_DISCONNECT; - command.data = NULL; - - getdrv.interface = interface; - r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv); - if (r == 0 && strcmp(getdrv.driver, "usbfs") == 0) - return LIBUSB_ERROR_NOT_FOUND; - - r = ioctl(fd, IOCTL_USBFS_IOCTL, &command); - if (r) { - if (errno == ENODATA) - return LIBUSB_ERROR_NOT_FOUND; - else if (errno == EINVAL) - return LIBUSB_ERROR_INVALID_PARAM; - else if (errno == ENODEV) - return LIBUSB_ERROR_NO_DEVICE; - - usbi_err(HANDLE_CTX(handle), - "detach failed error %d errno %d", r, errno); - return LIBUSB_ERROR_OTHER; - } - - return 0; -} - -static int op_attach_kernel_driver(struct libusb_device_handle *handle, - int interface) -{ - int fd = _device_handle_priv(handle)->fd; - struct usbfs_ioctl command; - int r; - - command.ifno = interface; - command.ioctl_code = IOCTL_USBFS_CONNECT; - command.data = NULL; - - r = ioctl(fd, IOCTL_USBFS_IOCTL, &command); - if (r < 0) { - if (errno == ENODATA) - return LIBUSB_ERROR_NOT_FOUND; - else if (errno == EINVAL) - return LIBUSB_ERROR_INVALID_PARAM; - else if (errno == ENODEV) - return LIBUSB_ERROR_NO_DEVICE; - else if (errno == EBUSY) - return LIBUSB_ERROR_BUSY; - - usbi_err(HANDLE_CTX(handle), - "attach failed error %d errno %d", r, errno); - return LIBUSB_ERROR_OTHER; - } else if (r == 0) { - return LIBUSB_ERROR_NOT_FOUND; - } - - return 0; -} - -static int detach_kernel_driver_and_claim(struct libusb_device_handle *handle, - int interface) -{ - struct usbfs_disconnect_claim dc; - int r, fd = _device_handle_priv(handle)->fd; - - dc.interface = interface; - strcpy(dc.driver, "usbfs"); - dc.flags = USBFS_DISCONNECT_CLAIM_EXCEPT_DRIVER; - r = ioctl(fd, IOCTL_USBFS_DISCONNECT_CLAIM, &dc); - if (r == 0 || (r != 0 && errno != ENOTTY)) { - if (r == 0) - return 0; - - switch (errno) { - case EBUSY: - return LIBUSB_ERROR_BUSY; - case EINVAL: - return LIBUSB_ERROR_INVALID_PARAM; - case ENODEV: - return LIBUSB_ERROR_NO_DEVICE; - } - usbi_err(HANDLE_CTX(handle), - "disconnect-and-claim failed errno %d", errno); - return LIBUSB_ERROR_OTHER; - } - - /* Fallback code for kernels which don't support the - disconnect-and-claim ioctl */ - r = op_detach_kernel_driver(handle, interface); - if (r != 0 && r != LIBUSB_ERROR_NOT_FOUND) - return r; - - return claim_interface(handle, interface); -} - -static int op_claim_interface(struct libusb_device_handle *handle, int iface) -{ - if (handle->auto_detach_kernel_driver) - return detach_kernel_driver_and_claim(handle, iface); - else - return claim_interface(handle, iface); -} - -static int op_release_interface(struct libusb_device_handle *handle, int iface) -{ - int r; - - r = release_interface(handle, iface); - if (r) - return r; - - if (handle->auto_detach_kernel_driver) - op_attach_kernel_driver(handle, iface); - - return 0; -} - -static void op_destroy_device(struct libusb_device *dev) -{ - struct linux_device_priv *priv = _device_priv(dev); - if (priv->descriptors) - free(priv->descriptors); - if (priv->sysfs_dir) - free(priv->sysfs_dir); -} - -/* URBs are discarded in reverse order of submission to avoid races. */ -static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one) -{ - struct libusb_transfer *transfer = - USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct linux_transfer_priv *tpriv = - usbi_transfer_get_os_priv(itransfer); - struct linux_device_handle_priv *dpriv = - _device_handle_priv(transfer->dev_handle); - int i, ret = 0; - struct usbfs_urb *urb; - - for (i = last_plus_one - 1; i >= first; i--) { - if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type) - urb = tpriv->iso_urbs[i]; - else - urb = &tpriv->urbs[i]; - - if (0 == ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb)) - continue; - - if (EINVAL == errno) { - usbi_dbg("URB not found --> assuming ready to be reaped"); - if (i == (last_plus_one - 1)) - ret = LIBUSB_ERROR_NOT_FOUND; - } else if (ENODEV == errno) { - usbi_dbg("Device not found for URB --> assuming ready to be reaped"); - ret = LIBUSB_ERROR_NO_DEVICE; - } else { - usbi_warn(TRANSFER_CTX(transfer), - "unrecognised discard errno %d", errno); - ret = LIBUSB_ERROR_OTHER; - } - } - return ret; -} - -static void free_iso_urbs(struct linux_transfer_priv *tpriv) -{ - int i; - for (i = 0; i < tpriv->num_urbs; i++) { - struct usbfs_urb *urb = tpriv->iso_urbs[i]; - if (!urb) - break; - free(urb); - } - - free(tpriv->iso_urbs); - tpriv->iso_urbs = NULL; -} - -static int submit_bulk_transfer(struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer = - USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer); - struct linux_device_handle_priv *dpriv = - _device_handle_priv(transfer->dev_handle); - struct usbfs_urb *urbs; - int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK) - == LIBUSB_ENDPOINT_OUT; - int bulk_buffer_len, use_bulk_continuation; - int r; - int i; - - if (is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) && - !(dpriv->caps & USBFS_CAP_ZERO_PACKET)) - return LIBUSB_ERROR_NOT_SUPPORTED; - - /* - * Older versions of usbfs place a 16kb limit on bulk URBs. We work - * around this by splitting large transfers into 16k blocks, and then - * submit all urbs at once. it would be simpler to submit one urb at - * a time, but there is a big performance gain doing it this way. - * - * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM), - * using arbritary large transfers can still be a bad idea though, as - * the kernel needs to allocate physical contiguous memory for this, - * which may fail for large buffers. - * - * The kernel solves this problem by splitting the transfer into - * blocks itself when the host-controller is scatter-gather capable - * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are. - * - * Last, there is the issue of short-transfers when splitting, for - * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION - * is needed, but this is not always available. - */ - if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) { - /* Good! Just submit everything in one go */ - bulk_buffer_len = transfer->length ? transfer->length : 1; - use_bulk_continuation = 0; - } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) { - /* Split the transfers and use bulk-continuation to - avoid issues with short-transfers */ - bulk_buffer_len = MAX_BULK_BUFFER_LENGTH; - use_bulk_continuation = 1; - } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) { - /* Don't split, assume the kernel can alloc the buffer - (otherwise the submit will fail with -ENOMEM) */ - bulk_buffer_len = transfer->length ? transfer->length : 1; - use_bulk_continuation = 0; - } else { - /* Bad, splitting without bulk-continuation, short transfers - which end before the last urb will not work reliable! */ - /* Note we don't warn here as this is "normal" on kernels < - 2.6.32 and not a problem for most applications */ - bulk_buffer_len = MAX_BULK_BUFFER_LENGTH; - use_bulk_continuation = 0; - } - - int num_urbs = transfer->length / bulk_buffer_len; - int last_urb_partial = 0; - - if (transfer->length == 0) { - num_urbs = 1; - } else if ((transfer->length % bulk_buffer_len) > 0) { - last_urb_partial = 1; - num_urbs++; - } - usbi_dbg("need %d urbs for new transfer with length %d", num_urbs, - transfer->length); - urbs = calloc(num_urbs, sizeof(struct usbfs_urb)); - if (!urbs) - return LIBUSB_ERROR_NO_MEM; - tpriv->urbs = urbs; - tpriv->num_urbs = num_urbs; - tpriv->num_retired = 0; - tpriv->reap_action = NORMAL; - tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED; - - for (i = 0; i < num_urbs; i++) { - struct usbfs_urb *urb = &urbs[i]; - urb->usercontext = itransfer; - switch (transfer->type) { - case LIBUSB_TRANSFER_TYPE_BULK: - urb->type = USBFS_URB_TYPE_BULK; - urb->stream_id = 0; - break; - case LIBUSB_TRANSFER_TYPE_BULK_STREAM: - urb->type = USBFS_URB_TYPE_BULK; - urb->stream_id = itransfer->stream_id; - break; - case LIBUSB_TRANSFER_TYPE_INTERRUPT: - urb->type = USBFS_URB_TYPE_INTERRUPT; - break; - } - urb->endpoint = transfer->endpoint; - urb->buffer = transfer->buffer + (i * bulk_buffer_len); - /* don't set the short not ok flag for the last URB */ - if (use_bulk_continuation && !is_out && (i < num_urbs - 1)) - urb->flags = USBFS_URB_SHORT_NOT_OK; - if (i == num_urbs - 1 && last_urb_partial) - urb->buffer_length = transfer->length % bulk_buffer_len; - else if (transfer->length == 0) - urb->buffer_length = 0; - else - urb->buffer_length = bulk_buffer_len; - - if (i > 0 && use_bulk_continuation) - urb->flags |= USBFS_URB_BULK_CONTINUATION; - - /* we have already checked that the flag is supported */ - if (is_out && i == num_urbs - 1 && - transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) - urb->flags |= USBFS_URB_ZERO_PACKET; - - r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb); - if (r < 0) { - if (errno == ENODEV) { - r = LIBUSB_ERROR_NO_DEVICE; - } else { - usbi_err(TRANSFER_CTX(transfer), - "submiturb failed error %d errno=%d", r, errno); - r = LIBUSB_ERROR_IO; - } - - /* if the first URB submission fails, we can simply free up and - * return failure immediately. */ - if (i == 0) { - usbi_dbg("first URB failed, easy peasy"); - free(urbs); - tpriv->urbs = NULL; - return r; - } - - /* if it's not the first URB that failed, the situation is a bit - * tricky. we may need to discard all previous URBs. there are - * complications: - * - discarding is asynchronous - discarded urbs will be reaped - * later. the user must not have freed the transfer when the - * discarded URBs are reaped, otherwise libusb will be using - * freed memory. - * - the earlier URBs may have completed successfully and we do - * not want to throw away any data. - * - this URB failing may be no error; EREMOTEIO means that - * this transfer simply didn't need all the URBs we submitted - * so, we report that the transfer was submitted successfully and - * in case of error we discard all previous URBs. later when - * the final reap completes we can report error to the user, - * or success if an earlier URB was completed successfully. - */ - tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED; - - /* The URBs we haven't submitted yet we count as already - * retired. */ - tpriv->num_retired += num_urbs - i; - - /* If we completed short then don't try to discard. */ - if (COMPLETED_EARLY == tpriv->reap_action) - return 0; - - discard_urbs(itransfer, 0, i); - - usbi_dbg("reporting successful submission but waiting for %d " - "discards before reporting error", i); - return 0; - } - } - - return 0; -} - -static int submit_iso_transfer(struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer = - USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer); - struct linux_device_handle_priv *dpriv = - _device_handle_priv(transfer->dev_handle); - struct usbfs_urb **urbs; - size_t alloc_size; - int num_packets = transfer->num_iso_packets; - int i; - int this_urb_len = 0; - int num_urbs = 1; - int packet_offset = 0; - unsigned int packet_len; - unsigned char *urb_buffer = transfer->buffer; - - /* usbfs places arbitrary limits on iso URBs. this limit has changed - * at least three times, and it's difficult to accurately detect which - * limit this running kernel might impose. so we attempt to submit - * whatever the user has provided. if the kernel rejects the request - * due to its size, we return an error indicating such to the user. - */ - - /* calculate how many URBs we need */ - for (i = 0; i < num_packets; i++) { - unsigned int space_remaining = MAX_ISO_BUFFER_LENGTH - this_urb_len; - packet_len = transfer->iso_packet_desc[i].length; - - if (packet_len > space_remaining) { - num_urbs++; - this_urb_len = packet_len; - /* check that we can actually support this packet length */ - if (this_urb_len > MAX_ISO_BUFFER_LENGTH) - return LIBUSB_ERROR_INVALID_PARAM; - } else { - this_urb_len += packet_len; - } - } - usbi_dbg("need %d %dk URBs for transfer", num_urbs, MAX_ISO_BUFFER_LENGTH / 1024); - - urbs = calloc(num_urbs, sizeof(*urbs)); - if (!urbs) - return LIBUSB_ERROR_NO_MEM; - - tpriv->iso_urbs = urbs; - tpriv->num_urbs = num_urbs; - tpriv->num_retired = 0; - tpriv->reap_action = NORMAL; - tpriv->iso_packet_offset = 0; - - /* allocate + initialize each URB with the correct number of packets */ - for (i = 0; i < num_urbs; i++) { - struct usbfs_urb *urb; - unsigned int space_remaining_in_urb = MAX_ISO_BUFFER_LENGTH; - int urb_packet_offset = 0; - unsigned char *urb_buffer_orig = urb_buffer; - int j; - int k; - - /* swallow up all the packets we can fit into this URB */ - while (packet_offset < transfer->num_iso_packets) { - packet_len = transfer->iso_packet_desc[packet_offset].length; - if (packet_len <= space_remaining_in_urb) { - /* throw it in */ - urb_packet_offset++; - packet_offset++; - space_remaining_in_urb -= packet_len; - urb_buffer += packet_len; - } else { - /* it can't fit, save it for the next URB */ - break; - } - } - - alloc_size = sizeof(*urb) - + (urb_packet_offset * sizeof(struct usbfs_iso_packet_desc)); - urb = calloc(1, alloc_size); - if (!urb) { - free_iso_urbs(tpriv); - return LIBUSB_ERROR_NO_MEM; - } - urbs[i] = urb; - - /* populate packet lengths */ - for (j = 0, k = packet_offset - urb_packet_offset; - k < packet_offset; k++, j++) { - packet_len = transfer->iso_packet_desc[k].length; - urb->iso_frame_desc[j].length = packet_len; - } - - urb->usercontext = itransfer; - urb->type = USBFS_URB_TYPE_ISO; - /* FIXME: interface for non-ASAP data? */ - urb->flags = USBFS_URB_ISO_ASAP; - urb->endpoint = transfer->endpoint; - urb->number_of_packets = urb_packet_offset; - urb->buffer = urb_buffer_orig; - } - - /* submit URBs */ - for (i = 0; i < num_urbs; i++) { - int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]); - if (r < 0) { - if (errno == ENODEV) { - r = LIBUSB_ERROR_NO_DEVICE; - } else if (errno == EINVAL) { - usbi_warn(TRANSFER_CTX(transfer), - "submiturb failed, transfer too large"); - r = LIBUSB_ERROR_INVALID_PARAM; - } else { - usbi_err(TRANSFER_CTX(transfer), - "submiturb failed error %d errno=%d", r, errno); - r = LIBUSB_ERROR_IO; - } - - /* if the first URB submission fails, we can simply free up and - * return failure immediately. */ - if (i == 0) { - usbi_dbg("first URB failed, easy peasy"); - free_iso_urbs(tpriv); - return r; - } - - /* if it's not the first URB that failed, the situation is a bit - * tricky. we must discard all previous URBs. there are - * complications: - * - discarding is asynchronous - discarded urbs will be reaped - * later. the user must not have freed the transfer when the - * discarded URBs are reaped, otherwise libusb will be using - * freed memory. - * - the earlier URBs may have completed successfully and we do - * not want to throw away any data. - * so, in this case we discard all the previous URBs BUT we report - * that the transfer was submitted successfully. then later when - * the final discard completes we can report error to the user. - */ - tpriv->reap_action = SUBMIT_FAILED; - - /* The URBs we haven't submitted yet we count as already - * retired. */ - tpriv->num_retired = num_urbs - i; - discard_urbs(itransfer, 0, i); - - usbi_dbg("reporting successful submission but waiting for %d " - "discards before reporting error", i); - return 0; - } - } - - return 0; -} - -static int submit_control_transfer(struct usbi_transfer *itransfer) -{ - struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer); - struct libusb_transfer *transfer = - USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct linux_device_handle_priv *dpriv = - _device_handle_priv(transfer->dev_handle); - struct usbfs_urb *urb; - int r; - - if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH) - return LIBUSB_ERROR_INVALID_PARAM; - - urb = calloc(1, sizeof(struct usbfs_urb)); - if (!urb) - return LIBUSB_ERROR_NO_MEM; - tpriv->urbs = urb; - tpriv->num_urbs = 1; - tpriv->reap_action = NORMAL; - - urb->usercontext = itransfer; - urb->type = USBFS_URB_TYPE_CONTROL; - urb->endpoint = transfer->endpoint; - urb->buffer = transfer->buffer; - urb->buffer_length = transfer->length; - - r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb); - if (r < 0) { - free(urb); - tpriv->urbs = NULL; - if (errno == ENODEV) - return LIBUSB_ERROR_NO_DEVICE; - - usbi_err(TRANSFER_CTX(transfer), - "submiturb failed error %d errno=%d", r, errno); - return LIBUSB_ERROR_IO; - } - return 0; -} - -static int op_submit_transfer(struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer = - USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - - switch (transfer->type) { - case LIBUSB_TRANSFER_TYPE_CONTROL: - return submit_control_transfer(itransfer); - case LIBUSB_TRANSFER_TYPE_BULK: - case LIBUSB_TRANSFER_TYPE_BULK_STREAM: - return submit_bulk_transfer(itransfer); - case LIBUSB_TRANSFER_TYPE_INTERRUPT: - return submit_bulk_transfer(itransfer); - case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS: - return submit_iso_transfer(itransfer); - default: - usbi_err(TRANSFER_CTX(transfer), - "unknown endpoint type %d", transfer->type); - return LIBUSB_ERROR_INVALID_PARAM; - } -} - -static int op_cancel_transfer(struct usbi_transfer *itransfer) -{ - struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer); - struct libusb_transfer *transfer = - USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - int r; - - if (!tpriv->urbs) - return LIBUSB_ERROR_NOT_FOUND; - - r = discard_urbs(itransfer, 0, tpriv->num_urbs); - if (r != 0) - return r; - - switch (transfer->type) { - case LIBUSB_TRANSFER_TYPE_BULK: - case LIBUSB_TRANSFER_TYPE_BULK_STREAM: - if (tpriv->reap_action == ERROR) - break; - /* else, fall through */ - default: - tpriv->reap_action = CANCELLED; - } - - return 0; -} - -static void op_clear_transfer_priv(struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer = - USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer); - - /* urbs can be freed also in submit_transfer so lock mutex first */ - switch (transfer->type) { - case LIBUSB_TRANSFER_TYPE_CONTROL: - case LIBUSB_TRANSFER_TYPE_BULK: - case LIBUSB_TRANSFER_TYPE_BULK_STREAM: - case LIBUSB_TRANSFER_TYPE_INTERRUPT: - if (tpriv->urbs) { - free(tpriv->urbs); - tpriv->urbs = NULL; - } - break; - case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS: - if (tpriv->iso_urbs) { - free_iso_urbs(tpriv); - tpriv->iso_urbs = NULL; - } - break; - default: - usbi_err(TRANSFER_CTX(transfer), - "unknown endpoint type %d", transfer->type); - } -} - -static int handle_bulk_completion(struct usbi_transfer *itransfer, - struct usbfs_urb *urb) -{ - struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer); - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - int urb_idx = urb - tpriv->urbs; - - usbi_mutex_lock(&itransfer->lock); - usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status, - urb_idx + 1, tpriv->num_urbs); - - tpriv->num_retired++; - - if (tpriv->reap_action != NORMAL) { - /* cancelled, submit_fail, or completed early */ - usbi_dbg("abnormal reap: urb status %d", urb->status); - - /* even though we're in the process of cancelling, it's possible that - * we may receive some data in these URBs that we don't want to lose. - * examples: - * 1. while the kernel is cancelling all the packets that make up an - * URB, a few of them might complete. so we get back a successful - * cancellation *and* some data. - * 2. we receive a short URB which marks the early completion condition, - * so we start cancelling the remaining URBs. however, we're too - * slow and another URB completes (or at least completes partially). - * (this can't happen since we always use BULK_CONTINUATION.) - * - * When this happens, our objectives are not to lose any "surplus" data, - * and also to stick it at the end of the previously-received data - * (closing any holes), so that libusb reports the total amount of - * transferred data and presents it in a contiguous chunk. - */ - if (urb->actual_length > 0) { - unsigned char *target = transfer->buffer + itransfer->transferred; - usbi_dbg("received %d bytes of surplus data", urb->actual_length); - if (urb->buffer != target) { - usbi_dbg("moving surplus data from offset %d to offset %d", - (unsigned char *) urb->buffer - transfer->buffer, - target - transfer->buffer); - memmove(target, urb->buffer, urb->actual_length); - } - itransfer->transferred += urb->actual_length; - } - - if (tpriv->num_retired == tpriv->num_urbs) { - usbi_dbg("abnormal reap: last URB handled, reporting"); - if (tpriv->reap_action != COMPLETED_EARLY && - tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED) - tpriv->reap_status = LIBUSB_TRANSFER_ERROR; - goto completed; - } - goto out_unlock; - } - - itransfer->transferred += urb->actual_length; - - /* Many of these errors can occur on *any* urb of a multi-urb - * transfer. When they do, we tear down the rest of the transfer. - */ - switch (urb->status) { - case 0: - break; - case -EREMOTEIO: /* short transfer */ - break; - case -ENOENT: /* cancelled */ - case -ECONNRESET: - break; - case -ENODEV: - case -ESHUTDOWN: - usbi_dbg("device removed"); - tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE; - goto cancel_remaining; - case -EPIPE: - usbi_dbg("detected endpoint stall"); - if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED) - tpriv->reap_status = LIBUSB_TRANSFER_STALL; - goto cancel_remaining; - case -EOVERFLOW: - /* overflow can only ever occur in the last urb */ - usbi_dbg("overflow, actual_length=%d", urb->actual_length); - if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED) - tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW; - goto completed; - case -ETIME: - case -EPROTO: - case -EILSEQ: - case -ECOMM: - case -ENOSR: - usbi_dbg("low level error %d", urb->status); - tpriv->reap_action = ERROR; - goto cancel_remaining; - default: - usbi_warn(ITRANSFER_CTX(itransfer), - "unrecognised urb status %d", urb->status); - tpriv->reap_action = ERROR; - goto cancel_remaining; - } - - /* if we're the last urb or we got less data than requested then we're - * done */ - if (urb_idx == tpriv->num_urbs - 1) { - usbi_dbg("last URB in transfer --> complete!"); - goto completed; - } else if (urb->actual_length < urb->buffer_length) { - usbi_dbg("short transfer %d/%d --> complete!", - urb->actual_length, urb->buffer_length); - if (tpriv->reap_action == NORMAL) - tpriv->reap_action = COMPLETED_EARLY; - } else - goto out_unlock; - -cancel_remaining: - if (ERROR == tpriv->reap_action && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status) - tpriv->reap_status = LIBUSB_TRANSFER_ERROR; - - if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */ - goto completed; - - /* cancel remaining urbs and wait for their completion before - * reporting results */ - discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs); - -out_unlock: - usbi_mutex_unlock(&itransfer->lock); - return 0; - -completed: - free(tpriv->urbs); - tpriv->urbs = NULL; - usbi_mutex_unlock(&itransfer->lock); - return CANCELLED == tpriv->reap_action ? - usbi_handle_transfer_cancellation(itransfer) : - usbi_handle_transfer_completion(itransfer, tpriv->reap_status); -} - -static int handle_iso_completion(struct usbi_transfer *itransfer, - struct usbfs_urb *urb) -{ - struct libusb_transfer *transfer = - USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer); - int num_urbs = tpriv->num_urbs; - int urb_idx = 0; - int i; - enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED; - - usbi_mutex_lock(&itransfer->lock); - for (i = 0; i < num_urbs; i++) { - if (urb == tpriv->iso_urbs[i]) { - urb_idx = i + 1; - break; - } - } - if (urb_idx == 0) { - usbi_err(TRANSFER_CTX(transfer), "could not locate urb!"); - usbi_mutex_unlock(&itransfer->lock); - return LIBUSB_ERROR_NOT_FOUND; - } - - usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status, - urb_idx, num_urbs); - - /* copy isochronous results back in */ - - for (i = 0; i < urb->number_of_packets; i++) { - struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i]; - struct libusb_iso_packet_descriptor *lib_desc = - &transfer->iso_packet_desc[tpriv->iso_packet_offset++]; - lib_desc->status = LIBUSB_TRANSFER_COMPLETED; - switch (urb_desc->status) { - case 0: - break; - case -ENOENT: /* cancelled */ - case -ECONNRESET: - break; - case -ENODEV: - case -ESHUTDOWN: - usbi_dbg("device removed"); - lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE; - break; - case -EPIPE: - usbi_dbg("detected endpoint stall"); - lib_desc->status = LIBUSB_TRANSFER_STALL; - break; - case -EOVERFLOW: - usbi_dbg("overflow error"); - lib_desc->status = LIBUSB_TRANSFER_OVERFLOW; - break; - case -ETIME: - case -EPROTO: - case -EILSEQ: - case -ECOMM: - case -ENOSR: - case -EXDEV: - usbi_dbg("low-level USB error %d", urb_desc->status); - lib_desc->status = LIBUSB_TRANSFER_ERROR; - break; - default: - usbi_warn(TRANSFER_CTX(transfer), - "unrecognised urb status %d", urb_desc->status); - lib_desc->status = LIBUSB_TRANSFER_ERROR; - break; - } - lib_desc->actual_length = urb_desc->actual_length; - } - - tpriv->num_retired++; - - if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */ - usbi_dbg("CANCEL: urb status %d", urb->status); - - if (tpriv->num_retired == num_urbs) { - usbi_dbg("CANCEL: last URB handled, reporting"); - free_iso_urbs(tpriv); - if (tpriv->reap_action == CANCELLED) { - usbi_mutex_unlock(&itransfer->lock); - return usbi_handle_transfer_cancellation(itransfer); - } else { - usbi_mutex_unlock(&itransfer->lock); - return usbi_handle_transfer_completion(itransfer, - LIBUSB_TRANSFER_ERROR); - } - } - goto out; - } - - switch (urb->status) { - case 0: - break; - case -ENOENT: /* cancelled */ - case -ECONNRESET: - break; - case -ESHUTDOWN: - usbi_dbg("device removed"); - status = LIBUSB_TRANSFER_NO_DEVICE; - break; - default: - usbi_warn(TRANSFER_CTX(transfer), - "unrecognised urb status %d", urb->status); - status = LIBUSB_TRANSFER_ERROR; - break; - } - - /* if we're the last urb then we're done */ - if (urb_idx == num_urbs) { - usbi_dbg("last URB in transfer --> complete!"); - free_iso_urbs(tpriv); - usbi_mutex_unlock(&itransfer->lock); - return usbi_handle_transfer_completion(itransfer, status); - } - -out: - usbi_mutex_unlock(&itransfer->lock); - return 0; -} - -static int handle_control_completion(struct usbi_transfer *itransfer, - struct usbfs_urb *urb) -{ - struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer); - int status; - - usbi_mutex_lock(&itransfer->lock); - usbi_dbg("handling completion status %d", urb->status); - - itransfer->transferred += urb->actual_length; - - if (tpriv->reap_action == CANCELLED) { - if (urb->status != 0 && urb->status != -ENOENT) - usbi_warn(ITRANSFER_CTX(itransfer), - "cancel: unrecognised urb status %d", urb->status); - free(tpriv->urbs); - tpriv->urbs = NULL; - usbi_mutex_unlock(&itransfer->lock); - return usbi_handle_transfer_cancellation(itransfer); - } - - switch (urb->status) { - case 0: - status = LIBUSB_TRANSFER_COMPLETED; - break; - case -ENOENT: /* cancelled */ - status = LIBUSB_TRANSFER_CANCELLED; - break; - case -ENODEV: - case -ESHUTDOWN: - usbi_dbg("device removed"); - status = LIBUSB_TRANSFER_NO_DEVICE; - break; - case -EPIPE: - usbi_dbg("unsupported control request"); - status = LIBUSB_TRANSFER_STALL; - break; - case -EOVERFLOW: - usbi_dbg("control overflow error"); - status = LIBUSB_TRANSFER_OVERFLOW; - break; - case -ETIME: - case -EPROTO: - case -EILSEQ: - case -ECOMM: - case -ENOSR: - usbi_dbg("low-level bus error occurred"); - status = LIBUSB_TRANSFER_ERROR; - break; - default: - usbi_warn(ITRANSFER_CTX(itransfer), - "unrecognised urb status %d", urb->status); - status = LIBUSB_TRANSFER_ERROR; - break; - } - - free(tpriv->urbs); - tpriv->urbs = NULL; - usbi_mutex_unlock(&itransfer->lock); - return usbi_handle_transfer_completion(itransfer, status); -} - -static int reap_for_handle(struct libusb_device_handle *handle) -{ - struct linux_device_handle_priv *hpriv = _device_handle_priv(handle); - int r; - struct usbfs_urb *urb; - struct usbi_transfer *itransfer; - struct libusb_transfer *transfer; - - r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb); - if (r == -1 && errno == EAGAIN) - return 1; - if (r < 0) { - if (errno == ENODEV) - return LIBUSB_ERROR_NO_DEVICE; - - usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d", - r, errno); - return LIBUSB_ERROR_IO; - } - - itransfer = urb->usercontext; - transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - - usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status, - urb->actual_length); - - switch (transfer->type) { - case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS: - return handle_iso_completion(itransfer, urb); - case LIBUSB_TRANSFER_TYPE_BULK: - case LIBUSB_TRANSFER_TYPE_BULK_STREAM: - case LIBUSB_TRANSFER_TYPE_INTERRUPT: - return handle_bulk_completion(itransfer, urb); - case LIBUSB_TRANSFER_TYPE_CONTROL: - return handle_control_completion(itransfer, urb); - default: - usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x", - transfer->type); - return LIBUSB_ERROR_OTHER; - } -} - -static int op_handle_events(struct libusb_context *ctx, - struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready) -{ - int r; - unsigned int i = 0; - - usbi_mutex_lock(&ctx->open_devs_lock); - for (i = 0; i < nfds && num_ready > 0; i++) { - struct pollfd *pollfd = &fds[i]; - struct libusb_device_handle *handle; - struct linux_device_handle_priv *hpriv = NULL; - - if (!pollfd->revents) - continue; - - num_ready--; - list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) { - hpriv = _device_handle_priv(handle); - if (hpriv->fd == pollfd->fd) - break; - } - - if (!hpriv || hpriv->fd != pollfd->fd) { - usbi_err(ctx, "cannot find handle for fd %d", - pollfd->fd); - continue; - } - - if (pollfd->revents & POLLERR) { - /* remove the fd from the pollfd set so that it doesn't continuously - * trigger an event, and flag that it has been removed so op_close() - * doesn't try to remove it a second time */ - usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd); - hpriv->fd_removed = 1; - - /* device will still be marked as attached if hotplug monitor thread - * hasn't processed remove event yet */ - usbi_mutex_static_lock(&linux_hotplug_lock); - if (handle->dev->attached) - linux_device_disconnected(handle->dev->bus_number, - handle->dev->device_address); - usbi_mutex_static_unlock(&linux_hotplug_lock); - - if (hpriv->caps & USBFS_CAP_REAP_AFTER_DISCONNECT) { - do { - r = reap_for_handle(handle); - } while (r == 0); - } - - usbi_handle_disconnect(handle); - continue; - } - - do { - r = reap_for_handle(handle); - } while (r == 0); - if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE) - continue; - else if (r < 0) - goto out; - } - - r = 0; -out: - usbi_mutex_unlock(&ctx->open_devs_lock); - return r; -} - -static int op_clock_gettime(int clk_id, struct timespec *tp) -{ - switch (clk_id) { - case USBI_CLOCK_MONOTONIC: - return clock_gettime(monotonic_clkid, tp); - case USBI_CLOCK_REALTIME: - return clock_gettime(CLOCK_REALTIME, tp); - default: - return LIBUSB_ERROR_INVALID_PARAM; - } -} - -#ifdef USBI_TIMERFD_AVAILABLE -static clockid_t op_get_timerfd_clockid(void) -{ - return monotonic_clkid; - -} -#endif - -const struct usbi_os_backend linux_usbfs_backend = { - .name = "Linux usbfs", - .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER, - .init = op_init, - .exit = op_exit, - .get_device_list = NULL, - .hotplug_poll = op_hotplug_poll, - .get_device_descriptor = op_get_device_descriptor, - .get_active_config_descriptor = op_get_active_config_descriptor, - .get_config_descriptor = op_get_config_descriptor, - .get_config_descriptor_by_value = op_get_config_descriptor_by_value, - - .open = op_open, - .close = op_close, - .get_configuration = op_get_configuration, - .set_configuration = op_set_configuration, - .claim_interface = op_claim_interface, - .release_interface = op_release_interface, - - .set_interface_altsetting = op_set_interface, - .clear_halt = op_clear_halt, - .reset_device = op_reset_device, - - .alloc_streams = op_alloc_streams, - .free_streams = op_free_streams, - - .dev_mem_alloc = op_dev_mem_alloc, - .dev_mem_free = op_dev_mem_free, - - .kernel_driver_active = op_kernel_driver_active, - .detach_kernel_driver = op_detach_kernel_driver, - .attach_kernel_driver = op_attach_kernel_driver, - - .destroy_device = op_destroy_device, - - .submit_transfer = op_submit_transfer, - .cancel_transfer = op_cancel_transfer, - .clear_transfer_priv = op_clear_transfer_priv, - - .handle_events = op_handle_events, - - .clock_gettime = op_clock_gettime, - -#ifdef USBI_TIMERFD_AVAILABLE - .get_timerfd_clockid = op_get_timerfd_clockid, -#endif - - .device_priv_size = sizeof(struct linux_device_priv), - .device_handle_priv_size = sizeof(struct linux_device_handle_priv), - .transfer_priv_size = sizeof(struct linux_transfer_priv), -}; diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/linux_usbfs.h b/vendor/github.com/karalabe/hid/libusb/libusb/os/linux_usbfs.h deleted file mode 100644 index 8bd3ebcb..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/linux_usbfs.h +++ /dev/null @@ -1,193 +0,0 @@ -/* - * usbfs header structures - * Copyright © 2007 Daniel Drake - * Copyright © 2001 Johannes Erdfelt - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef LIBUSB_USBFS_H -#define LIBUSB_USBFS_H - -#include - -#define SYSFS_DEVICE_PATH "/sys/bus/usb/devices" - -struct usbfs_ctrltransfer { - /* keep in sync with usbdevice_fs.h:usbdevfs_ctrltransfer */ - uint8_t bmRequestType; - uint8_t bRequest; - uint16_t wValue; - uint16_t wIndex; - uint16_t wLength; - - uint32_t timeout; /* in milliseconds */ - - /* pointer to data */ - void *data; -}; - -struct usbfs_bulktransfer { - /* keep in sync with usbdevice_fs.h:usbdevfs_bulktransfer */ - unsigned int ep; - unsigned int len; - unsigned int timeout; /* in milliseconds */ - - /* pointer to data */ - void *data; -}; - -struct usbfs_setinterface { - /* keep in sync with usbdevice_fs.h:usbdevfs_setinterface */ - unsigned int interface; - unsigned int altsetting; -}; - -#define USBFS_MAXDRIVERNAME 255 - -struct usbfs_getdriver { - unsigned int interface; - char driver[USBFS_MAXDRIVERNAME + 1]; -}; - -#define USBFS_URB_SHORT_NOT_OK 0x01 -#define USBFS_URB_ISO_ASAP 0x02 -#define USBFS_URB_BULK_CONTINUATION 0x04 -#define USBFS_URB_QUEUE_BULK 0x10 -#define USBFS_URB_ZERO_PACKET 0x40 - -enum usbfs_urb_type { - USBFS_URB_TYPE_ISO = 0, - USBFS_URB_TYPE_INTERRUPT = 1, - USBFS_URB_TYPE_CONTROL = 2, - USBFS_URB_TYPE_BULK = 3, -}; - -struct usbfs_iso_packet_desc { - unsigned int length; - unsigned int actual_length; - unsigned int status; -}; - -#define MAX_ISO_BUFFER_LENGTH 49152 * 128 -#define MAX_BULK_BUFFER_LENGTH 16384 -#define MAX_CTRL_BUFFER_LENGTH 4096 - -struct usbfs_urb { - unsigned char type; - unsigned char endpoint; - int status; - unsigned int flags; - void *buffer; - int buffer_length; - int actual_length; - int start_frame; - union { - int number_of_packets; /* Only used for isoc urbs */ - unsigned int stream_id; /* Only used with bulk streams */ - }; - int error_count; - unsigned int signr; - void *usercontext; - struct usbfs_iso_packet_desc iso_frame_desc[0]; -}; - -struct usbfs_connectinfo { - unsigned int devnum; - unsigned char slow; -}; - -struct usbfs_ioctl { - int ifno; /* interface 0..N ; negative numbers reserved */ - int ioctl_code; /* MUST encode size + direction of data so the - * macros in give correct values */ - void *data; /* param buffer (in, or out) */ -}; - -struct usbfs_hub_portinfo { - unsigned char numports; - unsigned char port[127]; /* port to device num mapping */ -}; - -#define USBFS_CAP_ZERO_PACKET 0x01 -#define USBFS_CAP_BULK_CONTINUATION 0x02 -#define USBFS_CAP_NO_PACKET_SIZE_LIM 0x04 -#define USBFS_CAP_BULK_SCATTER_GATHER 0x08 -#define USBFS_CAP_REAP_AFTER_DISCONNECT 0x10 - -#define USBFS_DISCONNECT_CLAIM_IF_DRIVER 0x01 -#define USBFS_DISCONNECT_CLAIM_EXCEPT_DRIVER 0x02 - -struct usbfs_disconnect_claim { - unsigned int interface; - unsigned int flags; - char driver[USBFS_MAXDRIVERNAME + 1]; -}; - -struct usbfs_streams { - unsigned int num_streams; /* Not used by USBDEVFS_FREE_STREAMS */ - unsigned int num_eps; - unsigned char eps[0]; -}; - -#define IOCTL_USBFS_CONTROL _IOWR('U', 0, struct usbfs_ctrltransfer) -#define IOCTL_USBFS_BULK _IOWR('U', 2, struct usbfs_bulktransfer) -#define IOCTL_USBFS_RESETEP _IOR('U', 3, unsigned int) -#define IOCTL_USBFS_SETINTF _IOR('U', 4, struct usbfs_setinterface) -#define IOCTL_USBFS_SETCONFIG _IOR('U', 5, unsigned int) -#define IOCTL_USBFS_GETDRIVER _IOW('U', 8, struct usbfs_getdriver) -#define IOCTL_USBFS_SUBMITURB _IOR('U', 10, struct usbfs_urb) -#define IOCTL_USBFS_DISCARDURB _IO('U', 11) -#define IOCTL_USBFS_REAPURB _IOW('U', 12, void *) -#define IOCTL_USBFS_REAPURBNDELAY _IOW('U', 13, void *) -#define IOCTL_USBFS_CLAIMINTF _IOR('U', 15, unsigned int) -#define IOCTL_USBFS_RELEASEINTF _IOR('U', 16, unsigned int) -#define IOCTL_USBFS_CONNECTINFO _IOW('U', 17, struct usbfs_connectinfo) -#define IOCTL_USBFS_IOCTL _IOWR('U', 18, struct usbfs_ioctl) -#define IOCTL_USBFS_HUB_PORTINFO _IOR('U', 19, struct usbfs_hub_portinfo) -#define IOCTL_USBFS_RESET _IO('U', 20) -#define IOCTL_USBFS_CLEAR_HALT _IOR('U', 21, unsigned int) -#define IOCTL_USBFS_DISCONNECT _IO('U', 22) -#define IOCTL_USBFS_CONNECT _IO('U', 23) -#define IOCTL_USBFS_CLAIM_PORT _IOR('U', 24, unsigned int) -#define IOCTL_USBFS_RELEASE_PORT _IOR('U', 25, unsigned int) -#define IOCTL_USBFS_GET_CAPABILITIES _IOR('U', 26, __u32) -#define IOCTL_USBFS_DISCONNECT_CLAIM _IOR('U', 27, struct usbfs_disconnect_claim) -#define IOCTL_USBFS_ALLOC_STREAMS _IOR('U', 28, struct usbfs_streams) -#define IOCTL_USBFS_FREE_STREAMS _IOR('U', 29, struct usbfs_streams) - -extern usbi_mutex_static_t linux_hotplug_lock; - -#if defined(HAVE_LIBUDEV) -int linux_udev_start_event_monitor(void); -int linux_udev_stop_event_monitor(void); -int linux_udev_scan_devices(struct libusb_context *ctx); -void linux_udev_hotplug_poll(void); -#else -int linux_netlink_start_event_monitor(void); -int linux_netlink_stop_event_monitor(void); -void linux_netlink_hotplug_poll(void); -#endif - -void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name); -void linux_device_disconnected(uint8_t busnum, uint8_t devaddr); - -int linux_get_device_address (struct libusb_context *ctx, int detached, - uint8_t *busnum, uint8_t *devaddr, const char *dev_node, - const char *sys_name); -int linux_enumerate_device(struct libusb_context *ctx, - uint8_t busnum, uint8_t devaddr, const char *sysfs_dir); - -#endif diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/netbsd_usb.c b/vendor/github.com/karalabe/hid/libusb/libusb/os/netbsd_usb.c deleted file mode 100644 index ad1ede73..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/netbsd_usb.c +++ /dev/null @@ -1,677 +0,0 @@ -/* - * Copyright © 2011 Martin Pieuchot - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include - -#include -#include - -#include -#include -#include -#include -#include -#include - -#include - -#include "libusbi.h" - -struct device_priv { - char devnode[16]; - int fd; - - unsigned char *cdesc; /* active config descriptor */ - usb_device_descriptor_t ddesc; /* usb device descriptor */ -}; - -struct handle_priv { - int endpoints[USB_MAX_ENDPOINTS]; -}; - -/* - * Backend functions - */ -static int netbsd_get_device_list(struct libusb_context *, - struct discovered_devs **); -static int netbsd_open(struct libusb_device_handle *); -static void netbsd_close(struct libusb_device_handle *); - -static int netbsd_get_device_descriptor(struct libusb_device *, unsigned char *, - int *); -static int netbsd_get_active_config_descriptor(struct libusb_device *, - unsigned char *, size_t, int *); -static int netbsd_get_config_descriptor(struct libusb_device *, uint8_t, - unsigned char *, size_t, int *); - -static int netbsd_get_configuration(struct libusb_device_handle *, int *); -static int netbsd_set_configuration(struct libusb_device_handle *, int); - -static int netbsd_claim_interface(struct libusb_device_handle *, int); -static int netbsd_release_interface(struct libusb_device_handle *, int); - -static int netbsd_set_interface_altsetting(struct libusb_device_handle *, int, - int); -static int netbsd_clear_halt(struct libusb_device_handle *, unsigned char); -static int netbsd_reset_device(struct libusb_device_handle *); -static void netbsd_destroy_device(struct libusb_device *); - -static int netbsd_submit_transfer(struct usbi_transfer *); -static int netbsd_cancel_transfer(struct usbi_transfer *); -static void netbsd_clear_transfer_priv(struct usbi_transfer *); -static int netbsd_handle_transfer_completion(struct usbi_transfer *); -static int netbsd_clock_gettime(int, struct timespec *); - -/* - * Private functions - */ -static int _errno_to_libusb(int); -static int _cache_active_config_descriptor(struct libusb_device *, int); -static int _sync_control_transfer(struct usbi_transfer *); -static int _sync_gen_transfer(struct usbi_transfer *); -static int _access_endpoint(struct libusb_transfer *); - -const struct usbi_os_backend netbsd_backend = { - "Synchronous NetBSD backend", - 0, - NULL, /* init() */ - NULL, /* exit() */ - netbsd_get_device_list, - NULL, /* hotplug_poll */ - netbsd_open, - netbsd_close, - - netbsd_get_device_descriptor, - netbsd_get_active_config_descriptor, - netbsd_get_config_descriptor, - NULL, /* get_config_descriptor_by_value() */ - - netbsd_get_configuration, - netbsd_set_configuration, - - netbsd_claim_interface, - netbsd_release_interface, - - netbsd_set_interface_altsetting, - netbsd_clear_halt, - netbsd_reset_device, - - NULL, /* alloc_streams */ - NULL, /* free_streams */ - - NULL, /* dev_mem_alloc() */ - NULL, /* dev_mem_free() */ - - NULL, /* kernel_driver_active() */ - NULL, /* detach_kernel_driver() */ - NULL, /* attach_kernel_driver() */ - - netbsd_destroy_device, - - netbsd_submit_transfer, - netbsd_cancel_transfer, - netbsd_clear_transfer_priv, - - NULL, /* handle_events() */ - netbsd_handle_transfer_completion, - - netbsd_clock_gettime, - sizeof(struct device_priv), - sizeof(struct handle_priv), - 0, /* transfer_priv_size */ -}; - -int -netbsd_get_device_list(struct libusb_context * ctx, - struct discovered_devs **discdevs) -{ - struct libusb_device *dev; - struct device_priv *dpriv; - struct usb_device_info di; - unsigned long session_id; - char devnode[16]; - int fd, err, i; - - usbi_dbg(""); - - /* Only ugen(4) is supported */ - for (i = 0; i < USB_MAX_DEVICES; i++) { - /* Control endpoint is always .00 */ - snprintf(devnode, sizeof(devnode), "/dev/ugen%d.00", i); - - if ((fd = open(devnode, O_RDONLY)) < 0) { - if (errno != ENOENT && errno != ENXIO) - usbi_err(ctx, "could not open %s", devnode); - continue; - } - - if (ioctl(fd, USB_GET_DEVICEINFO, &di) < 0) - continue; - - session_id = (di.udi_bus << 8 | di.udi_addr); - dev = usbi_get_device_by_session_id(ctx, session_id); - - if (dev == NULL) { - dev = usbi_alloc_device(ctx, session_id); - if (dev == NULL) - return (LIBUSB_ERROR_NO_MEM); - - dev->bus_number = di.udi_bus; - dev->device_address = di.udi_addr; - dev->speed = di.udi_speed; - - dpriv = (struct device_priv *)dev->os_priv; - strlcpy(dpriv->devnode, devnode, sizeof(devnode)); - dpriv->fd = -1; - - if (ioctl(fd, USB_GET_DEVICE_DESC, &dpriv->ddesc) < 0) { - err = errno; - goto error; - } - - dpriv->cdesc = NULL; - if (_cache_active_config_descriptor(dev, fd)) { - err = errno; - goto error; - } - - if ((err = usbi_sanitize_device(dev))) - goto error; - } - close(fd); - - if (discovered_devs_append(*discdevs, dev) == NULL) - return (LIBUSB_ERROR_NO_MEM); - - libusb_unref_device(dev); - } - - return (LIBUSB_SUCCESS); - -error: - close(fd); - libusb_unref_device(dev); - return _errno_to_libusb(err); -} - -int -netbsd_open(struct libusb_device_handle *handle) -{ - struct handle_priv *hpriv = (struct handle_priv *)handle->os_priv; - struct device_priv *dpriv = (struct device_priv *)handle->dev->os_priv; - - dpriv->fd = open(dpriv->devnode, O_RDWR); - if (dpriv->fd < 0) { - dpriv->fd = open(dpriv->devnode, O_RDONLY); - if (dpriv->fd < 0) - return _errno_to_libusb(errno); - } - - usbi_dbg("open %s: fd %d", dpriv->devnode, dpriv->fd); - - return (LIBUSB_SUCCESS); -} - -void -netbsd_close(struct libusb_device_handle *handle) -{ - struct handle_priv *hpriv = (struct handle_priv *)handle->os_priv; - struct device_priv *dpriv = (struct device_priv *)handle->dev->os_priv; - - usbi_dbg("close: fd %d", dpriv->fd); - - close(dpriv->fd); - dpriv->fd = -1; -} - -int -netbsd_get_device_descriptor(struct libusb_device *dev, unsigned char *buf, - int *host_endian) -{ - struct device_priv *dpriv = (struct device_priv *)dev->os_priv; - - usbi_dbg(""); - - memcpy(buf, &dpriv->ddesc, DEVICE_DESC_LENGTH); - - *host_endian = 0; - - return (LIBUSB_SUCCESS); -} - -int -netbsd_get_active_config_descriptor(struct libusb_device *dev, - unsigned char *buf, size_t len, int *host_endian) -{ - struct device_priv *dpriv = (struct device_priv *)dev->os_priv; - usb_config_descriptor_t *ucd; - - ucd = (usb_config_descriptor_t *) dpriv->cdesc; - len = MIN(len, UGETW(ucd->wTotalLength)); - - usbi_dbg("len %d", len); - - memcpy(buf, dpriv->cdesc, len); - - *host_endian = 0; - - return len; -} - -int -netbsd_get_config_descriptor(struct libusb_device *dev, uint8_t idx, - unsigned char *buf, size_t len, int *host_endian) -{ - struct device_priv *dpriv = (struct device_priv *)dev->os_priv; - struct usb_full_desc ufd; - int fd, err; - - usbi_dbg("index %d, len %d", idx, len); - - /* A config descriptor may be requested before opening the device */ - if (dpriv->fd >= 0) { - fd = dpriv->fd; - } else { - fd = open(dpriv->devnode, O_RDONLY); - if (fd < 0) - return _errno_to_libusb(errno); - } - - ufd.ufd_config_index = idx; - ufd.ufd_size = len; - ufd.ufd_data = buf; - - if ((ioctl(fd, USB_GET_FULL_DESC, &ufd)) < 0) { - err = errno; - if (dpriv->fd < 0) - close(fd); - return _errno_to_libusb(err); - } - - if (dpriv->fd < 0) - close(fd); - - *host_endian = 0; - - return len; -} - -int -netbsd_get_configuration(struct libusb_device_handle *handle, int *config) -{ - struct device_priv *dpriv = (struct device_priv *)handle->dev->os_priv; - - usbi_dbg(""); - - if (ioctl(dpriv->fd, USB_GET_CONFIG, config) < 0) - return _errno_to_libusb(errno); - - usbi_dbg("configuration %d", *config); - - return (LIBUSB_SUCCESS); -} - -int -netbsd_set_configuration(struct libusb_device_handle *handle, int config) -{ - struct device_priv *dpriv = (struct device_priv *)handle->dev->os_priv; - - usbi_dbg("configuration %d", config); - - if (ioctl(dpriv->fd, USB_SET_CONFIG, &config) < 0) - return _errno_to_libusb(errno); - - return _cache_active_config_descriptor(handle->dev, dpriv->fd); -} - -int -netbsd_claim_interface(struct libusb_device_handle *handle, int iface) -{ - struct handle_priv *hpriv = (struct handle_priv *)handle->os_priv; - int i; - - for (i = 0; i < USB_MAX_ENDPOINTS; i++) - hpriv->endpoints[i] = -1; - - return (LIBUSB_SUCCESS); -} - -int -netbsd_release_interface(struct libusb_device_handle *handle, int iface) -{ - struct handle_priv *hpriv = (struct handle_priv *)handle->os_priv; - int i; - - for (i = 0; i < USB_MAX_ENDPOINTS; i++) - if (hpriv->endpoints[i] >= 0) - close(hpriv->endpoints[i]); - - return (LIBUSB_SUCCESS); -} - -int -netbsd_set_interface_altsetting(struct libusb_device_handle *handle, int iface, - int altsetting) -{ - struct device_priv *dpriv = (struct device_priv *)handle->dev->os_priv; - struct usb_alt_interface intf; - - usbi_dbg("iface %d, setting %d", iface, altsetting); - - memset(&intf, 0, sizeof(intf)); - - intf.uai_interface_index = iface; - intf.uai_alt_no = altsetting; - - if (ioctl(dpriv->fd, USB_SET_ALTINTERFACE, &intf) < 0) - return _errno_to_libusb(errno); - - return (LIBUSB_SUCCESS); -} - -int -netbsd_clear_halt(struct libusb_device_handle *handle, unsigned char endpoint) -{ - struct device_priv *dpriv = (struct device_priv *)handle->dev->os_priv; - struct usb_ctl_request req; - - usbi_dbg(""); - - req.ucr_request.bmRequestType = UT_WRITE_ENDPOINT; - req.ucr_request.bRequest = UR_CLEAR_FEATURE; - USETW(req.ucr_request.wValue, UF_ENDPOINT_HALT); - USETW(req.ucr_request.wIndex, endpoint); - USETW(req.ucr_request.wLength, 0); - - if (ioctl(dpriv->fd, USB_DO_REQUEST, &req) < 0) - return _errno_to_libusb(errno); - - return (LIBUSB_SUCCESS); -} - -int -netbsd_reset_device(struct libusb_device_handle *handle) -{ - usbi_dbg(""); - - return (LIBUSB_ERROR_NOT_SUPPORTED); -} - -void -netbsd_destroy_device(struct libusb_device *dev) -{ - struct device_priv *dpriv = (struct device_priv *)dev->os_priv; - - usbi_dbg(""); - - free(dpriv->cdesc); -} - -int -netbsd_submit_transfer(struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer; - struct handle_priv *hpriv; - int err = 0; - - usbi_dbg(""); - - transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - hpriv = (struct handle_priv *)transfer->dev_handle->os_priv; - - switch (transfer->type) { - case LIBUSB_TRANSFER_TYPE_CONTROL: - err = _sync_control_transfer(itransfer); - break; - case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS: - if (IS_XFEROUT(transfer)) { - /* Isochronous write is not supported */ - err = LIBUSB_ERROR_NOT_SUPPORTED; - break; - } - err = _sync_gen_transfer(itransfer); - break; - case LIBUSB_TRANSFER_TYPE_BULK: - case LIBUSB_TRANSFER_TYPE_INTERRUPT: - if (IS_XFEROUT(transfer) && - transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) { - err = LIBUSB_ERROR_NOT_SUPPORTED; - break; - } - err = _sync_gen_transfer(itransfer); - break; - case LIBUSB_TRANSFER_TYPE_BULK_STREAM: - err = LIBUSB_ERROR_NOT_SUPPORTED; - break; - } - - if (err) - return (err); - - usbi_signal_transfer_completion(itransfer); - - return (LIBUSB_SUCCESS); -} - -int -netbsd_cancel_transfer(struct usbi_transfer *itransfer) -{ - usbi_dbg(""); - - return (LIBUSB_ERROR_NOT_SUPPORTED); -} - -void -netbsd_clear_transfer_priv(struct usbi_transfer *itransfer) -{ - usbi_dbg(""); - - /* Nothing to do */ -} - -int -netbsd_handle_transfer_completion(struct usbi_transfer *itransfer) -{ - return usbi_handle_transfer_completion(itransfer, LIBUSB_TRANSFER_COMPLETED); -} - -int -netbsd_clock_gettime(int clkid, struct timespec *tp) -{ - usbi_dbg("clock %d", clkid); - - if (clkid == USBI_CLOCK_REALTIME) - return clock_gettime(CLOCK_REALTIME, tp); - - if (clkid == USBI_CLOCK_MONOTONIC) - return clock_gettime(CLOCK_MONOTONIC, tp); - - return (LIBUSB_ERROR_INVALID_PARAM); -} - -int -_errno_to_libusb(int err) -{ - switch (err) { - case EIO: - return (LIBUSB_ERROR_IO); - case EACCES: - return (LIBUSB_ERROR_ACCESS); - case ENOENT: - return (LIBUSB_ERROR_NO_DEVICE); - case ENOMEM: - return (LIBUSB_ERROR_NO_MEM); - } - - usbi_dbg("error: %s", strerror(err)); - - return (LIBUSB_ERROR_OTHER); -} - -int -_cache_active_config_descriptor(struct libusb_device *dev, int fd) -{ - struct device_priv *dpriv = (struct device_priv *)dev->os_priv; - struct usb_config_desc ucd; - struct usb_full_desc ufd; - unsigned char* buf; - int len; - - usbi_dbg("fd %d", fd); - - ucd.ucd_config_index = USB_CURRENT_CONFIG_INDEX; - - if ((ioctl(fd, USB_GET_CONFIG_DESC, &ucd)) < 0) - return _errno_to_libusb(errno); - - usbi_dbg("active bLength %d", ucd.ucd_desc.bLength); - - len = UGETW(ucd.ucd_desc.wTotalLength); - buf = malloc(len); - if (buf == NULL) - return (LIBUSB_ERROR_NO_MEM); - - ufd.ufd_config_index = ucd.ucd_config_index; - ufd.ufd_size = len; - ufd.ufd_data = buf; - - usbi_dbg("index %d, len %d", ufd.ufd_config_index, len); - - if ((ioctl(fd, USB_GET_FULL_DESC, &ufd)) < 0) { - free(buf); - return _errno_to_libusb(errno); - } - - if (dpriv->cdesc) - free(dpriv->cdesc); - dpriv->cdesc = buf; - - return (0); -} - -int -_sync_control_transfer(struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer; - struct libusb_control_setup *setup; - struct device_priv *dpriv; - struct usb_ctl_request req; - - transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - dpriv = (struct device_priv *)transfer->dev_handle->dev->os_priv; - setup = (struct libusb_control_setup *)transfer->buffer; - - usbi_dbg("type %d request %d value %d index %d length %d timeout %d", - setup->bmRequestType, setup->bRequest, - libusb_le16_to_cpu(setup->wValue), - libusb_le16_to_cpu(setup->wIndex), - libusb_le16_to_cpu(setup->wLength), transfer->timeout); - - req.ucr_request.bmRequestType = setup->bmRequestType; - req.ucr_request.bRequest = setup->bRequest; - /* Don't use USETW, libusb already deals with the endianness */ - (*(uint16_t *)req.ucr_request.wValue) = setup->wValue; - (*(uint16_t *)req.ucr_request.wIndex) = setup->wIndex; - (*(uint16_t *)req.ucr_request.wLength) = setup->wLength; - req.ucr_data = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE; - - if ((transfer->flags & LIBUSB_TRANSFER_SHORT_NOT_OK) == 0) - req.ucr_flags = USBD_SHORT_XFER_OK; - - if ((ioctl(dpriv->fd, USB_SET_TIMEOUT, &transfer->timeout)) < 0) - return _errno_to_libusb(errno); - - if ((ioctl(dpriv->fd, USB_DO_REQUEST, &req)) < 0) - return _errno_to_libusb(errno); - - itransfer->transferred = req.ucr_actlen; - - usbi_dbg("transferred %d", itransfer->transferred); - - return (0); -} - -int -_access_endpoint(struct libusb_transfer *transfer) -{ - struct handle_priv *hpriv; - struct device_priv *dpriv; - char *s, devnode[16]; - int fd, endpt; - mode_t mode; - - hpriv = (struct handle_priv *)transfer->dev_handle->os_priv; - dpriv = (struct device_priv *)transfer->dev_handle->dev->os_priv; - - endpt = UE_GET_ADDR(transfer->endpoint); - mode = IS_XFERIN(transfer) ? O_RDONLY : O_WRONLY; - - usbi_dbg("endpoint %d mode %d", endpt, mode); - - if (hpriv->endpoints[endpt] < 0) { - /* Pick the right node given the control one */ - strlcpy(devnode, dpriv->devnode, sizeof(devnode)); - s = strchr(devnode, '.'); - snprintf(s, 4, ".%02d", endpt); - - /* We may need to read/write to the same endpoint later. */ - if (((fd = open(devnode, O_RDWR)) < 0) && (errno == ENXIO)) - if ((fd = open(devnode, mode)) < 0) - return (-1); - - hpriv->endpoints[endpt] = fd; - } - - return (hpriv->endpoints[endpt]); -} - -int -_sync_gen_transfer(struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer; - int fd, nr = 1; - - transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - - /* - * Bulk, Interrupt or Isochronous transfer depends on the - * endpoint and thus the node to open. - */ - if ((fd = _access_endpoint(transfer)) < 0) - return _errno_to_libusb(errno); - - if ((ioctl(fd, USB_SET_TIMEOUT, &transfer->timeout)) < 0) - return _errno_to_libusb(errno); - - if (IS_XFERIN(transfer)) { - if ((transfer->flags & LIBUSB_TRANSFER_SHORT_NOT_OK) == 0) - if ((ioctl(fd, USB_SET_SHORT_XFER, &nr)) < 0) - return _errno_to_libusb(errno); - - nr = read(fd, transfer->buffer, transfer->length); - } else { - nr = write(fd, transfer->buffer, transfer->length); - } - - if (nr < 0) - return _errno_to_libusb(errno); - - itransfer->transferred = nr; - - return (0); -} diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/openbsd_usb.c b/vendor/github.com/karalabe/hid/libusb/libusb/os/openbsd_usb.c deleted file mode 100644 index c6602571..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/openbsd_usb.c +++ /dev/null @@ -1,771 +0,0 @@ -/* - * Copyright © 2011-2013 Martin Pieuchot - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include - -#include -#include - -#include -#include -#include -#include -#include -#include - -#include - -#include "libusbi.h" - -struct device_priv { - char *devname; /* name of the ugen(4) node */ - int fd; /* device file descriptor */ - - unsigned char *cdesc; /* active config descriptor */ - usb_device_descriptor_t ddesc; /* usb device descriptor */ -}; - -struct handle_priv { - int endpoints[USB_MAX_ENDPOINTS]; -}; - -/* - * Backend functions - */ -static int obsd_get_device_list(struct libusb_context *, - struct discovered_devs **); -static int obsd_open(struct libusb_device_handle *); -static void obsd_close(struct libusb_device_handle *); - -static int obsd_get_device_descriptor(struct libusb_device *, unsigned char *, - int *); -static int obsd_get_active_config_descriptor(struct libusb_device *, - unsigned char *, size_t, int *); -static int obsd_get_config_descriptor(struct libusb_device *, uint8_t, - unsigned char *, size_t, int *); - -static int obsd_get_configuration(struct libusb_device_handle *, int *); -static int obsd_set_configuration(struct libusb_device_handle *, int); - -static int obsd_claim_interface(struct libusb_device_handle *, int); -static int obsd_release_interface(struct libusb_device_handle *, int); - -static int obsd_set_interface_altsetting(struct libusb_device_handle *, int, - int); -static int obsd_clear_halt(struct libusb_device_handle *, unsigned char); -static int obsd_reset_device(struct libusb_device_handle *); -static void obsd_destroy_device(struct libusb_device *); - -static int obsd_submit_transfer(struct usbi_transfer *); -static int obsd_cancel_transfer(struct usbi_transfer *); -static void obsd_clear_transfer_priv(struct usbi_transfer *); -static int obsd_handle_transfer_completion(struct usbi_transfer *); -static int obsd_clock_gettime(int, struct timespec *); - -/* - * Private functions - */ -static int _errno_to_libusb(int); -static int _cache_active_config_descriptor(struct libusb_device *); -static int _sync_control_transfer(struct usbi_transfer *); -static int _sync_gen_transfer(struct usbi_transfer *); -static int _access_endpoint(struct libusb_transfer *); - -static int _bus_open(int); - - -const struct usbi_os_backend openbsd_backend = { - "Synchronous OpenBSD backend", - 0, - NULL, /* init() */ - NULL, /* exit() */ - obsd_get_device_list, - NULL, /* hotplug_poll */ - obsd_open, - obsd_close, - - obsd_get_device_descriptor, - obsd_get_active_config_descriptor, - obsd_get_config_descriptor, - NULL, /* get_config_descriptor_by_value() */ - - obsd_get_configuration, - obsd_set_configuration, - - obsd_claim_interface, - obsd_release_interface, - - obsd_set_interface_altsetting, - obsd_clear_halt, - obsd_reset_device, - - NULL, /* alloc_streams */ - NULL, /* free_streams */ - - NULL, /* dev_mem_alloc() */ - NULL, /* dev_mem_free() */ - - NULL, /* kernel_driver_active() */ - NULL, /* detach_kernel_driver() */ - NULL, /* attach_kernel_driver() */ - - obsd_destroy_device, - - obsd_submit_transfer, - obsd_cancel_transfer, - obsd_clear_transfer_priv, - - NULL, /* handle_events() */ - obsd_handle_transfer_completion, - - obsd_clock_gettime, - sizeof(struct device_priv), - sizeof(struct handle_priv), - 0, /* transfer_priv_size */ -}; - -#define DEVPATH "/dev/" -#define USBDEV DEVPATH "usb" - -int -obsd_get_device_list(struct libusb_context * ctx, - struct discovered_devs **discdevs) -{ - struct discovered_devs *ddd; - struct libusb_device *dev; - struct device_priv *dpriv; - struct usb_device_info di; - struct usb_device_ddesc dd; - unsigned long session_id; - char devices[USB_MAX_DEVICES]; - char busnode[16]; - char *udevname; - int fd, addr, i, j; - - usbi_dbg(""); - - for (i = 0; i < 8; i++) { - snprintf(busnode, sizeof(busnode), USBDEV "%d", i); - - if ((fd = open(busnode, O_RDWR)) < 0) { - if (errno != ENOENT && errno != ENXIO) - usbi_err(ctx, "could not open %s", busnode); - continue; - } - - bzero(devices, sizeof(devices)); - for (addr = 1; addr < USB_MAX_DEVICES; addr++) { - if (devices[addr]) - continue; - - di.udi_addr = addr; - if (ioctl(fd, USB_DEVICEINFO, &di) < 0) - continue; - - /* - * XXX If ugen(4) is attached to the USB device - * it will be used. - */ - udevname = NULL; - for (j = 0; j < USB_MAX_DEVNAMES; j++) - if (!strncmp("ugen", di.udi_devnames[j], 4)) { - udevname = strdup(di.udi_devnames[j]); - break; - } - - session_id = (di.udi_bus << 8 | di.udi_addr); - dev = usbi_get_device_by_session_id(ctx, session_id); - - if (dev == NULL) { - dev = usbi_alloc_device(ctx, session_id); - if (dev == NULL) { - close(fd); - return (LIBUSB_ERROR_NO_MEM); - } - - dev->bus_number = di.udi_bus; - dev->device_address = di.udi_addr; - dev->speed = di.udi_speed; - - dpriv = (struct device_priv *)dev->os_priv; - dpriv->fd = -1; - dpriv->cdesc = NULL; - dpriv->devname = udevname; - - dd.udd_bus = di.udi_bus; - dd.udd_addr = di.udi_addr; - if (ioctl(fd, USB_DEVICE_GET_DDESC, &dd) < 0) { - libusb_unref_device(dev); - continue; - } - dpriv->ddesc = dd.udd_desc; - - if (_cache_active_config_descriptor(dev)) { - libusb_unref_device(dev); - continue; - } - - if (usbi_sanitize_device(dev)) { - libusb_unref_device(dev); - continue; - } - } - - ddd = discovered_devs_append(*discdevs, dev); - if (ddd == NULL) { - close(fd); - return (LIBUSB_ERROR_NO_MEM); - } - libusb_unref_device(dev); - - *discdevs = ddd; - devices[addr] = 1; - } - - close(fd); - } - - return (LIBUSB_SUCCESS); -} - -int -obsd_open(struct libusb_device_handle *handle) -{ - struct handle_priv *hpriv = (struct handle_priv *)handle->os_priv; - struct device_priv *dpriv = (struct device_priv *)handle->dev->os_priv; - char devnode[16]; - - if (dpriv->devname) { - /* - * Only open ugen(4) attached devices read-write, all - * read-only operations are done through the bus node. - */ - snprintf(devnode, sizeof(devnode), DEVPATH "%s.00", - dpriv->devname); - dpriv->fd = open(devnode, O_RDWR); - if (dpriv->fd < 0) - return _errno_to_libusb(errno); - - usbi_dbg("open %s: fd %d", devnode, dpriv->fd); - } - - return (LIBUSB_SUCCESS); -} - -void -obsd_close(struct libusb_device_handle *handle) -{ - struct handle_priv *hpriv = (struct handle_priv *)handle->os_priv; - struct device_priv *dpriv = (struct device_priv *)handle->dev->os_priv; - - if (dpriv->devname) { - usbi_dbg("close: fd %d", dpriv->fd); - - close(dpriv->fd); - dpriv->fd = -1; - } -} - -int -obsd_get_device_descriptor(struct libusb_device *dev, unsigned char *buf, - int *host_endian) -{ - struct device_priv *dpriv = (struct device_priv *)dev->os_priv; - - usbi_dbg(""); - - memcpy(buf, &dpriv->ddesc, DEVICE_DESC_LENGTH); - - *host_endian = 0; - - return (LIBUSB_SUCCESS); -} - -int -obsd_get_active_config_descriptor(struct libusb_device *dev, - unsigned char *buf, size_t len, int *host_endian) -{ - struct device_priv *dpriv = (struct device_priv *)dev->os_priv; - usb_config_descriptor_t *ucd = (usb_config_descriptor_t *)dpriv->cdesc; - - len = MIN(len, UGETW(ucd->wTotalLength)); - - usbi_dbg("len %d", len); - - memcpy(buf, dpriv->cdesc, len); - - *host_endian = 0; - - return (len); -} - -int -obsd_get_config_descriptor(struct libusb_device *dev, uint8_t idx, - unsigned char *buf, size_t len, int *host_endian) -{ - struct usb_device_fdesc udf; - int fd, err; - - if ((fd = _bus_open(dev->bus_number)) < 0) - return _errno_to_libusb(errno); - - udf.udf_bus = dev->bus_number; - udf.udf_addr = dev->device_address; - udf.udf_config_index = idx; - udf.udf_size = len; - udf.udf_data = buf; - - usbi_dbg("index %d, len %d", udf.udf_config_index, len); - - if (ioctl(fd, USB_DEVICE_GET_FDESC, &udf) < 0) { - err = errno; - close(fd); - return _errno_to_libusb(err); - } - close(fd); - - *host_endian = 0; - - return (len); -} - -int -obsd_get_configuration(struct libusb_device_handle *handle, int *config) -{ - struct device_priv *dpriv = (struct device_priv *)handle->dev->os_priv; - usb_config_descriptor_t *ucd = (usb_config_descriptor_t *)dpriv->cdesc; - - *config = ucd->bConfigurationValue; - - usbi_dbg("bConfigurationValue %d", *config); - - return (LIBUSB_SUCCESS); -} - -int -obsd_set_configuration(struct libusb_device_handle *handle, int config) -{ - struct device_priv *dpriv = (struct device_priv *)handle->dev->os_priv; - - if (dpriv->devname == NULL) - return (LIBUSB_ERROR_NOT_SUPPORTED); - - usbi_dbg("bConfigurationValue %d", config); - - if (ioctl(dpriv->fd, USB_SET_CONFIG, &config) < 0) - return _errno_to_libusb(errno); - - return _cache_active_config_descriptor(handle->dev); -} - -int -obsd_claim_interface(struct libusb_device_handle *handle, int iface) -{ - struct handle_priv *hpriv = (struct handle_priv *)handle->os_priv; - int i; - - for (i = 0; i < USB_MAX_ENDPOINTS; i++) - hpriv->endpoints[i] = -1; - - return (LIBUSB_SUCCESS); -} - -int -obsd_release_interface(struct libusb_device_handle *handle, int iface) -{ - struct handle_priv *hpriv = (struct handle_priv *)handle->os_priv; - int i; - - for (i = 0; i < USB_MAX_ENDPOINTS; i++) - if (hpriv->endpoints[i] >= 0) - close(hpriv->endpoints[i]); - - return (LIBUSB_SUCCESS); -} - -int -obsd_set_interface_altsetting(struct libusb_device_handle *handle, int iface, - int altsetting) -{ - struct device_priv *dpriv = (struct device_priv *)handle->dev->os_priv; - struct usb_alt_interface intf; - - if (dpriv->devname == NULL) - return (LIBUSB_ERROR_NOT_SUPPORTED); - - usbi_dbg("iface %d, setting %d", iface, altsetting); - - memset(&intf, 0, sizeof(intf)); - - intf.uai_interface_index = iface; - intf.uai_alt_no = altsetting; - - if (ioctl(dpriv->fd, USB_SET_ALTINTERFACE, &intf) < 0) - return _errno_to_libusb(errno); - - return (LIBUSB_SUCCESS); -} - -int -obsd_clear_halt(struct libusb_device_handle *handle, unsigned char endpoint) -{ - struct usb_ctl_request req; - int fd, err; - - if ((fd = _bus_open(handle->dev->bus_number)) < 0) - return _errno_to_libusb(errno); - - usbi_dbg(""); - - req.ucr_addr = handle->dev->device_address; - req.ucr_request.bmRequestType = UT_WRITE_ENDPOINT; - req.ucr_request.bRequest = UR_CLEAR_FEATURE; - USETW(req.ucr_request.wValue, UF_ENDPOINT_HALT); - USETW(req.ucr_request.wIndex, endpoint); - USETW(req.ucr_request.wLength, 0); - - if (ioctl(fd, USB_REQUEST, &req) < 0) { - err = errno; - close(fd); - return _errno_to_libusb(err); - } - close(fd); - - return (LIBUSB_SUCCESS); -} - -int -obsd_reset_device(struct libusb_device_handle *handle) -{ - usbi_dbg(""); - - return (LIBUSB_ERROR_NOT_SUPPORTED); -} - -void -obsd_destroy_device(struct libusb_device *dev) -{ - struct device_priv *dpriv = (struct device_priv *)dev->os_priv; - - usbi_dbg(""); - - free(dpriv->cdesc); - free(dpriv->devname); -} - -int -obsd_submit_transfer(struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer; - struct handle_priv *hpriv; - int err = 0; - - usbi_dbg(""); - - transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - hpriv = (struct handle_priv *)transfer->dev_handle->os_priv; - - switch (transfer->type) { - case LIBUSB_TRANSFER_TYPE_CONTROL: - err = _sync_control_transfer(itransfer); - break; - case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS: - if (IS_XFEROUT(transfer)) { - /* Isochronous write is not supported */ - err = LIBUSB_ERROR_NOT_SUPPORTED; - break; - } - err = _sync_gen_transfer(itransfer); - break; - case LIBUSB_TRANSFER_TYPE_BULK: - case LIBUSB_TRANSFER_TYPE_INTERRUPT: - if (IS_XFEROUT(transfer) && - transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) { - err = LIBUSB_ERROR_NOT_SUPPORTED; - break; - } - err = _sync_gen_transfer(itransfer); - break; - case LIBUSB_TRANSFER_TYPE_BULK_STREAM: - err = LIBUSB_ERROR_NOT_SUPPORTED; - break; - } - - if (err) - return (err); - - usbi_signal_transfer_completion(itransfer); - - return (LIBUSB_SUCCESS); -} - -int -obsd_cancel_transfer(struct usbi_transfer *itransfer) -{ - usbi_dbg(""); - - return (LIBUSB_ERROR_NOT_SUPPORTED); -} - -void -obsd_clear_transfer_priv(struct usbi_transfer *itransfer) -{ - usbi_dbg(""); - - /* Nothing to do */ -} - -int -obsd_handle_transfer_completion(struct usbi_transfer *itransfer) -{ - return usbi_handle_transfer_completion(itransfer, LIBUSB_TRANSFER_COMPLETED); -} - -int -obsd_clock_gettime(int clkid, struct timespec *tp) -{ - usbi_dbg("clock %d", clkid); - - if (clkid == USBI_CLOCK_REALTIME) - return clock_gettime(CLOCK_REALTIME, tp); - - if (clkid == USBI_CLOCK_MONOTONIC) - return clock_gettime(CLOCK_MONOTONIC, tp); - - return (LIBUSB_ERROR_INVALID_PARAM); -} - -int -_errno_to_libusb(int err) -{ - usbi_dbg("error: %s (%d)", strerror(err), err); - - switch (err) { - case EIO: - return (LIBUSB_ERROR_IO); - case EACCES: - return (LIBUSB_ERROR_ACCESS); - case ENOENT: - return (LIBUSB_ERROR_NO_DEVICE); - case ENOMEM: - return (LIBUSB_ERROR_NO_MEM); - case ETIMEDOUT: - return (LIBUSB_ERROR_TIMEOUT); - } - - return (LIBUSB_ERROR_OTHER); -} - -int -_cache_active_config_descriptor(struct libusb_device *dev) -{ - struct device_priv *dpriv = (struct device_priv *)dev->os_priv; - struct usb_device_cdesc udc; - struct usb_device_fdesc udf; - unsigned char* buf; - int fd, len, err; - - if ((fd = _bus_open(dev->bus_number)) < 0) - return _errno_to_libusb(errno); - - usbi_dbg("fd %d, addr %d", fd, dev->device_address); - - udc.udc_bus = dev->bus_number; - udc.udc_addr = dev->device_address; - udc.udc_config_index = USB_CURRENT_CONFIG_INDEX; - if (ioctl(fd, USB_DEVICE_GET_CDESC, &udc) < 0) { - err = errno; - close(fd); - return _errno_to_libusb(errno); - } - - usbi_dbg("active bLength %d", udc.udc_desc.bLength); - - len = UGETW(udc.udc_desc.wTotalLength); - buf = malloc(len); - if (buf == NULL) - return (LIBUSB_ERROR_NO_MEM); - - udf.udf_bus = dev->bus_number; - udf.udf_addr = dev->device_address; - udf.udf_config_index = udc.udc_config_index; - udf.udf_size = len; - udf.udf_data = buf; - - usbi_dbg("index %d, len %d", udf.udf_config_index, len); - - if (ioctl(fd, USB_DEVICE_GET_FDESC, &udf) < 0) { - err = errno; - close(fd); - free(buf); - return _errno_to_libusb(err); - } - close(fd); - - if (dpriv->cdesc) - free(dpriv->cdesc); - dpriv->cdesc = buf; - - return (LIBUSB_SUCCESS); -} - -int -_sync_control_transfer(struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer; - struct libusb_control_setup *setup; - struct device_priv *dpriv; - struct usb_ctl_request req; - - transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - dpriv = (struct device_priv *)transfer->dev_handle->dev->os_priv; - setup = (struct libusb_control_setup *)transfer->buffer; - - usbi_dbg("type %x request %x value %x index %d length %d timeout %d", - setup->bmRequestType, setup->bRequest, - libusb_le16_to_cpu(setup->wValue), - libusb_le16_to_cpu(setup->wIndex), - libusb_le16_to_cpu(setup->wLength), transfer->timeout); - - req.ucr_addr = transfer->dev_handle->dev->device_address; - req.ucr_request.bmRequestType = setup->bmRequestType; - req.ucr_request.bRequest = setup->bRequest; - /* Don't use USETW, libusb already deals with the endianness */ - (*(uint16_t *)req.ucr_request.wValue) = setup->wValue; - (*(uint16_t *)req.ucr_request.wIndex) = setup->wIndex; - (*(uint16_t *)req.ucr_request.wLength) = setup->wLength; - req.ucr_data = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE; - - if ((transfer->flags & LIBUSB_TRANSFER_SHORT_NOT_OK) == 0) - req.ucr_flags = USBD_SHORT_XFER_OK; - - if (dpriv->devname == NULL) { - /* - * XXX If the device is not attached to ugen(4) it is - * XXX still possible to submit a control transfer but - * XXX with the default timeout only. - */ - int fd, err; - - if ((fd = _bus_open(transfer->dev_handle->dev->bus_number)) < 0) - return _errno_to_libusb(errno); - - if ((ioctl(fd, USB_REQUEST, &req)) < 0) { - err = errno; - close(fd); - return _errno_to_libusb(err); - } - close(fd); - } else { - if ((ioctl(dpriv->fd, USB_SET_TIMEOUT, &transfer->timeout)) < 0) - return _errno_to_libusb(errno); - - if ((ioctl(dpriv->fd, USB_DO_REQUEST, &req)) < 0) - return _errno_to_libusb(errno); - } - - itransfer->transferred = req.ucr_actlen; - - usbi_dbg("transferred %d", itransfer->transferred); - - return (0); -} - -int -_access_endpoint(struct libusb_transfer *transfer) -{ - struct handle_priv *hpriv; - struct device_priv *dpriv; - char devnode[16]; - int fd, endpt; - mode_t mode; - - hpriv = (struct handle_priv *)transfer->dev_handle->os_priv; - dpriv = (struct device_priv *)transfer->dev_handle->dev->os_priv; - - endpt = UE_GET_ADDR(transfer->endpoint); - mode = IS_XFERIN(transfer) ? O_RDONLY : O_WRONLY; - - usbi_dbg("endpoint %d mode %d", endpt, mode); - - if (hpriv->endpoints[endpt] < 0) { - /* Pick the right endpoint node */ - snprintf(devnode, sizeof(devnode), DEVPATH "%s.%02d", - dpriv->devname, endpt); - - /* We may need to read/write to the same endpoint later. */ - if (((fd = open(devnode, O_RDWR)) < 0) && (errno == ENXIO)) - if ((fd = open(devnode, mode)) < 0) - return (-1); - - hpriv->endpoints[endpt] = fd; - } - - return (hpriv->endpoints[endpt]); -} - -int -_sync_gen_transfer(struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer; - struct device_priv *dpriv; - int fd, nr = 1; - - transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - dpriv = (struct device_priv *)transfer->dev_handle->dev->os_priv; - - if (dpriv->devname == NULL) - return (LIBUSB_ERROR_NOT_SUPPORTED); - - /* - * Bulk, Interrupt or Isochronous transfer depends on the - * endpoint and thus the node to open. - */ - if ((fd = _access_endpoint(transfer)) < 0) - return _errno_to_libusb(errno); - - if ((ioctl(fd, USB_SET_TIMEOUT, &transfer->timeout)) < 0) - return _errno_to_libusb(errno); - - if (IS_XFERIN(transfer)) { - if ((transfer->flags & LIBUSB_TRANSFER_SHORT_NOT_OK) == 0) - if ((ioctl(fd, USB_SET_SHORT_XFER, &nr)) < 0) - return _errno_to_libusb(errno); - - nr = read(fd, transfer->buffer, transfer->length); - } else { - nr = write(fd, transfer->buffer, transfer->length); - } - - if (nr < 0) - return _errno_to_libusb(errno); - - itransfer->transferred = nr; - - return (0); -} - -int -_bus_open(int number) -{ - char busnode[16]; - - snprintf(busnode, sizeof(busnode), USBDEV "%d", number); - - return open(busnode, O_RDWR); -} diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/poll_posix.c b/vendor/github.com/karalabe/hid/libusb/libusb/os/poll_posix.c deleted file mode 100644 index e2f55a57..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/poll_posix.c +++ /dev/null @@ -1,53 +0,0 @@ -/* - * poll_posix: poll compatibility wrapper for POSIX systems - * Copyright © 2013 RealVNC Ltd. - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -#include - -#include -#include -#include -#include - -#include "libusbi.h" - -int usbi_pipe(int pipefd[2]) -{ - int ret = pipe(pipefd); - if (ret != 0) { - return ret; - } - ret = fcntl(pipefd[1], F_GETFL); - if (ret == -1) { - usbi_dbg("Failed to get pipe fd flags: %d", errno); - goto err_close_pipe; - } - ret = fcntl(pipefd[1], F_SETFL, ret | O_NONBLOCK); - if (ret != 0) { - usbi_dbg("Failed to set non-blocking on new pipe: %d", errno); - goto err_close_pipe; - } - - return 0; - -err_close_pipe: - usbi_close(pipefd[0]); - usbi_close(pipefd[1]); - return ret; -} diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/poll_posix.h b/vendor/github.com/karalabe/hid/libusb/libusb/os/poll_posix.h deleted file mode 100644 index 5b4b2c90..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/poll_posix.h +++ /dev/null @@ -1,11 +0,0 @@ -#ifndef LIBUSB_POLL_POSIX_H -#define LIBUSB_POLL_POSIX_H - -#define usbi_write write -#define usbi_read read -#define usbi_close close -#define usbi_poll poll - -int usbi_pipe(int pipefd[2]); - -#endif /* LIBUSB_POLL_POSIX_H */ diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/poll_windows.c b/vendor/github.com/karalabe/hid/libusb/libusb/os/poll_windows.c deleted file mode 100644 index 98256075..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/poll_windows.c +++ /dev/null @@ -1,728 +0,0 @@ -/* - * poll_windows: poll compatibility wrapper for Windows - * Copyright © 2012-2013 RealVNC Ltd. - * Copyright © 2009-2010 Pete Batard - * With contributions from Michael Plante, Orin Eman et al. - * Parts of poll implementation from libusb-win32, by Stephan Meyer et al. - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -/* - * poll() and pipe() Windows compatibility layer for libusb 1.0 - * - * The way this layer works is by using OVERLAPPED with async I/O transfers, as - * OVERLAPPED have an associated event which is flagged for I/O completion. - * - * For USB pollable async I/O, you would typically: - * - obtain a Windows HANDLE to a file or device that has been opened in - * OVERLAPPED mode - * - call usbi_create_fd with this handle to obtain a custom fd. - * Note that if you need simultaneous R/W access, you need to call create_fd - * twice, once in RW_READ and once in RW_WRITE mode to obtain 2 separate - * pollable fds - * - leave the core functions call the poll routine and flag POLLIN/POLLOUT - * - * The pipe pollable synchronous I/O works using the overlapped event associated - * with a fake pipe. The read/write functions are only meant to be used in that - * context. - */ -#include - -#include -#include -#include - -#include "libusbi.h" - -// Uncomment to debug the polling layer -//#define DEBUG_POLL_WINDOWS -#if defined(DEBUG_POLL_WINDOWS) -#define poll_dbg usbi_dbg -#else -// MSVC++ < 2005 cannot use a variadic argument and non MSVC -// compilers produce warnings if parenthesis are omitted. -#if defined(_MSC_VER) && (_MSC_VER < 1400) -#define poll_dbg -#else -#define poll_dbg(...) -#endif -#endif - -#if defined(_PREFAST_) -#pragma warning(disable:28719) -#endif - -#define CHECK_INIT_POLLING do {if(!is_polling_set) init_polling();} while(0) - -// public fd data -const struct winfd INVALID_WINFD = {-1, INVALID_HANDLE_VALUE, NULL, NULL, NULL, RW_NONE}; -struct winfd poll_fd[MAX_FDS]; -// internal fd data -struct { - CRITICAL_SECTION mutex; // lock for fds - // Additional variables for XP CancelIoEx partial emulation - HANDLE original_handle; - DWORD thread_id; -} _poll_fd[MAX_FDS]; - -// globals -BOOLEAN is_polling_set = FALSE; -LONG pipe_number = 0; -static volatile LONG compat_spinlock = 0; - -#if !defined(_WIN32_WCE) -// CancelIoEx, available on Vista and later only, provides the ability to cancel -// a single transfer (OVERLAPPED) when used. As it may not be part of any of the -// platform headers, we hook into the Kernel32 system DLL directly to seek it. -static BOOL (__stdcall *pCancelIoEx)(HANDLE, LPOVERLAPPED) = NULL; -#define Use_Duplicate_Handles (pCancelIoEx == NULL) - -static inline void setup_cancel_io(void) -{ - HMODULE hKernel32 = GetModuleHandleA("KERNEL32"); - if (hKernel32 != NULL) { - pCancelIoEx = (BOOL (__stdcall *)(HANDLE,LPOVERLAPPED)) - GetProcAddress(hKernel32, "CancelIoEx"); - } - usbi_dbg("Will use CancelIo%s for I/O cancellation", - Use_Duplicate_Handles?"":"Ex"); -} - -static inline BOOL cancel_io(int _index) -{ - if ((_index < 0) || (_index >= MAX_FDS)) { - return FALSE; - } - - if ( (poll_fd[_index].fd < 0) || (poll_fd[_index].handle == INVALID_HANDLE_VALUE) - || (poll_fd[_index].handle == 0) || (poll_fd[_index].overlapped == NULL) ) { - return TRUE; - } - if (poll_fd[_index].itransfer && poll_fd[_index].cancel_fn) { - // Cancel outstanding transfer via the specific callback - (*poll_fd[_index].cancel_fn)(poll_fd[_index].itransfer); - return TRUE; - } - if (pCancelIoEx != NULL) { - return (*pCancelIoEx)(poll_fd[_index].handle, poll_fd[_index].overlapped); - } - if (_poll_fd[_index].thread_id == GetCurrentThreadId()) { - return CancelIo(poll_fd[_index].handle); - } - usbi_warn(NULL, "Unable to cancel I/O that was started from another thread"); - return FALSE; -} -#else -#define Use_Duplicate_Handles FALSE - -static __inline void setup_cancel_io() -{ - // No setup needed on WinCE -} - -static __inline BOOL cancel_io(int _index) -{ - if ((_index < 0) || (_index >= MAX_FDS)) { - return FALSE; - } - if ( (poll_fd[_index].fd < 0) || (poll_fd[_index].handle == INVALID_HANDLE_VALUE) - || (poll_fd[_index].handle == 0) || (poll_fd[_index].overlapped == NULL) ) { - return TRUE; - } - if (poll_fd[_index].itransfer && poll_fd[_index].cancel_fn) { - // Cancel outstanding transfer via the specific callback - (*poll_fd[_index].cancel_fn)(poll_fd[_index].itransfer); - } - return TRUE; -} -#endif - -// Init -void init_polling(void) -{ - int i; - - while (InterlockedExchange((LONG *)&compat_spinlock, 1) == 1) { - SleepEx(0, TRUE); - } - if (!is_polling_set) { - setup_cancel_io(); - for (i=0; ihEvent = CreateEvent(NULL, TRUE, FALSE, NULL); - if(overlapped->hEvent == NULL) { - free (overlapped); - return NULL; - } - return overlapped; -} - -static void free_overlapped(OVERLAPPED *overlapped) -{ - if (overlapped == NULL) - return; - - if ( (overlapped->hEvent != 0) - && (overlapped->hEvent != INVALID_HANDLE_VALUE) ) { - CloseHandle(overlapped->hEvent); - } - free(overlapped); -} - -void exit_polling(void) -{ - int i; - - while (InterlockedExchange((LONG *)&compat_spinlock, 1) == 1) { - SleepEx(0, TRUE); - } - if (is_polling_set) { - is_polling_set = FALSE; - - for (i=0; iInternal = STATUS_PENDING; - overlapped->InternalHigh = 0; - - for (i=0; i= 0) { - LeaveCriticalSection(&_poll_fd[i].mutex); - continue; - } - - // Use index as the unique fd number - poll_fd[i].fd = i; - // Read end of the "pipe" - filedes[0] = poll_fd[i].fd; - // We can use the same handle for both ends - filedes[1] = filedes[0]; - - poll_fd[i].handle = DUMMY_HANDLE; - poll_fd[i].overlapped = overlapped; - // There's no polling on the write end, so we just use READ for our needs - poll_fd[i].rw = RW_READ; - _poll_fd[i].original_handle = INVALID_HANDLE_VALUE; - LeaveCriticalSection(&_poll_fd[i].mutex); - return 0; - } - } - free_overlapped(overlapped); - return -1; -} - -/* - * Create both an fd and an OVERLAPPED from an open Windows handle, so that - * it can be used with our polling function - * The handle MUST support overlapped transfers (usually requires CreateFile - * with FILE_FLAG_OVERLAPPED) - * Return a pollable file descriptor struct, or INVALID_WINFD on error - * - * Note that the fd returned by this function is a per-transfer fd, rather - * than a per-session fd and cannot be used for anything else but our - * custom functions (the fd itself points to the NUL: device) - * if you plan to do R/W on the same handle, you MUST create 2 fds: one for - * read and one for write. Using a single R/W fd is unsupported and will - * produce unexpected results - */ -struct winfd usbi_create_fd(HANDLE handle, int access_mode, struct usbi_transfer *itransfer, cancel_transfer *cancel_fn) -{ - int i; - struct winfd wfd = INVALID_WINFD; - OVERLAPPED* overlapped = NULL; - - CHECK_INIT_POLLING; - - if ((handle == 0) || (handle == INVALID_HANDLE_VALUE)) { - return INVALID_WINFD; - } - - wfd.itransfer = itransfer; - wfd.cancel_fn = cancel_fn; - - if ((access_mode != RW_READ) && (access_mode != RW_WRITE)) { - usbi_warn(NULL, "only one of RW_READ or RW_WRITE are supported. " - "If you want to poll for R/W simultaneously, create multiple fds from the same handle."); - return INVALID_WINFD; - } - if (access_mode == RW_READ) { - wfd.rw = RW_READ; - } else { - wfd.rw = RW_WRITE; - } - - overlapped = create_overlapped(); - if(overlapped == NULL) { - return INVALID_WINFD; - } - - for (i=0; i= 0) { - LeaveCriticalSection(&_poll_fd[i].mutex); - continue; - } - // Use index as the unique fd number - wfd.fd = i; - // Attempt to emulate some of the CancelIoEx behaviour on platforms - // that don't have it - if (Use_Duplicate_Handles) { - _poll_fd[i].thread_id = GetCurrentThreadId(); - if (!DuplicateHandle(GetCurrentProcess(), handle, GetCurrentProcess(), - &wfd.handle, 0, TRUE, DUPLICATE_SAME_ACCESS)) { - usbi_dbg("could not duplicate handle for CancelIo - using original one"); - wfd.handle = handle; - // Make sure we won't close the original handle on fd deletion then - _poll_fd[i].original_handle = INVALID_HANDLE_VALUE; - } else { - _poll_fd[i].original_handle = handle; - } - } else { - wfd.handle = handle; - } - wfd.overlapped = overlapped; - memcpy(&poll_fd[i], &wfd, sizeof(struct winfd)); - LeaveCriticalSection(&_poll_fd[i].mutex); - return wfd; - } - } - free_overlapped(overlapped); - return INVALID_WINFD; -} - -static void _free_index(int _index) -{ - // Cancel any async IO (Don't care about the validity of our handles for this) - cancel_io(_index); - // close the duplicate handle (if we have an actual duplicate) - if (Use_Duplicate_Handles) { - if (_poll_fd[_index].original_handle != INVALID_HANDLE_VALUE) { - CloseHandle(poll_fd[_index].handle); - } - _poll_fd[_index].original_handle = INVALID_HANDLE_VALUE; - _poll_fd[_index].thread_id = 0; - } - free_overlapped(poll_fd[_index].overlapped); - poll_fd[_index] = INVALID_WINFD; -} - -/* - * Release a pollable file descriptor. - * - * Note that the associated Windows handle is not closed by this call - */ -void usbi_free_fd(struct winfd *wfd) -{ - int _index; - - CHECK_INIT_POLLING; - - _index = _fd_to_index_and_lock(wfd->fd); - if (_index < 0) { - return; - } - _free_index(_index); - *wfd = INVALID_WINFD; - LeaveCriticalSection(&_poll_fd[_index].mutex); -} - -/* - * The functions below perform various conversions between fd, handle and OVERLAPPED - */ -struct winfd fd_to_winfd(int fd) -{ - int i; - struct winfd wfd; - - CHECK_INIT_POLLING; - - if (fd < 0) - return INVALID_WINFD; - - for (i=0; i= 0) { - LeaveCriticalSection(&_poll_fd[_index].mutex); - } - usbi_warn(NULL, "invalid fd"); - triggered = -1; - goto poll_exit; - } - - // IN or OUT must match our fd direction - if ((fds[i].events & POLLIN) && (poll_fd[_index].rw != RW_READ)) { - fds[i].revents |= POLLNVAL | POLLERR; - errno = EBADF; - usbi_warn(NULL, "attempted POLLIN on fd without READ access"); - LeaveCriticalSection(&_poll_fd[_index].mutex); - triggered = -1; - goto poll_exit; - } - - if ((fds[i].events & POLLOUT) && (poll_fd[_index].rw != RW_WRITE)) { - fds[i].revents |= POLLNVAL | POLLERR; - errno = EBADF; - usbi_warn(NULL, "attempted POLLOUT on fd without WRITE access"); - LeaveCriticalSection(&_poll_fd[_index].mutex); - triggered = -1; - goto poll_exit; - } - - // The following macro only works if overlapped I/O was reported pending - if ( (HasOverlappedIoCompleted(poll_fd[_index].overlapped)) - || (HasOverlappedIoCompletedSync(poll_fd[_index].overlapped)) ) { - poll_dbg(" completed"); - // checks above should ensure this works: - fds[i].revents = fds[i].events; - triggered++; - } else { - handles_to_wait_on[nb_handles_to_wait_on] = poll_fd[_index].overlapped->hEvent; - handle_to_index[nb_handles_to_wait_on] = i; - nb_handles_to_wait_on++; - } - LeaveCriticalSection(&_poll_fd[_index].mutex); - } - - // If nothing was triggered, wait on all fds that require it - if ((timeout != 0) && (triggered == 0) && (nb_handles_to_wait_on != 0)) { - if (timeout < 0) { - poll_dbg("starting infinite wait for %u handles...", (unsigned int)nb_handles_to_wait_on); - } else { - poll_dbg("starting %d ms wait for %u handles...", timeout, (unsigned int)nb_handles_to_wait_on); - } - ret = WaitForMultipleObjects(nb_handles_to_wait_on, handles_to_wait_on, - FALSE, (timeout<0)?INFINITE:(DWORD)timeout); - object_index = ret-WAIT_OBJECT_0; - if ((object_index >= 0) && ((DWORD)object_index < nb_handles_to_wait_on)) { - poll_dbg(" completed after wait"); - i = handle_to_index[object_index]; - _index = _fd_to_index_and_lock(fds[i].fd); - fds[i].revents = fds[i].events; - triggered++; - if (_index >= 0) { - LeaveCriticalSection(&_poll_fd[_index].mutex); - } - } else if (ret == WAIT_TIMEOUT) { - poll_dbg(" timed out"); - triggered = 0; // 0 = timeout - } else { - errno = EIO; - triggered = -1; // error - } - } - -poll_exit: - if (handles_to_wait_on != NULL) { - free(handles_to_wait_on); - } - if (handle_to_index != NULL) { - free(handle_to_index); - } - return triggered; -} - -/* - * close a fake pipe fd - */ -int usbi_close(int fd) -{ - int _index; - int r = -1; - - CHECK_INIT_POLLING; - - _index = _fd_to_index_and_lock(fd); - - if (_index < 0) { - errno = EBADF; - } else { - free_overlapped(poll_fd[_index].overlapped); - poll_fd[_index] = INVALID_WINFD; - LeaveCriticalSection(&_poll_fd[_index].mutex); - } - return r; -} - -/* - * synchronous write for fake "pipe" signaling - */ -ssize_t usbi_write(int fd, const void *buf, size_t count) -{ - int _index; - UNUSED(buf); - - CHECK_INIT_POLLING; - - if (count != sizeof(unsigned char)) { - usbi_err(NULL, "this function should only used for signaling"); - return -1; - } - - _index = _fd_to_index_and_lock(fd); - - if ( (_index < 0) || (poll_fd[_index].overlapped == NULL) ) { - errno = EBADF; - if (_index >= 0) { - LeaveCriticalSection(&_poll_fd[_index].mutex); - } - return -1; - } - - poll_dbg("set pipe event (fd = %d, thread = %08X)", _index, (unsigned int)GetCurrentThreadId()); - SetEvent(poll_fd[_index].overlapped->hEvent); - poll_fd[_index].overlapped->Internal = STATUS_WAIT_0; - // If two threads write on the pipe at the same time, we need to - // process two separate reads => use the overlapped as a counter - poll_fd[_index].overlapped->InternalHigh++; - - LeaveCriticalSection(&_poll_fd[_index].mutex); - return sizeof(unsigned char); -} - -/* - * synchronous read for fake "pipe" signaling - */ -ssize_t usbi_read(int fd, void *buf, size_t count) -{ - int _index; - ssize_t r = -1; - UNUSED(buf); - - CHECK_INIT_POLLING; - - if (count != sizeof(unsigned char)) { - usbi_err(NULL, "this function should only used for signaling"); - return -1; - } - - _index = _fd_to_index_and_lock(fd); - - if (_index < 0) { - errno = EBADF; - return -1; - } - - if (WaitForSingleObject(poll_fd[_index].overlapped->hEvent, INFINITE) != WAIT_OBJECT_0) { - usbi_warn(NULL, "waiting for event failed: %u", (unsigned int)GetLastError()); - errno = EIO; - goto out; - } - - poll_dbg("clr pipe event (fd = %d, thread = %08X)", _index, (unsigned int)GetCurrentThreadId()); - poll_fd[_index].overlapped->InternalHigh--; - // Don't reset unless we don't have any more events to process - if (poll_fd[_index].overlapped->InternalHigh <= 0) { - ResetEvent(poll_fd[_index].overlapped->hEvent); - poll_fd[_index].overlapped->Internal = STATUS_PENDING; - } - - r = sizeof(unsigned char); - -out: - LeaveCriticalSection(&_poll_fd[_index].mutex); - return r; -} diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/poll_windows.h b/vendor/github.com/karalabe/hid/libusb/libusb/os/poll_windows.h deleted file mode 100644 index aa4c985d..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/poll_windows.h +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Windows compat: POSIX compatibility wrapper - * Copyright © 2012-2013 RealVNC Ltd. - * Copyright © 2009-2010 Pete Batard - * With contributions from Michael Plante, Orin Eman et al. - * Parts of poll implementation from libusb-win32, by Stephan Meyer et al. - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - */ -#pragma once - -#if defined(_MSC_VER) -// disable /W4 MSVC warnings that are benign -#pragma warning(disable:4127) // conditional expression is constant -#endif - -// Handle synchronous completion through the overlapped structure -#if !defined(STATUS_REPARSE) // reuse the REPARSE status code -#define STATUS_REPARSE ((LONG)0x00000104L) -#endif -#define STATUS_COMPLETED_SYNCHRONOUSLY STATUS_REPARSE -#if defined(_WIN32_WCE) -// WinCE doesn't have a HasOverlappedIoCompleted() macro, so attempt to emulate it -#define HasOverlappedIoCompleted(lpOverlapped) (((DWORD)(lpOverlapped)->Internal) != STATUS_PENDING) -#endif -#define HasOverlappedIoCompletedSync(lpOverlapped) (((DWORD)(lpOverlapped)->Internal) == STATUS_COMPLETED_SYNCHRONOUSLY) - -#define DUMMY_HANDLE ((HANDLE)(LONG_PTR)-2) - -/* Windows versions */ -enum windows_version { - WINDOWS_CE = -2, - WINDOWS_UNDEFINED = -1, - WINDOWS_UNSUPPORTED = 0, - WINDOWS_XP = 0x51, - WINDOWS_2003 = 0x52, // Also XP x64 - WINDOWS_VISTA = 0x60, - WINDOWS_7 = 0x61, - WINDOWS_8 = 0x62, - WINDOWS_8_1_OR_LATER = 0x63, - WINDOWS_MAX -}; -extern int windows_version; - -#define MAX_FDS 256 - -#define POLLIN 0x0001 /* There is data to read */ -#define POLLPRI 0x0002 /* There is urgent data to read */ -#define POLLOUT 0x0004 /* Writing now will not block */ -#define POLLERR 0x0008 /* Error condition */ -#define POLLHUP 0x0010 /* Hung up */ -#define POLLNVAL 0x0020 /* Invalid request: fd not open */ - -struct pollfd { - int fd; /* file descriptor */ - short events; /* requested events */ - short revents; /* returned events */ -}; - -// access modes -enum rw_type { - RW_NONE, - RW_READ, - RW_WRITE, -}; - -// fd struct that can be used for polling on Windows -typedef int cancel_transfer(struct usbi_transfer *itransfer); - -struct winfd { - int fd; // what's exposed to libusb core - HANDLE handle; // what we need to attach overlapped to the I/O op, so we can poll it - OVERLAPPED* overlapped; // what will report our I/O status - struct usbi_transfer *itransfer; // Associated transfer, or NULL if completed - cancel_transfer *cancel_fn; // Function pointer to cancel transfer API - enum rw_type rw; // I/O transfer direction: read *XOR* write (NOT BOTH) -}; -extern const struct winfd INVALID_WINFD; - -int usbi_pipe(int pipefd[2]); -int usbi_poll(struct pollfd *fds, unsigned int nfds, int timeout); -ssize_t usbi_write(int fd, const void *buf, size_t count); -ssize_t usbi_read(int fd, void *buf, size_t count); -int usbi_close(int fd); - -void init_polling(void); -void exit_polling(void); -struct winfd usbi_create_fd(HANDLE handle, int access_mode, - struct usbi_transfer *transfer, cancel_transfer *cancel_fn); -void usbi_free_fd(struct winfd* winfd); -struct winfd fd_to_winfd(int fd); -struct winfd handle_to_winfd(HANDLE handle); -struct winfd overlapped_to_winfd(OVERLAPPED* overlapped); - -/* - * Timeval operations - */ -#if defined(DDKBUILD) -#include // defines timeval functions on DDK -#endif - -#if !defined(TIMESPEC_TO_TIMEVAL) -#define TIMESPEC_TO_TIMEVAL(tv, ts) { \ - (tv)->tv_sec = (long)(ts)->tv_sec; \ - (tv)->tv_usec = (long)(ts)->tv_nsec / 1000; \ -} -#endif -#if !defined(timersub) -#define timersub(a, b, result) \ -do { \ - (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \ - (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \ - if ((result)->tv_usec < 0) { \ - --(result)->tv_sec; \ - (result)->tv_usec += 1000000; \ - } \ -} while (0) -#endif diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/sunos_usb.c b/vendor/github.com/karalabe/hid/libusb/libusb/os/sunos_usb.c deleted file mode 100644 index cb608976..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/sunos_usb.c +++ /dev/null @@ -1,1292 +0,0 @@ -/* - * - * Copyright (c) 2016, Oracle and/or its affiliates. - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "libusbi.h" -#include "sunos_usb.h" - -/* - * Backend functions - */ -static int sunos_init(struct libusb_context *); -static void sunos_exit(void); -static int sunos_get_device_list(struct libusb_context *, - struct discovered_devs **); -static int sunos_open(struct libusb_device_handle *); -static void sunos_close(struct libusb_device_handle *); -static int sunos_get_device_descriptor(struct libusb_device *, - uint8_t*, int *); -static int sunos_get_active_config_descriptor(struct libusb_device *, - uint8_t*, size_t, int *); -static int sunos_get_config_descriptor(struct libusb_device *, uint8_t, - uint8_t*, size_t, int *); -static int sunos_get_configuration(struct libusb_device_handle *, int *); -static int sunos_set_configuration(struct libusb_device_handle *, int); -static int sunos_claim_interface(struct libusb_device_handle *, int); -static int sunos_release_interface(struct libusb_device_handle *, int); -static int sunos_set_interface_altsetting(struct libusb_device_handle *, - int, int); -static int sunos_clear_halt(struct libusb_device_handle *, uint8_t); -static int sunos_reset_device(struct libusb_device_handle *); -static void sunos_destroy_device(struct libusb_device *); -static int sunos_submit_transfer(struct usbi_transfer *); -static int sunos_cancel_transfer(struct usbi_transfer *); -static void sunos_clear_transfer_priv(struct usbi_transfer *); -static int sunos_handle_transfer_completion(struct usbi_transfer *); -static int sunos_clock_gettime(int, struct timespec *); - -/* - * Private functions - */ -static int _errno_to_libusb(int); -static int sunos_usb_get_status(int fd); - -static int sunos_init(struct libusb_context *ctx) -{ - return (LIBUSB_SUCCESS); -} - -static void sunos_exit(void) -{ - usbi_dbg(""); -} - -static int -sunos_fill_in_dev_info(di_node_t node, struct libusb_device *dev) -{ - int proplen; - int n, *addr, *port_prop; - char *phypath; - uint8_t *rdata; - struct libusb_device_descriptor *descr; - sunos_dev_priv_t *dpriv = (sunos_dev_priv_t *)dev->os_priv; - - /* Device descriptors */ - proplen = di_prop_lookup_bytes(DDI_DEV_T_ANY, node, - "usb-dev-descriptor", &rdata); - if (proplen <= 0) { - - return (LIBUSB_ERROR_IO); - } - - descr = (struct libusb_device_descriptor *)rdata; - bcopy(descr, &dpriv->dev_descr, LIBUSB_DT_DEVICE_SIZE); - dpriv->dev_descr.bcdUSB = libusb_cpu_to_le16(descr->bcdUSB); - dpriv->dev_descr.idVendor = libusb_cpu_to_le16(descr->idVendor); - dpriv->dev_descr.idProduct = libusb_cpu_to_le16(descr->idProduct); - dpriv->dev_descr.bcdDevice = libusb_cpu_to_le16(descr->bcdDevice); - - /* Raw configuration descriptors */ - proplen = di_prop_lookup_bytes(DDI_DEV_T_ANY, node, - "usb-raw-cfg-descriptors", &rdata); - if (proplen <= 0) { - usbi_dbg("can't find raw config descriptors"); - - return (LIBUSB_ERROR_IO); - } - dpriv->raw_cfgdescr = calloc(1, proplen); - if (dpriv->raw_cfgdescr == NULL) { - return (LIBUSB_ERROR_NO_MEM); - } else { - bcopy(rdata, dpriv->raw_cfgdescr, proplen); - dpriv->cfgvalue = ((struct libusb_config_descriptor *) - rdata)->bConfigurationValue; - } - - n = di_prop_lookup_ints(DDI_DEV_T_ANY, node, "reg", &port_prop); - - if ((n != 1) || (*port_prop <= 0)) { - return (LIBUSB_ERROR_IO); - } - dev->port_number = *port_prop; - - /* device physical path */ - phypath = di_devfs_path(node); - if (phypath) { - dpriv->phypath = strdup(phypath); - di_devfs_path_free(phypath); - } else { - free(dpriv->raw_cfgdescr); - - return (LIBUSB_ERROR_IO); - } - - /* address */ - n = di_prop_lookup_ints(DDI_DEV_T_ANY, node, "assigned-address", &addr); - if (n != 1 || *addr == 0) { - usbi_dbg("can't get address"); - } else { - dev->device_address = *addr; - } - - /* speed */ - if (di_prop_exists(DDI_DEV_T_ANY, node, "low-speed") == 1) { - dev->speed = LIBUSB_SPEED_LOW; - } else if (di_prop_exists(DDI_DEV_T_ANY, node, "high-speed") == 1) { - dev->speed = LIBUSB_SPEED_HIGH; - } else if (di_prop_exists(DDI_DEV_T_ANY, node, "full-speed") == 1) { - dev->speed = LIBUSB_SPEED_FULL; - } else if (di_prop_exists(DDI_DEV_T_ANY, node, "super-speed") == 1) { - dev->speed = LIBUSB_SPEED_SUPER; - } - - usbi_dbg("vid=%x pid=%x, path=%s, bus_nmber=0x%x, port_number=%d, " - "speed=%d", dpriv->dev_descr.idVendor, dpriv->dev_descr.idProduct, - dpriv->phypath, dev->bus_number, dev->port_number, dev->speed); - - return (LIBUSB_SUCCESS); -} - - -static int -sunos_add_devices(di_devlink_t link, void *arg) -{ - struct devlink_cbarg *largs = (struct devlink_cbarg *)arg; - struct node_args *nargs; - di_node_t myself, pnode; - uint64_t session_id = 0; - uint16_t bdf = 0; - struct libusb_device *dev; - sunos_dev_priv_t *devpriv; - const char *path, *newpath; - int n, i; - int *addr_prop; - uint8_t bus_number = 0; - - nargs = (struct node_args *)largs->nargs; - myself = largs->myself; - if (nargs->last_ugenpath) { - /* the same node's links */ - return (DI_WALK_CONTINUE); - } - - /* - * Construct session ID. - * session ID = ...parent hub addr|hub addr|dev addr. - */ - pnode = myself; - i = 0; - while (pnode != DI_NODE_NIL) { - if (di_prop_exists(DDI_DEV_T_ANY, pnode, "root-hub") == 1) { - /* walk to root */ - uint32_t *regbuf = NULL; - uint32_t reg; - - n = di_prop_lookup_ints(DDI_DEV_T_ANY, pnode, "reg", - (int **)®buf); - reg = regbuf[0]; - bdf = (PCI_REG_BUS_G(reg) << 8) | - (PCI_REG_DEV_G(reg) << 3) | PCI_REG_FUNC_G(reg); - session_id |= (bdf << i * 8); - - /* same as 'unit-address' property */ - bus_number = - (PCI_REG_DEV_G(reg) << 3) | PCI_REG_FUNC_G(reg); - - usbi_dbg("device bus address=%s:%x", - di_bus_addr(pnode), bus_number); - - break; - } - - /* usb_addr */ - n = di_prop_lookup_ints(DDI_DEV_T_ANY, pnode, - "assigned-address", &addr_prop); - if ((n != 1) || (addr_prop[0] == 0)) { - usbi_dbg("cannot get valid usb_addr"); - - return (DI_WALK_CONTINUE); - } - - session_id |= ((addr_prop[0] & 0xff) << i * 8); - if (++i > 7) - break; - - pnode = di_parent_node(pnode); - } - - path = di_devlink_path(link); - dev = usbi_get_device_by_session_id(nargs->ctx, session_id); - if (dev == NULL) { - dev = usbi_alloc_device(nargs->ctx, session_id); - if (dev == NULL) { - usbi_dbg("can't alloc device"); - - return (DI_WALK_TERMINATE); - } - devpriv = (sunos_dev_priv_t *)dev->os_priv; - if ((newpath = strrchr(path, '/')) == NULL) { - libusb_unref_device(dev); - - return (DI_WALK_TERMINATE); - } - devpriv->ugenpath = strndup(path, strlen(path) - - strlen(newpath)); - dev->bus_number = bus_number; - - if (sunos_fill_in_dev_info(myself, dev) != LIBUSB_SUCCESS) { - libusb_unref_device(dev); - - return (DI_WALK_TERMINATE); - } - if (usbi_sanitize_device(dev) < 0) { - libusb_unref_device(dev); - usbi_dbg("sanatize failed: "); - return (DI_WALK_TERMINATE); - } - } else { - usbi_dbg("Dev %s exists", path); - } - - devpriv = (sunos_dev_priv_t *)dev->os_priv; - if (nargs->last_ugenpath == NULL) { - /* first device */ - nargs->last_ugenpath = devpriv->ugenpath; - - if (discovered_devs_append(*(nargs->discdevs), dev) == NULL) { - usbi_dbg("cannot append device"); - } - - /* - * we alloc and hence ref this dev. We don't need to ref it - * hereafter. Front end or app should take care of their ref. - */ - libusb_unref_device(dev); - } - - usbi_dbg("Device %s %s id=0x%llx, devcount:%d, bdf=%x", - devpriv->ugenpath, path, (uint64_t)session_id, - (*nargs->discdevs)->len, bdf); - - return (DI_WALK_CONTINUE); -} - -static int -sunos_walk_minor_node_link(di_node_t node, void *args) -{ - di_minor_t minor = DI_MINOR_NIL; - char *minor_path; - struct devlink_cbarg arg; - struct node_args *nargs = (struct node_args *)args; - di_devlink_handle_t devlink_hdl = nargs->dlink_hdl; - - /* walk each minor to find ugen devices */ - while ((minor = di_minor_next(node, minor)) != DI_MINOR_NIL) { - minor_path = di_devfs_minor_path(minor); - arg.nargs = args; - arg.myself = node; - arg.minor = minor; - (void) di_devlink_walk(devlink_hdl, - "^usb/[0-9a-f]+[.][0-9a-f]+", minor_path, - DI_PRIMARY_LINK, (void *)&arg, sunos_add_devices); - di_devfs_path_free(minor_path); - } - - /* switch to a different node */ - nargs->last_ugenpath = NULL; - - return (DI_WALK_CONTINUE); -} - -int -sunos_get_device_list(struct libusb_context * ctx, - struct discovered_devs **discdevs) -{ - di_node_t root_node; - struct node_args args; - di_devlink_handle_t devlink_hdl; - - args.ctx = ctx; - args.discdevs = discdevs; - args.last_ugenpath = NULL; - if ((root_node = di_init("/", DINFOCPYALL)) == DI_NODE_NIL) { - usbi_dbg("di_int() failed: %s", strerror(errno)); - return (LIBUSB_ERROR_IO); - } - - if ((devlink_hdl = di_devlink_init(NULL, 0)) == NULL) { - di_fini(root_node); - usbi_dbg("di_devlink_init() failed: %s", strerror(errno)); - - return (LIBUSB_ERROR_IO); - } - args.dlink_hdl = devlink_hdl; - - /* walk each node to find USB devices */ - if (di_walk_node(root_node, DI_WALK_SIBFIRST, &args, - sunos_walk_minor_node_link) == -1) { - usbi_dbg("di_walk_node() failed: %s", strerror(errno)); - di_fini(root_node); - - return (LIBUSB_ERROR_IO); - } - - di_fini(root_node); - di_devlink_fini(&devlink_hdl); - - usbi_dbg("%d devices", (*discdevs)->len); - - return ((*discdevs)->len); -} - -static int -sunos_usb_open_ep0(sunos_dev_handle_priv_t *hpriv, sunos_dev_priv_t *dpriv) -{ - char filename[PATH_MAX + 1]; - - if (hpriv->eps[0].datafd > 0) { - - return (LIBUSB_SUCCESS); - } - snprintf(filename, PATH_MAX, "%s/cntrl0", dpriv->ugenpath); - - usbi_dbg("opening %s", filename); - hpriv->eps[0].datafd = open(filename, O_RDWR); - if (hpriv->eps[0].datafd < 0) { - return(_errno_to_libusb(errno)); - } - - snprintf(filename, PATH_MAX, "%s/cntrl0stat", dpriv->ugenpath); - hpriv->eps[0].statfd = open(filename, O_RDONLY); - if (hpriv->eps[0].statfd < 0) { - close(hpriv->eps[0].datafd); - hpriv->eps[0].datafd = -1; - - return(_errno_to_libusb(errno)); - } - - return (LIBUSB_SUCCESS); -} - -static void -sunos_usb_close_all_eps(sunos_dev_handle_priv_t *hdev) -{ - int i; - - /* not close ep0 */ - for (i = 1; i < USB_MAXENDPOINTS; i++) { - if (hdev->eps[i].datafd != -1) { - (void) close(hdev->eps[i].datafd); - hdev->eps[i].datafd = -1; - } - if (hdev->eps[i].statfd != -1) { - (void) close(hdev->eps[i].statfd); - hdev->eps[i].statfd = -1; - } - } -} - -static void -sunos_usb_close_ep0(sunos_dev_handle_priv_t *hdev, sunos_dev_priv_t *dpriv) -{ - if (hdev->eps[0].datafd >= 0) { - close(hdev->eps[0].datafd); - close(hdev->eps[0].statfd); - hdev->eps[0].datafd = -1; - hdev->eps[0].statfd = -1; - } -} - -static uchar_t -sunos_usb_ep_index(uint8_t ep_addr) -{ - return ((ep_addr & LIBUSB_ENDPOINT_ADDRESS_MASK) + - ((ep_addr & LIBUSB_ENDPOINT_DIR_MASK) ? 16 : 0)); -} - -static int -sunos_find_interface(struct libusb_device_handle *hdev, - uint8_t endpoint, uint8_t *interface) -{ - struct libusb_config_descriptor *config; - int r; - int iface_idx; - - r = libusb_get_active_config_descriptor(hdev->dev, &config); - if (r < 0) { - return (LIBUSB_ERROR_INVALID_PARAM); - } - - for (iface_idx = 0; iface_idx < config->bNumInterfaces; iface_idx++) { - const struct libusb_interface *iface = - &config->interface[iface_idx]; - int altsetting_idx; - - for (altsetting_idx = 0; altsetting_idx < iface->num_altsetting; - altsetting_idx++) { - const struct libusb_interface_descriptor *altsetting = - &iface->altsetting[altsetting_idx]; - int ep_idx; - - for (ep_idx = 0; ep_idx < altsetting->bNumEndpoints; - ep_idx++) { - const struct libusb_endpoint_descriptor *ep = - &altsetting->endpoint[ep_idx]; - if (ep->bEndpointAddress == endpoint) { - *interface = iface_idx; - libusb_free_config_descriptor(config); - - return (LIBUSB_SUCCESS); - } - } - } - } - libusb_free_config_descriptor(config); - - return (LIBUSB_ERROR_INVALID_PARAM); -} - -static int -sunos_check_device_and_status_open(struct libusb_device_handle *hdl, - uint8_t ep_addr, int ep_type) -{ - char filename[PATH_MAX + 1], statfilename[PATH_MAX + 1]; - char cfg_num[16], alt_num[16]; - int fd, fdstat, mode; - uint8_t ifc = 0; - uint8_t ep_index; - sunos_dev_handle_priv_t *hpriv; - - usbi_dbg("open ep 0x%02x", ep_addr); - hpriv = (sunos_dev_handle_priv_t *)hdl->os_priv; - ep_index = sunos_usb_ep_index(ep_addr); - /* ep already opened */ - if ((hpriv->eps[ep_index].datafd > 0) && - (hpriv->eps[ep_index].statfd > 0)) { - usbi_dbg("ep 0x%02x already opened, return success", - ep_addr); - - return (0); - } - - if (sunos_find_interface(hdl, ep_addr, &ifc) < 0) { - usbi_dbg("can't find interface for endpoint 0x%02x", - ep_addr); - - return (LIBUSB_ERROR_ACCESS); - } - - /* create filename */ - if (hpriv->config_index > 0) { - (void) snprintf(cfg_num, sizeof (cfg_num), "cfg%d", - hpriv->config_index + 1); - } else { - bzero(cfg_num, sizeof (cfg_num)); - } - - if (hpriv->altsetting[ifc] > 0) { - (void) snprintf(alt_num, sizeof (alt_num), ".%d", - hpriv->altsetting[ifc]); - } else { - bzero(alt_num, sizeof (alt_num)); - } - - (void) snprintf(filename, PATH_MAX, "%s/%sif%d%s%s%d", - hpriv->dpriv->ugenpath, cfg_num, ifc, alt_num, - (ep_addr & LIBUSB_ENDPOINT_DIR_MASK) ? "in" : - "out", (ep_addr & LIBUSB_ENDPOINT_ADDRESS_MASK)); - (void) snprintf(statfilename, PATH_MAX, "%sstat", filename); - - /* - * for interrupt IN endpoints, we need to enable one xfer - * mode before opening the endpoint - */ - if ((ep_type == LIBUSB_TRANSFER_TYPE_INTERRUPT) && - (ep_addr & LIBUSB_ENDPOINT_IN)) { - char control = USB_EP_INTR_ONE_XFER; - int count; - - /* open the status device node for the ep first RDWR */ - if ((fdstat = open(statfilename, O_RDWR)) == -1) { - usbi_dbg("can't open %s RDWR: %d", - statfilename, errno); - } else { - count = write(fdstat, &control, sizeof (control)); - if (count != 1) { - /* this should have worked */ - usbi_dbg("can't write to %s: %d", - statfilename, errno); - (void) close(fdstat); - - return (errno); - } - /* close status node and open xfer node first */ - close (fdstat); - } - } - - /* open the xfer node first in case alt needs to be changed */ - if (ep_type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS) { - mode = O_RDWR; - } else if (ep_addr & LIBUSB_ENDPOINT_IN) { - mode = O_RDONLY; - } else { - mode = O_WRONLY; - } - - /* - * IMPORTANT: must open data xfer node first and then open stat node - * Otherwise, it will fail on multi-config or multi-altsetting devices - * with "Device Busy" error. See ugen_epxs_switch_cfg_alt() and - * ugen_epxs_check_alt_switch() in ugen driver source code. - */ - if ((fd = open(filename, mode)) == -1) { - usbi_dbg("can't open %s: %d(%s)", filename, errno, - strerror(errno)); - - return (errno); - } - /* open the status node */ - if ((fdstat = open(statfilename, O_RDONLY)) == -1) { - usbi_dbg("can't open %s: %d", statfilename, errno); - - (void) close(fd); - - return (errno); - } - - hpriv->eps[ep_index].datafd = fd; - hpriv->eps[ep_index].statfd = fdstat; - usbi_dbg("ep=0x%02x datafd=%d, statfd=%d", ep_addr, fd, fdstat); - - return (0); -} - -int -sunos_open(struct libusb_device_handle *handle) -{ - sunos_dev_handle_priv_t *hpriv; - sunos_dev_priv_t *dpriv; - int i; - int ret; - - hpriv = (sunos_dev_handle_priv_t *)handle->os_priv; - dpriv = (sunos_dev_priv_t *)handle->dev->os_priv; - hpriv->dpriv = dpriv; - - /* set all file descriptors to "closed" */ - for (i = 0; i < USB_MAXENDPOINTS; i++) { - hpriv->eps[i].datafd = -1; - hpriv->eps[i].statfd = -1; - } - - if ((ret = sunos_usb_open_ep0(hpriv, dpriv)) != LIBUSB_SUCCESS) { - usbi_dbg("fail: %d", ret); - return (ret); - } - - return (LIBUSB_SUCCESS); -} - -void -sunos_close(struct libusb_device_handle *handle) -{ - sunos_dev_handle_priv_t *hpriv; - sunos_dev_priv_t *dpriv; - - usbi_dbg(""); - if (!handle) { - return; - } - - hpriv = (sunos_dev_handle_priv_t *)handle->os_priv; - if (!hpriv) { - return; - } - dpriv = (sunos_dev_priv_t *)handle->dev->os_priv; - if (!dpriv) { - return; - } - - sunos_usb_close_all_eps(hpriv); - sunos_usb_close_ep0(hpriv, dpriv); -} - -int -sunos_get_device_descriptor(struct libusb_device *dev, uint8_t *buf, - int *host_endian) -{ - sunos_dev_priv_t *dpriv = (sunos_dev_priv_t *)dev->os_priv; - - memcpy(buf, &dpriv->dev_descr, LIBUSB_DT_DEVICE_SIZE); - *host_endian = 0; - - return (LIBUSB_SUCCESS); -} - -int -sunos_get_active_config_descriptor(struct libusb_device *dev, - uint8_t *buf, size_t len, int *host_endian) -{ - sunos_dev_priv_t *dpriv = (sunos_dev_priv_t *)dev->os_priv; - struct libusb_config_descriptor *cfg; - int proplen; - di_node_t node; - uint8_t *rdata; - - /* - * Keep raw configuration descriptors updated, in case config - * has ever been changed through setCfg. - */ - if ((node = di_init(dpriv->phypath, DINFOCPYALL)) == DI_NODE_NIL) { - usbi_dbg("di_int() failed: %s", strerror(errno)); - return (LIBUSB_ERROR_IO); - } - proplen = di_prop_lookup_bytes(DDI_DEV_T_ANY, node, - "usb-raw-cfg-descriptors", &rdata); - if (proplen <= 0) { - usbi_dbg("can't find raw config descriptors"); - - return (LIBUSB_ERROR_IO); - } - dpriv->raw_cfgdescr = realloc(dpriv->raw_cfgdescr, proplen); - if (dpriv->raw_cfgdescr == NULL) { - return (LIBUSB_ERROR_NO_MEM); - } else { - bcopy(rdata, dpriv->raw_cfgdescr, proplen); - dpriv->cfgvalue = ((struct libusb_config_descriptor *) - rdata)->bConfigurationValue; - } - di_fini(node); - - cfg = (struct libusb_config_descriptor *)dpriv->raw_cfgdescr; - len = MIN(len, libusb_le16_to_cpu(cfg->wTotalLength)); - memcpy(buf, dpriv->raw_cfgdescr, len); - *host_endian = 0; - usbi_dbg("path:%s len %d", dpriv->phypath, len); - - return (len); -} - -int -sunos_get_config_descriptor(struct libusb_device *dev, uint8_t idx, - uint8_t *buf, size_t len, int *host_endian) -{ - /* XXX */ - return(sunos_get_active_config_descriptor(dev, buf, len, host_endian)); -} - -int -sunos_get_configuration(struct libusb_device_handle *handle, int *config) -{ - sunos_dev_priv_t *dpriv = (sunos_dev_priv_t *)handle->dev->os_priv; - - *config = dpriv->cfgvalue; - - usbi_dbg("bConfigurationValue %d", *config); - - return (LIBUSB_SUCCESS); -} - -int -sunos_set_configuration(struct libusb_device_handle *handle, int config) -{ - sunos_dev_priv_t *dpriv = (sunos_dev_priv_t *)handle->dev->os_priv; - sunos_dev_handle_priv_t *hpriv; - - usbi_dbg("bConfigurationValue %d", config); - hpriv = (sunos_dev_handle_priv_t *)handle->os_priv; - - if (dpriv->ugenpath == NULL) - return (LIBUSB_ERROR_NOT_SUPPORTED); - - if (config < 1 || config > dpriv->dev_descr.bNumConfigurations) - return (LIBUSB_ERROR_INVALID_PARAM); - - dpriv->cfgvalue = config; - hpriv->config_index = config - 1; - - return (LIBUSB_SUCCESS); -} - -int -sunos_claim_interface(struct libusb_device_handle *handle, int iface) -{ - usbi_dbg("iface %d", iface); - if (iface < 0) { - return (LIBUSB_ERROR_INVALID_PARAM); - } - - return (LIBUSB_SUCCESS); -} - -int -sunos_release_interface(struct libusb_device_handle *handle, int iface) -{ - sunos_dev_handle_priv_t *hpriv = - (sunos_dev_handle_priv_t *)handle->os_priv; - - usbi_dbg("iface %d", iface); - if (iface < 0) { - return (LIBUSB_ERROR_INVALID_PARAM); - } - - /* XXX: can we release it? */ - hpriv->altsetting[iface] = 0; - - return (LIBUSB_SUCCESS); -} - -int -sunos_set_interface_altsetting(struct libusb_device_handle *handle, int iface, - int altsetting) -{ - sunos_dev_priv_t *dpriv = (sunos_dev_priv_t *)handle->dev->os_priv; - sunos_dev_handle_priv_t *hpriv = - (sunos_dev_handle_priv_t *)handle->os_priv; - - usbi_dbg("iface %d, setting %d", iface, altsetting); - - if (iface < 0 || altsetting < 0) { - return (LIBUSB_ERROR_INVALID_PARAM); - } - if (dpriv->ugenpath == NULL) - return (LIBUSB_ERROR_NOT_FOUND); - - /* XXX: can we switch altsetting? */ - hpriv->altsetting[iface] = altsetting; - - return (LIBUSB_SUCCESS); -} - -static void -usb_dump_data(unsigned char *data, size_t size) -{ - int i; - - if (getenv("LIBUSB_DEBUG") == NULL) { - return; - } - - (void) fprintf(stderr, "data dump:"); - for (i = 0; i < size; i++) { - if (i % 16 == 0) { - (void) fprintf(stderr, "\n%08x ", i); - } - (void) fprintf(stderr, "%02x ", (uchar_t)data[i]); - } - (void) fprintf(stderr, "\n"); -} - -static void -sunos_async_callback(union sigval arg) -{ - struct sunos_transfer_priv *tpriv = - (struct sunos_transfer_priv *)arg.sival_ptr; - struct libusb_transfer *xfer = tpriv->transfer; - struct aiocb *aiocb = &tpriv->aiocb; - int ret; - sunos_dev_handle_priv_t *hpriv; - uint8_t ep; - - hpriv = (sunos_dev_handle_priv_t *)xfer->dev_handle->os_priv; - ep = sunos_usb_ep_index(xfer->endpoint); - - ret = aio_error(aiocb); - if (ret != 0) { - xfer->status = sunos_usb_get_status(hpriv->eps[ep].statfd); - } else { - xfer->actual_length = - LIBUSB_TRANSFER_TO_USBI_TRANSFER(xfer)->transferred = - aio_return(aiocb); - } - - usb_dump_data(xfer->buffer, xfer->actual_length); - - usbi_dbg("ret=%d, len=%d, actual_len=%d", ret, xfer->length, - xfer->actual_length); - - /* async notification */ - usbi_signal_transfer_completion(LIBUSB_TRANSFER_TO_USBI_TRANSFER(xfer)); -} - -static int -sunos_do_async_io(struct libusb_transfer *transfer) -{ - int ret = -1; - struct aiocb *aiocb; - sunos_dev_handle_priv_t *hpriv; - uint8_t ep; - struct sunos_transfer_priv *tpriv; - - usbi_dbg(""); - - tpriv = usbi_transfer_get_os_priv(LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer)); - hpriv = (sunos_dev_handle_priv_t *)transfer->dev_handle->os_priv; - ep = sunos_usb_ep_index(transfer->endpoint); - - tpriv->transfer = transfer; - aiocb = &tpriv->aiocb; - bzero(aiocb, sizeof (*aiocb)); - aiocb->aio_fildes = hpriv->eps[ep].datafd; - aiocb->aio_buf = transfer->buffer; - aiocb->aio_nbytes = transfer->length; - aiocb->aio_lio_opcode = - ((transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK) == - LIBUSB_ENDPOINT_IN) ? LIO_READ:LIO_WRITE; - aiocb->aio_sigevent.sigev_notify = SIGEV_THREAD; - aiocb->aio_sigevent.sigev_value.sival_ptr = tpriv; - aiocb->aio_sigevent.sigev_notify_function = sunos_async_callback; - - if (aiocb->aio_lio_opcode == LIO_READ) { - ret = aio_read(aiocb); - } else { - ret = aio_write(aiocb); - } - - return (ret); -} - -/* return the number of bytes read/written */ -static int -usb_do_io(int fd, int stat_fd, char *data, size_t size, int flag, int *status) -{ - int error; - int ret = -1; - - usbi_dbg("usb_do_io(): datafd=%d statfd=%d size=0x%x flag=%s", - fd, stat_fd, size, flag? "WRITE":"READ"); - - switch (flag) { - case READ: - errno = 0; - ret = read(fd, data, size); - usb_dump_data(data, size); - break; - case WRITE: - usb_dump_data(data, size); - errno = 0; - ret = write(fd, data, size); - break; - } - - usbi_dbg("usb_do_io(): amount=%d", ret); - - if (ret < 0) { - int save_errno = errno; - - usbi_dbg("TID=%x io %s errno=%d(%s) ret=%d", pthread_self(), - flag?"WRITE":"READ", errno, strerror(errno), ret); - - /* sunos_usb_get_status will do a read and overwrite errno */ - error = sunos_usb_get_status(stat_fd); - usbi_dbg("io status=%d errno=%d(%s)", error, - save_errno, strerror(save_errno)); - - if (status) { - *status = save_errno; - } - - return (save_errno); - - } else if (status) { - *status = 0; - } - - return (ret); -} - -static int -solaris_submit_ctrl_on_default(struct libusb_transfer *transfer) -{ - int ret = -1, setup_ret; - int status; - sunos_dev_handle_priv_t *hpriv; - struct libusb_device_handle *hdl = transfer->dev_handle; - uint16_t wLength; - uint8_t *data = transfer->buffer; - - hpriv = (sunos_dev_handle_priv_t *)hdl->os_priv; - wLength = transfer->length - LIBUSB_CONTROL_SETUP_SIZE; - - if (hpriv->eps[0].datafd == -1) { - usbi_dbg("ep0 not opened"); - - return (LIBUSB_ERROR_NOT_FOUND); - } - - if ((data[0] & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_IN) { - usbi_dbg("IN request"); - ret = usb_do_io(hpriv->eps[0].datafd, - hpriv->eps[0].statfd, (char *)data, LIBUSB_CONTROL_SETUP_SIZE, - WRITE, (int *)&status); - } else { - usbi_dbg("OUT request"); - ret = usb_do_io(hpriv->eps[0].datafd, hpriv->eps[0].statfd, - transfer->buffer, transfer->length, WRITE, - (int *)&transfer->status); - } - - setup_ret = ret; - if (ret < LIBUSB_CONTROL_SETUP_SIZE) { - usbi_dbg("error sending control msg: %d", ret); - - return (LIBUSB_ERROR_IO); - } - - ret = transfer->length - LIBUSB_CONTROL_SETUP_SIZE; - - /* Read the remaining bytes for IN request */ - if ((wLength) && ((data[0] & LIBUSB_ENDPOINT_DIR_MASK) == - LIBUSB_ENDPOINT_IN)) { - usbi_dbg("DATA: %d", transfer->length - setup_ret); - ret = usb_do_io(hpriv->eps[0].datafd, - hpriv->eps[0].statfd, - (char *)transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, - wLength, READ, (int *)&transfer->status); - } - - if (ret >= 0) { - transfer->actual_length = ret; - LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer)->transferred = ret; - } - usbi_dbg("Done: ctrl data bytes %d", ret); - - /* sync transfer handling */ - ret = usbi_handle_transfer_completion(LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer), - transfer->status); - - return (ret); -} - -int -sunos_clear_halt(struct libusb_device_handle *handle, uint8_t endpoint) -{ - int ret; - - usbi_dbg("endpoint=0x%02x", endpoint); - - ret = libusb_control_transfer(handle, LIBUSB_ENDPOINT_OUT | - LIBUSB_RECIPIENT_ENDPOINT | LIBUSB_REQUEST_TYPE_STANDARD, - LIBUSB_REQUEST_CLEAR_FEATURE, 0, endpoint, NULL, 0, 1000); - - usbi_dbg("ret=%d", ret); - - return (ret); -} - -int -sunos_reset_device(struct libusb_device_handle *handle) -{ - usbi_dbg(""); - - return (LIBUSB_ERROR_NOT_SUPPORTED); -} - -void -sunos_destroy_device(struct libusb_device *dev) -{ - sunos_dev_priv_t *dpriv = (sunos_dev_priv_t *)dev->os_priv; - - usbi_dbg(""); - - free(dpriv->raw_cfgdescr); - free(dpriv->ugenpath); - free(dpriv->phypath); -} - -int -sunos_submit_transfer(struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer; - struct libusb_device_handle *hdl; - int err = 0; - - transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - hdl = transfer->dev_handle; - - err = sunos_check_device_and_status_open(hdl, - transfer->endpoint, transfer->type); - if (err < 0) { - - return (_errno_to_libusb(err)); - } - - switch (transfer->type) { - case LIBUSB_TRANSFER_TYPE_CONTROL: - /* sync transfer */ - usbi_dbg("CTRL transfer: %d", transfer->length); - err = solaris_submit_ctrl_on_default(transfer); - break; - - case LIBUSB_TRANSFER_TYPE_BULK: - /* fallthru */ - case LIBUSB_TRANSFER_TYPE_INTERRUPT: - if (transfer->type == LIBUSB_TRANSFER_TYPE_BULK) - usbi_dbg("BULK transfer: %d", transfer->length); - else - usbi_dbg("INTR transfer: %d", transfer->length); - err = sunos_do_async_io(transfer); - break; - - case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS: - /* Isochronous/Stream is not supported */ - - /* fallthru */ - case LIBUSB_TRANSFER_TYPE_BULK_STREAM: - if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS) - usbi_dbg("ISOC transfer: %d", transfer->length); - else - usbi_dbg("BULK STREAM transfer: %d", transfer->length); - err = LIBUSB_ERROR_NOT_SUPPORTED; - break; - } - - return (err); -} - -int -sunos_cancel_transfer(struct usbi_transfer *itransfer) -{ - sunos_xfer_priv_t *tpriv; - sunos_dev_handle_priv_t *hpriv; - struct libusb_transfer *transfer; - struct aiocb *aiocb; - uint8_t ep; - int ret; - - tpriv = usbi_transfer_get_os_priv(itransfer); - aiocb = &tpriv->aiocb; - transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - hpriv = (sunos_dev_handle_priv_t *)transfer->dev_handle->os_priv; - ep = sunos_usb_ep_index(transfer->endpoint); - - ret = aio_cancel(hpriv->eps[ep].datafd, aiocb); - - usbi_dbg("aio->fd=%d fd=%d ret = %d, %s", aiocb->aio_fildes, - hpriv->eps[ep].datafd, ret, (ret == AIO_CANCELED)? - strerror(0):strerror(errno)); - - if (ret != AIO_CANCELED) { - ret = _errno_to_libusb(errno); - } else { - /* - * we don't need to call usbi_handle_transfer_cancellation(), - * because we'll handle everything in sunos_async_callback. - */ - ret = LIBUSB_SUCCESS; - } - - return (ret); -} - -void -sunos_clear_transfer_priv(struct usbi_transfer *itransfer) -{ - usbi_dbg(""); - - /* Nothing to do */ -} - -int -sunos_handle_transfer_completion(struct usbi_transfer *itransfer) -{ - return usbi_handle_transfer_completion(itransfer, LIBUSB_TRANSFER_COMPLETED); -} - -int -sunos_clock_gettime(int clkid, struct timespec *tp) -{ - usbi_dbg("clock %d", clkid); - - if (clkid == USBI_CLOCK_REALTIME) - return clock_gettime(CLOCK_REALTIME, tp); - - if (clkid == USBI_CLOCK_MONOTONIC) - return clock_gettime(CLOCK_MONOTONIC, tp); - - return (LIBUSB_ERROR_INVALID_PARAM); -} - -int -_errno_to_libusb(int err) -{ - usbi_dbg("error: %s (%d)", strerror(err), err); - - switch (err) { - case EIO: - return (LIBUSB_ERROR_IO); - case EACCES: - return (LIBUSB_ERROR_ACCESS); - case ENOENT: - return (LIBUSB_ERROR_NO_DEVICE); - case ENOMEM: - return (LIBUSB_ERROR_NO_MEM); - case ETIMEDOUT: - return (LIBUSB_ERROR_TIMEOUT); - } - - return (LIBUSB_ERROR_OTHER); -} - -/* - * sunos_usb_get_status: - * gets status of endpoint - * - * Returns: ugen's last cmd status - */ -static int -sunos_usb_get_status(int fd) -{ - int status, ret; - - usbi_dbg("sunos_usb_get_status(): fd=%d", fd); - - ret = read(fd, &status, sizeof (status)); - if (ret == sizeof (status)) { - switch (status) { - case USB_LC_STAT_NOERROR: - usbi_dbg("No Error"); - break; - case USB_LC_STAT_CRC: - usbi_dbg("CRC Timeout Detected\n"); - break; - case USB_LC_STAT_BITSTUFFING: - usbi_dbg("Bit Stuffing Violation\n"); - break; - case USB_LC_STAT_DATA_TOGGLE_MM: - usbi_dbg("Data Toggle Mismatch\n"); - break; - case USB_LC_STAT_STALL: - usbi_dbg("End Point Stalled\n"); - break; - case USB_LC_STAT_DEV_NOT_RESP: - usbi_dbg("Device is Not Responding\n"); - break; - case USB_LC_STAT_PID_CHECKFAILURE: - usbi_dbg("PID Check Failure\n"); - break; - case USB_LC_STAT_UNEXP_PID: - usbi_dbg("Unexpected PID\n"); - break; - case USB_LC_STAT_DATA_OVERRUN: - usbi_dbg("Data Exceeded Size\n"); - break; - case USB_LC_STAT_DATA_UNDERRUN: - usbi_dbg("Less data received\n"); - break; - case USB_LC_STAT_BUFFER_OVERRUN: - usbi_dbg("Buffer Size Exceeded\n"); - break; - case USB_LC_STAT_BUFFER_UNDERRUN: - usbi_dbg("Buffer Underrun\n"); - break; - case USB_LC_STAT_TIMEOUT: - usbi_dbg("Command Timed Out\n"); - break; - case USB_LC_STAT_NOT_ACCESSED: - usbi_dbg("Not Accessed by h/w\n"); - break; - case USB_LC_STAT_UNSPECIFIED_ERR: - usbi_dbg("Unspecified Error\n"); - break; - case USB_LC_STAT_NO_BANDWIDTH: - usbi_dbg("No Bandwidth\n"); - break; - case USB_LC_STAT_HW_ERR: - usbi_dbg("Host Controller h/w Error\n"); - break; - case USB_LC_STAT_SUSPENDED: - usbi_dbg("Device was Suspended\n"); - break; - case USB_LC_STAT_DISCONNECTED: - usbi_dbg("Device was Disconnected\n"); - break; - case USB_LC_STAT_INTR_BUF_FULL: - usbi_dbg("Interrupt buffer was full\n"); - break; - case USB_LC_STAT_INVALID_REQ: - usbi_dbg("Request was Invalid\n"); - break; - case USB_LC_STAT_INTERRUPTED: - usbi_dbg("Request was Interrupted\n"); - break; - case USB_LC_STAT_NO_RESOURCES: - usbi_dbg("No resources available for " - "request\n"); - break; - case USB_LC_STAT_INTR_POLLING_FAILED: - usbi_dbg("Failed to Restart Poll"); - break; - default: - usbi_dbg("Error Not Determined %d\n", - status); - break; - } - } else { - usbi_dbg("read stat error: %s",strerror(errno)); - status = -1; - } - - return (status); -} - -const struct usbi_os_backend sunos_backend = { - .name = "Solaris", - .caps = 0, - .init = sunos_init, - .exit = sunos_exit, - .get_device_list = sunos_get_device_list, - .get_device_descriptor = sunos_get_device_descriptor, - .get_active_config_descriptor = sunos_get_active_config_descriptor, - .get_config_descriptor = sunos_get_config_descriptor, - .hotplug_poll = NULL, - .open = sunos_open, - .close = sunos_close, - .get_configuration = sunos_get_configuration, - .set_configuration = sunos_set_configuration, - - .claim_interface = sunos_claim_interface, - .release_interface = sunos_release_interface, - .set_interface_altsetting = sunos_set_interface_altsetting, - .clear_halt = sunos_clear_halt, - .reset_device = sunos_reset_device, /* TODO */ - .alloc_streams = NULL, - .free_streams = NULL, - .kernel_driver_active = NULL, - .detach_kernel_driver = NULL, - .attach_kernel_driver = NULL, - .destroy_device = sunos_destroy_device, - .submit_transfer = sunos_submit_transfer, - .cancel_transfer = sunos_cancel_transfer, - .handle_events = NULL, - .clear_transfer_priv = sunos_clear_transfer_priv, - .handle_transfer_completion = sunos_handle_transfer_completion, - .clock_gettime = sunos_clock_gettime, - .device_priv_size = sizeof(sunos_dev_priv_t), - .device_handle_priv_size = sizeof(sunos_dev_handle_priv_t), - .transfer_priv_size = sizeof(sunos_xfer_priv_t), -}; diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/sunos_usb.h b/vendor/github.com/karalabe/hid/libusb/libusb/os/sunos_usb.h deleted file mode 100644 index 57416603..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/sunos_usb.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * - * Copyright (c) 2016, Oracle and/or its affiliates. - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef LIBUSB_SUNOS_H -#define LIBUSB_SUNOS_H - -#include -#include -#include "libusbi.h" - -#define READ 0 -#define WRITE 1 - -typedef struct sunos_device_priv { - uint8_t cfgvalue; /* active config value */ - uint8_t *raw_cfgdescr; /* active config descriptor */ - struct libusb_device_descriptor dev_descr; /* usb device descriptor */ - char *ugenpath; /* name of the ugen(4) node */ - char *phypath; /* physical path */ -} sunos_dev_priv_t; - -typedef struct endpoint { - int datafd; /* data file */ - int statfd; /* state file */ -} sunos_ep_priv_t; - -typedef struct sunos_device_handle_priv { - uint8_t altsetting[USB_MAXINTERFACES]; /* a interface's alt */ - uint8_t config_index; - sunos_ep_priv_t eps[USB_MAXENDPOINTS]; - sunos_dev_priv_t *dpriv; /* device private */ -} sunos_dev_handle_priv_t; - -typedef struct sunos_transfer_priv { - struct aiocb aiocb; - struct libusb_transfer *transfer; -} sunos_xfer_priv_t; - -struct node_args { - struct libusb_context *ctx; - struct discovered_devs **discdevs; - const char *last_ugenpath; - di_devlink_handle_t dlink_hdl; -}; - -struct devlink_cbarg { - struct node_args *nargs; /* di node walk arguments */ - di_node_t myself; /* the di node */ - di_minor_t minor; -}; - -/* AIO callback args */ -struct aio_callback_args{ - struct libusb_transfer *transfer; - struct aiocb aiocb; -}; - -#endif /* LIBUSB_SUNOS_H */ diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/threads_posix.c b/vendor/github.com/karalabe/hid/libusb/libusb/os/threads_posix.c deleted file mode 100644 index a4f270bb..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/threads_posix.c +++ /dev/null @@ -1,79 +0,0 @@ -/* - * libusb synchronization using POSIX Threads - * - * Copyright © 2011 Vitali Lovich - * Copyright © 2011 Peter Stuge - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include - -#include -#if defined(__linux__) || defined(__OpenBSD__) -# if defined(__OpenBSD__) -# define _BSD_SOURCE -# endif -# include -# include -#elif defined(__APPLE__) -# include -#elif defined(__CYGWIN__) -# include -#endif - -#include "threads_posix.h" -#include "libusbi.h" - -int usbi_cond_timedwait(pthread_cond_t *cond, - pthread_mutex_t *mutex, const struct timeval *tv) -{ - struct timespec timeout; - int r; - - r = usbi_backend->clock_gettime(USBI_CLOCK_REALTIME, &timeout); - if (r < 0) - return r; - - timeout.tv_sec += tv->tv_sec; - timeout.tv_nsec += tv->tv_usec * 1000; - while (timeout.tv_nsec >= 1000000000L) { - timeout.tv_nsec -= 1000000000L; - timeout.tv_sec++; - } - - return pthread_cond_timedwait(cond, mutex, &timeout); -} - -int usbi_get_tid(void) -{ - int ret = -1; -#if defined(__ANDROID__) - ret = gettid(); -#elif defined(__linux__) - ret = syscall(SYS_gettid); -#elif defined(__OpenBSD__) - /* The following only works with OpenBSD > 5.1 as it requires - real thread support. For 5.1 and earlier, -1 is returned. */ - ret = syscall(SYS_getthrid); -#elif defined(__APPLE__) - ret = mach_thread_self(); - mach_port_deallocate(mach_task_self(), ret); -#elif defined(__CYGWIN__) - ret = GetCurrentThreadId(); -#endif -/* TODO: NetBSD thread ID support */ - return ret; -} diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/threads_posix.h b/vendor/github.com/karalabe/hid/libusb/libusb/os/threads_posix.h deleted file mode 100644 index 4c1514ea..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/threads_posix.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * libusb synchronization using POSIX Threads - * - * Copyright © 2010 Peter Stuge - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef LIBUSB_THREADS_POSIX_H -#define LIBUSB_THREADS_POSIX_H - -#include -#ifdef HAVE_SYS_TIME_H -#include -#endif - -#define usbi_mutex_static_t pthread_mutex_t -#define USBI_MUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER -#define usbi_mutex_static_lock pthread_mutex_lock -#define usbi_mutex_static_unlock pthread_mutex_unlock - -#define usbi_mutex_t pthread_mutex_t -#define usbi_mutex_init(mutex) pthread_mutex_init((mutex), NULL) -#define usbi_mutex_lock pthread_mutex_lock -#define usbi_mutex_unlock pthread_mutex_unlock -#define usbi_mutex_trylock pthread_mutex_trylock -#define usbi_mutex_destroy pthread_mutex_destroy - -#define usbi_cond_t pthread_cond_t -#define usbi_cond_init(cond) pthread_cond_init((cond), NULL) -#define usbi_cond_wait pthread_cond_wait -#define usbi_cond_broadcast pthread_cond_broadcast -#define usbi_cond_destroy pthread_cond_destroy - -#define usbi_tls_key_t pthread_key_t -#define usbi_tls_key_create(key) pthread_key_create((key), NULL) -#define usbi_tls_key_get pthread_getspecific -#define usbi_tls_key_set pthread_setspecific -#define usbi_tls_key_delete pthread_key_delete - -int usbi_get_tid(void); - -#endif /* LIBUSB_THREADS_POSIX_H */ diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/threads_windows.c b/vendor/github.com/karalabe/hid/libusb/libusb/os/threads_windows.c deleted file mode 100644 index 7c2e52db..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/threads_windows.c +++ /dev/null @@ -1,259 +0,0 @@ -/* - * libusb synchronization on Microsoft Windows - * - * Copyright © 2010 Michael Plante - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include - -#include -#include - -#include "libusbi.h" - -struct usbi_cond_perthread { - struct list_head list; - DWORD tid; - HANDLE event; -}; - -int usbi_mutex_static_lock(usbi_mutex_static_t *mutex) -{ - if (!mutex) - return EINVAL; - while (InterlockedExchange(mutex, 1) == 1) - SleepEx(0, TRUE); - return 0; -} - -int usbi_mutex_static_unlock(usbi_mutex_static_t *mutex) -{ - if (!mutex) - return EINVAL; - InterlockedExchange(mutex, 0); - return 0; -} - -int usbi_mutex_init(usbi_mutex_t *mutex) -{ - if (!mutex) - return EINVAL; - *mutex = CreateMutex(NULL, FALSE, NULL); - if (!*mutex) - return ENOMEM; - return 0; -} - -int usbi_mutex_lock(usbi_mutex_t *mutex) -{ - DWORD result; - - if (!mutex) - return EINVAL; - result = WaitForSingleObject(*mutex, INFINITE); - if (result == WAIT_OBJECT_0 || result == WAIT_ABANDONED) - return 0; // acquired (ToDo: check that abandoned is ok) - else - return EINVAL; // don't know how this would happen - // so don't know proper errno -} - -int usbi_mutex_unlock(usbi_mutex_t *mutex) -{ - if (!mutex) - return EINVAL; - if (ReleaseMutex(*mutex)) - return 0; - else - return EPERM; -} - -int usbi_mutex_trylock(usbi_mutex_t *mutex) -{ - DWORD result; - - if (!mutex) - return EINVAL; - result = WaitForSingleObject(*mutex, 0); - if (result == WAIT_OBJECT_0 || result == WAIT_ABANDONED) - return 0; // acquired (ToDo: check that abandoned is ok) - else if (result == WAIT_TIMEOUT) - return EBUSY; - else - return EINVAL; // don't know how this would happen - // so don't know proper error -} - -int usbi_mutex_destroy(usbi_mutex_t *mutex) -{ - // It is not clear if CloseHandle failure is due to failure to unlock. - // If so, this should be errno=EBUSY. - if (!mutex || !CloseHandle(*mutex)) - return EINVAL; - *mutex = NULL; - return 0; -} - -int usbi_cond_init(usbi_cond_t *cond) -{ - if (!cond) - return EINVAL; - list_init(&cond->waiters); - list_init(&cond->not_waiting); - return 0; -} - -int usbi_cond_destroy(usbi_cond_t *cond) -{ - // This assumes no one is using this anymore. The check MAY NOT BE safe. - struct usbi_cond_perthread *pos, *next_pos; - - if(!cond) - return EINVAL; - if (!list_empty(&cond->waiters)) - return EBUSY; // (!see above!) - list_for_each_entry_safe(pos, next_pos, &cond->not_waiting, list, struct usbi_cond_perthread) { - CloseHandle(pos->event); - list_del(&pos->list); - free(pos); - } - return 0; -} - -int usbi_cond_broadcast(usbi_cond_t *cond) -{ - // Assumes mutex is locked; this is not in keeping with POSIX spec, but - // libusb does this anyway, so we simplify by not adding more sync - // primitives to the CV definition! - int fail = 0; - struct usbi_cond_perthread *pos; - - if (!cond) - return EINVAL; - list_for_each_entry(pos, &cond->waiters, list, struct usbi_cond_perthread) { - if (!SetEvent(pos->event)) - fail = 1; - } - // The wait function will remove its respective item from the list. - return fail ? EINVAL : 0; -} - -__inline static int usbi_cond_intwait(usbi_cond_t *cond, - usbi_mutex_t *mutex, DWORD timeout_ms) -{ - struct usbi_cond_perthread *pos; - int r, found = 0; - DWORD r2, tid = GetCurrentThreadId(); - - if (!cond || !mutex) - return EINVAL; - list_for_each_entry(pos, &cond->not_waiting, list, struct usbi_cond_perthread) { - if(tid == pos->tid) { - found = 1; - break; - } - } - - if (!found) { - pos = calloc(1, sizeof(struct usbi_cond_perthread)); - if (!pos) - return ENOMEM; // This errno is not POSIX-allowed. - pos->tid = tid; - pos->event = CreateEvent(NULL, FALSE, FALSE, NULL); // auto-reset. - if (!pos->event) { - free(pos); - return ENOMEM; - } - list_add(&pos->list, &cond->not_waiting); - } - - list_del(&pos->list); // remove from not_waiting list. - list_add(&pos->list, &cond->waiters); - - r = usbi_mutex_unlock(mutex); - if (r) - return r; - - r2 = WaitForSingleObject(pos->event, timeout_ms); - r = usbi_mutex_lock(mutex); - if (r) - return r; - - list_del(&pos->list); - list_add(&pos->list, &cond->not_waiting); - - if (r2 == WAIT_OBJECT_0) - return 0; - else if (r2 == WAIT_TIMEOUT) - return ETIMEDOUT; - else - return EINVAL; -} -// N.B.: usbi_cond_*wait() can also return ENOMEM, even though pthread_cond_*wait cannot! -int usbi_cond_wait(usbi_cond_t *cond, usbi_mutex_t *mutex) -{ - return usbi_cond_intwait(cond, mutex, INFINITE); -} - -int usbi_cond_timedwait(usbi_cond_t *cond, - usbi_mutex_t *mutex, const struct timeval *tv) -{ - DWORD millis; - - millis = (DWORD)(tv->tv_sec * 1000) + (tv->tv_usec / 1000); - /* round up to next millisecond */ - if (tv->tv_usec % 1000) - millis++; - return usbi_cond_intwait(cond, mutex, millis); -} - -int usbi_tls_key_create(usbi_tls_key_t *key) -{ - if (!key) - return EINVAL; - *key = TlsAlloc(); - if (*key == TLS_OUT_OF_INDEXES) - return ENOMEM; - else - return 0; -} - -void *usbi_tls_key_get(usbi_tls_key_t key) -{ - return TlsGetValue(key); -} - -int usbi_tls_key_set(usbi_tls_key_t key, void *value) -{ - if (TlsSetValue(key, value)) - return 0; - else - return EINVAL; -} - -int usbi_tls_key_delete(usbi_tls_key_t key) -{ - if (TlsFree(key)) - return 0; - else - return EINVAL; -} - -int usbi_get_tid(void) -{ - return (int)GetCurrentThreadId(); -} diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/threads_windows.h b/vendor/github.com/karalabe/hid/libusb/libusb/os/threads_windows.h deleted file mode 100644 index e97ee787..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/threads_windows.h +++ /dev/null @@ -1,76 +0,0 @@ -/* - * libusb synchronization on Microsoft Windows - * - * Copyright © 2010 Michael Plante - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef LIBUSB_THREADS_WINDOWS_H -#define LIBUSB_THREADS_WINDOWS_H - -#define usbi_mutex_static_t volatile LONG -#define USBI_MUTEX_INITIALIZER 0 - -#define usbi_mutex_t HANDLE - -typedef struct usbi_cond { - // Every time a thread touches the CV, it winds up in one of these lists. - // It stays there until the CV is destroyed, even if the thread terminates. - struct list_head waiters; - struct list_head not_waiting; -} usbi_cond_t; - -// We *were* getting timespec from pthread.h: -#if (!defined(HAVE_STRUCT_TIMESPEC) && !defined(_TIMESPEC_DEFINED)) -#define HAVE_STRUCT_TIMESPEC 1 -#define _TIMESPEC_DEFINED 1 -struct timespec { - long tv_sec; - long tv_nsec; -}; -#endif /* HAVE_STRUCT_TIMESPEC | _TIMESPEC_DEFINED */ - -// We *were* getting ETIMEDOUT from pthread.h: -#ifndef ETIMEDOUT -# define ETIMEDOUT 10060 /* This is the value in winsock.h. */ -#endif - -#define usbi_tls_key_t DWORD - -int usbi_mutex_static_lock(usbi_mutex_static_t *mutex); -int usbi_mutex_static_unlock(usbi_mutex_static_t *mutex); - -int usbi_mutex_init(usbi_mutex_t *mutex); -int usbi_mutex_lock(usbi_mutex_t *mutex); -int usbi_mutex_unlock(usbi_mutex_t *mutex); -int usbi_mutex_trylock(usbi_mutex_t *mutex); -int usbi_mutex_destroy(usbi_mutex_t *mutex); - -int usbi_cond_init(usbi_cond_t *cond); -int usbi_cond_wait(usbi_cond_t *cond, usbi_mutex_t *mutex); -int usbi_cond_timedwait(usbi_cond_t *cond, - usbi_mutex_t *mutex, const struct timeval *tv); -int usbi_cond_broadcast(usbi_cond_t *cond); -int usbi_cond_destroy(usbi_cond_t *cond); - -int usbi_tls_key_create(usbi_tls_key_t *key); -void *usbi_tls_key_get(usbi_tls_key_t key); -int usbi_tls_key_set(usbi_tls_key_t key, void *value); -int usbi_tls_key_delete(usbi_tls_key_t key); - -int usbi_get_tid(void); - -#endif /* LIBUSB_THREADS_WINDOWS_H */ diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/wince_usb.c b/vendor/github.com/karalabe/hid/libusb/libusb/os/wince_usb.c deleted file mode 100644 index 0d466b8c..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/wince_usb.c +++ /dev/null @@ -1,899 +0,0 @@ -/* - * Windows CE backend for libusb 1.0 - * Copyright © 2011-2013 RealVNC Ltd. - * Large portions taken from Windows backend, which is - * Copyright © 2009-2010 Pete Batard - * With contributions from Michael Plante, Orin Eman et al. - * Parts of this code adapted from libusb-win32-v1 by Stephan Meyer - * Major code testing contribution by Xiaofan Chen - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include - -#include -#include - -#include "libusbi.h" -#include "wince_usb.h" - -// Global variables -int windows_version = WINDOWS_CE; -static uint64_t hires_frequency, hires_ticks_to_ps; -static HANDLE driver_handle = INVALID_HANDLE_VALUE; -static int concurrent_usage = -1; - -/* - * Converts a windows error to human readable string - * uses retval as errorcode, or, if 0, use GetLastError() - */ -#if defined(ENABLE_LOGGING) -static const char *windows_error_str(DWORD error_code) -{ - static TCHAR wErr_string[ERR_BUFFER_SIZE]; - static char err_string[ERR_BUFFER_SIZE]; - - DWORD size; - int len; - - if (error_code == 0) - error_code = GetLastError(); - - len = sprintf(err_string, "[%u] ", (unsigned int)error_code); - - size = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - wErr_string, ERR_BUFFER_SIZE, NULL); - if (size == 0) { - DWORD format_error = GetLastError(); - if (format_error) - snprintf(err_string, ERR_BUFFER_SIZE, - "Windows error code %u (FormatMessage error code %u)", - (unsigned int)error_code, (unsigned int)format_error); - else - snprintf(err_string, ERR_BUFFER_SIZE, "Unknown error code %u", (unsigned int)error_code); - } else { - // Remove CR/LF terminators, if present - size_t pos = size - 2; - if (wErr_string[pos] == 0x0D) - wErr_string[pos] = 0; - - if (!WideCharToMultiByte(CP_ACP, 0, wErr_string, -1, &err_string[len], ERR_BUFFER_SIZE - len, NULL, NULL)) - strcpy(err_string, "Unable to convert error string"); - } - - return err_string; -} -#endif - -static struct wince_device_priv *_device_priv(struct libusb_device *dev) -{ - return (struct wince_device_priv *)dev->os_priv; -} - -// ceusbkwrapper to libusb error code mapping -static int translate_driver_error(DWORD error) -{ - switch (error) { - case ERROR_INVALID_PARAMETER: - return LIBUSB_ERROR_INVALID_PARAM; - case ERROR_CALL_NOT_IMPLEMENTED: - case ERROR_NOT_SUPPORTED: - return LIBUSB_ERROR_NOT_SUPPORTED; - case ERROR_NOT_ENOUGH_MEMORY: - return LIBUSB_ERROR_NO_MEM; - case ERROR_INVALID_HANDLE: - return LIBUSB_ERROR_NO_DEVICE; - case ERROR_BUSY: - return LIBUSB_ERROR_BUSY; - - // Error codes that are either unexpected, or have - // no suitable LIBUSB_ERROR equivalent. - case ERROR_CANCELLED: - case ERROR_INTERNAL_ERROR: - default: - return LIBUSB_ERROR_OTHER; - } -} - -static int init_dllimports(void) -{ - DLL_GET_HANDLE(ceusbkwrapper); - DLL_LOAD_FUNC(ceusbkwrapper, UkwOpenDriver, TRUE); - DLL_LOAD_FUNC(ceusbkwrapper, UkwGetDeviceList, TRUE); - DLL_LOAD_FUNC(ceusbkwrapper, UkwReleaseDeviceList, TRUE); - DLL_LOAD_FUNC(ceusbkwrapper, UkwGetDeviceAddress, TRUE); - DLL_LOAD_FUNC(ceusbkwrapper, UkwGetDeviceDescriptor, TRUE); - DLL_LOAD_FUNC(ceusbkwrapper, UkwGetConfigDescriptor, TRUE); - DLL_LOAD_FUNC(ceusbkwrapper, UkwCloseDriver, TRUE); - DLL_LOAD_FUNC(ceusbkwrapper, UkwCancelTransfer, TRUE); - DLL_LOAD_FUNC(ceusbkwrapper, UkwIssueControlTransfer, TRUE); - DLL_LOAD_FUNC(ceusbkwrapper, UkwClaimInterface, TRUE); - DLL_LOAD_FUNC(ceusbkwrapper, UkwReleaseInterface, TRUE); - DLL_LOAD_FUNC(ceusbkwrapper, UkwSetInterfaceAlternateSetting, TRUE); - DLL_LOAD_FUNC(ceusbkwrapper, UkwClearHaltHost, TRUE); - DLL_LOAD_FUNC(ceusbkwrapper, UkwClearHaltDevice, TRUE); - DLL_LOAD_FUNC(ceusbkwrapper, UkwGetConfig, TRUE); - DLL_LOAD_FUNC(ceusbkwrapper, UkwSetConfig, TRUE); - DLL_LOAD_FUNC(ceusbkwrapper, UkwResetDevice, TRUE); - DLL_LOAD_FUNC(ceusbkwrapper, UkwKernelDriverActive, TRUE); - DLL_LOAD_FUNC(ceusbkwrapper, UkwAttachKernelDriver, TRUE); - DLL_LOAD_FUNC(ceusbkwrapper, UkwDetachKernelDriver, TRUE); - DLL_LOAD_FUNC(ceusbkwrapper, UkwIssueBulkTransfer, TRUE); - DLL_LOAD_FUNC(ceusbkwrapper, UkwIsPipeHalted, TRUE); - - return LIBUSB_SUCCESS; -} - -static void exit_dllimports(void) -{ - DLL_FREE_HANDLE(ceusbkwrapper); -} - -static int init_device( - struct libusb_device *dev, UKW_DEVICE drv_dev, - unsigned char bus_addr, unsigned char dev_addr) -{ - struct wince_device_priv *priv = _device_priv(dev); - int r = LIBUSB_SUCCESS; - - dev->bus_number = bus_addr; - dev->device_address = dev_addr; - priv->dev = drv_dev; - - if (!UkwGetDeviceDescriptor(priv->dev, &(priv->desc))) - r = translate_driver_error(GetLastError()); - - return r; -} - -// Internal API functions -static int wince_init(struct libusb_context *ctx) -{ - int r = LIBUSB_ERROR_OTHER; - HANDLE semaphore; - LARGE_INTEGER li_frequency; - TCHAR sem_name[11 + 8 + 1]; // strlen("libusb_init") + (32-bit hex PID) + '\0' - - _stprintf(sem_name, _T("libusb_init%08X"), (unsigned int)(GetCurrentProcessId() & 0xFFFFFFFF)); - semaphore = CreateSemaphore(NULL, 1, 1, sem_name); - if (semaphore == NULL) { - usbi_err(ctx, "could not create semaphore: %s", windows_error_str(0)); - return LIBUSB_ERROR_NO_MEM; - } - - // A successful wait brings our semaphore count to 0 (unsignaled) - // => any concurent wait stalls until the semaphore's release - if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) { - usbi_err(ctx, "failure to access semaphore: %s", windows_error_str(0)); - CloseHandle(semaphore); - return LIBUSB_ERROR_NO_MEM; - } - - // NB: concurrent usage supposes that init calls are equally balanced with - // exit calls. If init is called more than exit, we will not exit properly - if ( ++concurrent_usage == 0 ) { // First init? - // Initialize pollable file descriptors - init_polling(); - - // Load DLL imports - if (init_dllimports() != LIBUSB_SUCCESS) { - usbi_err(ctx, "could not resolve DLL functions"); - r = LIBUSB_ERROR_NOT_SUPPORTED; - goto init_exit; - } - - // try to open a handle to the driver - driver_handle = UkwOpenDriver(); - if (driver_handle == INVALID_HANDLE_VALUE) { - usbi_err(ctx, "could not connect to driver"); - r = LIBUSB_ERROR_NOT_SUPPORTED; - goto init_exit; - } - - // find out if we have access to a monotonic (hires) timer - if (QueryPerformanceFrequency(&li_frequency)) { - hires_frequency = li_frequency.QuadPart; - // The hires frequency can go as high as 4 GHz, so we'll use a conversion - // to picoseconds to compute the tv_nsecs part in clock_gettime - hires_ticks_to_ps = UINT64_C(1000000000000) / hires_frequency; - usbi_dbg("hires timer available (Frequency: %"PRIu64" Hz)", hires_frequency); - } else { - usbi_dbg("no hires timer available on this platform"); - hires_frequency = 0; - hires_ticks_to_ps = UINT64_C(0); - } - } - // At this stage, either we went through full init successfully, or didn't need to - r = LIBUSB_SUCCESS; - -init_exit: // Holds semaphore here. - if (!concurrent_usage && r != LIBUSB_SUCCESS) { // First init failed? - exit_dllimports(); - exit_polling(); - - if (driver_handle != INVALID_HANDLE_VALUE) { - UkwCloseDriver(driver_handle); - driver_handle = INVALID_HANDLE_VALUE; - } - } - - if (r != LIBUSB_SUCCESS) - --concurrent_usage; // Not expected to call libusb_exit if we failed. - - ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1 - CloseHandle(semaphore); - return r; -} - -static void wince_exit(void) -{ - HANDLE semaphore; - TCHAR sem_name[11 + 8 + 1]; // strlen("libusb_init") + (32-bit hex PID) + '\0' - - _stprintf(sem_name, _T("libusb_init%08X"), (unsigned int)(GetCurrentProcessId() & 0xFFFFFFFF)); - semaphore = CreateSemaphore(NULL, 1, 1, sem_name); - if (semaphore == NULL) - return; - - // A successful wait brings our semaphore count to 0 (unsignaled) - // => any concurent wait stalls until the semaphore release - if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) { - CloseHandle(semaphore); - return; - } - - // Only works if exits and inits are balanced exactly - if (--concurrent_usage < 0) { // Last exit - exit_dllimports(); - exit_polling(); - - if (driver_handle != INVALID_HANDLE_VALUE) { - UkwCloseDriver(driver_handle); - driver_handle = INVALID_HANDLE_VALUE; - } - } - - ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1 - CloseHandle(semaphore); -} - -static int wince_get_device_list( - struct libusb_context *ctx, - struct discovered_devs **discdevs) -{ - UKW_DEVICE devices[MAX_DEVICE_COUNT]; - struct discovered_devs *new_devices = *discdevs; - DWORD count = 0, i; - struct libusb_device *dev = NULL; - unsigned char bus_addr, dev_addr; - unsigned long session_id; - BOOL success; - DWORD release_list_offset = 0; - int r = LIBUSB_SUCCESS; - - success = UkwGetDeviceList(driver_handle, devices, MAX_DEVICE_COUNT, &count); - if (!success) { - int libusbErr = translate_driver_error(GetLastError()); - usbi_err(ctx, "could not get devices: %s", windows_error_str(0)); - return libusbErr; - } - - for (i = 0; i < count; ++i) { - release_list_offset = i; - success = UkwGetDeviceAddress(devices[i], &bus_addr, &dev_addr, &session_id); - if (!success) { - r = translate_driver_error(GetLastError()); - usbi_err(ctx, "could not get device address for %u: %s", (unsigned int)i, windows_error_str(0)); - goto err_out; - } - - dev = usbi_get_device_by_session_id(ctx, session_id); - if (dev) { - usbi_dbg("using existing device for %u/%u (session %lu)", - bus_addr, dev_addr, session_id); - // Release just this element in the device list (as we already hold a - // reference to it). - UkwReleaseDeviceList(driver_handle, &devices[i], 1); - release_list_offset++; - } else { - usbi_dbg("allocating new device for %u/%u (session %lu)", - bus_addr, dev_addr, session_id); - dev = usbi_alloc_device(ctx, session_id); - if (!dev) { - r = LIBUSB_ERROR_NO_MEM; - goto err_out; - } - - r = init_device(dev, devices[i], bus_addr, dev_addr); - if (r < 0) - goto err_out; - - r = usbi_sanitize_device(dev); - if (r < 0) - goto err_out; - } - - new_devices = discovered_devs_append(new_devices, dev); - if (!discdevs) { - r = LIBUSB_ERROR_NO_MEM; - goto err_out; - } - - libusb_unref_device(dev); - } - - *discdevs = new_devices; - return r; -err_out: - *discdevs = new_devices; - libusb_unref_device(dev); - // Release the remainder of the unprocessed device list. - // The devices added to new_devices already will still be passed up to libusb, - // which can dispose of them at its leisure. - UkwReleaseDeviceList(driver_handle, &devices[release_list_offset], count - release_list_offset); - return r; -} - -static int wince_open(struct libusb_device_handle *handle) -{ - // Nothing to do to open devices as a handle to it has - // been retrieved by wince_get_device_list - return LIBUSB_SUCCESS; -} - -static void wince_close(struct libusb_device_handle *handle) -{ - // Nothing to do as wince_open does nothing. -} - -static int wince_get_device_descriptor( - struct libusb_device *device, - unsigned char *buffer, int *host_endian) -{ - struct wince_device_priv *priv = _device_priv(device); - - *host_endian = 1; - memcpy(buffer, &priv->desc, DEVICE_DESC_LENGTH); - return LIBUSB_SUCCESS; -} - -static int wince_get_active_config_descriptor( - struct libusb_device *device, - unsigned char *buffer, size_t len, int *host_endian) -{ - struct wince_device_priv *priv = _device_priv(device); - DWORD actualSize = len; - - *host_endian = 0; - if (!UkwGetConfigDescriptor(priv->dev, UKW_ACTIVE_CONFIGURATION, buffer, len, &actualSize)) - return translate_driver_error(GetLastError()); - - return actualSize; -} - -static int wince_get_config_descriptor( - struct libusb_device *device, - uint8_t config_index, - unsigned char *buffer, size_t len, int *host_endian) -{ - struct wince_device_priv *priv = _device_priv(device); - DWORD actualSize = len; - - *host_endian = 0; - if (!UkwGetConfigDescriptor(priv->dev, config_index, buffer, len, &actualSize)) - return translate_driver_error(GetLastError()); - - return actualSize; -} - -static int wince_get_configuration( - struct libusb_device_handle *handle, - int *config) -{ - struct wince_device_priv *priv = _device_priv(handle->dev); - UCHAR cv = 0; - - if (!UkwGetConfig(priv->dev, &cv)) - return translate_driver_error(GetLastError()); - - (*config) = cv; - return LIBUSB_SUCCESS; -} - -static int wince_set_configuration( - struct libusb_device_handle *handle, - int config) -{ - struct wince_device_priv *priv = _device_priv(handle->dev); - // Setting configuration 0 places the device in Address state. - // This should correspond to the "unconfigured state" required by - // libusb when the specified configuration is -1. - UCHAR cv = (config < 0) ? 0 : config; - if (!UkwSetConfig(priv->dev, cv)) - return translate_driver_error(GetLastError()); - - return LIBUSB_SUCCESS; -} - -static int wince_claim_interface( - struct libusb_device_handle *handle, - int interface_number) -{ - struct wince_device_priv *priv = _device_priv(handle->dev); - - if (!UkwClaimInterface(priv->dev, interface_number)) - return translate_driver_error(GetLastError()); - - return LIBUSB_SUCCESS; -} - -static int wince_release_interface( - struct libusb_device_handle *handle, - int interface_number) -{ - struct wince_device_priv *priv = _device_priv(handle->dev); - - if (!UkwSetInterfaceAlternateSetting(priv->dev, interface_number, 0)) - return translate_driver_error(GetLastError()); - - if (!UkwReleaseInterface(priv->dev, interface_number)) - return translate_driver_error(GetLastError()); - - return LIBUSB_SUCCESS; -} - -static int wince_set_interface_altsetting( - struct libusb_device_handle *handle, - int interface_number, int altsetting) -{ - struct wince_device_priv *priv = _device_priv(handle->dev); - - if (!UkwSetInterfaceAlternateSetting(priv->dev, interface_number, altsetting)) - return translate_driver_error(GetLastError()); - - return LIBUSB_SUCCESS; -} - -static int wince_clear_halt( - struct libusb_device_handle *handle, - unsigned char endpoint) -{ - struct wince_device_priv *priv = _device_priv(handle->dev); - - if (!UkwClearHaltHost(priv->dev, endpoint)) - return translate_driver_error(GetLastError()); - - if (!UkwClearHaltDevice(priv->dev, endpoint)) - return translate_driver_error(GetLastError()); - - return LIBUSB_SUCCESS; -} - -static int wince_reset_device( - struct libusb_device_handle *handle) -{ - struct wince_device_priv *priv = _device_priv(handle->dev); - - if (!UkwResetDevice(priv->dev)) - return translate_driver_error(GetLastError()); - - return LIBUSB_SUCCESS; -} - -static int wince_kernel_driver_active( - struct libusb_device_handle *handle, - int interface_number) -{ - struct wince_device_priv *priv = _device_priv(handle->dev); - BOOL result = FALSE; - - if (!UkwKernelDriverActive(priv->dev, interface_number, &result)) - return translate_driver_error(GetLastError()); - - return result ? 1 : 0; -} - -static int wince_detach_kernel_driver( - struct libusb_device_handle *handle, - int interface_number) -{ - struct wince_device_priv *priv = _device_priv(handle->dev); - - if (!UkwDetachKernelDriver(priv->dev, interface_number)) - return translate_driver_error(GetLastError()); - - return LIBUSB_SUCCESS; -} - -static int wince_attach_kernel_driver( - struct libusb_device_handle *handle, - int interface_number) -{ - struct wince_device_priv *priv = _device_priv(handle->dev); - - if (!UkwAttachKernelDriver(priv->dev, interface_number)) - return translate_driver_error(GetLastError()); - - return LIBUSB_SUCCESS; -} - -static void wince_destroy_device(struct libusb_device *dev) -{ - struct wince_device_priv *priv = _device_priv(dev); - - UkwReleaseDeviceList(driver_handle, &priv->dev, 1); -} - -static void wince_clear_transfer_priv(struct usbi_transfer *itransfer) -{ - struct wince_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer); - struct winfd wfd = fd_to_winfd(transfer_priv->pollable_fd.fd); - - // No need to cancel transfer as it is either complete or abandoned - wfd.itransfer = NULL; - CloseHandle(wfd.handle); - usbi_free_fd(&transfer_priv->pollable_fd); -} - -static int wince_cancel_transfer(struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct wince_device_priv *priv = _device_priv(transfer->dev_handle->dev); - struct wince_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer); - - if (!UkwCancelTransfer(priv->dev, transfer_priv->pollable_fd.overlapped, UKW_TF_NO_WAIT)) - return translate_driver_error(GetLastError()); - - return LIBUSB_SUCCESS; -} - -static int wince_submit_control_or_bulk_transfer(struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev); - struct wince_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer); - struct wince_device_priv *priv = _device_priv(transfer->dev_handle->dev); - BOOL direction_in, ret; - struct winfd wfd; - DWORD flags; - HANDLE eventHandle; - PUKW_CONTROL_HEADER setup = NULL; - const BOOL control_transfer = transfer->type == LIBUSB_TRANSFER_TYPE_CONTROL; - - transfer_priv->pollable_fd = INVALID_WINFD; - if (control_transfer) { - setup = (PUKW_CONTROL_HEADER) transfer->buffer; - direction_in = setup->bmRequestType & LIBUSB_ENDPOINT_IN; - } else { - direction_in = transfer->endpoint & LIBUSB_ENDPOINT_IN; - } - flags = direction_in ? UKW_TF_IN_TRANSFER : UKW_TF_OUT_TRANSFER; - flags |= UKW_TF_SHORT_TRANSFER_OK; - - eventHandle = CreateEvent(NULL, FALSE, FALSE, NULL); - if (eventHandle == NULL) { - usbi_err(ctx, "Failed to create event for async transfer"); - return LIBUSB_ERROR_NO_MEM; - } - - wfd = usbi_create_fd(eventHandle, direction_in ? RW_READ : RW_WRITE, itransfer, &wince_cancel_transfer); - if (wfd.fd < 0) { - CloseHandle(eventHandle); - return LIBUSB_ERROR_NO_MEM; - } - - transfer_priv->pollable_fd = wfd; - if (control_transfer) { - // Split out control setup header and data buffer - DWORD bufLen = transfer->length - sizeof(UKW_CONTROL_HEADER); - PVOID buf = (PVOID) &transfer->buffer[sizeof(UKW_CONTROL_HEADER)]; - - ret = UkwIssueControlTransfer(priv->dev, flags, setup, buf, bufLen, &transfer->actual_length, wfd.overlapped); - } else { - ret = UkwIssueBulkTransfer(priv->dev, flags, transfer->endpoint, transfer->buffer, - transfer->length, &transfer->actual_length, wfd.overlapped); - } - - if (!ret) { - int libusbErr = translate_driver_error(GetLastError()); - usbi_err(ctx, "UkwIssue%sTransfer failed: error %u", - control_transfer ? "Control" : "Bulk", (unsigned int)GetLastError()); - wince_clear_transfer_priv(itransfer); - return libusbErr; - } - usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd, direction_in ? POLLIN : POLLOUT); - - return LIBUSB_SUCCESS; -} - -static int wince_submit_iso_transfer(struct usbi_transfer *itransfer) -{ - return LIBUSB_ERROR_NOT_SUPPORTED; -} - -static int wince_submit_transfer(struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - - switch (transfer->type) { - case LIBUSB_TRANSFER_TYPE_CONTROL: - case LIBUSB_TRANSFER_TYPE_BULK: - case LIBUSB_TRANSFER_TYPE_INTERRUPT: - return wince_submit_control_or_bulk_transfer(itransfer); - case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS: - return wince_submit_iso_transfer(itransfer); - case LIBUSB_TRANSFER_TYPE_BULK_STREAM: - return LIBUSB_ERROR_NOT_SUPPORTED; - default: - usbi_err(TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type); - return LIBUSB_ERROR_INVALID_PARAM; - } -} - -static void wince_transfer_callback( - struct usbi_transfer *itransfer, - uint32_t io_result, uint32_t io_size) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct wince_transfer_priv *transfer_priv = (struct wince_transfer_priv*)usbi_transfer_get_os_priv(itransfer); - struct wince_device_priv *priv = _device_priv(transfer->dev_handle->dev); - int status; - - usbi_dbg("handling I/O completion with errcode %u", io_result); - - if (io_result == ERROR_NOT_SUPPORTED && - transfer->type != LIBUSB_TRANSFER_TYPE_CONTROL) { - /* For functional stalls, the WinCE USB layer (and therefore the USB Kernel Wrapper - * Driver) will report USB_ERROR_STALL/ERROR_NOT_SUPPORTED in situations where the - * endpoint isn't actually stalled. - * - * One example of this is that some devices will occasionally fail to reply to an IN - * token. The WinCE USB layer carries on with the transaction until it is completed - * (or cancelled) but then completes it with USB_ERROR_STALL. - * - * This code therefore needs to confirm that there really is a stall error, by both - * checking the pipe status and requesting the endpoint status from the device. - */ - BOOL halted = FALSE; - usbi_dbg("checking I/O completion with errcode ERROR_NOT_SUPPORTED is really a stall"); - if (UkwIsPipeHalted(priv->dev, transfer->endpoint, &halted)) { - /* Pipe status retrieved, so now request endpoint status by sending a GET_STATUS - * control request to the device. This is done synchronously, which is a bit - * naughty, but this is a special corner case. - */ - WORD wStatus = 0; - DWORD written = 0; - UKW_CONTROL_HEADER ctrlHeader; - ctrlHeader.bmRequestType = LIBUSB_REQUEST_TYPE_STANDARD | - LIBUSB_ENDPOINT_IN | LIBUSB_RECIPIENT_ENDPOINT; - ctrlHeader.bRequest = LIBUSB_REQUEST_GET_STATUS; - ctrlHeader.wValue = 0; - ctrlHeader.wIndex = transfer->endpoint; - ctrlHeader.wLength = sizeof(wStatus); - if (UkwIssueControlTransfer(priv->dev, - UKW_TF_IN_TRANSFER | UKW_TF_SEND_TO_ENDPOINT, - &ctrlHeader, &wStatus, sizeof(wStatus), &written, NULL)) { - if (written == sizeof(wStatus) && - (wStatus & STATUS_HALT_FLAG) == 0) { - if (!halted || UkwClearHaltHost(priv->dev, transfer->endpoint)) { - usbi_dbg("Endpoint doesn't appear to be stalled, overriding error with success"); - io_result = ERROR_SUCCESS; - } else { - usbi_dbg("Endpoint doesn't appear to be stalled, but the host is halted, changing error"); - io_result = ERROR_IO_DEVICE; - } - } - } - } - } - - switch(io_result) { - case ERROR_SUCCESS: - itransfer->transferred += io_size; - status = LIBUSB_TRANSFER_COMPLETED; - break; - case ERROR_CANCELLED: - usbi_dbg("detected transfer cancel"); - status = LIBUSB_TRANSFER_CANCELLED; - break; - case ERROR_NOT_SUPPORTED: - case ERROR_GEN_FAILURE: - usbi_dbg("detected endpoint stall"); - status = LIBUSB_TRANSFER_STALL; - break; - case ERROR_SEM_TIMEOUT: - usbi_dbg("detected semaphore timeout"); - status = LIBUSB_TRANSFER_TIMED_OUT; - break; - case ERROR_OPERATION_ABORTED: - usbi_dbg("detected operation aborted"); - status = LIBUSB_TRANSFER_CANCELLED; - break; - default: - usbi_err(ITRANSFER_CTX(itransfer), "detected I/O error: %s", windows_error_str(io_result)); - status = LIBUSB_TRANSFER_ERROR; - break; - } - - wince_clear_transfer_priv(itransfer); - if (status == LIBUSB_TRANSFER_CANCELLED) - usbi_handle_transfer_cancellation(itransfer); - else - usbi_handle_transfer_completion(itransfer, (enum libusb_transfer_status)status); -} - -static void wince_handle_callback( - struct usbi_transfer *itransfer, - uint32_t io_result, uint32_t io_size) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - - switch (transfer->type) { - case LIBUSB_TRANSFER_TYPE_CONTROL: - case LIBUSB_TRANSFER_TYPE_BULK: - case LIBUSB_TRANSFER_TYPE_INTERRUPT: - case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS: - wince_transfer_callback (itransfer, io_result, io_size); - break; - case LIBUSB_TRANSFER_TYPE_BULK_STREAM: - break; - default: - usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type); - } -} - -static int wince_handle_events( - struct libusb_context *ctx, - struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready) -{ - struct wince_transfer_priv* transfer_priv = NULL; - POLL_NFDS_TYPE i = 0; - BOOL found = FALSE; - struct usbi_transfer *transfer; - DWORD io_size, io_result; - int r = LIBUSB_SUCCESS; - - usbi_mutex_lock(&ctx->open_devs_lock); - for (i = 0; i < nfds && num_ready > 0; i++) { - - usbi_dbg("checking fd %d with revents = %04x", fds[i].fd, fds[i].revents); - - if (!fds[i].revents) - continue; - - num_ready--; - - // Because a Windows OVERLAPPED is used for poll emulation, - // a pollable fd is created and stored with each transfer - usbi_mutex_lock(&ctx->flying_transfers_lock); - list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) { - transfer_priv = usbi_transfer_get_os_priv(transfer); - if (transfer_priv->pollable_fd.fd == fds[i].fd) { - found = TRUE; - break; - } - } - usbi_mutex_unlock(&ctx->flying_transfers_lock); - - if (found && HasOverlappedIoCompleted(transfer_priv->pollable_fd.overlapped)) { - io_result = (DWORD)transfer_priv->pollable_fd.overlapped->Internal; - io_size = (DWORD)transfer_priv->pollable_fd.overlapped->InternalHigh; - usbi_remove_pollfd(ctx, transfer_priv->pollable_fd.fd); - // let handle_callback free the event using the transfer wfd - // If you don't use the transfer wfd, you run a risk of trying to free a - // newly allocated wfd that took the place of the one from the transfer. - wince_handle_callback(transfer, io_result, io_size); - } else if (found) { - usbi_err(ctx, "matching transfer for fd %d has not completed", fds[i]); - r = LIBUSB_ERROR_OTHER; - break; - } else { - usbi_err(ctx, "could not find a matching transfer for fd %d", fds[i]); - r = LIBUSB_ERROR_NOT_FOUND; - break; - } - } - usbi_mutex_unlock(&ctx->open_devs_lock); - - return r; -} - -/* - * Monotonic and real time functions - */ -static int wince_clock_gettime(int clk_id, struct timespec *tp) -{ - LARGE_INTEGER hires_counter; - ULARGE_INTEGER rtime; - FILETIME filetime; - SYSTEMTIME st; - - switch(clk_id) { - case USBI_CLOCK_MONOTONIC: - if (hires_frequency != 0 && QueryPerformanceCounter(&hires_counter)) { - tp->tv_sec = (long)(hires_counter.QuadPart / hires_frequency); - tp->tv_nsec = (long)(((hires_counter.QuadPart % hires_frequency) / 1000) * hires_ticks_to_ps); - return LIBUSB_SUCCESS; - } - // Fall through and return real-time if monotonic read failed or was not detected @ init - case USBI_CLOCK_REALTIME: - // We follow http://msdn.microsoft.com/en-us/library/ms724928%28VS.85%29.aspx - // with a predef epoch time to have an epoch that starts at 1970.01.01 00:00 - // Note however that our resolution is bounded by the Windows system time - // functions and is at best of the order of 1 ms (or, usually, worse) - GetSystemTime(&st); - SystemTimeToFileTime(&st, &filetime); - rtime.LowPart = filetime.dwLowDateTime; - rtime.HighPart = filetime.dwHighDateTime; - rtime.QuadPart -= EPOCH_TIME; - tp->tv_sec = (long)(rtime.QuadPart / 10000000); - tp->tv_nsec = (long)((rtime.QuadPart % 10000000)*100); - return LIBUSB_SUCCESS; - default: - return LIBUSB_ERROR_INVALID_PARAM; - } -} - -const struct usbi_os_backend wince_backend = { - "Windows CE", - 0, - wince_init, - wince_exit, - - wince_get_device_list, - NULL, /* hotplug_poll */ - wince_open, - wince_close, - - wince_get_device_descriptor, - wince_get_active_config_descriptor, - wince_get_config_descriptor, - NULL, /* get_config_descriptor_by_value() */ - - wince_get_configuration, - wince_set_configuration, - wince_claim_interface, - wince_release_interface, - - wince_set_interface_altsetting, - wince_clear_halt, - wince_reset_device, - - NULL, /* alloc_streams */ - NULL, /* free_streams */ - - NULL, /* dev_mem_alloc() */ - NULL, /* dev_mem_free() */ - - wince_kernel_driver_active, - wince_detach_kernel_driver, - wince_attach_kernel_driver, - - wince_destroy_device, - - wince_submit_transfer, - wince_cancel_transfer, - wince_clear_transfer_priv, - - wince_handle_events, - NULL, /* handle_transfer_completion() */ - - wince_clock_gettime, - sizeof(struct wince_device_priv), - 0, - sizeof(struct wince_transfer_priv), -}; diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/wince_usb.h b/vendor/github.com/karalabe/hid/libusb/libusb/os/wince_usb.h deleted file mode 100644 index edcb9fcc..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/wince_usb.h +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Windows CE backend for libusb 1.0 - * Copyright © 2011-2013 RealVNC Ltd. - * Portions taken from Windows backend, which is - * Copyright © 2009-2010 Pete Batard - * With contributions from Michael Plante, Orin Eman et al. - * Parts of this code adapted from libusb-win32-v1 by Stephan Meyer - * Major code testing contribution by Xiaofan Chen - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ -#pragma once - -#include "windows_common.h" - -#include -#include "poll_windows.h" - -#define MAX_DEVICE_COUNT 256 - -// This is a modified dump of the types in the ceusbkwrapper.h library header -// with functions transformed into extern pointers. -// -// This backend dynamically loads ceusbkwrapper.dll and doesn't include -// ceusbkwrapper.h directly to simplify the build process. The kernel -// side wrapper driver is built using the platform image build tools, -// which makes it difficult to reference directly from the libusb build -// system. -struct UKW_DEVICE_PRIV; -typedef struct UKW_DEVICE_PRIV *UKW_DEVICE; -typedef UKW_DEVICE *PUKW_DEVICE, *LPUKW_DEVICE; - -typedef struct { - UINT8 bLength; - UINT8 bDescriptorType; - UINT16 bcdUSB; - UINT8 bDeviceClass; - UINT8 bDeviceSubClass; - UINT8 bDeviceProtocol; - UINT8 bMaxPacketSize0; - UINT16 idVendor; - UINT16 idProduct; - UINT16 bcdDevice; - UINT8 iManufacturer; - UINT8 iProduct; - UINT8 iSerialNumber; - UINT8 bNumConfigurations; -} UKW_DEVICE_DESCRIPTOR, *PUKW_DEVICE_DESCRIPTOR, *LPUKW_DEVICE_DESCRIPTOR; - -typedef struct { - UINT8 bmRequestType; - UINT8 bRequest; - UINT16 wValue; - UINT16 wIndex; - UINT16 wLength; -} UKW_CONTROL_HEADER, *PUKW_CONTROL_HEADER, *LPUKW_CONTROL_HEADER; - -// Collection of flags which can be used when issuing transfer requests -/* Indicates that the transfer direction is 'in' */ -#define UKW_TF_IN_TRANSFER 0x00000001 -/* Indicates that the transfer direction is 'out' */ -#define UKW_TF_OUT_TRANSFER 0x00000000 -/* Specifies that the transfer should complete as soon as possible, - * even if no OVERLAPPED structure has been provided. */ -#define UKW_TF_NO_WAIT 0x00000100 -/* Indicates that transfers shorter than the buffer are ok */ -#define UKW_TF_SHORT_TRANSFER_OK 0x00000200 -#define UKW_TF_SEND_TO_DEVICE 0x00010000 -#define UKW_TF_SEND_TO_INTERFACE 0x00020000 -#define UKW_TF_SEND_TO_ENDPOINT 0x00040000 -/* Don't block when waiting for memory allocations */ -#define UKW_TF_DONT_BLOCK_FOR_MEM 0x00080000 - -/* Value to use when dealing with configuration values, such as UkwGetConfigDescriptor, - * to specify the currently active configuration for the device. */ -#define UKW_ACTIVE_CONFIGURATION -1 - -DLL_DECLARE_HANDLE(ceusbkwrapper); -DLL_DECLARE_FUNC(WINAPI, HANDLE, UkwOpenDriver, ()); -DLL_DECLARE_FUNC(WINAPI, BOOL, UkwGetDeviceList, (HANDLE, LPUKW_DEVICE, DWORD, LPDWORD)); -DLL_DECLARE_FUNC(WINAPI, void, UkwReleaseDeviceList, (HANDLE, LPUKW_DEVICE, DWORD)); -DLL_DECLARE_FUNC(WINAPI, BOOL, UkwGetDeviceAddress, (UKW_DEVICE, unsigned char*, unsigned char*, unsigned long*)); -DLL_DECLARE_FUNC(WINAPI, BOOL, UkwGetDeviceDescriptor, (UKW_DEVICE, LPUKW_DEVICE_DESCRIPTOR)); -DLL_DECLARE_FUNC(WINAPI, BOOL, UkwGetConfigDescriptor, (UKW_DEVICE, DWORD, LPVOID, DWORD, LPDWORD)); -DLL_DECLARE_FUNC(WINAPI, void, UkwCloseDriver, (HANDLE)); -DLL_DECLARE_FUNC(WINAPI, BOOL, UkwCancelTransfer, (UKW_DEVICE, LPOVERLAPPED, DWORD)); -DLL_DECLARE_FUNC(WINAPI, BOOL, UkwIssueControlTransfer, (UKW_DEVICE, DWORD, LPUKW_CONTROL_HEADER, LPVOID, DWORD, LPDWORD, LPOVERLAPPED)); -DLL_DECLARE_FUNC(WINAPI, BOOL, UkwClaimInterface, (UKW_DEVICE, DWORD)); -DLL_DECLARE_FUNC(WINAPI, BOOL, UkwReleaseInterface, (UKW_DEVICE, DWORD)); -DLL_DECLARE_FUNC(WINAPI, BOOL, UkwSetInterfaceAlternateSetting, (UKW_DEVICE, DWORD, DWORD)); -DLL_DECLARE_FUNC(WINAPI, BOOL, UkwClearHaltHost, (UKW_DEVICE, UCHAR)); -DLL_DECLARE_FUNC(WINAPI, BOOL, UkwClearHaltDevice, (UKW_DEVICE, UCHAR)); -DLL_DECLARE_FUNC(WINAPI, BOOL, UkwGetConfig, (UKW_DEVICE, PUCHAR)); -DLL_DECLARE_FUNC(WINAPI, BOOL, UkwSetConfig, (UKW_DEVICE, UCHAR)); -DLL_DECLARE_FUNC(WINAPI, BOOL, UkwResetDevice, (UKW_DEVICE)); -DLL_DECLARE_FUNC(WINAPI, BOOL, UkwKernelDriverActive, (UKW_DEVICE, DWORD, PBOOL)); -DLL_DECLARE_FUNC(WINAPI, BOOL, UkwAttachKernelDriver, (UKW_DEVICE, DWORD)); -DLL_DECLARE_FUNC(WINAPI, BOOL, UkwDetachKernelDriver, (UKW_DEVICE, DWORD)); -DLL_DECLARE_FUNC(WINAPI, BOOL, UkwIssueBulkTransfer, (UKW_DEVICE, DWORD, UCHAR, LPVOID, DWORD, LPDWORD, LPOVERLAPPED)); -DLL_DECLARE_FUNC(WINAPI, BOOL, UkwIsPipeHalted, (UKW_DEVICE, UCHAR, LPBOOL)); - -// Used to determine if an endpoint status really is halted on a failed transfer. -#define STATUS_HALT_FLAG 0x1 - -struct wince_device_priv { - UKW_DEVICE dev; - UKW_DEVICE_DESCRIPTOR desc; -}; - -struct wince_transfer_priv { - struct winfd pollable_fd; - uint8_t interface_number; -}; - diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/windows_common.h b/vendor/github.com/karalabe/hid/libusb/libusb/os/windows_common.h deleted file mode 100644 index 55344ca2..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/windows_common.h +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Windows backend common header for libusb 1.0 - * - * This file brings together header code common between - * the desktop Windows and Windows CE backends. - * Copyright © 2012-2013 RealVNC Ltd. - * Copyright © 2009-2012 Pete Batard - * With contributions from Michael Plante, Orin Eman et al. - * Parts of this code adapted from libusb-win32-v1 by Stephan Meyer - * Major code testing contribution by Xiaofan Chen - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#pragma once - -// Windows API default is uppercase - ugh! -#if !defined(bool) -#define bool BOOL -#endif -#if !defined(true) -#define true TRUE -#endif -#if !defined(false) -#define false FALSE -#endif - -#define EPOCH_TIME UINT64_C(116444736000000000) // 1970.01.01 00:00:000 in MS Filetime - -#if defined(__CYGWIN__ ) -#define _stricmp strcasecmp -#define _strdup strdup -// _beginthreadex is MSVCRT => unavailable for cygwin. Fallback to using CreateThread -#define _beginthreadex(a, b, c, d, e, f) CreateThread(a, b, (LPTHREAD_START_ROUTINE)c, d, e, (LPDWORD)f) -#endif - -#define safe_free(p) do {if (p != NULL) {free((void *)p); p = NULL;}} while (0) - -#ifndef ARRAYSIZE -#define ARRAYSIZE(A) (sizeof(A)/sizeof((A)[0])) -#endif - -#define ERR_BUFFER_SIZE 256 - -/* - * API macros - leveraged from libusb-win32 1.x - */ -#ifndef _WIN32_WCE -#define DLL_STRINGIFY(s) #s -#define DLL_LOAD_LIBRARY(name) LoadLibraryA(DLL_STRINGIFY(name)) -#else -#define DLL_STRINGIFY(s) L#s -#define DLL_LOAD_LIBRARY(name) LoadLibrary(DLL_STRINGIFY(name)) -#endif - -/* - * Macros for handling DLL themselves - */ -#define DLL_DECLARE_HANDLE(name) \ - static HMODULE __dll_##name##_handle = NULL - -#define DLL_GET_HANDLE(name) \ - do { \ - __dll_##name##_handle = DLL_LOAD_LIBRARY(name); \ - if (!__dll_##name##_handle) \ - return LIBUSB_ERROR_OTHER; \ - } while (0) - -#define DLL_FREE_HANDLE(name) \ - do { \ - if (__dll_##name##_handle) { \ - FreeLibrary(__dll_##name##_handle); \ - __dll_##name##_handle = NULL; \ - } \ - } while(0) - - -/* - * Macros for handling functions within a DLL - */ -#define DLL_DECLARE_FUNC_PREFIXNAME(api, ret, prefixname, name, args) \ - typedef ret (api * __dll_##name##_func_t)args; \ - static __dll_##name##_func_t prefixname = NULL - -#define DLL_DECLARE_FUNC(api, ret, name, args) \ - DLL_DECLARE_FUNC_PREFIXNAME(api, ret, name, name, args) -#define DLL_DECLARE_FUNC_PREFIXED(api, ret, prefix, name, args) \ - DLL_DECLARE_FUNC_PREFIXNAME(api, ret, prefix##name, name, args) - -#define DLL_LOAD_FUNC_PREFIXNAME(dll, prefixname, name, ret_on_failure) \ - do { \ - HMODULE h = __dll_##dll##_handle; \ - prefixname = (__dll_##name##_func_t)GetProcAddress(h, \ - DLL_STRINGIFY(name)); \ - if (prefixname) \ - break; \ - prefixname = (__dll_##name##_func_t)GetProcAddress(h, \ - DLL_STRINGIFY(name) DLL_STRINGIFY(A)); \ - if (prefixname) \ - break; \ - prefixname = (__dll_##name##_func_t)GetProcAddress(h, \ - DLL_STRINGIFY(name) DLL_STRINGIFY(W)); \ - if (prefixname) \ - break; \ - if (ret_on_failure) \ - return LIBUSB_ERROR_NOT_FOUND; \ - } while(0) - -#define DLL_LOAD_FUNC(dll, name, ret_on_failure) \ - DLL_LOAD_FUNC_PREFIXNAME(dll, name, name, ret_on_failure) -#define DLL_LOAD_FUNC_PREFIXED(dll, prefix, name, ret_on_failure) \ - DLL_LOAD_FUNC_PREFIXNAME(dll, prefix##name, name, ret_on_failure) diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/windows_nt_common.c b/vendor/github.com/karalabe/hid/libusb/libusb/os/windows_nt_common.c deleted file mode 100644 index d935394a..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/windows_nt_common.c +++ /dev/null @@ -1,591 +0,0 @@ -/* - * windows backend for libusb 1.0 - * Copyright © 2009-2012 Pete Batard - * With contributions from Michael Plante, Orin Eman et al. - * Parts of this code adapted from libusb-win32-v1 by Stephan Meyer - * HID Reports IOCTLs inspired from HIDAPI by Alan Ott, Signal 11 Software - * Hash table functions adapted from glibc, by Ulrich Drepper et al. - * Major code testing contribution by Xiaofan Chen - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include - -#include -#include -#include - -#include "libusbi.h" -#include "windows_common.h" -#include "windows_nt_common.h" - -// Global variables for clock_gettime mechanism -static uint64_t hires_ticks_to_ps; -static uint64_t hires_frequency; - -#define TIMER_REQUEST_RETRY_MS 100 -#define WM_TIMER_REQUEST (WM_USER + 1) -#define WM_TIMER_EXIT (WM_USER + 2) - -// used for monotonic clock_gettime() -struct timer_request { - struct timespec *tp; - HANDLE event; -}; - -// Timer thread -static HANDLE timer_thread = NULL; -static DWORD timer_thread_id = 0; - -/* User32 dependencies */ -DLL_DECLARE_HANDLE(User32); -DLL_DECLARE_FUNC_PREFIXED(WINAPI, BOOL, p, GetMessageA, (LPMSG, HWND, UINT, UINT)); -DLL_DECLARE_FUNC_PREFIXED(WINAPI, BOOL, p, PeekMessageA, (LPMSG, HWND, UINT, UINT, UINT)); -DLL_DECLARE_FUNC_PREFIXED(WINAPI, BOOL, p, PostThreadMessageA, (DWORD, UINT, WPARAM, LPARAM)); - -static unsigned __stdcall windows_clock_gettime_threaded(void *param); - -/* -* Converts a windows error to human readable string -* uses retval as errorcode, or, if 0, use GetLastError() -*/ -#if defined(ENABLE_LOGGING) -const char *windows_error_str(DWORD error_code) -{ - static char err_string[ERR_BUFFER_SIZE]; - - DWORD size; - int len; - - if (error_code == 0) - error_code = GetLastError(); - - len = sprintf(err_string, "[%u] ", (unsigned int)error_code); - - // Translate codes returned by SetupAPI. The ones we are dealing with are either - // in 0x0000xxxx or 0xE000xxxx and can be distinguished from standard error codes. - // See http://msdn.microsoft.com/en-us/library/windows/hardware/ff545011.aspx - switch (error_code & 0xE0000000) { - case 0: - error_code = HRESULT_FROM_WIN32(error_code); // Still leaves ERROR_SUCCESS unmodified - break; - case 0xE0000000: - error_code = 0x80000000 | (FACILITY_SETUPAPI << 16) | (error_code & 0x0000FFFF); - break; - default: - break; - } - - size = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - &err_string[len], ERR_BUFFER_SIZE - len, NULL); - if (size == 0) { - DWORD format_error = GetLastError(); - if (format_error) - snprintf(err_string, ERR_BUFFER_SIZE, - "Windows error code %u (FormatMessage error code %u)", - (unsigned int)error_code, (unsigned int)format_error); - else - snprintf(err_string, ERR_BUFFER_SIZE, "Unknown error code %u", (unsigned int)error_code); - } else { - // Remove CRLF from end of message, if present - size_t pos = len + size - 2; - if (err_string[pos] == '\r') - err_string[pos] = '\0'; - } - - return err_string; -} -#endif - -/* Hash table functions - modified From glibc 2.3.2: - [Aho,Sethi,Ullman] Compilers: Principles, Techniques and Tools, 1986 - [Knuth] The Art of Computer Programming, part 3 (6.4) */ - -#define HTAB_SIZE 1021UL // *MUST* be a prime number!! - -typedef struct htab_entry { - unsigned long used; - char *str; -} htab_entry; - -static htab_entry *htab_table = NULL; -static usbi_mutex_t htab_mutex = NULL; -static unsigned long htab_filled; - -/* Before using the hash table we must allocate memory for it. - We allocate one element more as the found prime number says. - This is done for more effective indexing as explained in the - comment for the hash function. */ -static bool htab_create(struct libusb_context *ctx) -{ - if (htab_table != NULL) { - usbi_err(ctx, "hash table already allocated"); - return true; - } - - // Create a mutex - usbi_mutex_init(&htab_mutex); - - usbi_dbg("using %lu entries hash table", HTAB_SIZE); - htab_filled = 0; - - // allocate memory and zero out. - htab_table = calloc(HTAB_SIZE + 1, sizeof(htab_entry)); - if (htab_table == NULL) { - usbi_err(ctx, "could not allocate space for hash table"); - return false; - } - - return true; -} - -/* After using the hash table it has to be destroyed. */ -static void htab_destroy(void) -{ - unsigned long i; - - if (htab_table == NULL) - return; - - for (i = 0; i < HTAB_SIZE; i++) - free(htab_table[i].str); - - safe_free(htab_table); - - usbi_mutex_destroy(&htab_mutex); -} - -/* This is the search function. It uses double hashing with open addressing. - We use a trick to speed up the lookup. The table is created with one - more element available. This enables us to use the index zero special. - This index will never be used because we store the first hash index in - the field used where zero means not used. Every other value means used. - The used field can be used as a first fast comparison for equality of - the stored and the parameter value. This helps to prevent unnecessary - expensive calls of strcmp. */ -unsigned long htab_hash(const char *str) -{ - unsigned long hval, hval2; - unsigned long idx; - unsigned long r = 5381; - int c; - const char *sz = str; - - if (str == NULL) - return 0; - - // Compute main hash value (algorithm suggested by Nokia) - while ((c = *sz++) != 0) - r = ((r << 5) + r) + c; - if (r == 0) - ++r; - - // compute table hash: simply take the modulus - hval = r % HTAB_SIZE; - if (hval == 0) - ++hval; - - // Try the first index - idx = hval; - - // Mutually exclusive access (R/W lock would be better) - usbi_mutex_lock(&htab_mutex); - - if (htab_table[idx].used) { - if ((htab_table[idx].used == hval) && (strcmp(str, htab_table[idx].str) == 0)) - goto out_unlock; // existing hash - - usbi_dbg("hash collision ('%s' vs '%s')", str, htab_table[idx].str); - - // Second hash function, as suggested in [Knuth] - hval2 = 1 + hval % (HTAB_SIZE - 2); - - do { - // Because size is prime this guarantees to step through all available indexes - if (idx <= hval2) - idx = HTAB_SIZE + idx - hval2; - else - idx -= hval2; - - // If we visited all entries leave the loop unsuccessfully - if (idx == hval) - break; - - // If entry is found use it. - if ((htab_table[idx].used == hval) && (strcmp(str, htab_table[idx].str) == 0)) - goto out_unlock; - } while (htab_table[idx].used); - } - - // Not found => New entry - - // If the table is full return an error - if (htab_filled >= HTAB_SIZE) { - usbi_err(NULL, "hash table is full (%lu entries)", HTAB_SIZE); - idx = 0; - goto out_unlock; - } - - htab_table[idx].str = _strdup(str); - if (htab_table[idx].str == NULL) { - usbi_err(NULL, "could not duplicate string for hash table"); - idx = 0; - goto out_unlock; - } - - htab_table[idx].used = hval; - ++htab_filled; - -out_unlock: - usbi_mutex_unlock(&htab_mutex); - - return idx; -} - -static int windows_init_dlls(void) -{ - DLL_GET_HANDLE(User32); - DLL_LOAD_FUNC_PREFIXED(User32, p, GetMessageA, TRUE); - DLL_LOAD_FUNC_PREFIXED(User32, p, PeekMessageA, TRUE); - DLL_LOAD_FUNC_PREFIXED(User32, p, PostThreadMessageA, TRUE); - - return LIBUSB_SUCCESS; -} - -static void windows_exit_dlls(void) -{ - DLL_FREE_HANDLE(User32); -} - -static bool windows_init_clock(struct libusb_context *ctx) -{ - DWORD_PTR affinity, dummy; - HANDLE event = NULL; - LARGE_INTEGER li_frequency; - int i; - - if (QueryPerformanceFrequency(&li_frequency)) { - // Load DLL imports - if (windows_init_dlls() != LIBUSB_SUCCESS) { - usbi_err(ctx, "could not resolve DLL functions"); - return false; - } - - // The hires frequency can go as high as 4 GHz, so we'll use a conversion - // to picoseconds to compute the tv_nsecs part in clock_gettime - hires_frequency = li_frequency.QuadPart; - hires_ticks_to_ps = UINT64_C(1000000000000) / hires_frequency; - usbi_dbg("hires timer available (Frequency: %"PRIu64" Hz)", hires_frequency); - - // Because QueryPerformanceCounter might report different values when - // running on different cores, we create a separate thread for the timer - // calls, which we glue to the first available core always to prevent timing discrepancies. - if (!GetProcessAffinityMask(GetCurrentProcess(), &affinity, &dummy) || (affinity == 0)) { - usbi_err(ctx, "could not get process affinity: %s", windows_error_str(0)); - return false; - } - - // The process affinity mask is a bitmask where each set bit represents a core on - // which this process is allowed to run, so we find the first set bit - for (i = 0; !(affinity & (DWORD_PTR)(1 << i)); i++); - affinity = (DWORD_PTR)(1 << i); - - usbi_dbg("timer thread will run on core #%d", i); - - event = CreateEvent(NULL, FALSE, FALSE, NULL); - if (event == NULL) { - usbi_err(ctx, "could not create event: %s", windows_error_str(0)); - return false; - } - - timer_thread = (HANDLE)_beginthreadex(NULL, 0, windows_clock_gettime_threaded, (void *)event, - 0, (unsigned int *)&timer_thread_id); - if (timer_thread == NULL) { - usbi_err(ctx, "unable to create timer thread - aborting"); - CloseHandle(event); - return false; - } - - if (!SetThreadAffinityMask(timer_thread, affinity)) - usbi_warn(ctx, "unable to set timer thread affinity, timer discrepancies may arise"); - - // Wait for timer thread to init before continuing. - if (WaitForSingleObject(event, INFINITE) != WAIT_OBJECT_0) { - usbi_err(ctx, "failed to wait for timer thread to become ready - aborting"); - CloseHandle(event); - return false; - } - - CloseHandle(event); - } else { - usbi_dbg("no hires timer available on this platform"); - hires_frequency = 0; - hires_ticks_to_ps = UINT64_C(0); - } - - return true; -} - -void windows_destroy_clock(void) -{ - if (timer_thread) { - // actually the signal to quit the thread. - if (!pPostThreadMessageA(timer_thread_id, WM_TIMER_EXIT, 0, 0) - || (WaitForSingleObject(timer_thread, INFINITE) != WAIT_OBJECT_0)) { - usbi_dbg("could not wait for timer thread to quit"); - TerminateThread(timer_thread, 1); - // shouldn't happen, but we're destroying - // all objects it might have held anyway. - } - CloseHandle(timer_thread); - timer_thread = NULL; - timer_thread_id = 0; - } -} - -/* -* Monotonic and real time functions -*/ -static unsigned __stdcall windows_clock_gettime_threaded(void *param) -{ - struct timer_request *request; - LARGE_INTEGER hires_counter; - MSG msg; - - // The following call will create this thread's message queue - // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms644946.aspx - pPeekMessageA(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE); - - // Signal windows_init_clock() that we're ready to service requests - if (!SetEvent((HANDLE)param)) - usbi_dbg("SetEvent failed for timer init event: %s", windows_error_str(0)); - param = NULL; - - // Main loop - wait for requests - while (1) { - if (pGetMessageA(&msg, NULL, WM_TIMER_REQUEST, WM_TIMER_EXIT) == -1) { - usbi_err(NULL, "GetMessage failed for timer thread: %s", windows_error_str(0)); - return 1; - } - - switch (msg.message) { - case WM_TIMER_REQUEST: - // Requests to this thread are for hires always - // Microsoft says that this function always succeeds on XP and later - // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms644904.aspx - request = (struct timer_request *)msg.lParam; - QueryPerformanceCounter(&hires_counter); - request->tp->tv_sec = (long)(hires_counter.QuadPart / hires_frequency); - request->tp->tv_nsec = (long)(((hires_counter.QuadPart % hires_frequency) / 1000) * hires_ticks_to_ps); - if (!SetEvent(request->event)) - usbi_err(NULL, "SetEvent failed for timer request: %s", windows_error_str(0)); - break; - case WM_TIMER_EXIT: - usbi_dbg("timer thread quitting"); - return 0; - } - } -} - -int windows_clock_gettime(int clk_id, struct timespec *tp) -{ - struct timer_request request; -#if !defined(_MSC_VER) || (_MSC_VER < 1900) - FILETIME filetime; - ULARGE_INTEGER rtime; -#endif - DWORD r; - - switch (clk_id) { - case USBI_CLOCK_MONOTONIC: - if (timer_thread) { - request.tp = tp; - request.event = CreateEvent(NULL, FALSE, FALSE, NULL); - if (request.event == NULL) - return LIBUSB_ERROR_NO_MEM; - - if (!pPostThreadMessageA(timer_thread_id, WM_TIMER_REQUEST, 0, (LPARAM)&request)) { - usbi_err(NULL, "PostThreadMessage failed for timer thread: %s", windows_error_str(0)); - CloseHandle(request.event); - return LIBUSB_ERROR_OTHER; - } - - do { - r = WaitForSingleObject(request.event, TIMER_REQUEST_RETRY_MS); - if (r == WAIT_TIMEOUT) - usbi_dbg("could not obtain a timer value within reasonable timeframe - too much load?"); - else if (r == WAIT_FAILED) - usbi_err(NULL, "WaitForSingleObject failed: %s", windows_error_str(0)); - } while (r == WAIT_TIMEOUT); - CloseHandle(request.event); - - if (r == WAIT_OBJECT_0) - return LIBUSB_SUCCESS; - else - return LIBUSB_ERROR_OTHER; - } - // Fall through and return real-time if monotonic was not detected @ timer init - case USBI_CLOCK_REALTIME: -#if defined(_MSC_VER) && (_MSC_VER >= 1900) - timespec_get(tp, TIME_UTC); -#else - // We follow http://msdn.microsoft.com/en-us/library/ms724928%28VS.85%29.aspx - // with a predef epoch time to have an epoch that starts at 1970.01.01 00:00 - // Note however that our resolution is bounded by the Windows system time - // functions and is at best of the order of 1 ms (or, usually, worse) - GetSystemTimeAsFileTime(&filetime); - rtime.LowPart = filetime.dwLowDateTime; - rtime.HighPart = filetime.dwHighDateTime; - rtime.QuadPart -= EPOCH_TIME; - tp->tv_sec = (long)(rtime.QuadPart / 10000000); - tp->tv_nsec = (long)((rtime.QuadPart % 10000000) * 100); -#endif - return LIBUSB_SUCCESS; - default: - return LIBUSB_ERROR_INVALID_PARAM; - } -} - -static void windows_transfer_callback(struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size) -{ - int status, istatus; - - usbi_dbg("handling I/O completion with errcode %u, size %u", io_result, io_size); - - switch (io_result) { - case NO_ERROR: - status = windows_copy_transfer_data(itransfer, io_size); - break; - case ERROR_GEN_FAILURE: - usbi_dbg("detected endpoint stall"); - status = LIBUSB_TRANSFER_STALL; - break; - case ERROR_SEM_TIMEOUT: - usbi_dbg("detected semaphore timeout"); - status = LIBUSB_TRANSFER_TIMED_OUT; - break; - case ERROR_OPERATION_ABORTED: - istatus = windows_copy_transfer_data(itransfer, io_size); - if (istatus != LIBUSB_TRANSFER_COMPLETED) - usbi_dbg("Failed to copy partial data in aborted operation: %d", istatus); - - usbi_dbg("detected operation aborted"); - status = LIBUSB_TRANSFER_CANCELLED; - break; - default: - usbi_err(ITRANSFER_CTX(itransfer), "detected I/O error %u: %s", io_result, windows_error_str(io_result)); - status = LIBUSB_TRANSFER_ERROR; - break; - } - windows_clear_transfer_priv(itransfer); // Cancel polling - if (status == LIBUSB_TRANSFER_CANCELLED) - usbi_handle_transfer_cancellation(itransfer); - else - usbi_handle_transfer_completion(itransfer, (enum libusb_transfer_status)status); -} - -void windows_handle_callback(struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - - switch (transfer->type) { - case LIBUSB_TRANSFER_TYPE_CONTROL: - case LIBUSB_TRANSFER_TYPE_BULK: - case LIBUSB_TRANSFER_TYPE_INTERRUPT: - case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS: - windows_transfer_callback(itransfer, io_result, io_size); - break; - case LIBUSB_TRANSFER_TYPE_BULK_STREAM: - usbi_warn(ITRANSFER_CTX(itransfer), "bulk stream transfers are not yet supported on this platform"); - break; - default: - usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type); - } -} - -int windows_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready) -{ - POLL_NFDS_TYPE i; - bool found = false; - struct usbi_transfer *transfer; - struct winfd *pollable_fd = NULL; - DWORD io_size, io_result; - int r = LIBUSB_SUCCESS; - - usbi_mutex_lock(&ctx->open_devs_lock); - for (i = 0; i < nfds && num_ready > 0; i++) { - - usbi_dbg("checking fd %d with revents = %04x", fds[i].fd, fds[i].revents); - - if (!fds[i].revents) - continue; - - num_ready--; - - // Because a Windows OVERLAPPED is used for poll emulation, - // a pollable fd is created and stored with each transfer - usbi_mutex_lock(&ctx->flying_transfers_lock); - found = false; - list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) { - pollable_fd = windows_get_fd(transfer); - if (pollable_fd->fd == fds[i].fd) { - found = true; - break; - } - } - usbi_mutex_unlock(&ctx->flying_transfers_lock); - - if (found) { - windows_get_overlapped_result(transfer, pollable_fd, &io_result, &io_size); - - usbi_remove_pollfd(ctx, pollable_fd->fd); - // let handle_callback free the event using the transfer wfd - // If you don't use the transfer wfd, you run a risk of trying to free a - // newly allocated wfd that took the place of the one from the transfer. - windows_handle_callback(transfer, io_result, io_size); - } else { - usbi_err(ctx, "could not find a matching transfer for fd %d", fds[i]); - r = LIBUSB_ERROR_NOT_FOUND; - break; - } - } - usbi_mutex_unlock(&ctx->open_devs_lock); - - return r; -} - -int windows_common_init(struct libusb_context *ctx) -{ - if (!windows_init_clock(ctx)) - goto error_roll_back; - - if (!htab_create(ctx)) - goto error_roll_back; - - return LIBUSB_SUCCESS; - -error_roll_back: - windows_common_exit(); - return LIBUSB_ERROR_NO_MEM; -} - -void windows_common_exit(void) -{ - htab_destroy(); - windows_destroy_clock(); - windows_exit_dlls(); -} diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/windows_nt_common.h b/vendor/github.com/karalabe/hid/libusb/libusb/os/windows_nt_common.h deleted file mode 100644 index 52ea8708..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/windows_nt_common.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Windows backend common header for libusb 1.0 - * - * This file brings together header code common between - * the desktop Windows backends. - * Copyright © 2012-2013 RealVNC Ltd. - * Copyright © 2009-2012 Pete Batard - * With contributions from Michael Plante, Orin Eman et al. - * Parts of this code adapted from libusb-win32-v1 by Stephan Meyer - * Major code testing contribution by Xiaofan Chen - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#pragma once - -// Missing from MinGW -#if !defined(FACILITY_SETUPAPI) -#define FACILITY_SETUPAPI 15 -#endif - -typedef struct USB_CONFIGURATION_DESCRIPTOR { - UCHAR bLength; - UCHAR bDescriptorType; - USHORT wTotalLength; - UCHAR bNumInterfaces; - UCHAR bConfigurationValue; - UCHAR iConfiguration; - UCHAR bmAttributes; - UCHAR MaxPower; -} USB_CONFIGURATION_DESCRIPTOR, *PUSB_CONFIGURATION_DESCRIPTOR; - -typedef struct libusb_device_descriptor USB_DEVICE_DESCRIPTOR, *PUSB_DEVICE_DESCRIPTOR; - -int windows_common_init(struct libusb_context *ctx); -void windows_common_exit(void); - -unsigned long htab_hash(const char *str); -int windows_clock_gettime(int clk_id, struct timespec *tp); - -void windows_clear_transfer_priv(struct usbi_transfer *itransfer); -int windows_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size); -struct winfd *windows_get_fd(struct usbi_transfer *transfer); -void windows_get_overlapped_result(struct usbi_transfer *transfer, struct winfd *pollable_fd, DWORD *io_result, DWORD *io_size); - -void windows_handle_callback(struct usbi_transfer *itransfer, uint32_t io_result, uint32_t io_size); -int windows_handle_events(struct libusb_context *ctx, struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready); - -#if defined(ENABLE_LOGGING) -const char *windows_error_str(DWORD error_code); -#endif diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/windows_usbdk.c b/vendor/github.com/karalabe/hid/libusb/libusb/os/windows_usbdk.c deleted file mode 100644 index 7cc57938..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/windows_usbdk.c +++ /dev/null @@ -1,905 +0,0 @@ -/* - * windows UsbDk backend for libusb 1.0 - * Copyright © 2014 Red Hat, Inc. - - * Authors: - * Dmitry Fleytman - * Pavel Gurvich - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include - -#if defined(USE_USBDK) - -#include -#include -#include - -#include "libusbi.h" -#include "windows_common.h" -#include "windows_nt_common.h" - -#define ULONG64 uint64_t -#define PVOID64 uint64_t - -typedef CONST WCHAR *PCWCHAR; -#define wcsncpy_s wcsncpy - -#include "windows_usbdk.h" - -#if !defined(STATUS_SUCCESS) -typedef LONG NTSTATUS; -#define STATUS_SUCCESS ((NTSTATUS)0x00000000L) -#endif - -#if !defined(STATUS_CANCELLED) -#define STATUS_CANCELLED ((NTSTATUS)0xC0000120L) -#endif - -#if !defined(STATUS_REQUEST_CANCELED) -#define STATUS_REQUEST_CANCELED ((NTSTATUS)0xC0000703L) -#endif - -#if !defined(USBD_SUCCESS) -typedef int32_t USBD_STATUS; -#define USBD_SUCCESS(Status) ((USBD_STATUS) (Status) >= 0) -#define USBD_PENDING(Status) ((ULONG) (Status) >> 30 == 1) -#define USBD_ERROR(Status) ((USBD_STATUS) (Status) < 0) -#define USBD_STATUS_STALL_PID ((USBD_STATUS) 0xc0000004) -#define USBD_STATUS_ENDPOINT_HALTED ((USBD_STATUS) 0xc0000030) -#define USBD_STATUS_BAD_START_FRAME ((USBD_STATUS) 0xc0000a00) -#define USBD_STATUS_TIMEOUT ((USBD_STATUS) 0xc0006000) -#define USBD_STATUS_CANCELED ((USBD_STATUS) 0xc0010000) -#endif - -static int concurrent_usage = -1; - -struct usbdk_device_priv { - USB_DK_DEVICE_INFO info; - PUSB_CONFIGURATION_DESCRIPTOR *config_descriptors; - HANDLE redirector_handle; - uint8_t active_configuration; -}; - -struct usbdk_transfer_priv { - USB_DK_TRANSFER_REQUEST request; - struct winfd pollable_fd; - PULONG64 IsochronousPacketsArray; - PUSB_DK_ISO_TRANSFER_RESULT IsochronousResultsArray; -}; - -static inline struct usbdk_device_priv *_usbdk_device_priv(struct libusb_device *dev) -{ - return (struct usbdk_device_priv *)dev->os_priv; -} - -static inline struct usbdk_transfer_priv *_usbdk_transfer_priv(struct usbi_transfer *itransfer) -{ - return (struct usbdk_transfer_priv *)usbi_transfer_get_os_priv(itransfer); -} - -static struct { - HMODULE module; - - USBDK_GET_DEVICES_LIST GetDevicesList; - USBDK_RELEASE_DEVICES_LIST ReleaseDevicesList; - USBDK_START_REDIRECT StartRedirect; - USBDK_STOP_REDIRECT StopRedirect; - USBDK_GET_CONFIGURATION_DESCRIPTOR GetConfigurationDescriptor; - USBDK_RELEASE_CONFIGURATION_DESCRIPTOR ReleaseConfigurationDescriptor; - USBDK_READ_PIPE ReadPipe; - USBDK_WRITE_PIPE WritePipe; - USBDK_ABORT_PIPE AbortPipe; - USBDK_RESET_PIPE ResetPipe; - USBDK_SET_ALTSETTING SetAltsetting; - USBDK_RESET_DEVICE ResetDevice; - USBDK_GET_REDIRECTOR_SYSTEM_HANDLE GetRedirectorSystemHandle; -} usbdk_helper; - -static FARPROC get_usbdk_proc_addr(struct libusb_context *ctx, LPCSTR api_name) -{ - FARPROC api_ptr = GetProcAddress(usbdk_helper.module, api_name); - - if (api_ptr == NULL) - usbi_err(ctx, "UsbDkHelper API %s not found, error %d", api_name, GetLastError()); - - return api_ptr; -} - -static void unload_usbdk_helper_dll(void) -{ - if (usbdk_helper.module != NULL) { - FreeLibrary(usbdk_helper.module); - usbdk_helper.module = NULL; - } -} - -static int load_usbdk_helper_dll(struct libusb_context *ctx) -{ - usbdk_helper.module = LoadLibraryA("UsbDkHelper"); - if (usbdk_helper.module == NULL) { - usbi_err(ctx, "Failed to load UsbDkHelper.dll, error %d", GetLastError()); - return LIBUSB_ERROR_NOT_FOUND; - } - - usbdk_helper.GetDevicesList = (USBDK_GET_DEVICES_LIST)get_usbdk_proc_addr(ctx, "UsbDk_GetDevicesList"); - if (usbdk_helper.GetDevicesList == NULL) - goto error_unload; - - usbdk_helper.ReleaseDevicesList = (USBDK_RELEASE_DEVICES_LIST)get_usbdk_proc_addr(ctx, "UsbDk_ReleaseDevicesList"); - if (usbdk_helper.ReleaseDevicesList == NULL) - goto error_unload; - - usbdk_helper.StartRedirect = (USBDK_START_REDIRECT)get_usbdk_proc_addr(ctx, "UsbDk_StartRedirect"); - if (usbdk_helper.StartRedirect == NULL) - goto error_unload; - - usbdk_helper.StopRedirect = (USBDK_STOP_REDIRECT)get_usbdk_proc_addr(ctx, "UsbDk_StopRedirect"); - if (usbdk_helper.StopRedirect == NULL) - goto error_unload; - - usbdk_helper.GetConfigurationDescriptor = (USBDK_GET_CONFIGURATION_DESCRIPTOR)get_usbdk_proc_addr(ctx, "UsbDk_GetConfigurationDescriptor"); - if (usbdk_helper.GetConfigurationDescriptor == NULL) - goto error_unload; - - usbdk_helper.ReleaseConfigurationDescriptor = (USBDK_RELEASE_CONFIGURATION_DESCRIPTOR)get_usbdk_proc_addr(ctx, "UsbDk_ReleaseConfigurationDescriptor"); - if (usbdk_helper.ReleaseConfigurationDescriptor == NULL) - goto error_unload; - - usbdk_helper.ReadPipe = (USBDK_READ_PIPE)get_usbdk_proc_addr(ctx, "UsbDk_ReadPipe"); - if (usbdk_helper.ReadPipe == NULL) - goto error_unload; - - usbdk_helper.WritePipe = (USBDK_WRITE_PIPE)get_usbdk_proc_addr(ctx, "UsbDk_WritePipe"); - if (usbdk_helper.WritePipe == NULL) - goto error_unload; - - usbdk_helper.AbortPipe = (USBDK_ABORT_PIPE)get_usbdk_proc_addr(ctx, "UsbDk_AbortPipe"); - if (usbdk_helper.AbortPipe == NULL) - goto error_unload; - - usbdk_helper.ResetPipe = (USBDK_RESET_PIPE)get_usbdk_proc_addr(ctx, "UsbDk_ResetPipe"); - if (usbdk_helper.ResetPipe == NULL) - goto error_unload; - - usbdk_helper.SetAltsetting = (USBDK_SET_ALTSETTING)get_usbdk_proc_addr(ctx, "UsbDk_SetAltsetting"); - if (usbdk_helper.SetAltsetting == NULL) - goto error_unload; - - usbdk_helper.ResetDevice = (USBDK_RESET_DEVICE)get_usbdk_proc_addr(ctx, "UsbDk_ResetDevice"); - if (usbdk_helper.ResetDevice == NULL) - goto error_unload; - - usbdk_helper.GetRedirectorSystemHandle = (USBDK_GET_REDIRECTOR_SYSTEM_HANDLE)get_usbdk_proc_addr(ctx, "UsbDk_GetRedirectorSystemHandle"); - if (usbdk_helper.GetRedirectorSystemHandle == NULL) - goto error_unload; - - return LIBUSB_SUCCESS; - -error_unload: - FreeLibrary(usbdk_helper.module); - usbdk_helper.module = NULL; - return LIBUSB_ERROR_NOT_FOUND; -} - -static int usbdk_init(struct libusb_context *ctx) -{ - int r; - - if (++concurrent_usage == 0) { // First init? - r = load_usbdk_helper_dll(ctx); - if (r) - goto init_exit; - - init_polling(); - - r = windows_common_init(ctx); - if (r) - goto init_exit; - } - // At this stage, either we went through full init successfully, or didn't need to - r = LIBUSB_SUCCESS; - -init_exit: - if (!concurrent_usage && r != LIBUSB_SUCCESS) { // First init failed? - exit_polling(); - windows_common_exit(); - unload_usbdk_helper_dll(); - } - - if (r != LIBUSB_SUCCESS) - --concurrent_usage; // Not expected to call libusb_exit if we failed. - - return r; -} - -static int usbdk_get_session_id_for_device(struct libusb_context *ctx, - PUSB_DK_DEVICE_ID id, unsigned long *session_id) -{ - char dev_identity[ARRAYSIZE(id->DeviceID) + ARRAYSIZE(id->InstanceID)]; - - if (sprintf(dev_identity, "%S%S", id->DeviceID, id->InstanceID) == -1) { - usbi_warn(ctx, "cannot form device identity", id->DeviceID); - return LIBUSB_ERROR_NOT_SUPPORTED; - } - - *session_id = htab_hash(dev_identity); - - return LIBUSB_SUCCESS; -} - -static void usbdk_release_config_descriptors(struct usbdk_device_priv *p, uint8_t count) -{ - uint8_t i; - - for (i = 0; i < count; i++) - usbdk_helper.ReleaseConfigurationDescriptor(p->config_descriptors[i]); - - free(p->config_descriptors); - p->config_descriptors = NULL; -} - -static int usbdk_cache_config_descriptors(struct libusb_context *ctx, - struct usbdk_device_priv *p, PUSB_DK_DEVICE_INFO info) -{ - uint8_t i; - USB_DK_CONFIG_DESCRIPTOR_REQUEST Request; - Request.ID = info->ID; - - p->config_descriptors = calloc(info->DeviceDescriptor.bNumConfigurations, sizeof(PUSB_CONFIGURATION_DESCRIPTOR)); - if (p->config_descriptors == NULL) { - usbi_err(ctx, "failed to allocate configuration descriptors holder"); - return LIBUSB_ERROR_NO_MEM; - } - - for (i = 0; i < info->DeviceDescriptor.bNumConfigurations; i++) { - ULONG Length; - - Request.Index = i; - if (!usbdk_helper.GetConfigurationDescriptor(&Request, &p->config_descriptors[i], &Length)) { - usbi_err(ctx, "failed to retrieve configuration descriptors"); - usbdk_release_config_descriptors(p, i); - return LIBUSB_ERROR_OTHER; - } - } - - return LIBUSB_SUCCESS; -} - -static inline int usbdk_device_priv_init(struct libusb_context *ctx, struct libusb_device *dev, PUSB_DK_DEVICE_INFO info) -{ - struct usbdk_device_priv *p = _usbdk_device_priv(dev); - - p->info = *info; - p->active_configuration = 0; - - return usbdk_cache_config_descriptors(ctx, p, info); -} - -static void usbdk_device_init(libusb_device *dev, PUSB_DK_DEVICE_INFO info) -{ - dev->bus_number = (uint8_t)info->FilterID; - dev->port_number = (uint8_t)info->Port; - dev->parent_dev = NULL; - - //Addresses in libusb are 1-based - dev->device_address = (uint8_t)(info->Port + 1); - - dev->num_configurations = info->DeviceDescriptor.bNumConfigurations; - dev->device_descriptor = info->DeviceDescriptor; - - switch (info->Speed) { - case LowSpeed: - dev->speed = LIBUSB_SPEED_LOW; - break; - case FullSpeed: - dev->speed = LIBUSB_SPEED_FULL; - break; - case HighSpeed: - dev->speed = LIBUSB_SPEED_HIGH; - break; - case SuperSpeed: - dev->speed = LIBUSB_SPEED_SUPER; - break; - case NoSpeed: - default: - dev->speed = LIBUSB_SPEED_UNKNOWN; - break; - } -} - -static int usbdk_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) -{ - int r = LIBUSB_SUCCESS; - ULONG i; - struct discovered_devs *discdevs = NULL; - ULONG dev_number; - PUSB_DK_DEVICE_INFO devices; - - if(!usbdk_helper.GetDevicesList(&devices, &dev_number)) - return LIBUSB_ERROR_OTHER; - - for (i = 0; i < dev_number; i++) { - unsigned long session_id; - struct libusb_device *dev = NULL; - - if (usbdk_get_session_id_for_device(ctx, &devices[i].ID, &session_id)) - continue; - - dev = usbi_get_device_by_session_id(ctx, session_id); - if (dev == NULL) { - dev = usbi_alloc_device(ctx, session_id); - if (dev == NULL) { - usbi_err(ctx, "failed to allocate a new device structure"); - continue; - } - - usbdk_device_init(dev, &devices[i]); - if (usbdk_device_priv_init(ctx, dev, &devices[i]) != LIBUSB_SUCCESS) { - libusb_unref_device(dev); - continue; - } - } - - discdevs = discovered_devs_append(*_discdevs, dev); - libusb_unref_device(dev); - if (!discdevs) { - usbi_err(ctx, "cannot append new device to list"); - r = LIBUSB_ERROR_NO_MEM; - goto func_exit; - } - - *_discdevs = discdevs; - } - -func_exit: - usbdk_helper.ReleaseDevicesList(devices); - return r; -} - -static void usbdk_exit(void) -{ - if (--concurrent_usage < 0) { - windows_common_exit(); - exit_polling(); - unload_usbdk_helper_dll(); - } -} - -static int usbdk_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) -{ - struct usbdk_device_priv *priv = _usbdk_device_priv(dev); - - memcpy(buffer, &priv->info.DeviceDescriptor, DEVICE_DESC_LENGTH); - *host_endian = 0; - - return LIBUSB_SUCCESS; -} - -static int usbdk_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) -{ - struct usbdk_device_priv *priv = _usbdk_device_priv(dev); - PUSB_CONFIGURATION_DESCRIPTOR config_header; - size_t size; - - if (config_index >= dev->num_configurations) - return LIBUSB_ERROR_INVALID_PARAM; - - config_header = (PUSB_CONFIGURATION_DESCRIPTOR)priv->config_descriptors[config_index]; - - size = min(config_header->wTotalLength, len); - memcpy(buffer, config_header, size); - *host_endian = 0; - - return (int)size; -} - -static inline int usbdk_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) -{ - return usbdk_get_config_descriptor(dev, _usbdk_device_priv(dev)->active_configuration, - buffer, len, host_endian); -} - -static int usbdk_open(struct libusb_device_handle *dev_handle) -{ - struct usbdk_device_priv *priv = _usbdk_device_priv(dev_handle->dev); - - priv->redirector_handle = usbdk_helper.StartRedirect(&priv->info.ID); - if (priv->redirector_handle == INVALID_HANDLE_VALUE) { - usbi_err(DEVICE_CTX(dev_handle->dev), "Redirector startup failed"); - return LIBUSB_ERROR_OTHER; - } - - return LIBUSB_SUCCESS; -} - -static void usbdk_close(struct libusb_device_handle *dev_handle) -{ - struct usbdk_device_priv *priv = _usbdk_device_priv(dev_handle->dev); - - if (!usbdk_helper.StopRedirect(priv->redirector_handle)) { - struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev); - usbi_err(ctx, "Redirector shutdown failed"); - } -} - -static int usbdk_get_configuration(struct libusb_device_handle *dev_handle, int *config) -{ - *config = _usbdk_device_priv(dev_handle->dev)->active_configuration; - - return LIBUSB_SUCCESS; -} - -static int usbdk_set_configuration(struct libusb_device_handle *dev_handle, int config) -{ - UNUSED(dev_handle); - UNUSED(config); - return LIBUSB_SUCCESS; -} - -static int usbdk_claim_interface(struct libusb_device_handle *dev_handle, int iface) -{ - UNUSED(dev_handle); - UNUSED(iface); - return LIBUSB_SUCCESS; -} - -static int usbdk_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) -{ - struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev); - struct usbdk_device_priv *priv = _usbdk_device_priv(dev_handle->dev); - - if (!usbdk_helper.SetAltsetting(priv->redirector_handle, iface, altsetting)) { - usbi_err(ctx, "SetAltsetting failed: %s", windows_error_str(0)); - return LIBUSB_ERROR_NO_DEVICE; - } - - return LIBUSB_SUCCESS; -} - -static int usbdk_release_interface(struct libusb_device_handle *dev_handle, int iface) -{ - UNUSED(dev_handle); - UNUSED(iface); - return LIBUSB_SUCCESS; -} - -static int usbdk_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) -{ - struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev); - struct usbdk_device_priv *priv = _usbdk_device_priv(dev_handle->dev); - - if (!usbdk_helper.ResetPipe(priv->redirector_handle, endpoint)) { - usbi_err(ctx, "ResetPipe failed: %s", windows_error_str(0)); - return LIBUSB_ERROR_NO_DEVICE; - } - - return LIBUSB_SUCCESS; -} - -static int usbdk_reset_device(struct libusb_device_handle *dev_handle) -{ - struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev); - struct usbdk_device_priv *priv = _usbdk_device_priv(dev_handle->dev); - - if (!usbdk_helper.ResetDevice(priv->redirector_handle)) { - usbi_err(ctx, "ResetDevice failed: %s", windows_error_str(0)); - return LIBUSB_ERROR_NO_DEVICE; - } - - return LIBUSB_SUCCESS; -} - -static int usbdk_kernel_driver_active(struct libusb_device_handle *dev_handle, int iface) -{ - UNUSED(dev_handle); - UNUSED(iface); - return LIBUSB_ERROR_NOT_SUPPORTED; -} - -static int usbdk_attach_kernel_driver(struct libusb_device_handle *dev_handle, int iface) -{ - UNUSED(dev_handle); - UNUSED(iface); - return LIBUSB_ERROR_NOT_SUPPORTED; -} - -static int usbdk_detach_kernel_driver(struct libusb_device_handle *dev_handle, int iface) -{ - UNUSED(dev_handle); - UNUSED(iface); - return LIBUSB_ERROR_NOT_SUPPORTED; -} - -static void usbdk_destroy_device(struct libusb_device *dev) -{ - struct usbdk_device_priv* p = _usbdk_device_priv(dev); - - if (p->config_descriptors != NULL) - usbdk_release_config_descriptors(p, p->info.DeviceDescriptor.bNumConfigurations); -} - -void windows_clear_transfer_priv(struct usbi_transfer *itransfer) -{ - struct usbdk_transfer_priv *transfer_priv = _usbdk_transfer_priv(itransfer); - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - - usbi_free_fd(&transfer_priv->pollable_fd); - - if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS) { - safe_free(transfer_priv->IsochronousPacketsArray); - safe_free(transfer_priv->IsochronousResultsArray); - } -} - -static int usbdk_do_control_transfer(struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct usbdk_device_priv *priv = _usbdk_device_priv(transfer->dev_handle->dev); - struct usbdk_transfer_priv *transfer_priv = _usbdk_transfer_priv(itransfer); - struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev); - struct winfd wfd; - ULONG Length; - TransferResult transResult; - HANDLE sysHandle; - - sysHandle = usbdk_helper.GetRedirectorSystemHandle(priv->redirector_handle); - - wfd = usbi_create_fd(sysHandle, RW_READ, NULL, NULL); - // Always use the handle returned from usbi_create_fd (wfd.handle) - if (wfd.fd < 0) - return LIBUSB_ERROR_NO_MEM; - - transfer_priv->request.Buffer = (PVOID64)(uintptr_t)transfer->buffer; - transfer_priv->request.BufferLength = transfer->length; - transfer_priv->request.TransferType = ControlTransferType; - transfer_priv->pollable_fd = INVALID_WINFD; - Length = (ULONG)transfer->length; - - if (IS_XFERIN(transfer)) - transResult = usbdk_helper.ReadPipe(priv->redirector_handle, &transfer_priv->request, wfd.overlapped); - else - transResult = usbdk_helper.WritePipe(priv->redirector_handle, &transfer_priv->request, wfd.overlapped); - - switch (transResult) { - case TransferSuccess: - wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY; - wfd.overlapped->InternalHigh = (DWORD)Length; - break; - case TransferSuccessAsync: - break; - case TransferFailure: - usbi_err(ctx, "ControlTransfer failed: %s", windows_error_str(0)); - usbi_free_fd(&wfd); - return LIBUSB_ERROR_IO; - } - - // Use priv_transfer to store data needed for async polling - transfer_priv->pollable_fd = wfd; - usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd, POLLIN); - - return LIBUSB_SUCCESS; -} - -static int usbdk_do_bulk_transfer(struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct usbdk_device_priv *priv = _usbdk_device_priv(transfer->dev_handle->dev); - struct usbdk_transfer_priv *transfer_priv = _usbdk_transfer_priv(itransfer); - struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev); - struct winfd wfd; - TransferResult transferRes; - HANDLE sysHandle; - - transfer_priv->request.Buffer = (PVOID64)(uintptr_t)transfer->buffer; - transfer_priv->request.BufferLength = transfer->length; - transfer_priv->request.EndpointAddress = transfer->endpoint; - - switch (transfer->type) { - case LIBUSB_TRANSFER_TYPE_BULK: - transfer_priv->request.TransferType = BulkTransferType; - break; - case LIBUSB_TRANSFER_TYPE_INTERRUPT: - transfer_priv->request.TransferType = IntertuptTransferType; - break; - default: - usbi_err(ctx, "Wrong transfer type (%d) in usbdk_do_bulk_transfer. %s", transfer->type, windows_error_str(0)); - return LIBUSB_ERROR_INVALID_PARAM; - } - - transfer_priv->pollable_fd = INVALID_WINFD; - - sysHandle = usbdk_helper.GetRedirectorSystemHandle(priv->redirector_handle); - - wfd = usbi_create_fd(sysHandle, IS_XFERIN(transfer) ? RW_READ : RW_WRITE, NULL, NULL); - // Always use the handle returned from usbi_create_fd (wfd.handle) - if (wfd.fd < 0) - return LIBUSB_ERROR_NO_MEM; - - if (IS_XFERIN(transfer)) - transferRes = usbdk_helper.ReadPipe(priv->redirector_handle, &transfer_priv->request, wfd.overlapped); - else - transferRes = usbdk_helper.WritePipe(priv->redirector_handle, &transfer_priv->request, wfd.overlapped); - - switch (transferRes) { - case TransferSuccess: - wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY; - break; - case TransferSuccessAsync: - break; - case TransferFailure: - usbi_err(ctx, "ReadPipe/WritePipe failed: %s", windows_error_str(0)); - usbi_free_fd(&wfd); - return LIBUSB_ERROR_IO; - } - - transfer_priv->pollable_fd = wfd; - usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd, IS_XFERIN(transfer) ? POLLIN : POLLOUT); - - return LIBUSB_SUCCESS; -} - -static int usbdk_do_iso_transfer(struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct usbdk_device_priv *priv = _usbdk_device_priv(transfer->dev_handle->dev); - struct usbdk_transfer_priv *transfer_priv = _usbdk_transfer_priv(itransfer); - struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev); - struct winfd wfd; - TransferResult transferRes; - int i; - HANDLE sysHandle; - - transfer_priv->request.Buffer = (PVOID64)(uintptr_t)transfer->buffer; - transfer_priv->request.BufferLength = transfer->length; - transfer_priv->request.EndpointAddress = transfer->endpoint; - transfer_priv->request.TransferType = IsochronousTransferType; - transfer_priv->request.IsochronousPacketsArraySize = transfer->num_iso_packets; - transfer_priv->IsochronousPacketsArray = malloc(transfer->num_iso_packets * sizeof(ULONG64)); - transfer_priv->request.IsochronousPacketsArray = (PVOID64)(uintptr_t)transfer_priv->IsochronousPacketsArray; - if (!transfer_priv->IsochronousPacketsArray) { - usbi_err(ctx, "Allocation of IsochronousPacketsArray is failed, %s", windows_error_str(0)); - return LIBUSB_ERROR_IO; - } - - transfer_priv->IsochronousResultsArray = malloc(transfer->num_iso_packets * sizeof(USB_DK_ISO_TRANSFER_RESULT)); - transfer_priv->request.Result.IsochronousResultsArray = (PVOID64)(uintptr_t)transfer_priv->IsochronousResultsArray; - if (!transfer_priv->IsochronousResultsArray) { - usbi_err(ctx, "Allocation of isochronousResultsArray is failed, %s", windows_error_str(0)); - free(transfer_priv->IsochronousPacketsArray); - return LIBUSB_ERROR_IO; - } - - for (i = 0; i < transfer->num_iso_packets; i++) - transfer_priv->IsochronousPacketsArray[i] = transfer->iso_packet_desc[i].length; - - transfer_priv->pollable_fd = INVALID_WINFD; - - sysHandle = usbdk_helper.GetRedirectorSystemHandle(priv->redirector_handle); - - wfd = usbi_create_fd(sysHandle, IS_XFERIN(transfer) ? RW_READ : RW_WRITE, NULL, NULL); - // Always use the handle returned from usbi_create_fd (wfd.handle) - if (wfd.fd < 0) { - free(transfer_priv->IsochronousPacketsArray); - free(transfer_priv->IsochronousResultsArray); - return LIBUSB_ERROR_NO_MEM; - } - - if (IS_XFERIN(transfer)) - transferRes = usbdk_helper.ReadPipe(priv->redirector_handle, &transfer_priv->request, wfd.overlapped); - else - transferRes = usbdk_helper.WritePipe(priv->redirector_handle, &transfer_priv->request, wfd.overlapped); - - switch (transferRes) { - case TransferSuccess: - wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY; - break; - case TransferSuccessAsync: - break; - case TransferFailure: - usbi_err(ctx, "ReadPipe/WritePipe failed: %s", windows_error_str(0)); - usbi_free_fd(&wfd); - free(transfer_priv->IsochronousPacketsArray); - free(transfer_priv->IsochronousResultsArray); - return LIBUSB_ERROR_IO; - } - - transfer_priv->pollable_fd = wfd; - usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd, IS_XFERIN(transfer) ? POLLIN : POLLOUT); - - return LIBUSB_SUCCESS; -} - -static int usbdk_submit_transfer(struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - - switch (transfer->type) { - case LIBUSB_TRANSFER_TYPE_CONTROL: - return usbdk_do_control_transfer(itransfer); - case LIBUSB_TRANSFER_TYPE_BULK: - case LIBUSB_TRANSFER_TYPE_INTERRUPT: - if (IS_XFEROUT(transfer) && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)) - return LIBUSB_ERROR_NOT_SUPPORTED; //TODO: Check whether we can support this in UsbDk - else - return usbdk_do_bulk_transfer(itransfer); - case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS: - return usbdk_do_iso_transfer(itransfer); - default: - usbi_err(TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type); - return LIBUSB_ERROR_INVALID_PARAM; - } -} - -static int usbdk_abort_transfers(struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev); - struct usbdk_device_priv *priv = _usbdk_device_priv(transfer->dev_handle->dev); - - if (!usbdk_helper.AbortPipe(priv->redirector_handle, transfer->endpoint)) { - usbi_err(ctx, "AbortPipe failed: %s", windows_error_str(0)); - return LIBUSB_ERROR_NO_DEVICE; - } - - return LIBUSB_SUCCESS; -} - -static int usbdk_cancel_transfer(struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - - switch (transfer->type) { - case LIBUSB_TRANSFER_TYPE_CONTROL: - // Control transfers cancelled by IoCancelXXX() API - // No special treatment needed - return LIBUSB_SUCCESS; - case LIBUSB_TRANSFER_TYPE_BULK: - case LIBUSB_TRANSFER_TYPE_INTERRUPT: - case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS: - return usbdk_abort_transfers(itransfer); - default: - usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type); - return LIBUSB_ERROR_INVALID_PARAM; - } -} - -int windows_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size) -{ - itransfer->transferred += io_size; - return LIBUSB_TRANSFER_COMPLETED; -} - -struct winfd *windows_get_fd(struct usbi_transfer *transfer) -{ - struct usbdk_transfer_priv *transfer_priv = _usbdk_transfer_priv(transfer); - return &transfer_priv->pollable_fd; -} - -static DWORD usbdk_translate_usbd_status(USBD_STATUS UsbdStatus) -{ - if (USBD_SUCCESS(UsbdStatus)) - return NO_ERROR; - - switch (UsbdStatus) { - case USBD_STATUS_STALL_PID: - case USBD_STATUS_ENDPOINT_HALTED: - case USBD_STATUS_BAD_START_FRAME: - return ERROR_GEN_FAILURE; - case USBD_STATUS_TIMEOUT: - return ERROR_SEM_TIMEOUT; - case USBD_STATUS_CANCELED: - return ERROR_OPERATION_ABORTED; - default: - return ERROR_FUNCTION_FAILED; - } -} - -void windows_get_overlapped_result(struct usbi_transfer *transfer, struct winfd *pollable_fd, DWORD *io_result, DWORD *io_size) -{ - if (HasOverlappedIoCompletedSync(pollable_fd->overlapped) // Handle async requests that completed synchronously first - || GetOverlappedResult(pollable_fd->handle, pollable_fd->overlapped, io_size, false)) { // Regular async overlapped - struct libusb_transfer *ltransfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer); - struct usbdk_transfer_priv *transfer_priv = _usbdk_transfer_priv(transfer); - - if (ltransfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS) { - int i; - for (i = 0; i < transfer_priv->request.IsochronousPacketsArraySize; i++) { - struct libusb_iso_packet_descriptor *lib_desc = <ransfer->iso_packet_desc[i]; - - switch (transfer_priv->IsochronousResultsArray[i].TransferResult) { - case STATUS_SUCCESS: - case STATUS_CANCELLED: - case STATUS_REQUEST_CANCELED: - lib_desc->status = LIBUSB_TRANSFER_COMPLETED; // == ERROR_SUCCESS - break; - default: - lib_desc->status = LIBUSB_TRANSFER_ERROR; // ERROR_UNKNOWN_EXCEPTION; - break; - } - - lib_desc->actual_length = (unsigned int)transfer_priv->IsochronousResultsArray[i].ActualLength; - } - } - - *io_size = (DWORD) transfer_priv->request.Result.GenResult.BytesTransferred; - *io_result = usbdk_translate_usbd_status((USBD_STATUS) transfer_priv->request.Result.GenResult.UsbdStatus); - } - else { - *io_result = GetLastError(); - } -} - -static int usbdk_clock_gettime(int clk_id, struct timespec *tp) -{ - return windows_clock_gettime(clk_id, tp); -} - -const struct usbi_os_backend usbdk_backend = { - "Windows", - USBI_CAP_HAS_HID_ACCESS, - usbdk_init, - usbdk_exit, - - usbdk_get_device_list, - NULL, - usbdk_open, - usbdk_close, - - usbdk_get_device_descriptor, - usbdk_get_active_config_descriptor, - usbdk_get_config_descriptor, - NULL, - - usbdk_get_configuration, - usbdk_set_configuration, - usbdk_claim_interface, - usbdk_release_interface, - - usbdk_set_interface_altsetting, - usbdk_clear_halt, - usbdk_reset_device, - - NULL, - NULL, - - NULL, // dev_mem_alloc() - NULL, // dev_mem_free() - - usbdk_kernel_driver_active, - usbdk_detach_kernel_driver, - usbdk_attach_kernel_driver, - - usbdk_destroy_device, - - usbdk_submit_transfer, - usbdk_cancel_transfer, - windows_clear_transfer_priv, - - windows_handle_events, - NULL, - - usbdk_clock_gettime, -#if defined(USBI_TIMERFD_AVAILABLE) - NULL, -#endif - sizeof(struct usbdk_device_priv), - 0, - sizeof(struct usbdk_transfer_priv), -}; - -#endif /* USE_USBDK */ diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/windows_usbdk.h b/vendor/github.com/karalabe/hid/libusb/libusb/os/windows_usbdk.h deleted file mode 100644 index 04a9787f..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/windows_usbdk.h +++ /dev/null @@ -1,146 +0,0 @@ -/* -* windows UsbDk backend for libusb 1.0 -* Copyright © 2014 Red Hat, Inc. - -* Authors: -* Dmitry Fleytman -* Pavel Gurvich -* -* This 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 2.1 of the License, or (at your option) any later version. -* -* This 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 this library; if not, write to the Free Software -* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#pragma once - -typedef struct tag_USB_DK_DEVICE_ID { - WCHAR DeviceID[MAX_DEVICE_ID_LEN]; - WCHAR InstanceID[MAX_DEVICE_ID_LEN]; -} USB_DK_DEVICE_ID, *PUSB_DK_DEVICE_ID; - -static inline void UsbDkFillIDStruct(USB_DK_DEVICE_ID *ID, PCWCHAR DeviceID, PCWCHAR InstanceID) -{ - wcsncpy_s(ID->DeviceID, DeviceID, MAX_DEVICE_ID_LEN); - wcsncpy_s(ID->InstanceID, InstanceID, MAX_DEVICE_ID_LEN); -} - -typedef struct tag_USB_DK_DEVICE_INFO { - USB_DK_DEVICE_ID ID; - ULONG64 FilterID; - ULONG64 Port; - ULONG64 Speed; - USB_DEVICE_DESCRIPTOR DeviceDescriptor; -} USB_DK_DEVICE_INFO, *PUSB_DK_DEVICE_INFO; - -typedef struct tag_USB_DK_CONFIG_DESCRIPTOR_REQUEST { - USB_DK_DEVICE_ID ID; - ULONG64 Index; -} USB_DK_CONFIG_DESCRIPTOR_REQUEST, *PUSB_DK_CONFIG_DESCRIPTOR_REQUEST; - -typedef struct tag_USB_DK_ISO_TRANSFER_RESULT { - ULONG64 ActualLength; - ULONG64 TransferResult; -} USB_DK_ISO_TRANSFER_RESULT, *PUSB_DK_ISO_TRANSFER_RESULT; - -typedef struct tag_USB_DK_GEN_TRANSFER_RESULT { - ULONG64 BytesTransferred; - ULONG64 UsbdStatus; // USBD_STATUS code -} USB_DK_GEN_TRANSFER_RESULT, *PUSB_DK_GEN_TRANSFER_RESULT; - -typedef struct tag_USB_DK_TRANSFER_RESULT { - USB_DK_GEN_TRANSFER_RESULT GenResult; - PVOID64 IsochronousResultsArray; // array of USB_DK_ISO_TRANSFER_RESULT -} USB_DK_TRANSFER_RESULT, *PUSB_DK_TRANSFER_RESULT; - -typedef struct tag_USB_DK_TRANSFER_REQUEST { - ULONG64 EndpointAddress; - PVOID64 Buffer; - ULONG64 BufferLength; - ULONG64 TransferType; - ULONG64 IsochronousPacketsArraySize; - PVOID64 IsochronousPacketsArray; - - USB_DK_TRANSFER_RESULT Result; -} USB_DK_TRANSFER_REQUEST, *PUSB_DK_TRANSFER_REQUEST; - -typedef enum { - TransferFailure = 0, - TransferSuccess, - TransferSuccessAsync -} TransferResult; - -typedef enum { - NoSpeed = 0, - LowSpeed, - FullSpeed, - HighSpeed, - SuperSpeed -} USB_DK_DEVICE_SPEED; - -typedef enum { - ControlTransferType, - BulkTransferType, - IntertuptTransferType, - IsochronousTransferType -} USB_DK_TRANSFER_TYPE; - -typedef BOOL (__cdecl *USBDK_GET_DEVICES_LIST)( - PUSB_DK_DEVICE_INFO *DeviceInfo, - PULONG DeviceNumber -); -typedef void (__cdecl *USBDK_RELEASE_DEVICES_LIST)( - PUSB_DK_DEVICE_INFO DeviceInfo -); -typedef HANDLE (__cdecl *USBDK_START_REDIRECT)( - PUSB_DK_DEVICE_ID DeviceId -); -typedef BOOL (__cdecl *USBDK_STOP_REDIRECT)( - HANDLE DeviceHandle -); -typedef BOOL (__cdecl *USBDK_GET_CONFIGURATION_DESCRIPTOR)( - PUSB_DK_CONFIG_DESCRIPTOR_REQUEST Request, - PUSB_CONFIGURATION_DESCRIPTOR *Descriptor, - PULONG Length -); -typedef void (__cdecl *USBDK_RELEASE_CONFIGURATION_DESCRIPTOR)( - PUSB_CONFIGURATION_DESCRIPTOR Descriptor -); -typedef TransferResult (__cdecl *USBDK_WRITE_PIPE)( - HANDLE DeviceHandle, - PUSB_DK_TRANSFER_REQUEST Request, - LPOVERLAPPED lpOverlapped -); -typedef TransferResult (__cdecl *USBDK_READ_PIPE)( - HANDLE DeviceHandle, - PUSB_DK_TRANSFER_REQUEST Request, - LPOVERLAPPED lpOverlapped -); -typedef BOOL (__cdecl *USBDK_ABORT_PIPE)( - HANDLE DeviceHandle, - ULONG64 PipeAddress -); -typedef BOOL (__cdecl *USBDK_RESET_PIPE)( - HANDLE DeviceHandle, - ULONG64 PipeAddress -); -typedef BOOL (__cdecl *USBDK_SET_ALTSETTING)( - HANDLE DeviceHandle, - ULONG64 InterfaceIdx, - ULONG64 AltSettingIdx -); -typedef BOOL (__cdecl *USBDK_RESET_DEVICE)( - HANDLE DeviceHandle -); -typedef HANDLE (__cdecl *USBDK_GET_REDIRECTOR_SYSTEM_HANDLE)( - HANDLE DeviceHandle -); diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/windows_winusb.c b/vendor/github.com/karalabe/hid/libusb/libusb/os/windows_winusb.c deleted file mode 100644 index 0dce0ea6..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/windows_winusb.c +++ /dev/null @@ -1,4290 +0,0 @@ -/* - * windows backend for libusb 1.0 - * Copyright © 2009-2012 Pete Batard - * With contributions from Michael Plante, Orin Eman et al. - * Parts of this code adapted from libusb-win32-v1 by Stephan Meyer - * HID Reports IOCTLs inspired from HIDAPI by Alan Ott, Signal 11 Software - * Hash table functions adapted from glibc, by Ulrich Drepper et al. - * Major code testing contribution by Xiaofan Chen - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include - -#if !defined(USE_USBDK) - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "libusbi.h" -#include "poll_windows.h" -#include "windows_winusb.h" - -#define HANDLE_VALID(h) (((h) != 0) && ((h) != INVALID_HANDLE_VALUE)) - -// The 2 macros below are used in conjunction with safe loops. -#define LOOP_CHECK(fcall) \ - { \ - r = fcall; \ - if (r != LIBUSB_SUCCESS) \ - continue; \ - } -#define LOOP_BREAK(err) \ - { \ - r = err; \ - continue; \ - } - -// WinUSB-like API prototypes -static int winusbx_init(int sub_api, struct libusb_context *ctx); -static int winusbx_exit(int sub_api); -static int winusbx_open(int sub_api, struct libusb_device_handle *dev_handle); -static void winusbx_close(int sub_api, struct libusb_device_handle *dev_handle); -static int winusbx_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface); -static int winusbx_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface); -static int winusbx_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface); -static int winusbx_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer); -static int winusbx_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting); -static int winusbx_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer); -static int winusbx_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint); -static int winusbx_abort_transfers(int sub_api, struct usbi_transfer *itransfer); -static int winusbx_abort_control(int sub_api, struct usbi_transfer *itransfer); -static int winusbx_reset_device(int sub_api, struct libusb_device_handle *dev_handle); -static int winusbx_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size); -// HID API prototypes -static int hid_init(int sub_api, struct libusb_context *ctx); -static int hid_exit(int sub_api); -static int hid_open(int sub_api, struct libusb_device_handle *dev_handle); -static void hid_close(int sub_api, struct libusb_device_handle *dev_handle); -static int hid_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface); -static int hid_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface); -static int hid_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting); -static int hid_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer); -static int hid_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer); -static int hid_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint); -static int hid_abort_transfers(int sub_api, struct usbi_transfer *itransfer); -static int hid_reset_device(int sub_api, struct libusb_device_handle *dev_handle); -static int hid_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size); -// Composite API prototypes -static int composite_init(int sub_api, struct libusb_context *ctx); -static int composite_exit(int sub_api); -static int composite_open(int sub_api, struct libusb_device_handle *dev_handle); -static void composite_close(int sub_api, struct libusb_device_handle *dev_handle); -static int composite_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface); -static int composite_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting); -static int composite_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface); -static int composite_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer); -static int composite_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer); -static int composite_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer); -static int composite_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint); -static int composite_abort_transfers(int sub_api, struct usbi_transfer *itransfer); -static int composite_abort_control(int sub_api, struct usbi_transfer *itransfer); -static int composite_reset_device(int sub_api, struct libusb_device_handle *dev_handle); -static int composite_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size); - - -// Global variables -int windows_version = WINDOWS_UNDEFINED; -static char windows_version_str[128] = "Undefined"; -// Concurrency -static int concurrent_usage = -1; -static usbi_mutex_t autoclaim_lock; -// API globals -#define CHECK_WINUSBX_AVAILABLE(sub_api) \ - do { \ - if (sub_api == SUB_API_NOTSET) \ - sub_api = priv->sub_api; \ - if (!WinUSBX[sub_api].initialized) \ - return LIBUSB_ERROR_ACCESS; \ - } while(0) - -static HMODULE WinUSBX_handle = NULL; -static struct winusb_interface WinUSBX[SUB_API_MAX]; -static const char *sub_api_name[SUB_API_MAX] = WINUSBX_DRV_NAMES; - -static bool api_hid_available = false; -#define CHECK_HID_AVAILABLE \ - do { \ - if (!api_hid_available) \ - return LIBUSB_ERROR_ACCESS; \ - } while (0) - -static inline BOOLEAN guid_eq(const GUID *guid1, const GUID *guid2) -{ - if ((guid1 != NULL) && (guid2 != NULL)) - return (memcmp(guid1, guid2, sizeof(GUID)) == 0); - - return false; -} - -#if defined(ENABLE_LOGGING) -static char *guid_to_string(const GUID *guid) -{ - static char guid_string[MAX_GUID_STRING_LENGTH]; - - if (guid == NULL) - return NULL; - - sprintf(guid_string, "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}", - (unsigned int)guid->Data1, guid->Data2, guid->Data3, - guid->Data4[0], guid->Data4[1], guid->Data4[2], guid->Data4[3], - guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7]); - - return guid_string; -} -#endif - -/* - * Sanitize Microsoft's paths: convert to uppercase, add prefix and fix backslashes. - * Return an allocated sanitized string or NULL on error. - */ -static char *sanitize_path(const char *path) -{ - const char root_prefix[] = { '\\', '\\', '.', '\\' }; - size_t j, size; - char *ret_path; - size_t add_root = 0; - - if (path == NULL) - return NULL; - - size = strlen(path) + 1; - - // Microsoft indiscriminately uses '\\?\', '\\.\', '##?#" or "##.#" for root prefixes. - if (!((size > 3) && (((path[0] == '\\') && (path[1] == '\\') && (path[3] == '\\')) - || ((path[0] == '#') && (path[1] == '#') && (path[3] == '#'))))) { - add_root = sizeof(root_prefix); - size += add_root; - } - - ret_path = malloc(size); - if (ret_path == NULL) - return NULL; - - strcpy(&ret_path[add_root], path); - - // Ensure consistency with root prefix - memcpy(ret_path, root_prefix, sizeof(root_prefix)); - - // Same goes for '\' and '#' after the root prefix. Ensure '#' is used - for (j = sizeof(root_prefix); j < size; j++) { - ret_path[j] = (char)toupper((int)ret_path[j]); // Fix case too - if (ret_path[j] == '\\') - ret_path[j] = '#'; - } - - return ret_path; -} - -/* - * Cfgmgr32, OLE32 and SetupAPI DLL functions - */ -static int init_dlls(void) -{ - DLL_GET_HANDLE(Cfgmgr32); - DLL_LOAD_FUNC(Cfgmgr32, CM_Get_Parent, TRUE); - DLL_LOAD_FUNC(Cfgmgr32, CM_Get_Child, TRUE); - DLL_LOAD_FUNC(Cfgmgr32, CM_Get_Sibling, TRUE); - DLL_LOAD_FUNC(Cfgmgr32, CM_Get_Device_IDA, TRUE); - - // Prefixed to avoid conflict with header files - DLL_GET_HANDLE(AdvAPI32); - DLL_LOAD_FUNC_PREFIXED(AdvAPI32, p, RegQueryValueExW, TRUE); - DLL_LOAD_FUNC_PREFIXED(AdvAPI32, p, RegCloseKey, TRUE); - - DLL_GET_HANDLE(Kernel32); - DLL_LOAD_FUNC_PREFIXED(Kernel32, p, IsWow64Process, FALSE); - - DLL_GET_HANDLE(OLE32); - DLL_LOAD_FUNC_PREFIXED(OLE32, p, CLSIDFromString, TRUE); - - DLL_GET_HANDLE(SetupAPI); - DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiGetClassDevsA, TRUE); - DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiEnumDeviceInfo, TRUE); - DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiEnumDeviceInterfaces, TRUE); - DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiGetDeviceInterfaceDetailA, TRUE); - DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiDestroyDeviceInfoList, TRUE); - DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiOpenDevRegKey, TRUE); - DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiGetDeviceRegistryPropertyA, TRUE); - DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiOpenDeviceInterfaceRegKey, TRUE); - - return LIBUSB_SUCCESS; -} - -static void exit_dlls(void) -{ - DLL_FREE_HANDLE(Cfgmgr32); - DLL_FREE_HANDLE(AdvAPI32); - DLL_FREE_HANDLE(Kernel32); - DLL_FREE_HANDLE(OLE32); - DLL_FREE_HANDLE(SetupAPI); -} - -/* - * enumerate interfaces for the whole USB class - * - * Parameters: - * dev_info: a pointer to a dev_info list - * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed) - * usb_class: the generic USB class for which to retrieve interface details - * index: zero based index of the interface in the device info list - * - * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA - * structure returned and call this function repeatedly using the same guid (with an - * incremented index starting at zero) until all interfaces have been returned. - */ -static bool get_devinfo_data(struct libusb_context *ctx, - HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const char *usb_class, unsigned _index) -{ - if (_index <= 0) { - *dev_info = pSetupDiGetClassDevsA(NULL, usb_class, NULL, DIGCF_PRESENT|DIGCF_ALLCLASSES); - if (*dev_info == INVALID_HANDLE_VALUE) - return false; - } - - dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA); - if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) { - if (GetLastError() != ERROR_NO_MORE_ITEMS) - usbi_err(ctx, "Could not obtain device info data for index %u: %s", - _index, windows_error_str(0)); - - pSetupDiDestroyDeviceInfoList(*dev_info); - *dev_info = INVALID_HANDLE_VALUE; - return false; - } - return true; -} - -/* - * enumerate interfaces for a specific GUID - * - * Parameters: - * dev_info: a pointer to a dev_info list - * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed) - * guid: the GUID for which to retrieve interface details - * index: zero based index of the interface in the device info list - * - * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA - * structure returned and call this function repeatedly using the same guid (with an - * incremented index starting at zero) until all interfaces have been returned. - */ -static SP_DEVICE_INTERFACE_DETAIL_DATA_A *get_interface_details(struct libusb_context *ctx, - HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const GUID *guid, unsigned _index) -{ - SP_DEVICE_INTERFACE_DATA dev_interface_data; - SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details; - DWORD size; - - if (_index <= 0) - *dev_info = pSetupDiGetClassDevsA(guid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE); - - if (dev_info_data != NULL) { - dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA); - if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) { - if (GetLastError() != ERROR_NO_MORE_ITEMS) - usbi_err(ctx, "Could not obtain device info data for index %u: %s", - _index, windows_error_str(0)); - - pSetupDiDestroyDeviceInfoList(*dev_info); - *dev_info = INVALID_HANDLE_VALUE; - return NULL; - } - } - - dev_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); - if (!pSetupDiEnumDeviceInterfaces(*dev_info, NULL, guid, _index, &dev_interface_data)) { - if (GetLastError() != ERROR_NO_MORE_ITEMS) - usbi_err(ctx, "Could not obtain interface data for index %u: %s", - _index, windows_error_str(0)); - - pSetupDiDestroyDeviceInfoList(*dev_info); - *dev_info = INVALID_HANDLE_VALUE; - return NULL; - } - - // Read interface data (dummy + actual) to access the device path - if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, NULL, 0, &size, NULL)) { - // The dummy call should fail with ERROR_INSUFFICIENT_BUFFER - if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) { - usbi_err(ctx, "could not access interface data (dummy) for index %u: %s", - _index, windows_error_str(0)); - goto err_exit; - } - } else { - usbi_err(ctx, "program assertion failed - http://msdn.microsoft.com/en-us/library/ms792901.aspx is wrong."); - goto err_exit; - } - - dev_interface_details = calloc(1, size); - if (dev_interface_details == NULL) { - usbi_err(ctx, "could not allocate interface data for index %u.", _index); - goto err_exit; - } - - dev_interface_details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A); - if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, - dev_interface_details, size, &size, NULL)) { - usbi_err(ctx, "could not access interface data (actual) for index %u: %s", - _index, windows_error_str(0)); - } - - return dev_interface_details; - -err_exit: - pSetupDiDestroyDeviceInfoList(*dev_info); - *dev_info = INVALID_HANDLE_VALUE; - return NULL; -} - -/* For libusb0 filter */ -static SP_DEVICE_INTERFACE_DETAIL_DATA_A *get_interface_details_filter(struct libusb_context *ctx, - HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const GUID *guid, unsigned _index, char *filter_path) -{ - SP_DEVICE_INTERFACE_DATA dev_interface_data; - SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details; - DWORD size; - - if (_index <= 0) - *dev_info = pSetupDiGetClassDevsA(guid, NULL, NULL, DIGCF_PRESENT|DIGCF_DEVICEINTERFACE); - - if (dev_info_data != NULL) { - dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA); - if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) { - if (GetLastError() != ERROR_NO_MORE_ITEMS) - usbi_err(ctx, "Could not obtain device info data for index %u: %s", - _index, windows_error_str(0)); - - pSetupDiDestroyDeviceInfoList(*dev_info); - *dev_info = INVALID_HANDLE_VALUE; - return NULL; - } - } - - dev_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); - if (!pSetupDiEnumDeviceInterfaces(*dev_info, NULL, guid, _index, &dev_interface_data)) { - if (GetLastError() != ERROR_NO_MORE_ITEMS) - usbi_err(ctx, "Could not obtain interface data for index %u: %s", - _index, windows_error_str(0)); - - pSetupDiDestroyDeviceInfoList(*dev_info); - *dev_info = INVALID_HANDLE_VALUE; - return NULL; - } - - // Read interface data (dummy + actual) to access the device path - if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, NULL, 0, &size, NULL)) { - // The dummy call should fail with ERROR_INSUFFICIENT_BUFFER - if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) { - usbi_err(ctx, "could not access interface data (dummy) for index %u: %s", - _index, windows_error_str(0)); - goto err_exit; - } - } else { - usbi_err(ctx, "program assertion failed - http://msdn.microsoft.com/en-us/library/ms792901.aspx is wrong."); - goto err_exit; - } - - dev_interface_details = calloc(1, size); - if (dev_interface_details == NULL) { - usbi_err(ctx, "could not allocate interface data for index %u.", _index); - goto err_exit; - } - - dev_interface_details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A); - if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, dev_interface_details, size, &size, NULL)) - usbi_err(ctx, "could not access interface data (actual) for index %u: %s", - _index, windows_error_str(0)); - - // [trobinso] lookup the libusb0 symbolic index. - if (dev_interface_details) { - HKEY hkey_device_interface = pSetupDiOpenDeviceInterfaceRegKey(*dev_info, &dev_interface_data, 0, KEY_READ); - if (hkey_device_interface != INVALID_HANDLE_VALUE) { - DWORD libusb0_symboliclink_index = 0; - DWORD value_length = sizeof(DWORD); - DWORD value_type = 0; - LONG status; - - status = pRegQueryValueExW(hkey_device_interface, L"LUsb0", NULL, &value_type, - (LPBYTE)&libusb0_symboliclink_index, &value_length); - if (status == ERROR_SUCCESS) { - if (libusb0_symboliclink_index < 256) { - // libusb0.sys is connected to this device instance. - // If the the device interface guid is {F9F3FF14-AE21-48A0-8A25-8011A7A931D9} then it's a filter. - sprintf(filter_path, "\\\\.\\libusb0-%04u", (unsigned int)libusb0_symboliclink_index); - usbi_dbg("assigned libusb0 symbolic link %s", filter_path); - } else { - // libusb0.sys was connected to this device instance at one time; but not anymore. - } - } - pRegCloseKey(hkey_device_interface); - } - } - - return dev_interface_details; - -err_exit: - pSetupDiDestroyDeviceInfoList(*dev_info); - *dev_info = INVALID_HANDLE_VALUE; - return NULL; -} - -/* - * Returns the session ID of a device's nth level ancestor - * If there's no device at the nth level, return 0 - */ -static unsigned long get_ancestor_session_id(DWORD devinst, unsigned level) -{ - DWORD parent_devinst; - unsigned long session_id; - char *sanitized_path; - char path[MAX_PATH_LENGTH]; - unsigned i; - - if (level < 1) - return 0; - - for (i = 0; i < level; i++) { - if (CM_Get_Parent(&parent_devinst, devinst, 0) != CR_SUCCESS) - return 0; - devinst = parent_devinst; - } - - if (CM_Get_Device_IDA(devinst, path, MAX_PATH_LENGTH, 0) != CR_SUCCESS) - return 0; - - // TODO: (post hotplug): try without sanitizing - sanitized_path = sanitize_path(path); - if (sanitized_path == NULL) - return 0; - - session_id = htab_hash(sanitized_path); - free(sanitized_path); - return session_id; -} - -/* - * Determine which interface the given endpoint address belongs to - */ -static int get_interface_by_endpoint(struct libusb_config_descriptor *conf_desc, uint8_t ep) -{ - const struct libusb_interface *intf; - const struct libusb_interface_descriptor *intf_desc; - int i, j, k; - - for (i = 0; i < conf_desc->bNumInterfaces; i++) { - intf = &conf_desc->interface[i]; - for (j = 0; j < intf->num_altsetting; j++) { - intf_desc = &intf->altsetting[j]; - for (k = 0; k < intf_desc->bNumEndpoints; k++) { - if (intf_desc->endpoint[k].bEndpointAddress == ep) { - usbi_dbg("found endpoint %02X on interface %d", intf_desc->bInterfaceNumber, i); - return intf_desc->bInterfaceNumber; - } - } - } - } - - usbi_dbg("endpoint %02X not found on any interface", ep); - return LIBUSB_ERROR_NOT_FOUND; -} - -/* - * Populate the endpoints addresses of the device_priv interface helper structs - */ -static int windows_assign_endpoints(struct libusb_device_handle *dev_handle, int iface, int altsetting) -{ - int i, r; - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - struct libusb_config_descriptor *conf_desc; - const struct libusb_interface_descriptor *if_desc; - struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev); - - r = libusb_get_active_config_descriptor(dev_handle->dev, &conf_desc); - if (r != LIBUSB_SUCCESS) { - usbi_warn(ctx, "could not read config descriptor: error %d", r); - return r; - } - - if_desc = &conf_desc->interface[iface].altsetting[altsetting]; - safe_free(priv->usb_interface[iface].endpoint); - - if (if_desc->bNumEndpoints == 0) { - usbi_dbg("no endpoints found for interface %d", iface); - libusb_free_config_descriptor(conf_desc); - return LIBUSB_SUCCESS; - } - - priv->usb_interface[iface].endpoint = malloc(if_desc->bNumEndpoints); - if (priv->usb_interface[iface].endpoint == NULL) { - libusb_free_config_descriptor(conf_desc); - return LIBUSB_ERROR_NO_MEM; - } - - priv->usb_interface[iface].nb_endpoints = if_desc->bNumEndpoints; - for (i = 0; i < if_desc->bNumEndpoints; i++) { - priv->usb_interface[iface].endpoint[i] = if_desc->endpoint[i].bEndpointAddress; - usbi_dbg("(re)assigned endpoint %02X to interface %d", priv->usb_interface[iface].endpoint[i], iface); - } - libusb_free_config_descriptor(conf_desc); - - // Extra init may be required to configure endpoints - return priv->apib->configure_endpoints(SUB_API_NOTSET, dev_handle, iface); -} - -// Lookup for a match in the list of API driver names -// return -1 if not found, driver match number otherwise -static int get_sub_api(char *driver, int api) -{ - int i; - const char sep_str[2] = {LIST_SEPARATOR, 0}; - char *tok, *tmp_str; - size_t len = strlen(driver); - - if (len == 0) - return SUB_API_NOTSET; - - tmp_str = _strdup(driver); - if (tmp_str == NULL) - return SUB_API_NOTSET; - - tok = strtok(tmp_str, sep_str); - while (tok != NULL) { - for (i = 0; i < usb_api_backend[api].nb_driver_names; i++) { - if (_stricmp(tok, usb_api_backend[api].driver_name_list[i]) == 0) { - free(tmp_str); - return i; - } - } - tok = strtok(NULL, sep_str); - } - - free(tmp_str); - return SUB_API_NOTSET; -} - -/* - * auto-claiming and auto-release helper functions - */ -static int auto_claim(struct libusb_transfer *transfer, int *interface_number, int api_type) -{ - struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev); - struct windows_device_handle_priv *handle_priv = _device_handle_priv( - transfer->dev_handle); - struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev); - int current_interface = *interface_number; - int r = LIBUSB_SUCCESS; - - switch(api_type) { - case USB_API_WINUSBX: - case USB_API_HID: - break; - default: - return LIBUSB_ERROR_INVALID_PARAM; - } - - usbi_mutex_lock(&autoclaim_lock); - if (current_interface < 0) { // No serviceable interface was found - for (current_interface = 0; current_interface < USB_MAXINTERFACES; current_interface++) { - // Must claim an interface of the same API type - if ((priv->usb_interface[current_interface].apib->id == api_type) - && (libusb_claim_interface(transfer->dev_handle, current_interface) == LIBUSB_SUCCESS)) { - usbi_dbg("auto-claimed interface %d for control request", current_interface); - if (handle_priv->autoclaim_count[current_interface] != 0) - usbi_warn(ctx, "program assertion failed - autoclaim_count was nonzero"); - handle_priv->autoclaim_count[current_interface]++; - break; - } - } - if (current_interface == USB_MAXINTERFACES) { - usbi_err(ctx, "could not auto-claim any interface"); - r = LIBUSB_ERROR_NOT_FOUND; - } - } else { - // If we have a valid interface that was autoclaimed, we must increment - // its autoclaim count so that we can prevent an early release. - if (handle_priv->autoclaim_count[current_interface] != 0) - handle_priv->autoclaim_count[current_interface]++; - } - usbi_mutex_unlock(&autoclaim_lock); - - *interface_number = current_interface; - return r; -} - -static void auto_release(struct usbi_transfer *itransfer) -{ - struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer); - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - libusb_device_handle *dev_handle = transfer->dev_handle; - struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle); - int r; - - usbi_mutex_lock(&autoclaim_lock); - if (handle_priv->autoclaim_count[transfer_priv->interface_number] > 0) { - handle_priv->autoclaim_count[transfer_priv->interface_number]--; - if (handle_priv->autoclaim_count[transfer_priv->interface_number] == 0) { - r = libusb_release_interface(dev_handle, transfer_priv->interface_number); - if (r == LIBUSB_SUCCESS) - usbi_dbg("auto-released interface %d", transfer_priv->interface_number); - else - usbi_dbg("failed to auto-release interface %d (%s)", - transfer_priv->interface_number, libusb_error_name((enum libusb_error)r)); - } - } - usbi_mutex_unlock(&autoclaim_lock); -} - -/* Windows version dtection */ -static BOOL is_x64(void) -{ - BOOL ret = FALSE; - - // Detect if we're running a 32 or 64 bit system - if (sizeof(uintptr_t) < 8) { - if (pIsWow64Process != NULL) - pIsWow64Process(GetCurrentProcess(), &ret); - } else { - ret = TRUE; - } - - return ret; -} - -static void get_windows_version(void) -{ - OSVERSIONINFOEXA vi, vi2; - const char *arch, *w = NULL; - unsigned major, minor; - ULONGLONG major_equal, minor_equal; - BOOL ws; - - memset(&vi, 0, sizeof(vi)); - vi.dwOSVersionInfoSize = sizeof(vi); - if (!GetVersionExA((OSVERSIONINFOA *)&vi)) { - memset(&vi, 0, sizeof(vi)); - vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA); - if (!GetVersionExA((OSVERSIONINFOA *)&vi)) - return; - } - - if (vi.dwPlatformId == VER_PLATFORM_WIN32_NT) { - if (vi.dwMajorVersion > 6 || (vi.dwMajorVersion == 6 && vi.dwMinorVersion >= 2)) { - // Starting with Windows 8.1 Preview, GetVersionEx() does no longer report the actual OS version - // See: http://msdn.microsoft.com/en-us/library/windows/desktop/dn302074.aspx - - major_equal = VerSetConditionMask(0, VER_MAJORVERSION, VER_EQUAL); - for (major = vi.dwMajorVersion; major <= 9; major++) { - memset(&vi2, 0, sizeof(vi2)); - vi2.dwOSVersionInfoSize = sizeof(vi2); - vi2.dwMajorVersion = major; - if (!VerifyVersionInfoA(&vi2, VER_MAJORVERSION, major_equal)) - continue; - - if (vi.dwMajorVersion < major) { - vi.dwMajorVersion = major; - vi.dwMinorVersion = 0; - } - - minor_equal = VerSetConditionMask(0, VER_MINORVERSION, VER_EQUAL); - for (minor = vi.dwMinorVersion; minor <= 9; minor++) { - memset(&vi2, 0, sizeof(vi2)); - vi2.dwOSVersionInfoSize = sizeof(vi2); - vi2.dwMinorVersion = minor; - if (!VerifyVersionInfoA(&vi2, VER_MINORVERSION, minor_equal)) - continue; - - vi.dwMinorVersion = minor; - break; - } - - break; - } - } - - if (vi.dwMajorVersion <= 0xf && vi.dwMinorVersion <= 0xf) { - ws = (vi.wProductType <= VER_NT_WORKSTATION); - windows_version = vi.dwMajorVersion << 4 | vi.dwMinorVersion; - switch (windows_version) { - case 0x50: w = "2000"; break; - case 0x51: w = "XP"; break; - case 0x52: w = "2003"; break; - case 0x60: w = (ws ? "Vista" : "2008"); break; - case 0x61: w = (ws ? "7" : "2008_R2"); break; - case 0x62: w = (ws ? "8" : "2012"); break; - case 0x63: w = (ws ? "8.1" : "2012_R2"); break; - case 0x64: w = (ws ? "10" : "2015"); break; - default: - if (windows_version < 0x50) - windows_version = WINDOWS_UNSUPPORTED; - else - w = "11 or later"; - break; - } - } - } - - arch = is_x64() ? "64-bit" : "32-bit"; - - if (w == NULL) - snprintf(windows_version_str, sizeof(windows_version_str), "%s %u.%u %s", - (vi.dwPlatformId == VER_PLATFORM_WIN32_NT ? "NT" : "??"), - (unsigned int)vi.dwMajorVersion, (unsigned int)vi.dwMinorVersion, arch); - else if (vi.wServicePackMinor) - snprintf(windows_version_str, sizeof(windows_version_str), "%s SP%u.%u %s", - w, vi.wServicePackMajor, vi.wServicePackMinor, arch); - else if (vi.wServicePackMajor) - snprintf(windows_version_str, sizeof(windows_version_str), "%s SP%u %s", - w, vi.wServicePackMajor, arch); - else - snprintf(windows_version_str, sizeof(windows_version_str), "%s %s", - w, arch); -} - -/* - * init: libusb backend init function - * - * This function enumerates the HCDs (Host Controller Drivers) and populates our private HCD list - * In our implementation, we equate Windows' "HCD" to libusb's "bus". Note that bus is zero indexed. - * HCDs are not expected to change after init (might not hold true for hot pluggable USB PCI card?) - */ -static int windows_init(struct libusb_context *ctx) -{ - int i, r = LIBUSB_ERROR_OTHER; - HANDLE semaphore; - char sem_name[11 + 8 + 1]; // strlen("libusb_init") + (32-bit hex PID) + '\0' - - sprintf(sem_name, "libusb_init%08X", (unsigned int)(GetCurrentProcessId() & 0xFFFFFFFF)); - semaphore = CreateSemaphoreA(NULL, 1, 1, sem_name); - if (semaphore == NULL) { - usbi_err(ctx, "could not create semaphore: %s", windows_error_str(0)); - return LIBUSB_ERROR_NO_MEM; - } - - // A successful wait brings our semaphore count to 0 (unsignaled) - // => any concurent wait stalls until the semaphore's release - if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) { - usbi_err(ctx, "failure to access semaphore: %s", windows_error_str(0)); - CloseHandle(semaphore); - return LIBUSB_ERROR_NO_MEM; - } - - // NB: concurrent usage supposes that init calls are equally balanced with - // exit calls. If init is called more than exit, we will not exit properly - if (++concurrent_usage == 0) { // First init? - get_windows_version(); - usbi_dbg("Windows %s", windows_version_str); - - if (windows_version == WINDOWS_UNSUPPORTED) { - usbi_err(ctx, "This version of Windows is NOT supported"); - r = LIBUSB_ERROR_NOT_SUPPORTED; - goto init_exit; - } - - // We need a lock for proper auto-release - usbi_mutex_init(&autoclaim_lock); - - // Initialize pollable file descriptors - init_polling(); - - // Load DLL imports - if (init_dlls() != LIBUSB_SUCCESS) { - usbi_err(ctx, "could not resolve DLL functions"); - goto init_exit; - } - - // Initialize the low level APIs (we don't care about errors at this stage) - for (i = 0; i < USB_API_MAX; i++) - usb_api_backend[i].init(SUB_API_NOTSET, ctx); - - r = windows_common_init(ctx); - if (r) - goto init_exit; - } - // At this stage, either we went through full init successfully, or didn't need to - r = LIBUSB_SUCCESS; - -init_exit: // Holds semaphore here. - if (!concurrent_usage && r != LIBUSB_SUCCESS) { // First init failed? - for (i = 0; i < USB_API_MAX; i++) - usb_api_backend[i].exit(SUB_API_NOTSET); - exit_dlls(); - exit_polling(); - windows_common_exit(); - usbi_mutex_destroy(&autoclaim_lock); - } - - if (r != LIBUSB_SUCCESS) - --concurrent_usage; // Not expected to call libusb_exit if we failed. - - ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1 - CloseHandle(semaphore); - return r; -} - -/* - * HCD (root) hubs need to have their device descriptor manually populated - * - * Note that, like Microsoft does in the device manager, we populate the - * Vendor and Device ID for HCD hubs with the ones from the PCI HCD device. - */ -static int force_hcd_device_descriptor(struct libusb_device *dev) -{ - struct windows_device_priv *parent_priv, *priv = _device_priv(dev); - struct libusb_context *ctx = DEVICE_CTX(dev); - int vid, pid; - - dev->num_configurations = 1; - priv->dev_descriptor.bLength = sizeof(USB_DEVICE_DESCRIPTOR); - priv->dev_descriptor.bDescriptorType = USB_DEVICE_DESCRIPTOR_TYPE; - priv->dev_descriptor.bNumConfigurations = 1; - priv->active_config = 1; - - if (dev->parent_dev == NULL) { - usbi_err(ctx, "program assertion failed - HCD hub has no parent"); - return LIBUSB_ERROR_NO_DEVICE; - } - - parent_priv = _device_priv(dev->parent_dev); - if (sscanf(parent_priv->path, "\\\\.\\PCI#VEN_%04x&DEV_%04x%*s", &vid, &pid) == 2) { - priv->dev_descriptor.idVendor = (uint16_t)vid; - priv->dev_descriptor.idProduct = (uint16_t)pid; - } else { - usbi_warn(ctx, "could not infer VID/PID of HCD hub from '%s'", parent_priv->path); - priv->dev_descriptor.idVendor = 0x1d6b; // Linux Foundation root hub - priv->dev_descriptor.idProduct = 1; - } - - return LIBUSB_SUCCESS; -} - -/* - * fetch and cache all the config descriptors through I/O - */ -static int cache_config_descriptors(struct libusb_device *dev, HANDLE hub_handle, char *device_id) -{ - DWORD size, ret_size; - struct libusb_context *ctx = DEVICE_CTX(dev); - struct windows_device_priv *priv = _device_priv(dev); - int r; - uint8_t i; - - USB_CONFIGURATION_DESCRIPTOR_SHORT cd_buf_short; // dummy request - PUSB_DESCRIPTOR_REQUEST cd_buf_actual = NULL; // actual request - PUSB_CONFIGURATION_DESCRIPTOR cd_data = NULL; - - if (dev->num_configurations == 0) - return LIBUSB_ERROR_INVALID_PARAM; - - priv->config_descriptor = calloc(dev->num_configurations, sizeof(unsigned char *)); - if (priv->config_descriptor == NULL) - return LIBUSB_ERROR_NO_MEM; - - for (i = 0; i < dev->num_configurations; i++) - priv->config_descriptor[i] = NULL; - - for (i = 0, r = LIBUSB_SUCCESS; ; i++) { - // safe loop: release all dynamic resources - safe_free(cd_buf_actual); - - // safe loop: end of loop condition - if ((i >= dev->num_configurations) || (r != LIBUSB_SUCCESS)) - break; - - size = sizeof(USB_CONFIGURATION_DESCRIPTOR_SHORT); - memset(&cd_buf_short, 0, size); - - cd_buf_short.req.ConnectionIndex = (ULONG)priv->port; - cd_buf_short.req.SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN; - cd_buf_short.req.SetupPacket.bRequest = USB_REQUEST_GET_DESCRIPTOR; - cd_buf_short.req.SetupPacket.wValue = (USB_CONFIGURATION_DESCRIPTOR_TYPE << 8) | i; - cd_buf_short.req.SetupPacket.wIndex = 0; - cd_buf_short.req.SetupPacket.wLength = (USHORT)(size - sizeof(USB_DESCRIPTOR_REQUEST)); - - // Dummy call to get the required data size. Initial failures are reported as info rather - // than error as they can occur for non-penalizing situations, such as with some hubs. - // coverity[tainted_data_argument] - if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, &cd_buf_short, size, - &cd_buf_short, size, &ret_size, NULL)) { - usbi_info(ctx, "could not access configuration descriptor (dummy) for '%s': %s", device_id, windows_error_str(0)); - LOOP_BREAK(LIBUSB_ERROR_IO); - } - - if ((ret_size != size) || (cd_buf_short.data.wTotalLength < sizeof(USB_CONFIGURATION_DESCRIPTOR))) { - usbi_info(ctx, "unexpected configuration descriptor size (dummy) for '%s'.", device_id); - LOOP_BREAK(LIBUSB_ERROR_IO); - } - - size = sizeof(USB_DESCRIPTOR_REQUEST) + cd_buf_short.data.wTotalLength; - cd_buf_actual = calloc(1, size); - if (cd_buf_actual == NULL) { - usbi_err(ctx, "could not allocate configuration descriptor buffer for '%s'.", device_id); - LOOP_BREAK(LIBUSB_ERROR_NO_MEM); - } - - // Actual call - cd_buf_actual->ConnectionIndex = (ULONG)priv->port; - cd_buf_actual->SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN; - cd_buf_actual->SetupPacket.bRequest = USB_REQUEST_GET_DESCRIPTOR; - cd_buf_actual->SetupPacket.wValue = (USB_CONFIGURATION_DESCRIPTOR_TYPE << 8) | i; - cd_buf_actual->SetupPacket.wIndex = 0; - cd_buf_actual->SetupPacket.wLength = (USHORT)(size - sizeof(USB_DESCRIPTOR_REQUEST)); - - if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, cd_buf_actual, size, - cd_buf_actual, size, &ret_size, NULL)) { - usbi_err(ctx, "could not access configuration descriptor (actual) for '%s': %s", device_id, windows_error_str(0)); - LOOP_BREAK(LIBUSB_ERROR_IO); - } - - cd_data = (PUSB_CONFIGURATION_DESCRIPTOR)((UCHAR *)cd_buf_actual + sizeof(USB_DESCRIPTOR_REQUEST)); - - if ((size != ret_size) || (cd_data->wTotalLength != cd_buf_short.data.wTotalLength)) { - usbi_err(ctx, "unexpected configuration descriptor size (actual) for '%s'.", device_id); - LOOP_BREAK(LIBUSB_ERROR_IO); - } - - if (cd_data->bDescriptorType != USB_CONFIGURATION_DESCRIPTOR_TYPE) { - usbi_err(ctx, "not a configuration descriptor for '%s'", device_id); - LOOP_BREAK(LIBUSB_ERROR_IO); - } - - usbi_dbg("cached config descriptor %d (bConfigurationValue=%u, %u bytes)", - i, cd_data->bConfigurationValue, cd_data->wTotalLength); - - // Cache the descriptor - priv->config_descriptor[i] = malloc(cd_data->wTotalLength); - if (priv->config_descriptor[i] == NULL) - LOOP_BREAK(LIBUSB_ERROR_NO_MEM); - memcpy(priv->config_descriptor[i], cd_data, cd_data->wTotalLength); - } - return LIBUSB_SUCCESS; -} - -/* - * Populate a libusb device structure - */ -static int init_device(struct libusb_device *dev, struct libusb_device *parent_dev, - uint8_t port_number, char *device_id, DWORD devinst) -{ - HANDLE handle; - DWORD size; - USB_NODE_CONNECTION_INFORMATION_EX conn_info; - USB_NODE_CONNECTION_INFORMATION_EX_V2 conn_info_v2; - struct windows_device_priv *priv, *parent_priv; - struct libusb_context *ctx; - struct libusb_device *tmp_dev; - unsigned long tmp_id; - unsigned i; - - if ((dev == NULL) || (parent_dev == NULL)) - return LIBUSB_ERROR_NOT_FOUND; - - ctx = DEVICE_CTX(dev); - priv = _device_priv(dev); - parent_priv = _device_priv(parent_dev); - if (parent_priv->apib->id != USB_API_HUB) { - usbi_warn(ctx, "parent for device '%s' is not a hub", device_id); - return LIBUSB_ERROR_NOT_FOUND; - } - - // It is possible for the parent hub not to have been initialized yet - // If that's the case, lookup the ancestors to set the bus number - if (parent_dev->bus_number == 0) { - for (i = 2; ; i++) { - tmp_id = get_ancestor_session_id(devinst, i); - if (tmp_id == 0) - break; - - tmp_dev = usbi_get_device_by_session_id(ctx, tmp_id); - if (tmp_dev == NULL) - continue; - - if (tmp_dev->bus_number != 0) { - usbi_dbg("got bus number from ancestor #%u", i); - parent_dev->bus_number = tmp_dev->bus_number; - libusb_unref_device(tmp_dev); - break; - } - - libusb_unref_device(tmp_dev); - } - } - - if (parent_dev->bus_number == 0) { - usbi_err(ctx, "program assertion failed: unable to find ancestor bus number for '%s'", device_id); - return LIBUSB_ERROR_NOT_FOUND; - } - - dev->bus_number = parent_dev->bus_number; - priv->port = port_number; - dev->port_number = port_number; - priv->depth = parent_priv->depth + 1; - dev->parent_dev = parent_dev; - - // If the device address is already set, we can stop here - if (dev->device_address != 0) - return LIBUSB_SUCCESS; - - memset(&conn_info, 0, sizeof(conn_info)); - if (priv->depth != 0) { // Not a HCD hub - handle = CreateFileA(parent_priv->path, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, - FILE_FLAG_OVERLAPPED, NULL); - if (handle == INVALID_HANDLE_VALUE) { - usbi_warn(ctx, "could not open hub %s: %s", parent_priv->path, windows_error_str(0)); - return LIBUSB_ERROR_ACCESS; - } - - size = sizeof(conn_info); - conn_info.ConnectionIndex = (ULONG)port_number; - // coverity[tainted_data_argument] - if (!DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX, &conn_info, size, - &conn_info, size, &size, NULL)) { - usbi_warn(ctx, "could not get node connection information for device '%s': %s", - device_id, windows_error_str(0)); - CloseHandle(handle); - return LIBUSB_ERROR_NO_DEVICE; - } - - if (conn_info.ConnectionStatus == NoDeviceConnected) { - usbi_err(ctx, "device '%s' is no longer connected!", device_id); - CloseHandle(handle); - return LIBUSB_ERROR_NO_DEVICE; - } - - memcpy(&priv->dev_descriptor, &(conn_info.DeviceDescriptor), sizeof(USB_DEVICE_DESCRIPTOR)); - dev->num_configurations = priv->dev_descriptor.bNumConfigurations; - priv->active_config = conn_info.CurrentConfigurationValue; - usbi_dbg("found %u configurations (active conf: %u)", dev->num_configurations, priv->active_config); - - // If we can't read the config descriptors, just set the number of confs to zero - if (cache_config_descriptors(dev, handle, device_id) != LIBUSB_SUCCESS) { - dev->num_configurations = 0; - priv->dev_descriptor.bNumConfigurations = 0; - } - - // In their great wisdom, Microsoft decided to BREAK the USB speed report between Windows 7 and Windows 8 - if (windows_version >= WINDOWS_8) { - memset(&conn_info_v2, 0, sizeof(conn_info_v2)); - size = sizeof(conn_info_v2); - conn_info_v2.ConnectionIndex = (ULONG)port_number; - conn_info_v2.Length = size; - conn_info_v2.SupportedUsbProtocols.Usb300 = 1; - if (!DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX_V2, - &conn_info_v2, size, &conn_info_v2, size, &size, NULL)) { - usbi_warn(ctx, "could not get node connection information (V2) for device '%s': %s", - device_id, windows_error_str(0)); - } else if (conn_info_v2.Flags.DeviceIsOperatingAtSuperSpeedOrHigher) { - conn_info.Speed = 3; - } - } - - CloseHandle(handle); - - if (conn_info.DeviceAddress > UINT8_MAX) - usbi_err(ctx, "program assertion failed: device address overflow"); - - dev->device_address = (uint8_t)conn_info.DeviceAddress + 1; - if (dev->device_address == 1) - usbi_err(ctx, "program assertion failed: device address collision with root hub"); - - switch (conn_info.Speed) { - case 0: dev->speed = LIBUSB_SPEED_LOW; break; - case 1: dev->speed = LIBUSB_SPEED_FULL; break; - case 2: dev->speed = LIBUSB_SPEED_HIGH; break; - case 3: dev->speed = LIBUSB_SPEED_SUPER; break; - default: - usbi_warn(ctx, "Got unknown device speed %u", conn_info.Speed); - break; - } - } else { - dev->device_address = 1; // root hubs are set to use device number 1 - force_hcd_device_descriptor(dev); - } - - usbi_sanitize_device(dev); - - usbi_dbg("(bus: %u, addr: %u, depth: %u, port: %u): '%s'", - dev->bus_number, dev->device_address, priv->depth, priv->port, device_id); - - return LIBUSB_SUCCESS; -} - -// Returns the api type, or 0 if not found/unsupported -static void get_api_type(struct libusb_context *ctx, HDEVINFO *dev_info, - SP_DEVINFO_DATA *dev_info_data, int *api, int *sub_api) -{ - // Precedence for filter drivers vs driver is in the order of this array - struct driver_lookup lookup[3] = { - {"\0\0", SPDRP_SERVICE, "driver"}, - {"\0\0", SPDRP_UPPERFILTERS, "upper filter driver"}, - {"\0\0", SPDRP_LOWERFILTERS, "lower filter driver"} - }; - DWORD size, reg_type; - unsigned k, l; - int i, j; - - *api = USB_API_UNSUPPORTED; - *sub_api = SUB_API_NOTSET; - - // Check the service & filter names to know the API we should use - for (k = 0; k < 3; k++) { - if (pSetupDiGetDeviceRegistryPropertyA(*dev_info, dev_info_data, lookup[k].reg_prop, - ®_type, (BYTE *)lookup[k].list, MAX_KEY_LENGTH, &size)) { - // Turn the REG_SZ SPDRP_SERVICE into REG_MULTI_SZ - if (lookup[k].reg_prop == SPDRP_SERVICE) - // our buffers are MAX_KEY_LENGTH + 1 so we can overflow if needed - lookup[k].list[strlen(lookup[k].list) + 1] = 0; - - // MULTI_SZ is a pain to work with. Turn it into something much more manageable - // NB: none of the driver names we check against contain LIST_SEPARATOR, - // (currently ';'), so even if an unsuported one does, it's not an issue - for (l = 0; (lookup[k].list[l] != 0) || (lookup[k].list[l + 1] != 0); l++) { - if (lookup[k].list[l] == 0) - lookup[k].list[l] = LIST_SEPARATOR; - } - usbi_dbg("%s(s): %s", lookup[k].designation, lookup[k].list); - } else { - if (GetLastError() != ERROR_INVALID_DATA) - usbi_dbg("could not access %s: %s", lookup[k].designation, windows_error_str(0)); - lookup[k].list[0] = 0; - } - } - - for (i = 1; i < USB_API_MAX; i++) { - for (k = 0; k < 3; k++) { - j = get_sub_api(lookup[k].list, i); - if (j >= 0) { - usbi_dbg("matched %s name against %s", lookup[k].designation, - (i != USB_API_WINUSBX) ? usb_api_backend[i].designation : sub_api_name[j]); - *api = i; - *sub_api = j; - return; - } - } - } -} - -static int set_composite_interface(struct libusb_context *ctx, struct libusb_device *dev, - char *dev_interface_path, char *device_id, int api, int sub_api) -{ - unsigned i; - struct windows_device_priv *priv = _device_priv(dev); - int interface_number; - - if (priv->apib->id != USB_API_COMPOSITE) { - usbi_err(ctx, "program assertion failed: '%s' is not composite", device_id); - return LIBUSB_ERROR_NO_DEVICE; - } - - // Because MI_## are not necessarily in sequential order (some composite - // devices will have only MI_00 & MI_03 for instance), we retrieve the actual - // interface number from the path's MI value - interface_number = 0; - for (i = 0; device_id[i] != 0; ) { - if ((device_id[i++] == 'M') && (device_id[i++] == 'I') - && (device_id[i++] == '_')) { - interface_number = (device_id[i++] - '0') * 10; - interface_number += device_id[i] - '0'; - break; - } - } - - if (device_id[i] == 0) - usbi_warn(ctx, "failure to read interface number for %s. Using default value %d", - device_id, interface_number); - - if (priv->usb_interface[interface_number].path != NULL) { - if (api == USB_API_HID) { - // HID devices can have multiple collections (COL##) for each MI_## interface - usbi_dbg("interface[%d] already set - ignoring HID collection: %s", - interface_number, device_id); - return LIBUSB_ERROR_ACCESS; - } - // In other cases, just use the latest data - safe_free(priv->usb_interface[interface_number].path); - } - - usbi_dbg("interface[%d] = %s", interface_number, dev_interface_path); - priv->usb_interface[interface_number].path = dev_interface_path; - priv->usb_interface[interface_number].apib = &usb_api_backend[api]; - priv->usb_interface[interface_number].sub_api = sub_api; - if ((api == USB_API_HID) && (priv->hid == NULL)) { - priv->hid = calloc(1, sizeof(struct hid_device_priv)); - if (priv->hid == NULL) - return LIBUSB_ERROR_NO_MEM; - } - - return LIBUSB_SUCCESS; -} - -static int set_hid_interface(struct libusb_context *ctx, struct libusb_device *dev, - char *dev_interface_path) -{ - int i; - struct windows_device_priv *priv = _device_priv(dev); - - if (priv->hid == NULL) { - usbi_err(ctx, "program assertion failed: parent is not HID"); - return LIBUSB_ERROR_NO_DEVICE; - } else if (priv->hid->nb_interfaces == USB_MAXINTERFACES) { - usbi_err(ctx, "program assertion failed: max USB interfaces reached for HID device"); - return LIBUSB_ERROR_NO_DEVICE; - } - - for (i = 0; i < priv->hid->nb_interfaces; i++) { - if ((priv->usb_interface[i].path != NULL) && strcmp(priv->usb_interface[i].path, dev_interface_path) == 0) { - usbi_dbg("interface[%d] already set to %s", i, dev_interface_path); - return LIBUSB_ERROR_ACCESS; - } - } - - priv->usb_interface[priv->hid->nb_interfaces].path = dev_interface_path; - priv->usb_interface[priv->hid->nb_interfaces].apib = &usb_api_backend[USB_API_HID]; - usbi_dbg("interface[%u] = %s", priv->hid->nb_interfaces, dev_interface_path); - priv->hid->nb_interfaces++; - return LIBUSB_SUCCESS; -} - -/* - * get_device_list: libusb backend device enumeration function - */ -static int windows_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs) -{ - struct discovered_devs *discdevs; - HDEVINFO dev_info = { 0 }; - const char *usb_class[] = {"USB", "NUSB3", "IUSB3", "IARUSB3"}; - SP_DEVINFO_DATA dev_info_data = { 0 }; - SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL; - GUID hid_guid; -#define MAX_ENUM_GUIDS 64 - const GUID *guid[MAX_ENUM_GUIDS]; -#define HCD_PASS 0 -#define HUB_PASS 1 -#define GEN_PASS 2 -#define DEV_PASS 3 -#define HID_PASS 4 - int r = LIBUSB_SUCCESS; - int api, sub_api; - size_t class_index = 0; - unsigned int nb_guids, pass, i, j, ancestor; - char path[MAX_PATH_LENGTH]; - char strbuf[MAX_PATH_LENGTH]; - struct libusb_device *dev, *parent_dev; - struct windows_device_priv *priv, *parent_priv; - char *dev_interface_path = NULL; - char *dev_id_path = NULL; - unsigned long session_id; - DWORD size, reg_type, port_nr, install_state; - HKEY key; - WCHAR guid_string_w[MAX_GUID_STRING_LENGTH]; - GUID *if_guid; - LONG s; - // Keep a list of newly allocated devs to unref - libusb_device **unref_list, **new_unref_list; - unsigned int unref_size = 64; - unsigned int unref_cur = 0; - - // PASS 1 : (re)enumerate HCDs (allows for HCD hotplug) - // PASS 2 : (re)enumerate HUBS - // PASS 3 : (re)enumerate generic USB devices (including driverless) - // and list additional USB device interface GUIDs to explore - // PASS 4 : (re)enumerate master USB devices that have a device interface - // PASS 5+: (re)enumerate device interfaced GUIDs (including HID) and - // set the device interfaces. - - // Init the GUID table - guid[HCD_PASS] = &GUID_DEVINTERFACE_USB_HOST_CONTROLLER; - guid[HUB_PASS] = &GUID_DEVINTERFACE_USB_HUB; - guid[GEN_PASS] = NULL; - guid[DEV_PASS] = &GUID_DEVINTERFACE_USB_DEVICE; - HidD_GetHidGuid(&hid_guid); - guid[HID_PASS] = &hid_guid; - nb_guids = HID_PASS + 1; - - unref_list = calloc(unref_size, sizeof(libusb_device *)); - if (unref_list == NULL) - return LIBUSB_ERROR_NO_MEM; - - for (pass = 0; ((pass < nb_guids) && (r == LIBUSB_SUCCESS)); pass++) { -//#define ENUM_DEBUG -#if defined(ENABLE_LOGGING) && defined(ENUM_DEBUG) - const char *passname[] = { "HCD", "HUB", "GEN", "DEV", "HID", "EXT" }; - usbi_dbg("#### PROCESSING %ss %s", passname[(pass <= HID_PASS) ? pass : (HID_PASS + 1)], - (pass != GEN_PASS) ? guid_to_string(guid[pass]) : ""); -#endif - for (i = 0; ; i++) { - // safe loop: free up any (unprotected) dynamic resource - // NB: this is always executed before breaking the loop - safe_free(dev_interface_details); - safe_free(dev_interface_path); - safe_free(dev_id_path); - priv = parent_priv = NULL; - dev = parent_dev = NULL; - - // Safe loop: end of loop conditions - if (r != LIBUSB_SUCCESS) - break; - - if ((pass == HCD_PASS) && (i == UINT8_MAX)) { - usbi_warn(ctx, "program assertion failed - found more than %d buses, skipping the rest.", UINT8_MAX); - break; - } - - if (pass != GEN_PASS) { - // Except for GEN, all passes deal with device interfaces - dev_interface_details = get_interface_details(ctx, &dev_info, &dev_info_data, guid[pass], i); - if (dev_interface_details == NULL) - break; - - dev_interface_path = sanitize_path(dev_interface_details->DevicePath); - if (dev_interface_path == NULL) { - usbi_warn(ctx, "could not sanitize device interface path for '%s'", dev_interface_details->DevicePath); - continue; - } - } else { - // Workaround for a Nec/Renesas USB 3.0 driver bug where root hubs are - // being listed under the "NUSB3" PnP Symbolic Name rather than "USB". - // The Intel USB 3.0 driver behaves similar, but uses "IUSB3" - // The Intel Alpine Ridge USB 3.1 driver uses "IARUSB3" - for (; class_index < ARRAYSIZE(usb_class); class_index++) { - if (get_devinfo_data(ctx, &dev_info, &dev_info_data, usb_class[class_index], i)) - break; - i = 0; - } - if (class_index >= ARRAYSIZE(usb_class)) - break; - } - - // Read the Device ID path. This is what we'll use as UID - // Note that if the device is plugged in a different port or hub, the Device ID changes - if (CM_Get_Device_IDA(dev_info_data.DevInst, path, sizeof(path), 0) != CR_SUCCESS) { - usbi_warn(ctx, "could not read the device id path for devinst %X, skipping", - (unsigned int)dev_info_data.DevInst); - continue; - } - - dev_id_path = sanitize_path(path); - if (dev_id_path == NULL) { - usbi_warn(ctx, "could not sanitize device id path for devinst %X, skipping", - (unsigned int)dev_info_data.DevInst); - continue; - } -#ifdef ENUM_DEBUG - usbi_dbg("PRO: %s", dev_id_path); -#endif - - // The SPDRP_ADDRESS for USB devices is the device port number on the hub - port_nr = 0; - if ((pass >= HUB_PASS) && (pass <= GEN_PASS)) { - if ((!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_ADDRESS, - ®_type, (BYTE *)&port_nr, 4, &size)) || (size != 4)) { - usbi_warn(ctx, "could not retrieve port number for device '%s', skipping: %s", - dev_id_path, windows_error_str(0)); - continue; - } - } - - // Set API to use or get additional data from generic pass - api = USB_API_UNSUPPORTED; - sub_api = SUB_API_NOTSET; - switch (pass) { - case HCD_PASS: - break; - case GEN_PASS: - // We use the GEN pass to detect driverless devices... - size = sizeof(strbuf); - if (!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_DRIVER, - ®_type, (BYTE *)strbuf, size, &size)) { - usbi_info(ctx, "The following device has no driver: '%s'", dev_id_path); - usbi_info(ctx, "libusb will not be able to access it."); - } - // ...and to add the additional device interface GUIDs - key = pSetupDiOpenDevRegKey(dev_info, &dev_info_data, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ); - if (key != INVALID_HANDLE_VALUE) { - size = sizeof(guid_string_w); - s = pRegQueryValueExW(key, L"DeviceInterfaceGUIDs", NULL, ®_type, - (BYTE *)guid_string_w, &size); - pRegCloseKey(key); - if (s == ERROR_SUCCESS) { - if (nb_guids >= MAX_ENUM_GUIDS) { - // If this assert is ever reported, grow a GUID table dynamically - usbi_err(ctx, "program assertion failed: too many GUIDs"); - LOOP_BREAK(LIBUSB_ERROR_OVERFLOW); - } - if_guid = calloc(1, sizeof(GUID)); - if (if_guid == NULL) { - usbi_err(ctx, "could not calloc for if_guid: not enough memory"); - LOOP_BREAK(LIBUSB_ERROR_NO_MEM); - } - pCLSIDFromString(guid_string_w, if_guid); - guid[nb_guids++] = if_guid; - usbi_dbg("extra GUID: %s", guid_to_string(if_guid)); - } - } - break; - case HID_PASS: - api = USB_API_HID; - break; - default: - // Get the API type (after checking that the driver installation is OK) - if ((!pSetupDiGetDeviceRegistryPropertyA(dev_info, &dev_info_data, SPDRP_INSTALL_STATE, - ®_type, (BYTE *)&install_state, 4, &size)) || (size != 4)) { - usbi_warn(ctx, "could not detect installation state of driver for '%s': %s", - dev_id_path, windows_error_str(0)); - } else if (install_state != 0) { - usbi_warn(ctx, "driver for device '%s' is reporting an issue (code: %u) - skipping", - dev_id_path, (unsigned int)install_state); - continue; - } - get_api_type(ctx, &dev_info, &dev_info_data, &api, &sub_api); - break; - } - - // Find parent device (for the passes that need it) - switch (pass) { - case HCD_PASS: - case DEV_PASS: - case HUB_PASS: - break; - default: - // Go through the ancestors until we see a face we recognize - parent_dev = NULL; - for (ancestor = 1; parent_dev == NULL; ancestor++) { - session_id = get_ancestor_session_id(dev_info_data.DevInst, ancestor); - if (session_id == 0) - break; - - parent_dev = usbi_get_device_by_session_id(ctx, session_id); - } - - if (parent_dev == NULL) { - usbi_dbg("unlisted ancestor for '%s' (non USB HID, newly connected, etc.) - ignoring", dev_id_path); - continue; - } - - parent_priv = _device_priv(parent_dev); - // virtual USB devices are also listed during GEN - don't process these yet - if ((pass == GEN_PASS) && (parent_priv->apib->id != USB_API_HUB)) { - libusb_unref_device(parent_dev); - continue; - } - - break; - } - - // Create new or match existing device, using the (hashed) device_id as session id - if (pass <= DEV_PASS) { // For subsequent passes, we'll lookup the parent - // These are the passes that create "new" devices - session_id = htab_hash(dev_id_path); - dev = usbi_get_device_by_session_id(ctx, session_id); - if (dev == NULL) { - if (pass == DEV_PASS) { - // This can occur if the OS only reports a newly plugged device after we started enum - usbi_warn(ctx, "'%s' was only detected in late pass (newly connected device?)" - " - ignoring", dev_id_path); - continue; - } - - usbi_dbg("allocating new device for session [%lX]", session_id); - dev = usbi_alloc_device(ctx, session_id); - if (dev == NULL) - LOOP_BREAK(LIBUSB_ERROR_NO_MEM); - - priv = windows_device_priv_init(dev); - } else { - usbi_dbg("found existing device for session [%lX] (%u.%u)", - session_id, dev->bus_number, dev->device_address); - - priv = _device_priv(dev); - if ((parent_dev != NULL) && (dev->parent_dev != NULL)) { - if (dev->parent_dev != parent_dev) { - // It is possible for the actual parent device to not have existed at the - // time of enumeration, so the currently assigned parent may in fact be a - // grandparent. If the devices differ, we assume the "new" parent device - // is in fact closer to the device. - usbi_dbg("updating parent device [session %lX -> %lX]", - dev->parent_dev->session_data, parent_dev->session_data); - libusb_unref_device(dev->parent_dev); - dev->parent_dev = parent_dev; - } else { - // We hold a reference to parent_dev instance, but this device already - // has a parent_dev reference (only one per child) - libusb_unref_device(parent_dev); - } - } - } - - // Keep track of devices that need unref - unref_list[unref_cur++] = dev; - if (unref_cur >= unref_size) { - unref_size += 64; - new_unref_list = usbi_reallocf(unref_list, unref_size * sizeof(libusb_device *)); - if (new_unref_list == NULL) { - usbi_err(ctx, "could not realloc list for unref - aborting."); - LOOP_BREAK(LIBUSB_ERROR_NO_MEM); - } else { - unref_list = new_unref_list; - } - } - } - - // Setup device - switch (pass) { - case HCD_PASS: - // If the hcd has already been setup, don't do it again - if (priv->path != NULL) - break; - dev->bus_number = (uint8_t)(i + 1); // bus 0 is reserved for disconnected - dev->device_address = 0; - dev->num_configurations = 0; - priv->apib = &usb_api_backend[USB_API_HUB]; - priv->sub_api = SUB_API_NOTSET; - priv->depth = UINT8_MAX; // Overflow to 0 for HCD Hubs - priv->path = dev_interface_path; - dev_interface_path = NULL; - break; - case HUB_PASS: - case DEV_PASS: - // If the device has already been setup, don't do it again - if (priv->path != NULL) - break; - // Take care of API initialization - priv->path = dev_interface_path; - dev_interface_path = NULL; - priv->apib = &usb_api_backend[api]; - priv->sub_api = sub_api; - switch(api) { - case USB_API_COMPOSITE: - case USB_API_HUB: - break; - case USB_API_HID: - priv->hid = calloc(1, sizeof(struct hid_device_priv)); - if (priv->hid == NULL) - LOOP_BREAK(LIBUSB_ERROR_NO_MEM); - - priv->hid->nb_interfaces = 0; - break; - default: - // For other devices, the first interface is the same as the device - priv->usb_interface[0].path = _strdup(priv->path); - if (priv->usb_interface[0].path == NULL) - usbi_warn(ctx, "could not duplicate interface path '%s'", priv->path); - // The following is needed if we want API calls to work for both simple - // and composite devices. - for (j = 0; j < USB_MAXINTERFACES; j++) - priv->usb_interface[j].apib = &usb_api_backend[api]; - - break; - } - break; - case GEN_PASS: - r = init_device(dev, parent_dev, (uint8_t)port_nr, dev_id_path, dev_info_data.DevInst); - if (r == LIBUSB_SUCCESS) { - // Append device to the list of discovered devices - discdevs = discovered_devs_append(*_discdevs, dev); - if (!discdevs) - LOOP_BREAK(LIBUSB_ERROR_NO_MEM); - - *_discdevs = discdevs; - } else if (r == LIBUSB_ERROR_NO_DEVICE) { - // This can occur if the device was disconnected but Windows hasn't - // refreshed its enumeration yet - in that case, we ignore the device - r = LIBUSB_SUCCESS; - } - break; - default: // HID_PASS and later - if (parent_priv->apib->id == USB_API_HID || parent_priv->apib->id == USB_API_COMPOSITE) { - if (parent_priv->apib->id == USB_API_HID) { - usbi_dbg("setting HID interface for [%lX]:", parent_dev->session_data); - r = set_hid_interface(ctx, parent_dev, dev_interface_path); - } else { - usbi_dbg("setting composite interface for [%lX]:", parent_dev->session_data); - r = set_composite_interface(ctx, parent_dev, dev_interface_path, dev_id_path, api, sub_api); - } - switch (r) { - case LIBUSB_SUCCESS: - dev_interface_path = NULL; - break; - case LIBUSB_ERROR_ACCESS: - // interface has already been set => make sure dev_interface_path is freed then - r = LIBUSB_SUCCESS; - break; - default: - LOOP_BREAK(r); - break; - } - } - libusb_unref_device(parent_dev); - break; - } - } - } - - // Free any additional GUIDs - for (pass = HID_PASS + 1; pass < nb_guids; pass++) - free((void *)guid[pass]); - - // Unref newly allocated devs - for (i = 0; i < unref_cur; i++) - libusb_unref_device(unref_list[i]); - free(unref_list); - - return r; -} - -/* - * exit: libusb backend deinitialization function - */ -static void windows_exit(void) -{ - int i; - HANDLE semaphore; - char sem_name[11 + 8 + 1]; // strlen("libusb_init") + (32-bit hex PID) + '\0' - - sprintf(sem_name, "libusb_init%08X", (unsigned int)(GetCurrentProcessId() & 0xFFFFFFFF)); - semaphore = CreateSemaphoreA(NULL, 1, 1, sem_name); - if (semaphore == NULL) - return; - - // A successful wait brings our semaphore count to 0 (unsignaled) - // => any concurent wait stalls until the semaphore release - if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) { - CloseHandle(semaphore); - return; - } - - // Only works if exits and inits are balanced exactly - if (--concurrent_usage < 0) { // Last exit - for (i = 0; i < USB_API_MAX; i++) - usb_api_backend[i].exit(SUB_API_NOTSET); - exit_dlls(); - exit_polling(); - windows_common_exit(); - usbi_mutex_destroy(&autoclaim_lock); - } - - ReleaseSemaphore(semaphore, 1, NULL); // increase count back to 1 - CloseHandle(semaphore); -} - -static int windows_get_device_descriptor(struct libusb_device *dev, unsigned char *buffer, int *host_endian) -{ - struct windows_device_priv *priv = _device_priv(dev); - - memcpy(buffer, &priv->dev_descriptor, DEVICE_DESC_LENGTH); - *host_endian = 0; - - return LIBUSB_SUCCESS; -} - -static int windows_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian) -{ - struct windows_device_priv *priv = _device_priv(dev); - PUSB_CONFIGURATION_DESCRIPTOR config_header; - size_t size; - - // config index is zero based - if (config_index >= dev->num_configurations) - return LIBUSB_ERROR_INVALID_PARAM; - - if ((priv->config_descriptor == NULL) || (priv->config_descriptor[config_index] == NULL)) - return LIBUSB_ERROR_NOT_FOUND; - - config_header = (PUSB_CONFIGURATION_DESCRIPTOR)priv->config_descriptor[config_index]; - - size = MIN(config_header->wTotalLength, len); - memcpy(buffer, priv->config_descriptor[config_index], size); - *host_endian = 0; - - return (int)size; -} - -static int windows_get_config_descriptor_by_value(struct libusb_device *dev, uint8_t bConfigurationValue, - unsigned char **buffer, int *host_endian) -{ - struct windows_device_priv *priv = _device_priv(dev); - PUSB_CONFIGURATION_DESCRIPTOR config_header; - uint8_t index; - - *buffer = NULL; - *host_endian = 0; - - if (priv->config_descriptor == NULL) - return LIBUSB_ERROR_NOT_FOUND; - - for (index = 0; index < dev->num_configurations; index++) { - config_header = (PUSB_CONFIGURATION_DESCRIPTOR)priv->config_descriptor[index]; - if (config_header->bConfigurationValue == bConfigurationValue) { - *buffer = priv->config_descriptor[index]; - return (int)config_header->wTotalLength; - } - } - - return LIBUSB_ERROR_NOT_FOUND; -} - -/* - * return the cached copy of the active config descriptor - */ -static int windows_get_active_config_descriptor(struct libusb_device *dev, unsigned char *buffer, size_t len, int *host_endian) -{ - struct windows_device_priv *priv = _device_priv(dev); - unsigned char *config_desc; - int r; - - if (priv->active_config == 0) - return LIBUSB_ERROR_NOT_FOUND; - - r = windows_get_config_descriptor_by_value(dev, priv->active_config, &config_desc, host_endian); - if (r < 0) - return r; - - len = MIN((size_t)r, len); - memcpy(buffer, config_desc, len); - return (int)len; -} - -static int windows_open(struct libusb_device_handle *dev_handle) -{ - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev); - - if (priv->apib == NULL) { - usbi_err(ctx, "program assertion failed - device is not initialized"); - return LIBUSB_ERROR_NO_DEVICE; - } - - return priv->apib->open(SUB_API_NOTSET, dev_handle); -} - -static void windows_close(struct libusb_device_handle *dev_handle) -{ - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - - priv->apib->close(SUB_API_NOTSET, dev_handle); -} - -static int windows_get_configuration(struct libusb_device_handle *dev_handle, int *config) -{ - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - - if (priv->active_config == 0) { - *config = 0; - return LIBUSB_ERROR_NOT_FOUND; - } - - *config = priv->active_config; - return LIBUSB_SUCCESS; -} - -/* - * from http://msdn.microsoft.com/en-us/library/ms793522.aspx: "The port driver - * does not currently expose a service that allows higher-level drivers to set - * the configuration." - */ -static int windows_set_configuration(struct libusb_device_handle *dev_handle, int config) -{ - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - int r = LIBUSB_SUCCESS; - - if (config >= USB_MAXCONFIG) - return LIBUSB_ERROR_INVALID_PARAM; - - r = libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_OUT | - LIBUSB_REQUEST_TYPE_STANDARD | LIBUSB_RECIPIENT_DEVICE, - LIBUSB_REQUEST_SET_CONFIGURATION, (uint16_t)config, - 0, NULL, 0, 1000); - - if (r == LIBUSB_SUCCESS) - priv->active_config = (uint8_t)config; - - return r; -} - -static int windows_claim_interface(struct libusb_device_handle *dev_handle, int iface) -{ - int r = LIBUSB_SUCCESS; - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - - safe_free(priv->usb_interface[iface].endpoint); - priv->usb_interface[iface].nb_endpoints = 0; - - r = priv->apib->claim_interface(SUB_API_NOTSET, dev_handle, iface); - - if (r == LIBUSB_SUCCESS) - r = windows_assign_endpoints(dev_handle, iface, 0); - - return r; -} - -static int windows_set_interface_altsetting(struct libusb_device_handle *dev_handle, int iface, int altsetting) -{ - int r = LIBUSB_SUCCESS; - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - - safe_free(priv->usb_interface[iface].endpoint); - priv->usb_interface[iface].nb_endpoints = 0; - - r = priv->apib->set_interface_altsetting(SUB_API_NOTSET, dev_handle, iface, altsetting); - - if (r == LIBUSB_SUCCESS) - r = windows_assign_endpoints(dev_handle, iface, altsetting); - - return r; -} - -static int windows_release_interface(struct libusb_device_handle *dev_handle, int iface) -{ - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - - return priv->apib->release_interface(SUB_API_NOTSET, dev_handle, iface); -} - -static int windows_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) -{ - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - return priv->apib->clear_halt(SUB_API_NOTSET, dev_handle, endpoint); -} - -static int windows_reset_device(struct libusb_device_handle *dev_handle) -{ - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - return priv->apib->reset_device(SUB_API_NOTSET, dev_handle); -} - -// The 3 functions below are unlikely to ever get supported on Windows -static int windows_kernel_driver_active(struct libusb_device_handle *dev_handle, int iface) -{ - return LIBUSB_ERROR_NOT_SUPPORTED; -} - -static int windows_attach_kernel_driver(struct libusb_device_handle *dev_handle, int iface) -{ - return LIBUSB_ERROR_NOT_SUPPORTED; -} - -static int windows_detach_kernel_driver(struct libusb_device_handle *dev_handle, int iface) -{ - return LIBUSB_ERROR_NOT_SUPPORTED; -} - -static void windows_destroy_device(struct libusb_device *dev) -{ - windows_device_priv_release(dev); -} - -void windows_clear_transfer_priv(struct usbi_transfer *itransfer) -{ - struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer); - - usbi_free_fd(&transfer_priv->pollable_fd); - safe_free(transfer_priv->hid_buffer); - // When auto claim is in use, attempt to release the auto-claimed interface - auto_release(itransfer); -} - -static int submit_bulk_transfer(struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev); - struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer); - struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev); - int r; - - r = priv->apib->submit_bulk_transfer(SUB_API_NOTSET, itransfer); - if (r != LIBUSB_SUCCESS) - return r; - - usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd, - (short)(IS_XFERIN(transfer) ? POLLIN : POLLOUT)); - - return LIBUSB_SUCCESS; -} - -static int submit_iso_transfer(struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev); - struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer); - struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev); - int r; - - r = priv->apib->submit_iso_transfer(SUB_API_NOTSET, itransfer); - if (r != LIBUSB_SUCCESS) - return r; - - usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd, - (short)(IS_XFERIN(transfer) ? POLLIN : POLLOUT)); - - return LIBUSB_SUCCESS; -} - -static int submit_control_transfer(struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev); - struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer); - struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev); - int r; - - r = priv->apib->submit_control_transfer(SUB_API_NOTSET, itransfer); - if (r != LIBUSB_SUCCESS) - return r; - - usbi_add_pollfd(ctx, transfer_priv->pollable_fd.fd, POLLIN); - - return LIBUSB_SUCCESS; -} - -static int windows_submit_transfer(struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - - switch (transfer->type) { - case LIBUSB_TRANSFER_TYPE_CONTROL: - return submit_control_transfer(itransfer); - case LIBUSB_TRANSFER_TYPE_BULK: - case LIBUSB_TRANSFER_TYPE_INTERRUPT: - if (IS_XFEROUT(transfer) && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)) - return LIBUSB_ERROR_NOT_SUPPORTED; - return submit_bulk_transfer(itransfer); - case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS: - return submit_iso_transfer(itransfer); - case LIBUSB_TRANSFER_TYPE_BULK_STREAM: - return LIBUSB_ERROR_NOT_SUPPORTED; - default: - usbi_err(TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type); - return LIBUSB_ERROR_INVALID_PARAM; - } -} - -static int windows_abort_control(struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev); - - return priv->apib->abort_control(SUB_API_NOTSET, itransfer); -} - -static int windows_abort_transfers(struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev); - - return priv->apib->abort_transfers(SUB_API_NOTSET, itransfer); -} - -static int windows_cancel_transfer(struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - - switch (transfer->type) { - case LIBUSB_TRANSFER_TYPE_CONTROL: - return windows_abort_control(itransfer); - case LIBUSB_TRANSFER_TYPE_BULK: - case LIBUSB_TRANSFER_TYPE_INTERRUPT: - case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS: - return windows_abort_transfers(itransfer); - case LIBUSB_TRANSFER_TYPE_BULK_STREAM: - return LIBUSB_ERROR_NOT_SUPPORTED; - default: - usbi_err(ITRANSFER_CTX(itransfer), "unknown endpoint type %d", transfer->type); - return LIBUSB_ERROR_INVALID_PARAM; - } -} - -int windows_copy_transfer_data(struct usbi_transfer *itransfer, uint32_t io_size) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev); - return priv->apib->copy_transfer_data(SUB_API_NOTSET, itransfer, io_size); -} - -struct winfd *windows_get_fd(struct usbi_transfer *transfer) -{ - struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(transfer); - return &transfer_priv->pollable_fd; -} - -void windows_get_overlapped_result(struct usbi_transfer *transfer, struct winfd *pollable_fd, DWORD *io_result, DWORD *io_size) -{ - if (HasOverlappedIoCompletedSync(pollable_fd->overlapped)) { - *io_result = NO_ERROR; - *io_size = (DWORD)pollable_fd->overlapped->InternalHigh; - } else if (GetOverlappedResult(pollable_fd->handle, pollable_fd->overlapped, io_size, false)) { - // Regular async overlapped - *io_result = NO_ERROR; - } else { - *io_result = GetLastError(); - } -} - -// NB: MSVC6 does not support named initializers. -const struct usbi_os_backend windows_backend = { - "Windows", - USBI_CAP_HAS_HID_ACCESS, - windows_init, - windows_exit, - - windows_get_device_list, - NULL, /* hotplug_poll */ - windows_open, - windows_close, - - windows_get_device_descriptor, - windows_get_active_config_descriptor, - windows_get_config_descriptor, - windows_get_config_descriptor_by_value, - - windows_get_configuration, - windows_set_configuration, - windows_claim_interface, - windows_release_interface, - - windows_set_interface_altsetting, - windows_clear_halt, - windows_reset_device, - - NULL, /* alloc_streams */ - NULL, /* free_streams */ - - NULL, /* dev_mem_alloc */ - NULL, /* dev_mem_free */ - - windows_kernel_driver_active, - windows_detach_kernel_driver, - windows_attach_kernel_driver, - - windows_destroy_device, - - windows_submit_transfer, - windows_cancel_transfer, - windows_clear_transfer_priv, - - windows_handle_events, - NULL, - - windows_clock_gettime, -#if defined(USBI_TIMERFD_AVAILABLE) - NULL, -#endif - sizeof(struct windows_device_priv), - sizeof(struct windows_device_handle_priv), - sizeof(struct windows_transfer_priv), -}; - - -/* - * USB API backends - */ -static int unsupported_init(int sub_api, struct libusb_context *ctx) -{ - return LIBUSB_SUCCESS; -} - -static int unsupported_exit(int sub_api) -{ - return LIBUSB_SUCCESS; -} - -static int unsupported_open(int sub_api, struct libusb_device_handle *dev_handle) -{ - PRINT_UNSUPPORTED_API(open); -} - -static void unsupported_close(int sub_api, struct libusb_device_handle *dev_handle) -{ - usbi_dbg("unsupported API call for 'close'"); -} - -static int unsupported_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface) -{ - PRINT_UNSUPPORTED_API(configure_endpoints); -} - -static int unsupported_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface) -{ - PRINT_UNSUPPORTED_API(claim_interface); -} - -static int unsupported_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting) -{ - PRINT_UNSUPPORTED_API(set_interface_altsetting); -} - -static int unsupported_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface) -{ - PRINT_UNSUPPORTED_API(release_interface); -} - -static int unsupported_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint) -{ - PRINT_UNSUPPORTED_API(clear_halt); -} - -static int unsupported_reset_device(int sub_api, struct libusb_device_handle *dev_handle) -{ - PRINT_UNSUPPORTED_API(reset_device); -} - -static int unsupported_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer) -{ - PRINT_UNSUPPORTED_API(submit_bulk_transfer); -} - -static int unsupported_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer) -{ - PRINT_UNSUPPORTED_API(submit_iso_transfer); -} - -static int unsupported_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer) -{ - PRINT_UNSUPPORTED_API(submit_control_transfer); -} - -static int unsupported_abort_control(int sub_api, struct usbi_transfer *itransfer) -{ - PRINT_UNSUPPORTED_API(abort_control); -} - -static int unsupported_abort_transfers(int sub_api, struct usbi_transfer *itransfer) -{ - PRINT_UNSUPPORTED_API(abort_transfers); -} - -static int unsupported_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size) -{ - PRINT_UNSUPPORTED_API(copy_transfer_data); -} - -static int common_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface) -{ - return LIBUSB_SUCCESS; -} - -// These names must be uppercase -static const char *hub_driver_names[] = {"USBHUB", "USBHUB3", "USB3HUB", "NUSB3HUB", "RUSB3HUB", "FLXHCIH", "TIHUB3", "ETRONHUB3", "VIAHUB3", "ASMTHUB3", "IUSB3HUB", "VUSB3HUB", "AMDHUB30", "VHHUB", "AUSB3HUB"}; -static const char *composite_driver_names[] = {"USBCCGP"}; -static const char *winusbx_driver_names[] = WINUSBX_DRV_NAMES; -static const char *hid_driver_names[] = {"HIDUSB", "MOUHID", "KBDHID"}; -const struct windows_usb_api_backend usb_api_backend[USB_API_MAX] = { - { - USB_API_UNSUPPORTED, - "Unsupported API", - NULL, - 0, - unsupported_init, - unsupported_exit, - unsupported_open, - unsupported_close, - unsupported_configure_endpoints, - unsupported_claim_interface, - unsupported_set_interface_altsetting, - unsupported_release_interface, - unsupported_clear_halt, - unsupported_reset_device, - unsupported_submit_bulk_transfer, - unsupported_submit_iso_transfer, - unsupported_submit_control_transfer, - unsupported_abort_control, - unsupported_abort_transfers, - unsupported_copy_transfer_data, - }, - { - USB_API_HUB, - "HUB API", - hub_driver_names, - ARRAYSIZE(hub_driver_names), - unsupported_init, - unsupported_exit, - unsupported_open, - unsupported_close, - unsupported_configure_endpoints, - unsupported_claim_interface, - unsupported_set_interface_altsetting, - unsupported_release_interface, - unsupported_clear_halt, - unsupported_reset_device, - unsupported_submit_bulk_transfer, - unsupported_submit_iso_transfer, - unsupported_submit_control_transfer, - unsupported_abort_control, - unsupported_abort_transfers, - unsupported_copy_transfer_data, - }, - { - USB_API_COMPOSITE, - "Composite API", - composite_driver_names, - ARRAYSIZE(composite_driver_names), - composite_init, - composite_exit, - composite_open, - composite_close, - common_configure_endpoints, - composite_claim_interface, - composite_set_interface_altsetting, - composite_release_interface, - composite_clear_halt, - composite_reset_device, - composite_submit_bulk_transfer, - composite_submit_iso_transfer, - composite_submit_control_transfer, - composite_abort_control, - composite_abort_transfers, - composite_copy_transfer_data, - }, - { - USB_API_WINUSBX, - "WinUSB-like APIs", - winusbx_driver_names, - ARRAYSIZE(winusbx_driver_names), - winusbx_init, - winusbx_exit, - winusbx_open, - winusbx_close, - winusbx_configure_endpoints, - winusbx_claim_interface, - winusbx_set_interface_altsetting, - winusbx_release_interface, - winusbx_clear_halt, - winusbx_reset_device, - winusbx_submit_bulk_transfer, - unsupported_submit_iso_transfer, - winusbx_submit_control_transfer, - winusbx_abort_control, - winusbx_abort_transfers, - winusbx_copy_transfer_data, - }, - { - USB_API_HID, - "HID API", - hid_driver_names, - ARRAYSIZE(hid_driver_names), - hid_init, - hid_exit, - hid_open, - hid_close, - common_configure_endpoints, - hid_claim_interface, - hid_set_interface_altsetting, - hid_release_interface, - hid_clear_halt, - hid_reset_device, - hid_submit_bulk_transfer, - unsupported_submit_iso_transfer, - hid_submit_control_transfer, - hid_abort_transfers, - hid_abort_transfers, - hid_copy_transfer_data, - }, -}; - - -/* - * WinUSB-like (WinUSB, libusb0/libusbK through libusbk DLL) API functions - */ -#define WinUSBX_Set(fn) \ - do { \ - if (native_winusb) \ - WinUSBX[i].fn = (WinUsb_##fn##_t)GetProcAddress(h, "WinUsb_" #fn); \ - else \ - pLibK_GetProcAddress((PVOID *)&WinUSBX[i].fn, i, KUSB_FNID_##fn); \ - } while (0) - -static int winusbx_init(int sub_api, struct libusb_context *ctx) -{ - HMODULE h; - bool native_winusb; - int i; - KLIB_VERSION LibK_Version; - LibK_GetProcAddress_t pLibK_GetProcAddress = NULL; - LibK_GetVersion_t pLibK_GetVersion; - - h = LoadLibraryA("libusbK"); - - if (h == NULL) { - usbi_info(ctx, "libusbK DLL is not available, will use native WinUSB"); - h = LoadLibraryA("WinUSB"); - - if (h == NULL) { - usbi_warn(ctx, "WinUSB DLL is not available either, " - "you will not be able to access devices outside of enumeration"); - return LIBUSB_ERROR_NOT_FOUND; - } - } else { - usbi_dbg("using libusbK DLL for universal access"); - pLibK_GetVersion = (LibK_GetVersion_t)GetProcAddress(h, "LibK_GetVersion"); - if (pLibK_GetVersion != NULL) { - pLibK_GetVersion(&LibK_Version); - usbi_dbg("libusbK version: %d.%d.%d.%d", LibK_Version.Major, LibK_Version.Minor, - LibK_Version.Micro, LibK_Version.Nano); - } - pLibK_GetProcAddress = (LibK_GetProcAddress_t)GetProcAddress(h, "LibK_GetProcAddress"); - if (pLibK_GetProcAddress == NULL) { - usbi_err(ctx, "LibK_GetProcAddress() not found in libusbK DLL"); - FreeLibrary(h); - return LIBUSB_ERROR_NOT_FOUND; - } - } - - native_winusb = (pLibK_GetProcAddress == NULL); - for (i = SUB_API_LIBUSBK; i < SUB_API_MAX; i++) { - WinUSBX_Set(AbortPipe); - WinUSBX_Set(ControlTransfer); - WinUSBX_Set(FlushPipe); - WinUSBX_Set(Free); - WinUSBX_Set(GetAssociatedInterface); - WinUSBX_Set(GetCurrentAlternateSetting); - WinUSBX_Set(GetDescriptor); - WinUSBX_Set(GetOverlappedResult); - WinUSBX_Set(GetPipePolicy); - WinUSBX_Set(GetPowerPolicy); - WinUSBX_Set(Initialize); - WinUSBX_Set(QueryDeviceInformation); - WinUSBX_Set(QueryInterfaceSettings); - WinUSBX_Set(QueryPipe); - WinUSBX_Set(ReadPipe); - WinUSBX_Set(ResetPipe); - WinUSBX_Set(SetCurrentAlternateSetting); - WinUSBX_Set(SetPipePolicy); - WinUSBX_Set(SetPowerPolicy); - WinUSBX_Set(WritePipe); - if (!native_winusb) - WinUSBX_Set(ResetDevice); - - if (WinUSBX[i].Initialize != NULL) { - WinUSBX[i].initialized = true; - usbi_dbg("initalized sub API %s", sub_api_name[i]); - } else { - usbi_warn(ctx, "Failed to initalize sub API %s", sub_api_name[i]); - WinUSBX[i].initialized = false; - } - } - - WinUSBX_handle = h; - return LIBUSB_SUCCESS; -} - -static int winusbx_exit(int sub_api) -{ - if (WinUSBX_handle != NULL) { - FreeLibrary(WinUSBX_handle); - WinUSBX_handle = NULL; - - /* Reset the WinUSBX API structures */ - memset(&WinUSBX, 0, sizeof(WinUSBX)); - } - - return LIBUSB_SUCCESS; -} - -// NB: open and close must ensure that they only handle interface of -// the right API type, as these functions can be called wholesale from -// composite_open(), with interfaces belonging to different APIs -static int winusbx_open(int sub_api, struct libusb_device_handle *dev_handle) -{ - struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev); - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle); - - HANDLE file_handle; - int i; - - CHECK_WINUSBX_AVAILABLE(sub_api); - - // WinUSB requires a separate handle for each interface - for (i = 0; i < USB_MAXINTERFACES; i++) { - if ((priv->usb_interface[i].path != NULL) - && (priv->usb_interface[i].apib->id == USB_API_WINUSBX)) { - file_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ, - NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL); - if (file_handle == INVALID_HANDLE_VALUE) { - usbi_err(ctx, "could not open device %s (interface %d): %s", priv->usb_interface[i].path, i, windows_error_str(0)); - switch(GetLastError()) { - case ERROR_FILE_NOT_FOUND: // The device was disconnected - return LIBUSB_ERROR_NO_DEVICE; - case ERROR_ACCESS_DENIED: - return LIBUSB_ERROR_ACCESS; - default: - return LIBUSB_ERROR_IO; - } - } - handle_priv->interface_handle[i].dev_handle = file_handle; - } - } - - return LIBUSB_SUCCESS; -} - -static void winusbx_close(int sub_api, struct libusb_device_handle *dev_handle) -{ - struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle); - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - HANDLE handle; - int i; - - if (sub_api == SUB_API_NOTSET) - sub_api = priv->sub_api; - - if (!WinUSBX[sub_api].initialized) - return; - - if (priv->apib->id == USB_API_COMPOSITE) { - // If this is a composite device, just free and close all WinUSB-like - // interfaces directly (each is independent and not associated with another) - for (i = 0; i < USB_MAXINTERFACES; i++) { - if (priv->usb_interface[i].apib->id == USB_API_WINUSBX) { - handle = handle_priv->interface_handle[i].api_handle; - if (HANDLE_VALID(handle)) - WinUSBX[sub_api].Free(handle); - - handle = handle_priv->interface_handle[i].dev_handle; - if (HANDLE_VALID(handle)) - CloseHandle(handle); - } - } - } else { - // If this is a WinUSB device, free all interfaces above interface 0, - // then free and close interface 0 last - for (i = 1; i < USB_MAXINTERFACES; i++) { - handle = handle_priv->interface_handle[i].api_handle; - if (HANDLE_VALID(handle)) - WinUSBX[sub_api].Free(handle); - } - handle = handle_priv->interface_handle[0].api_handle; - if (HANDLE_VALID(handle)) - WinUSBX[sub_api].Free(handle); - - handle = handle_priv->interface_handle[0].dev_handle; - if (HANDLE_VALID(handle)) - CloseHandle(handle); - } -} - -static int winusbx_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, int iface) -{ - struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle); - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - HANDLE winusb_handle = handle_priv->interface_handle[iface].api_handle; - UCHAR policy; - ULONG timeout = 0; - uint8_t endpoint_address; - int i; - - CHECK_WINUSBX_AVAILABLE(sub_api); - - // With handle and enpoints set (in parent), we can setup the default pipe properties - // see http://download.microsoft.com/download/D/1/D/D1DD7745-426B-4CC3-A269-ABBBE427C0EF/DVC-T705_DDC08.pptx - for (i = -1; i < priv->usb_interface[iface].nb_endpoints; i++) { - endpoint_address = (i == -1) ? 0 : priv->usb_interface[iface].endpoint[i]; - if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address, - PIPE_TRANSFER_TIMEOUT, sizeof(ULONG), &timeout)) - usbi_dbg("failed to set PIPE_TRANSFER_TIMEOUT for control endpoint %02X", endpoint_address); - - if ((i == -1) || (sub_api == SUB_API_LIBUSB0)) - continue; // Other policies don't apply to control endpoint or libusb0 - - policy = false; - if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address, - SHORT_PACKET_TERMINATE, sizeof(UCHAR), &policy)) - usbi_dbg("failed to disable SHORT_PACKET_TERMINATE for endpoint %02X", endpoint_address); - - if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address, - IGNORE_SHORT_PACKETS, sizeof(UCHAR), &policy)) - usbi_dbg("failed to disable IGNORE_SHORT_PACKETS for endpoint %02X", endpoint_address); - - policy = true; - /* ALLOW_PARTIAL_READS must be enabled due to likely libusbK bug. See: - https://sourceforge.net/mailarchive/message.php?msg_id=29736015 */ - if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address, - ALLOW_PARTIAL_READS, sizeof(UCHAR), &policy)) - usbi_dbg("failed to enable ALLOW_PARTIAL_READS for endpoint %02X", endpoint_address); - - if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address, - AUTO_CLEAR_STALL, sizeof(UCHAR), &policy)) - usbi_dbg("failed to enable AUTO_CLEAR_STALL for endpoint %02X", endpoint_address); - } - - return LIBUSB_SUCCESS; -} - -static int winusbx_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface) -{ - struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev); - struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle); - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - bool is_using_usbccgp = (priv->apib->id == USB_API_COMPOSITE); - SP_DEVICE_INTERFACE_DETAIL_DATA_A *dev_interface_details = NULL; - HDEVINFO dev_info = INVALID_HANDLE_VALUE; - SP_DEVINFO_DATA dev_info_data; - char *dev_path_no_guid = NULL; - char filter_path[] = "\\\\.\\libusb0-0000"; - bool found_filter = false; - HANDLE file_handle, winusb_handle; - DWORD err; - int i; - - CHECK_WINUSBX_AVAILABLE(sub_api); - - // If the device is composite, but using the default Windows composite parent driver (usbccgp) - // or if it's the first WinUSB-like interface, we get a handle through Initialize(). - if ((is_using_usbccgp) || (iface == 0)) { - // composite device (independent interfaces) or interface 0 - file_handle = handle_priv->interface_handle[iface].dev_handle; - if (!HANDLE_VALID(file_handle)) - return LIBUSB_ERROR_NOT_FOUND; - - if (!WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) { - handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE; - err = GetLastError(); - switch(err) { - case ERROR_BAD_COMMAND: - // The device was disconnected - usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(0)); - return LIBUSB_ERROR_NO_DEVICE; - default: - // it may be that we're using the libusb0 filter driver. - // TODO: can we move this whole business into the K/0 DLL? - for (i = 0; ; i++) { - safe_free(dev_interface_details); - safe_free(dev_path_no_guid); - - dev_interface_details = get_interface_details_filter(ctx, &dev_info, &dev_info_data, &GUID_DEVINTERFACE_LIBUSB0_FILTER, i, filter_path); - if ((found_filter) || (dev_interface_details == NULL)) - break; - - // ignore GUID part - dev_path_no_guid = sanitize_path(strtok(dev_interface_details->DevicePath, "{")); - if (dev_path_no_guid == NULL) - continue; - - if (strncmp(dev_path_no_guid, priv->usb_interface[iface].path, strlen(dev_path_no_guid)) == 0) { - file_handle = CreateFileA(filter_path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ, - NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL); - if (file_handle != INVALID_HANDLE_VALUE) { - if (WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) { - // Replace the existing file handle with the working one - CloseHandle(handle_priv->interface_handle[iface].dev_handle); - handle_priv->interface_handle[iface].dev_handle = file_handle; - found_filter = true; - } else { - usbi_err(ctx, "could not initialize filter driver for %s", filter_path); - CloseHandle(file_handle); - } - } else { - usbi_err(ctx, "could not open device %s: %s", filter_path, windows_error_str(0)); - } - } - } - free(dev_interface_details); - if (!found_filter) { - usbi_err(ctx, "could not access interface %d: %s", iface, windows_error_str(err)); - return LIBUSB_ERROR_ACCESS; - } - } - } - handle_priv->interface_handle[iface].api_handle = winusb_handle; - } else { - // For all other interfaces, use GetAssociatedInterface() - winusb_handle = handle_priv->interface_handle[0].api_handle; - // It is a requirement for multiple interface devices on Windows that, to you - // must first claim the first interface before you claim the others - if (!HANDLE_VALID(winusb_handle)) { - file_handle = handle_priv->interface_handle[0].dev_handle; - if (WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) { - handle_priv->interface_handle[0].api_handle = winusb_handle; - usbi_warn(ctx, "auto-claimed interface 0 (required to claim %d with WinUSB)", iface); - } else { - usbi_warn(ctx, "failed to auto-claim interface 0 (required to claim %d with WinUSB): %s", iface, windows_error_str(0)); - return LIBUSB_ERROR_ACCESS; - } - } - if (!WinUSBX[sub_api].GetAssociatedInterface(winusb_handle, (UCHAR)(iface - 1), - &handle_priv->interface_handle[iface].api_handle)) { - handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE; - switch(GetLastError()) { - case ERROR_NO_MORE_ITEMS: // invalid iface - return LIBUSB_ERROR_NOT_FOUND; - case ERROR_BAD_COMMAND: // The device was disconnected - return LIBUSB_ERROR_NO_DEVICE; - case ERROR_ALREADY_EXISTS: // already claimed - return LIBUSB_ERROR_BUSY; - default: - usbi_err(ctx, "could not claim interface %d: %s", iface, windows_error_str(0)); - return LIBUSB_ERROR_ACCESS; - } - } - } - usbi_dbg("claimed interface %d", iface); - handle_priv->active_interface = iface; - - return LIBUSB_SUCCESS; -} - -static int winusbx_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface) -{ - struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle); - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - HANDLE winusb_handle; - - CHECK_WINUSBX_AVAILABLE(sub_api); - - winusb_handle = handle_priv->interface_handle[iface].api_handle; - if (!HANDLE_VALID(winusb_handle)) - return LIBUSB_ERROR_NOT_FOUND; - - WinUSBX[sub_api].Free(winusb_handle); - handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE; - - return LIBUSB_SUCCESS; -} - -/* - * Return the first valid interface (of the same API type), for control transfers - */ -static int get_valid_interface(struct libusb_device_handle *dev_handle, int api_id) -{ - struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle); - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - int i; - - if ((api_id < USB_API_WINUSBX) || (api_id > USB_API_HID)) { - usbi_dbg("unsupported API ID"); - return -1; - } - - for (i = 0; i < USB_MAXINTERFACES; i++) { - if (HANDLE_VALID(handle_priv->interface_handle[i].dev_handle) - && HANDLE_VALID(handle_priv->interface_handle[i].api_handle) - && (priv->usb_interface[i].apib->id == api_id)) - return i; - } - - return -1; -} - -/* - * Lookup interface by endpoint address. -1 if not found - */ -static int interface_by_endpoint(struct windows_device_priv *priv, - struct windows_device_handle_priv *handle_priv, uint8_t endpoint_address) -{ - int i, j; - - for (i = 0; i < USB_MAXINTERFACES; i++) { - if (!HANDLE_VALID(handle_priv->interface_handle[i].api_handle)) - continue; - if (priv->usb_interface[i].endpoint == NULL) - continue; - for (j = 0; j < priv->usb_interface[i].nb_endpoints; j++) { - if (priv->usb_interface[i].endpoint[j] == endpoint_address) - return i; - } - } - - return -1; -} - -static int winusbx_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev); - struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev); - struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer); - struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle); - WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *)transfer->buffer; - ULONG size; - HANDLE winusb_handle; - int current_interface; - struct winfd wfd; - - CHECK_WINUSBX_AVAILABLE(sub_api); - - transfer_priv->pollable_fd = INVALID_WINFD; - size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE; - - // Windows places upper limits on the control transfer size - // See: https://msdn.microsoft.com/en-us/library/windows/hardware/ff538112.aspx - if (size > MAX_CTRL_BUFFER_LENGTH) - return LIBUSB_ERROR_INVALID_PARAM; - - current_interface = get_valid_interface(transfer->dev_handle, USB_API_WINUSBX); - if (current_interface < 0) { - if (auto_claim(transfer, ¤t_interface, USB_API_WINUSBX) != LIBUSB_SUCCESS) - return LIBUSB_ERROR_NOT_FOUND; - } - - usbi_dbg("will use interface %d", current_interface); - winusb_handle = handle_priv->interface_handle[current_interface].api_handle; - - wfd = usbi_create_fd(winusb_handle, RW_READ, NULL, NULL); - // Always use the handle returned from usbi_create_fd (wfd.handle) - if (wfd.fd < 0) - return LIBUSB_ERROR_NO_MEM; - - // Sending of set configuration control requests from WinUSB creates issues - if (((setup->request_type & (0x03 << 5)) == LIBUSB_REQUEST_TYPE_STANDARD) - && (setup->request == LIBUSB_REQUEST_SET_CONFIGURATION)) { - if (setup->value != priv->active_config) { - usbi_warn(ctx, "cannot set configuration other than the default one"); - usbi_free_fd(&wfd); - return LIBUSB_ERROR_INVALID_PARAM; - } - wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY; - wfd.overlapped->InternalHigh = 0; - } else { - if (!WinUSBX[sub_api].ControlTransfer(wfd.handle, *setup, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, size, NULL, wfd.overlapped)) { - if (GetLastError() != ERROR_IO_PENDING) { - usbi_warn(ctx, "ControlTransfer failed: %s", windows_error_str(0)); - usbi_free_fd(&wfd); - return LIBUSB_ERROR_IO; - } - } else { - wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY; - wfd.overlapped->InternalHigh = (DWORD)size; - } - } - - // Use priv_transfer to store data needed for async polling - transfer_priv->pollable_fd = wfd; - transfer_priv->interface_number = (uint8_t)current_interface; - - return LIBUSB_SUCCESS; -} - -static int winusbx_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting) -{ - struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev); - struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle); - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - HANDLE winusb_handle; - - CHECK_WINUSBX_AVAILABLE(sub_api); - - if (altsetting > 255) - return LIBUSB_ERROR_INVALID_PARAM; - - winusb_handle = handle_priv->interface_handle[iface].api_handle; - if (!HANDLE_VALID(winusb_handle)) { - usbi_err(ctx, "interface must be claimed first"); - return LIBUSB_ERROR_NOT_FOUND; - } - - if (!WinUSBX[sub_api].SetCurrentAlternateSetting(winusb_handle, (UCHAR)altsetting)) { - usbi_err(ctx, "SetCurrentAlternateSetting failed: %s", windows_error_str(0)); - return LIBUSB_ERROR_IO; - } - - return LIBUSB_SUCCESS; -} - -static int winusbx_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev); - struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer); - struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle); - struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev); - HANDLE winusb_handle; - bool ret; - int current_interface; - struct winfd wfd; - - CHECK_WINUSBX_AVAILABLE(sub_api); - - transfer_priv->pollable_fd = INVALID_WINFD; - - current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint); - if (current_interface < 0) { - usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer"); - return LIBUSB_ERROR_NOT_FOUND; - } - - usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface); - - winusb_handle = handle_priv->interface_handle[current_interface].api_handle; - - wfd = usbi_create_fd(winusb_handle, IS_XFERIN(transfer) ? RW_READ : RW_WRITE, NULL, NULL); - // Always use the handle returned from usbi_create_fd (wfd.handle) - if (wfd.fd < 0) - return LIBUSB_ERROR_NO_MEM; - - if (IS_XFERIN(transfer)) { - usbi_dbg("reading %d bytes", transfer->length); - ret = WinUSBX[sub_api].ReadPipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped); - } else { - usbi_dbg("writing %d bytes", transfer->length); - ret = WinUSBX[sub_api].WritePipe(wfd.handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, wfd.overlapped); - } - - if (!ret) { - if (GetLastError() != ERROR_IO_PENDING) { - usbi_err(ctx, "ReadPipe/WritePipe failed: %s", windows_error_str(0)); - usbi_free_fd(&wfd); - return LIBUSB_ERROR_IO; - } - } else { - wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY; - wfd.overlapped->InternalHigh = (DWORD)transfer->length; - } - - transfer_priv->pollable_fd = wfd; - transfer_priv->interface_number = (uint8_t)current_interface; - - return LIBUSB_SUCCESS; -} - -static int winusbx_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint) -{ - struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev); - struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle); - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - HANDLE winusb_handle; - int current_interface; - - CHECK_WINUSBX_AVAILABLE(sub_api); - - current_interface = interface_by_endpoint(priv, handle_priv, endpoint); - if (current_interface < 0) { - usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear"); - return LIBUSB_ERROR_NOT_FOUND; - } - - usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface); - winusb_handle = handle_priv->interface_handle[current_interface].api_handle; - - if (!WinUSBX[sub_api].ResetPipe(winusb_handle, endpoint)) { - usbi_err(ctx, "ResetPipe failed: %s", windows_error_str(0)); - return LIBUSB_ERROR_NO_DEVICE; - } - - return LIBUSB_SUCCESS; -} - -/* - * from http://www.winvistatips.com/winusb-bugchecks-t335323.html (confirmed - * through testing as well): - * "You can not call WinUsb_AbortPipe on control pipe. You can possibly cancel - * the control transfer using CancelIo" - */ -static int winusbx_abort_control(int sub_api, struct usbi_transfer *itransfer) -{ - // Cancelling of the I/O is done in the parent - return LIBUSB_SUCCESS; -} - -static int winusbx_abort_transfers(int sub_api, struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev); - struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle); - struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer); - struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev); - HANDLE winusb_handle; - int current_interface; - - CHECK_WINUSBX_AVAILABLE(sub_api); - - current_interface = transfer_priv->interface_number; - if ((current_interface < 0) || (current_interface >= USB_MAXINTERFACES)) { - usbi_err(ctx, "program assertion failed: invalid interface_number"); - return LIBUSB_ERROR_NOT_FOUND; - } - usbi_dbg("will use interface %d", current_interface); - - winusb_handle = handle_priv->interface_handle[current_interface].api_handle; - - if (!WinUSBX[sub_api].AbortPipe(winusb_handle, transfer->endpoint)) { - usbi_err(ctx, "AbortPipe failed: %s", windows_error_str(0)); - return LIBUSB_ERROR_NO_DEVICE; - } - - return LIBUSB_SUCCESS; -} - -/* - * from the "How to Use WinUSB to Communicate with a USB Device" Microsoft white paper - * (http://www.microsoft.com/whdc/connect/usb/winusb_howto.mspx): - * "WinUSB does not support host-initiated reset port and cycle port operations" and - * IOCTL_INTERNAL_USB_CYCLE_PORT is only available in kernel mode and the - * IOCTL_USB_HUB_CYCLE_PORT ioctl was removed from Vista => the best we can do is - * cycle the pipes (and even then, the control pipe can not be reset using WinUSB) - */ -// TODO: (post hotplug): see if we can force eject the device and redetect it (reuse hotplug?) -static int winusbx_reset_device(int sub_api, struct libusb_device_handle *dev_handle) -{ - struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev); - struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle); - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - struct winfd wfd; - HANDLE winusb_handle; - int i, j; - - CHECK_WINUSBX_AVAILABLE(sub_api); - - // Reset any available pipe (except control) - for (i = 0; i < USB_MAXINTERFACES; i++) { - winusb_handle = handle_priv->interface_handle[i].api_handle; - for (wfd = handle_to_winfd(winusb_handle); wfd.fd > 0; ) { - // Cancel any pollable I/O - usbi_remove_pollfd(ctx, wfd.fd); - usbi_free_fd(&wfd); - wfd = handle_to_winfd(winusb_handle); - } - - if (HANDLE_VALID(winusb_handle)) { - for (j = 0; j < priv->usb_interface[i].nb_endpoints; j++) { - usbi_dbg("resetting ep %02X", priv->usb_interface[i].endpoint[j]); - if (!WinUSBX[sub_api].AbortPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) - usbi_err(ctx, "AbortPipe (pipe address %02X) failed: %s", - priv->usb_interface[i].endpoint[j], windows_error_str(0)); - - // FlushPipe seems to fail on OUT pipes - if (IS_EPIN(priv->usb_interface[i].endpoint[j]) - && (!WinUSBX[sub_api].FlushPipe(winusb_handle, priv->usb_interface[i].endpoint[j]))) - usbi_err(ctx, "FlushPipe (pipe address %02X) failed: %s", - priv->usb_interface[i].endpoint[j], windows_error_str(0)); - - if (!WinUSBX[sub_api].ResetPipe(winusb_handle, priv->usb_interface[i].endpoint[j])) - usbi_err(ctx, "ResetPipe (pipe address %02X) failed: %s", - priv->usb_interface[i].endpoint[j], windows_error_str(0)); - } - } - } - - // libusbK & libusb0 have the ability to issue an actual device reset - if (WinUSBX[sub_api].ResetDevice != NULL) { - winusb_handle = handle_priv->interface_handle[0].api_handle; - if (HANDLE_VALID(winusb_handle)) - WinUSBX[sub_api].ResetDevice(winusb_handle); - } - - return LIBUSB_SUCCESS; -} - -static int winusbx_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size) -{ - itransfer->transferred += io_size; - return LIBUSB_TRANSFER_COMPLETED; -} - -/* - * Internal HID Support functions (from libusb-win32) - * Note that functions that complete data transfer synchronously must return - * LIBUSB_COMPLETED instead of LIBUSB_SUCCESS - */ -static int _hid_get_hid_descriptor(struct hid_device_priv *dev, void *data, size_t *size); -static int _hid_get_report_descriptor(struct hid_device_priv *dev, void *data, size_t *size); - -static int _hid_wcslen(WCHAR *str) -{ - int i = 0; - - while (str[i] && (str[i] != 0x409)) - i++; - - return i; -} - -static int _hid_get_device_descriptor(struct hid_device_priv *dev, void *data, size_t *size) -{ - struct libusb_device_descriptor d; - - d.bLength = LIBUSB_DT_DEVICE_SIZE; - d.bDescriptorType = LIBUSB_DT_DEVICE; - d.bcdUSB = 0x0200; /* 2.00 */ - d.bDeviceClass = 0; - d.bDeviceSubClass = 0; - d.bDeviceProtocol = 0; - d.bMaxPacketSize0 = 64; /* fix this! */ - d.idVendor = (uint16_t)dev->vid; - d.idProduct = (uint16_t)dev->pid; - d.bcdDevice = 0x0100; - d.iManufacturer = dev->string_index[0]; - d.iProduct = dev->string_index[1]; - d.iSerialNumber = dev->string_index[2]; - d.bNumConfigurations = 1; - - if (*size > LIBUSB_DT_DEVICE_SIZE) - *size = LIBUSB_DT_DEVICE_SIZE; - memcpy(data, &d, *size); - - return LIBUSB_COMPLETED; -} - -static int _hid_get_config_descriptor(struct hid_device_priv *dev, void *data, size_t *size) -{ - char num_endpoints = 0; - size_t config_total_len = 0; - char tmp[HID_MAX_CONFIG_DESC_SIZE]; - struct libusb_config_descriptor *cd; - struct libusb_interface_descriptor *id; - struct libusb_hid_descriptor *hd; - struct libusb_endpoint_descriptor *ed; - size_t tmp_size; - - if (dev->input_report_size) - num_endpoints++; - if (dev->output_report_size) - num_endpoints++; - - config_total_len = LIBUSB_DT_CONFIG_SIZE + LIBUSB_DT_INTERFACE_SIZE - + LIBUSB_DT_HID_SIZE + num_endpoints * LIBUSB_DT_ENDPOINT_SIZE; - - cd = (struct libusb_config_descriptor *)tmp; - id = (struct libusb_interface_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE); - hd = (struct libusb_hid_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE - + LIBUSB_DT_INTERFACE_SIZE); - ed = (struct libusb_endpoint_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE - + LIBUSB_DT_INTERFACE_SIZE - + LIBUSB_DT_HID_SIZE); - - cd->bLength = LIBUSB_DT_CONFIG_SIZE; - cd->bDescriptorType = LIBUSB_DT_CONFIG; - cd->wTotalLength = (uint16_t)config_total_len; - cd->bNumInterfaces = 1; - cd->bConfigurationValue = 1; - cd->iConfiguration = 0; - cd->bmAttributes = 1 << 7; /* bus powered */ - cd->MaxPower = 50; - - id->bLength = LIBUSB_DT_INTERFACE_SIZE; - id->bDescriptorType = LIBUSB_DT_INTERFACE; - id->bInterfaceNumber = 0; - id->bAlternateSetting = 0; - id->bNumEndpoints = num_endpoints; - id->bInterfaceClass = 3; - id->bInterfaceSubClass = 0; - id->bInterfaceProtocol = 0; - id->iInterface = 0; - - tmp_size = LIBUSB_DT_HID_SIZE; - _hid_get_hid_descriptor(dev, hd, &tmp_size); - - if (dev->input_report_size) { - ed->bLength = LIBUSB_DT_ENDPOINT_SIZE; - ed->bDescriptorType = LIBUSB_DT_ENDPOINT; - ed->bEndpointAddress = HID_IN_EP; - ed->bmAttributes = 3; - ed->wMaxPacketSize = dev->input_report_size - 1; - ed->bInterval = 10; - ed = (struct libusb_endpoint_descriptor *)((char *)ed + LIBUSB_DT_ENDPOINT_SIZE); - } - - if (dev->output_report_size) { - ed->bLength = LIBUSB_DT_ENDPOINT_SIZE; - ed->bDescriptorType = LIBUSB_DT_ENDPOINT; - ed->bEndpointAddress = HID_OUT_EP; - ed->bmAttributes = 3; - ed->wMaxPacketSize = dev->output_report_size - 1; - ed->bInterval = 10; - } - - if (*size > config_total_len) - *size = config_total_len; - memcpy(data, tmp, *size); - - return LIBUSB_COMPLETED; -} - -static int _hid_get_string_descriptor(struct hid_device_priv *dev, int _index, - void *data, size_t *size) -{ - void *tmp = NULL; - size_t tmp_size = 0; - int i; - - /* language ID, EN-US */ - char string_langid[] = {0x09, 0x04}; - - if ((*size < 2) || (*size > 255)) - return LIBUSB_ERROR_OVERFLOW; - - if (_index == 0) { - tmp = string_langid; - tmp_size = sizeof(string_langid) + 2; - } else { - for (i = 0; i < 3; i++) { - if (_index == (dev->string_index[i])) { - tmp = dev->string[i]; - tmp_size = (_hid_wcslen(dev->string[i]) + 1) * sizeof(WCHAR); - break; - } - } - - if (i == 3) // not found - return LIBUSB_ERROR_INVALID_PARAM; - } - - if (!tmp_size) - return LIBUSB_ERROR_INVALID_PARAM; - - if (tmp_size < *size) - *size = tmp_size; - - // 2 byte header - ((uint8_t *)data)[0] = (uint8_t)*size; - ((uint8_t *)data)[1] = LIBUSB_DT_STRING; - memcpy((uint8_t *)data + 2, tmp, *size - 2); - - return LIBUSB_COMPLETED; -} - -static int _hid_get_hid_descriptor(struct hid_device_priv *dev, void *data, size_t *size) -{ - struct libusb_hid_descriptor d; - uint8_t tmp[MAX_HID_DESCRIPTOR_SIZE]; - size_t report_len = MAX_HID_DESCRIPTOR_SIZE; - - _hid_get_report_descriptor(dev, tmp, &report_len); - - d.bLength = LIBUSB_DT_HID_SIZE; - d.bDescriptorType = LIBUSB_DT_HID; - d.bcdHID = 0x0110; /* 1.10 */ - d.bCountryCode = 0; - d.bNumDescriptors = 1; - d.bClassDescriptorType = LIBUSB_DT_REPORT; - d.wClassDescriptorLength = (uint16_t)report_len; - - if (*size > LIBUSB_DT_HID_SIZE) - *size = LIBUSB_DT_HID_SIZE; - memcpy(data, &d, *size); - - return LIBUSB_COMPLETED; -} - -static int _hid_get_report_descriptor(struct hid_device_priv *dev, void *data, size_t *size) -{ - uint8_t d[MAX_HID_DESCRIPTOR_SIZE]; - size_t i = 0; - - /* usage page (0xFFA0 == vendor defined) */ - d[i++] = 0x06; d[i++] = 0xA0; d[i++] = 0xFF; - /* usage (vendor defined) */ - d[i++] = 0x09; d[i++] = 0x01; - /* start collection (application) */ - d[i++] = 0xA1; d[i++] = 0x01; - /* input report */ - if (dev->input_report_size) { - /* usage (vendor defined) */ - d[i++] = 0x09; d[i++] = 0x01; - /* logical minimum (0) */ - d[i++] = 0x15; d[i++] = 0x00; - /* logical maximum (255) */ - d[i++] = 0x25; d[i++] = 0xFF; - /* report size (8 bits) */ - d[i++] = 0x75; d[i++] = 0x08; - /* report count */ - d[i++] = 0x95; d[i++] = (uint8_t)dev->input_report_size - 1; - /* input (data, variable, absolute) */ - d[i++] = 0x81; d[i++] = 0x00; - } - /* output report */ - if (dev->output_report_size) { - /* usage (vendor defined) */ - d[i++] = 0x09; d[i++] = 0x02; - /* logical minimum (0) */ - d[i++] = 0x15; d[i++] = 0x00; - /* logical maximum (255) */ - d[i++] = 0x25; d[i++] = 0xFF; - /* report size (8 bits) */ - d[i++] = 0x75; d[i++] = 0x08; - /* report count */ - d[i++] = 0x95; d[i++] = (uint8_t)dev->output_report_size - 1; - /* output (data, variable, absolute) */ - d[i++] = 0x91; d[i++] = 0x00; - } - /* feature report */ - if (dev->feature_report_size) { - /* usage (vendor defined) */ - d[i++] = 0x09; d[i++] = 0x03; - /* logical minimum (0) */ - d[i++] = 0x15; d[i++] = 0x00; - /* logical maximum (255) */ - d[i++] = 0x25; d[i++] = 0xFF; - /* report size (8 bits) */ - d[i++] = 0x75; d[i++] = 0x08; - /* report count */ - d[i++] = 0x95; d[i++] = (uint8_t)dev->feature_report_size - 1; - /* feature (data, variable, absolute) */ - d[i++] = 0xb2; d[i++] = 0x02; d[i++] = 0x01; - } - - /* end collection */ - d[i++] = 0xC0; - - if (*size > i) - *size = i; - memcpy(data, d, *size); - - return LIBUSB_COMPLETED; -} - -static int _hid_get_descriptor(struct hid_device_priv *dev, HANDLE hid_handle, int recipient, - int type, int _index, void *data, size_t *size) -{ - switch(type) { - case LIBUSB_DT_DEVICE: - usbi_dbg("LIBUSB_DT_DEVICE"); - return _hid_get_device_descriptor(dev, data, size); - case LIBUSB_DT_CONFIG: - usbi_dbg("LIBUSB_DT_CONFIG"); - if (!_index) - return _hid_get_config_descriptor(dev, data, size); - return LIBUSB_ERROR_INVALID_PARAM; - case LIBUSB_DT_STRING: - usbi_dbg("LIBUSB_DT_STRING"); - return _hid_get_string_descriptor(dev, _index, data, size); - case LIBUSB_DT_HID: - usbi_dbg("LIBUSB_DT_HID"); - if (!_index) - return _hid_get_hid_descriptor(dev, data, size); - return LIBUSB_ERROR_INVALID_PARAM; - case LIBUSB_DT_REPORT: - usbi_dbg("LIBUSB_DT_REPORT"); - if (!_index) - return _hid_get_report_descriptor(dev, data, size); - return LIBUSB_ERROR_INVALID_PARAM; - case LIBUSB_DT_PHYSICAL: - usbi_dbg("LIBUSB_DT_PHYSICAL"); - if (HidD_GetPhysicalDescriptor(hid_handle, data, (ULONG)*size)) - return LIBUSB_COMPLETED; - return LIBUSB_ERROR_OTHER; - } - - usbi_dbg("unsupported"); - return LIBUSB_ERROR_NOT_SUPPORTED; -} - -static int _hid_get_report(struct hid_device_priv *dev, HANDLE hid_handle, int id, void *data, - struct windows_transfer_priv *tp, size_t *size, OVERLAPPED *overlapped, int report_type) -{ - uint8_t *buf; - DWORD ioctl_code, read_size, expected_size = (DWORD)*size; - int r = LIBUSB_SUCCESS; - - if (tp->hid_buffer != NULL) - usbi_dbg("program assertion failed: hid_buffer is not NULL"); - - if ((*size == 0) || (*size > MAX_HID_REPORT_SIZE)) { - usbi_dbg("invalid size (%u)", *size); - return LIBUSB_ERROR_INVALID_PARAM; - } - - switch (report_type) { - case HID_REPORT_TYPE_INPUT: - ioctl_code = IOCTL_HID_GET_INPUT_REPORT; - break; - case HID_REPORT_TYPE_FEATURE: - ioctl_code = IOCTL_HID_GET_FEATURE; - break; - default: - usbi_dbg("unknown HID report type %d", report_type); - return LIBUSB_ERROR_INVALID_PARAM; - } - - // Add a trailing byte to detect overflows - buf = calloc(1, expected_size + 1); - if (buf == NULL) - return LIBUSB_ERROR_NO_MEM; - - buf[0] = (uint8_t)id; // Must be set always - usbi_dbg("report ID: 0x%02X", buf[0]); - - tp->hid_expected_size = expected_size; - read_size = expected_size; - - // NB: The size returned by DeviceIoControl doesn't include report IDs when not in use (0) - if (!DeviceIoControl(hid_handle, ioctl_code, buf, expected_size + 1, - buf, expected_size + 1, &read_size, overlapped)) { - if (GetLastError() != ERROR_IO_PENDING) { - usbi_dbg("Failed to Read HID Report: %s", windows_error_str(0)); - free(buf); - return LIBUSB_ERROR_IO; - } - // Asynchronous wait - tp->hid_buffer = buf; - tp->hid_dest = data; // copy dest, as not necessarily the start of the transfer buffer - return LIBUSB_SUCCESS; - } - - // Transfer completed synchronously => copy and discard extra buffer - if (read_size == 0) { - usbi_warn(NULL, "program assertion failed - read completed synchronously, but no data was read"); - *size = 0; - } else { - if (buf[0] != id) - usbi_warn(NULL, "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id); - - if ((size_t)read_size > expected_size) { - r = LIBUSB_ERROR_OVERFLOW; - usbi_dbg("OVERFLOW!"); - } else { - r = LIBUSB_COMPLETED; - } - - *size = MIN((size_t)read_size, *size); - if (id == 0) - memcpy(data, buf + 1, *size); // Discard report ID - else - memcpy(data, buf, *size); - } - - free(buf); - return r; -} - -static int _hid_set_report(struct hid_device_priv *dev, HANDLE hid_handle, int id, void *data, - struct windows_transfer_priv *tp, size_t *size, OVERLAPPED *overlapped, int report_type) -{ - uint8_t *buf = NULL; - DWORD ioctl_code, write_size = (DWORD)*size; - - if (tp->hid_buffer != NULL) - usbi_dbg("program assertion failed: hid_buffer is not NULL"); - - if ((*size == 0) || (*size > MAX_HID_REPORT_SIZE)) { - usbi_dbg("invalid size (%u)", *size); - return LIBUSB_ERROR_INVALID_PARAM; - } - - switch (report_type) { - case HID_REPORT_TYPE_OUTPUT: - ioctl_code = IOCTL_HID_SET_OUTPUT_REPORT; - break; - case HID_REPORT_TYPE_FEATURE: - ioctl_code = IOCTL_HID_SET_FEATURE; - break; - default: - usbi_dbg("unknown HID report type %d", report_type); - return LIBUSB_ERROR_INVALID_PARAM; - } - - usbi_dbg("report ID: 0x%02X", id); - // When report IDs are not used (i.e. when id == 0), we must add - // a null report ID. Otherwise, we just use original data buffer - if (id == 0) - write_size++; - - buf = malloc(write_size); - if (buf == NULL) - return LIBUSB_ERROR_NO_MEM; - - if (id == 0) { - buf[0] = 0; - memcpy(buf + 1, data, *size); - } else { - // This seems like a waste, but if we don't duplicate the - // data, we'll get issues when freeing hid_buffer - memcpy(buf, data, *size); - if (buf[0] != id) - usbi_warn(NULL, "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id); - } - - // NB: The size returned by DeviceIoControl doesn't include report IDs when not in use (0) - if (!DeviceIoControl(hid_handle, ioctl_code, buf, write_size, - buf, write_size, &write_size, overlapped)) { - if (GetLastError() != ERROR_IO_PENDING) { - usbi_dbg("Failed to Write HID Output Report: %s", windows_error_str(0)); - free(buf); - return LIBUSB_ERROR_IO; - } - tp->hid_buffer = buf; - tp->hid_dest = NULL; - return LIBUSB_SUCCESS; - } - - // Transfer completed synchronously - *size = write_size; - if (write_size == 0) - usbi_dbg("program assertion failed - write completed synchronously, but no data was written"); - - free(buf); - return LIBUSB_COMPLETED; -} - -static int _hid_class_request(struct hid_device_priv *dev, HANDLE hid_handle, int request_type, - int request, int value, int _index, void *data, struct windows_transfer_priv *tp, - size_t *size, OVERLAPPED *overlapped) -{ - int report_type = (value >> 8) & 0xFF; - int report_id = value & 0xFF; - - if ((LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_INTERFACE) - && (LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_DEVICE)) - return LIBUSB_ERROR_INVALID_PARAM; - - if (LIBUSB_REQ_OUT(request_type) && request == HID_REQ_SET_REPORT) - return _hid_set_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type); - - if (LIBUSB_REQ_IN(request_type) && request == HID_REQ_GET_REPORT) - return _hid_get_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type); - - return LIBUSB_ERROR_INVALID_PARAM; -} - - -/* - * HID API functions - */ -static int hid_init(int sub_api, struct libusb_context *ctx) -{ - DLL_GET_HANDLE(hid); - DLL_LOAD_FUNC(hid, HidD_GetAttributes, TRUE); - DLL_LOAD_FUNC(hid, HidD_GetHidGuid, TRUE); - DLL_LOAD_FUNC(hid, HidD_GetPreparsedData, TRUE); - DLL_LOAD_FUNC(hid, HidD_FreePreparsedData, TRUE); - DLL_LOAD_FUNC(hid, HidD_GetManufacturerString, TRUE); - DLL_LOAD_FUNC(hid, HidD_GetProductString, TRUE); - DLL_LOAD_FUNC(hid, HidD_GetSerialNumberString, TRUE); - DLL_LOAD_FUNC(hid, HidP_GetCaps, TRUE); - DLL_LOAD_FUNC(hid, HidD_SetNumInputBuffers, TRUE); - DLL_LOAD_FUNC(hid, HidD_SetFeature, TRUE); - DLL_LOAD_FUNC(hid, HidD_GetFeature, TRUE); - DLL_LOAD_FUNC(hid, HidD_GetPhysicalDescriptor, TRUE); - DLL_LOAD_FUNC(hid, HidD_GetInputReport, FALSE); - DLL_LOAD_FUNC(hid, HidD_SetOutputReport, FALSE); - DLL_LOAD_FUNC(hid, HidD_FlushQueue, TRUE); - DLL_LOAD_FUNC(hid, HidP_GetValueCaps, TRUE); - - api_hid_available = true; - return LIBUSB_SUCCESS; -} - -static int hid_exit(int sub_api) -{ - DLL_FREE_HANDLE(hid); - - return LIBUSB_SUCCESS; -} - -// NB: open and close must ensure that they only handle interface of -// the right API type, as these functions can be called wholesale from -// composite_open(), with interfaces belonging to different APIs -static int hid_open(int sub_api, struct libusb_device_handle *dev_handle) -{ - struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev); - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle); - HIDD_ATTRIBUTES hid_attributes; - PHIDP_PREPARSED_DATA preparsed_data = NULL; - HIDP_CAPS capabilities; - HIDP_VALUE_CAPS *value_caps; - HANDLE hid_handle = INVALID_HANDLE_VALUE; - int i, j; - // report IDs handling - ULONG size[3]; - int nb_ids[2]; // zero and nonzero report IDs -#if defined(ENABLE_LOGGING) - const char *type[3] = {"input", "output", "feature"}; -#endif - - CHECK_HID_AVAILABLE; - - if (priv->hid == NULL) { - usbi_err(ctx, "program assertion failed - private HID structure is unitialized"); - return LIBUSB_ERROR_NOT_FOUND; - } - - for (i = 0; i < USB_MAXINTERFACES; i++) { - if ((priv->usb_interface[i].path != NULL) - && (priv->usb_interface[i].apib->id == USB_API_HID)) { - hid_handle = CreateFileA(priv->usb_interface[i].path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ, - NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL); - /* - * http://www.lvr.com/hidfaq.htm: Why do I receive "Access denied" when attempting to access my HID? - * "Windows 2000 and later have exclusive read/write access to HIDs that are configured as a system - * keyboards or mice. An application can obtain a handle to a system keyboard or mouse by not - * requesting READ or WRITE access with CreateFile. Applications can then use HidD_SetFeature and - * HidD_GetFeature (if the device supports Feature reports)." - */ - if (hid_handle == INVALID_HANDLE_VALUE) { - usbi_warn(ctx, "could not open HID device in R/W mode (keyboard or mouse?) - trying without"); - hid_handle = CreateFileA(priv->usb_interface[i].path, 0, FILE_SHARE_WRITE | FILE_SHARE_READ, - NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL); - if (hid_handle == INVALID_HANDLE_VALUE) { - usbi_err(ctx, "could not open device %s (interface %d): %s", priv->path, i, windows_error_str(0)); - switch(GetLastError()) { - case ERROR_FILE_NOT_FOUND: // The device was disconnected - return LIBUSB_ERROR_NO_DEVICE; - case ERROR_ACCESS_DENIED: - return LIBUSB_ERROR_ACCESS; - default: - return LIBUSB_ERROR_IO; - } - } - priv->usb_interface[i].restricted_functionality = true; - } - handle_priv->interface_handle[i].api_handle = hid_handle; - } - } - - hid_attributes.Size = sizeof(hid_attributes); - do { - if (!HidD_GetAttributes(hid_handle, &hid_attributes)) { - usbi_err(ctx, "could not gain access to HID top collection (HidD_GetAttributes)"); - break; - } - - priv->hid->vid = hid_attributes.VendorID; - priv->hid->pid = hid_attributes.ProductID; - - // Set the maximum available input buffer size - for (i = 32; HidD_SetNumInputBuffers(hid_handle, i); i *= 2); - usbi_dbg("set maximum input buffer size to %d", i / 2); - - // Get the maximum input and output report size - if (!HidD_GetPreparsedData(hid_handle, &preparsed_data) || !preparsed_data) { - usbi_err(ctx, "could not read HID preparsed data (HidD_GetPreparsedData)"); - break; - } - if (HidP_GetCaps(preparsed_data, &capabilities) != HIDP_STATUS_SUCCESS) { - usbi_err(ctx, "could not parse HID capabilities (HidP_GetCaps)"); - break; - } - - // Find out if interrupt will need report IDs - size[0] = capabilities.NumberInputValueCaps; - size[1] = capabilities.NumberOutputValueCaps; - size[2] = capabilities.NumberFeatureValueCaps; - for (j = HidP_Input; j <= HidP_Feature; j++) { - usbi_dbg("%u HID %s report value(s) found", (unsigned int)size[j], type[j]); - priv->hid->uses_report_ids[j] = false; - if (size[j] > 0) { - value_caps = calloc(size[j], sizeof(HIDP_VALUE_CAPS)); - if ((value_caps != NULL) - && (HidP_GetValueCaps((HIDP_REPORT_TYPE)j, value_caps, &size[j], preparsed_data) == HIDP_STATUS_SUCCESS) - && (size[j] >= 1)) { - nb_ids[0] = 0; - nb_ids[1] = 0; - for (i = 0; i < (int)size[j]; i++) { - usbi_dbg(" Report ID: 0x%02X", value_caps[i].ReportID); - if (value_caps[i].ReportID != 0) - nb_ids[1]++; - else - nb_ids[0]++; - } - if (nb_ids[1] != 0) { - if (nb_ids[0] != 0) - usbi_warn(ctx, "program assertion failed: zero and nonzero report IDs used for %s", - type[j]); - priv->hid->uses_report_ids[j] = true; - } - } else { - usbi_warn(ctx, " could not process %s report IDs", type[j]); - } - free(value_caps); - } - } - - // Set the report sizes - priv->hid->input_report_size = capabilities.InputReportByteLength; - priv->hid->output_report_size = capabilities.OutputReportByteLength; - priv->hid->feature_report_size = capabilities.FeatureReportByteLength; - - // Fetch string descriptors - priv->hid->string_index[0] = priv->dev_descriptor.iManufacturer; - if (priv->hid->string_index[0] != 0) - HidD_GetManufacturerString(hid_handle, priv->hid->string[0], sizeof(priv->hid->string[0])); - else - priv->hid->string[0][0] = 0; - - priv->hid->string_index[1] = priv->dev_descriptor.iProduct; - if (priv->hid->string_index[1] != 0) - HidD_GetProductString(hid_handle, priv->hid->string[1], sizeof(priv->hid->string[1])); - else - priv->hid->string[1][0] = 0; - - priv->hid->string_index[2] = priv->dev_descriptor.iSerialNumber; - if (priv->hid->string_index[2] != 0) - HidD_GetSerialNumberString(hid_handle, priv->hid->string[2], sizeof(priv->hid->string[2])); - else - priv->hid->string[2][0] = 0; - } while(0); - - if (preparsed_data) - HidD_FreePreparsedData(preparsed_data); - - return LIBUSB_SUCCESS; -} - -static void hid_close(int sub_api, struct libusb_device_handle *dev_handle) -{ - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle); - HANDLE file_handle; - int i; - - if (!api_hid_available) - return; - - for (i = 0; i < USB_MAXINTERFACES; i++) { - if (priv->usb_interface[i].apib->id == USB_API_HID) { - file_handle = handle_priv->interface_handle[i].api_handle; - if (HANDLE_VALID(file_handle)) - CloseHandle(file_handle); - } - } -} - -static int hid_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface) -{ - struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle); - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - - CHECK_HID_AVAILABLE; - - // NB: Disconnection detection is not possible in this function - if (priv->usb_interface[iface].path == NULL) - return LIBUSB_ERROR_NOT_FOUND; // invalid iface - - // We use dev_handle as a flag for interface claimed - if (handle_priv->interface_handle[iface].dev_handle == INTERFACE_CLAIMED) - return LIBUSB_ERROR_BUSY; // already claimed - - - handle_priv->interface_handle[iface].dev_handle = INTERFACE_CLAIMED; - - usbi_dbg("claimed interface %d", iface); - handle_priv->active_interface = iface; - - return LIBUSB_SUCCESS; -} - -static int hid_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface) -{ - struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle); - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - - CHECK_HID_AVAILABLE; - - if (priv->usb_interface[iface].path == NULL) - return LIBUSB_ERROR_NOT_FOUND; // invalid iface - - if (handle_priv->interface_handle[iface].dev_handle != INTERFACE_CLAIMED) - return LIBUSB_ERROR_NOT_FOUND; // invalid iface - - handle_priv->interface_handle[iface].dev_handle = INVALID_HANDLE_VALUE; - - return LIBUSB_SUCCESS; -} - -static int hid_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting) -{ - struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev); - - CHECK_HID_AVAILABLE; - - if (altsetting > 255) - return LIBUSB_ERROR_INVALID_PARAM; - - if (altsetting != 0) { - usbi_err(ctx, "set interface altsetting not supported for altsetting >0"); - return LIBUSB_ERROR_NOT_SUPPORTED; - } - - return LIBUSB_SUCCESS; -} - -static int hid_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer); - struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle); - struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev); - struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev); - WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *)transfer->buffer; - HANDLE hid_handle; - struct winfd wfd; - int current_interface, config; - size_t size; - int r = LIBUSB_ERROR_INVALID_PARAM; - - CHECK_HID_AVAILABLE; - - transfer_priv->pollable_fd = INVALID_WINFD; - safe_free(transfer_priv->hid_buffer); - transfer_priv->hid_dest = NULL; - size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE; - - if (size > MAX_CTRL_BUFFER_LENGTH) - return LIBUSB_ERROR_INVALID_PARAM; - - current_interface = get_valid_interface(transfer->dev_handle, USB_API_HID); - if (current_interface < 0) { - if (auto_claim(transfer, ¤t_interface, USB_API_HID) != LIBUSB_SUCCESS) - return LIBUSB_ERROR_NOT_FOUND; - } - - usbi_dbg("will use interface %d", current_interface); - hid_handle = handle_priv->interface_handle[current_interface].api_handle; - // Always use the handle returned from usbi_create_fd (wfd.handle) - wfd = usbi_create_fd(hid_handle, RW_READ, NULL, NULL); - if (wfd.fd < 0) - return LIBUSB_ERROR_NOT_FOUND; - - switch(LIBUSB_REQ_TYPE(setup->request_type)) { - case LIBUSB_REQUEST_TYPE_STANDARD: - switch(setup->request) { - case LIBUSB_REQUEST_GET_DESCRIPTOR: - r = _hid_get_descriptor(priv->hid, wfd.handle, LIBUSB_REQ_RECIPIENT(setup->request_type), - (setup->value >> 8) & 0xFF, setup->value & 0xFF, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, &size); - break; - case LIBUSB_REQUEST_GET_CONFIGURATION: - r = windows_get_configuration(transfer->dev_handle, &config); - if (r == LIBUSB_SUCCESS) { - size = 1; - ((uint8_t *)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = (uint8_t)config; - r = LIBUSB_COMPLETED; - } - break; - case LIBUSB_REQUEST_SET_CONFIGURATION: - if (setup->value == priv->active_config) { - r = LIBUSB_COMPLETED; - } else { - usbi_warn(ctx, "cannot set configuration other than the default one"); - r = LIBUSB_ERROR_NOT_SUPPORTED; - } - break; - case LIBUSB_REQUEST_GET_INTERFACE: - size = 1; - ((uint8_t *)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = 0; - r = LIBUSB_COMPLETED; - break; - case LIBUSB_REQUEST_SET_INTERFACE: - r = hid_set_interface_altsetting(0, transfer->dev_handle, setup->index, setup->value); - if (r == LIBUSB_SUCCESS) - r = LIBUSB_COMPLETED; - break; - default: - usbi_warn(ctx, "unsupported HID control request"); - r = LIBUSB_ERROR_NOT_SUPPORTED; - break; - } - break; - case LIBUSB_REQUEST_TYPE_CLASS: - r = _hid_class_request(priv->hid, wfd.handle, setup->request_type, setup->request, setup->value, - setup->index, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, transfer_priv, - &size, wfd.overlapped); - break; - default: - usbi_warn(ctx, "unsupported HID control request"); - r = LIBUSB_ERROR_NOT_SUPPORTED; - break; - } - - if (r == LIBUSB_COMPLETED) { - // Force request to be completed synchronously. Transferred size has been set by previous call - wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY; - // http://msdn.microsoft.com/en-us/library/ms684342%28VS.85%29.aspx - // set InternalHigh to the number of bytes transferred - wfd.overlapped->InternalHigh = (DWORD)size; - r = LIBUSB_SUCCESS; - } - - if (r == LIBUSB_SUCCESS) { - // Use priv_transfer to store data needed for async polling - transfer_priv->pollable_fd = wfd; - transfer_priv->interface_number = (uint8_t)current_interface; - } else { - usbi_free_fd(&wfd); - } - - return r; -} - -static int hid_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer); - struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev); - struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle); - struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev); - struct winfd wfd; - HANDLE hid_handle; - bool direction_in, ret; - int current_interface, length; - DWORD size; - int r = LIBUSB_SUCCESS; - - CHECK_HID_AVAILABLE; - - transfer_priv->pollable_fd = INVALID_WINFD; - transfer_priv->hid_dest = NULL; - safe_free(transfer_priv->hid_buffer); - - current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint); - if (current_interface < 0) { - usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer"); - return LIBUSB_ERROR_NOT_FOUND; - } - - usbi_dbg("matched endpoint %02X with interface %d", transfer->endpoint, current_interface); - - hid_handle = handle_priv->interface_handle[current_interface].api_handle; - direction_in = transfer->endpoint & LIBUSB_ENDPOINT_IN; - - wfd = usbi_create_fd(hid_handle, direction_in?RW_READ:RW_WRITE, NULL, NULL); - // Always use the handle returned from usbi_create_fd (wfd.handle) - if (wfd.fd < 0) - return LIBUSB_ERROR_NO_MEM; - - // If report IDs are not in use, an extra prefix byte must be added - if (((direction_in) && (!priv->hid->uses_report_ids[0])) - || ((!direction_in) && (!priv->hid->uses_report_ids[1]))) - length = transfer->length + 1; - else - length = transfer->length; - - // Add a trailing byte to detect overflows on input - transfer_priv->hid_buffer = calloc(1, length + 1); - if (transfer_priv->hid_buffer == NULL) - return LIBUSB_ERROR_NO_MEM; - - transfer_priv->hid_expected_size = length; - - if (direction_in) { - transfer_priv->hid_dest = transfer->buffer; - usbi_dbg("reading %d bytes (report ID: 0x00)", length); - ret = ReadFile(wfd.handle, transfer_priv->hid_buffer, length + 1, &size, wfd.overlapped); - } else { - if (!priv->hid->uses_report_ids[1]) - memcpy(transfer_priv->hid_buffer + 1, transfer->buffer, transfer->length); - else - // We could actually do without the calloc and memcpy in this case - memcpy(transfer_priv->hid_buffer, transfer->buffer, transfer->length); - - usbi_dbg("writing %d bytes (report ID: 0x%02X)", length, transfer_priv->hid_buffer[0]); - ret = WriteFile(wfd.handle, transfer_priv->hid_buffer, length, &size, wfd.overlapped); - } - - if (!ret) { - if (GetLastError() != ERROR_IO_PENDING) { - usbi_err(ctx, "HID transfer failed: %s", windows_error_str(0)); - usbi_free_fd(&wfd); - safe_free(transfer_priv->hid_buffer); - return LIBUSB_ERROR_IO; - } - } else { - // Only write operations that completed synchronously need to free up - // hid_buffer. For reads, copy_transfer_data() handles that process. - if (!direction_in) - safe_free(transfer_priv->hid_buffer); - - if (size == 0) { - usbi_err(ctx, "program assertion failed - no data was transferred"); - size = 1; - } - if (size > (size_t)length) { - usbi_err(ctx, "OVERFLOW!"); - r = LIBUSB_ERROR_OVERFLOW; - } - wfd.overlapped->Internal = STATUS_COMPLETED_SYNCHRONOUSLY; - wfd.overlapped->InternalHigh = size; - } - - transfer_priv->pollable_fd = wfd; - transfer_priv->interface_number = (uint8_t)current_interface; - - return r; -} - -static int hid_abort_transfers(int sub_api, struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer); - struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle); - HANDLE hid_handle; - int current_interface; - - CHECK_HID_AVAILABLE; - - current_interface = transfer_priv->interface_number; - hid_handle = handle_priv->interface_handle[current_interface].api_handle; - CancelIo(hid_handle); - - return LIBUSB_SUCCESS; -} - -static int hid_reset_device(int sub_api, struct libusb_device_handle *dev_handle) -{ - struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle); - HANDLE hid_handle; - int current_interface; - - CHECK_HID_AVAILABLE; - - // Flushing the queues on all interfaces is the best we can achieve - for (current_interface = 0; current_interface < USB_MAXINTERFACES; current_interface++) { - hid_handle = handle_priv->interface_handle[current_interface].api_handle; - if (HANDLE_VALID(hid_handle)) - HidD_FlushQueue(hid_handle); - } - - return LIBUSB_SUCCESS; -} - -static int hid_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint) -{ - struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev); - struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle); - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - HANDLE hid_handle; - int current_interface; - - CHECK_HID_AVAILABLE; - - current_interface = interface_by_endpoint(priv, handle_priv, endpoint); - if (current_interface < 0) { - usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear"); - return LIBUSB_ERROR_NOT_FOUND; - } - - usbi_dbg("matched endpoint %02X with interface %d", endpoint, current_interface); - hid_handle = handle_priv->interface_handle[current_interface].api_handle; - - // No endpoint selection with Microsoft's implementation, so we try to flush the - // whole interface. Should be OK for most case scenarios - if (!HidD_FlushQueue(hid_handle)) { - usbi_err(ctx, "Flushing of HID queue failed: %s", windows_error_str(0)); - // Device was probably disconnected - return LIBUSB_ERROR_NO_DEVICE; - } - - return LIBUSB_SUCCESS; -} - -// This extra function is only needed for HID -static int hid_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev); - struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer); - int r = LIBUSB_TRANSFER_COMPLETED; - uint32_t corrected_size = io_size; - - if (transfer_priv->hid_buffer != NULL) { - // If we have a valid hid_buffer, it means the transfer was async - if (transfer_priv->hid_dest != NULL) { // Data readout - if (corrected_size > 0) { - // First, check for overflow - if (corrected_size > transfer_priv->hid_expected_size) { - usbi_err(ctx, "OVERFLOW!"); - corrected_size = (uint32_t)transfer_priv->hid_expected_size; - r = LIBUSB_TRANSFER_OVERFLOW; - } - - if (transfer_priv->hid_buffer[0] == 0) { - // Discard the 1 byte report ID prefix - corrected_size--; - memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer + 1, corrected_size); - } else { - memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer, corrected_size); - } - } - transfer_priv->hid_dest = NULL; - } - // For write, we just need to free the hid buffer - safe_free(transfer_priv->hid_buffer); - } - - itransfer->transferred += corrected_size; - return r; -} - - -/* - * Composite API functions - */ -static int composite_init(int sub_api, struct libusb_context *ctx) -{ - return LIBUSB_SUCCESS; -} - -static int composite_exit(int sub_api) -{ - return LIBUSB_SUCCESS; -} - -static int composite_open(int sub_api, struct libusb_device_handle *dev_handle) -{ - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - int r = LIBUSB_ERROR_NOT_FOUND; - uint8_t i; - // SUB_API_MAX + 1 as the SUB_API_MAX pos is used to indicate availability of HID - bool available[SUB_API_MAX + 1] = { 0 }; - - for (i = 0; i < USB_MAXINTERFACES; i++) { - switch (priv->usb_interface[i].apib->id) { - case USB_API_WINUSBX: - if (priv->usb_interface[i].sub_api != SUB_API_NOTSET) - available[priv->usb_interface[i].sub_api] = true; - break; - case USB_API_HID: - available[SUB_API_MAX] = true; - break; - default: - break; - } - } - - for (i = 0; i < SUB_API_MAX; i++) { // WinUSB-like drivers - if (available[i]) { - r = usb_api_backend[USB_API_WINUSBX].open(i, dev_handle); - if (r != LIBUSB_SUCCESS) - return r; - } - } - - if (available[SUB_API_MAX]) // HID driver - r = hid_open(SUB_API_NOTSET, dev_handle); - - return r; -} - -static void composite_close(int sub_api, struct libusb_device_handle *dev_handle) -{ - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - uint8_t i; - // SUB_API_MAX + 1 as the SUB_API_MAX pos is used to indicate availability of HID - bool available[SUB_API_MAX + 1] = { 0 }; - - for (i = 0; i < USB_MAXINTERFACES; i++) { - switch (priv->usb_interface[i].apib->id) { - case USB_API_WINUSBX: - if (priv->usb_interface[i].sub_api != SUB_API_NOTSET) - available[priv->usb_interface[i].sub_api] = true; - break; - case USB_API_HID: - available[SUB_API_MAX] = true; - break; - default: - break; - } - } - - for (i = 0; i < SUB_API_MAX; i++) { // WinUSB-like drivers - if (available[i]) - usb_api_backend[USB_API_WINUSBX].close(i, dev_handle); - } - - if (available[SUB_API_MAX]) // HID driver - hid_close(SUB_API_NOTSET, dev_handle); -} - -static int composite_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface) -{ - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - - return priv->usb_interface[iface].apib-> - claim_interface(priv->usb_interface[iface].sub_api, dev_handle, iface); -} - -static int composite_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting) -{ - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - - return priv->usb_interface[iface].apib-> - set_interface_altsetting(priv->usb_interface[iface].sub_api, dev_handle, iface, altsetting); -} - -static int composite_release_interface(int sub_api, struct libusb_device_handle *dev_handle, int iface) -{ - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - - return priv->usb_interface[iface].apib-> - release_interface(priv->usb_interface[iface].sub_api, dev_handle, iface); -} - -static int composite_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev); - struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev); - struct libusb_config_descriptor *conf_desc; - WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *)transfer->buffer; - int iface, pass, r; - - // Interface shouldn't matter for control, but it does in practice, with Windows' - // restrictions with regards to accessing HID keyboards and mice. Try to target - // a specific interface first, if possible. - switch (LIBUSB_REQ_RECIPIENT(setup->request_type)) { - case LIBUSB_RECIPIENT_INTERFACE: - iface = setup->index & 0xFF; - break; - case LIBUSB_RECIPIENT_ENDPOINT: - r = libusb_get_active_config_descriptor(transfer->dev_handle->dev, &conf_desc); - if (r == LIBUSB_SUCCESS) { - iface = get_interface_by_endpoint(conf_desc, (setup->index & 0xFF)); - libusb_free_config_descriptor(conf_desc); - break; - } - // Fall through if not able to determine interface - default: - iface = -1; - break; - } - - // Try and target a specific interface if the control setup indicates such - if ((iface >= 0) && (iface < USB_MAXINTERFACES)) { - usbi_dbg("attempting control transfer targeted to interface %d", iface); - if (priv->usb_interface[iface].path != NULL) { - r = priv->usb_interface[iface].apib->submit_control_transfer(priv->usb_interface[iface].sub_api, itransfer); - if (r == LIBUSB_SUCCESS) - return r; - } - } - - // Either not targeted to a specific interface or no luck in doing so. - // Try a 2 pass approach with all interfaces. - for (pass = 0; pass < 2; pass++) { - for (iface = 0; iface < USB_MAXINTERFACES; iface++) { - if (priv->usb_interface[iface].path != NULL) { - if ((pass == 0) && (priv->usb_interface[iface].restricted_functionality)) { - usbi_dbg("trying to skip restricted interface #%d (HID keyboard or mouse?)", iface); - continue; - } - usbi_dbg("using interface %d", iface); - r = priv->usb_interface[iface].apib->submit_control_transfer(priv->usb_interface[iface].sub_api, itransfer); - // If not supported on this API, it may be supported on another, so don't give up yet!! - if (r == LIBUSB_ERROR_NOT_SUPPORTED) - continue; - return r; - } - } - } - - usbi_err(ctx, "no libusb supported interfaces to complete request"); - return LIBUSB_ERROR_NOT_FOUND; -} - -static int composite_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer) { - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev); - struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle); - struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev); - int current_interface; - - current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint); - if (current_interface < 0) { - usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer"); - return LIBUSB_ERROR_NOT_FOUND; - } - - return priv->usb_interface[current_interface].apib-> - submit_bulk_transfer(priv->usb_interface[current_interface].sub_api, itransfer); -} - -static int composite_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer) { - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct libusb_context *ctx = DEVICE_CTX(transfer->dev_handle->dev); - struct windows_device_handle_priv *handle_priv = _device_handle_priv(transfer->dev_handle); - struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev); - int current_interface; - - current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint); - if (current_interface < 0) { - usbi_err(ctx, "unable to match endpoint to an open interface - cancelling transfer"); - return LIBUSB_ERROR_NOT_FOUND; - } - - return priv->usb_interface[current_interface].apib-> - submit_iso_transfer(priv->usb_interface[current_interface].sub_api, itransfer); -} - -static int composite_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint) -{ - struct libusb_context *ctx = DEVICE_CTX(dev_handle->dev); - struct windows_device_handle_priv *handle_priv = _device_handle_priv(dev_handle); - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - int current_interface; - - current_interface = interface_by_endpoint(priv, handle_priv, endpoint); - if (current_interface < 0) { - usbi_err(ctx, "unable to match endpoint to an open interface - cannot clear"); - return LIBUSB_ERROR_NOT_FOUND; - } - - return priv->usb_interface[current_interface].apib-> - clear_halt(priv->usb_interface[current_interface].sub_api, dev_handle, endpoint); -} - -static int composite_abort_control(int sub_api, struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer); - struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev); - - return priv->usb_interface[transfer_priv->interface_number].apib-> - abort_control(priv->usb_interface[transfer_priv->interface_number].sub_api, itransfer); -} - -static int composite_abort_transfers(int sub_api, struct usbi_transfer *itransfer) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer); - struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev); - - return priv->usb_interface[transfer_priv->interface_number].apib-> - abort_transfers(priv->usb_interface[transfer_priv->interface_number].sub_api, itransfer); -} - -static int composite_reset_device(int sub_api, struct libusb_device_handle *dev_handle) -{ - struct windows_device_priv *priv = _device_priv(dev_handle->dev); - int r; - uint8_t i; - bool available[SUB_API_MAX]; - - for (i = 0; i < SUB_API_MAX; i++) - available[i] = false; - - for (i = 0; i < USB_MAXINTERFACES; i++) { - if ((priv->usb_interface[i].apib->id == USB_API_WINUSBX) - && (priv->usb_interface[i].sub_api != SUB_API_NOTSET)) - available[priv->usb_interface[i].sub_api] = true; - } - - for (i = 0; i < SUB_API_MAX; i++) { - if (available[i]) { - r = usb_api_backend[USB_API_WINUSBX].reset_device(i, dev_handle); - if (r != LIBUSB_SUCCESS) - return r; - } - } - - return LIBUSB_SUCCESS; -} - -static int composite_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size) -{ - struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer); - struct windows_transfer_priv *transfer_priv = usbi_transfer_get_os_priv(itransfer); - struct windows_device_priv *priv = _device_priv(transfer->dev_handle->dev); - - return priv->usb_interface[transfer_priv->interface_number].apib-> - copy_transfer_data(priv->usb_interface[transfer_priv->interface_number].sub_api, itransfer, io_size); -} - -#endif /* !USE_USBDK */ diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/os/windows_winusb.h b/vendor/github.com/karalabe/hid/libusb/libusb/os/windows_winusb.h deleted file mode 100644 index b7b9cd91..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/os/windows_winusb.h +++ /dev/null @@ -1,937 +0,0 @@ -/* - * Windows backend for libusb 1.0 - * Copyright © 2009-2012 Pete Batard - * With contributions from Michael Plante, Orin Eman et al. - * Parts of this code adapted from libusb-win32-v1 by Stephan Meyer - * Major code testing contribution by Xiaofan Chen - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#pragma once - -#include "windows_common.h" -#include "windows_nt_common.h" - -#if defined(_MSC_VER) -// disable /W4 MSVC warnings that are benign -#pragma warning(disable:4100) // unreferenced formal parameter -#pragma warning(disable:4127) // conditional expression is constant -#pragma warning(disable:4201) // nameless struct/union -#pragma warning(disable:4214) // bit field types other than int -#pragma warning(disable:4996) // deprecated API calls -#pragma warning(disable:28159) // more deprecated API calls -#endif - -// Missing from MSVC6 setupapi.h -#if !defined(SPDRP_ADDRESS) -#define SPDRP_ADDRESS 28 -#endif -#if !defined(SPDRP_INSTALL_STATE) -#define SPDRP_INSTALL_STATE 34 -#endif - -#define MAX_CTRL_BUFFER_LENGTH 4096 -#define MAX_USB_DEVICES 256 -#define MAX_USB_STRING_LENGTH 128 -#define MAX_HID_REPORT_SIZE 1024 -#define MAX_HID_DESCRIPTOR_SIZE 256 -#define MAX_GUID_STRING_LENGTH 40 -#define MAX_PATH_LENGTH 128 -#define MAX_KEY_LENGTH 256 -#define LIST_SEPARATOR ';' - -// Handle code for HID interface that have been claimed ("dibs") -#define INTERFACE_CLAIMED ((HANDLE)(intptr_t)0xD1B5) -// Additional return code for HID operations that completed synchronously -#define LIBUSB_COMPLETED (LIBUSB_SUCCESS + 1) - -// http://msdn.microsoft.com/en-us/library/ff545978.aspx -// http://msdn.microsoft.com/en-us/library/ff545972.aspx -// http://msdn.microsoft.com/en-us/library/ff545982.aspx -#if !defined(GUID_DEVINTERFACE_USB_HOST_CONTROLLER) -const GUID GUID_DEVINTERFACE_USB_HOST_CONTROLLER = { 0x3ABF6F2D, 0x71C4, 0x462A, {0x8A, 0x92, 0x1E, 0x68, 0x61, 0xE6, 0xAF, 0x27} }; -#endif -#if !defined(GUID_DEVINTERFACE_USB_DEVICE) -const GUID GUID_DEVINTERFACE_USB_DEVICE = { 0xA5DCBF10, 0x6530, 0x11D2, {0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED} }; -#endif -#if !defined(GUID_DEVINTERFACE_USB_HUB) -const GUID GUID_DEVINTERFACE_USB_HUB = { 0xF18A0E88, 0xC30C, 0x11D0, {0x88, 0x15, 0x00, 0xA0, 0xC9, 0x06, 0xBE, 0xD8} }; -#endif -#if !defined(GUID_DEVINTERFACE_LIBUSB0_FILTER) -const GUID GUID_DEVINTERFACE_LIBUSB0_FILTER = { 0xF9F3FF14, 0xAE21, 0x48A0, {0x8A, 0x25, 0x80, 0x11, 0xA7, 0xA9, 0x31, 0xD9} }; -#endif - - -/* - * Multiple USB API backend support - */ -#define USB_API_UNSUPPORTED 0 -#define USB_API_HUB 1 -#define USB_API_COMPOSITE 2 -#define USB_API_WINUSBX 3 -#define USB_API_HID 4 -#define USB_API_MAX 5 -// The following is used to indicate if the HID or composite extra props have already been set. -#define USB_API_SET (1 << USB_API_MAX) - -// Sub-APIs for WinUSB-like driver APIs (WinUSB, libusbK, libusb-win32 through the libusbK DLL) -// Must have the same values as the KUSB_DRVID enum from libusbk.h -#define SUB_API_NOTSET -1 -#define SUB_API_LIBUSBK 0 -#define SUB_API_LIBUSB0 1 -#define SUB_API_WINUSB 2 -#define SUB_API_MAX 3 - -#define WINUSBX_DRV_NAMES {"libusbK", "libusb0", "WinUSB"} - -struct windows_usb_api_backend { - const uint8_t id; - const char *designation; - const char **driver_name_list; // Driver name, without .sys, e.g. "usbccgp" - const uint8_t nb_driver_names; - int (*init)(int sub_api, struct libusb_context *ctx); - int (*exit)(int sub_api); - int (*open)(int sub_api, struct libusb_device_handle *dev_handle); - void (*close)(int sub_api, struct libusb_device_handle *dev_handle); - int (*configure_endpoints)(int sub_api, struct libusb_device_handle *dev_handle, int iface); - int (*claim_interface)(int sub_api, struct libusb_device_handle *dev_handle, int iface); - int (*set_interface_altsetting)(int sub_api, struct libusb_device_handle *dev_handle, int iface, int altsetting); - int (*release_interface)(int sub_api, struct libusb_device_handle *dev_handle, int iface); - int (*clear_halt)(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint); - int (*reset_device)(int sub_api, struct libusb_device_handle *dev_handle); - int (*submit_bulk_transfer)(int sub_api, struct usbi_transfer *itransfer); - int (*submit_iso_transfer)(int sub_api, struct usbi_transfer *itransfer); - int (*submit_control_transfer)(int sub_api, struct usbi_transfer *itransfer); - int (*abort_control)(int sub_api, struct usbi_transfer *itransfer); - int (*abort_transfers)(int sub_api, struct usbi_transfer *itransfer); - int (*copy_transfer_data)(int sub_api, struct usbi_transfer *itransfer, uint32_t io_size); -}; - -extern const struct windows_usb_api_backend usb_api_backend[USB_API_MAX]; - -#define PRINT_UNSUPPORTED_API(fname) \ - usbi_dbg("unsupported API call for '" \ - #fname "' (unrecognized device driver)"); \ - return LIBUSB_ERROR_NOT_SUPPORTED; - -/* - * private structures definition - * with inline pseudo constructors/destructors - */ - -// TODO (v2+): move hid desc to libusb.h? -struct libusb_hid_descriptor { - uint8_t bLength; - uint8_t bDescriptorType; - uint16_t bcdHID; - uint8_t bCountryCode; - uint8_t bNumDescriptors; - uint8_t bClassDescriptorType; - uint16_t wClassDescriptorLength; -}; - -#define LIBUSB_DT_HID_SIZE 9 -#define HID_MAX_CONFIG_DESC_SIZE (LIBUSB_DT_CONFIG_SIZE + LIBUSB_DT_INTERFACE_SIZE \ - + LIBUSB_DT_HID_SIZE + 2 * LIBUSB_DT_ENDPOINT_SIZE) -#define HID_MAX_REPORT_SIZE 1024 -#define HID_IN_EP 0x81 -#define HID_OUT_EP 0x02 -#define LIBUSB_REQ_RECIPIENT(request_type) ((request_type) & 0x1F) -#define LIBUSB_REQ_TYPE(request_type) ((request_type) & (0x03 << 5)) -#define LIBUSB_REQ_IN(request_type) ((request_type) & LIBUSB_ENDPOINT_IN) -#define LIBUSB_REQ_OUT(request_type) (!LIBUSB_REQ_IN(request_type)) - -// The following are used for HID reports IOCTLs -#define HID_CTL_CODE(id) \ - CTL_CODE (FILE_DEVICE_KEYBOARD, (id), METHOD_NEITHER, FILE_ANY_ACCESS) -#define HID_BUFFER_CTL_CODE(id) \ - CTL_CODE (FILE_DEVICE_KEYBOARD, (id), METHOD_BUFFERED, FILE_ANY_ACCESS) -#define HID_IN_CTL_CODE(id) \ - CTL_CODE (FILE_DEVICE_KEYBOARD, (id), METHOD_IN_DIRECT, FILE_ANY_ACCESS) -#define HID_OUT_CTL_CODE(id) \ - CTL_CODE (FILE_DEVICE_KEYBOARD, (id), METHOD_OUT_DIRECT, FILE_ANY_ACCESS) - -#define IOCTL_HID_GET_FEATURE HID_OUT_CTL_CODE(100) -#define IOCTL_HID_GET_INPUT_REPORT HID_OUT_CTL_CODE(104) -#define IOCTL_HID_SET_FEATURE HID_IN_CTL_CODE(100) -#define IOCTL_HID_SET_OUTPUT_REPORT HID_IN_CTL_CODE(101) - -enum libusb_hid_request_type { - HID_REQ_GET_REPORT = 0x01, - HID_REQ_GET_IDLE = 0x02, - HID_REQ_GET_PROTOCOL = 0x03, - HID_REQ_SET_REPORT = 0x09, - HID_REQ_SET_IDLE = 0x0A, - HID_REQ_SET_PROTOCOL = 0x0B -}; - -enum libusb_hid_report_type { - HID_REPORT_TYPE_INPUT = 0x01, - HID_REPORT_TYPE_OUTPUT = 0x02, - HID_REPORT_TYPE_FEATURE = 0x03 -}; - -struct hid_device_priv { - uint16_t vid; - uint16_t pid; - uint8_t config; - uint8_t nb_interfaces; - bool uses_report_ids[3]; // input, ouptput, feature - uint16_t input_report_size; - uint16_t output_report_size; - uint16_t feature_report_size; - WCHAR string[3][MAX_USB_STRING_LENGTH]; - uint8_t string_index[3]; // man, prod, ser -}; - -struct windows_device_priv { - uint8_t depth; // distance to HCD - uint8_t port; // port number on the hub - uint8_t active_config; - struct windows_usb_api_backend const *apib; - char *path; // device interface path - int sub_api; // for WinUSB-like APIs - struct { - char *path; // each interface needs a device interface path, - struct windows_usb_api_backend const *apib; // an API backend (multiple drivers support), - int sub_api; - int8_t nb_endpoints; // and a set of endpoint addresses (USB_MAXENDPOINTS) - uint8_t *endpoint; - bool restricted_functionality; // indicates if the interface functionality is restricted - // by Windows (eg. HID keyboards or mice cannot do R/W) - } usb_interface[USB_MAXINTERFACES]; - struct hid_device_priv *hid; - USB_DEVICE_DESCRIPTOR dev_descriptor; - unsigned char **config_descriptor; // list of pointers to the cached config descriptors -}; - -static inline struct windows_device_priv *_device_priv(struct libusb_device *dev) -{ - return (struct windows_device_priv *)dev->os_priv; -} - -static inline struct windows_device_priv *windows_device_priv_init(struct libusb_device *dev) -{ - struct windows_device_priv *p = _device_priv(dev); - int i; - - p->apib = &usb_api_backend[USB_API_UNSUPPORTED]; - p->sub_api = SUB_API_NOTSET; - for (i = 0; i < USB_MAXINTERFACES; i++) { - p->usb_interface[i].apib = &usb_api_backend[USB_API_UNSUPPORTED]; - p->usb_interface[i].sub_api = SUB_API_NOTSET; - } - - return p; -} - -static inline void windows_device_priv_release(struct libusb_device *dev) -{ - struct windows_device_priv *p = _device_priv(dev); - int i; - - free(p->path); - if ((dev->num_configurations > 0) && (p->config_descriptor != NULL)) { - for (i = 0; i < dev->num_configurations; i++) - free(p->config_descriptor[i]); - } - free(p->config_descriptor); - free(p->hid); - for (i = 0; i < USB_MAXINTERFACES; i++) { - free(p->usb_interface[i].path); - free(p->usb_interface[i].endpoint); - } -} - -struct interface_handle_t { - HANDLE dev_handle; // WinUSB needs an extra handle for the file - HANDLE api_handle; // used by the API to communicate with the device -}; - -struct windows_device_handle_priv { - int active_interface; - struct interface_handle_t interface_handle[USB_MAXINTERFACES]; - int autoclaim_count[USB_MAXINTERFACES]; // For auto-release -}; - -static inline struct windows_device_handle_priv *_device_handle_priv( - struct libusb_device_handle *handle) -{ - return (struct windows_device_handle_priv *)handle->os_priv; -} - -// used for async polling functions -struct windows_transfer_priv { - struct winfd pollable_fd; - uint8_t interface_number; - uint8_t *hid_buffer; // 1 byte extended data buffer, required for HID - uint8_t *hid_dest; // transfer buffer destination, required for HID - size_t hid_expected_size; -}; - -// used to match a device driver (including filter drivers) against a supported API -struct driver_lookup { - char list[MAX_KEY_LENGTH + 1]; // REG_MULTI_SZ list of services (driver) names - const DWORD reg_prop; // SPDRP registry key to use to retrieve list - const char* designation; // internal designation (for debug output) -}; - -/* OLE32 dependency */ -DLL_DECLARE_HANDLE(OLE32); -DLL_DECLARE_FUNC_PREFIXED(WINAPI, HRESULT, p, CLSIDFromString, (LPCOLESTR, LPCLSID)); - -/* Kernel32 dependencies */ -DLL_DECLARE_HANDLE(Kernel32); -/* This call is only available from XP SP2 */ -DLL_DECLARE_FUNC_PREFIXED(WINAPI, BOOL, p, IsWow64Process, (HANDLE, PBOOL)); - -/* SetupAPI dependencies */ -DLL_DECLARE_HANDLE(SetupAPI); -DLL_DECLARE_FUNC_PREFIXED(WINAPI, HDEVINFO, p, SetupDiGetClassDevsA, (const GUID*, PCSTR, HWND, DWORD)); -DLL_DECLARE_FUNC_PREFIXED(WINAPI, BOOL, p, SetupDiEnumDeviceInfo, (HDEVINFO, DWORD, PSP_DEVINFO_DATA)); -DLL_DECLARE_FUNC_PREFIXED(WINAPI, BOOL, p, SetupDiEnumDeviceInterfaces, (HDEVINFO, PSP_DEVINFO_DATA, - const GUID*, DWORD, PSP_DEVICE_INTERFACE_DATA)); -DLL_DECLARE_FUNC_PREFIXED(WINAPI, BOOL, p, SetupDiGetDeviceInterfaceDetailA, (HDEVINFO, PSP_DEVICE_INTERFACE_DATA, - PSP_DEVICE_INTERFACE_DETAIL_DATA_A, DWORD, PDWORD, PSP_DEVINFO_DATA)); -DLL_DECLARE_FUNC_PREFIXED(WINAPI, BOOL, p, SetupDiDestroyDeviceInfoList, (HDEVINFO)); -DLL_DECLARE_FUNC_PREFIXED(WINAPI, HKEY, p, SetupDiOpenDevRegKey, (HDEVINFO, PSP_DEVINFO_DATA, DWORD, DWORD, DWORD, REGSAM)); -DLL_DECLARE_FUNC_PREFIXED(WINAPI, BOOL, p, SetupDiGetDeviceRegistryPropertyA, (HDEVINFO, - PSP_DEVINFO_DATA, DWORD, PDWORD, PBYTE, DWORD, PDWORD)); -DLL_DECLARE_FUNC_PREFIXED(WINAPI, HKEY, p, SetupDiOpenDeviceInterfaceRegKey, (HDEVINFO, PSP_DEVICE_INTERFACE_DATA, DWORD, DWORD)); - -/* AdvAPI32 dependencies */ -DLL_DECLARE_HANDLE(AdvAPI32); -DLL_DECLARE_FUNC_PREFIXED(WINAPI, LONG, p, RegQueryValueExW, (HKEY, LPCWSTR, LPDWORD, LPDWORD, LPBYTE, LPDWORD)); -DLL_DECLARE_FUNC_PREFIXED(WINAPI, LONG, p, RegCloseKey, (HKEY)); - -/* - * Windows DDK API definitions. Most of it copied from MinGW's includes - */ -typedef DWORD DEVNODE, DEVINST; -typedef DEVNODE *PDEVNODE, *PDEVINST; -typedef DWORD RETURN_TYPE; -typedef RETURN_TYPE CONFIGRET; - -#define CR_SUCCESS 0x00000000 -#define CR_NO_SUCH_DEVNODE 0x0000000D - -#define USB_DEVICE_DESCRIPTOR_TYPE LIBUSB_DT_DEVICE -#define USB_CONFIGURATION_DESCRIPTOR_TYPE LIBUSB_DT_CONFIG -#define USB_STRING_DESCRIPTOR_TYPE LIBUSB_DT_STRING -#define USB_INTERFACE_DESCRIPTOR_TYPE LIBUSB_DT_INTERFACE -#define USB_ENDPOINT_DESCRIPTOR_TYPE LIBUSB_DT_ENDPOINT - -#define USB_REQUEST_GET_STATUS LIBUSB_REQUEST_GET_STATUS -#define USB_REQUEST_CLEAR_FEATURE LIBUSB_REQUEST_CLEAR_FEATURE -#define USB_REQUEST_SET_FEATURE LIBUSB_REQUEST_SET_FEATURE -#define USB_REQUEST_SET_ADDRESS LIBUSB_REQUEST_SET_ADDRESS -#define USB_REQUEST_GET_DESCRIPTOR LIBUSB_REQUEST_GET_DESCRIPTOR -#define USB_REQUEST_SET_DESCRIPTOR LIBUSB_REQUEST_SET_DESCRIPTOR -#define USB_REQUEST_GET_CONFIGURATION LIBUSB_REQUEST_GET_CONFIGURATION -#define USB_REQUEST_SET_CONFIGURATION LIBUSB_REQUEST_SET_CONFIGURATION -#define USB_REQUEST_GET_INTERFACE LIBUSB_REQUEST_GET_INTERFACE -#define USB_REQUEST_SET_INTERFACE LIBUSB_REQUEST_SET_INTERFACE -#define USB_REQUEST_SYNC_FRAME LIBUSB_REQUEST_SYNCH_FRAME - -#define USB_GET_NODE_INFORMATION 258 -#define USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION 260 -#define USB_GET_NODE_CONNECTION_NAME 261 -#define USB_GET_HUB_CAPABILITIES 271 -#if !defined(USB_GET_NODE_CONNECTION_INFORMATION_EX) -#define USB_GET_NODE_CONNECTION_INFORMATION_EX 274 -#endif -#if !defined(USB_GET_HUB_CAPABILITIES_EX) -#define USB_GET_HUB_CAPABILITIES_EX 276 -#endif -#if !defined(USB_GET_NODE_CONNECTION_INFORMATION_EX_V2) -#define USB_GET_NODE_CONNECTION_INFORMATION_EX_V2 279 -#endif - -#ifndef METHOD_BUFFERED -#define METHOD_BUFFERED 0 -#endif -#ifndef FILE_ANY_ACCESS -#define FILE_ANY_ACCESS 0x00000000 -#endif -#ifndef FILE_DEVICE_UNKNOWN -#define FILE_DEVICE_UNKNOWN 0x00000022 -#endif -#ifndef FILE_DEVICE_USB -#define FILE_DEVICE_USB FILE_DEVICE_UNKNOWN -#endif - -#ifndef CTL_CODE -#define CTL_CODE(DeviceType, Function, Method, Access) \ - (((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method)) -#endif - -typedef enum USB_CONNECTION_STATUS { - NoDeviceConnected, - DeviceConnected, - DeviceFailedEnumeration, - DeviceGeneralFailure, - DeviceCausedOvercurrent, - DeviceNotEnoughPower, - DeviceNotEnoughBandwidth, - DeviceHubNestedTooDeeply, - DeviceInLegacyHub -} USB_CONNECTION_STATUS, *PUSB_CONNECTION_STATUS; - -typedef enum USB_HUB_NODE { - UsbHub, - UsbMIParent -} USB_HUB_NODE; - -/* Cfgmgr32.dll interface */ -DLL_DECLARE_HANDLE(Cfgmgr32); -DLL_DECLARE_FUNC(WINAPI, CONFIGRET, CM_Get_Parent, (PDEVINST, DEVINST, ULONG)); -DLL_DECLARE_FUNC(WINAPI, CONFIGRET, CM_Get_Child, (PDEVINST, DEVINST, ULONG)); -DLL_DECLARE_FUNC(WINAPI, CONFIGRET, CM_Get_Sibling, (PDEVINST, DEVINST, ULONG)); -DLL_DECLARE_FUNC(WINAPI, CONFIGRET, CM_Get_Device_IDA, (DEVINST, PCHAR, ULONG, ULONG)); - -#define IOCTL_USB_GET_HUB_CAPABILITIES_EX \ - CTL_CODE( FILE_DEVICE_USB, USB_GET_HUB_CAPABILITIES_EX, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_USB_GET_HUB_CAPABILITIES \ - CTL_CODE(FILE_DEVICE_USB, USB_GET_HUB_CAPABILITIES, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION \ - CTL_CODE(FILE_DEVICE_USB, USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_USB_GET_ROOT_HUB_NAME \ - CTL_CODE(FILE_DEVICE_USB, HCD_GET_ROOT_HUB_NAME, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_USB_GET_NODE_INFORMATION \ - CTL_CODE(FILE_DEVICE_USB, USB_GET_NODE_INFORMATION, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX \ - CTL_CODE(FILE_DEVICE_USB, USB_GET_NODE_CONNECTION_INFORMATION_EX, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX_V2 \ - CTL_CODE(FILE_DEVICE_USB, USB_GET_NODE_CONNECTION_INFORMATION_EX_V2, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_USB_GET_NODE_CONNECTION_ATTRIBUTES \ - CTL_CODE(FILE_DEVICE_USB, USB_GET_NODE_CONNECTION_ATTRIBUTES, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_USB_GET_NODE_CONNECTION_NAME \ - CTL_CODE(FILE_DEVICE_USB, USB_GET_NODE_CONNECTION_NAME, METHOD_BUFFERED, FILE_ANY_ACCESS) - -// Most of the structures below need to be packed -#pragma pack(push, 1) - -typedef struct USB_INTERFACE_DESCRIPTOR { - UCHAR bLength; - UCHAR bDescriptorType; - UCHAR bInterfaceNumber; - UCHAR bAlternateSetting; - UCHAR bNumEndpoints; - UCHAR bInterfaceClass; - UCHAR bInterfaceSubClass; - UCHAR bInterfaceProtocol; - UCHAR iInterface; -} USB_INTERFACE_DESCRIPTOR, *PUSB_INTERFACE_DESCRIPTOR; - -typedef struct USB_CONFIGURATION_DESCRIPTOR_SHORT { - struct { - ULONG ConnectionIndex; - struct { - UCHAR bmRequest; - UCHAR bRequest; - USHORT wValue; - USHORT wIndex; - USHORT wLength; - } SetupPacket; - } req; - USB_CONFIGURATION_DESCRIPTOR data; -} USB_CONFIGURATION_DESCRIPTOR_SHORT; - -typedef struct USB_ENDPOINT_DESCRIPTOR { - UCHAR bLength; - UCHAR bDescriptorType; - UCHAR bEndpointAddress; - UCHAR bmAttributes; - USHORT wMaxPacketSize; - UCHAR bInterval; -} USB_ENDPOINT_DESCRIPTOR, *PUSB_ENDPOINT_DESCRIPTOR; - -typedef struct USB_DESCRIPTOR_REQUEST { - ULONG ConnectionIndex; - struct { - UCHAR bmRequest; - UCHAR bRequest; - USHORT wValue; - USHORT wIndex; - USHORT wLength; - } SetupPacket; -// UCHAR Data[0]; -} USB_DESCRIPTOR_REQUEST, *PUSB_DESCRIPTOR_REQUEST; - -typedef struct USB_HUB_DESCRIPTOR { - UCHAR bDescriptorLength; - UCHAR bDescriptorType; - UCHAR bNumberOfPorts; - USHORT wHubCharacteristics; - UCHAR bPowerOnToPowerGood; - UCHAR bHubControlCurrent; - UCHAR bRemoveAndPowerMask[64]; -} USB_HUB_DESCRIPTOR, *PUSB_HUB_DESCRIPTOR; - -typedef struct USB_ROOT_HUB_NAME { - ULONG ActualLength; - WCHAR RootHubName[1]; -} USB_ROOT_HUB_NAME, *PUSB_ROOT_HUB_NAME; - -typedef struct USB_ROOT_HUB_NAME_FIXED { - ULONG ActualLength; - WCHAR RootHubName[MAX_PATH_LENGTH]; -} USB_ROOT_HUB_NAME_FIXED; - -typedef struct USB_NODE_CONNECTION_NAME { - ULONG ConnectionIndex; - ULONG ActualLength; - WCHAR NodeName[1]; -} USB_NODE_CONNECTION_NAME, *PUSB_NODE_CONNECTION_NAME; - -typedef struct USB_NODE_CONNECTION_NAME_FIXED { - ULONG ConnectionIndex; - ULONG ActualLength; - WCHAR NodeName[MAX_PATH_LENGTH]; -} USB_NODE_CONNECTION_NAME_FIXED; - -typedef struct USB_HUB_NAME_FIXED { - union { - USB_ROOT_HUB_NAME_FIXED root; - USB_NODE_CONNECTION_NAME_FIXED node; - } u; -} USB_HUB_NAME_FIXED; - -typedef struct USB_HUB_INFORMATION { - USB_HUB_DESCRIPTOR HubDescriptor; - BOOLEAN HubIsBusPowered; -} USB_HUB_INFORMATION, *PUSB_HUB_INFORMATION; - -typedef struct USB_MI_PARENT_INFORMATION { - ULONG NumberOfInterfaces; -} USB_MI_PARENT_INFORMATION, *PUSB_MI_PARENT_INFORMATION; - -typedef struct USB_NODE_INFORMATION { - USB_HUB_NODE NodeType; - union { - USB_HUB_INFORMATION HubInformation; - USB_MI_PARENT_INFORMATION MiParentInformation; - } u; -} USB_NODE_INFORMATION, *PUSB_NODE_INFORMATION; - -typedef struct USB_PIPE_INFO { - USB_ENDPOINT_DESCRIPTOR EndpointDescriptor; - ULONG ScheduleOffset; -} USB_PIPE_INFO, *PUSB_PIPE_INFO; - -typedef struct USB_NODE_CONNECTION_INFORMATION_EX { - ULONG ConnectionIndex; - USB_DEVICE_DESCRIPTOR DeviceDescriptor; - UCHAR CurrentConfigurationValue; - UCHAR Speed; - BOOLEAN DeviceIsHub; - USHORT DeviceAddress; - ULONG NumberOfOpenPipes; - USB_CONNECTION_STATUS ConnectionStatus; -// USB_PIPE_INFO PipeList[0]; -} USB_NODE_CONNECTION_INFORMATION_EX, *PUSB_NODE_CONNECTION_INFORMATION_EX; - -typedef union _USB_PROTOCOLS { - ULONG ul; - struct { - ULONG Usb110:1; - ULONG Usb200:1; - ULONG Usb300:1; - ULONG ReservedMBZ:29; - }; -} USB_PROTOCOLS, *PUSB_PROTOCOLS; - -typedef union _USB_NODE_CONNECTION_INFORMATION_EX_V2_FLAGS { - ULONG ul; - struct { - ULONG DeviceIsOperatingAtSuperSpeedOrHigher:1; - ULONG DeviceIsSuperSpeedCapableOrHigher:1; - ULONG ReservedMBZ:30; - }; -} USB_NODE_CONNECTION_INFORMATION_EX_V2_FLAGS, *PUSB_NODE_CONNECTION_INFORMATION_EX_V2_FLAGS; - -typedef struct _USB_NODE_CONNECTION_INFORMATION_EX_V2 { - ULONG ConnectionIndex; - ULONG Length; - USB_PROTOCOLS SupportedUsbProtocols; - USB_NODE_CONNECTION_INFORMATION_EX_V2_FLAGS Flags; -} USB_NODE_CONNECTION_INFORMATION_EX_V2, *PUSB_NODE_CONNECTION_INFORMATION_EX_V2; - -typedef struct USB_HUB_CAP_FLAGS { - ULONG HubIsHighSpeedCapable:1; - ULONG HubIsHighSpeed:1; - ULONG HubIsMultiTtCapable:1; - ULONG HubIsMultiTt:1; - ULONG HubIsRoot:1; - ULONG HubIsArmedWakeOnConnect:1; - ULONG ReservedMBZ:26; -} USB_HUB_CAP_FLAGS, *PUSB_HUB_CAP_FLAGS; - -typedef struct USB_HUB_CAPABILITIES { - ULONG HubIs2xCapable:1; -} USB_HUB_CAPABILITIES, *PUSB_HUB_CAPABILITIES; - -typedef struct USB_HUB_CAPABILITIES_EX { - USB_HUB_CAP_FLAGS CapabilityFlags; -} USB_HUB_CAPABILITIES_EX, *PUSB_HUB_CAPABILITIES_EX; - -#pragma pack(pop) - -/* winusb.dll interface */ - -#define SHORT_PACKET_TERMINATE 0x01 -#define AUTO_CLEAR_STALL 0x02 -#define PIPE_TRANSFER_TIMEOUT 0x03 -#define IGNORE_SHORT_PACKETS 0x04 -#define ALLOW_PARTIAL_READS 0x05 -#define AUTO_FLUSH 0x06 -#define RAW_IO 0x07 -#define MAXIMUM_TRANSFER_SIZE 0x08 -#define AUTO_SUSPEND 0x81 -#define SUSPEND_DELAY 0x83 -#define DEVICE_SPEED 0x01 -#define LowSpeed 0x01 -#define FullSpeed 0x02 -#define HighSpeed 0x03 - -typedef enum USBD_PIPE_TYPE { - UsbdPipeTypeControl, - UsbdPipeTypeIsochronous, - UsbdPipeTypeBulk, - UsbdPipeTypeInterrupt -} USBD_PIPE_TYPE; - -typedef struct { - USBD_PIPE_TYPE PipeType; - UCHAR PipeId; - USHORT MaximumPacketSize; - UCHAR Interval; -} WINUSB_PIPE_INFORMATION, *PWINUSB_PIPE_INFORMATION; - -#pragma pack(1) -typedef struct { - UCHAR request_type; - UCHAR request; - USHORT value; - USHORT index; - USHORT length; -} WINUSB_SETUP_PACKET, *PWINUSB_SETUP_PACKET; -#pragma pack() - -typedef void *WINUSB_INTERFACE_HANDLE, *PWINUSB_INTERFACE_HANDLE; - -typedef BOOL (WINAPI *WinUsb_AbortPipe_t)( - WINUSB_INTERFACE_HANDLE InterfaceHandle, - UCHAR PipeID -); -typedef BOOL (WINAPI *WinUsb_ControlTransfer_t)( - WINUSB_INTERFACE_HANDLE InterfaceHandle, - WINUSB_SETUP_PACKET SetupPacket, - PUCHAR Buffer, - ULONG BufferLength, - PULONG LengthTransferred, - LPOVERLAPPED Overlapped -); -typedef BOOL (WINAPI *WinUsb_FlushPipe_t)( - WINUSB_INTERFACE_HANDLE InterfaceHandle, - UCHAR PipeID -); -typedef BOOL (WINAPI *WinUsb_Free_t)( - WINUSB_INTERFACE_HANDLE InterfaceHandle -); -typedef BOOL (WINAPI *WinUsb_GetAssociatedInterface_t)( - WINUSB_INTERFACE_HANDLE InterfaceHandle, - UCHAR AssociatedInterfaceIndex, - PWINUSB_INTERFACE_HANDLE AssociatedInterfaceHandle -); -typedef BOOL (WINAPI *WinUsb_GetCurrentAlternateSetting_t)( - WINUSB_INTERFACE_HANDLE InterfaceHandle, - PUCHAR AlternateSetting -); -typedef BOOL (WINAPI *WinUsb_GetDescriptor_t)( - WINUSB_INTERFACE_HANDLE InterfaceHandle, - UCHAR DescriptorType, - UCHAR Index, - USHORT LanguageID, - PUCHAR Buffer, - ULONG BufferLength, - PULONG LengthTransferred -); -typedef BOOL (WINAPI *WinUsb_GetOverlappedResult_t)( - WINUSB_INTERFACE_HANDLE InterfaceHandle, - LPOVERLAPPED lpOverlapped, - LPDWORD lpNumberOfBytesTransferred, - BOOL bWait -); -typedef BOOL (WINAPI *WinUsb_GetPipePolicy_t)( - WINUSB_INTERFACE_HANDLE InterfaceHandle, - UCHAR PipeID, - ULONG PolicyType, - PULONG ValueLength, - PVOID Value -); -typedef BOOL (WINAPI *WinUsb_GetPowerPolicy_t)( - WINUSB_INTERFACE_HANDLE InterfaceHandle, - ULONG PolicyType, - PULONG ValueLength, - PVOID Value -); -typedef BOOL (WINAPI *WinUsb_Initialize_t)( - HANDLE DeviceHandle, - PWINUSB_INTERFACE_HANDLE InterfaceHandle -); -typedef BOOL (WINAPI *WinUsb_QueryDeviceInformation_t)( - WINUSB_INTERFACE_HANDLE InterfaceHandle, - ULONG InformationType, - PULONG BufferLength, - PVOID Buffer -); -typedef BOOL (WINAPI *WinUsb_QueryInterfaceSettings_t)( - WINUSB_INTERFACE_HANDLE InterfaceHandle, - UCHAR AlternateSettingNumber, - PUSB_INTERFACE_DESCRIPTOR UsbAltInterfaceDescriptor -); -typedef BOOL (WINAPI *WinUsb_QueryPipe_t)( - WINUSB_INTERFACE_HANDLE InterfaceHandle, - UCHAR AlternateInterfaceNumber, - UCHAR PipeIndex, - PWINUSB_PIPE_INFORMATION PipeInformation -); -typedef BOOL (WINAPI *WinUsb_ReadPipe_t)( - WINUSB_INTERFACE_HANDLE InterfaceHandle, - UCHAR PipeID, - PUCHAR Buffer, - ULONG BufferLength, - PULONG LengthTransferred, - LPOVERLAPPED Overlapped -); -typedef BOOL (WINAPI *WinUsb_ResetPipe_t)( - WINUSB_INTERFACE_HANDLE InterfaceHandle, - UCHAR PipeID -); -typedef BOOL (WINAPI *WinUsb_SetCurrentAlternateSetting_t)( - WINUSB_INTERFACE_HANDLE InterfaceHandle, - UCHAR AlternateSetting -); -typedef BOOL (WINAPI *WinUsb_SetPipePolicy_t)( - WINUSB_INTERFACE_HANDLE InterfaceHandle, - UCHAR PipeID, - ULONG PolicyType, - ULONG ValueLength, - PVOID Value -); -typedef BOOL (WINAPI *WinUsb_SetPowerPolicy_t)( - WINUSB_INTERFACE_HANDLE InterfaceHandle, - ULONG PolicyType, - ULONG ValueLength, - PVOID Value -); -typedef BOOL (WINAPI *WinUsb_WritePipe_t)( - WINUSB_INTERFACE_HANDLE InterfaceHandle, - UCHAR PipeID, - PUCHAR Buffer, - ULONG BufferLength, - PULONG LengthTransferred, - LPOVERLAPPED Overlapped -); -typedef BOOL (WINAPI *WinUsb_ResetDevice_t)( - WINUSB_INTERFACE_HANDLE InterfaceHandle -); - -/* /!\ These must match the ones from the official libusbk.h */ -typedef enum _KUSB_FNID { - KUSB_FNID_Init, - KUSB_FNID_Free, - KUSB_FNID_ClaimInterface, - KUSB_FNID_ReleaseInterface, - KUSB_FNID_SetAltInterface, - KUSB_FNID_GetAltInterface, - KUSB_FNID_GetDescriptor, - KUSB_FNID_ControlTransfer, - KUSB_FNID_SetPowerPolicy, - KUSB_FNID_GetPowerPolicy, - KUSB_FNID_SetConfiguration, - KUSB_FNID_GetConfiguration, - KUSB_FNID_ResetDevice, - KUSB_FNID_Initialize, - KUSB_FNID_SelectInterface, - KUSB_FNID_GetAssociatedInterface, - KUSB_FNID_Clone, - KUSB_FNID_QueryInterfaceSettings, - KUSB_FNID_QueryDeviceInformation, - KUSB_FNID_SetCurrentAlternateSetting, - KUSB_FNID_GetCurrentAlternateSetting, - KUSB_FNID_QueryPipe, - KUSB_FNID_SetPipePolicy, - KUSB_FNID_GetPipePolicy, - KUSB_FNID_ReadPipe, - KUSB_FNID_WritePipe, - KUSB_FNID_ResetPipe, - KUSB_FNID_AbortPipe, - KUSB_FNID_FlushPipe, - KUSB_FNID_IsoReadPipe, - KUSB_FNID_IsoWritePipe, - KUSB_FNID_GetCurrentFrameNumber, - KUSB_FNID_GetOverlappedResult, - KUSB_FNID_GetProperty, - KUSB_FNID_COUNT, -} KUSB_FNID; - -typedef struct _KLIB_VERSION { - INT Major; - INT Minor; - INT Micro; - INT Nano; -} KLIB_VERSION; -typedef KLIB_VERSION* PKLIB_VERSION; - -typedef BOOL (WINAPI *LibK_GetProcAddress_t)( - PVOID *ProcAddress, - ULONG DriverID, - ULONG FunctionID -); - -typedef VOID (WINAPI *LibK_GetVersion_t)( - PKLIB_VERSION Version -); - -struct winusb_interface { - bool initialized; - WinUsb_AbortPipe_t AbortPipe; - WinUsb_ControlTransfer_t ControlTransfer; - WinUsb_FlushPipe_t FlushPipe; - WinUsb_Free_t Free; - WinUsb_GetAssociatedInterface_t GetAssociatedInterface; - WinUsb_GetCurrentAlternateSetting_t GetCurrentAlternateSetting; - WinUsb_GetDescriptor_t GetDescriptor; - WinUsb_GetOverlappedResult_t GetOverlappedResult; - WinUsb_GetPipePolicy_t GetPipePolicy; - WinUsb_GetPowerPolicy_t GetPowerPolicy; - WinUsb_Initialize_t Initialize; - WinUsb_QueryDeviceInformation_t QueryDeviceInformation; - WinUsb_QueryInterfaceSettings_t QueryInterfaceSettings; - WinUsb_QueryPipe_t QueryPipe; - WinUsb_ReadPipe_t ReadPipe; - WinUsb_ResetPipe_t ResetPipe; - WinUsb_SetCurrentAlternateSetting_t SetCurrentAlternateSetting; - WinUsb_SetPipePolicy_t SetPipePolicy; - WinUsb_SetPowerPolicy_t SetPowerPolicy; - WinUsb_WritePipe_t WritePipe; - WinUsb_ResetDevice_t ResetDevice; -}; - -/* hid.dll interface */ - -#define HIDP_STATUS_SUCCESS 0x110000 -typedef void * PHIDP_PREPARSED_DATA; - -#pragma pack(1) -typedef struct { - ULONG Size; - USHORT VendorID; - USHORT ProductID; - USHORT VersionNumber; -} HIDD_ATTRIBUTES, *PHIDD_ATTRIBUTES; -#pragma pack() - -typedef USHORT USAGE; -typedef struct { - USAGE Usage; - USAGE UsagePage; - USHORT InputReportByteLength; - USHORT OutputReportByteLength; - USHORT FeatureReportByteLength; - USHORT Reserved[17]; - USHORT NumberLinkCollectionNodes; - USHORT NumberInputButtonCaps; - USHORT NumberInputValueCaps; - USHORT NumberInputDataIndices; - USHORT NumberOutputButtonCaps; - USHORT NumberOutputValueCaps; - USHORT NumberOutputDataIndices; - USHORT NumberFeatureButtonCaps; - USHORT NumberFeatureValueCaps; - USHORT NumberFeatureDataIndices; -} HIDP_CAPS, *PHIDP_CAPS; - -typedef enum _HIDP_REPORT_TYPE { - HidP_Input, - HidP_Output, - HidP_Feature -} HIDP_REPORT_TYPE; - -typedef struct _HIDP_VALUE_CAPS { - USAGE UsagePage; - UCHAR ReportID; - BOOLEAN IsAlias; - USHORT BitField; - USHORT LinkCollection; - USAGE LinkUsage; - USAGE LinkUsagePage; - BOOLEAN IsRange; - BOOLEAN IsStringRange; - BOOLEAN IsDesignatorRange; - BOOLEAN IsAbsolute; - BOOLEAN HasNull; - UCHAR Reserved; - USHORT BitSize; - USHORT ReportCount; - USHORT Reserved2[5]; - ULONG UnitsExp; - ULONG Units; - LONG LogicalMin, LogicalMax; - LONG PhysicalMin, PhysicalMax; - union { - struct { - USAGE UsageMin, UsageMax; - USHORT StringMin, StringMax; - USHORT DesignatorMin, DesignatorMax; - USHORT DataIndexMin, DataIndexMax; - } Range; - struct { - USAGE Usage, Reserved1; - USHORT StringIndex, Reserved2; - USHORT DesignatorIndex, Reserved3; - USHORT DataIndex, Reserved4; - } NotRange; - } u; -} HIDP_VALUE_CAPS, *PHIDP_VALUE_CAPS; - -DLL_DECLARE_HANDLE(hid); -DLL_DECLARE_FUNC(WINAPI, BOOL, HidD_GetAttributes, (HANDLE, PHIDD_ATTRIBUTES)); -DLL_DECLARE_FUNC(WINAPI, VOID, HidD_GetHidGuid, (LPGUID)); -DLL_DECLARE_FUNC(WINAPI, BOOL, HidD_GetPreparsedData, (HANDLE, PHIDP_PREPARSED_DATA *)); -DLL_DECLARE_FUNC(WINAPI, BOOL, HidD_FreePreparsedData, (PHIDP_PREPARSED_DATA)); -DLL_DECLARE_FUNC(WINAPI, BOOL, HidD_GetManufacturerString, (HANDLE, PVOID, ULONG)); -DLL_DECLARE_FUNC(WINAPI, BOOL, HidD_GetProductString, (HANDLE, PVOID, ULONG)); -DLL_DECLARE_FUNC(WINAPI, BOOL, HidD_GetSerialNumberString, (HANDLE, PVOID, ULONG)); -DLL_DECLARE_FUNC(WINAPI, LONG, HidP_GetCaps, (PHIDP_PREPARSED_DATA, PHIDP_CAPS)); -DLL_DECLARE_FUNC(WINAPI, BOOL, HidD_SetNumInputBuffers, (HANDLE, ULONG)); -DLL_DECLARE_FUNC(WINAPI, BOOL, HidD_SetFeature, (HANDLE, PVOID, ULONG)); -DLL_DECLARE_FUNC(WINAPI, BOOL, HidD_GetFeature, (HANDLE, PVOID, ULONG)); -DLL_DECLARE_FUNC(WINAPI, BOOL, HidD_GetPhysicalDescriptor, (HANDLE, PVOID, ULONG)); -DLL_DECLARE_FUNC(WINAPI, BOOL, HidD_GetInputReport, (HANDLE, PVOID, ULONG)); -DLL_DECLARE_FUNC(WINAPI, BOOL, HidD_SetOutputReport, (HANDLE, PVOID, ULONG)); -DLL_DECLARE_FUNC(WINAPI, BOOL, HidD_FlushQueue, (HANDLE)); -DLL_DECLARE_FUNC(WINAPI, BOOL, HidP_GetValueCaps, (HIDP_REPORT_TYPE, PHIDP_VALUE_CAPS, PULONG, PHIDP_PREPARSED_DATA)); \ No newline at end of file diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/strerror.c b/vendor/github.com/karalabe/hid/libusb/libusb/strerror.c deleted file mode 100644 index d2be0e2a..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/strerror.c +++ /dev/null @@ -1,202 +0,0 @@ -/* - * libusb strerror code - * Copyright © 2013 Hans de Goede - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include - -#include -#include -#include -#if defined(HAVE_STRINGS_H) -#include -#endif - -#include "libusbi.h" - -#if defined(_MSC_VER) -#define strncasecmp _strnicmp -#endif - -static size_t usbi_locale = 0; - -/** \ingroup libusb_misc - * How to add a new \ref libusb_strerror() translation: - *
    - *
  1. Download the latest \c strerror.c from:
    - * https://raw.github.com/libusb/libusb/master/libusb/sterror.c
  2. - *
  3. Open the file in an UTF-8 capable editor
  4. - *
  5. Add the 2 letter ISO 639-1 - * code for your locale at the end of \c usbi_locale_supported[]
    - * Eg. for Chinese, you would add "zh" so that: - * \code... usbi_locale_supported[] = { "en", "nl", "fr" };\endcode - * becomes: - * \code... usbi_locale_supported[] = { "en", "nl", "fr", "zh" };\endcode
  6. - *
  7. Copy the { / * English (en) * / ... } section and add it at the end of \c usbi_localized_errors
    - * Eg. for Chinese, the last section of \c usbi_localized_errors could look like: - * \code - * }, { / * Chinese (zh) * / - * "Success", - * ... - * "Other error", - * } - * };\endcode
  8. - *
  9. Translate each of the English messages from the section you copied into your language
  10. - *
  11. Save the file (in UTF-8 format) and send it to \c libusb-devel\@lists.sourceforge.net
  12. - *
- */ - -static const char* usbi_locale_supported[] = { "en", "nl", "fr", "ru" }; -static const char* usbi_localized_errors[ARRAYSIZE(usbi_locale_supported)][LIBUSB_ERROR_COUNT] = { - { /* English (en) */ - "Success", - "Input/Output Error", - "Invalid parameter", - "Access denied (insufficient permissions)", - "No such device (it may have been disconnected)", - "Entity not found", - "Resource busy", - "Operation timed out", - "Overflow", - "Pipe error", - "System call interrupted (perhaps due to signal)", - "Insufficient memory", - "Operation not supported or unimplemented on this platform", - "Other error", - }, { /* Dutch (nl) */ - "Gelukt", - "Invoer-/uitvoerfout", - "Ongeldig argument", - "Toegang geweigerd (onvoldoende toegangsrechten)", - "Apparaat bestaat niet (verbinding met apparaat verbroken?)", - "Niet gevonden", - "Apparaat of hulpbron is bezig", - "Bewerking verlopen", - "Waarde is te groot", - "Gebroken pijp", - "Onderbroken systeemaanroep", - "Onvoldoende geheugen beschikbaar", - "Bewerking wordt niet ondersteund", - "Andere fout", - }, { /* French (fr) */ - "Succès", - "Erreur d'entrée/sortie", - "Paramètre invalide", - "Accès refusé (permissions insuffisantes)", - "Périphérique introuvable (peut-être déconnecté)", - "Elément introuvable", - "Resource déjà occupée", - "Operation expirée", - "Débordement", - "Erreur de pipe", - "Appel système abandonné (peut-être à cause d’un signal)", - "Mémoire insuffisante", - "Opération non supportée or non implémentée sur cette plateforme", - "Autre erreur", - }, { /* Russian (ru) */ - "Успех", - "Ошибка ввода/вывода", - "Неверный параметр", - "Доступ запрещён (не хватает прав)", - "Устройство отсутствует (возможно, оно было отсоединено)", - "Элемент не найден", - "Ресурс занят", - "Истекло время ожидания операции", - "Переполнение", - "Ошибка канала", - "Системный вызов прерван (возможно, сигналом)", - "Память исчерпана", - "Операция не поддерживается данной платформой", - "Неизвестная ошибка" - } -}; - -/** \ingroup libusb_misc - * Set the language, and only the language, not the encoding! used for - * translatable libusb messages. - * - * This takes a locale string in the default setlocale format: lang[-region] - * or lang[_country_region][.codeset]. Only the lang part of the string is - * used, and only 2 letter ISO 639-1 codes are accepted for it, such as "de". - * The optional region, country_region or codeset parts are ignored. This - * means that functions which return translatable strings will NOT honor the - * specified encoding. - * All strings returned are encoded as UTF-8 strings. - * - * If libusb_setlocale() is not called, all messages will be in English. - * - * The following functions return translatable strings: libusb_strerror(). - * Note that the libusb log messages controlled through libusb_set_debug() - * are not translated, they are always in English. - * - * For POSIX UTF-8 environments if you want libusb to follow the standard - * locale settings, call libusb_setlocale(setlocale(LC_MESSAGES, NULL)), - * after your app has done its locale setup. - * - * \param locale locale-string in the form of lang[_country_region][.codeset] - * or lang[-region], where lang is a 2 letter ISO 639-1 code - * \returns LIBUSB_SUCCESS on success - * \returns LIBUSB_ERROR_INVALID_PARAM if the locale doesn't meet the requirements - * \returns LIBUSB_ERROR_NOT_FOUND if the requested language is not supported - * \returns a LIBUSB_ERROR code on other errors - */ - -int API_EXPORTED libusb_setlocale(const char *locale) -{ - size_t i; - - if ( (locale == NULL) || (strlen(locale) < 2) - || ((strlen(locale) > 2) && (locale[2] != '-') && (locale[2] != '_') && (locale[2] != '.')) ) - return LIBUSB_ERROR_INVALID_PARAM; - - for (i=0; i= ARRAYSIZE(usbi_locale_supported)) { - return LIBUSB_ERROR_NOT_FOUND; - } - - usbi_locale = i; - - return LIBUSB_SUCCESS; -} - -/** \ingroup libusb_misc - * Returns a constant string with a short description of the given error code, - * this description is intended for displaying to the end user and will be in - * the language set by libusb_setlocale(). - * - * The returned string is encoded in UTF-8. - * - * The messages always start with a capital letter and end without any dot. - * The caller must not free() the returned string. - * - * \param errcode the error code whose description is desired - * \returns a short description of the error code in UTF-8 encoding - */ -DEFAULT_VISIBILITY const char* LIBUSB_CALL libusb_strerror(enum libusb_error errcode) -{ - int errcode_index = -errcode; - - if ((errcode_index < 0) || (errcode_index >= LIBUSB_ERROR_COUNT)) { - /* "Other Error", which should always be our last message, is returned */ - errcode_index = LIBUSB_ERROR_COUNT - 1; - } - - return usbi_localized_errors[usbi_locale][errcode_index]; -} diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/sync.c b/vendor/github.com/karalabe/hid/libusb/libusb/sync.c deleted file mode 100644 index a609f65f..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/sync.c +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Synchronous I/O functions for libusb - * Copyright © 2007-2008 Daniel Drake - * - * This 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 2.1 of the License, or (at your option) any later version. - * - * This 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 this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include - -#include -#include -#include -#include - -#include "libusbi.h" - -/** - * @defgroup libusb_syncio Synchronous device I/O - * - * This page documents libusb's synchronous (blocking) API for USB device I/O. - * This interface is easy to use but has some limitations. More advanced users - * may wish to consider using the \ref libusb_asyncio "asynchronous I/O API" instead. - */ - -static void LIBUSB_CALL sync_transfer_cb(struct libusb_transfer *transfer) -{ - int *completed = transfer->user_data; - *completed = 1; - usbi_dbg("actual_length=%d", transfer->actual_length); - /* caller interprets result and frees transfer */ -} - -static void sync_transfer_wait_for_completion(struct libusb_transfer *transfer) -{ - int r, *completed = transfer->user_data; - struct libusb_context *ctx = HANDLE_CTX(transfer->dev_handle); - - while (!*completed) { - r = libusb_handle_events_completed(ctx, completed); - if (r < 0) { - if (r == LIBUSB_ERROR_INTERRUPTED) - continue; - usbi_err(ctx, "libusb_handle_events failed: %s, cancelling transfer and retrying", - libusb_error_name(r)); - libusb_cancel_transfer(transfer); - continue; - } - } -} - -/** \ingroup libusb_syncio - * Perform a USB control transfer. - * - * The direction of the transfer is inferred from the bmRequestType field of - * the setup packet. - * - * The wValue, wIndex and wLength fields values should be given in host-endian - * byte order. - * - * \param dev_handle a handle for the device to communicate with - * \param bmRequestType the request type field for the setup packet - * \param bRequest the request field for the setup packet - * \param wValue the value field for the setup packet - * \param wIndex the index field for the setup packet - * \param data a suitably-sized data buffer for either input or output - * (depending on direction bits within bmRequestType) - * \param wLength the length field for the setup packet. The data buffer should - * be at least this size. - * \param timeout timeout (in millseconds) that this function should wait - * before giving up due to no response being received. For an unlimited - * timeout, use value 0. - * \returns on success, the number of bytes actually transferred - * \returns LIBUSB_ERROR_TIMEOUT if the transfer timed out - * \returns LIBUSB_ERROR_PIPE if the control request was not supported by the - * device - * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected - * \returns LIBUSB_ERROR_BUSY if called from event handling context - * \returns LIBUSB_ERROR_INVALID_PARAM if the transfer size is larger than - * the operating system and/or hardware can support - * \returns another LIBUSB_ERROR code on other failures - */ -int API_EXPORTED libusb_control_transfer(libusb_device_handle *dev_handle, - uint8_t bmRequestType, uint8_t bRequest, uint16_t wValue, uint16_t wIndex, - unsigned char *data, uint16_t wLength, unsigned int timeout) -{ - struct libusb_transfer *transfer; - unsigned char *buffer; - int completed = 0; - int r; - - if (usbi_handling_events(HANDLE_CTX(dev_handle))) - return LIBUSB_ERROR_BUSY; - - transfer = libusb_alloc_transfer(0); - if (!transfer) - return LIBUSB_ERROR_NO_MEM; - - buffer = (unsigned char*) malloc(LIBUSB_CONTROL_SETUP_SIZE + wLength); - if (!buffer) { - libusb_free_transfer(transfer); - return LIBUSB_ERROR_NO_MEM; - } - - libusb_fill_control_setup(buffer, bmRequestType, bRequest, wValue, wIndex, - wLength); - if ((bmRequestType & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT) - memcpy(buffer + LIBUSB_CONTROL_SETUP_SIZE, data, wLength); - - libusb_fill_control_transfer(transfer, dev_handle, buffer, - sync_transfer_cb, &completed, timeout); - transfer->flags = LIBUSB_TRANSFER_FREE_BUFFER; - r = libusb_submit_transfer(transfer); - if (r < 0) { - libusb_free_transfer(transfer); - return r; - } - - sync_transfer_wait_for_completion(transfer); - - if ((bmRequestType & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_IN) - memcpy(data, libusb_control_transfer_get_data(transfer), - transfer->actual_length); - - switch (transfer->status) { - case LIBUSB_TRANSFER_COMPLETED: - r = transfer->actual_length; - break; - case LIBUSB_TRANSFER_TIMED_OUT: - r = LIBUSB_ERROR_TIMEOUT; - break; - case LIBUSB_TRANSFER_STALL: - r = LIBUSB_ERROR_PIPE; - break; - case LIBUSB_TRANSFER_NO_DEVICE: - r = LIBUSB_ERROR_NO_DEVICE; - break; - case LIBUSB_TRANSFER_OVERFLOW: - r = LIBUSB_ERROR_OVERFLOW; - break; - case LIBUSB_TRANSFER_ERROR: - case LIBUSB_TRANSFER_CANCELLED: - r = LIBUSB_ERROR_IO; - break; - default: - usbi_warn(HANDLE_CTX(dev_handle), - "unrecognised status code %d", transfer->status); - r = LIBUSB_ERROR_OTHER; - } - - libusb_free_transfer(transfer); - return r; -} - -static int do_sync_bulk_transfer(struct libusb_device_handle *dev_handle, - unsigned char endpoint, unsigned char *buffer, int length, - int *transferred, unsigned int timeout, unsigned char type) -{ - struct libusb_transfer *transfer; - int completed = 0; - int r; - - if (usbi_handling_events(HANDLE_CTX(dev_handle))) - return LIBUSB_ERROR_BUSY; - - transfer = libusb_alloc_transfer(0); - if (!transfer) - return LIBUSB_ERROR_NO_MEM; - - libusb_fill_bulk_transfer(transfer, dev_handle, endpoint, buffer, length, - sync_transfer_cb, &completed, timeout); - transfer->type = type; - - r = libusb_submit_transfer(transfer); - if (r < 0) { - libusb_free_transfer(transfer); - return r; - } - - sync_transfer_wait_for_completion(transfer); - - if (transferred) - *transferred = transfer->actual_length; - - switch (transfer->status) { - case LIBUSB_TRANSFER_COMPLETED: - r = 0; - break; - case LIBUSB_TRANSFER_TIMED_OUT: - r = LIBUSB_ERROR_TIMEOUT; - break; - case LIBUSB_TRANSFER_STALL: - r = LIBUSB_ERROR_PIPE; - break; - case LIBUSB_TRANSFER_OVERFLOW: - r = LIBUSB_ERROR_OVERFLOW; - break; - case LIBUSB_TRANSFER_NO_DEVICE: - r = LIBUSB_ERROR_NO_DEVICE; - break; - case LIBUSB_TRANSFER_ERROR: - case LIBUSB_TRANSFER_CANCELLED: - r = LIBUSB_ERROR_IO; - break; - default: - usbi_warn(HANDLE_CTX(dev_handle), - "unrecognised status code %d", transfer->status); - r = LIBUSB_ERROR_OTHER; - } - - libusb_free_transfer(transfer); - return r; -} - -/** \ingroup libusb_syncio - * Perform a USB bulk transfer. The direction of the transfer is inferred from - * the direction bits of the endpoint address. - * - * For bulk reads, the length field indicates the maximum length of - * data you are expecting to receive. If less data arrives than expected, - * this function will return that data, so be sure to check the - * transferred output parameter. - * - * You should also check the transferred parameter for bulk writes. - * Not all of the data may have been written. - * - * Also check transferred when dealing with a timeout error code. - * libusb may have to split your transfer into a number of chunks to satisfy - * underlying O/S requirements, meaning that the timeout may expire after - * the first few chunks have completed. libusb is careful not to lose any data - * that may have been transferred; do not assume that timeout conditions - * indicate a complete lack of I/O. - * - * \param dev_handle a handle for the device to communicate with - * \param endpoint the address of a valid endpoint to communicate with - * \param data a suitably-sized data buffer for either input or output - * (depending on endpoint) - * \param length for bulk writes, the number of bytes from data to be sent. for - * bulk reads, the maximum number of bytes to receive into the data buffer. - * \param transferred output location for the number of bytes actually - * transferred. Since version 1.0.21 (\ref LIBUSB_API_VERSION >= 0x01000105), - * it is legal to pass a NULL pointer if you do not wish to receive this - * information. - * \param timeout timeout (in millseconds) that this function should wait - * before giving up due to no response being received. For an unlimited - * timeout, use value 0. - * - * \returns 0 on success (and populates transferred) - * \returns LIBUSB_ERROR_TIMEOUT if the transfer timed out (and populates - * transferred) - * \returns LIBUSB_ERROR_PIPE if the endpoint halted - * \returns LIBUSB_ERROR_OVERFLOW if the device offered more data, see - * \ref libusb_packetoverflow - * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected - * \returns LIBUSB_ERROR_BUSY if called from event handling context - * \returns another LIBUSB_ERROR code on other failures - */ -int API_EXPORTED libusb_bulk_transfer(struct libusb_device_handle *dev_handle, - unsigned char endpoint, unsigned char *data, int length, int *transferred, - unsigned int timeout) -{ - return do_sync_bulk_transfer(dev_handle, endpoint, data, length, - transferred, timeout, LIBUSB_TRANSFER_TYPE_BULK); -} - -/** \ingroup libusb_syncio - * Perform a USB interrupt transfer. The direction of the transfer is inferred - * from the direction bits of the endpoint address. - * - * For interrupt reads, the length field indicates the maximum length - * of data you are expecting to receive. If less data arrives than expected, - * this function will return that data, so be sure to check the - * transferred output parameter. - * - * You should also check the transferred parameter for interrupt - * writes. Not all of the data may have been written. - * - * Also check transferred when dealing with a timeout error code. - * libusb may have to split your transfer into a number of chunks to satisfy - * underlying O/S requirements, meaning that the timeout may expire after - * the first few chunks have completed. libusb is careful not to lose any data - * that may have been transferred; do not assume that timeout conditions - * indicate a complete lack of I/O. - * - * The default endpoint bInterval value is used as the polling interval. - * - * \param dev_handle a handle for the device to communicate with - * \param endpoint the address of a valid endpoint to communicate with - * \param data a suitably-sized data buffer for either input or output - * (depending on endpoint) - * \param length for bulk writes, the number of bytes from data to be sent. for - * bulk reads, the maximum number of bytes to receive into the data buffer. - * \param transferred output location for the number of bytes actually - * transferred. Since version 1.0.21 (\ref LIBUSB_API_VERSION >= 0x01000105), - * it is legal to pass a NULL pointer if you do not wish to receive this - * information. - * \param timeout timeout (in millseconds) that this function should wait - * before giving up due to no response being received. For an unlimited - * timeout, use value 0. - * - * \returns 0 on success (and populates transferred) - * \returns LIBUSB_ERROR_TIMEOUT if the transfer timed out - * \returns LIBUSB_ERROR_PIPE if the endpoint halted - * \returns LIBUSB_ERROR_OVERFLOW if the device offered more data, see - * \ref libusb_packetoverflow - * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected - * \returns LIBUSB_ERROR_BUSY if called from event handling context - * \returns another LIBUSB_ERROR code on other error - */ -int API_EXPORTED libusb_interrupt_transfer( - struct libusb_device_handle *dev_handle, unsigned char endpoint, - unsigned char *data, int length, int *transferred, unsigned int timeout) -{ - return do_sync_bulk_transfer(dev_handle, endpoint, data, length, - transferred, timeout, LIBUSB_TRANSFER_TYPE_INTERRUPT); -} diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/version.h b/vendor/github.com/karalabe/hid/libusb/libusb/version.h deleted file mode 100644 index 6ce48a7d..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/version.h +++ /dev/null @@ -1,18 +0,0 @@ -/* This file is parsed by m4 and windres and RC.EXE so please keep it simple. */ -#include "version_nano.h" -#ifndef LIBUSB_MAJOR -#define LIBUSB_MAJOR 1 -#endif -#ifndef LIBUSB_MINOR -#define LIBUSB_MINOR 0 -#endif -#ifndef LIBUSB_MICRO -#define LIBUSB_MICRO 21 -#endif -#ifndef LIBUSB_NANO -#define LIBUSB_NANO 0 -#endif -/* LIBUSB_RC is the release candidate suffix. Should normally be empty. */ -#ifndef LIBUSB_RC -#define LIBUSB_RC "" -#endif diff --git a/vendor/github.com/karalabe/hid/libusb/libusb/version_nano.h b/vendor/github.com/karalabe/hid/libusb/libusb/version_nano.h deleted file mode 100644 index 0a5d1c99..00000000 --- a/vendor/github.com/karalabe/hid/libusb/libusb/version_nano.h +++ /dev/null @@ -1 +0,0 @@ -#define LIBUSB_NANO 11182 diff --git a/vendor/github.com/karalabe/hid/wchar.go b/vendor/github.com/karalabe/hid/wchar.go deleted file mode 100644 index d103beff..00000000 --- a/vendor/github.com/karalabe/hid/wchar.go +++ /dev/null @@ -1,227 +0,0 @@ -// This file is https://github.com/orofarne/gowchar/blob/master/gowchar.go -// -// It was vendored inline to work around CGO limitations that don't allow C types -// to directly cross package API boundaries. -// -// The vendored file is licensed under the 3-clause BSD license, according to: -// https://github.com/orofarne/gowchar/blob/master/LICENSE - -// +build !ios -// +build linux darwin windows - -package hid - -/* -#include - -const size_t SIZEOF_WCHAR_T = sizeof(wchar_t); - -void gowchar_set (wchar_t *arr, int pos, wchar_t val) -{ - arr[pos] = val; -} - -wchar_t gowchar_get (wchar_t *arr, int pos) -{ - return arr[pos]; -} -*/ -import "C" - -import ( - "fmt" - "unicode/utf16" - "unicode/utf8" -) - -var sizeofWcharT C.size_t = C.size_t(C.SIZEOF_WCHAR_T) - -func stringToWcharT(s string) (*C.wchar_t, C.size_t) { - switch sizeofWcharT { - case 2: - return stringToWchar2(s) // Windows - case 4: - return stringToWchar4(s) // Unix - default: - panic(fmt.Sprintf("Invalid sizeof(wchar_t) = %v", sizeofWcharT)) - } -} - -func wcharTToString(s *C.wchar_t) (string, error) { - switch sizeofWcharT { - case 2: - return wchar2ToString(s) // Windows - case 4: - return wchar4ToString(s) // Unix - default: - panic(fmt.Sprintf("Invalid sizeof(wchar_t) = %v", sizeofWcharT)) - } -} - -func wcharTNToString(s *C.wchar_t, size C.size_t) (string, error) { - switch sizeofWcharT { - case 2: - return wchar2NToString(s, size) // Windows - case 4: - return wchar4NToString(s, size) // Unix - default: - panic(fmt.Sprintf("Invalid sizeof(wchar_t) = %v", sizeofWcharT)) - } -} - -// Windows -func stringToWchar2(s string) (*C.wchar_t, C.size_t) { - var slen int - s1 := s - for len(s1) > 0 { - r, size := utf8.DecodeRuneInString(s1) - if er, _ := utf16.EncodeRune(r); er == '\uFFFD' { - slen += 1 - } else { - slen += 2 - } - s1 = s1[size:] - } - slen++ // \0 - res := C.malloc(C.size_t(slen) * sizeofWcharT) - var i int - for len(s) > 0 { - r, size := utf8.DecodeRuneInString(s) - if r1, r2 := utf16.EncodeRune(r); r1 != '\uFFFD' { - C.gowchar_set((*C.wchar_t)(res), C.int(i), C.wchar_t(r1)) - i++ - C.gowchar_set((*C.wchar_t)(res), C.int(i), C.wchar_t(r2)) - i++ - } else { - C.gowchar_set((*C.wchar_t)(res), C.int(i), C.wchar_t(r)) - i++ - } - s = s[size:] - } - C.gowchar_set((*C.wchar_t)(res), C.int(slen-1), C.wchar_t(0)) // \0 - return (*C.wchar_t)(res), C.size_t(slen) -} - -// Unix -func stringToWchar4(s string) (*C.wchar_t, C.size_t) { - slen := utf8.RuneCountInString(s) - slen++ // \0 - res := C.malloc(C.size_t(slen) * sizeofWcharT) - var i int - for len(s) > 0 { - r, size := utf8.DecodeRuneInString(s) - C.gowchar_set((*C.wchar_t)(res), C.int(i), C.wchar_t(r)) - s = s[size:] - i++ - } - C.gowchar_set((*C.wchar_t)(res), C.int(slen-1), C.wchar_t(0)) // \0 - return (*C.wchar_t)(res), C.size_t(slen) -} - -// Windows -func wchar2ToString(s *C.wchar_t) (string, error) { - var i int - var res string - for { - ch := C.gowchar_get(s, C.int(i)) - if ch == 0 { - break - } - r := rune(ch) - i++ - if !utf16.IsSurrogate(r) { - if !utf8.ValidRune(r) { - err := fmt.Errorf("Invalid rune at position %v", i) - return "", err - } - res += string(r) - } else { - ch2 := C.gowchar_get(s, C.int(i)) - r2 := rune(ch2) - r12 := utf16.DecodeRune(r, r2) - if r12 == '\uFFFD' { - err := fmt.Errorf("Invalid surrogate pair at position %v", i-1) - return "", err - } - res += string(r12) - i++ - } - } - return res, nil -} - -// Unix -func wchar4ToString(s *C.wchar_t) (string, error) { - var i int - var res string - for { - ch := C.gowchar_get(s, C.int(i)) - if ch == 0 { - break - } - r := rune(ch) - if !utf8.ValidRune(r) { - err := fmt.Errorf("Invalid rune at position %v", i) - return "", err - } - res += string(r) - i++ - } - return res, nil -} - -// Windows -func wchar2NToString(s *C.wchar_t, size C.size_t) (string, error) { - var i int - var res string - N := int(size) - for i < N { - ch := C.gowchar_get(s, C.int(i)) - if ch == 0 { - break - } - r := rune(ch) - i++ - if !utf16.IsSurrogate(r) { - if !utf8.ValidRune(r) { - err := fmt.Errorf("Invalid rune at position %v", i) - return "", err - } - - res += string(r) - } else { - if i >= N { - err := fmt.Errorf("Invalid surrogate pair at position %v", i-1) - return "", err - } - ch2 := C.gowchar_get(s, C.int(i)) - r2 := rune(ch2) - r12 := utf16.DecodeRune(r, r2) - if r12 == '\uFFFD' { - err := fmt.Errorf("Invalid surrogate pair at position %v", i-1) - return "", err - } - res += string(r12) - i++ - } - } - return res, nil -} - -// Unix -func wchar4NToString(s *C.wchar_t, size C.size_t) (string, error) { - var i int - var res string - N := int(size) - for i < N { - ch := C.gowchar_get(s, C.int(i)) - r := rune(ch) - if !utf8.ValidRune(r) { - err := fmt.Errorf("Invalid rune at position %v", i) - return "", err - } - res += string(r) - i++ - } - return res, nil -} diff --git a/vendor/github.com/mattn/go-colorable/LICENSE b/vendor/github.com/mattn/go-colorable/LICENSE deleted file mode 100644 index 91b5cef3..00000000 --- a/vendor/github.com/mattn/go-colorable/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Yasuhiro Matsumoto - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/mattn/go-colorable/colorable_appengine.go b/vendor/github.com/mattn/go-colorable/colorable_appengine.go deleted file mode 100644 index 1f28d773..00000000 --- a/vendor/github.com/mattn/go-colorable/colorable_appengine.go +++ /dev/null @@ -1,29 +0,0 @@ -// +build appengine - -package colorable - -import ( - "io" - "os" - - _ "github.com/mattn/go-isatty" -) - -// NewColorable return new instance of Writer which handle escape sequence. -func NewColorable(file *os.File) io.Writer { - if file == nil { - panic("nil passed instead of *os.File to NewColorable()") - } - - return file -} - -// NewColorableStdout return new instance of Writer which handle escape sequence for stdout. -func NewColorableStdout() io.Writer { - return os.Stdout -} - -// NewColorableStderr return new instance of Writer which handle escape sequence for stderr. -func NewColorableStderr() io.Writer { - return os.Stderr -} diff --git a/vendor/github.com/mattn/go-colorable/colorable_others.go b/vendor/github.com/mattn/go-colorable/colorable_others.go deleted file mode 100644 index 887f203d..00000000 --- a/vendor/github.com/mattn/go-colorable/colorable_others.go +++ /dev/null @@ -1,30 +0,0 @@ -// +build !windows -// +build !appengine - -package colorable - -import ( - "io" - "os" - - _ "github.com/mattn/go-isatty" -) - -// NewColorable return new instance of Writer which handle escape sequence. -func NewColorable(file *os.File) io.Writer { - if file == nil { - panic("nil passed instead of *os.File to NewColorable()") - } - - return file -} - -// NewColorableStdout return new instance of Writer which handle escape sequence for stdout. -func NewColorableStdout() io.Writer { - return os.Stdout -} - -// NewColorableStderr return new instance of Writer which handle escape sequence for stderr. -func NewColorableStderr() io.Writer { - return os.Stderr -} diff --git a/vendor/github.com/mattn/go-colorable/colorable_windows.go b/vendor/github.com/mattn/go-colorable/colorable_windows.go deleted file mode 100644 index e17a5474..00000000 --- a/vendor/github.com/mattn/go-colorable/colorable_windows.go +++ /dev/null @@ -1,884 +0,0 @@ -// +build windows -// +build !appengine - -package colorable - -import ( - "bytes" - "io" - "math" - "os" - "strconv" - "strings" - "syscall" - "unsafe" - - "github.com/mattn/go-isatty" -) - -const ( - foregroundBlue = 0x1 - foregroundGreen = 0x2 - foregroundRed = 0x4 - foregroundIntensity = 0x8 - foregroundMask = (foregroundRed | foregroundBlue | foregroundGreen | foregroundIntensity) - backgroundBlue = 0x10 - backgroundGreen = 0x20 - backgroundRed = 0x40 - backgroundIntensity = 0x80 - backgroundMask = (backgroundRed | backgroundBlue | backgroundGreen | backgroundIntensity) -) - -type wchar uint16 -type short int16 -type dword uint32 -type word uint16 - -type coord struct { - x short - y short -} - -type smallRect struct { - left short - top short - right short - bottom short -} - -type consoleScreenBufferInfo struct { - size coord - cursorPosition coord - attributes word - window smallRect - maximumWindowSize coord -} - -type consoleCursorInfo struct { - size dword - visible int32 -} - -var ( - kernel32 = syscall.NewLazyDLL("kernel32.dll") - procGetConsoleScreenBufferInfo = kernel32.NewProc("GetConsoleScreenBufferInfo") - procSetConsoleTextAttribute = kernel32.NewProc("SetConsoleTextAttribute") - procSetConsoleCursorPosition = kernel32.NewProc("SetConsoleCursorPosition") - procFillConsoleOutputCharacter = kernel32.NewProc("FillConsoleOutputCharacterW") - procFillConsoleOutputAttribute = kernel32.NewProc("FillConsoleOutputAttribute") - procGetConsoleCursorInfo = kernel32.NewProc("GetConsoleCursorInfo") - procSetConsoleCursorInfo = kernel32.NewProc("SetConsoleCursorInfo") - procSetConsoleTitle = kernel32.NewProc("SetConsoleTitleW") -) - -// Writer provide colorable Writer to the console -type Writer struct { - out io.Writer - handle syscall.Handle - oldattr word - oldpos coord -} - -// NewColorable return new instance of Writer which handle escape sequence from File. -func NewColorable(file *os.File) io.Writer { - if file == nil { - panic("nil passed instead of *os.File to NewColorable()") - } - - if isatty.IsTerminal(file.Fd()) { - var csbi consoleScreenBufferInfo - handle := syscall.Handle(file.Fd()) - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - return &Writer{out: file, handle: handle, oldattr: csbi.attributes, oldpos: coord{0, 0}} - } - return file -} - -// NewColorableStdout return new instance of Writer which handle escape sequence for stdout. -func NewColorableStdout() io.Writer { - return NewColorable(os.Stdout) -} - -// NewColorableStderr return new instance of Writer which handle escape sequence for stderr. -func NewColorableStderr() io.Writer { - return NewColorable(os.Stderr) -} - -var color256 = map[int]int{ - 0: 0x000000, - 1: 0x800000, - 2: 0x008000, - 3: 0x808000, - 4: 0x000080, - 5: 0x800080, - 6: 0x008080, - 7: 0xc0c0c0, - 8: 0x808080, - 9: 0xff0000, - 10: 0x00ff00, - 11: 0xffff00, - 12: 0x0000ff, - 13: 0xff00ff, - 14: 0x00ffff, - 15: 0xffffff, - 16: 0x000000, - 17: 0x00005f, - 18: 0x000087, - 19: 0x0000af, - 20: 0x0000d7, - 21: 0x0000ff, - 22: 0x005f00, - 23: 0x005f5f, - 24: 0x005f87, - 25: 0x005faf, - 26: 0x005fd7, - 27: 0x005fff, - 28: 0x008700, - 29: 0x00875f, - 30: 0x008787, - 31: 0x0087af, - 32: 0x0087d7, - 33: 0x0087ff, - 34: 0x00af00, - 35: 0x00af5f, - 36: 0x00af87, - 37: 0x00afaf, - 38: 0x00afd7, - 39: 0x00afff, - 40: 0x00d700, - 41: 0x00d75f, - 42: 0x00d787, - 43: 0x00d7af, - 44: 0x00d7d7, - 45: 0x00d7ff, - 46: 0x00ff00, - 47: 0x00ff5f, - 48: 0x00ff87, - 49: 0x00ffaf, - 50: 0x00ffd7, - 51: 0x00ffff, - 52: 0x5f0000, - 53: 0x5f005f, - 54: 0x5f0087, - 55: 0x5f00af, - 56: 0x5f00d7, - 57: 0x5f00ff, - 58: 0x5f5f00, - 59: 0x5f5f5f, - 60: 0x5f5f87, - 61: 0x5f5faf, - 62: 0x5f5fd7, - 63: 0x5f5fff, - 64: 0x5f8700, - 65: 0x5f875f, - 66: 0x5f8787, - 67: 0x5f87af, - 68: 0x5f87d7, - 69: 0x5f87ff, - 70: 0x5faf00, - 71: 0x5faf5f, - 72: 0x5faf87, - 73: 0x5fafaf, - 74: 0x5fafd7, - 75: 0x5fafff, - 76: 0x5fd700, - 77: 0x5fd75f, - 78: 0x5fd787, - 79: 0x5fd7af, - 80: 0x5fd7d7, - 81: 0x5fd7ff, - 82: 0x5fff00, - 83: 0x5fff5f, - 84: 0x5fff87, - 85: 0x5fffaf, - 86: 0x5fffd7, - 87: 0x5fffff, - 88: 0x870000, - 89: 0x87005f, - 90: 0x870087, - 91: 0x8700af, - 92: 0x8700d7, - 93: 0x8700ff, - 94: 0x875f00, - 95: 0x875f5f, - 96: 0x875f87, - 97: 0x875faf, - 98: 0x875fd7, - 99: 0x875fff, - 100: 0x878700, - 101: 0x87875f, - 102: 0x878787, - 103: 0x8787af, - 104: 0x8787d7, - 105: 0x8787ff, - 106: 0x87af00, - 107: 0x87af5f, - 108: 0x87af87, - 109: 0x87afaf, - 110: 0x87afd7, - 111: 0x87afff, - 112: 0x87d700, - 113: 0x87d75f, - 114: 0x87d787, - 115: 0x87d7af, - 116: 0x87d7d7, - 117: 0x87d7ff, - 118: 0x87ff00, - 119: 0x87ff5f, - 120: 0x87ff87, - 121: 0x87ffaf, - 122: 0x87ffd7, - 123: 0x87ffff, - 124: 0xaf0000, - 125: 0xaf005f, - 126: 0xaf0087, - 127: 0xaf00af, - 128: 0xaf00d7, - 129: 0xaf00ff, - 130: 0xaf5f00, - 131: 0xaf5f5f, - 132: 0xaf5f87, - 133: 0xaf5faf, - 134: 0xaf5fd7, - 135: 0xaf5fff, - 136: 0xaf8700, - 137: 0xaf875f, - 138: 0xaf8787, - 139: 0xaf87af, - 140: 0xaf87d7, - 141: 0xaf87ff, - 142: 0xafaf00, - 143: 0xafaf5f, - 144: 0xafaf87, - 145: 0xafafaf, - 146: 0xafafd7, - 147: 0xafafff, - 148: 0xafd700, - 149: 0xafd75f, - 150: 0xafd787, - 151: 0xafd7af, - 152: 0xafd7d7, - 153: 0xafd7ff, - 154: 0xafff00, - 155: 0xafff5f, - 156: 0xafff87, - 157: 0xafffaf, - 158: 0xafffd7, - 159: 0xafffff, - 160: 0xd70000, - 161: 0xd7005f, - 162: 0xd70087, - 163: 0xd700af, - 164: 0xd700d7, - 165: 0xd700ff, - 166: 0xd75f00, - 167: 0xd75f5f, - 168: 0xd75f87, - 169: 0xd75faf, - 170: 0xd75fd7, - 171: 0xd75fff, - 172: 0xd78700, - 173: 0xd7875f, - 174: 0xd78787, - 175: 0xd787af, - 176: 0xd787d7, - 177: 0xd787ff, - 178: 0xd7af00, - 179: 0xd7af5f, - 180: 0xd7af87, - 181: 0xd7afaf, - 182: 0xd7afd7, - 183: 0xd7afff, - 184: 0xd7d700, - 185: 0xd7d75f, - 186: 0xd7d787, - 187: 0xd7d7af, - 188: 0xd7d7d7, - 189: 0xd7d7ff, - 190: 0xd7ff00, - 191: 0xd7ff5f, - 192: 0xd7ff87, - 193: 0xd7ffaf, - 194: 0xd7ffd7, - 195: 0xd7ffff, - 196: 0xff0000, - 197: 0xff005f, - 198: 0xff0087, - 199: 0xff00af, - 200: 0xff00d7, - 201: 0xff00ff, - 202: 0xff5f00, - 203: 0xff5f5f, - 204: 0xff5f87, - 205: 0xff5faf, - 206: 0xff5fd7, - 207: 0xff5fff, - 208: 0xff8700, - 209: 0xff875f, - 210: 0xff8787, - 211: 0xff87af, - 212: 0xff87d7, - 213: 0xff87ff, - 214: 0xffaf00, - 215: 0xffaf5f, - 216: 0xffaf87, - 217: 0xffafaf, - 218: 0xffafd7, - 219: 0xffafff, - 220: 0xffd700, - 221: 0xffd75f, - 222: 0xffd787, - 223: 0xffd7af, - 224: 0xffd7d7, - 225: 0xffd7ff, - 226: 0xffff00, - 227: 0xffff5f, - 228: 0xffff87, - 229: 0xffffaf, - 230: 0xffffd7, - 231: 0xffffff, - 232: 0x080808, - 233: 0x121212, - 234: 0x1c1c1c, - 235: 0x262626, - 236: 0x303030, - 237: 0x3a3a3a, - 238: 0x444444, - 239: 0x4e4e4e, - 240: 0x585858, - 241: 0x626262, - 242: 0x6c6c6c, - 243: 0x767676, - 244: 0x808080, - 245: 0x8a8a8a, - 246: 0x949494, - 247: 0x9e9e9e, - 248: 0xa8a8a8, - 249: 0xb2b2b2, - 250: 0xbcbcbc, - 251: 0xc6c6c6, - 252: 0xd0d0d0, - 253: 0xdadada, - 254: 0xe4e4e4, - 255: 0xeeeeee, -} - -// `\033]0;TITLESTR\007` -func doTitleSequence(er *bytes.Reader) error { - var c byte - var err error - - c, err = er.ReadByte() - if err != nil { - return err - } - if c != '0' && c != '2' { - return nil - } - c, err = er.ReadByte() - if err != nil { - return err - } - if c != ';' { - return nil - } - title := make([]byte, 0, 80) - for { - c, err = er.ReadByte() - if err != nil { - return err - } - if c == 0x07 || c == '\n' { - break - } - title = append(title, c) - } - if len(title) > 0 { - title8, err := syscall.UTF16PtrFromString(string(title)) - if err == nil { - procSetConsoleTitle.Call(uintptr(unsafe.Pointer(title8))) - } - } - return nil -} - -// Write write data on console -func (w *Writer) Write(data []byte) (n int, err error) { - var csbi consoleScreenBufferInfo - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - - er := bytes.NewReader(data) - var bw [1]byte -loop: - for { - c1, err := er.ReadByte() - if err != nil { - break loop - } - if c1 != 0x1b { - bw[0] = c1 - w.out.Write(bw[:]) - continue - } - c2, err := er.ReadByte() - if err != nil { - break loop - } - - if c2 == ']' { - if err := doTitleSequence(er); err != nil { - break loop - } - continue - } - if c2 != 0x5b { - continue - } - - var buf bytes.Buffer - var m byte - for { - c, err := er.ReadByte() - if err != nil { - break loop - } - if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '@' { - m = c - break - } - buf.Write([]byte(string(c))) - } - - switch m { - case 'A': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.y -= short(n) - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'B': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.y += short(n) - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'C': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.x += short(n) - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'D': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.x -= short(n) - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'E': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.x = 0 - csbi.cursorPosition.y += short(n) - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'F': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.x = 0 - csbi.cursorPosition.y -= short(n) - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'G': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.x = short(n - 1) - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'H', 'f': - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - if buf.Len() > 0 { - token := strings.Split(buf.String(), ";") - switch len(token) { - case 1: - n1, err := strconv.Atoi(token[0]) - if err != nil { - continue - } - csbi.cursorPosition.y = short(n1 - 1) - case 2: - n1, err := strconv.Atoi(token[0]) - if err != nil { - continue - } - n2, err := strconv.Atoi(token[1]) - if err != nil { - continue - } - csbi.cursorPosition.x = short(n2 - 1) - csbi.cursorPosition.y = short(n1 - 1) - } - } else { - csbi.cursorPosition.y = 0 - } - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'J': - n := 0 - if buf.Len() > 0 { - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - } - var count, written dword - var cursor coord - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - switch n { - case 0: - cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y} - count = dword(csbi.size.x - csbi.cursorPosition.x + (csbi.size.y-csbi.cursorPosition.y)*csbi.size.x) - case 1: - cursor = coord{x: csbi.window.left, y: csbi.window.top} - count = dword(csbi.size.x - csbi.cursorPosition.x + (csbi.window.top-csbi.cursorPosition.y)*csbi.size.x) - case 2: - cursor = coord{x: csbi.window.left, y: csbi.window.top} - count = dword(csbi.size.x - csbi.cursorPosition.x + (csbi.size.y-csbi.cursorPosition.y)*csbi.size.x) - } - procFillConsoleOutputCharacter.Call(uintptr(w.handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) - procFillConsoleOutputAttribute.Call(uintptr(w.handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) - case 'K': - n := 0 - if buf.Len() > 0 { - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - } - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - var cursor coord - var count, written dword - switch n { - case 0: - cursor = coord{x: csbi.cursorPosition.x + 1, y: csbi.cursorPosition.y} - count = dword(csbi.size.x - csbi.cursorPosition.x - 1) - case 1: - cursor = coord{x: csbi.window.left, y: csbi.window.top + csbi.cursorPosition.y} - count = dword(csbi.size.x - csbi.cursorPosition.x) - case 2: - cursor = coord{x: csbi.window.left, y: csbi.window.top + csbi.cursorPosition.y} - count = dword(csbi.size.x) - } - procFillConsoleOutputCharacter.Call(uintptr(w.handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) - procFillConsoleOutputAttribute.Call(uintptr(w.handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) - case 'm': - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - attr := csbi.attributes - cs := buf.String() - if cs == "" { - procSetConsoleTextAttribute.Call(uintptr(w.handle), uintptr(w.oldattr)) - continue - } - token := strings.Split(cs, ";") - for i := 0; i < len(token); i++ { - ns := token[i] - if n, err = strconv.Atoi(ns); err == nil { - switch { - case n == 0 || n == 100: - attr = w.oldattr - case 1 <= n && n <= 5: - attr |= foregroundIntensity - case n == 7: - attr = ((attr & foregroundMask) << 4) | ((attr & backgroundMask) >> 4) - case n == 22 || n == 25: - attr |= foregroundIntensity - case n == 27: - attr = ((attr & foregroundMask) << 4) | ((attr & backgroundMask) >> 4) - case 30 <= n && n <= 37: - attr &= backgroundMask - if (n-30)&1 != 0 { - attr |= foregroundRed - } - if (n-30)&2 != 0 { - attr |= foregroundGreen - } - if (n-30)&4 != 0 { - attr |= foregroundBlue - } - case n == 38: // set foreground color. - if i < len(token)-2 && (token[i+1] == "5" || token[i+1] == "05") { - if n256, err := strconv.Atoi(token[i+2]); err == nil { - if n256foreAttr == nil { - n256setup() - } - attr &= backgroundMask - attr |= n256foreAttr[n256] - i += 2 - } - } else { - attr = attr & (w.oldattr & backgroundMask) - } - case n == 39: // reset foreground color. - attr &= backgroundMask - attr |= w.oldattr & foregroundMask - case 40 <= n && n <= 47: - attr &= foregroundMask - if (n-40)&1 != 0 { - attr |= backgroundRed - } - if (n-40)&2 != 0 { - attr |= backgroundGreen - } - if (n-40)&4 != 0 { - attr |= backgroundBlue - } - case n == 48: // set background color. - if i < len(token)-2 && token[i+1] == "5" { - if n256, err := strconv.Atoi(token[i+2]); err == nil { - if n256backAttr == nil { - n256setup() - } - attr &= foregroundMask - attr |= n256backAttr[n256] - i += 2 - } - } else { - attr = attr & (w.oldattr & foregroundMask) - } - case n == 49: // reset foreground color. - attr &= foregroundMask - attr |= w.oldattr & backgroundMask - case 90 <= n && n <= 97: - attr = (attr & backgroundMask) - attr |= foregroundIntensity - if (n-90)&1 != 0 { - attr |= foregroundRed - } - if (n-90)&2 != 0 { - attr |= foregroundGreen - } - if (n-90)&4 != 0 { - attr |= foregroundBlue - } - case 100 <= n && n <= 107: - attr = (attr & foregroundMask) - attr |= backgroundIntensity - if (n-100)&1 != 0 { - attr |= backgroundRed - } - if (n-100)&2 != 0 { - attr |= backgroundGreen - } - if (n-100)&4 != 0 { - attr |= backgroundBlue - } - } - procSetConsoleTextAttribute.Call(uintptr(w.handle), uintptr(attr)) - } - } - case 'h': - var ci consoleCursorInfo - cs := buf.String() - if cs == "5>" { - procGetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) - ci.visible = 0 - procSetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) - } else if cs == "?25" { - procGetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) - ci.visible = 1 - procSetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) - } - case 'l': - var ci consoleCursorInfo - cs := buf.String() - if cs == "5>" { - procGetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) - ci.visible = 1 - procSetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) - } else if cs == "?25" { - procGetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) - ci.visible = 0 - procSetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) - } - case 's': - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - w.oldpos = csbi.cursorPosition - case 'u': - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&w.oldpos))) - } - } - - return len(data), nil -} - -type consoleColor struct { - rgb int - red bool - green bool - blue bool - intensity bool -} - -func (c consoleColor) foregroundAttr() (attr word) { - if c.red { - attr |= foregroundRed - } - if c.green { - attr |= foregroundGreen - } - if c.blue { - attr |= foregroundBlue - } - if c.intensity { - attr |= foregroundIntensity - } - return -} - -func (c consoleColor) backgroundAttr() (attr word) { - if c.red { - attr |= backgroundRed - } - if c.green { - attr |= backgroundGreen - } - if c.blue { - attr |= backgroundBlue - } - if c.intensity { - attr |= backgroundIntensity - } - return -} - -var color16 = []consoleColor{ - {0x000000, false, false, false, false}, - {0x000080, false, false, true, false}, - {0x008000, false, true, false, false}, - {0x008080, false, true, true, false}, - {0x800000, true, false, false, false}, - {0x800080, true, false, true, false}, - {0x808000, true, true, false, false}, - {0xc0c0c0, true, true, true, false}, - {0x808080, false, false, false, true}, - {0x0000ff, false, false, true, true}, - {0x00ff00, false, true, false, true}, - {0x00ffff, false, true, true, true}, - {0xff0000, true, false, false, true}, - {0xff00ff, true, false, true, true}, - {0xffff00, true, true, false, true}, - {0xffffff, true, true, true, true}, -} - -type hsv struct { - h, s, v float32 -} - -func (a hsv) dist(b hsv) float32 { - dh := a.h - b.h - switch { - case dh > 0.5: - dh = 1 - dh - case dh < -0.5: - dh = -1 - dh - } - ds := a.s - b.s - dv := a.v - b.v - return float32(math.Sqrt(float64(dh*dh + ds*ds + dv*dv))) -} - -func toHSV(rgb int) hsv { - r, g, b := float32((rgb&0xFF0000)>>16)/256.0, - float32((rgb&0x00FF00)>>8)/256.0, - float32(rgb&0x0000FF)/256.0 - min, max := minmax3f(r, g, b) - h := max - min - if h > 0 { - if max == r { - h = (g - b) / h - if h < 0 { - h += 6 - } - } else if max == g { - h = 2 + (b-r)/h - } else { - h = 4 + (r-g)/h - } - } - h /= 6.0 - s := max - min - if max != 0 { - s /= max - } - v := max - return hsv{h: h, s: s, v: v} -} - -type hsvTable []hsv - -func toHSVTable(rgbTable []consoleColor) hsvTable { - t := make(hsvTable, len(rgbTable)) - for i, c := range rgbTable { - t[i] = toHSV(c.rgb) - } - return t -} - -func (t hsvTable) find(rgb int) consoleColor { - hsv := toHSV(rgb) - n := 7 - l := float32(5.0) - for i, p := range t { - d := hsv.dist(p) - if d < l { - l, n = d, i - } - } - return color16[n] -} - -func minmax3f(a, b, c float32) (min, max float32) { - if a < b { - if b < c { - return a, c - } else if a < c { - return a, b - } else { - return c, b - } - } else { - if a < c { - return b, c - } else if b < c { - return b, a - } else { - return c, a - } - } -} - -var n256foreAttr []word -var n256backAttr []word - -func n256setup() { - n256foreAttr = make([]word, 256) - n256backAttr = make([]word, 256) - t := toHSVTable(color16) - for i, rgb := range color256 { - c := t.find(rgb) - n256foreAttr[i] = c.foregroundAttr() - n256backAttr[i] = c.backgroundAttr() - } -} diff --git a/vendor/github.com/mattn/go-colorable/noncolorable.go b/vendor/github.com/mattn/go-colorable/noncolorable.go deleted file mode 100644 index 9721e16f..00000000 --- a/vendor/github.com/mattn/go-colorable/noncolorable.go +++ /dev/null @@ -1,55 +0,0 @@ -package colorable - -import ( - "bytes" - "io" -) - -// NonColorable hold writer but remove escape sequence. -type NonColorable struct { - out io.Writer -} - -// NewNonColorable return new instance of Writer which remove escape sequence from Writer. -func NewNonColorable(w io.Writer) io.Writer { - return &NonColorable{out: w} -} - -// Write write data on console -func (w *NonColorable) Write(data []byte) (n int, err error) { - er := bytes.NewReader(data) - var bw [1]byte -loop: - for { - c1, err := er.ReadByte() - if err != nil { - break loop - } - if c1 != 0x1b { - bw[0] = c1 - w.out.Write(bw[:]) - continue - } - c2, err := er.ReadByte() - if err != nil { - break loop - } - if c2 != 0x5b { - continue - } - - var buf bytes.Buffer - for { - c, err := er.ReadByte() - if err != nil { - break loop - } - if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '@' { - break - } - buf.Write([]byte(string(c))) - } - } - - return len(data), nil -} diff --git a/vendor/github.com/mattn/go-isatty/LICENSE b/vendor/github.com/mattn/go-isatty/LICENSE deleted file mode 100644 index 65dc692b..00000000 --- a/vendor/github.com/mattn/go-isatty/LICENSE +++ /dev/null @@ -1,9 +0,0 @@ -Copyright (c) Yasuhiro MATSUMOTO - -MIT License (Expat) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/mattn/go-isatty/doc.go b/vendor/github.com/mattn/go-isatty/doc.go deleted file mode 100644 index 17d4f90e..00000000 --- a/vendor/github.com/mattn/go-isatty/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package isatty implements interface to isatty -package isatty diff --git a/vendor/github.com/mattn/go-isatty/isatty_appengine.go b/vendor/github.com/mattn/go-isatty/isatty_appengine.go deleted file mode 100644 index 9584a988..00000000 --- a/vendor/github.com/mattn/go-isatty/isatty_appengine.go +++ /dev/null @@ -1,15 +0,0 @@ -// +build appengine - -package isatty - -// IsTerminal returns true if the file descriptor is terminal which -// is always false on on appengine classic which is a sandboxed PaaS. -func IsTerminal(fd uintptr) bool { - return false -} - -// IsCygwinTerminal() return true if the file descriptor is a cygwin or msys2 -// terminal. This is also always false on this environment. -func IsCygwinTerminal(fd uintptr) bool { - return false -} diff --git a/vendor/github.com/mattn/go-isatty/isatty_bsd.go b/vendor/github.com/mattn/go-isatty/isatty_bsd.go deleted file mode 100644 index 42f2514d..00000000 --- a/vendor/github.com/mattn/go-isatty/isatty_bsd.go +++ /dev/null @@ -1,18 +0,0 @@ -// +build darwin freebsd openbsd netbsd dragonfly -// +build !appengine - -package isatty - -import ( - "syscall" - "unsafe" -) - -const ioctlReadTermios = syscall.TIOCGETA - -// IsTerminal return true if the file descriptor is terminal. -func IsTerminal(fd uintptr) bool { - var termios syscall.Termios - _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) - return err == 0 -} diff --git a/vendor/github.com/mattn/go-isatty/isatty_linux.go b/vendor/github.com/mattn/go-isatty/isatty_linux.go deleted file mode 100644 index 7384cf99..00000000 --- a/vendor/github.com/mattn/go-isatty/isatty_linux.go +++ /dev/null @@ -1,18 +0,0 @@ -// +build linux -// +build !appengine,!ppc64,!ppc64le - -package isatty - -import ( - "syscall" - "unsafe" -) - -const ioctlReadTermios = syscall.TCGETS - -// IsTerminal return true if the file descriptor is terminal. -func IsTerminal(fd uintptr) bool { - var termios syscall.Termios - _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) - return err == 0 -} diff --git a/vendor/github.com/mattn/go-isatty/isatty_linux_ppc64x.go b/vendor/github.com/mattn/go-isatty/isatty_linux_ppc64x.go deleted file mode 100644 index 44e5d213..00000000 --- a/vendor/github.com/mattn/go-isatty/isatty_linux_ppc64x.go +++ /dev/null @@ -1,19 +0,0 @@ -// +build linux -// +build ppc64 ppc64le - -package isatty - -import ( - "unsafe" - - syscall "golang.org/x/sys/unix" -) - -const ioctlReadTermios = syscall.TCGETS - -// IsTerminal return true if the file descriptor is terminal. -func IsTerminal(fd uintptr) bool { - var termios syscall.Termios - _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) - return err == 0 -} diff --git a/vendor/github.com/mattn/go-isatty/isatty_others.go b/vendor/github.com/mattn/go-isatty/isatty_others.go deleted file mode 100644 index ff4de3d9..00000000 --- a/vendor/github.com/mattn/go-isatty/isatty_others.go +++ /dev/null @@ -1,10 +0,0 @@ -// +build !windows -// +build !appengine - -package isatty - -// IsCygwinTerminal() return true if the file descriptor is a cygwin or msys2 -// terminal. This is also always false on this environment. -func IsCygwinTerminal(fd uintptr) bool { - return false -} diff --git a/vendor/github.com/mattn/go-isatty/isatty_solaris.go b/vendor/github.com/mattn/go-isatty/isatty_solaris.go deleted file mode 100644 index 1f0c6bf5..00000000 --- a/vendor/github.com/mattn/go-isatty/isatty_solaris.go +++ /dev/null @@ -1,16 +0,0 @@ -// +build solaris -// +build !appengine - -package isatty - -import ( - "golang.org/x/sys/unix" -) - -// IsTerminal returns true if the given file descriptor is a terminal. -// see: http://src.illumos.org/source/xref/illumos-gate/usr/src/lib/libbc/libc/gen/common/isatty.c -func IsTerminal(fd uintptr) bool { - var termio unix.Termio - err := unix.IoctlSetTermio(int(fd), unix.TCGETA, &termio) - return err == nil -} diff --git a/vendor/github.com/mattn/go-isatty/isatty_windows.go b/vendor/github.com/mattn/go-isatty/isatty_windows.go deleted file mode 100644 index af51cbca..00000000 --- a/vendor/github.com/mattn/go-isatty/isatty_windows.go +++ /dev/null @@ -1,94 +0,0 @@ -// +build windows -// +build !appengine - -package isatty - -import ( - "strings" - "syscall" - "unicode/utf16" - "unsafe" -) - -const ( - fileNameInfo uintptr = 2 - fileTypePipe = 3 -) - -var ( - kernel32 = syscall.NewLazyDLL("kernel32.dll") - procGetConsoleMode = kernel32.NewProc("GetConsoleMode") - procGetFileInformationByHandleEx = kernel32.NewProc("GetFileInformationByHandleEx") - procGetFileType = kernel32.NewProc("GetFileType") -) - -func init() { - // Check if GetFileInformationByHandleEx is available. - if procGetFileInformationByHandleEx.Find() != nil { - procGetFileInformationByHandleEx = nil - } -} - -// IsTerminal return true if the file descriptor is terminal. -func IsTerminal(fd uintptr) bool { - var st uint32 - r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, fd, uintptr(unsafe.Pointer(&st)), 0) - return r != 0 && e == 0 -} - -// Check pipe name is used for cygwin/msys2 pty. -// Cygwin/MSYS2 PTY has a name like: -// \{cygwin,msys}-XXXXXXXXXXXXXXXX-ptyN-{from,to}-master -func isCygwinPipeName(name string) bool { - token := strings.Split(name, "-") - if len(token) < 5 { - return false - } - - if token[0] != `\msys` && token[0] != `\cygwin` { - return false - } - - if token[1] == "" { - return false - } - - if !strings.HasPrefix(token[2], "pty") { - return false - } - - if token[3] != `from` && token[3] != `to` { - return false - } - - if token[4] != "master" { - return false - } - - return true -} - -// IsCygwinTerminal() return true if the file descriptor is a cygwin or msys2 -// terminal. -func IsCygwinTerminal(fd uintptr) bool { - if procGetFileInformationByHandleEx == nil { - return false - } - - // Cygwin/msys's pty is a pipe. - ft, _, e := syscall.Syscall(procGetFileType.Addr(), 1, fd, 0, 0) - if ft != fileTypePipe || e != 0 { - return false - } - - var buf [2 + syscall.MAX_PATH]uint16 - r, _, e := syscall.Syscall6(procGetFileInformationByHandleEx.Addr(), - 4, fd, fileNameInfo, uintptr(unsafe.Pointer(&buf)), - uintptr(len(buf)*2), 0, 0) - if r == 0 || e != 0 { - return false - } - - l := *(*uint32)(unsafe.Pointer(&buf)) - return isCygwinPipeName(string(utf16.Decode(buf[2 : 2+l/2]))) -} diff --git a/vendor/github.com/prometheus/prometheus/LICENSE b/vendor/github.com/prometheus/prometheus/LICENSE deleted file mode 100644 index 261eeb9e..00000000 --- a/vendor/github.com/prometheus/prometheus/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/vendor/github.com/prometheus/prometheus/NOTICE b/vendor/github.com/prometheus/prometheus/NOTICE deleted file mode 100644 index 2e141355..00000000 --- a/vendor/github.com/prometheus/prometheus/NOTICE +++ /dev/null @@ -1,87 +0,0 @@ -The Prometheus systems and service monitoring server -Copyright 2012-2015 The Prometheus Authors - -This product includes software developed at -SoundCloud Ltd. (http://soundcloud.com/). - - -The following components are included in this product: - -Bootstrap -http://getbootstrap.com -Copyright 2011-2014 Twitter, Inc. -Licensed under the MIT License - -bootstrap3-typeahead.js -https://github.com/bassjobsen/Bootstrap-3-Typeahead -Original written by @mdo and @fat -Copyright 2014 Bass Jobsen @bassjobsen -Licensed under the Apache License, Version 2.0 - -fuzzy -https://github.com/mattyork/fuzzy -Original written by @mattyork -Copyright 2012 Matt York -Licensed under the MIT License - -bootstrap-datetimepicker.js -https://github.com/Eonasdan/bootstrap-datetimepicker -Copyright 2015 Jonathan Peterson (@Eonasdan) -Licensed under the MIT License - -moment.js -https://github.com/moment/moment/ -Copyright JS Foundation and other contributors -Licensed under the MIT License - -Rickshaw -https://github.com/shutterstock/rickshaw -Copyright 2011-2014 by Shutterstock Images, LLC -See https://github.com/shutterstock/rickshaw/blob/master/LICENSE for license details - -mustache.js -https://github.com/janl/mustache.js -Copyright 2009 Chris Wanstrath (Ruby) -Copyright 2010-2014 Jan Lehnardt (JavaScript) -Copyright 2010-2015 The mustache.js community -Licensed under the MIT License - -jQuery -https://jquery.org -Copyright jQuery Foundation and other contributors -Licensed under the MIT License - -Protocol Buffers for Go with Gadgets -http://github.com/gogo/protobuf/ -Copyright (c) 2013, The GoGo Authors. -See source code for license details. - -Go support for leveled logs, analogous to -https://code.google.com/p/google-glog/ -Copyright 2013 Google Inc. -Licensed under the Apache License, Version 2.0 - -Support for streaming Protocol Buffer messages for the Go language (golang). -https://github.com/matttproud/golang_protobuf_extensions -Copyright 2013 Matt T. Proud -Licensed under the Apache License, Version 2.0 - -DNS library in Go -http://miek.nl/posts/2014/Aug/16/go-dns-package/ -Copyright 2009 The Go Authors, 2011 Miek Gieben -See https://github.com/miekg/dns/blob/master/LICENSE for license details. - -LevelDB key/value database in Go -https://github.com/syndtr/goleveldb -Copyright 2012 Suryandaru Triandana -See https://github.com/syndtr/goleveldb/blob/master/LICENSE for license details. - -gosnappy - a fork of code.google.com/p/snappy-go -https://github.com/syndtr/gosnappy -Copyright 2011 The Snappy-Go Authors -See https://github.com/syndtr/gosnappy/blob/master/LICENSE for license details. - -go-zookeeper - Native ZooKeeper client for Go -https://github.com/samuel/go-zookeeper -Copyright (c) 2013, Samuel Stauffer -See https://github.com/samuel/go-zookeeper/blob/master/LICENSE for license details. diff --git a/vendor/github.com/prometheus/prometheus/util/flock/flock.go b/vendor/github.com/prometheus/prometheus/util/flock/flock.go deleted file mode 100644 index 5dc22a2f..00000000 --- a/vendor/github.com/prometheus/prometheus/util/flock/flock.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2016 The Prometheus Authors -// 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 flock provides portable file locking. It is essentially ripped out -// from the code of github.com/syndtr/goleveldb. Strange enough that the -// standard library does not provide this functionality. Once this package has -// proven to work as expected, we should probably turn it into a separate -// general purpose package for humanity. -package flock - -import ( - "os" - "path/filepath" -) - -// Releaser provides the Release method to release a file lock. -type Releaser interface { - Release() error -} - -// New locks the file with the provided name. If the file does not exist, it is -// created. The returned Releaser is used to release the lock. existed is true -// if the file to lock already existed. A non-nil error is returned if the -// locking has failed. Neither this function nor the returned Releaser is -// goroutine-safe. -func New(fileName string) (r Releaser, existed bool, err error) { - if err = os.MkdirAll(filepath.Dir(fileName), 0755); err != nil { - return - } - - _, err = os.Stat(fileName) - existed = err == nil - - r, err = newLock(fileName) - return -} diff --git a/vendor/github.com/prometheus/prometheus/util/flock/flock_plan9.go b/vendor/github.com/prometheus/prometheus/util/flock/flock_plan9.go deleted file mode 100644 index 004e85c0..00000000 --- a/vendor/github.com/prometheus/prometheus/util/flock/flock_plan9.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2016 The Prometheus Authors -// 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 flock - -import "os" - -type plan9Lock struct { - f *os.File -} - -func (l *plan9Lock) Release() error { - return l.f.Close() -} - -func newLock(fileName string) (Releaser, error) { - f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, os.ModeExclusive|0644) - if err != nil { - return nil, err - } - return &plan9Lock{f}, nil -} diff --git a/vendor/github.com/prometheus/prometheus/util/flock/flock_solaris.go b/vendor/github.com/prometheus/prometheus/util/flock/flock_solaris.go deleted file mode 100644 index 299fc874..00000000 --- a/vendor/github.com/prometheus/prometheus/util/flock/flock_solaris.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2016 The Prometheus Authors -// 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. - -// +build solaris - -package flock - -import ( - "os" - "syscall" -) - -type unixLock struct { - f *os.File -} - -func (l *unixLock) Release() error { - if err := l.set(false); err != nil { - return err - } - return l.f.Close() -} - -func (l *unixLock) set(lock bool) error { - flock := syscall.Flock_t{ - Type: syscall.F_UNLCK, - Start: 0, - Len: 0, - Whence: 1, - } - if lock { - flock.Type = syscall.F_WRLCK - } - return syscall.FcntlFlock(l.f.Fd(), syscall.F_SETLK, &flock) -} - -func newLock(fileName string) (Releaser, error) { - f, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE, 0644) - if err != nil { - return nil, err - } - l := &unixLock{f} - err = l.set(true) - if err != nil { - f.Close() - return nil, err - } - return l, nil -} diff --git a/vendor/github.com/prometheus/prometheus/util/flock/flock_unix.go b/vendor/github.com/prometheus/prometheus/util/flock/flock_unix.go deleted file mode 100644 index 7d71f8fc..00000000 --- a/vendor/github.com/prometheus/prometheus/util/flock/flock_unix.go +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2016 The Prometheus Authors -// 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. - -// +build darwin dragonfly freebsd linux netbsd openbsd - -package flock - -import ( - "os" - "syscall" -) - -type unixLock struct { - f *os.File -} - -func (l *unixLock) Release() error { - if err := l.set(false); err != nil { - return err - } - return l.f.Close() -} - -func (l *unixLock) set(lock bool) error { - how := syscall.LOCK_UN - if lock { - how = syscall.LOCK_EX - } - return syscall.Flock(int(l.f.Fd()), how|syscall.LOCK_NB) -} - -func newLock(fileName string) (Releaser, error) { - f, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE, 0644) - if err != nil { - return nil, err - } - l := &unixLock{f} - err = l.set(true) - if err != nil { - f.Close() - return nil, err - } - return l, nil -} diff --git a/vendor/github.com/prometheus/prometheus/util/flock/flock_windows.go b/vendor/github.com/prometheus/prometheus/util/flock/flock_windows.go deleted file mode 100644 index bf7266f1..00000000 --- a/vendor/github.com/prometheus/prometheus/util/flock/flock_windows.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2016 The Prometheus Authors -// 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 flock - -import "syscall" - -type windowsLock struct { - fd syscall.Handle -} - -func (fl *windowsLock) Release() error { - return syscall.Close(fl.fd) -} - -func newLock(fileName string) (Releaser, error) { - pathp, err := syscall.UTF16PtrFromString(fileName) - if err != nil { - return nil, err - } - fd, err := syscall.CreateFile(pathp, syscall.GENERIC_READ|syscall.GENERIC_WRITE, 0, nil, syscall.CREATE_ALWAYS, syscall.FILE_ATTRIBUTE_NORMAL, 0) - if err != nil { - return nil, err - } - return &windowsLock{fd}, nil -} diff --git a/vendor/gopkg.in/olebedev/go-duktape.v3/LICENSE.md b/vendor/gopkg.in/olebedev/go-duktape.v3/LICENSE.md deleted file mode 100644 index 785c8530..00000000 --- a/vendor/gopkg.in/olebedev/go-duktape.v3/LICENSE.md +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Oleg Lebedev - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/gopkg.in/olebedev/go-duktape.v3/api.go b/vendor/gopkg.in/olebedev/go-duktape.v3/api.go deleted file mode 100644 index 924b5c32..00000000 --- a/vendor/gopkg.in/olebedev/go-duktape.v3/api.go +++ /dev/null @@ -1,1616 +0,0 @@ -package duktape - -/* -#cgo !windows CFLAGS: -std=c99 -O3 -Wall -Wno-unused-value -fomit-frame-pointer -fstrict-aliasing -#cgo windows CFLAGS: -O3 -Wall -Wno-unused-value -fomit-frame-pointer -fstrict-aliasing - -#include "duktape.h" -#include "duk_logging.h" -#include "duk_v1_compat.h" -#include "duk_print_alert.h" -static void _duk_eval_string(duk_context *ctx, const char *str) { - duk_eval_string(ctx, str); -} -static void _duk_compile(duk_context *ctx, duk_uint_t flags) { - duk_compile(ctx, flags); -} -static void _duk_compile_file(duk_context *ctx, duk_uint_t flags, const char *path) { - duk_compile_file(ctx, flags, path); -} -static void _duk_compile_lstring(duk_context *ctx, duk_uint_t flags, const char *src, duk_size_t len) { - duk_compile_lstring(ctx, flags, src, len); -} -static void _duk_compile_lstring_filename(duk_context *ctx, duk_uint_t flags, const char *src, duk_size_t len) { - duk_compile_lstring_filename(ctx, flags, src, len); -} -static void _duk_compile_string(duk_context *ctx, duk_uint_t flags, const char *src) { - duk_compile_string(ctx, flags, src); -} -static void _duk_compile_string_filename(duk_context *ctx, duk_uint_t flags, const char *src) { - duk_compile_string_filename(ctx, flags, src); -} -static void _duk_dump_context_stderr(duk_context *ctx) { - duk_dump_context_stderr(ctx); -} -static void _duk_dump_context_stdout(duk_context *ctx) { - duk_dump_context_stdout(ctx); -} -static void _duk_eval(duk_context *ctx) { - duk_eval(ctx); -} -static void _duk_eval_file(duk_context *ctx, const char *path) { - duk_eval_file(ctx, path); -} -static void _duk_eval_file_noresult(duk_context *ctx, const char *path) { - duk_eval_file_noresult(ctx, path); -} -static void _duk_eval_lstring(duk_context *ctx, const char *src, duk_size_t len) { - duk_eval_lstring(ctx, src, len); -} -static void _duk_eval_lstring_noresult(duk_context *ctx, const char *src, duk_size_t len) { - duk_eval_lstring_noresult(ctx, src, len); -} -static void _duk_eval_noresult(duk_context *ctx) { - duk_eval_noresult(ctx); -} -static void _duk_eval_string_noresult(duk_context *ctx, const char *src) { - duk_eval_string_noresult(ctx, src); -} -static duk_bool_t _duk_is_error(duk_context *ctx, duk_idx_t index) { - return duk_is_error(ctx, index); -} -static duk_bool_t _duk_is_object_coercible(duk_context *ctx, duk_idx_t index) { - return duk_is_object_coercible(ctx, index); -} -static duk_int_t _duk_pcompile(duk_context *ctx, duk_uint_t flags) { - return duk_pcompile(ctx, flags); -} -static duk_int_t _duk_pcompile_file(duk_context *ctx, duk_uint_t flags, const char *path) { - return duk_pcompile_file(ctx, flags, path); -} -static duk_int_t _duk_pcompile_lstring(duk_context *ctx, duk_uint_t flags, const char *src, duk_size_t len) { - return duk_pcompile_lstring(ctx, flags, src, len); -} -static duk_int_t _duk_pcompile_lstring_filename(duk_context *ctx, duk_uint_t flags, const char *src, duk_size_t len) { - return duk_pcompile_lstring_filename(ctx, flags, src, len); -} -static duk_int_t _duk_pcompile_string(duk_context *ctx, duk_uint_t flags, const char *src) { - return duk_pcompile_string(ctx, flags, src); -} -static duk_int_t _duk_pcompile_string_filename(duk_context *ctx, duk_uint_t flags, const char *src) { - return duk_pcompile_string_filename(ctx, flags, src); -} -static duk_int_t _duk_peval(duk_context *ctx) { - return duk_peval(ctx); -} -static duk_int_t _duk_peval_file(duk_context *ctx, const char *path) { - return duk_peval_file(ctx, path); -} -static duk_int_t _duk_peval_file_noresult(duk_context *ctx, const char *path) { - return duk_peval_file_noresult(ctx, path); -} -static duk_int_t _duk_peval_lstring(duk_context *ctx, const char *src, duk_size_t len) { - return duk_peval_lstring(ctx, src, len); -} -static duk_int_t _duk_peval_lstring_noresult(duk_context *ctx, const char *src, duk_size_t len) { - return duk_peval_lstring_noresult(ctx, src, len); -} -static duk_int_t _duk_peval_noresult(duk_context *ctx) { - return duk_peval_noresult(ctx); -} -static duk_int_t _duk_peval_string(duk_context *ctx, const char *src) { - return duk_peval_string(ctx, src); -} -static duk_int_t _duk_peval_string_noresult(duk_context *ctx, const char *src) { - return duk_peval_string_noresult(ctx, src); -} -static const char *_duk_push_string_file(duk_context *ctx, const char *path) { - return duk_push_string_file(ctx, path); -} -static duk_idx_t _duk_push_thread(duk_context *ctx) { - return duk_push_thread(ctx); -} -static duk_idx_t _duk_push_thread_new_globalenv(duk_context *ctx) { - return duk_push_thread_new_globalenv(ctx); -} -static void _duk_require_object_coercible(duk_context *ctx, duk_idx_t index) { - duk_require_object_coercible(ctx, index); -} -static void _duk_require_type_mask(duk_context *ctx, duk_idx_t index, duk_uint_t mask) { - duk_require_type_mask(ctx, index, mask); -} -static const char *_duk_safe_to_string(duk_context *ctx, duk_idx_t index) { - return duk_safe_to_string(ctx, index); -} -static void _duk_xcopy_top(duk_context *to_ctx, duk_context *from_ctx, duk_idx_t count) { - duk_xcopy_top(to_ctx, from_ctx, count); -} -static void _duk_xmove_top(duk_context *to_ctx, duk_context *from_ctx, duk_idx_t count) { - duk_xmove_top(to_ctx, from_ctx, count); -} -static void *_duk_to_buffer(duk_context *ctx, duk_idx_t index, duk_size_t *out_size) { - return duk_to_buffer(ctx, index, out_size); -} -static void *_duk_to_dynamic_buffer(duk_context *ctx, duk_idx_t index, duk_size_t *out_size) { - return duk_to_dynamic_buffer(ctx, index, out_size); -} -static void *_duk_to_fixed_buffer(duk_context *ctx, duk_idx_t index, duk_size_t *out_size) { - return duk_to_fixed_buffer(ctx, index, out_size); -} -static duk_int_t _duk_is_primitive(duk_context *ctx, duk_idx_t index) { - return duk_is_primitive(ctx, index); -} -static void *_duk_push_buffer(duk_context *ctx, duk_size_t size, duk_bool_t dynamic) { - return duk_push_buffer(ctx, size, dynamic); -} -static void *_duk_push_fixed_buffer(duk_context *ctx, duk_size_t size) { - return duk_push_fixed_buffer(ctx, size); -} -static void *_duk_push_dynamic_buffer(duk_context *ctx, duk_size_t size) { - return duk_push_dynamic_buffer(ctx, size); -} -static void _duk_error(duk_context *ctx, duk_errcode_t err_code, const char *str) { - duk_error(ctx, err_code, "%s", str); -} -static void _duk_push_error_object(duk_context *ctx, duk_errcode_t err_code, const char *str) { - duk_push_error_object(ctx, err_code, "%s", str); -} -static void _duk_error_raw(duk_context *ctx, duk_errcode_t err_code, const char *filename, duk_int_t line, const char *text) { - duk_error_raw(ctx, err_code, filename, line, text); -} -static void _duk_log(duk_context *ctx, duk_int_t level, const char *str) { - duk_log(ctx, level, "%s", str); -} -static void _duk_push_external_buffer(duk_context *ctx) { - duk_push_external_buffer(ctx); -} -*/ -import "C" -import ( - "fmt" - "unsafe" -) - -// See: http://duktape.org/api.html#duk_alloc -func (d *Context) Alloc(size int) unsafe.Pointer { - return C.duk_alloc(d.duk_context, C.duk_size_t(size)) -} - -// See: http://duktape.org/api.html#duk_alloc_raw -func (d *Context) AllocRaw(size int) unsafe.Pointer { - return C.duk_alloc_raw(d.duk_context, C.duk_size_t(size)) -} - -// See: http://duktape.org/api.html#duk_base64_decode -func (d *Context) Base64Decode(index int) { - C.duk_base64_decode(d.duk_context, C.duk_idx_t(index)) -} - -// See: http://duktape.org/api.html#duk_base64_encode -func (d *Context) Base64Encode(index int) string { - if s := C.duk_base64_encode(d.duk_context, C.duk_idx_t(index)); s != nil { - return C.GoString(s) - } - return "" -} - -// See: http://duktape.org/api.html#duk_call -func (d *Context) Call(nargs int) { - C.duk_call(d.duk_context, C.duk_idx_t(nargs)) -} - -// See: http://duktape.org/api.html#duk_call_method -func (d *Context) CallMethod(nargs int) { - C.duk_call_method(d.duk_context, C.duk_idx_t(nargs)) -} - -// See: http://duktape.org/api.html#duk_call_prop -func (d *Context) CallProp(objIndex int, nargs int) { - C.duk_call_prop(d.duk_context, C.duk_idx_t(objIndex), C.duk_idx_t(nargs)) -} - -// See: http://duktape.org/api.html#duk_check_stack -func (d *Context) CheckStack(extra int) bool { - return int(C.duk_check_stack(d.duk_context, C.duk_idx_t(extra))) == 1 -} - -// See: http://duktape.org/api.html#duk_check_stack_top -func (d *Context) CheckStackTop(top int) bool { - return int(C.duk_check_stack_top(d.duk_context, C.duk_idx_t(top))) == 1 -} - -// See: http://duktape.org/api.html#duk_check_type -func (d *Context) CheckType(index int, typ int) bool { - return int(C.duk_check_type(d.duk_context, C.duk_idx_t(index), C.duk_int_t(typ))) == 1 -} - -// See: http://duktape.org/api.html#duk_check_type_mask -func (d *Context) CheckTypeMask(index int, mask uint) bool { - return int(C.duk_check_type_mask(d.duk_context, C.duk_idx_t(index), C.duk_uint_t(mask))) == 1 -} - -// See: http://duktape.org/api.html#duk_compact -func (d *Context) Compact(objIndex int) { - C.duk_compact(d.duk_context, C.duk_idx_t(objIndex)) -} - -// See: http://duktape.org/api.html#duk_compile -func (d *Context) Compile(flags uint) { - C._duk_compile(d.duk_context, C.duk_uint_t(flags)) -} - -// See: http://duktape.org/api.html#duk_compile_file -func (d *Context) CompileFile(flags uint, path string) { - __path__ := C.CString(path) - C._duk_compile_file(d.duk_context, C.duk_uint_t(flags), __path__) - C.free(unsafe.Pointer(__path__)) -} - -// See: http://duktape.org/api.html#duk_compile_lstring -func (d *Context) CompileLstring(flags uint, src string, len int) { - __src__ := C.CString(src) - C._duk_compile_lstring(d.duk_context, C.duk_uint_t(flags), __src__, C.duk_size_t(len)) - C.free(unsafe.Pointer(__src__)) -} - -// See: http://duktape.org/api.html#duk_compile_lstring_filename -func (d *Context) CompileLstringFilename(flags uint, src string, len int) { - __src__ := C.CString(src) - C._duk_compile_lstring_filename(d.duk_context, C.duk_uint_t(flags), __src__, C.duk_size_t(len)) - C.free(unsafe.Pointer(__src__)) -} - -// See: http://duktape.org/api.html#duk_compile_string -func (d *Context) CompileString(flags uint, src string) { - __src__ := C.CString(src) - C._duk_compile_string(d.duk_context, C.duk_uint_t(flags), __src__) - C.free(unsafe.Pointer(__src__)) -} - -// See: http://duktape.org/api.html#duk_compile_string_filename -func (d *Context) CompileStringFilename(flags uint, src string) { - __src__ := C.CString(src) - C._duk_compile_string_filename(d.duk_context, C.duk_uint_t(flags), __src__) - C.free(unsafe.Pointer(__src__)) -} - -// See: http://duktape.org/api.html#duk_concat -func (d *Context) Concat(count int) { - C.duk_concat(d.duk_context, C.duk_idx_t(count)) -} - -// See: http://duktape.org/api.html#duk_copy -func (d *Context) Copy(fromIndex int, toIndex int) { - C.duk_copy(d.duk_context, C.duk_idx_t(fromIndex), C.duk_idx_t(toIndex)) -} - -// See: http://duktape.org/api.html#duk_del_prop -func (d *Context) DelProp(objIndex int) bool { - return int(C.duk_del_prop(d.duk_context, C.duk_idx_t(objIndex))) == 1 -} - -// See: http://duktape.org/api.html#duk_del_prop_index -func (d *Context) DelPropIndex(objIndex int, arrIndex uint) bool { - return int(C.duk_del_prop_index(d.duk_context, C.duk_idx_t(objIndex), C.duk_uarridx_t(arrIndex))) == 1 -} - -// See: http://duktape.org/api.html#duk_del_prop_string -func (d *Context) DelPropString(objIndex int, key string) bool { - __key__ := C.CString(key) - result := int(C.duk_del_prop_string(d.duk_context, C.duk_idx_t(objIndex), __key__)) == 1 - C.free(unsafe.Pointer(__key__)) - return result -} - -// See: http://duktape.org/api.html#duk_def_prop -func (d *Context) DefProp(objIndex int, flags uint) { - C.duk_def_prop(d.duk_context, C.duk_idx_t(objIndex), C.duk_uint_t(flags)) -} - -// See: http://duktape.org/api.html#duk_destroy_heap -func (d *Context) DestroyHeap() { - d.Gc(0) - C.duk_destroy_heap(d.duk_context) - d.duk_context = nil -} - -// See: http://duktape.org/api.html#duk_dump_context_stderr -func (d *Context) DumpContextStderr() { - C._duk_dump_context_stderr(d.duk_context) -} - -// See: http://duktape.org/api.html#duk_dump_context_stdout -func (d *Context) DumpContextStdout() { - C._duk_dump_context_stdout(d.duk_context) -} - -// See: http://duktape.org/api.html#duk_dup -func (d *Context) Dup(fromIndex int) { - C.duk_dup(d.duk_context, C.duk_idx_t(fromIndex)) -} - -// See: http://duktape.org/api.html#duk_dup_top -func (d *Context) DupTop() { - C.duk_dup_top(d.duk_context) -} - -// See: http://duktape.org/api.html#duk_enum -func (d *Context) Enum(objIndex int, enumFlags uint) { - C.duk_enum(d.duk_context, C.duk_idx_t(objIndex), C.duk_uint_t(enumFlags)) -} - -// See: http://duktape.org/api.html#duk_equals -func (d *Context) Equals(index1 int, index2 int) bool { - return int(C.duk_equals(d.duk_context, C.duk_idx_t(index1), C.duk_idx_t(index2))) == 1 -} - -// Error pushes a new Error object to the stack and throws it. This will call -// fmt.Sprint, forwarding arguments after the error code, to produce the -// Error's message. -// -// See: http://duktape.org/api.html#duk_error -func (d *Context) Error(errCode int, str string) { - __str__ := C.CString(str) - C._duk_error(d.duk_context, C.duk_errcode_t(errCode), __str__) - C.free(unsafe.Pointer(__str__)) -} - -func (d *Context) ErrorRaw(errCode int, filename string, line int, errMsg string) { - __filename__ := C.CString(filename) - __errMsg__ := C.CString(errMsg) - C._duk_error_raw(d.duk_context, C.duk_errcode_t(errCode), __filename__, C.duk_int_t(line), __errMsg__) - C.free(unsafe.Pointer(__filename__)) - C.free(unsafe.Pointer(__errMsg__)) -} - -// Errorf pushes a new Error object to the stack and throws it. This will call -// fmt.Sprintf, forwarding the format string and additional arguments, to -// produce the Error's message. -// -// See: http://duktape.org/api.html#duk_error -func (d *Context) Errorf(errCode int, format string, a ...interface{}) { - str := fmt.Sprintf(format, a...) - __str__ := C.CString(str) - C._duk_error(d.duk_context, C.duk_errcode_t(errCode), __str__) - C.free(unsafe.Pointer(__str__)) -} - -// See: http://duktape.org/api.html#duk_eval -func (d *Context) Eval() { - C._duk_eval(d.duk_context) -} - -// See: http://duktape.org/api.html#duk_eval_file -func (d *Context) EvalFile(path string) { - __path__ := C.CString(path) - C._duk_eval_file(d.duk_context, __path__) - C.free(unsafe.Pointer(__path__)) -} - -// See: http://duktape.org/api.html#duk_eval_file_noresult -func (d *Context) EvalFileNoresult(path string) { - __path__ := C.CString(path) - C._duk_eval_file_noresult(d.duk_context, __path__) - C.free(unsafe.Pointer(__path__)) -} - -// See: http://duktape.org/api.html#duk_eval_lstring -func (d *Context) EvalLstring(src string, len int) { - __src__ := C.CString(src) - C._duk_eval_lstring(d.duk_context, __src__, C.duk_size_t(len)) - C.free(unsafe.Pointer(__src__)) -} - -// See: http://duktape.org/api.html#duk_eval_lstring_noresult -func (d *Context) EvalLstringNoresult(src string, len int) { - __src__ := C.CString(src) - C._duk_eval_lstring_noresult(d.duk_context, __src__, C.duk_size_t(len)) - C.free(unsafe.Pointer(__src__)) -} - -// See: http://duktape.org/api.html#duk_eval_noresult -func (d *Context) EvalNoresult() { - C._duk_eval_noresult(d.duk_context) -} - -// See: http://duktape.org/api.html#duk_eval_string -func (d *Context) EvalString(src string) { - __src__ := C.CString(src) - C._duk_eval_string(d.duk_context, __src__) - C.free(unsafe.Pointer(__src__)) -} - -// See: http://duktape.org/api.html#duk_eval_string_noresult -func (d *Context) EvalStringNoresult(src string) { - __src__ := C.CString(src) - C._duk_eval_string_noresult(d.duk_context, __src__) - C.free(unsafe.Pointer(__src__)) -} - -// See: http://duktape.org/api.html#duk_fatal -func (d *Context) Fatal(errCode int, errMsg string) { - __errMsg__ := C.CString(errMsg) - defer C.free(unsafe.Pointer(__errMsg__)) - C.duk_fatal_raw(d.duk_context, __errMsg__) -} - -// See: http://duktape.org/api.html#duk_gc -func (d *Context) Gc(flags uint) { - C.duk_gc(d.duk_context, C.duk_uint_t(flags)) -} - -// See: http://duktape.org/api.html#duk_get_boolean -func (d *Context) GetBoolean(index int) bool { - return int(C.duk_get_boolean(d.duk_context, C.duk_idx_t(index))) == 1 -} - -// See: http://duktape.org/api.html#duk_get_buffer -func (d *Context) GetBuffer(index int) (rawPtr unsafe.Pointer, outSize uint) { - rawPtr = C.duk_get_buffer(d.duk_context, C.duk_idx_t(index), (*C.duk_size_t)(unsafe.Pointer(&outSize))) - return rawPtr, outSize -} - -// See: http://duktape.org/api.html#duk_get_context -func (d *Context) GetContext(index int) *Context { - return contextFromPointer(C.duk_get_context(d.duk_context, C.duk_idx_t(index))) -} - -// See: http://duktape.org/api.html#duk_get_current_magic -func (d *Context) GetCurrentMagic() int { - return int(C.duk_get_current_magic(d.duk_context)) -} - -// See: http://duktape.org/api.html#duk_get_error_code -func (d *Context) GetErrorCode(index int) int { - code := int(C.duk_get_error_code(d.duk_context, C.duk_idx_t(index))) - return code -} - -// See: http://duktape.org/api.html#duk_get_finalizer -func (d *Context) GetFinalizer(index int) { - C.duk_get_finalizer(d.duk_context, C.duk_idx_t(index)) -} - -// See: http://duktape.org/api.html#duk_get_global_string -func (d *Context) GetGlobalString(key string) bool { - __key__ := C.CString(key) - result := int(C.duk_get_global_string(d.duk_context, __key__)) == 1 - C.free(unsafe.Pointer(__key__)) - return result -} - -// See: http://duktape.org/api.html#duk_get_heapptr -func (d *Context) GetHeapptr(index int) unsafe.Pointer { - return unsafe.Pointer(C.duk_get_heapptr(d.duk_context, C.duk_idx_t(index))) -} - -// See: http://duktape.org/api.html#duk_get_int -func (d *Context) GetInt(index int) int { - return int(C.duk_get_int(d.duk_context, C.duk_idx_t(index))) -} - -// See: http://duktape.org/api.html#duk_get_length -func (d *Context) GetLength(index int) int { - return int(C.duk_get_length(d.duk_context, C.duk_idx_t(index))) -} - -// See: http://duktape.org/api.html#duk_get_lstring -func (d *Context) GetLstring(index int) string { - if s := C.duk_get_lstring(d.duk_context, C.duk_idx_t(index), nil); s != nil { - return C.GoString(s) - } - return "" -} - -// See: http://duktape.org/api.html#duk_get_magic -func (d *Context) GetMagic(index int) int { - return int(C.duk_get_magic(d.duk_context, C.duk_idx_t(index))) -} - -// See: http://duktape.org/api.html#duk_get_number -func (d *Context) GetNumber(index int) float64 { - return float64(C.duk_get_number(d.duk_context, C.duk_idx_t(index))) -} - -// See: http://duktape.org/api.html#duk_get_pointer -func (d *Context) GetPointer(index int) unsafe.Pointer { - return C.duk_get_pointer(d.duk_context, C.duk_idx_t(index)) -} - -// See: http://duktape.org/api.html#duk_get_prop -func (d *Context) GetProp(objIndex int) bool { - return int(C.duk_get_prop(d.duk_context, C.duk_idx_t(objIndex))) == 1 -} - -// See: http://duktape.org/api.html#duk_get_prop_index -func (d *Context) GetPropIndex(objIndex int, arrIndex uint) bool { - return int(C.duk_get_prop_index(d.duk_context, C.duk_idx_t(objIndex), C.duk_uarridx_t(arrIndex))) == 1 -} - -// See: http://duktape.org/api.html#duk_get_prop_string -func (d *Context) GetPropString(objIndex int, key string) bool { - __key__ := C.CString(key) - result := int(C.duk_get_prop_string(d.duk_context, C.duk_idx_t(objIndex), __key__)) == 1 - C.free(unsafe.Pointer(__key__)) - return result -} - -// See: http://duktape.org/api.html#duk_get_prototype -func (d *Context) GetPrototype(index int) { - C.duk_get_prototype(d.duk_context, C.duk_idx_t(index)) -} - -// See: http://duktape.org/api.html#duk_get_string -func (d *Context) GetString(i int) string { - if s := C.duk_get_string(d.duk_context, C.duk_idx_t(i)); s != nil { - return C.GoString(s) - } - return "" -} - -// See: http://duktape.org/api.html#duk_get_top -func (d *Context) GetTop() int { - return int(C.duk_get_top(d.duk_context)) -} - -// See: http://duktape.org/api.html#duk_get_top_index -func (d *Context) GetTopIndex() int { - return int(C.duk_get_top_index(d.duk_context)) -} - -// See: http://duktape.org/api.html#duk_get_type -func (d *Context) GetType(index int) Type { - return Type(C.duk_get_type(d.duk_context, C.duk_idx_t(index))) -} - -// See: http://duktape.org/api.html#duk_get_type_mask -func (d *Context) GetTypeMask(index int) uint { - return uint(C.duk_get_type_mask(d.duk_context, C.duk_idx_t(index))) -} - -// See: http://duktape.org/api.html#duk_get_uint -func (d *Context) GetUint(index int) uint { - return uint(C.duk_get_uint(d.duk_context, C.duk_idx_t(index))) -} - -// See: http://duktape.org/api.html#duk_has_prop -func (d *Context) HasProp(objIndex int) bool { - return int(C.duk_has_prop(d.duk_context, C.duk_idx_t(objIndex))) == 1 -} - -// See: http://duktape.org/api.html#duk_has_prop_index -func (d *Context) HasPropIndex(objIndex int, arrIndex uint) bool { - return int(C.duk_has_prop_index(d.duk_context, C.duk_idx_t(objIndex), C.duk_uarridx_t(arrIndex))) == 1 -} - -// See: http://duktape.org/api.html#duk_has_prop_string -func (d *Context) HasPropString(objIndex int, key string) bool { - __key__ := C.CString(key) - result := int(C.duk_has_prop_string(d.duk_context, C.duk_idx_t(objIndex), __key__)) == 1 - C.free(unsafe.Pointer(__key__)) - return result -} - -// See: http://duktape.org/api.html#duk_hex_decode -func (d *Context) HexDecode(index int) { - C.duk_hex_decode(d.duk_context, C.duk_idx_t(index)) -} - -// See: http://duktape.org/api.html#duk_hex_encode -func (d *Context) HexEncode(index int) string { - if s := C.duk_hex_encode(d.duk_context, C.duk_idx_t(index)); s != nil { - return C.GoString(s) - } - return "" -} - -// See: http://duktape.org/api.html#duk_insert -func (d *Context) Insert(toIndex int) { - C.duk_insert(d.duk_context, C.duk_idx_t(toIndex)) -} - -// See: http://duktape.org/api.html#duk_is_array -func (d *Context) IsArray(index int) bool { - return int(C.duk_is_array(d.duk_context, C.duk_idx_t(index))) == 1 -} - -// See: http://duktape.org/api.html#duk_is_boolean -func (d *Context) IsBoolean(index int) bool { - return int(C.duk_is_boolean(d.duk_context, C.duk_idx_t(index))) == 1 -} - -// See: http://duktape.org/api.html#duk_is_bound_function -func (d *Context) IsBoundFunction(index int) bool { - return int(C.duk_is_bound_function(d.duk_context, C.duk_idx_t(index))) == 1 -} - -// See: http://duktape.org/api.html#duk_is_buffer -func (d *Context) IsBuffer(index int) bool { - return int(C.duk_is_buffer(d.duk_context, C.duk_idx_t(index))) == 1 -} - -// See: http://duktape.org/api.html#duk_is_c_function -func (d *Context) IsCFunction(index int) bool { - return int(C.duk_is_c_function(d.duk_context, C.duk_idx_t(index))) == 1 -} - -// See: http://duktape.org/api.html#duk_is_callable -func (d *Context) IsCallable(index int) bool { - return int(C.duk_is_function(d.duk_context, C.duk_idx_t(index))) == 1 -} - -// See: http://duktape.org/api.html#duk_is_constructor_call -func (d *Context) IsConstructorCall() bool { - return int(C.duk_is_constructor_call(d.duk_context)) == 1 -} - -// See: http://duktape.org/api.html#duk_is_dynamic_buffer -func (d *Context) IsDynamicBuffer(index int) bool { - return int(C.duk_is_dynamic_buffer(d.duk_context, C.duk_idx_t(index))) == 1 -} - -// See: http://duktape.org/api.html#duk_is_ecmascript_function -func (d *Context) IsEcmascriptFunction(index int) bool { - return int(C.duk_is_ecmascript_function(d.duk_context, C.duk_idx_t(index))) == 1 -} - -// See: http://duktape.org/api.html#duk_is_fixed_buffer -func (d *Context) IsFixedBuffer(index int) bool { - return int(C.duk_is_fixed_buffer(d.duk_context, C.duk_idx_t(index))) == 1 -} - -// See: http://duktape.org/api.html#duk_is_function -func (d *Context) IsFunction(index int) bool { - return int(C.duk_is_function(d.duk_context, C.duk_idx_t(index))) == 1 -} - -// See: http://duktape.org/api.html#duk_is_nan -func (d *Context) IsNan(index int) bool { - return int(C.duk_is_nan(d.duk_context, C.duk_idx_t(index))) == 1 -} - -// See: http://duktape.org/api.html#duk_is_null -func (d *Context) IsNull(index int) bool { - return int(C.duk_is_null(d.duk_context, C.duk_idx_t(index))) == 1 -} - -// See: http://duktape.org/api.html#duk_is_null_or_undefined -func (d *Context) IsNullOrUndefined(index int) bool { - return d.IsNull(index) || d.IsUndefined(index) -} - -// See: http://duktape.org/api.html#duk_is_number -func (d *Context) IsNumber(index int) bool { - return int(C.duk_is_number(d.duk_context, C.duk_idx_t(index))) == 1 -} - -// See: http://duktape.org/api.html#duk_is_object -func (d *Context) IsObject(index int) bool { - return int(C.duk_is_object(d.duk_context, C.duk_idx_t(index))) == 1 -} - -// See: http://duktape.org/api.html#duk_is_error -func (d *Context) IsError(index int) bool { - return int(C._duk_is_error(d.duk_context, C.duk_idx_t(index))) == 1 -} - -// See: http://duktape.org/api.html#duk_is_object_coercible -func (d *Context) IsObjectCoercible(index int) bool { - return int(C._duk_is_object_coercible(d.duk_context, C.duk_idx_t(index))) == 1 -} - -// See: http://duktape.org/api.html#duk_is_pointer -func (d *Context) IsPointer(index int) bool { - return int(C.duk_is_pointer(d.duk_context, C.duk_idx_t(index))) == 1 -} - -// See: http://duktape.org/api.html#duk_is_primitive -func (d *Context) IsPrimitive(index int) bool { - return int(C._duk_is_primitive(d.duk_context, C.duk_idx_t(index))) == 1 -} - -// See: http://duktape.org/api.html#duk_is_strict_call -func (d *Context) IsStrictCall() bool { - return int(C.duk_is_strict_call(d.duk_context)) == 1 -} - -// See: http://duktape.org/api.html#duk_is_string -func (d *Context) IsString(index int) bool { - return int(C.duk_is_string(d.duk_context, C.duk_idx_t(index))) == 1 -} - -// See: http://duktape.org/api.html#duk_is_thread -func (d *Context) IsThread(index int) bool { - return int(C.duk_is_thread(d.duk_context, C.duk_idx_t(index))) == 1 -} - -// See: http://duktape.org/api.html#duk_is_undefined -func (d *Context) IsUndefined(index int) bool { - return int(C.duk_is_undefined(d.duk_context, C.duk_idx_t(index))) == 1 -} - -// See: http://duktape.org/api.html#duk_is_valid_index -func (d *Context) IsValidIndex(index int) bool { - return int(C.duk_is_valid_index(d.duk_context, C.duk_idx_t(index))) == 1 -} - -// See: http://duktape.org/api.html#duk_join -func (d *Context) Join(count int) { - C.duk_join(d.duk_context, C.duk_idx_t(count)) -} - -// See: http://duktape.org/api.html#duk_json_decode -func (d *Context) JsonDecode(index int) { - C.duk_json_decode(d.duk_context, C.duk_idx_t(index)) -} - -// See: http://duktape.org/api.html#duk_json_encode -func (d *Context) JsonEncode(index int) string { - if s := C.duk_json_encode(d.duk_context, C.duk_idx_t(index)); s != nil { - return C.GoString(s) - } - return "" -} - -// See: http://duktape.org/api.html#duk_new -func (d *Context) New(nargs int) { - C.duk_new(d.duk_context, C.duk_idx_t(nargs)) -} - -// See: http://duktape.org/api.html#duk_next -func (d *Context) Next(enumIndex int, getValue bool) bool { - var __getValue__ int - if getValue { - __getValue__ = 1 - } - return int(C.duk_next(d.duk_context, C.duk_idx_t(enumIndex), C.duk_bool_t(__getValue__))) == 1 -} - -// See: http://duktape.org/api.html#duk_normalize_index -func (d *Context) NormalizeIndex(index int) int { - return int(C.duk_normalize_index(d.duk_context, C.duk_idx_t(index))) -} - -// See: http://duktape.org/api.html#duk_pcall -func (d *Context) Pcall(nargs int) int { - return int(C.duk_pcall(d.duk_context, C.duk_idx_t(nargs))) -} - -// See: http://duktape.org/api.html#duk_pcall_method -func (d *Context) PcallMethod(nargs int) int { - return int(C.duk_pcall_method(d.duk_context, C.duk_idx_t(nargs))) -} - -// See: http://duktape.org/api.html#duk_pcall_prop -func (d *Context) PcallProp(objIndex int, nargs int) int { - return int(C.duk_pcall_prop(d.duk_context, C.duk_idx_t(objIndex), C.duk_idx_t(nargs))) -} - -// See: http://duktape.org/api.html#duk_pcompile -func (d *Context) Pcompile(flags uint) error { - result := int(C._duk_pcompile(d.duk_context, C.duk_uint_t(flags))) - return d.castStringToError(result) -} - -// See: http://duktape.org/api.html#duk_pcompile_file -func (d *Context) PcompileFile(flags uint, path string) error { - __path__ := C.CString(path) - result := int(C._duk_pcompile_file(d.duk_context, C.duk_uint_t(flags), __path__)) - C.free(unsafe.Pointer(__path__)) - return d.castStringToError(result) -} - -// See: http://duktape.org/api.html#duk_pcompile_lstring -func (d *Context) PcompileLstring(flags uint, src string, len int) error { - __src__ := C.CString(src) - result := int(C._duk_pcompile_lstring(d.duk_context, C.duk_uint_t(flags), __src__, C.duk_size_t(len))) - C.free(unsafe.Pointer(__src__)) - return d.castStringToError(result) -} - -// See: http://duktape.org/api.html#duk_pcompile_lstring_filename -func (d *Context) PcompileLstringFilename(flags uint, src string, len int) error { - __src__ := C.CString(src) - result := int(C._duk_pcompile_lstring_filename(d.duk_context, C.duk_uint_t(flags), __src__, C.duk_size_t(len))) - C.free(unsafe.Pointer(__src__)) - return d.castStringToError(result) -} - -// See: http://duktape.org/api.html#duk_pcompile_string -func (d *Context) PcompileString(flags uint, src string) error { - __src__ := C.CString(src) - result := int(C._duk_pcompile_string(d.duk_context, C.duk_uint_t(flags), __src__)) - C.free(unsafe.Pointer(__src__)) - fmt.Println("result herhehreh", result) - return nil //d.castStringToError(result) -} - -// See: http://duktape.org/api.html#duk_pcompile_string_filename -func (d *Context) PcompileStringFilename(flags uint, src string) error { - __src__ := C.CString(src) - result := int(C._duk_pcompile_string_filename(d.duk_context, C.duk_uint_t(flags), __src__)) - C.free(unsafe.Pointer(__src__)) - return d.castStringToError(result) -} - -// See: http://duktape.org/api.html#duk_peval -func (d *Context) Peval() error { - result := int(C._duk_peval(d.duk_context)) - return d.castStringToError(result) -} - -// See: http://duktape.org/api.html#duk_peval_file -func (d *Context) PevalFile(path string) error { - __path__ := C.CString(path) - result := int(C._duk_peval_file(d.duk_context, __path__)) - C.free(unsafe.Pointer(__path__)) - return d.castStringToError(result) -} - -// See: http://duktape.org/api.html#duk_peval_file_noresult -func (d *Context) PevalFileNoresult(path string) int { - __path__ := C.CString(path) - result := int(C._duk_peval_file_noresult(d.duk_context, __path__)) - C.free(unsafe.Pointer(__path__)) - return result -} - -// See: http://duktape.org/api.html#duk_peval_lstring -func (d *Context) PevalLstring(src string, len int) error { - __src__ := C.CString(src) - result := int(C._duk_peval_lstring(d.duk_context, __src__, C.duk_size_t(len))) - C.free(unsafe.Pointer(__src__)) - return d.castStringToError(result) - -} - -// See: http://duktape.org/api.html#duk_peval_lstring_noresult -func (d *Context) PevalLstringNoresult(src string, len int) int { - __src__ := C.CString(src) - result := int(C._duk_peval_lstring_noresult(d.duk_context, __src__, C.duk_size_t(len))) - C.free(unsafe.Pointer(__src__)) - return result -} - -// See: http://duktape.org/api.html#duk_peval_noresult -func (d *Context) PevalNoresult() int { - return int(C._duk_peval_noresult(d.duk_context)) -} - -// See: http://duktape.org/api.html#duk_peval_string -func (d *Context) PevalString(src string) error { - __src__ := C.CString(src) - result := int(C._duk_peval_string(d.duk_context, __src__)) - C.free(unsafe.Pointer(__src__)) - return d.castStringToError(result) -} - -// See: http://duktape.org/api.html#duk_peval_string_noresult -func (d *Context) PevalStringNoresult(src string) int { - __src__ := C.CString(src) - result := int(C._duk_peval_string_noresult(d.duk_context, __src__)) - C.free(unsafe.Pointer(__src__)) - return result -} - -func (d *Context) castStringToError(result int) error { - if result == 0 { - return nil - } - - err := &Error{} - for _, key := range []string{"name", "message", "fileName", "lineNumber", "stack"} { - d.GetPropString(-1, key) - - switch key { - case "name": - err.Type = d.SafeToString(-1) - case "message": - err.Message = d.SafeToString(-1) - case "fileName": - err.FileName = d.SafeToString(-1) - case "lineNumber": - if d.IsNumber(-1) { - err.LineNumber = d.GetInt(-1) - } - case "stack": - err.Stack = d.SafeToString(-1) - } - - d.Pop() - } - - return err -} - -// See: http://duktape.org/api.html#duk_pop -func (d *Context) Pop() { - if d.GetTop() == 0 { - return - } - C.duk_pop(d.duk_context) -} - -// See: http://duktape.org/api.html#duk_pop_2 -func (d *Context) Pop2() { - d.PopN(2) -} - -// See: http://duktape.org/api.html#duk_pop_3 -func (d *Context) Pop3() { - d.PopN(3) -} - -// See: http://duktape.org/api.html#duk_pop_n -func (d *Context) PopN(count int) { - if d.GetTop() < count || count < 1 { - return - } - C.duk_pop_n(d.duk_context, C.duk_idx_t(count)) -} - -// See: http://duktape.org/api.html#duk_push_array -func (d *Context) PushArray() int { - return int(C.duk_push_array(d.duk_context)) -} - -// See: http://duktape.org/api.html#duk_push_boolean -func (d *Context) PushBoolean(val bool) { - var __val__ int - if val { - __val__ = 1 - } - C.duk_push_boolean(d.duk_context, C.duk_bool_t(__val__)) -} - -// See: http://duktape.org/api.html#duk_push_buffer -func (d *Context) PushBuffer(size int, dynamic bool) unsafe.Pointer { - var __dynamic__ int - if dynamic { - __dynamic__ = 1 - } - return C._duk_push_buffer(d.duk_context, C.duk_size_t(size), C.duk_bool_t(__dynamic__)) -} - -// See: http://duktape.org/api.html#duk_push_c_function -func (d *Context) PushCFunction(fn *[0]byte, nargs int64) int { - return int(C.duk_push_c_function(d.duk_context, fn, C.duk_idx_t(nargs))) -} - -// See: http://duktape.org/api.html#duk_push_context_dump -func (d *Context) PushContextDump() { - C.duk_push_context_dump(d.duk_context) -} - -// See: http://duktape.org/api.html#duk_push_current_function -func (d *Context) PushCurrentFunction() { - C.duk_push_current_function(d.duk_context) -} - -// See: http://duktape.org/api.html#duk_push_current_thread -func (d *Context) PushCurrentThread() { - C.duk_push_current_thread(d.duk_context) -} - -// See: http://duktape.org/api.html#duk_push_dynamic_buffer -func (d *Context) PushDynamicBuffer(size int) unsafe.Pointer { - return C._duk_push_dynamic_buffer(d.duk_context, C.duk_size_t(size)) -} - -// See: http://duktape.org/api.html#duk_push_error_object -func (d *Context) PushErrorObject(errCode int, format string, value interface{}) { - __str__ := C.CString(fmt.Sprintf(format, value)) - C._duk_push_error_object(d.duk_context, C.duk_errcode_t(errCode), __str__) - C.free(unsafe.Pointer(__str__)) -} - -// See: http://duktape.org/api.html#duk_push_false -func (d *Context) PushFalse() { - C.duk_push_false(d.duk_context) -} - -// See: http://duktape.org/api.html#duk_push_fixed_buffer -func (d *Context) PushFixedBuffer(size int) unsafe.Pointer { - return C._duk_push_fixed_buffer(d.duk_context, C.duk_size_t(size)) -} - -// See: http://duktape.org/api.html#duk_push_global_object -func (d *Context) PushGlobalObject() { - C.duk_push_global_object(d.duk_context) -} - -// See: http://duktape.org/api.html#duk_push_global_stash -func (d *Context) PushGlobalStash() { - C.duk_push_global_stash(d.duk_context) -} - -// See: http://duktape.org/api.html#duk_push_heapptr -func (d *Context) PushHeapptr(ptr unsafe.Pointer) { - C.duk_push_heapptr(d.duk_context, ptr) -} - -// See: http://duktape.org/api.html#duk_push_heap_stash -func (d *Context) PushHeapStash() { - C.duk_push_heap_stash(d.duk_context) -} - -// See: http://duktape.org/api.html#duk_push_int -func (d *Context) PushInt(val int) { - C.duk_push_int(d.duk_context, C.duk_int_t(val)) -} - -// See: http://duktape.org/api.html#duk_push_lstring -func (d *Context) PushLstring(str string, len int) string { - __str__ := C.CString(str) - var result string - if s := C.duk_push_lstring(d.duk_context, __str__, C.duk_size_t(len)); s != nil { - result = C.GoString(s) - } - C.free(unsafe.Pointer(__str__)) - return result -} - -// See: http://duktape.org/api.html#duk_push_nan -func (d *Context) PushNan() { - C.duk_push_nan(d.duk_context) -} - -// See: http://duktape.org/api.html#duk_push_null -func (d *Context) PushNull() { - C.duk_push_null(d.duk_context) -} - -// See: http://duktape.org/api.html#duk_push_number -func (d *Context) PushNumber(val float64) { - C.duk_push_number(d.duk_context, C.duk_double_t(val)) -} - -// See: http://duktape.org/api.html#duk_push_object -func (d *Context) PushObject() int { - return int(C.duk_push_object(d.duk_context)) -} - -// See: http://duktape.org/api.html#duk_push_string -func (d *Context) PushString(str string) string { - __str__ := C.CString(str) - var result string - if s := C.duk_push_string(d.duk_context, __str__); s != nil { - result = C.GoString(s) - } - C.free(unsafe.Pointer(__str__)) - return result -} - -// See: http://duktape.org/api.html#duk_push_string_file -func (d *Context) PushStringFile(path string) string { - __path__ := C.CString(path) - var result string - if s := C._duk_push_string_file(d.duk_context, __path__); s != nil { - result = C.GoString(s) - } - C.free(unsafe.Pointer(__path__)) - return result -} - -// See: http://duktape.org/api.html#duk_push_this -func (d *Context) PushThis() { - C.duk_push_this(d.duk_context) -} - -// See: http://duktape.org/api.html#duk_push_thread -func (d *Context) PushThread() int { - return int(C._duk_push_thread(d.duk_context)) -} - -// See: http://duktape.org/api.html#duk_push_thread_new_globalenv -func (d *Context) PushThreadNewGlobalenv() int { - return int(C._duk_push_thread_new_globalenv(d.duk_context)) -} - -// See: http://duktape.org/api.html#duk_push_thread_stash -func (d *Context) PushThreadStash(targetCtx *Context) { - C.duk_push_thread_stash(d.duk_context, targetCtx.duk_context) -} - -// See: http://duktape.org/api.html#duk_push_true -func (d *Context) PushTrue() { - C.duk_push_true(d.duk_context) -} - -// See: http://duktape.org/api.html#duk_push_uint -func (d *Context) PushUint(val uint) { - C.duk_push_uint(d.duk_context, C.duk_uint_t(val)) -} - -// See: http://duktape.org/api.html#duk_push_undefined -func (d *Context) PushUndefined() { - C.duk_push_undefined(d.duk_context) -} - -// See: http://duktape.org/api.html#duk_put_global_string -func (d *Context) PutGlobalString(key string) bool { - __key__ := C.CString(key) - result := int(C.duk_put_global_string(d.duk_context, __key__)) == 1 - C.free(unsafe.Pointer(__key__)) - return result -} - -// See: http://duktape.org/api.html#duk_put_prop -func (d *Context) PutProp(objIndex int) bool { - return int(C.duk_put_prop(d.duk_context, C.duk_idx_t(objIndex))) == 1 -} - -// See: http://duktape.org/api.html#duk_put_prop_index -func (d *Context) PutPropIndex(objIndex int, arrIndex uint) bool { - return int(C.duk_put_prop_index(d.duk_context, C.duk_idx_t(objIndex), C.duk_uarridx_t(arrIndex))) == 1 -} - -// See: http://duktape.org/api.html#duk_put_prop_string -func (d *Context) PutPropString(objIndex int, key string) bool { - __key__ := C.CString(key) - result := int(C.duk_put_prop_string(d.duk_context, C.duk_idx_t(objIndex), __key__)) == 1 - C.free(unsafe.Pointer(__key__)) - return result -} - -// See: http://duktape.org/api.html#duk_remove -func (d *Context) Remove(index int) { - C.duk_remove(d.duk_context, C.duk_idx_t(index)) -} - -// See: http://duktape.org/api.html#duk_replace -func (d *Context) Replace(toIndex int) { - C.duk_replace(d.duk_context, C.duk_idx_t(toIndex)) -} - -// See: http://duktape.org/api.html#duk_require_boolean -func (d *Context) RequireBoolean(index int) bool { - return int(C.duk_require_boolean(d.duk_context, C.duk_idx_t(index))) == 1 -} - -// See: http://duktape.org/api.html#duk_require_buffer -func (d *Context) RequireBuffer(index int) (rawPtr unsafe.Pointer, outSize uint) { - rawPtr = C.duk_require_buffer(d.duk_context, C.duk_idx_t(index), (*C.duk_size_t)(unsafe.Pointer(&outSize))) - return rawPtr, outSize -} - -// See: http://duktape.org/api.html#duk_require_callable -func (d *Context) RequireCallable(index int) { - // At present, duk_require_callable is a macro that just calls duk_require_function. - // cgo does not support such macros we have to call it directly. - C.duk_require_function(d.duk_context, C.duk_idx_t(index)) -} - -// See: http://duktape.org/api.html#duk_require_context -func (d *Context) RequireContext(index int) *Context { - return contextFromPointer(C.duk_require_context(d.duk_context, C.duk_idx_t(index))) -} - -// See: http://duktape.org/api.html#duk_require_function -func (d *Context) RequireFunction(index int) { - C.duk_require_function(d.duk_context, C.duk_idx_t(index)) -} - -// See: http://duktape.org/api.html#duk_require_heapptr -func (d *Context) RequireHeapptr(index int) unsafe.Pointer { - return unsafe.Pointer(C.duk_require_heapptr(d.duk_context, C.duk_idx_t(index))) -} - -// See: http://duktape.org/api.html#duk_require_int -func (d *Context) RequireInt(index int) int { - return int(C.duk_require_int(d.duk_context, C.duk_idx_t(index))) -} - -// See: http://duktape.org/api.html#duk_require_lstring -func (d *Context) RequireLstring(index int) string { - if s := C.duk_require_lstring(d.duk_context, C.duk_idx_t(index), nil); s != nil { - return C.GoString(s) - } - return "" -} - -// See: http://duktape.org/api.html#duk_require_normalize_index -func (d *Context) RequireNormalizeIndex(index int) int { - return int(C.duk_require_normalize_index(d.duk_context, C.duk_idx_t(index))) -} - -// See: http://duktape.org/api.html#duk_require_null -func (d *Context) RequireNull(index int) { - C.duk_require_null(d.duk_context, C.duk_idx_t(index)) -} - -// See: http://duktape.org/api.html#duk_require_number -func (d *Context) RequireNumber(index int) float64 { - return float64(C.duk_require_number(d.duk_context, C.duk_idx_t(index))) -} - -// See: http://duktape.org/api.html#duk_require_object_coercible -func (d *Context) RequireObjectCoercible(index int) { - C._duk_require_object_coercible(d.duk_context, C.duk_idx_t(index)) -} - -// See: http://duktape.org/api.html#duk_require_pointer -func (d *Context) RequirePointer(index int) unsafe.Pointer { - return C.duk_require_pointer(d.duk_context, C.duk_idx_t(index)) -} - -// See: http://duktape.org/api.html#duk_require_stack -func (d *Context) RequireStack(extra int) { - C.duk_require_stack(d.duk_context, C.duk_idx_t(extra)) -} - -// See: http://duktape.org/api.html#duk_require_stack_top -func (d *Context) RequireStackTop(top int) { - C.duk_require_stack_top(d.duk_context, C.duk_idx_t(top)) -} - -// See: http://duktape.org/api.html#duk_require_string -func (d *Context) RequireString(index int) string { - if s := C.duk_require_string(d.duk_context, C.duk_idx_t(index)); s != nil { - return C.GoString(s) - } - return "" -} - -// See: http://duktape.org/api.html#duk_require_top_index -func (d *Context) RequireTopIndex() int { - return int(C.duk_require_top_index(d.duk_context)) -} - -// See: http://duktape.org/api.html#duk_require_type_mask -func (d *Context) RequireTypeMask(index int, mask uint) { - C._duk_require_type_mask(d.duk_context, C.duk_idx_t(index), C.duk_uint_t(mask)) -} - -// See: http://duktape.org/api.html#duk_require_uint -func (d *Context) RequireUint(index int) uint { - return uint(C.duk_require_uint(d.duk_context, C.duk_idx_t(index))) -} - -// See: http://duktape.org/api.html#duk_require_undefined -func (d *Context) RequireUndefined(index int) { - C.duk_require_undefined(d.duk_context, C.duk_idx_t(index)) -} - -// See: http://duktape.org/api.html#duk_require_valid_index -func (d *Context) RequireValidIndex(index int) { - C.duk_require_valid_index(d.duk_context, C.duk_idx_t(index)) -} - -// See: http://duktape.org/api.html#duk_resize_buffer -func (d *Context) ResizeBuffer(index int, newSize int) unsafe.Pointer { - return C.duk_resize_buffer(d.duk_context, C.duk_idx_t(index), C.duk_size_t(newSize)) -} - -// See: http://duktape.org/api.html#duk_safe_call -func (d *Context) SafeCall(fn, args *[0]byte, nargs, nrets int) int { - return int(C.duk_safe_call( - d.duk_context, - fn, - unsafe.Pointer(&args), - C.duk_idx_t(nargs), - C.duk_idx_t(nrets), - )) -} - -// See: http://duktape.org/api.html#duk_safe_to_lstring -func (d *Context) SafeToLstring(index int) string { - if s := C.duk_safe_to_lstring(d.duk_context, C.duk_idx_t(index), nil); s != nil { - return C.GoString(s) - } - return "" -} - -// See: http://duktape.org/api.html#duk_safe_to_string -func (d *Context) SafeToString(index int) string { - if s := C._duk_safe_to_string(d.duk_context, C.duk_idx_t(index)); s != nil { - return C.GoString(s) - } - return "" -} - -// See: http://duktape.org/api.html#duk_set_finalizer -func (d *Context) SetFinalizer(index int) { - C.duk_set_finalizer(d.duk_context, C.duk_idx_t(index)) -} - -// See: http://duktape.org/api.html#duk_set_global_object -func (d *Context) SetGlobalObject() { - C.duk_set_global_object(d.duk_context) -} - -// See: http://duktape.org/api.html#duk_set_magic -func (d *Context) SetMagic(index int, magic int) { - C.duk_set_magic(d.duk_context, C.duk_idx_t(index), C.duk_int_t(magic)) -} - -// See: http://duktape.org/api.html#duk_set_prototype -func (d *Context) SetPrototype(index int) { - C.duk_set_prototype(d.duk_context, C.duk_idx_t(index)) -} - -// See: http://duktape.org/api.html#duk_set_top -func (d *Context) SetTop(index int) { - C.duk_set_top(d.duk_context, C.duk_idx_t(index)) -} - -func (d *Context) StrictEquals(index1 int, index2 int) bool { - return int(C.duk_strict_equals(d.duk_context, C.duk_idx_t(index1), C.duk_idx_t(index2))) == 1 -} - -// See: http://duktape.org/api.html#duk_substring -func (d *Context) Substring(index int, startCharOffset int, endCharOffset int) { - C.duk_substring(d.duk_context, C.duk_idx_t(index), C.duk_size_t(startCharOffset), C.duk_size_t(endCharOffset)) -} - -// See: http://duktape.org/api.html#duk_swap -func (d *Context) Swap(index1 int, index2 int) { - C.duk_swap(d.duk_context, C.duk_idx_t(index1), C.duk_idx_t(index2)) -} - -// See: http://duktape.org/api.html#duk_swap_top -func (d *Context) SwapTop(index int) { - C.duk_swap_top(d.duk_context, C.duk_idx_t(index)) -} - -// See: http://duktape.org/api.html#duk_throw -func (d *Context) Throw() { - C.duk_throw_raw(d.duk_context) -} - -// See: http://duktape.org/api.html#duk_to_boolean -func (d *Context) ToBoolean(index int) bool { - return int(C.duk_to_boolean(d.duk_context, C.duk_idx_t(index))) == 1 -} - -// See: http://duktape.org/api.html#duk_to_buffer -func (d *Context) ToBuffer(index int) (rawPtr unsafe.Pointer, outSize uint) { - rawPtr = C._duk_to_buffer(d.duk_context, C.duk_idx_t(index), (*C.duk_size_t)(unsafe.Pointer(&outSize))) - return rawPtr, outSize -} - -// See: http://duktape.org/api.html#duk_to_defaultvalue -func (d *Context) ToDefaultvalue(index int, hint int) { - C.duk_to_defaultvalue(d.duk_context, C.duk_idx_t(index), C.duk_int_t(hint)) -} - -// See: http://duktape.org/api.html#duk_to_dynamic_buffer -func (d *Context) ToDynamicBuffer(index int) (rawPtr unsafe.Pointer, outSize uint) { - rawPtr = C._duk_to_dynamic_buffer(d.duk_context, C.duk_idx_t(index), (*C.duk_size_t)(unsafe.Pointer(&outSize))) - return rawPtr, outSize -} - -// See: http://duktape.org/api.html#duk_to_fixed_buffer -func (d *Context) ToFixedBuffer(index int) (rawPtr unsafe.Pointer, outSize uint) { - rawPtr = C._duk_to_fixed_buffer(d.duk_context, C.duk_idx_t(index), (*C.duk_size_t)(unsafe.Pointer(&outSize))) - return rawPtr, outSize -} - -// See: http://duktape.org/api.html#duk_to_int -func (d *Context) ToInt(index int) int { - return int(C.duk_to_int(d.duk_context, C.duk_idx_t(index))) -} - -// See: http://duktape.org/api.html#duk_to_int32 -func (d *Context) ToInt32(index int) int32 { - return int32(C.duk_to_int32(d.duk_context, C.duk_idx_t(index))) -} - -// See: http://duktape.org/api.html#duk_to_lstring -func (d *Context) ToLstring(index int) string { - if s := C.duk_to_lstring(d.duk_context, C.duk_idx_t(index), nil); s != nil { - return C.GoString(s) - } - return "" -} - -// See: http://duktape.org/api.html#duk_to_null -func (d *Context) ToNull(index int) { - C.duk_to_null(d.duk_context, C.duk_idx_t(index)) -} - -// See: http://duktape.org/api.html#duk_to_number -func (d *Context) ToNumber(index int) float64 { - return float64(C.duk_to_number(d.duk_context, C.duk_idx_t(index))) -} - -// See: http://duktape.org/api.html#duk_to_object -func (d *Context) ToObject(index int) { - C.duk_to_object(d.duk_context, C.duk_idx_t(index)) -} - -// See: http://duktape.org/api.html#duk_to_pointer -func (d *Context) ToPointer(index int) unsafe.Pointer { - return C.duk_to_pointer(d.duk_context, C.duk_idx_t(index)) -} - -// See: http://duktape.org/api.html#duk_to_primitive -func (d *Context) ToPrimitive(index int, hint int) { - C.duk_to_primitive(d.duk_context, C.duk_idx_t(index), C.duk_int_t(hint)) -} - -// See: http://duktape.org/api.html#duk_to_string -func (d *Context) ToString(index int) string { - if s := C.duk_to_string(d.duk_context, C.duk_idx_t(index)); s != nil { - return C.GoString(s) - } - return "" -} - -// See: http://duktape.org/api.html#duk_to_uint -func (d *Context) ToUint(index int) uint { - return uint(C.duk_to_uint(d.duk_context, C.duk_idx_t(index))) -} - -// See: http://duktape.org/api.html#duk_to_uint16 -func (d *Context) ToUint16(index int) uint16 { - return uint16(C.duk_to_uint16(d.duk_context, C.duk_idx_t(index))) -} - -// See: http://duktape.org/api.html#duk_to_uint32 -func (d *Context) ToUint32(index int) uint32 { - return uint32(C.duk_to_uint32(d.duk_context, C.duk_idx_t(index))) -} - -// See: http://duktape.org/api.html#duk_to_undefined -func (d *Context) ToUndefined(index int) { - C.duk_to_undefined(d.duk_context, C.duk_idx_t(index)) -} - -// See: http://duktape.org/api.html#duk_trim -func (d *Context) Trim(index int) { - C.duk_trim(d.duk_context, C.duk_idx_t(index)) -} - -// See: http://duktape.org/api.html#duk_xcopy_top -func (d *Context) XcopyTop(fromCtx *Context, count int) { - C._duk_xcopy_top(d.duk_context, fromCtx.duk_context, C.duk_idx_t(count)) -} - -// See: http://duktape.org/api.html#duk_xmove_top -func (d *Context) XmoveTop(fromCtx *Context, count int) { - C._duk_xmove_top(d.duk_context, fromCtx.duk_context, C.duk_idx_t(count)) -} - -// See: http://duktape.org/api.html#duk_push_pointer -func (d *Context) PushPointer(p unsafe.Pointer) { - C.duk_push_pointer(d.duk_context, p) -} - -//---[ Duktape 1.3 API ]--- // -// See: http://duktape.org/api.html#duk_debugger_attach -func (d *Context) DebuggerAttach( - readFn, - writeFn, - peekFn, - readFlushFn, - writeFlushFn, - detachedFn *[0]byte, - uData unsafe.Pointer) { - C.duk_debugger_attach( - d.duk_context, - readFn, - writeFn, - peekFn, - readFlushFn, - writeFlushFn, - nil, - detachedFn, - uData, - ) -} - -// See: http://duktape.org/api.html#duk_debugger_cooperate -func (d *Context) DebuggerCooperate() { - C.duk_debugger_cooperate(d.duk_context) -} - -// See: http://duktape.org/api.html#duk_debugger_detach -func (d *Context) DebuggerDetach() { - C.duk_debugger_detach(d.duk_context) -} - -// See: http://duktape.org/api.html#duk_dump_function -func (d *Context) DumpFunction() { - C.duk_dump_function(d.duk_context) -} - -// See: http://duktape.org/api.html#duk_error_va -func (d *Context) ErrorVa(errCode int, a ...interface{}) { - str := fmt.Sprint(a...) - d.Error(errCode, str) -} - -// See: http://duktape.org/api.html#duk_instanceof -func (d *Context) Instanceof(idx1, idx2 int) bool { - return int(C.duk_instanceof(d.duk_context, C.duk_idx_t(idx1), C.duk_idx_t(idx2))) == 1 -} - -// See: http://duktape.org/api.html#duk_is_lightfunc -func (d *Context) IsLightfunc(index int) bool { - return int(C.duk_is_lightfunc(d.duk_context, C.duk_idx_t(index))) == 1 -} - -// See: http://duktape.org/api.html#duk_load_function -func (d *Context) LoadFunction() { - C.duk_load_function(d.duk_context) -} - -// See: http://duktape.org/api.html#duk_log -func (d *Context) Log(loglevel int, format string, value interface{}) { - __str__ := C.CString(fmt.Sprintf(format, value)) - C._duk_log(d.duk_context, C.duk_int_t(loglevel), __str__) - C.free(unsafe.Pointer(__str__)) -} - -// See: http://duktape.org/api.html#duk_log_va -func (d *Context) LogVa(logLevel int, format string, values ...interface{}) { - __str__ := C.CString(fmt.Sprintf(format, values...)) - C._duk_log(d.duk_context, C.duk_int_t(logLevel), __str__) - C.free(unsafe.Pointer(__str__)) -} - -// See: http://duktape.org/api.html#duk_pnew -func (d *Context) Pnew(nargs int) error { - result := int(C.duk_pnew(d.duk_context, C.duk_idx_t(nargs))) - return d.castStringToError(result) -} - -// See: http://duktape.org/api.html#duk_push_buffer_object -func (d *Context) PushBufferObject(bufferIdx, size, length int, flags uint) { - C.duk_push_buffer_object( - d.duk_context, - C.duk_idx_t(bufferIdx), - C.duk_size_t(size), - C.duk_size_t(length), - C.duk_uint_t(flags), - ) -} - -// See: http://duktape.org/api.html#duk_push_c_lightfunc -func (d *Context) PushCLightfunc(fn *[0]byte, nargs, length, magic int) int { - return int(C.duk_push_c_lightfunc( - d.duk_context, - fn, - C.duk_idx_t(nargs), - C.duk_idx_t(length), - C.duk_int_t(magic), - )) -} - -// See: http://duktape.org/api.html#duk_push_error_object_va -func (d *Context) PushErrorObjectVa(errCode int, format string, values ...interface{}) { - __str__ := C.CString(fmt.Sprintf(format, values...)) - C._duk_push_error_object(d.duk_context, C.duk_errcode_t(errCode), __str__) - C.free(unsafe.Pointer(__str__)) -} - -// See: http://duktape.org/api.html#duk_push_external_buffer -func (d *Context) PushExternalBuffer() { - C._duk_push_external_buffer(d.duk_context) -} - -/** - * Unimplemented. - * - * CharCodeAt see: http://duktape.org/api.html#duk_char_code_at - * CreateHeap see: http://duktape.org/api.html#duk_create_heap - * DecodeString see: http://duktape.org/api.html#duk_decode_string - * Free see: http://duktape.org/api.html#duk_free - * FreeRaw see: http://duktape.org/api.html#duk_free_raw - * GetCFunction see: http://duktape.org/api.html#duk_get_c_function - * GetMemoryFunctions see: http://duktape.org/api.html#duk_get_memory_functions - * MapString see: http://duktape.org/api.html#duk_map_string - * PushSprintf see: http://duktape.org/api.html#duk_push_sprintf - * PushVsprintf see: http://duktape.org/api.html#duk_push_vsprintf - * PutFunctionList see: http://duktape.org/api.html#duk_put_function_list - * PutNumberList see: http://duktape.org/api.html#duk_put_number_list - * Realloc see: http://duktape.org/api.html#duk_realloc - * ReallocRaw see: http://duktape.org/api.html#duk_realloc_raw - * RequireCFunction see: http://duktape.org/api.html#duk_require_c_function - * ConfigBuffer see: http://duktape.org/api.html#duk_config_buffer - * GetBufferData see: http://duktape.org/api.html#duk_get_buffer_data - * StealBuffer see: http://duktape.org/api.html#duk_steal_buffer - * RequireBufferData see: http://duktape.org/api.html#duk_require_buffer_data - * IsEvalError see: http://duktape.org/api.html#duk_is_eval_error - */ diff --git a/vendor/gopkg.in/olebedev/go-duktape.v3/conts.go b/vendor/gopkg.in/olebedev/go-duktape.v3/conts.go deleted file mode 100644 index f3dbd8bc..00000000 --- a/vendor/gopkg.in/olebedev/go-duktape.v3/conts.go +++ /dev/null @@ -1,121 +0,0 @@ -package duktape - -const ( - CompileEval uint = 1 << iota - CompileFunction - CompileStrict - CompileSafe - CompileNoResult - CompileNoSource - CompileStrlen -) - -const ( - TypeNone Type = iota - TypeUndefined - TypeNull - TypeBoolean - TypeNumber - TypeString - TypeObject - TypeBuffer - TypePointer - TypeLightFunc -) - -const ( - TypeMaskNone uint = 1 << iota - TypeMaskUndefined - TypeMaskNull - TypeMaskBoolean - TypeMaskNumber - TypeMaskString - TypeMaskObject - TypeMaskBuffer - TypeMaskPointer - TypeMaskLightFunc -) - -const ( - EnumIncludeNonenumerable uint = 1 << iota - EnumIncludeInternal - EnumOwnPropertiesOnly - EnumArrayIndicesOnly - EnumSortArrayIndices - NoProxyBehavior -) - -const ( - ErrNone int = 0 - - // Internal to Duktape - ErrUnimplemented int = 50 + iota - ErrUnsupported - ErrInternal - ErrAlloc - ErrAssertion - ErrAPI - ErrUncaughtError -) - -const ( - // Common prototypes - ErrError int = 1 + iota - ErrEval - ErrRange - ErrReference - ErrSyntax - ErrType - ErrURI -) - -const ( - // Returned error values - ErrRetUnimplemented int = -(ErrUnimplemented + iota) - ErrRetUnsupported - ErrRetInternal - ErrRetAlloc - ErrRetAssertion - ErrRetAPI - ErrRetUncaughtError -) - -const ( - ErrRetError int = -(ErrError + iota) - ErrRetEval - ErrRetRange - ErrRetReference - ErrRetSyntax - ErrRetType - ErrRetURI -) - -const ( - ExecSuccess = iota - ExecError -) - -const ( - LogTrace int = iota - LogDebug - LogInfo - LogWarn - LogError - LogFatal -) - -const ( - BufobjDuktapeAuffer = 0 - BufobjNodejsAuffer = 1 - BufobjArraybuffer = 2 - BufobjDataview = 3 - BufobjInt8array = 4 - BufobjUint8array = 5 - BufobjUint8clampedarray = 6 - BufobjInt16array = 7 - BufobjUint16array = 8 - BufobjInt32array = 9 - BufobjUint32array = 10 - BufobjFloat32array = 11 - BufobjFloat64array = 12 -) diff --git a/vendor/gopkg.in/olebedev/go-duktape.v3/duk_alloc_pool.c b/vendor/gopkg.in/olebedev/go-duktape.v3/duk_alloc_pool.c deleted file mode 100755 index 750fa71d..00000000 --- a/vendor/gopkg.in/olebedev/go-duktape.v3/duk_alloc_pool.c +++ /dev/null @@ -1,612 +0,0 @@ -/* - * Pool allocator for low memory targets. - */ - -#include -#include -#include -#include -#include -#include "duktape.h" -#include "duk_alloc_pool.h" - -/* Define to enable some debug printfs. */ -/* #define DUK_ALLOC_POOL_DEBUG */ - -/* Define to enable approximate waste tracking. */ -/* #define DUK_ALLOC_POOL_TRACK_WASTE */ - -/* Define to track global highwater for used and waste bytes. VERY SLOW, only - * useful for manual testing. - */ -/* #define DUK_ALLOC_POOL_TRACK_HIGHWATER */ - -#if defined(DUK_ALLOC_POOL_ROMPTR_COMPRESSION) -#if 0 /* This extern declaration is provided by duktape.h, array provided by duktape.c. */ -extern const void * const duk_rom_compressed_pointers[]; -#endif -const void *duk_alloc_pool_romptr_low = NULL; -const void *duk_alloc_pool_romptr_high = NULL; -static void duk__alloc_pool_romptr_init(void); -#endif - -#if defined(DUK_USE_HEAPPTR16) -void *duk_alloc_pool_ptrcomp_base = NULL; -#endif - -#if defined(DUK_ALLOC_POOL_DEBUG) -static void duk__alloc_pool_dprintf(const char *fmt, ...) { - va_list ap; - va_start(ap, fmt); - vfprintf(stderr, fmt, ap); - va_end(ap); -} -#endif - -/* - * Pool initialization - */ - -void *duk_alloc_pool_init(char *buffer, - size_t size, - const duk_pool_config *configs, - duk_pool_state *states, - int num_pools, - duk_pool_global *global) { - double t_min, t_max, t_curr, x; - int step, i, j, n; - size_t total; - char *p; - - /* XXX: check that 'size' is not too large when using pointer - * compression. - */ - - /* To optimize pool counts first come up with a 't' which still allows - * total pool size to fit within user provided region. After that - * sprinkle any remaining bytes to the counts. Binary search with a - * fixed step count; last round uses 't_min' as 't_curr' to ensure it - * succeeds. - */ - - t_min = 0.0; /* Unless config is insane, this should always be "good". */ - t_max = 1e6; - - for (step = 0; ; step++) { - if (step >= 100) { - /* Force "known good", rerun config, and break out. - * Deals with rounding corner cases where t_curr is - * persistently "bad" even though t_min is a valid - * solution. - */ - t_curr = t_min; - } else { - t_curr = (t_min + t_max) / 2.0; - } - - for (i = 0, total = 0; i < num_pools; i++) { - states[i].size = configs[i].size; - - /* Target bytes = A*t + B ==> target count = (A*t + B) / block_size. - * Rely on A and B being small enough so that 'x' won't wrap. - */ - x = ((double) configs[i].a * t_curr + (double) configs[i].b) / (double) configs[i].size; - - states[i].count = (unsigned int) x; - total += (size_t) states[i].size * (size_t) states[i].count; - if (total > size) { - goto bad; - } - } - - /* t_curr is good. */ -#if defined(DUK_ALLOC_POOL_DEBUG) - duk__alloc_pool_dprintf("duk_alloc_pool_init: step=%d, t=[%lf %lf %lf] -> total %ld/%ld (good)\n", - step, t_min, t_curr, t_max, (long) total, (long) size); -#endif - if (step >= 100) { - /* Keep state[] initialization state. The state was - * created using the highest 't_min'. - */ - break; - } - t_min = t_curr; - continue; - - bad: - /* t_curr is bad. */ -#if defined(DUK_ALLOC_POOL_DEBUG) - duk__alloc_pool_dprintf("duk_alloc_pool_init: step=%d, t=[%lf %lf %lf] -> total %ld/%ld (bad)\n", - step, t_min, t_curr, t_max, (long) total, (long) size); -#endif - - if (step >= 1000) { - /* Cannot find any good solution; shouldn't happen - * unless config is bad or 'size' is so small that - * even a baseline allocation won't fit. - */ - return NULL; - } - t_max = t_curr; - /* continue */ - } - - /* The base configuration is now good; sprinkle any leftovers to - * pools in descending order. Note that for good t_curr, 'total' - * indicates allocated bytes so far and 'size - total' indicates - * leftovers. - */ - for (i = num_pools - 1; i >= 0; i--) { - while (size - total >= states[i].size) { - /* Ignore potential wrapping of states[i].count as the count - * is 32 bits and shouldn't wrap in practice. - */ - states[i].count++; - total += states[i].size; -#if defined(DUK_ALLOC_POOL_DEBUG) - duk__alloc_pool_dprintf("duk_alloc_pool_init: sprinkle %ld bytes (%ld left after) to pool index %ld, new count %ld\n", - (long) states[i].size, (long) (size - total), (long) i, (long) states[i].count); -#endif - } - } - - /* Pool counts are final. Allocate the user supplied region based - * on the final counts, initialize free lists for each block size, - * and otherwise finalize 'state' for use. - */ - p = buffer; - global->num_pools = num_pools; - global->states = states; -#if defined(DUK_ALLOC_POOL_TRACK_HIGHWATER) -#if defined(DUK_ALLOC_POOL_DEBUG) - duk__alloc_pool_dprintf("duk_alloc_pool_init: global highwater mark tracking enabled, THIS IS VERY SLOW!\n"); -#endif - global->hwm_used_bytes = 0U; - global->hwm_waste_bytes = 0U; -#endif -#if defined(DUK_ALLOC_POOL_TRACK_WASTE) -#if defined(DUK_ALLOC_POOL_DEBUG) - duk__alloc_pool_dprintf("duk_alloc_pool_init: approximate waste tracking enabled\n"); -#endif -#endif - -#if defined(DUK_USE_HEAPPTR16) - /* Register global base value for pointer compression, assumes - * a single active pool -4 allows a single subtract to be used and - * still ensures no non-NULL pointer encodes to zero. - */ - duk_alloc_pool_ptrcomp_base = (void *) (p - 4); -#endif - - for (i = 0; i < num_pools; i++) { - n = (int) states[i].count; - if (n > 0) { - states[i].first = (duk_pool_free *) p; - for (j = 0; j < n; j++) { - char *p_next = p + states[i].size; - ((duk_pool_free *) p)->next = - (j == n - 1) ? (duk_pool_free *) NULL : (duk_pool_free *) p_next; - p = p_next; - } - } else { - states[i].first = (duk_pool_free *) NULL; - } - states[i].alloc_end = p; -#if defined(DUK_ALLOC_POOL_TRACK_HIGHWATER) - states[i].hwm_used_count = 0; -#endif - /* All members of 'state' now initialized. */ - -#if defined(DUK_ALLOC_POOL_DEBUG) - duk__alloc_pool_dprintf("duk_alloc_pool_init: block size %5ld, count %5ld, %8ld total bytes, " - "end %p\n", - (long) states[i].size, (long) states[i].count, - (long) states[i].size * (long) states[i].count, - (void *) states[i].alloc_end); -#endif - } - -#if defined(DUK_ALLOC_POOL_ROMPTR_COMPRESSION) - /* ROM pointer compression precomputation. Assumes a single active - * pool. - */ - duk__alloc_pool_romptr_init(); -#endif - - /* Use 'global' as udata. */ - return (void *) global; -} - -/* - * Misc helpers - */ - -#if defined(DUK_ALLOC_POOL_TRACK_WASTE) -static void duk__alloc_pool_set_waste_marker(void *ptr, size_t used, size_t size) { - /* Rely on the base pointer and size being divisible by 4 and thus - * aligned. Use 32-bit markers: a 4-byte resolution is good enough, - * and comparing 32 bits at a time makes false waste estimates less - * likely than when comparing as bytes. - */ - duk_uint32_t *p, *p_start, *p_end; - size_t used_round; - - used_round = (used + 3U) & ~0x03U; /* round up to 4 */ - p_end = (duk_uint32_t *) ((duk_uint8_t *) ptr + size); - p_start = (duk_uint32_t *) ((duk_uint8_t *) ptr + used_round); - p = (duk_uint32_t *) p_start; - while (p != p_end) { - *p++ = DUK_ALLOC_POOL_WASTE_MARKER; - } -} -#else /* DUK_ALLOC_POOL_TRACK_WASTE */ -static void duk__alloc_pool_set_waste_marker(void *ptr, size_t used, size_t size) { - (void) ptr; (void) used; (void) size; -} -#endif /* DUK_ALLOC_POOL_TRACK_WASTE */ - -#if defined(DUK_ALLOC_POOL_TRACK_WASTE) -static size_t duk__alloc_pool_get_waste_estimate(void *ptr, size_t size) { - duk_uint32_t *p, *p_end, *p_start; - - /* Assumes size is >= 4. */ - p_start = (duk_uint32_t *) ptr; - p_end = (duk_uint32_t *) ((duk_uint8_t *) ptr + size); - p = p_end; - - /* This scan may cause harmless valgrind complaints: there may be - * uninitialized bytes within the legitimate allocation or between - * the start of the waste marker and the end of the allocation. - */ - do { - p--; - if (*p == DUK_ALLOC_POOL_WASTE_MARKER) { - ; - } else { - return (size_t) (p_end - p - 1) * 4U; - } - } while (p != p_start); - - return size; -} -#else /* DUK_ALLOC_POOL_TRACK_WASTE */ -static size_t duk__alloc_pool_get_waste_estimate(void *ptr, size_t size) { - (void) ptr; (void) size; - return 0; -} -#endif /* DUK_ALLOC_POOL_TRACK_WASTE */ - -static int duk__alloc_pool_ptr_in_freelist(duk_pool_state *s, void *ptr) { - duk_pool_free *curr; - - for (curr = s->first; curr != NULL; curr = curr->next) { - if ((void *) curr == ptr) { - return 1; - } - } - return 0; -} - -void duk_alloc_pool_get_pool_stats(duk_pool_state *s, duk_pool_stats *res) { - void *curr; - size_t free_count; - size_t used_count; - size_t waste_bytes; - - curr = s->alloc_end - (s->size * s->count); - free_count = 0U; - waste_bytes = 0U; - while (curr != s->alloc_end) { - if (duk__alloc_pool_ptr_in_freelist(s, curr)) { - free_count++; - } else { - waste_bytes += duk__alloc_pool_get_waste_estimate(curr, s->size); - } - curr = curr + s->size; - } - used_count = (size_t) (s->count - free_count); - - res->used_count = used_count; - res->used_bytes = (size_t) (used_count * s->size); - res->free_count = free_count; - res->free_bytes = (size_t) (free_count * s->size); - res->waste_bytes = waste_bytes; -#if defined(DUK_ALLOC_POOL_TRACK_HIGHWATER) - res->hwm_used_count = s->hwm_used_count; -#else - res->hwm_used_count = 0U; -#endif -} - -void duk_alloc_pool_get_global_stats(duk_pool_global *g, duk_pool_global_stats *res) { - int i; - size_t total_used = 0U; - size_t total_free = 0U; - size_t total_waste = 0U; - - for (i = 0; i < g->num_pools; i++) { - duk_pool_state *s = &g->states[i]; - duk_pool_stats stats; - - duk_alloc_pool_get_pool_stats(s, &stats); - - total_used += stats.used_bytes; - total_free += stats.free_bytes; - total_waste += stats.waste_bytes; - } - - res->used_bytes = total_used; - res->free_bytes = total_free; - res->waste_bytes = total_waste; -#if defined(DUK_ALLOC_POOL_TRACK_HIGHWATER) - res->hwm_used_bytes = g->hwm_used_bytes; - res->hwm_waste_bytes = g->hwm_waste_bytes; -#else - res->hwm_used_bytes = 0U; - res->hwm_waste_bytes = 0U; -#endif -} - -#if defined(DUK_ALLOC_POOL_TRACK_HIGHWATER) -static void duk__alloc_pool_update_highwater(duk_pool_global *g) { - int i; - size_t total_used = 0U; - size_t total_free = 0U; - size_t total_waste = 0U; - - /* Per pool highwater used count, useful to checking if a pool is - * too small. - */ - for (i = 0; i < g->num_pools; i++) { - duk_pool_state *s = &g->states[i]; - duk_pool_stats stats; - - duk_alloc_pool_get_pool_stats(s, &stats); - if (stats.used_count > s->hwm_used_count) { -#if defined(DUK_ALLOC_POOL_DEBUG) - duk__alloc_pool_dprintf("duk__alloc_pool_update_highwater: pool %ld (%ld bytes) highwater updated: count %ld -> %ld\n", - (long) i, (long) s->size, - (long) s->hwm_used_count, (long) stats.used_count); -#endif - s->hwm_used_count = stats.used_count; - } - - total_used += stats.used_bytes; - total_free += stats.free_bytes; - total_waste += stats.waste_bytes; - } - - /* Global highwater mark for used and waste bytes. Both fields are - * updated from the same snapshot based on highest used count. - * This is VERY, VERY slow and only useful for development. - * (Note that updating HWM states for pools individually and then - * summing them won't create a consistent global snapshot. There - * are still easy ways to make this much, much faster.) - */ - if (total_used > g->hwm_used_bytes) { -#if defined(DUK_ALLOC_POOL_DEBUG) - duk__alloc_pool_dprintf("duk__alloc_pool_update_highwater: global highwater updated: used=%ld, bytes=%ld -> " - "used=%ld, bytes=%ld\n", - (long) g->hwm_used_bytes, (long) g->hwm_waste_bytes, - (long) total_used, (long) total_waste); -#endif - g->hwm_used_bytes = total_used; - g->hwm_waste_bytes = total_waste; - } -} -#else /* DUK_ALLOC_POOL_TRACK_HIGHWATER */ -static void duk__alloc_pool_update_highwater(duk_pool_global *g) { - (void) g; -} -#endif /* DUK_ALLOC_POOL_TRACK_HIGHWATER */ - -/* - * Allocation providers - */ - -void *duk_alloc_pool(void *udata, duk_size_t size) { - duk_pool_global *g = (duk_pool_global *) udata; - int i, n; - -#if defined(DUK_ALLOC_POOL_DEBUG) - duk__alloc_pool_dprintf("duk_alloc_pool: %p %ld\n", udata, (long) size); -#endif - - if (size == 0) { - return NULL; - } - - for (i = 0, n = g->num_pools; i < n; i++) { - duk_pool_state *st = g->states + i; - - if (size <= st->size) { - duk_pool_free *res = st->first; - if (res != NULL) { - st->first = res->next; - duk__alloc_pool_set_waste_marker((void *) res, size, st->size); - duk__alloc_pool_update_highwater(g); - return (void *) res; - } - } - - /* Allocation doesn't fit or no free entries, try to borrow - * from the next block size. There's no support for preventing - * a borrow at present. - */ - } - - return NULL; -} - -void *duk_realloc_pool(void *udata, void *ptr, duk_size_t size) { - duk_pool_global *g = (duk_pool_global *) udata; - int i, j, n; - -#if defined(DUK_ALLOC_POOL_DEBUG) - duk__alloc_pool_dprintf("duk_realloc_pool: %p %p %ld\n", udata, ptr, (long) size); -#endif - - if (ptr == NULL) { - return duk_alloc_pool(udata, size); - } - if (size == 0) { - duk_free_pool(udata, ptr); - return NULL; - } - - /* Non-NULL pointers are necessarily from the pool so we should - * always be able to find the allocation. - */ - - for (i = 0, n = g->num_pools; i < n; i++) { - duk_pool_state *st = g->states + i; - char *new_ptr; - - /* Because 'ptr' is assumed to be in the pool and pools are - * allocated in sequence, it suffices to check for end pointer - * only. - */ - if ((char *) ptr >= st->alloc_end) { - continue; - } - - if (size <= st->size) { - /* Allocation still fits existing allocation. Check if - * we can shrink the allocation to a smaller block size - * (smallest possible). - */ - for (j = 0; j < i; j++) { - duk_pool_state *st2 = g->states + j; - - if (size <= st2->size) { - new_ptr = (char *) st2->first; - if (new_ptr != NULL) { -#if defined(DUK_ALLOC_POOL_DEBUG) - duk__alloc_pool_dprintf("duk_realloc_pool: shrink, block size %ld -> %ld\n", - (long) st->size, (long) st2->size); -#endif - st2->first = ((duk_pool_free *) new_ptr)->next; - memcpy((void *) new_ptr, (const void *) ptr, (size_t) size); - ((duk_pool_free *) ptr)->next = st->first; - st->first = (duk_pool_free *) ptr; - duk__alloc_pool_set_waste_marker((void *) new_ptr, size, st2->size); - duk__alloc_pool_update_highwater(g); - return (void *) new_ptr; - } - } - } - - /* Failed to shrink; return existing pointer. */ - duk__alloc_pool_set_waste_marker((void *) ptr, size, st->size); - return ptr; - } - - /* Find first free larger block. */ - for (j = i + 1; j < n; j++) { - duk_pool_state *st2 = g->states + j; - - if (size <= st2->size) { - new_ptr = (char *) st2->first; - if (new_ptr != NULL) { - st2->first = ((duk_pool_free *) new_ptr)->next; - memcpy((void *) new_ptr, (const void *) ptr, (size_t) st->size); - ((duk_pool_free *) ptr)->next = st->first; - st->first = (duk_pool_free *) ptr; - duk__alloc_pool_set_waste_marker((void *) new_ptr, size, st2->size); - duk__alloc_pool_update_highwater(g); - return (void *) new_ptr; - } - } - } - - /* Failed to resize. */ - return NULL; - } - - /* We should never be here because 'ptr' should be a valid pool - * entry and thus always found above. - */ - return NULL; -} - -void duk_free_pool(void *udata, void *ptr) { - duk_pool_global *g = (duk_pool_global *) udata; - int i, n; - -#if defined(DUK_ALLOC_POOL_DEBUG) - duk__alloc_pool_dprintf("duk_free_pool: %p %p\n", udata, ptr); -#endif - - if (ptr == NULL) { - return; - } - - for (i = 0, n = g->num_pools; i < n; i++) { - duk_pool_state *st = g->states + i; - - /* Enough to check end address only. */ - if ((char *) ptr >= st->alloc_end) { - continue; - } - - ((duk_pool_free *) ptr)->next = st->first; - st->first = (duk_pool_free *) ptr; -#if 0 /* never necessary when freeing */ - duk__alloc_pool_update_highwater(g); -#endif - return; - } - - /* We should never be here because 'ptr' should be a valid pool - * entry and thus always found above. - */ -} - -/* - * Pointer compression - */ - -#if defined(DUK_ALLOC_POOL_ROMPTR_COMPRESSION) -static void duk__alloc_pool_romptr_init(void) { - /* Scan ROM pointer range for faster detection of "is 'p' a ROM pointer" - * later on. - */ - const void * const * ptrs = (const void * const *) duk_rom_compressed_pointers; - duk_alloc_pool_romptr_low = duk_alloc_pool_romptr_high = (const void *) *ptrs; - while (*ptrs) { - if (*ptrs > duk_alloc_pool_romptr_high) { - duk_alloc_pool_romptr_high = (const void *) *ptrs; - } - if (*ptrs < duk_alloc_pool_romptr_low) { - duk_alloc_pool_romptr_low = (const void *) *ptrs; - } - ptrs++; - } -} -#endif - -/* Encode/decode functions are defined in the header to allow inlining. */ - -#if defined(DUK_ALLOC_POOL_ROMPTR_COMPRESSION) -duk_uint16_t duk_alloc_pool_enc16_rom(void *ptr) { - /* The if-condition should be the fastest possible check - * for "is 'ptr' in ROM?". If pointer is in ROM, we'd like - * to compress it quickly. Here we just scan a ~1K array - * which is very bad for performance. - */ - const void * const * ptrs = duk_rom_compressed_pointers; - while (*ptrs) { - if (*ptrs == ptr) { - return DUK_ALLOC_POOL_ROMPTR_FIRST + (duk_uint16_t) (ptrs - duk_rom_compressed_pointers); - } - ptrs++; - } - - /* We should really never be here: Duktape should only be - * compressing pointers which are in the ROM compressed - * pointers list, which are known at 'make dist' time. - * We go on, causing a pointer compression error. - */ - return 0; -} -#endif diff --git a/vendor/gopkg.in/olebedev/go-duktape.v3/duk_alloc_pool.h b/vendor/gopkg.in/olebedev/go-duktape.v3/duk_alloc_pool.h deleted file mode 100755 index 286ec016..00000000 --- a/vendor/gopkg.in/olebedev/go-duktape.v3/duk_alloc_pool.h +++ /dev/null @@ -1,223 +0,0 @@ -#if !defined(DUK_ALLOC_POOL_H_INCLUDED) -#define DUK_ALLOC_POOL_H_INCLUDED - -#include "duktape.h" - -/* 32-bit (big endian) marker used at the end of pool entries so that wasted - * space can be detected. Waste tracking must be enabled explicitly. - */ -#if defined(DUK_ALLOC_POOL_TRACK_WASTE) -#define DUK_ALLOC_POOL_WASTE_MARKER 0xedcb2345UL -#endif - -/* Pointer compression with ROM strings/objects: - * - * For now, use DUK_USE_ROM_OBJECTS to signal the need for compressed ROM - * pointers. DUK_USE_ROM_PTRCOMP_FIRST is provided for the ROM pointer - * compression range minimum to avoid duplication in user code. - */ -#if defined(DUK_USE_ROM_OBJECTS) && defined(DUK_USE_HEAPPTR16) -#define DUK_ALLOC_POOL_ROMPTR_COMPRESSION -#define DUK_ALLOC_POOL_ROMPTR_FIRST DUK_USE_ROM_PTRCOMP_FIRST - -/* This extern declaration is provided by duktape.h, array provided by duktape.c. - * Because duk_config.h may include this file (to get the inline functions) we - * need to forward declare this also here. - */ -extern const void * const duk_rom_compressed_pointers[]; -#endif - -/* Pool configuration for a certain block size. */ -typedef struct { - unsigned int size; /* must be divisible by 4 and >= sizeof(void *) */ - unsigned int a; /* bytes (not count) to allocate: a*t + b, t is an arbitrary scale parameter */ - unsigned int b; -} duk_pool_config; - -/* Freelist entry, must fit into the smallest block size. */ -struct duk_pool_free; -typedef struct duk_pool_free duk_pool_free; -struct duk_pool_free { - duk_pool_free *next; -}; - -/* Pool state for a certain block size. */ -typedef struct { - duk_pool_free *first; - char *alloc_end; - unsigned int size; - unsigned int count; -#if defined(DUK_ALLOC_POOL_TRACK_HIGHWATER) - unsigned int hwm_used_count; -#endif -} duk_pool_state; - -/* Statistics for a certain pool. */ -typedef struct { - size_t used_count; - size_t used_bytes; - size_t free_count; - size_t free_bytes; - size_t waste_bytes; - size_t hwm_used_count; -} duk_pool_stats; - -/* Top level state for all pools. Pointer to this struct is used as the allocator - * userdata pointer. - */ -typedef struct { - int num_pools; - duk_pool_state *states; -#if defined(DUK_ALLOC_POOL_TRACK_HIGHWATER) - size_t hwm_used_bytes; - size_t hwm_waste_bytes; -#endif -} duk_pool_global; - -/* Statistics for the entire set of pools. */ -typedef struct { - size_t used_bytes; - size_t free_bytes; - size_t waste_bytes; - size_t hwm_used_bytes; - size_t hwm_waste_bytes; -} duk_pool_global_stats; - -/* Initialize a pool allocator, arguments: - * - buffer and size: continuous region to use for pool, must align to 4 - * - config: configuration for pools in ascending block size - * - state: state for pools, matches config order - * - num_pools: number of entries in 'config' and 'state' - * - global: global state structure - * - * The 'config', 'state', and 'global' pointers must be valid beyond the init - * call, as long as the pool is used. - * - * Returns a void pointer to be used as userdata for the allocator functions. - * Concretely the return value will be "(void *) global", i.e. the global - * state struct. If pool init fails, the return value will be NULL. - */ -void *duk_alloc_pool_init(char *buffer, - size_t size, - const duk_pool_config *configs, - duk_pool_state *states, - int num_pools, - duk_pool_global *global); - -/* Duktape allocation providers. Typing matches Duktape requirements. */ -void *duk_alloc_pool(void *udata, duk_size_t size); -void *duk_realloc_pool(void *udata, void *ptr, duk_size_t size); -void duk_free_pool(void *udata, void *ptr); - -/* Stats. */ -void duk_alloc_pool_get_pool_stats(duk_pool_state *s, duk_pool_stats *res); -void duk_alloc_pool_get_global_stats(duk_pool_global *g, duk_pool_global_stats *res); - -/* Duktape pointer compression global state (assumes single pool). */ -#if defined(DUK_USE_ROM_OBJECTS) && defined(DUK_USE_HEAPPTR16) -extern const void *duk_alloc_pool_romptr_low; -extern const void *duk_alloc_pool_romptr_high; -duk_uint16_t duk_alloc_pool_enc16_rom(void *ptr); -#endif -#if defined(DUK_USE_HEAPPTR16) -extern void *duk_alloc_pool_ptrcomp_base; -#endif - -#if 0 -duk_uint16_t duk_alloc_pool_enc16(void *ptr); -void *duk_alloc_pool_dec16(duk_uint16_t val); -#endif - -/* Inlined pointer compression functions. Gcc and clang -Os won't in - * practice inline these without an "always inline" attribute because it's - * more size efficient (by a few kB) to use explicit calls instead. Having - * these defined inline here allows performance optimized builds to inline - * pointer compression operations. - * - * Pointer compression assumes there's a single globally registered memory - * pool which makes pointer compression more efficient. This would be easy - * to fix by adding a userdata pointer to the compression functions and - * plumbing the heap userdata from the compression/decompression macros. - */ - -/* DUK_ALWAYS_INLINE is not a public API symbol so it may go away in even a - * minor update. But it's pragmatic for this extra because it handles many - * compilers via duk_config.h detection. Check that the macro exists so that - * if it's gone, we can still compile. - */ -#if defined(DUK_ALWAYS_INLINE) -#define DUK__ALLOC_POOL_ALWAYS_INLINE DUK_ALWAYS_INLINE -#else -#define DUK__ALLOC_POOL_ALWAYS_INLINE /* nop */ -#endif - -#if defined(DUK_USE_HEAPPTR16) -static DUK__ALLOC_POOL_ALWAYS_INLINE duk_uint16_t duk_alloc_pool_enc16(void *ptr) { - if (ptr == NULL) { - /* With 'return 0' gcc and clang -Os generate inefficient code. - * For example, gcc -Os generates: - * - * 0804911d : - * 804911d: 55 push %ebp - * 804911e: 85 c0 test %eax,%eax - * 8049120: 89 e5 mov %esp,%ebp - * 8049122: 74 0b je 804912f - * 8049124: 2b 05 e4 90 07 08 sub 0x80790e4,%eax - * 804912a: c1 e8 02 shr $0x2,%eax - * 804912d: eb 02 jmp 8049131 - * 804912f: 31 c0 xor %eax,%eax - * 8049131: 5d pop %ebp - * 8049132: c3 ret - * - * The NULL path checks %eax for zero; if it is zero, a zero - * is unnecessarily loaded into %eax again. The non-zero path - * has an unnecessary jump as a side effect of this. - * - * Using 'return (duk_uint16_t) (intptr_t) ptr;' generates similarly - * inefficient code; not sure how to make the result better. - */ - return 0; - } -#if defined(DUK_ALLOC_POOL_ROMPTR_COMPRESSION) - if (ptr >= duk_alloc_pool_romptr_low && ptr <= duk_alloc_pool_romptr_high) { - /* This is complex enough now to need a separate function. */ - return duk_alloc_pool_enc16_rom(ptr); - } -#endif - return (duk_uint16_t) (((size_t) ((char *) ptr - (char *) duk_alloc_pool_ptrcomp_base)) >> 2); -} - -static DUK__ALLOC_POOL_ALWAYS_INLINE void *duk_alloc_pool_dec16(duk_uint16_t val) { - if (val == 0) { - /* As with enc16 the gcc and clang -Os output is inefficient, - * e.g. gcc -Os: - * - * 08049133 : - * 8049133: 55 push %ebp - * 8049134: 66 85 c0 test %ax,%ax - * 8049137: 89 e5 mov %esp,%ebp - * 8049139: 74 0e je 8049149 - * 804913b: 8b 15 e4 90 07 08 mov 0x80790e4,%edx - * 8049141: 0f b7 c0 movzwl %ax,%eax - * 8049144: 8d 04 82 lea (%edx,%eax,4),%eax - * 8049147: eb 02 jmp 804914b - * 8049149: 31 c0 xor %eax,%eax - * 804914b: 5d pop %ebp - * 804914c: c3 ret - */ - return NULL; - } -#if defined(DUK_ALLOC_POOL_ROMPTR_COMPRESSION) - if (val >= DUK_ALLOC_POOL_ROMPTR_FIRST) { - /* This is a blind lookup, could check index validity. - * Duktape should never decompress a pointer which would - * be out-of-bounds here. - */ - return (void *) (intptr_t) (duk_rom_compressed_pointers[val - DUK_ALLOC_POOL_ROMPTR_FIRST]); - } -#endif - return (void *) ((char *) duk_alloc_pool_ptrcomp_base + (((size_t) val) << 2)); -} -#endif - -#endif /* DUK_ALLOC_POOL_H_INCLUDED */ diff --git a/vendor/gopkg.in/olebedev/go-duktape.v3/duk_config.h b/vendor/gopkg.in/olebedev/go-duktape.v3/duk_config.h deleted file mode 100755 index 3f217ef7..00000000 --- a/vendor/gopkg.in/olebedev/go-duktape.v3/duk_config.h +++ /dev/null @@ -1,3672 +0,0 @@ -/* - * duk_config.h configuration header generated by genconfig.py. - * - * Git commit: a459cf3c9bd1779fc01b435d69302b742675a08f - * Git describe: v2.2.0 - * Git branch: master - * - * Supported platforms: - * - Mac OSX, iPhone, Darwin - * - Orbis - * - OpenBSD - * - Generic BSD - * - Atari ST TOS - * - AmigaOS - * - Durango (XboxOne) - * - Windows - * - Flashplayer (Crossbridge) - * - QNX - * - TI-Nspire - * - Emscripten - * - Linux - * - Solaris - * - AIX - * - HPUX - * - Generic POSIX - * - Cygwin - * - Generic UNIX - * - Generic fallback - * - * Supported architectures: - * - x86 - * - x64 - * - x32 - * - ARM 32-bit - * - ARM 64-bit - * - MIPS 32-bit - * - MIPS 64-bit - * - PowerPC 32-bit - * - PowerPC 64-bit - * - SPARC 32-bit - * - SPARC 64-bit - * - SuperH - * - Motorola 68k - * - Emscripten - * - Generic - * - * Supported compilers: - * - Clang - * - GCC - * - MSVC - * - Emscripten - * - TinyC - * - VBCC - * - Bruce's C compiler - * - Generic - * - */ - -#if !defined(DUK_CONFIG_H_INCLUDED) -#define DUK_CONFIG_H_INCLUDED - -/* - * Intermediate helper defines - */ - -/* DLL build detection */ -/* not configured for DLL build */ -#undef DUK_F_DLL_BUILD - -/* Apple OSX, iOS */ -#if defined(__APPLE__) -#define DUK_F_APPLE -#endif - -/* FreeBSD */ -#if defined(__FreeBSD__) || defined(__FreeBSD) -#define DUK_F_FREEBSD -#endif - -/* Orbis (PS4) variant */ -#if defined(DUK_F_FREEBSD) && defined(__ORBIS__) -#define DUK_F_ORBIS -#endif - -/* OpenBSD */ -#if defined(__OpenBSD__) || defined(__OpenBSD) -#define DUK_F_OPENBSD -#endif - -/* NetBSD */ -#if defined(__NetBSD__) || defined(__NetBSD) -#define DUK_F_NETBSD -#endif - -/* BSD variant */ -#if defined(DUK_F_FREEBSD) || defined(DUK_F_NETBSD) || defined(DUK_F_OPENBSD) || \ - defined(__bsdi__) || defined(__DragonFly__) -#define DUK_F_BSD -#endif - -/* Atari ST TOS. __TOS__ defined by PureC. No platform define in VBCC - * apparently, so to use with VBCC user must define __TOS__ manually. - */ -#if defined(__TOS__) -#define DUK_F_TOS -#endif - -/* Motorola 68K. Not defined by VBCC, so user must define one of these - * manually when using VBCC. - */ -#if defined(__m68k__) || defined(M68000) || defined(__MC68K__) -#define DUK_F_M68K -#endif - -/* AmigaOS. Neither AMIGA nor __amigaos__ is defined on VBCC, so user must - * define 'AMIGA' manually when using VBCC. - */ -#if defined(AMIGA) || defined(__amigaos__) -#define DUK_F_AMIGAOS -#endif - -/* PowerPC */ -#if defined(__powerpc) || defined(__powerpc__) || defined(__PPC__) -#define DUK_F_PPC -#if defined(__PPC64__) || defined(__LP64__) || defined(_LP64) -#define DUK_F_PPC64 -#else -#define DUK_F_PPC32 -#endif -#endif - -/* Durango (Xbox One) */ -#if defined(_DURANGO) || defined(_XBOX_ONE) -#define DUK_F_DURANGO -#endif - -/* Windows, both 32-bit and 64-bit */ -#if defined(_WIN32) || defined(WIN32) || defined(_WIN64) || defined(WIN64) || \ - defined(__WIN32__) || defined(__TOS_WIN__) || defined(__WINDOWS__) -#define DUK_F_WINDOWS -#if defined(_WIN64) || defined(WIN64) -#define DUK_F_WIN64 -#else -#define DUK_F_WIN32 -#endif -#endif - -/* Flash player (e.g. Crossbridge) */ -#if defined(__FLASHPLAYER__) -#define DUK_F_FLASHPLAYER -#endif - -/* QNX */ -#if defined(__QNX__) -#define DUK_F_QNX -#endif - -/* TI-Nspire (using Ndless) */ -#if defined(_TINSPIRE) -#define DUK_F_TINSPIRE -#endif - -/* Emscripten (provided explicitly by user), improve if possible */ -#if defined(EMSCRIPTEN) -#define DUK_F_EMSCRIPTEN -#endif - -/* BCC (Bruce's C compiler): this is a "torture target" for compilation */ -#if defined(__BCC__) || defined(__BCC_VERSION__) -#define DUK_F_BCC -#endif - -/* Linux */ -#if defined(__linux) || defined(__linux__) || defined(linux) -#define DUK_F_LINUX -#endif - -/* illumos / Solaris */ -#if defined(__sun) && defined(__SVR4) -#define DUK_F_SUN -#if defined(__SUNPRO_C) && (__SUNPRO_C < 0x550) -#define DUK_F_OLD_SOLARIS -/* Defines _ILP32 / _LP64 required by DUK_F_X86/DUK_F_X64. Platforms - * are processed before architectures, so this happens before the - * DUK_F_X86/DUK_F_X64 detection is emitted. - */ -#include -#endif -#endif - -/* AIX */ -#if defined(_AIX) -/* defined(__xlc__) || defined(__IBMC__): works but too wide */ -#define DUK_F_AIX -#endif - -/* HPUX */ -#if defined(__hpux) -#define DUK_F_HPUX -#if defined(__ia64) -#define DUK_F_HPUX_ITANIUM -#endif -#endif - -/* POSIX */ -#if defined(__posix) -#define DUK_F_POSIX -#endif - -/* Cygwin */ -#if defined(__CYGWIN__) -#define DUK_F_CYGWIN -#endif - -/* Generic Unix (includes Cygwin) */ -#if defined(__unix) || defined(__unix__) || defined(unix) || \ - defined(DUK_F_LINUX) || defined(DUK_F_BSD) -#define DUK_F_UNIX -#endif - -/* C++ */ -#undef DUK_F_CPP -#if defined(__cplusplus) -#define DUK_F_CPP -#endif - -/* Intel x86 (32-bit), x64 (64-bit) or x32 (64-bit but 32-bit pointers), - * define only one of DUK_F_X86, DUK_F_X64, DUK_F_X32. - * https://sites.google.com/site/x32abi/ - * - * With DUK_F_OLD_SOLARIS the header must be included - * before this. - */ -#if defined(__amd64__) || defined(__amd64) || \ - defined(__x86_64__) || defined(__x86_64) || \ - defined(_M_X64) || defined(_M_AMD64) -#if defined(__ILP32__) || defined(_ILP32) -#define DUK_F_X32 -#else -#define DUK_F_X64 -#endif -#elif defined(i386) || defined(__i386) || defined(__i386__) || \ - defined(__i486__) || defined(__i586__) || defined(__i686__) || \ - defined(__IA32__) || defined(_M_IX86) || defined(__X86__) || \ - defined(_X86_) || defined(__THW_INTEL__) || defined(__I86__) -#if defined(__LP64__) || defined(_LP64) -/* This should not really happen, but would indicate x64. */ -#define DUK_F_X64 -#else -#define DUK_F_X86 -#endif -#endif - -/* ARM */ -#if defined(__arm__) || defined(__thumb__) || defined(_ARM) || defined(_M_ARM) || defined(__aarch64__) -#define DUK_F_ARM -#if defined(__LP64__) || defined(_LP64) || defined(__arm64) || defined(__arm64__) || defined(__aarch64__) -#define DUK_F_ARM64 -#else -#define DUK_F_ARM32 -#endif -#endif - -/* MIPS. Related defines: __MIPSEB__, __MIPSEL__, __mips_isa_rev, __LP64__ */ -#if defined(__mips__) || defined(mips) || defined(_MIPS_ISA) || \ - defined(_R3000) || defined(_R4000) || defined(_R5900) || \ - defined(_MIPS_ISA_MIPS1) || defined(_MIPS_ISA_MIPS2) || \ - defined(_MIPS_ISA_MIPS3) || defined(_MIPS_ISA_MIPS4) || \ - defined(__mips) || defined(__MIPS__) -#define DUK_F_MIPS -#if defined(__LP64__) || defined(_LP64) || defined(__mips64) || \ - defined(__mips64__) || defined(__mips_n64) -#define DUK_F_MIPS64 -#else -#define DUK_F_MIPS32 -#endif -#endif - -/* SPARC */ -#if defined(sparc) || defined(__sparc) || defined(__sparc__) -#define DUK_F_SPARC -#if defined(__LP64__) || defined(_LP64) -#define DUK_F_SPARC64 -#else -#define DUK_F_SPARC32 -#endif -#endif - -/* SuperH */ -#if defined(__sh__) || \ - defined(__sh1__) || defined(__SH1__) || \ - defined(__sh2__) || defined(__SH2__) || \ - defined(__sh3__) || defined(__SH3__) || \ - defined(__sh4__) || defined(__SH4__) || \ - defined(__sh5__) || defined(__SH5__) -#define DUK_F_SUPERH -#endif - -/* Clang */ -#if defined(__clang__) -#define DUK_F_CLANG -#endif - -/* C99 or above */ -#undef DUK_F_C99 -#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) -#define DUK_F_C99 -#endif - -/* C++11 or above */ -#undef DUK_F_CPP11 -#if defined(__cplusplus) && (__cplusplus >= 201103L) -#define DUK_F_CPP11 -#endif - -/* GCC. Clang also defines __GNUC__ so don't detect GCC if using Clang. */ -#if defined(__GNUC__) && !defined(__clang__) && !defined(DUK_F_CLANG) -#define DUK_F_GCC -#if defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__) -/* Convenience, e.g. gcc 4.5.1 == 40501; http://stackoverflow.com/questions/6031819/emulating-gccs-builtin-unreachable */ -#define DUK_F_GCC_VERSION (__GNUC__ * 10000L + __GNUC_MINOR__ * 100L + __GNUC_PATCHLEVEL__) -#else -#error cannot figure out gcc version -#endif -#endif - -/* MinGW. Also GCC flags (DUK_F_GCC) are enabled now. */ -#if defined(__MINGW32__) || defined(__MINGW64__) -#define DUK_F_MINGW -#endif - -/* MSVC */ -#if defined(_MSC_VER) -/* MSVC preprocessor defines: http://msdn.microsoft.com/en-us/library/b0084kay.aspx - * _MSC_FULL_VER includes the build number, but it has at least two formats, see e.g. - * BOOST_MSVC_FULL_VER in http://www.boost.org/doc/libs/1_52_0/boost/config/compiler/visualc.hpp - */ -#define DUK_F_MSVC -#if defined(_MSC_FULL_VER) -#if (_MSC_FULL_VER > 100000000) -#define DUK_F_MSVC_FULL_VER _MSC_FULL_VER -#else -#define DUK_F_MSCV_FULL_VER (_MSC_FULL_VER * 10) -#endif -#endif -#endif /* _MSC_VER */ - -/* TinyC */ -#if defined(__TINYC__) -/* http://bellard.org/tcc/tcc-doc.html#SEC9 */ -#define DUK_F_TINYC -#endif - -/* VBCC */ -#if defined(__VBCC__) -#define DUK_F_VBCC -#endif - -#if defined(ANDROID) || defined(__ANDROID__) -#define DUK_F_ANDROID -#endif - -/* Atari Mint */ -#if defined(__MINT__) -#define DUK_F_MINT -#endif - -/* - * Platform autodetection - */ - -/* Workaround for older C++ compilers before including , - * see e.g.: https://sourceware.org/bugzilla/show_bug.cgi?id=15366 - */ -#if defined(__cplusplus) && !defined(__STDC_LIMIT_MACROS) -#define __STDC_LIMIT_MACROS -#endif -#if defined(__cplusplus) && !defined(__STDC_CONSTANT_MACROS) -#define __STDC_CONSTANT_MACROS -#endif - -#if defined(DUK_F_APPLE) -/* --- Mac OSX, iPhone, Darwin --- */ -#define DUK_USE_DATE_NOW_GETTIMEOFDAY -#define DUK_USE_DATE_TZO_GMTIME_R -#define DUK_USE_DATE_PRS_STRPTIME -#define DUK_USE_DATE_FMT_STRFTIME -#include -#include -#include -#include -#include - -/* http://stackoverflow.com/questions/5919996/how-to-detect-reliably-mac-os-x-ios-linux-windows-in-c-preprocessor */ -#if TARGET_IPHONE_SIMULATOR -#define DUK_USE_OS_STRING "iphone-sim" -#elif TARGET_OS_IPHONE -#define DUK_USE_OS_STRING "iphone" -#elif TARGET_OS_MAC -#define DUK_USE_OS_STRING "osx" -#else -#define DUK_USE_OS_STRING "osx-unknown" -#endif - -/* Use _setjmp() on Apple by default, see GH-55. */ -#define DUK_JMPBUF_TYPE jmp_buf -#define DUK_SETJMP(jb) _setjmp((jb)) -#define DUK_LONGJMP(jb) _longjmp((jb), 1) -#elif defined(DUK_F_ORBIS) -/* --- Orbis --- */ -/* Orbis = PS4 */ -#define DUK_USE_DATE_NOW_GETTIMEOFDAY -#define DUK_USE_DATE_TZO_GMTIME_S -/* no parsing (not an error) */ -#define DUK_USE_DATE_FMT_STRFTIME -#include -#include -#include -#include -#include - -#define DUK_USE_OS_STRING "orbis" -#elif defined(DUK_F_OPENBSD) -/* --- OpenBSD --- */ -/* http://www.monkey.org/openbsd/archive/ports/0401/msg00089.html */ -#define DUK_USE_DATE_NOW_GETTIMEOFDAY -#define DUK_USE_DATE_TZO_GMTIME_R -#define DUK_USE_DATE_PRS_STRPTIME -#define DUK_USE_DATE_FMT_STRFTIME -#include -#include -#include -#include -#include - -#define DUK_USE_OS_STRING "openbsd" -#elif defined(DUK_F_BSD) -/* --- Generic BSD --- */ -#define DUK_USE_DATE_NOW_GETTIMEOFDAY -#define DUK_USE_DATE_TZO_GMTIME_R -#define DUK_USE_DATE_PRS_STRPTIME -#define DUK_USE_DATE_FMT_STRFTIME -#include -#include -#include -#include -#include - -#define DUK_USE_OS_STRING "bsd" -#elif defined(DUK_F_TOS) -/* --- Atari ST TOS --- */ -#define DUK_USE_DATE_NOW_TIME -#define DUK_USE_DATE_TZO_GMTIME -/* no parsing (not an error) */ -#define DUK_USE_DATE_FMT_STRFTIME -#include - -#define DUK_USE_OS_STRING "tos" - -/* TOS on M68K is always big endian. */ -#if !defined(DUK_USE_BYTEORDER) && defined(DUK_F_M68K) -#define DUK_USE_BYTEORDER 3 -#endif -#elif defined(DUK_F_AMIGAOS) -/* --- AmigaOS --- */ -#if defined(DUK_F_M68K) -/* AmigaOS on M68k */ -#define DUK_USE_DATE_NOW_TIME -#define DUK_USE_DATE_TZO_GMTIME -/* no parsing (not an error) */ -#define DUK_USE_DATE_FMT_STRFTIME -#include -#elif defined(DUK_F_PPC) -#define DUK_USE_DATE_NOW_GETTIMEOFDAY -#define DUK_USE_DATE_TZO_GMTIME_R -#define DUK_USE_DATE_PRS_STRPTIME -#define DUK_USE_DATE_FMT_STRFTIME -#include -#if !defined(UINTPTR_MAX) -#define UINTPTR_MAX UINT_MAX -#endif -#else -#error AmigaOS but not M68K/PPC, not supported now -#endif - -#define DUK_USE_OS_STRING "amigaos" - -/* AmigaOS on M68K or PPC is always big endian. */ -#if !defined(DUK_USE_BYTEORDER) && (defined(DUK_F_M68K) || defined(DUK_F_PPC)) -#define DUK_USE_BYTEORDER 3 -#endif -#elif defined(DUK_F_DURANGO) -/* --- Durango (XboxOne) --- */ -/* Durango = XboxOne - * Configuration is nearly identical to Windows, except for - * DUK_USE_DATE_TZO_WINDOWS. - */ - -/* Initial fix: disable secure CRT related warnings when compiling Duktape - * itself (must be defined before including Windows headers). Don't define - * for user code including duktape.h. - */ -#if defined(DUK_COMPILING_DUKTAPE) && !defined(_CRT_SECURE_NO_WARNINGS) -#define _CRT_SECURE_NO_WARNINGS -#endif - -/* MSVC does not have sys/param.h */ -#define DUK_USE_DATE_NOW_WINDOWS -#define DUK_USE_DATE_TZO_WINDOWS_NO_DST -/* Note: PRS and FMT are intentionally left undefined for now. This means - * there is no platform specific date parsing/formatting but there is still - * the ISO 8601 standard format. - */ -#if defined(DUK_COMPILING_DUKTAPE) -/* Only include when compiling Duktape to avoid polluting application build - * with a lot of unnecessary defines. - */ -#include -#endif - -#define DUK_USE_OS_STRING "durango" - -#if !defined(DUK_USE_BYTEORDER) -#define DUK_USE_BYTEORDER 1 -#endif -#elif defined(DUK_F_WINDOWS) -/* --- Windows --- */ -/* Windows version can't obviously be determined at compile time, - * but _WIN32_WINNT indicates the minimum version targeted: - * - https://msdn.microsoft.com/en-us/library/6sehtctf.aspx - */ - -/* Initial fix: disable secure CRT related warnings when compiling Duktape - * itself (must be defined before including Windows headers). Don't define - * for user code including duktape.h. - */ -#if defined(DUK_COMPILING_DUKTAPE) && !defined(_CRT_SECURE_NO_WARNINGS) -#define _CRT_SECURE_NO_WARNINGS -#endif - -/* Windows 32-bit and 64-bit are currently the same. */ -/* MSVC does not have sys/param.h */ - -#if defined(DUK_COMPILING_DUKTAPE) -/* Only include when compiling Duktape to avoid polluting application build - * with a lot of unnecessary defines. - */ -#include -#endif - -/* GetSystemTimePreciseAsFileTime() available from Windows 8: - * https://msdn.microsoft.com/en-us/library/windows/desktop/hh706895(v=vs.85).aspx - */ -#if defined(DUK_USE_DATE_NOW_WINDOWS_SUBMS) || defined(DUK_USE_DATE_NOW_WINDOWS) -/* User forced provider. */ -#else -#if defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0602) -#define DUK_USE_DATE_NOW_WINDOWS_SUBMS -#else -#define DUK_USE_DATE_NOW_WINDOWS -#endif -#endif - -#define DUK_USE_DATE_TZO_WINDOWS - -/* Note: PRS and FMT are intentionally left undefined for now. This means - * there is no platform specific date parsing/formatting but there is still - * the ISO 8601 standard format. - */ - -/* QueryPerformanceCounter() may go backwards in Windows XP, so enable for - * Vista and later: https://msdn.microsoft.com/en-us/library/windows/desktop/dn553408(v=vs.85).aspx#qpc_support_in_windows_versions - */ -#if !defined(DUK_USE_GET_MONOTONIC_TIME_WINDOWS_QPC) && \ - defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0600) -#define DUK_USE_GET_MONOTONIC_TIME_WINDOWS_QPC -#endif - -#define DUK_USE_OS_STRING "windows" - -/* On Windows, assume we're little endian. Even Itanium which has a - * configurable endianness runs little endian in Windows. - */ -#if !defined(DUK_USE_BYTEORDER) -#define DUK_USE_BYTEORDER 1 -#endif -#elif defined(DUK_F_FLASHPLAYER) -/* --- Flashplayer (Crossbridge) --- */ -#define DUK_USE_DATE_NOW_GETTIMEOFDAY -#define DUK_USE_DATE_TZO_GMTIME_R -#define DUK_USE_DATE_PRS_STRPTIME -#define DUK_USE_DATE_FMT_STRFTIME -#include -#include -#include -#include - -#define DUK_USE_OS_STRING "flashplayer" - -#if !defined(DUK_USE_BYTEORDER) && defined(DUK_F_FLASHPLAYER) -#define DUK_USE_BYTEORDER 1 -#endif -#elif defined(DUK_F_QNX) -/* --- QNX --- */ -#if defined(DUK_F_QNX) && defined(DUK_COMPILING_DUKTAPE) -/* See: /opt/qnx650/target/qnx6/usr/include/sys/platform.h */ -#define _XOPEN_SOURCE 600 -#define _POSIX_C_SOURCE 200112L -#endif - -#define DUK_USE_DATE_NOW_GETTIMEOFDAY -#define DUK_USE_DATE_TZO_GMTIME_R -#define DUK_USE_DATE_PRS_STRPTIME -#define DUK_USE_DATE_FMT_STRFTIME -#include -#include -#include -#include - -#define DUK_USE_OS_STRING "qnx" -#elif defined(DUK_F_TINSPIRE) -/* --- TI-Nspire --- */ -#if defined(DUK_COMPILING_DUKTAPE) && !defined(_XOPEN_SOURCE) -#define _XOPEN_SOURCE /* e.g. strptime */ -#endif - -#define DUK_USE_DATE_NOW_GETTIMEOFDAY -#define DUK_USE_DATE_TZO_GMTIME_R -#define DUK_USE_DATE_PRS_STRPTIME -#define DUK_USE_DATE_FMT_STRFTIME -#include -#include -#include -#include - -#define DUK_USE_OS_STRING "tinspire" -#elif defined(DUK_F_EMSCRIPTEN) -/* --- Emscripten --- */ -#if defined(DUK_COMPILING_DUKTAPE) -#if !defined(_POSIX_C_SOURCE) -#define _POSIX_C_SOURCE 200809L -#endif -#if !defined(_GNU_SOURCE) -#define _GNU_SOURCE /* e.g. getdate_r */ -#endif -#if !defined(_XOPEN_SOURCE) -#define _XOPEN_SOURCE /* e.g. strptime */ -#endif -#endif /* DUK_COMPILING_DUKTAPE */ - -#include -#if defined(DUK_F_BCC) -/* no endian.h */ -#else -#include -#endif /* DUK_F_BCC */ -#include -#include -#include -#include - -#define DUK_USE_DATE_NOW_GETTIMEOFDAY -#define DUK_USE_DATE_TZO_GMTIME_R -#define DUK_USE_DATE_PRS_STRPTIME -#define DUK_USE_DATE_FMT_STRFTIME - -#define DUK_USE_OS_STRING "emscripten" -#elif defined(DUK_F_LINUX) -/* --- Linux --- */ -#if defined(DUK_COMPILING_DUKTAPE) -#if !defined(_POSIX_C_SOURCE) -#define _POSIX_C_SOURCE 200809L -#endif -#if !defined(_GNU_SOURCE) -#define _GNU_SOURCE /* e.g. getdate_r */ -#endif -#if !defined(_XOPEN_SOURCE) -#define _XOPEN_SOURCE /* e.g. strptime */ -#endif -#endif /* DUK_COMPILING_DUKTAPE */ - -#include -#if defined(DUK_F_BCC) -/* no endian.h or stdint.h */ -#else -#include -#include -#endif /* DUK_F_BCC */ -#include -#include -#include - -#define DUK_USE_DATE_NOW_GETTIMEOFDAY -#define DUK_USE_DATE_TZO_GMTIME_R -#define DUK_USE_DATE_PRS_STRPTIME -#define DUK_USE_DATE_FMT_STRFTIME - -#if 0 /* XXX: safe condition? */ -#define DUK_USE_GET_MONOTONIC_TIME_CLOCK_GETTIME -#endif - -#define DUK_USE_OS_STRING "linux" -#elif defined(DUK_F_SUN) -/* --- Solaris --- */ -#define DUK_USE_DATE_NOW_GETTIMEOFDAY -#define DUK_USE_DATE_TZO_GMTIME_R -#define DUK_USE_DATE_PRS_STRPTIME -#define DUK_USE_DATE_FMT_STRFTIME - -#include -#if defined(DUK_F_OLD_SOLARIS) -/* Old Solaris with no endian.h, stdint.h */ -#define DUK_F_NO_STDINT_H -#if !defined(DUK_USE_BYTEORDER) -#define DUK_USE_BYTEORDER 3 -#endif -#else /* DUK_F_OLD_SOLARIS */ -#include -#endif /* DUK_F_OLD_SOLARIS */ - -#include -#include -#include - -#define DUK_USE_OS_STRING "solaris" -#elif defined(DUK_F_AIX) -/* --- AIX --- */ -#if !defined(DUK_USE_BYTEORDER) -#define DUK_USE_BYTEORDER 3 -#endif -#define DUK_USE_DATE_NOW_GETTIMEOFDAY -#define DUK_USE_DATE_TZO_GMTIME_R -#define DUK_USE_DATE_PRS_STRPTIME -#define DUK_USE_DATE_FMT_STRFTIME -#include -#include -#include - -#define DUK_USE_OS_STRING "aix" -#elif defined(DUK_F_HPUX) -/* --- HPUX --- */ -#define DUK_F_NO_STDINT_H -#if !defined(DUK_USE_BYTEORDER) -#define DUK_USE_BYTEORDER 3 -#endif -#define DUK_USE_DATE_NOW_GETTIMEOFDAY -#define DUK_USE_DATE_TZO_GMTIME_R -#define DUK_USE_DATE_PRS_STRPTIME -#define DUK_USE_DATE_FMT_STRFTIME -#include -#include -#include - -#define DUK_USE_OS_STRING "hpux" -#elif defined(DUK_F_POSIX) -/* --- Generic POSIX --- */ -#define DUK_USE_DATE_NOW_GETTIMEOFDAY -#define DUK_USE_DATE_TZO_GMTIME_R -#define DUK_USE_DATE_PRS_STRPTIME -#define DUK_USE_DATE_FMT_STRFTIME -#include -#include -#include -#include -#include - -#define DUK_USE_OS_STRING "posix" -#elif defined(DUK_F_CYGWIN) -/* --- Cygwin --- */ -/* don't use strptime() for now */ -#define DUK_USE_DATE_NOW_GETTIMEOFDAY -#define DUK_USE_DATE_TZO_GMTIME_R -#define DUK_USE_DATE_FMT_STRFTIME -#include -#include -#include -#include -#include - -#define DUK_JMPBUF_TYPE jmp_buf -#define DUK_SETJMP(jb) _setjmp((jb)) -#define DUK_LONGJMP(jb) _longjmp((jb), 1) - -#define DUK_USE_OS_STRING "windows" -#elif defined(DUK_F_UNIX) -/* --- Generic UNIX --- */ -#define DUK_USE_DATE_NOW_GETTIMEOFDAY -#define DUK_USE_DATE_TZO_GMTIME_R -#define DUK_USE_DATE_PRS_STRPTIME -#define DUK_USE_DATE_FMT_STRFTIME -#include -#include -#define DUK_USE_OS_STRING "unknown" -#else -/* --- Generic fallback --- */ -/* The most portable current time provider is time(), but it only has a - * one second resolution. - */ -#define DUK_USE_DATE_NOW_TIME - -/* The most portable way to figure out local time offset is gmtime(), - * but it's not thread safe so use with caution. - */ -#define DUK_USE_DATE_TZO_GMTIME - -/* Avoid custom date parsing and formatting for portability. */ -#undef DUK_USE_DATE_PRS_STRPTIME -#undef DUK_USE_DATE_FMT_STRFTIME - -/* Rely on C89 headers only; time.h must be here. */ -#include - -#define DUK_USE_OS_STRING "unknown" -#endif /* autodetect platform */ - -/* Shared includes: C89 */ -#include -#include -#include -#include /* varargs */ -#include -#include /* e.g. ptrdiff_t */ -#include -#include - -/* date.h is omitted, and included per platform */ - -/* Shared includes: stdint.h is C99 */ -#if defined(DUK_F_NO_STDINT_H) -/* stdint.h not available */ -#else -/* Technically C99 (C++11) but found in many systems. On some systems - * __STDC_LIMIT_MACROS and __STDC_CONSTANT_MACROS must be defined before - * including stdint.h (see above). - */ -#include -#endif - -#if defined(DUK_F_CPP) -#include /* std::exception */ -#endif - -/* - * Architecture autodetection - */ - -#if defined(DUK_F_X86) -/* --- x86 --- */ -#define DUK_USE_ARCH_STRING "x86" -#if !defined(DUK_USE_BYTEORDER) -#define DUK_USE_BYTEORDER 1 -#endif -/* XXX: This is technically not guaranteed because it's possible to configure - * an x86 to require aligned accesses with Alignment Check (AC) flag. - */ -#if !defined(DUK_USE_ALIGN_BY) -#define DUK_USE_ALIGN_BY 1 -#endif -#define DUK_USE_PACKED_TVAL -#define DUK_F_PACKED_TVAL_PROVIDED -#elif defined(DUK_F_X64) -/* --- x64 --- */ -#define DUK_USE_ARCH_STRING "x64" -#if !defined(DUK_USE_BYTEORDER) -#define DUK_USE_BYTEORDER 1 -#endif -/* XXX: This is technically not guaranteed because it's possible to configure - * an x86 to require aligned accesses with Alignment Check (AC) flag. - */ -#if !defined(DUK_USE_ALIGN_BY) -#define DUK_USE_ALIGN_BY 1 -#endif -#undef DUK_USE_PACKED_TVAL -#define DUK_F_PACKED_TVAL_PROVIDED -#elif defined(DUK_F_X32) -/* --- x32 --- */ -#define DUK_USE_ARCH_STRING "x32" -#if !defined(DUK_USE_BYTEORDER) -#define DUK_USE_BYTEORDER 1 -#endif -/* XXX: This is technically not guaranteed because it's possible to configure - * an x86 to require aligned accesses with Alignment Check (AC) flag. - */ -#if !defined(DUK_USE_ALIGN_BY) -#define DUK_USE_ALIGN_BY 1 -#endif -#define DUK_USE_PACKED_TVAL -#define DUK_F_PACKED_TVAL_PROVIDED -#elif defined(DUK_F_ARM32) -/* --- ARM 32-bit --- */ -#define DUK_USE_ARCH_STRING "arm32" -/* Byte order varies, so rely on autodetect. */ -#if !defined(DUK_USE_ALIGN_BY) -#define DUK_USE_ALIGN_BY 4 -#endif -#define DUK_USE_PACKED_TVAL -#define DUK_F_PACKED_TVAL_PROVIDED -#elif defined(DUK_F_ARM64) -/* --- ARM 64-bit --- */ -#define DUK_USE_ARCH_STRING "arm64" -/* Byte order varies, so rely on autodetect. */ -#if !defined(DUK_USE_ALIGN_BY) -#define DUK_USE_ALIGN_BY 8 -#endif -#undef DUK_USE_PACKED_TVAL -#define DUK_F_PACKED_TVAL_PROVIDED -#elif defined(DUK_F_MIPS32) -/* --- MIPS 32-bit --- */ -#define DUK_USE_ARCH_STRING "mips32" -/* MIPS byte order varies so rely on autodetection. */ -#if !defined(DUK_USE_ALIGN_BY) -#define DUK_USE_ALIGN_BY 8 -#endif -#define DUK_USE_PACKED_TVAL -#define DUK_F_PACKED_TVAL_PROVIDED -#elif defined(DUK_F_MIPS64) -/* --- MIPS 64-bit --- */ -#define DUK_USE_ARCH_STRING "mips64" -/* MIPS byte order varies so rely on autodetection. */ -#if !defined(DUK_USE_ALIGN_BY) -#define DUK_USE_ALIGN_BY 8 -#endif -#undef DUK_USE_PACKED_TVAL -#define DUK_F_PACKED_TVAL_PROVIDED -#elif defined(DUK_F_PPC32) -/* --- PowerPC 32-bit --- */ -#define DUK_USE_ARCH_STRING "ppc32" -#if !defined(DUK_USE_BYTEORDER) -#define DUK_USE_BYTEORDER 3 -#endif -#if !defined(DUK_USE_ALIGN_BY) -#define DUK_USE_ALIGN_BY 8 -#endif -#define DUK_USE_PACKED_TVAL -#define DUK_F_PACKED_TVAL_PROVIDED -#elif defined(DUK_F_PPC64) -/* --- PowerPC 64-bit --- */ -#define DUK_USE_ARCH_STRING "ppc64" -#if !defined(DUK_USE_BYTEORDER) -#define DUK_USE_BYTEORDER 3 -#endif -#if !defined(DUK_USE_ALIGN_BY) -#define DUK_USE_ALIGN_BY 8 -#endif -#undef DUK_USE_PACKED_TVAL -#define DUK_F_PACKED_TVAL_PROVIDED -#elif defined(DUK_F_SPARC32) -/* --- SPARC 32-bit --- */ -#define DUK_USE_ARCH_STRING "sparc32" -/* SPARC byte order varies so rely on autodetection. */ -#if !defined(DUK_USE_ALIGN_BY) -#define DUK_USE_ALIGN_BY 8 -#endif -#define DUK_USE_PACKED_TVAL -#define DUK_F_PACKED_TVAL_PROVIDED -#elif defined(DUK_F_SPARC64) -/* --- SPARC 64-bit --- */ -#define DUK_USE_ARCH_STRING "sparc64" -/* SPARC byte order varies so rely on autodetection. */ -#if !defined(DUK_USE_ALIGN_BY) -#define DUK_USE_ALIGN_BY 8 -#endif -#undef DUK_USE_PACKED_TVAL -#define DUK_F_PACKED_TVAL_PROVIDED -#elif defined(DUK_F_SUPERH) -/* --- SuperH --- */ -#define DUK_USE_ARCH_STRING "sh" -/* Byte order varies, rely on autodetection. */ -/* Based on 'make checkalign' there are no alignment requirements on - * Linux SH4, but align by 4 is probably a good basic default. - */ -#if !defined(DUK_USE_ALIGN_BY) -#define DUK_USE_ALIGN_BY 4 -#endif -#define DUK_USE_PACKED_TVAL -#define DUK_F_PACKED_TVAL_PROVIDED -#elif defined(DUK_F_M68K) -/* --- Motorola 68k --- */ -#define DUK_USE_ARCH_STRING "m68k" -#if !defined(DUK_USE_BYTEORDER) -#define DUK_USE_BYTEORDER 3 -#endif -#if !defined(DUK_USE_ALIGN_BY) -#define DUK_USE_ALIGN_BY 8 -#endif -#define DUK_USE_PACKED_TVAL -#define DUK_F_PACKED_TVAL_PROVIDED -#elif defined(DUK_F_EMSCRIPTEN) -/* --- Emscripten --- */ -#define DUK_USE_ARCH_STRING "emscripten" -#if !defined(DUK_USE_BYTEORDER) -#define DUK_USE_BYTEORDER 1 -#endif -#if !defined(DUK_USE_ALIGN_BY) -#define DUK_USE_ALIGN_BY 8 -#endif -#undef DUK_USE_PACKED_TVAL -#define DUK_F_PACKED_TVAL_PROVIDED -#else -/* --- Generic --- */ -/* These are necessary wild guesses. */ -#define DUK_USE_ARCH_STRING "generic" -/* Rely on autodetection for byte order, alignment, and packed tval. */ -#endif /* autodetect architecture */ - -/* - * Compiler autodetection - */ - -#if defined(DUK_F_CLANG) -/* --- Clang --- */ -#if defined(DUK_F_C99) || defined(DUK_F_CPP11) -/* C99 / C++11 and above: rely on va_copy() which is required. */ -#define DUK_VA_COPY(dest,src) va_copy(dest,src) -#else -/* Clang: assume we have __va_copy() in non-C99 mode. */ -#define DUK_VA_COPY(dest,src) __va_copy(dest,src) -#endif - -#define DUK_NORETURN(decl) decl __attribute__((noreturn)) - -#if defined(__clang__) && defined(__has_builtin) -#if __has_builtin(__builtin_unreachable) -#define DUK_UNREACHABLE() do { __builtin_unreachable(); } while (0) -#endif -#endif - -#define DUK_USE_BRANCH_HINTS -#define DUK_LIKELY(x) __builtin_expect((x), 1) -#define DUK_UNLIKELY(x) __builtin_expect((x), 0) -#if defined(__clang__) && defined(__has_builtin) -#if __has_builtin(__builtin_unpredictable) -#define DUK_UNPREDICTABLE(x) __builtin_unpredictable((x)) -#endif -#endif - -#if defined(DUK_F_C99) || defined(DUK_F_CPP11) -#define DUK_NOINLINE __attribute__((noinline)) -#define DUK_INLINE inline -#define DUK_ALWAYS_INLINE inline __attribute__((always_inline)) -#endif - -/* DUK_HOT */ -/* DUK_COLD */ - -#if defined(DUK_F_DLL_BUILD) && defined(DUK_F_WINDOWS) -/* MSVC dllexport/dllimport: appropriate __declspec depends on whether we're - * compiling Duktape or the application. - */ -#if defined(DUK_COMPILING_DUKTAPE) -#define DUK_EXTERNAL_DECL extern __declspec(dllexport) -#define DUK_EXTERNAL __declspec(dllexport) -#else -#define DUK_EXTERNAL_DECL extern __declspec(dllimport) -#define DUK_EXTERNAL should_not_happen -#endif -#if defined(DUK_SINGLE_FILE) -#define DUK_INTERNAL_DECL static -#define DUK_INTERNAL static -#else -#define DUK_INTERNAL_DECL extern -#define DUK_INTERNAL /*empty*/ -#endif -#define DUK_LOCAL_DECL static -#define DUK_LOCAL static -#else -#define DUK_EXTERNAL_DECL __attribute__ ((visibility("default"))) extern -#define DUK_EXTERNAL __attribute__ ((visibility("default"))) -#if defined(DUK_SINGLE_FILE) -#if (defined(DUK_F_GCC_VERSION) && DUK_F_GCC_VERSION >= 30101) || defined(DUK_F_CLANG) -/* Minimize warnings for unused internal functions with GCC >= 3.1.1 and - * Clang. Based on documentation it should suffice to have the attribute - * in the declaration only, but in practice some warnings are generated unless - * the attribute is also applied to the definition. - */ -#define DUK_INTERNAL_DECL static __attribute__ ((unused)) -#define DUK_INTERNAL static __attribute__ ((unused)) -#else -#define DUK_INTERNAL_DECL static -#define DUK_INTERNAL static -#endif -#else -#if (defined(DUK_F_GCC_VERSION) && DUK_F_GCC_VERSION >= 30101) || defined(DUK_F_CLANG) -#define DUK_INTERNAL_DECL __attribute__ ((visibility("hidden"))) __attribute__ ((unused)) extern -#define DUK_INTERNAL __attribute__ ((visibility("hidden"))) __attribute__ ((unused)) -#else -#define DUK_INTERNAL_DECL __attribute__ ((visibility("hidden"))) extern -#define DUK_INTERNAL __attribute__ ((visibility("hidden"))) -#endif -#endif -#define DUK_LOCAL_DECL static -#define DUK_LOCAL static -#endif - -#if defined(DUK_F_CPP) -#define DUK_USE_COMPILER_STRING "clang" -#else -#define DUK_USE_COMPILER_STRING "clang" -#endif - -#undef DUK_USE_VARIADIC_MACROS -#if defined(DUK_F_C99) || defined(DUK_F_CPP11) -#define DUK_USE_VARIADIC_MACROS -#endif - -#define DUK_USE_UNION_INITIALIZERS - -#undef DUK_USE_FLEX_C99 -#undef DUK_USE_FLEX_ZEROSIZE -#undef DUK_USE_FLEX_ONESIZE -#if defined(DUK_F_C99) -#define DUK_USE_FLEX_C99 -#else -#define DUK_USE_FLEX_ZEROSIZE -#endif - -#undef DUK_USE_GCC_PRAGMAS -#define DUK_USE_PACK_CLANG_ATTR -#elif defined(DUK_F_GCC) -/* --- GCC --- */ -#if defined(DUK_F_C99) || defined(DUK_F_CPP11) -/* C99 / C++11 and above: rely on va_copy() which is required. */ -#define DUK_VA_COPY(dest,src) va_copy(dest,src) -#else -/* GCC: assume we have __va_copy() in non-C99 mode. */ -#define DUK_VA_COPY(dest,src) __va_copy(dest,src) -#endif - -#if defined(DUK_F_GCC_VERSION) && (DUK_F_GCC_VERSION >= 20500L) -/* since gcc-2.5 */ -#define DUK_NORETURN(decl) decl __attribute__((noreturn)) -#endif - -#if defined(DUK_F_GCC_VERSION) && (DUK_F_GCC_VERSION >= 40500L) -/* since gcc-4.5 */ -#define DUK_UNREACHABLE() do { __builtin_unreachable(); } while (0) -#endif - -#define DUK_USE_BRANCH_HINTS -#if defined(DUK_F_GCC_VERSION) && (DUK_F_GCC_VERSION >= 40500L) -/* GCC: test not very accurate; enable only in relatively recent builds - * because of bugs in gcc-4.4 (http://lists.debian.org/debian-gcc/2010/04/msg00000.html) - */ -#define DUK_LIKELY(x) __builtin_expect((x), 1) -#define DUK_UNLIKELY(x) __builtin_expect((x), 0) -#endif -/* XXX: equivalent of clang __builtin_unpredictable? */ - -#if (defined(DUK_F_C99) || defined(DUK_F_CPP11)) && \ - defined(DUK_F_GCC_VERSION) && (DUK_F_GCC_VERSION >= 30101) -#define DUK_NOINLINE __attribute__((noinline)) -#define DUK_INLINE inline -#define DUK_ALWAYS_INLINE inline __attribute__((always_inline)) -#endif - -#if (defined(DUK_F_C99) || defined(DUK_F_CPP11)) && \ - defined(DUK_F_GCC_VERSION) && (DUK_F_GCC_VERSION >= 40300) -#define DUK_HOT __attribute__((hot)) -#define DUK_COLD __attribute__((cold)) -#endif - -#if defined(DUK_F_DLL_BUILD) && defined(DUK_F_WINDOWS) -/* MSVC dllexport/dllimport: appropriate __declspec depends on whether we're - * compiling Duktape or the application. - */ -#if defined(DUK_COMPILING_DUKTAPE) -#define DUK_EXTERNAL_DECL extern __declspec(dllexport) -#define DUK_EXTERNAL __declspec(dllexport) -#else -#define DUK_EXTERNAL_DECL extern __declspec(dllimport) -#define DUK_EXTERNAL should_not_happen -#endif -#if defined(DUK_SINGLE_FILE) -#define DUK_INTERNAL_DECL static -#define DUK_INTERNAL static -#else -#define DUK_INTERNAL_DECL extern -#define DUK_INTERNAL /*empty*/ -#endif -#define DUK_LOCAL_DECL static -#define DUK_LOCAL static -#elif defined(DUK_F_GCC_VERSION) && (DUK_F_GCC_VERSION >= 40000) -#define DUK_EXTERNAL_DECL __attribute__ ((visibility("default"))) extern -#define DUK_EXTERNAL __attribute__ ((visibility("default"))) -#if defined(DUK_SINGLE_FILE) -#if (defined(DUK_F_GCC_VERSION) && DUK_F_GCC_VERSION >= 30101) || defined(DUK_F_CLANG) -/* Minimize warnings for unused internal functions with GCC >= 3.1.1 and - * Clang. Based on documentation it should suffice to have the attribute - * in the declaration only, but in practice some warnings are generated unless - * the attribute is also applied to the definition. - */ -#define DUK_INTERNAL_DECL static __attribute__ ((unused)) -#define DUK_INTERNAL static __attribute__ ((unused)) -#else -#define DUK_INTERNAL_DECL static -#define DUK_INTERNAL static -#endif -#else -#if (defined(DUK_F_GCC_VERSION) && DUK_F_GCC_VERSION >= 30101) || defined(DUK_F_CLANG) -#define DUK_INTERNAL_DECL __attribute__ ((visibility("hidden"))) __attribute__ ((unused)) extern -#define DUK_INTERNAL __attribute__ ((visibility("hidden"))) __attribute__ ((unused)) -#else -#define DUK_INTERNAL_DECL __attribute__ ((visibility("hidden"))) extern -#define DUK_INTERNAL __attribute__ ((visibility("hidden"))) -#endif -#endif -#define DUK_LOCAL_DECL static -#define DUK_LOCAL static -#endif - -#if defined(DUK_F_MINGW) -#if defined(DUK_F_CPP) -#define DUK_USE_COMPILER_STRING "mingw++" -#else -#define DUK_USE_COMPILER_STRING "mingw" -#endif -#else -#if defined(DUK_F_CPP) -#define DUK_USE_COMPILER_STRING "g++" -#else -#define DUK_USE_COMPILER_STRING "gcc" -#endif -#endif - -#undef DUK_USE_VARIADIC_MACROS -#if defined(DUK_F_C99) || (defined(DUK_F_CPP11) && defined(__GNUC__)) -#define DUK_USE_VARIADIC_MACROS -#endif - -#define DUK_USE_UNION_INITIALIZERS - -#undef DUK_USE_FLEX_C99 -#undef DUK_USE_FLEX_ZEROSIZE -#undef DUK_USE_FLEX_ONESIZE -#if defined(DUK_F_C99) -#define DUK_USE_FLEX_C99 -#else -#define DUK_USE_FLEX_ZEROSIZE -#endif - -#if defined(DUK_F_GCC_VERSION) && (DUK_F_GCC_VERSION >= 40600) -#define DUK_USE_GCC_PRAGMAS -#else -#undef DUK_USE_GCC_PRAGMAS -#endif - -#define DUK_USE_PACK_GCC_ATTR -#elif defined(DUK_F_MSVC) -/* --- MSVC --- */ -/* http://msdn.microsoft.com/en-us/library/aa235362(VS.60).aspx */ -#define DUK_NORETURN(decl) __declspec(noreturn) decl - -/* XXX: DUK_UNREACHABLE for msvc? */ - -#undef DUK_USE_BRANCH_HINTS - -/* XXX: DUK_LIKELY, DUK_UNLIKELY for msvc? */ -/* XXX: DUK_NOINLINE, DUK_INLINE, DUK_ALWAYS_INLINE for msvc? */ - -#if defined(DUK_F_DLL_BUILD) && defined(DUK_F_WINDOWS) -/* MSVC dllexport/dllimport: appropriate __declspec depends on whether we're - * compiling Duktape or the application. - */ -#if defined(DUK_COMPILING_DUKTAPE) -#define DUK_EXTERNAL_DECL extern __declspec(dllexport) -#define DUK_EXTERNAL __declspec(dllexport) -#else -#define DUK_EXTERNAL_DECL extern __declspec(dllimport) -#define DUK_EXTERNAL should_not_happen -#endif -#if defined(DUK_SINGLE_FILE) -#define DUK_INTERNAL_DECL static -#define DUK_INTERNAL static -#else -#define DUK_INTERNAL_DECL extern -#define DUK_INTERNAL /*empty*/ -#endif -#define DUK_LOCAL_DECL static -#define DUK_LOCAL static -#endif - -#if defined(DUK_F_CPP) -#define DUK_USE_COMPILER_STRING "msvc++" -#else -#define DUK_USE_COMPILER_STRING "msvc" -#endif - -#undef DUK_USE_VARIADIC_MACROS -#if defined(DUK_F_C99) -#define DUK_USE_VARIADIC_MACROS -#elif defined(_MSC_VER) && (_MSC_VER >= 1400) -/* VS2005+ should have variadic macros even when they're not C99. */ -#define DUK_USE_VARIADIC_MACROS -#endif - -#undef DUK_USE_UNION_INITIALIZERS -#if defined(_MSC_VER) && (_MSC_VER >= 1800) -/* VS2013+ supports union initializers but there's a bug involving union-inside-struct: - * https://connect.microsoft.com/VisualStudio/feedback/details/805981 - * The bug was fixed (at least) in VS2015 so check for VS2015 for now: - * https://blogs.msdn.microsoft.com/vcblog/2015/07/01/c-compiler-front-end-fixes-in-vs2015/ - * Manually tested using VS2013, CL reports 18.00.31101, so enable for VS2013 too. - */ -#define DUK_USE_UNION_INITIALIZERS -#endif - -#undef DUK_USE_FLEX_C99 -#undef DUK_USE_FLEX_ZEROSIZE -#undef DUK_USE_FLEX_ONESIZE -#if defined(DUK_F_C99) -#define DUK_USE_FLEX_C99 -#else -#define DUK_USE_FLEX_ZEROSIZE -#endif - -#undef DUK_USE_GCC_PRAGMAS - -#define DUK_USE_PACK_MSVC_PRAGMA - -/* These have been tested from VS2008 onwards; may work in older VS versions - * too but not enabled by default. - */ -#if defined(_MSC_VER) && (_MSC_VER >= 1500) -#define DUK_NOINLINE __declspec(noinline) -#define DUK_INLINE __inline -#define DUK_ALWAYS_INLINE __forceinline -#endif - -#if defined(_MSC_VER) && (_MSC_VER >= 1900) -#define DUK_SNPRINTF snprintf -#define DUK_VSNPRINTF vsnprintf -#else -/* (v)snprintf() is missing before MSVC 2015. Note that _(v)snprintf() does - * NOT NUL terminate on truncation, but Duktape code never assumes that. - * http://stackoverflow.com/questions/2915672/snprintf-and-visual-studio-2010 - */ -#define DUK_SNPRINTF _snprintf -#define DUK_VSNPRINTF _vsnprintf -#endif - -/* Avoid warning when doing DUK_UNREF(some_function). */ -#if defined(_MSC_VER) && (_MSC_VER < 1500) -#pragma warning(disable: 4100 4101 4550 4551) -#define DUK_UNREF(x) -#else -#define DUK_UNREF(x) do { __pragma(warning(suppress:4100 4101 4550 4551)) (x); } while (0) -#endif - -/* Older versions of MSVC don't support the LL/ULL suffix. */ -#define DUK_U64_CONSTANT(x) x##ui64 -#define DUK_I64_CONSTANT(x) x##i64 -#elif defined(DUK_F_EMSCRIPTEN) -/* --- Emscripten --- */ -#define DUK_NORETURN(decl) decl __attribute__((noreturn)) - -#if defined(__clang__) && defined(__has_builtin) -#if __has_builtin(__builtin_unreachable) -#define DUK_UNREACHABLE() do { __builtin_unreachable(); } while (0) -#endif -#endif - -#define DUK_USE_BRANCH_HINTS -#define DUK_LIKELY(x) __builtin_expect((x), 1) -#define DUK_UNLIKELY(x) __builtin_expect((x), 0) -#if defined(__clang__) && defined(__has_builtin) -#if __has_builtin(__builtin_unpredictable) -#define DUK_UNPREDICTABLE(x) __builtin_unpredictable((x)) -#endif -#endif - -#if defined(DUK_F_C99) || defined(DUK_F_CPP11) -#define DUK_NOINLINE __attribute__((noinline)) -#define DUK_INLINE inline -#define DUK_ALWAYS_INLINE inline __attribute__((always_inline)) -#endif - -#define DUK_EXTERNAL_DECL __attribute__ ((visibility("default"))) extern -#define DUK_EXTERNAL __attribute__ ((visibility("default"))) -#if defined(DUK_SINGLE_FILE) -#if (defined(DUK_F_GCC_VERSION) && DUK_F_GCC_VERSION >= 30101) || defined(DUK_F_CLANG) -/* Minimize warnings for unused internal functions with GCC >= 3.1.1 and - * Clang. Based on documentation it should suffice to have the attribute - * in the declaration only, but in practice some warnings are generated unless - * the attribute is also applied to the definition. - */ -#define DUK_INTERNAL_DECL static __attribute__ ((unused)) -#define DUK_INTERNAL static __attribute__ ((unused)) -#else -#define DUK_INTERNAL_DECL static -#define DUK_INTERNAL static -#endif -#else -#if (defined(DUK_F_GCC_VERSION) && DUK_F_GCC_VERSION >= 30101) || defined(DUK_F_CLANG) -#define DUK_INTERNAL_DECL __attribute__ ((visibility("hidden"))) __attribute__ ((unused)) extern -#define DUK_INTERNAL __attribute__ ((visibility("hidden"))) __attribute__ ((unused)) -#else -#define DUK_INTERNAL_DECL __attribute__ ((visibility("hidden"))) extern -#define DUK_INTERNAL __attribute__ ((visibility("hidden"))) -#endif -#endif -#define DUK_LOCAL_DECL static -#define DUK_LOCAL static - -#define DUK_USE_COMPILER_STRING "emscripten" - -#undef DUK_USE_VARIADIC_MACROS -#if defined(DUK_F_C99) || defined(DUK_F_CPP11) -#define DUK_USE_VARIADIC_MACROS -#endif - -#define DUK_USE_UNION_INITIALIZERS - -#undef DUK_USE_FLEX_C99 -#undef DUK_USE_FLEX_ZEROSIZE -#undef DUK_USE_FLEX_ONESIZE -#if defined(DUK_F_C99) -#define DUK_USE_FLEX_C99 -#else -#define DUK_USE_FLEX_ZEROSIZE -#endif - -#undef DUK_USE_GCC_PRAGMAS -#define DUK_USE_PACK_CLANG_ATTR -#elif defined(DUK_F_TINYC) -/* --- TinyC --- */ -#undef DUK_USE_BRANCH_HINTS - -#if defined(DUK_F_CPP) -#define DUK_USE_COMPILER_STRING "tinyc++" -#else -#define DUK_USE_COMPILER_STRING "tinyc" -#endif - -/* http://bellard.org/tcc/tcc-doc.html#SEC7 */ -#define DUK_USE_VARIADIC_MACROS - -#define DUK_USE_UNION_INITIALIZERS - -/* Most portable, wastes space */ -#define DUK_USE_FLEX_ONESIZE - -/* Most portable, potentially wastes space */ -#define DUK_USE_PACK_DUMMY_MEMBER -#elif defined(DUK_F_VBCC) -/* --- VBCC --- */ -#undef DUK_USE_BRANCH_HINTS - -#if defined(DUK_F_CPP) -#define DUK_USE_COMPILER_STRING "vbcc-c++" -#else -#define DUK_USE_COMPILER_STRING "vbcc" -#endif - -#undef DUK_USE_VARIADIC_MACROS -#if defined(DUK_F_C99) || defined(DUK_F_CPP11) -#define DUK_USE_VARIADIC_MACROS -#endif - -/* VBCC supports C99 so check only for C99 for union initializer support. - * Designated union initializers would possibly work even without a C99 check. - */ -#undef DUK_USE_UNION_INITIALIZERS -#if defined(DUK_F_C99) -#define DUK_USE_UNION_INITIALIZERS -#endif - -#define DUK_USE_FLEX_ZEROSIZE -#define DUK_USE_PACK_DUMMY_MEMBER -#elif defined(DUK_F_BCC) -/* --- Bruce's C compiler --- */ -#undef DUK_USE_BRANCH_HINTS - -#if defined(DUK_F_CPP) -#define DUK_USE_COMPILER_STRING "bcc++" -#else -#define DUK_USE_COMPILER_STRING "bcc" -#endif - -/* Most portable */ -#undef DUK_USE_VARIADIC_MACROS - -/* Most portable, wastes space */ -#undef DUK_USE_UNION_INITIALIZERS - -/* Most portable, wastes space */ -#define DUK_USE_FLEX_ONESIZE - -/* Most portable, potentially wastes space */ -#define DUK_USE_PACK_DUMMY_MEMBER - -/* BCC, assume we're on x86. */ -#if !defined(DUK_USE_BYTEORDER) -#define DUK_USE_BYTEORDER 1 -#endif -#else -/* --- Generic --- */ -#undef DUK_USE_BRANCH_HINTS - -#if defined(DUK_F_CPP) -#define DUK_USE_COMPILER_STRING "generic-c++" -#else -#define DUK_USE_COMPILER_STRING "generic" -#endif - -#undef DUK_USE_VARIADIC_MACROS -#if defined(DUK_F_C99) || defined(DUK_F_CPP11) -#define DUK_USE_VARIADIC_MACROS -#endif - -/* C++ doesn't have standard designated union initializers ({ .foo = 1 }). */ -#undef DUK_USE_UNION_INITIALIZERS -#if defined(DUK_F_C99) -#define DUK_USE_UNION_INITIALIZERS -#endif - -/* Most portable, wastes space */ -#define DUK_USE_FLEX_ONESIZE - -/* Most portable, potentially wastes space */ -#define DUK_USE_PACK_DUMMY_MEMBER -#endif /* autodetect compiler */ - -/* uclibc */ -#if defined(__UCLIBC__) -#define DUK_F_UCLIBC -#endif - -/* - * Wrapper typedefs and constants for integer types, also sanity check types. - * - * C99 typedefs are quite good but not always available, and we want to avoid - * forcibly redefining the C99 typedefs. So, there are Duktape wrappers for - * all C99 typedefs and Duktape code should only use these typedefs. Type - * detection when C99 is not supported is best effort and may end up detecting - * some types incorrectly. - * - * Pointer sizes are a portability problem: pointers to different types may - * have a different size and function pointers are very difficult to manage - * portably. - * - * http://en.wikipedia.org/wiki/C_data_types#Fixed-width_integer_types - * - * Note: there's an interesting corner case when trying to define minimum - * signed integer value constants which leads to the current workaround of - * defining e.g. -0x80000000 as (-0x7fffffffL - 1L). See doc/code-issues.txt - * for a longer discussion. - * - * Note: avoid typecasts and computations in macro integer constants as they - * can then no longer be used in macro relational expressions (such as - * #if DUK_SIZE_MAX < 0xffffffffUL). There is internal code which relies on - * being able to compare DUK_SIZE_MAX against a limit. - */ - -/* XXX: add feature options to force basic types from outside? */ - -#if !defined(INT_MAX) -#error INT_MAX not defined -#endif - -/* Check that architecture is two's complement, standard C allows e.g. - * INT_MIN to be -2**31+1 (instead of -2**31). - */ -#if defined(INT_MAX) && defined(INT_MIN) -#if INT_MAX != -(INT_MIN + 1) -#error platform does not seem complement of two -#endif -#else -#error cannot check complement of two -#endif - -/* Pointer size determination based on __WORDSIZE or architecture when - * that's not available. - */ -#if defined(DUK_F_X86) || defined(DUK_F_X32) || \ - defined(DUK_F_M68K) || defined(DUK_F_PPC32) || \ - defined(DUK_F_BCC) || \ - (defined(__WORDSIZE) && (__WORDSIZE == 32)) || \ - ((defined(DUK_F_OLD_SOLARIS) || defined(DUK_F_AIX) || \ - defined(DUK_F_HPUX)) && defined(_ILP32)) || \ - defined(DUK_F_ARM32) -#define DUK_F_32BIT_PTRS -#elif defined(DUK_F_X64) || \ - (defined(__WORDSIZE) && (__WORDSIZE == 64)) || \ - ((defined(DUK_F_OLD_SOLARIS) || defined(DUK_F_AIX) || \ - defined(DUK_F_HPUX)) && defined(_LP64)) || \ - defined(DUK_F_ARM64) -#define DUK_F_64BIT_PTRS -#else -/* not sure, not needed with C99 anyway */ -#endif - -/* Intermediate define for 'have inttypes.h' */ -#undef DUK_F_HAVE_INTTYPES -#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ - !(defined(DUK_F_AMIGAOS) && defined(DUK_F_VBCC)) -/* vbcc + AmigaOS has C99 but no inttypes.h */ -#define DUK_F_HAVE_INTTYPES -#elif defined(__cplusplus) && (__cplusplus >= 201103L) -/* C++11 apparently ratified stdint.h */ -#define DUK_F_HAVE_INTTYPES -#endif - -/* Basic integer typedefs and limits, preferably from inttypes.h, otherwise - * through automatic detection. - */ -#if defined(DUK_F_HAVE_INTTYPES) -/* C99 or compatible */ - -#define DUK_F_HAVE_64BIT -#include - -typedef uint8_t duk_uint8_t; -typedef int8_t duk_int8_t; -typedef uint16_t duk_uint16_t; -typedef int16_t duk_int16_t; -typedef uint32_t duk_uint32_t; -typedef int32_t duk_int32_t; -typedef uint64_t duk_uint64_t; -typedef int64_t duk_int64_t; -typedef uint_least8_t duk_uint_least8_t; -typedef int_least8_t duk_int_least8_t; -typedef uint_least16_t duk_uint_least16_t; -typedef int_least16_t duk_int_least16_t; -typedef uint_least32_t duk_uint_least32_t; -typedef int_least32_t duk_int_least32_t; -typedef uint_least64_t duk_uint_least64_t; -typedef int_least64_t duk_int_least64_t; -typedef uint_fast8_t duk_uint_fast8_t; -typedef int_fast8_t duk_int_fast8_t; -typedef uint_fast16_t duk_uint_fast16_t; -typedef int_fast16_t duk_int_fast16_t; -typedef uint_fast32_t duk_uint_fast32_t; -typedef int_fast32_t duk_int_fast32_t; -typedef uint_fast64_t duk_uint_fast64_t; -typedef int_fast64_t duk_int_fast64_t; -typedef uintptr_t duk_uintptr_t; -typedef intptr_t duk_intptr_t; -typedef uintmax_t duk_uintmax_t; -typedef intmax_t duk_intmax_t; - -#define DUK_UINT8_MIN 0 -#define DUK_UINT8_MAX UINT8_MAX -#define DUK_INT8_MIN INT8_MIN -#define DUK_INT8_MAX INT8_MAX -#define DUK_UINT_LEAST8_MIN 0 -#define DUK_UINT_LEAST8_MAX UINT_LEAST8_MAX -#define DUK_INT_LEAST8_MIN INT_LEAST8_MIN -#define DUK_INT_LEAST8_MAX INT_LEAST8_MAX -#define DUK_UINT_FAST8_MIN 0 -#define DUK_UINT_FAST8_MAX UINT_FAST8_MAX -#define DUK_INT_FAST8_MIN INT_FAST8_MIN -#define DUK_INT_FAST8_MAX INT_FAST8_MAX -#define DUK_UINT16_MIN 0 -#define DUK_UINT16_MAX UINT16_MAX -#define DUK_INT16_MIN INT16_MIN -#define DUK_INT16_MAX INT16_MAX -#define DUK_UINT_LEAST16_MIN 0 -#define DUK_UINT_LEAST16_MAX UINT_LEAST16_MAX -#define DUK_INT_LEAST16_MIN INT_LEAST16_MIN -#define DUK_INT_LEAST16_MAX INT_LEAST16_MAX -#define DUK_UINT_FAST16_MIN 0 -#define DUK_UINT_FAST16_MAX UINT_FAST16_MAX -#define DUK_INT_FAST16_MIN INT_FAST16_MIN -#define DUK_INT_FAST16_MAX INT_FAST16_MAX -#define DUK_UINT32_MIN 0 -#define DUK_UINT32_MAX UINT32_MAX -#define DUK_INT32_MIN INT32_MIN -#define DUK_INT32_MAX INT32_MAX -#define DUK_UINT_LEAST32_MIN 0 -#define DUK_UINT_LEAST32_MAX UINT_LEAST32_MAX -#define DUK_INT_LEAST32_MIN INT_LEAST32_MIN -#define DUK_INT_LEAST32_MAX INT_LEAST32_MAX -#define DUK_UINT_FAST32_MIN 0 -#define DUK_UINT_FAST32_MAX UINT_FAST32_MAX -#define DUK_INT_FAST32_MIN INT_FAST32_MIN -#define DUK_INT_FAST32_MAX INT_FAST32_MAX -#define DUK_UINT64_MIN 0 -#define DUK_UINT64_MAX UINT64_MAX -#define DUK_INT64_MIN INT64_MIN -#define DUK_INT64_MAX INT64_MAX -#define DUK_UINT_LEAST64_MIN 0 -#define DUK_UINT_LEAST64_MAX UINT_LEAST64_MAX -#define DUK_INT_LEAST64_MIN INT_LEAST64_MIN -#define DUK_INT_LEAST64_MAX INT_LEAST64_MAX -#define DUK_UINT_FAST64_MIN 0 -#define DUK_UINT_FAST64_MAX UINT_FAST64_MAX -#define DUK_INT_FAST64_MIN INT_FAST64_MIN -#define DUK_INT_FAST64_MAX INT_FAST64_MAX - -#define DUK_UINTPTR_MIN 0 -#define DUK_UINTPTR_MAX UINTPTR_MAX -#define DUK_INTPTR_MIN INTPTR_MIN -#define DUK_INTPTR_MAX INTPTR_MAX - -#define DUK_UINTMAX_MIN 0 -#define DUK_UINTMAX_MAX UINTMAX_MAX -#define DUK_INTMAX_MIN INTMAX_MIN -#define DUK_INTMAX_MAX INTMAX_MAX - -#define DUK_SIZE_MIN 0 -#define DUK_SIZE_MAX SIZE_MAX -#undef DUK_SIZE_MAX_COMPUTED - -#else /* C99 types */ - -/* When C99 types are not available, we use heuristic detection to get - * the basic 8, 16, 32, and (possibly) 64 bit types. The fast/least - * types are then assumed to be exactly the same for now: these could - * be improved per platform but C99 types are very often now available. - * 64-bit types are not available on all platforms; this is OK at least - * on 32-bit platforms. - * - * This detection code is necessarily a bit hacky and can provide typedefs - * and defines that won't work correctly on some exotic platform. - */ - -#if (defined(CHAR_BIT) && (CHAR_BIT == 8)) || \ - (defined(UCHAR_MAX) && (UCHAR_MAX == 255)) -typedef unsigned char duk_uint8_t; -typedef signed char duk_int8_t; -#else -#error cannot detect 8-bit type -#endif - -#if defined(USHRT_MAX) && (USHRT_MAX == 65535UL) -typedef unsigned short duk_uint16_t; -typedef signed short duk_int16_t; -#elif defined(UINT_MAX) && (UINT_MAX == 65535UL) -/* On some platforms int is 16-bit but long is 32-bit (e.g. PureC) */ -typedef unsigned int duk_uint16_t; -typedef signed int duk_int16_t; -#else -#error cannot detect 16-bit type -#endif - -#if defined(UINT_MAX) && (UINT_MAX == 4294967295UL) -typedef unsigned int duk_uint32_t; -typedef signed int duk_int32_t; -#elif defined(ULONG_MAX) && (ULONG_MAX == 4294967295UL) -/* On some platforms int is 16-bit but long is 32-bit (e.g. PureC) */ -typedef unsigned long duk_uint32_t; -typedef signed long duk_int32_t; -#else -#error cannot detect 32-bit type -#endif - -/* 64-bit type detection is a bit tricky. - * - * ULLONG_MAX is a standard define. __LONG_LONG_MAX__ and __ULONG_LONG_MAX__ - * are used by at least GCC (even if system headers don't provide ULLONG_MAX). - * Some GCC variants may provide __LONG_LONG_MAX__ but not __ULONG_LONG_MAX__. - * - * ULL / LL constants are rejected / warned about by some compilers, even if - * the compiler has a 64-bit type and the compiler/system headers provide an - * unsupported constant (ULL/LL)! Try to avoid using ULL / LL constants. - * As a side effect we can only check that e.g. ULONG_MAX is larger than 32 - * bits but can't be sure it is exactly 64 bits. Self tests will catch such - * cases. - */ -#undef DUK_F_HAVE_64BIT -#if !defined(DUK_F_HAVE_64BIT) && defined(ULONG_MAX) -#if (ULONG_MAX > 4294967295UL) -#define DUK_F_HAVE_64BIT -typedef unsigned long duk_uint64_t; -typedef signed long duk_int64_t; -#endif -#endif -#if !defined(DUK_F_HAVE_64BIT) && defined(ULLONG_MAX) -#if (ULLONG_MAX > 4294967295UL) -#define DUK_F_HAVE_64BIT -typedef unsigned long long duk_uint64_t; -typedef signed long long duk_int64_t; -#endif -#endif -#if !defined(DUK_F_HAVE_64BIT) && defined(__ULONG_LONG_MAX__) -#if (__ULONG_LONG_MAX__ > 4294967295UL) -#define DUK_F_HAVE_64BIT -typedef unsigned long long duk_uint64_t; -typedef signed long long duk_int64_t; -#endif -#endif -#if !defined(DUK_F_HAVE_64BIT) && defined(__LONG_LONG_MAX__) -#if (__LONG_LONG_MAX__ > 2147483647L) -#define DUK_F_HAVE_64BIT -typedef unsigned long long duk_uint64_t; -typedef signed long long duk_int64_t; -#endif -#endif -#if !defined(DUK_F_HAVE_64BIT) && defined(DUK_F_MINGW) -#define DUK_F_HAVE_64BIT -typedef unsigned long duk_uint64_t; -typedef signed long duk_int64_t; -#endif -#if !defined(DUK_F_HAVE_64BIT) && defined(DUK_F_MSVC) -#define DUK_F_HAVE_64BIT -typedef unsigned __int64 duk_uint64_t; -typedef signed __int64 duk_int64_t; -#endif -#if !defined(DUK_F_HAVE_64BIT) -/* cannot detect 64-bit type, not always needed so don't error */ -#endif - -typedef duk_uint8_t duk_uint_least8_t; -typedef duk_int8_t duk_int_least8_t; -typedef duk_uint16_t duk_uint_least16_t; -typedef duk_int16_t duk_int_least16_t; -typedef duk_uint32_t duk_uint_least32_t; -typedef duk_int32_t duk_int_least32_t; -typedef duk_uint8_t duk_uint_fast8_t; -typedef duk_int8_t duk_int_fast8_t; -typedef duk_uint16_t duk_uint_fast16_t; -typedef duk_int16_t duk_int_fast16_t; -typedef duk_uint32_t duk_uint_fast32_t; -typedef duk_int32_t duk_int_fast32_t; -#if defined(DUK_F_HAVE_64BIT) -typedef duk_uint64_t duk_uint_least64_t; -typedef duk_int64_t duk_int_least64_t; -typedef duk_uint64_t duk_uint_fast64_t; -typedef duk_int64_t duk_int_fast64_t; -#endif -#if defined(DUK_F_HAVE_64BIT) -typedef duk_uint64_t duk_uintmax_t; -typedef duk_int64_t duk_intmax_t; -#else -typedef duk_uint32_t duk_uintmax_t; -typedef duk_int32_t duk_intmax_t; -#endif - -/* Note: the funny looking computations for signed minimum 16-bit, 32-bit, and - * 64-bit values are intentional as the obvious forms (e.g. -0x80000000L) are - * -not- portable. See code-issues.txt for a detailed discussion. - */ -#define DUK_UINT8_MIN 0UL -#define DUK_UINT8_MAX 0xffUL -#define DUK_INT8_MIN (-0x80L) -#define DUK_INT8_MAX 0x7fL -#define DUK_UINT_LEAST8_MIN 0UL -#define DUK_UINT_LEAST8_MAX 0xffUL -#define DUK_INT_LEAST8_MIN (-0x80L) -#define DUK_INT_LEAST8_MAX 0x7fL -#define DUK_UINT_FAST8_MIN 0UL -#define DUK_UINT_FAST8_MAX 0xffUL -#define DUK_INT_FAST8_MIN (-0x80L) -#define DUK_INT_FAST8_MAX 0x7fL -#define DUK_UINT16_MIN 0UL -#define DUK_UINT16_MAX 0xffffUL -#define DUK_INT16_MIN (-0x7fffL - 1L) -#define DUK_INT16_MAX 0x7fffL -#define DUK_UINT_LEAST16_MIN 0UL -#define DUK_UINT_LEAST16_MAX 0xffffUL -#define DUK_INT_LEAST16_MIN (-0x7fffL - 1L) -#define DUK_INT_LEAST16_MAX 0x7fffL -#define DUK_UINT_FAST16_MIN 0UL -#define DUK_UINT_FAST16_MAX 0xffffUL -#define DUK_INT_FAST16_MIN (-0x7fffL - 1L) -#define DUK_INT_FAST16_MAX 0x7fffL -#define DUK_UINT32_MIN 0UL -#define DUK_UINT32_MAX 0xffffffffUL -#define DUK_INT32_MIN (-0x7fffffffL - 1L) -#define DUK_INT32_MAX 0x7fffffffL -#define DUK_UINT_LEAST32_MIN 0UL -#define DUK_UINT_LEAST32_MAX 0xffffffffUL -#define DUK_INT_LEAST32_MIN (-0x7fffffffL - 1L) -#define DUK_INT_LEAST32_MAX 0x7fffffffL -#define DUK_UINT_FAST32_MIN 0UL -#define DUK_UINT_FAST32_MAX 0xffffffffUL -#define DUK_INT_FAST32_MIN (-0x7fffffffL - 1L) -#define DUK_INT_FAST32_MAX 0x7fffffffL - -/* 64-bit constants. Since LL / ULL constants are not always available, - * use computed values. These values can't be used in preprocessor - * comparisons; flag them as such. - */ -#if defined(DUK_F_HAVE_64BIT) -#define DUK_UINT64_MIN ((duk_uint64_t) 0) -#define DUK_UINT64_MAX ((duk_uint64_t) -1) -#define DUK_INT64_MIN ((duk_int64_t) (~(DUK_UINT64_MAX >> 1))) -#define DUK_INT64_MAX ((duk_int64_t) (DUK_UINT64_MAX >> 1)) -#define DUK_UINT_LEAST64_MIN DUK_UINT64_MIN -#define DUK_UINT_LEAST64_MAX DUK_UINT64_MAX -#define DUK_INT_LEAST64_MIN DUK_INT64_MIN -#define DUK_INT_LEAST64_MAX DUK_INT64_MAX -#define DUK_UINT_FAST64_MIN DUK_UINT64_MIN -#define DUK_UINT_FAST64_MAX DUK_UINT64_MAX -#define DUK_INT_FAST64_MIN DUK_INT64_MIN -#define DUK_INT_FAST64_MAX DUK_INT64_MAX -#define DUK_UINT64_MIN_COMPUTED -#define DUK_UINT64_MAX_COMPUTED -#define DUK_INT64_MIN_COMPUTED -#define DUK_INT64_MAX_COMPUTED -#define DUK_UINT_LEAST64_MIN_COMPUTED -#define DUK_UINT_LEAST64_MAX_COMPUTED -#define DUK_INT_LEAST64_MIN_COMPUTED -#define DUK_INT_LEAST64_MAX_COMPUTED -#define DUK_UINT_FAST64_MIN_COMPUTED -#define DUK_UINT_FAST64_MAX_COMPUTED -#define DUK_INT_FAST64_MIN_COMPUTED -#define DUK_INT_FAST64_MAX_COMPUTED -#endif - -#if defined(DUK_F_HAVE_64BIT) -#define DUK_UINTMAX_MIN DUK_UINT64_MIN -#define DUK_UINTMAX_MAX DUK_UINT64_MAX -#define DUK_INTMAX_MIN DUK_INT64_MIN -#define DUK_INTMAX_MAX DUK_INT64_MAX -#define DUK_UINTMAX_MIN_COMPUTED -#define DUK_UINTMAX_MAX_COMPUTED -#define DUK_INTMAX_MIN_COMPUTED -#define DUK_INTMAX_MAX_COMPUTED -#else -#define DUK_UINTMAX_MIN 0UL -#define DUK_UINTMAX_MAX 0xffffffffUL -#define DUK_INTMAX_MIN (-0x7fffffffL - 1L) -#define DUK_INTMAX_MAX 0x7fffffffL -#endif - -/* This detection is not very reliable. */ -#if defined(DUK_F_32BIT_PTRS) -typedef duk_int32_t duk_intptr_t; -typedef duk_uint32_t duk_uintptr_t; -#define DUK_UINTPTR_MIN DUK_UINT32_MIN -#define DUK_UINTPTR_MAX DUK_UINT32_MAX -#define DUK_INTPTR_MIN DUK_INT32_MIN -#define DUK_INTPTR_MAX DUK_INT32_MAX -#elif defined(DUK_F_64BIT_PTRS) && defined(DUK_F_HAVE_64BIT) -typedef duk_int64_t duk_intptr_t; -typedef duk_uint64_t duk_uintptr_t; -#define DUK_UINTPTR_MIN DUK_UINT64_MIN -#define DUK_UINTPTR_MAX DUK_UINT64_MAX -#define DUK_INTPTR_MIN DUK_INT64_MIN -#define DUK_INTPTR_MAX DUK_INT64_MAX -#define DUK_UINTPTR_MIN_COMPUTED -#define DUK_UINTPTR_MAX_COMPUTED -#define DUK_INTPTR_MIN_COMPUTED -#define DUK_INTPTR_MAX_COMPUTED -#else -#error cannot determine intptr type -#endif - -/* SIZE_MAX may be missing so use an approximate value for it. */ -#undef DUK_SIZE_MAX_COMPUTED -#if !defined(SIZE_MAX) -#define DUK_SIZE_MAX_COMPUTED -#define SIZE_MAX ((size_t) (-1)) -#endif -#define DUK_SIZE_MIN 0 -#define DUK_SIZE_MAX SIZE_MAX - -#endif /* C99 types */ - -/* A few types are assumed to always exist. */ -typedef size_t duk_size_t; -typedef ptrdiff_t duk_ptrdiff_t; - -/* The best type for an "all around int" in Duktape internals is "at least - * 32 bit signed integer" which is most convenient. Same for unsigned type. - * Prefer 'int' when large enough, as it is almost always a convenient type. - */ -#if defined(UINT_MAX) && (UINT_MAX >= 0xffffffffUL) -typedef int duk_int_t; -typedef unsigned int duk_uint_t; -#define DUK_INT_MIN INT_MIN -#define DUK_INT_MAX INT_MAX -#define DUK_UINT_MIN 0 -#define DUK_UINT_MAX UINT_MAX -#else -typedef duk_int_fast32_t duk_int_t; -typedef duk_uint_fast32_t duk_uint_t; -#define DUK_INT_MIN DUK_INT_FAST32_MIN -#define DUK_INT_MAX DUK_INT_FAST32_MAX -#define DUK_UINT_MIN DUK_UINT_FAST32_MIN -#define DUK_UINT_MAX DUK_UINT_FAST32_MAX -#endif - -/* Same as 'duk_int_t' but guaranteed to be a 'fast' variant if this - * distinction matters for the CPU. These types are used mainly in the - * executor where it might really matter. - */ -typedef duk_int_fast32_t duk_int_fast_t; -typedef duk_uint_fast32_t duk_uint_fast_t; -#define DUK_INT_FAST_MIN DUK_INT_FAST32_MIN -#define DUK_INT_FAST_MAX DUK_INT_FAST32_MAX -#define DUK_UINT_FAST_MIN DUK_UINT_FAST32_MIN -#define DUK_UINT_FAST_MAX DUK_UINT_FAST32_MAX - -/* Small integers (16 bits or more) can fall back to the 'int' type, but - * have a typedef so they are marked "small" explicitly. - */ -typedef int duk_small_int_t; -typedef unsigned int duk_small_uint_t; -#define DUK_SMALL_INT_MIN INT_MIN -#define DUK_SMALL_INT_MAX INT_MAX -#define DUK_SMALL_UINT_MIN 0 -#define DUK_SMALL_UINT_MAX UINT_MAX - -/* Fast variants of small integers, again for really fast paths like the - * executor. - */ -typedef duk_int_fast16_t duk_small_int_fast_t; -typedef duk_uint_fast16_t duk_small_uint_fast_t; -#define DUK_SMALL_INT_FAST_MIN DUK_INT_FAST16_MIN -#define DUK_SMALL_INT_FAST_MAX DUK_INT_FAST16_MAX -#define DUK_SMALL_UINT_FAST_MIN DUK_UINT_FAST16_MIN -#define DUK_SMALL_UINT_FAST_MAX DUK_UINT_FAST16_MAX - -/* Boolean values are represented with the platform 'unsigned int'. */ -typedef duk_small_uint_t duk_bool_t; -#define DUK_BOOL_MIN DUK_SMALL_INT_MIN -#define DUK_BOOL_MAX DUK_SMALL_INT_MAX - -/* Index values must have at least 32-bit signed range. */ -typedef duk_int_t duk_idx_t; -#define DUK_IDX_MIN DUK_INT_MIN -#define DUK_IDX_MAX DUK_INT_MAX - -/* Unsigned index variant. */ -typedef duk_uint_t duk_uidx_t; -#define DUK_UIDX_MIN DUK_UINT_MIN -#define DUK_UIDX_MAX DUK_UINT_MAX - -/* Array index values, could be exact 32 bits. - * Currently no need for signed duk_arridx_t. - */ -typedef duk_uint_t duk_uarridx_t; -#define DUK_UARRIDX_MIN DUK_UINT_MIN -#define DUK_UARRIDX_MAX DUK_UINT_MAX - -/* Duktape/C function return value, platform int is enough for now to - * represent 0, 1, or negative error code. Must be compatible with - * assigning truth values (e.g. duk_ret_t rc = (foo == bar);). - */ -typedef duk_small_int_t duk_ret_t; -#define DUK_RET_MIN DUK_SMALL_INT_MIN -#define DUK_RET_MAX DUK_SMALL_INT_MAX - -/* Error codes are represented with platform int. High bits are used - * for flags and such, so 32 bits are needed. - */ -typedef duk_int_t duk_errcode_t; -#define DUK_ERRCODE_MIN DUK_INT_MIN -#define DUK_ERRCODE_MAX DUK_INT_MAX - -/* Codepoint type. Must be 32 bits or more because it is used also for - * internal codepoints. The type is signed because negative codepoints - * are used as internal markers (e.g. to mark EOF or missing argument). - * (X)UTF-8/CESU-8 encode/decode take and return an unsigned variant to - * ensure duk_uint32_t casts back and forth nicely. Almost everything - * else uses the signed one. - */ -typedef duk_int_t duk_codepoint_t; -typedef duk_uint_t duk_ucodepoint_t; -#define DUK_CODEPOINT_MIN DUK_INT_MIN -#define DUK_CODEPOINT_MAX DUK_INT_MAX -#define DUK_UCODEPOINT_MIN DUK_UINT_MIN -#define DUK_UCODEPOINT_MAX DUK_UINT_MAX - -/* IEEE float/double typedef. */ -typedef float duk_float_t; -typedef double duk_double_t; - -/* We're generally assuming that we're working on a platform with a 32-bit - * address space. If DUK_SIZE_MAX is a typecast value (which is necessary - * if SIZE_MAX is missing), the check must be avoided because the - * preprocessor can't do a comparison. - */ -#if !defined(DUK_SIZE_MAX) -#error DUK_SIZE_MAX is undefined, probably missing SIZE_MAX -#elif !defined(DUK_SIZE_MAX_COMPUTED) -#if DUK_SIZE_MAX < 0xffffffffUL -/* On some systems SIZE_MAX can be smaller than max unsigned 32-bit value - * which seems incorrect if size_t is (at least) an unsigned 32-bit type. - * However, it doesn't seem useful to error out compilation if this is the - * case. - */ -#endif -#endif - -/* Type used in public API declarations and user code. Typedef maps to - * 'struct duk_hthread' like the 'duk_hthread' typedef which is used - * exclusively in internals. - */ -typedef struct duk_hthread duk_context; - -/* Check whether we should use 64-bit integers or not. - * - * Quite incomplete now. Use 64-bit types if detected (C99 or other detection) - * unless they are known to be unreliable. For instance, 64-bit types are - * available on VBCC but seem to misbehave. - */ -#if defined(DUK_F_HAVE_64BIT) && !defined(DUK_F_VBCC) -#define DUK_USE_64BIT_OPS -#else -#undef DUK_USE_64BIT_OPS -#endif - -/* - * Fill-ins for platform, architecture, and compiler - */ - -/* An abort()-like primitive is needed by the default fatal error handler. */ -#if !defined(DUK_ABORT) -#define DUK_ABORT abort -#endif - -#if !defined(DUK_SETJMP) -#define DUK_JMPBUF_TYPE jmp_buf -#define DUK_SETJMP(jb) setjmp((jb)) -#define DUK_LONGJMP(jb) longjmp((jb), 1) -#endif - -#if 0 -/* sigsetjmp() alternative */ -#define DUK_JMPBUF_TYPE sigjmp_buf -#define DUK_SETJMP(jb) sigsetjmp((jb)) -#define DUK_LONGJMP(jb) siglongjmp((jb), 1) -#endif - -/* Special naming to avoid conflict with e.g. DUK_FREE() in duk_heap.h - * (which is unfortunately named). May sometimes need replacement, e.g. - * some compilers don't handle zero length or NULL correctly in realloc(). - */ -#if !defined(DUK_ANSI_MALLOC) -#define DUK_ANSI_MALLOC malloc -#endif -#if !defined(DUK_ANSI_REALLOC) -#define DUK_ANSI_REALLOC realloc -#endif -#if !defined(DUK_ANSI_CALLOC) -#define DUK_ANSI_CALLOC calloc -#endif -#if !defined(DUK_ANSI_FREE) -#define DUK_ANSI_FREE free -#endif - -/* ANSI C (various versions) and some implementations require that the - * pointer arguments to memset(), memcpy(), and memmove() be valid values - * even when byte size is 0 (even a NULL pointer is considered invalid in - * this context). Zero-size operations as such are allowed, as long as their - * pointer arguments point to a valid memory area. The DUK_MEMSET(), - * DUK_MEMCPY(), and DUK_MEMMOVE() macros require this same behavior, i.e.: - * (1) pointers must be valid and non-NULL, (2) zero size must otherwise be - * allowed. If these are not fulfilled, a macro wrapper is needed. - * - * http://stackoverflow.com/questions/5243012/is-it-guaranteed-to-be-safe-to-perform-memcpy0-0-0 - * http://lists.cs.uiuc.edu/pipermail/llvmdev/2007-October/011065.html - * - * Not sure what's the required behavior when a pointer points just past the - * end of a buffer, which often happens in practice (e.g. zero size memmoves). - * For example, if allocation size is 3, the following pointer would not - * technically point to a valid memory byte: - * - * <-- alloc --> - * | 0 | 1 | 2 | ..... - * ^-- p=3, points after last valid byte (2) - */ -#if !defined(DUK_MEMCPY) -#if defined(DUK_F_UCLIBC) -/* Old uclibcs have a broken memcpy so use memmove instead (this is overly wide - * now on purpose): http://lists.uclibc.org/pipermail/uclibc-cvs/2008-October/025511.html - */ -#define DUK_MEMCPY memmove -#else -#define DUK_MEMCPY memcpy -#endif -#endif -#if !defined(DUK_MEMMOVE) -#define DUK_MEMMOVE memmove -#endif -#if !defined(DUK_MEMCMP) -#define DUK_MEMCMP memcmp -#endif -#if !defined(DUK_MEMSET) -#define DUK_MEMSET memset -#endif -#if !defined(DUK_STRLEN) -#define DUK_STRLEN strlen -#endif -#if !defined(DUK_STRCMP) -#define DUK_STRCMP strcmp -#endif -#if !defined(DUK_STRNCMP) -#define DUK_STRNCMP strncmp -#endif -#if !defined(DUK_SPRINTF) -#define DUK_SPRINTF sprintf -#endif -#if !defined(DUK_SNPRINTF) -/* snprintf() is technically not part of C89 but usually available. */ -#define DUK_SNPRINTF snprintf -#endif -#if !defined(DUK_VSPRINTF) -#define DUK_VSPRINTF vsprintf -#endif -#if !defined(DUK_VSNPRINTF) -/* vsnprintf() is technically not part of C89 but usually available. */ -#define DUK_VSNPRINTF vsnprintf -#endif -#if !defined(DUK_SSCANF) -#define DUK_SSCANF sscanf -#endif -#if !defined(DUK_VSSCANF) -#define DUK_VSSCANF vsscanf -#endif -#if !defined(DUK_MEMZERO) -#define DUK_MEMZERO(p,n) DUK_MEMSET((p), 0, (n)) -#endif - -#if !defined(DUK_DOUBLE_INFINITY) -#undef DUK_USE_COMPUTED_INFINITY -#if defined(DUK_F_GCC_VERSION) && (DUK_F_GCC_VERSION < 40600) -/* GCC older than 4.6: avoid overflow warnings related to using INFINITY */ -#define DUK_DOUBLE_INFINITY (__builtin_inf()) -#elif defined(INFINITY) -#define DUK_DOUBLE_INFINITY ((double) INFINITY) -#elif !defined(DUK_F_VBCC) && !defined(DUK_F_MSVC) && !defined(DUK_F_BCC) && \ - !defined(DUK_F_OLD_SOLARIS) && !defined(DUK_F_AIX) -#define DUK_DOUBLE_INFINITY (1.0 / 0.0) -#else -/* In VBCC (1.0 / 0.0) results in a warning and 0.0 instead of infinity. - * Use a computed infinity (initialized when a heap is created at the - * latest). - */ -#define DUK_USE_COMPUTED_INFINITY -#define DUK_DOUBLE_INFINITY duk_computed_infinity -#endif -#endif - -#if !defined(DUK_DOUBLE_NAN) -#undef DUK_USE_COMPUTED_NAN -#if defined(NAN) -#define DUK_DOUBLE_NAN NAN -#elif !defined(DUK_F_VBCC) && !defined(DUK_F_MSVC) && !defined(DUK_F_BCC) && \ - !defined(DUK_F_OLD_SOLARIS) && !defined(DUK_F_AIX) -#define DUK_DOUBLE_NAN (0.0 / 0.0) -#else -/* In VBCC (0.0 / 0.0) results in a warning and 0.0 instead of NaN. - * In MSVC (VS2010 Express) (0.0 / 0.0) results in a compile error. - * Use a computed NaN (initialized when a heap is created at the - * latest). - */ -#define DUK_USE_COMPUTED_NAN -#define DUK_DOUBLE_NAN duk_computed_nan -#endif -#endif - -/* Many platforms are missing fpclassify() and friends, so use replacements - * if necessary. The replacement constants (FP_NAN etc) can be anything but - * match Linux constants now. - */ -#undef DUK_USE_REPL_FPCLASSIFY -#undef DUK_USE_REPL_SIGNBIT -#undef DUK_USE_REPL_ISFINITE -#undef DUK_USE_REPL_ISNAN -#undef DUK_USE_REPL_ISINF - -/* Complex condition broken into separate parts. */ -#undef DUK_F_USE_REPL_ALL -#if !(defined(FP_NAN) && defined(FP_INFINITE) && defined(FP_ZERO) && \ - defined(FP_SUBNORMAL) && defined(FP_NORMAL)) -/* Missing some obvious constants. */ -#define DUK_F_USE_REPL_ALL -#elif defined(DUK_F_AMIGAOS) && defined(DUK_F_VBCC) -/* VBCC is missing the built-ins even in C99 mode (perhaps a header issue). */ -#define DUK_F_USE_REPL_ALL -#elif defined(DUK_F_AMIGAOS) && defined(DUK_F_M68K) -/* AmigaOS + M68K seems to have math issues even when using GCC cross - * compilation. Use replacements for all AmigaOS versions on M68K - * regardless of compiler. - */ -#define DUK_F_USE_REPL_ALL -#elif defined(DUK_F_FREEBSD) && defined(DUK_F_CLANG) -/* Placeholder fix for (detection is wider than necessary): - * http://llvm.org/bugs/show_bug.cgi?id=17788 - */ -#define DUK_F_USE_REPL_ALL -#elif defined(DUK_F_UCLIBC) -/* At least some uclibc versions have broken floating point math. For - * example, fpclassify() can incorrectly classify certain NaN formats. - * To be safe, use replacements. - */ -#define DUK_F_USE_REPL_ALL -#elif defined(DUK_F_AIX) -/* Older versions may be missing isnan(), etc. */ -#define DUK_F_USE_REPL_ALL -#endif - -#if defined(DUK_F_USE_REPL_ALL) -#define DUK_USE_REPL_FPCLASSIFY -#define DUK_USE_REPL_SIGNBIT -#define DUK_USE_REPL_ISFINITE -#define DUK_USE_REPL_ISNAN -#define DUK_USE_REPL_ISINF -#define DUK_FPCLASSIFY duk_repl_fpclassify -#define DUK_SIGNBIT duk_repl_signbit -#define DUK_ISFINITE duk_repl_isfinite -#define DUK_ISNAN duk_repl_isnan -#define DUK_ISINF duk_repl_isinf -#define DUK_FP_NAN 0 -#define DUK_FP_INFINITE 1 -#define DUK_FP_ZERO 2 -#define DUK_FP_SUBNORMAL 3 -#define DUK_FP_NORMAL 4 -#else -#define DUK_FPCLASSIFY fpclassify -#define DUK_SIGNBIT signbit -#define DUK_ISFINITE isfinite -#define DUK_ISNAN isnan -#define DUK_ISINF isinf -#define DUK_FP_NAN FP_NAN -#define DUK_FP_INFINITE FP_INFINITE -#define DUK_FP_ZERO FP_ZERO -#define DUK_FP_SUBNORMAL FP_SUBNORMAL -#define DUK_FP_NORMAL FP_NORMAL -#endif - -#if defined(DUK_F_USE_REPL_ALL) -#undef DUK_F_USE_REPL_ALL -#endif - -/* These functions don't currently need replacement but are wrapped for - * completeness. Because these are used as function pointers, they need - * to be defined as concrete C functions (not macros). - */ -#if !defined(DUK_FABS) -#define DUK_FABS fabs -#endif -#if !defined(DUK_FLOOR) -#define DUK_FLOOR floor -#endif -#if !defined(DUK_CEIL) -#define DUK_CEIL ceil -#endif -#if !defined(DUK_FMOD) -#define DUK_FMOD fmod -#endif -#if !defined(DUK_POW) -#define DUK_POW pow -#endif -#if !defined(DUK_ACOS) -#define DUK_ACOS acos -#endif -#if !defined(DUK_ASIN) -#define DUK_ASIN asin -#endif -#if !defined(DUK_ATAN) -#define DUK_ATAN atan -#endif -#if !defined(DUK_ATAN2) -#define DUK_ATAN2 atan2 -#endif -#if !defined(DUK_SIN) -#define DUK_SIN sin -#endif -#if !defined(DUK_COS) -#define DUK_COS cos -#endif -#if !defined(DUK_TAN) -#define DUK_TAN tan -#endif -#if !defined(DUK_EXP) -#define DUK_EXP exp -#endif -#if !defined(DUK_LOG) -#define DUK_LOG log -#endif -#if !defined(DUK_SQRT) -#define DUK_SQRT sqrt -#endif - -/* The functions below exist only in C99/C++11 or later and need a workaround - * for platforms that don't include them. MSVC isn't detected as C99, but - * these functions also exist in MSVC 2013 and later so include a clause for - * that too. Android doesn't have log2; disable all of these for Android. - */ -#if (defined(DUK_F_C99) || defined(DUK_F_CPP11) || (defined(_MSC_VER) && (_MSC_VER >= 1800))) && \ - !defined(DUK_F_ANDROID) && !defined(DUK_F_MINT) -#if !defined(DUK_CBRT) -#define DUK_CBRT cbrt -#endif -#if !defined(DUK_LOG2) -#define DUK_LOG2 log2 -#endif -#if !defined(DUK_LOG10) -#define DUK_LOG10 log10 -#endif -#if !defined(DUK_TRUNC) -#define DUK_TRUNC trunc -#endif -#endif /* DUK_F_C99 etc */ - -/* NetBSD 6.0 x86 (at least) has a few problems with pow() semantics, - * see test-bug-netbsd-math-pow.js. MinGW has similar (but different) - * issues, see test-bug-mingw-math-issues.js. Enable pow() workarounds - * for these targets. - */ -#undef DUK_USE_POW_WORKAROUNDS -#if defined(DUK_F_NETBSD) || defined(DUK_F_MINGW) -#define DUK_USE_POW_WORKAROUNDS -#endif - -/* Similar workarounds for atan2() semantics issues. MinGW issues are - * documented in test-bug-mingw-math-issues.js. - */ -#undef DUK_USE_ATAN2_WORKAROUNDS -#if defined(DUK_F_MINGW) -#define DUK_USE_ATAN2_WORKAROUNDS -#endif - -/* Rely as little as possible on compiler behavior for NaN comparison, - * signed zero handling, etc. Currently never activated but may be needed - * for broken compilers. - */ -#undef DUK_USE_PARANOID_MATH - -/* There was a curious bug where test-bi-date-canceling.js would fail e.g. - * on 64-bit Ubuntu, gcc-4.8.1, -m32, and no -std=c99. Some date computations - * using doubles would be optimized which then broke some corner case tests. - * The problem goes away by adding 'volatile' to the datetime computations. - * Not sure what the actual triggering conditions are, but using this on - * non-C99 systems solves the known issues and has relatively little cost - * on other platforms. - */ -#undef DUK_USE_PARANOID_DATE_COMPUTATION -#if !defined(DUK_F_C99) -#define DUK_USE_PARANOID_DATE_COMPUTATION -#endif - -/* - * Byte order and double memory layout detection - * - * Endianness detection is a major portability hassle because the macros - * and headers are not standardized. There's even variance across UNIX - * platforms. Even with "standard" headers, details like underscore count - * varies between platforms, e.g. both __BYTE_ORDER and _BYTE_ORDER are used - * (Crossbridge has a single underscore, for instance). - * - * The checks below are structured with this in mind: several approaches are - * used, and at the end we check if any of them worked. This allows generic - * approaches to be tried first, and platform/compiler specific hacks tried - * last. As a last resort, the user can force a specific endianness, as it's - * not likely that automatic detection will work on the most exotic platforms. - * - * Duktape supports little and big endian machines. There's also support - * for a hybrid used by some ARM machines where integers are little endian - * but IEEE double values use a mixed order (12345678 -> 43218765). This - * byte order for doubles is referred to as "mixed endian". - */ - -/* GCC and Clang provide endianness defines as built-in predefines, with - * leading and trailing double underscores (e.g. __BYTE_ORDER__). See - * output of "make gccpredefs" and "make clangpredefs". Clang doesn't - * seem to provide __FLOAT_WORD_ORDER__; assume not mixed endian for clang. - * http://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html - */ -#if !defined(DUK_USE_BYTEORDER) && defined(__BYTE_ORDER__) -#if defined(__ORDER_LITTLE_ENDIAN__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) -#if defined(__FLOAT_WORD_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && (__FLOAT_WORD_ORDER__ == __ORDER_LITTLE_ENDIAN__) -#define DUK_USE_BYTEORDER 1 -#elif defined(__FLOAT_WORD_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && (__FLOAT_WORD_ORDER__ == __ORDER_BIG_ENDIAN__) -#define DUK_USE_BYTEORDER 2 -#elif !defined(__FLOAT_WORD_ORDER__) -/* Float word order not known, assume not a hybrid. */ -#define DUK_USE_BYTEORDER 1 -#else -/* Byte order is little endian but cannot determine IEEE double word order. */ -#endif /* float word order */ -#elif defined(__ORDER_BIG_ENDIAN__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) -#if defined(__FLOAT_WORD_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && (__FLOAT_WORD_ORDER__ == __ORDER_BIG_ENDIAN__) -#define DUK_USE_BYTEORDER 3 -#elif !defined(__FLOAT_WORD_ORDER__) -/* Float word order not known, assume not a hybrid. */ -#define DUK_USE_BYTEORDER 3 -#else -/* Byte order is big endian but cannot determine IEEE double word order. */ -#endif /* float word order */ -#else -/* Cannot determine byte order; __ORDER_PDP_ENDIAN__ is related to 32-bit - * integer ordering and is not relevant. - */ -#endif /* integer byte order */ -#endif /* !defined(DUK_USE_BYTEORDER) && defined(__BYTE_ORDER__) */ - -/* More or less standard endianness predefines provided by header files. - * The ARM hybrid case is detected by assuming that __FLOAT_WORD_ORDER - * will be big endian, see: http://lists.mysql.com/internals/443. - * On some platforms some defines may be present with an empty value which - * causes comparisons to fail: https://github.com/svaarala/duktape/issues/453. - */ -#if !defined(DUK_USE_BYTEORDER) -#if defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && (__BYTE_ORDER == __LITTLE_ENDIAN) || \ - defined(_BYTE_ORDER) && defined(_LITTLE_ENDIAN) && (_BYTE_ORDER == _LITTLE_ENDIAN) || \ - defined(__LITTLE_ENDIAN__) -#if defined(__FLOAT_WORD_ORDER) && defined(__LITTLE_ENDIAN) && (__FLOAT_WORD_ORDER == __LITTLE_ENDIAN) || \ - defined(_FLOAT_WORD_ORDER) && defined(_LITTLE_ENDIAN) && (_FLOAT_WORD_ORDER == _LITTLE_ENDIAN) -#define DUK_USE_BYTEORDER 1 -#elif defined(__FLOAT_WORD_ORDER) && defined(__BIG_ENDIAN) && (__FLOAT_WORD_ORDER == __BIG_ENDIAN) || \ - defined(_FLOAT_WORD_ORDER) && defined(_BIG_ENDIAN) && (_FLOAT_WORD_ORDER == _BIG_ENDIAN) -#define DUK_USE_BYTEORDER 2 -#elif !defined(__FLOAT_WORD_ORDER) && !defined(_FLOAT_WORD_ORDER) -/* Float word order not known, assume not a hybrid. */ -#define DUK_USE_BYTEORDER 1 -#else -/* Byte order is little endian but cannot determine IEEE double word order. */ -#endif /* float word order */ -#elif defined(__BYTE_ORDER) && defined(__BIG_ENDIAN) && (__BYTE_ORDER == __BIG_ENDIAN) || \ - defined(_BYTE_ORDER) && defined(_BIG_ENDIAN) && (_BYTE_ORDER == _BIG_ENDIAN) || \ - defined(__BIG_ENDIAN__) -#if defined(__FLOAT_WORD_ORDER) && defined(__BIG_ENDIAN) && (__FLOAT_WORD_ORDER == __BIG_ENDIAN) || \ - defined(_FLOAT_WORD_ORDER) && defined(_BIG_ENDIAN) && (_FLOAT_WORD_ORDER == _BIG_ENDIAN) -#define DUK_USE_BYTEORDER 3 -#elif !defined(__FLOAT_WORD_ORDER) && !defined(_FLOAT_WORD_ORDER) -/* Float word order not known, assume not a hybrid. */ -#define DUK_USE_BYTEORDER 3 -#else -/* Byte order is big endian but cannot determine IEEE double word order. */ -#endif /* float word order */ -#else -/* Cannot determine byte order. */ -#endif /* integer byte order */ -#endif /* !defined(DUK_USE_BYTEORDER) */ - -/* QNX gcc cross compiler seems to define e.g. __LITTLEENDIAN__ or __BIGENDIAN__: - * $ /opt/qnx650/host/linux/x86/usr/bin/i486-pc-nto-qnx6.5.0-gcc -dM -E -
> 24) | \ - ((((duk_uint32_t) (x)) >> 8) & 0xff00UL) | \ - ((((duk_uint32_t) (x)) << 8) & 0xff0000UL) | \ - (((duk_uint32_t) (x)) << 24)) -#endif -#if !defined(DUK_BSWAP16) -#define DUK_BSWAP16(x) \ - ((duk_uint16_t) (x) >> 8) | \ - ((duk_uint16_t) (x) << 8) -#endif - -/* DUK_USE_VARIADIC_MACROS: required from compilers, so no fill-in. */ -/* DUK_USE_UNION_INITIALIZERS: required from compilers, so no fill-in. */ - -#if !(defined(DUK_USE_FLEX_C99) || defined(DUK_USE_FLEX_ZEROSIZE) || defined(DUK_USE_FLEX_ONESIZE)) -#if defined(DUK_F_C99) -#define DUK_USE_FLEX_C99 -#else -#define DUK_USE_FLEX_ZEROSIZE /* Not standard but common enough */ -#endif -#endif - -#if !(defined(DUK_USE_PACK_GCC_ATTR) || defined(DUK_USE_PACK_CLANG_ATTR) || \ - defined(DUK_USE_PACK_MSVC_PRAGMA) || defined(DUK_USE_PACK_DUMMY_MEMBER)) -#define DUK_USE_PACK_DUMMY_MEMBER -#endif - -#if 0 /* not defined by default */ -#undef DUK_USE_GCC_PRAGMAS -#endif - -#if !defined(DUK_U64_CONSTANT) -#define DUK_U64_CONSTANT(x) x##ULL -#endif -#if !defined(DUK_I64_CONSTANT) -#define DUK_I64_CONSTANT(x) x##LL -#endif - -/* Workaround for GH-323: avoid inlining control when compiling from - * multiple sources, as it causes compiler portability trouble. - */ -#if !defined(DUK_SINGLE_FILE) -#undef DUK_NOINLINE -#undef DUK_INLINE -#undef DUK_ALWAYS_INLINE -#define DUK_NOINLINE /*nop*/ -#define DUK_INLINE /*nop*/ -#define DUK_ALWAYS_INLINE /*nop*/ -#endif - -/* - * Check whether or not a packed duk_tval representation is possible. - * What's basically required is that pointers are 32-bit values - * (sizeof(void *) == 4). Best effort check, not always accurate. - * If guess goes wrong, crashes may result; self tests also verify - * the guess. - */ - -/* Explicit marker needed; may be 'defined', 'undefined, 'or 'not provided'. */ -#if !defined(DUK_F_PACKED_TVAL_PROVIDED) -#undef DUK_F_PACKED_TVAL_POSSIBLE - -/* Strict C99 case: DUK_UINTPTR_MAX (= UINTPTR_MAX) should be very reliable */ -#if !defined(DUK_F_PACKED_TVAL_POSSIBLE) && defined(DUK_UINTPTR_MAX) -#if (DUK_UINTPTR_MAX <= 0xffffffffUL) -#define DUK_F_PACKED_TVAL_POSSIBLE -#endif -#endif - -/* Non-C99 case, still relying on DUK_UINTPTR_MAX, as long as it is not a computed value */ -#if !defined(DUK_F_PACKED_TVAL_POSSIBLE) && defined(DUK_UINTPTR_MAX) && !defined(DUK_UINTPTR_MAX_COMPUTED) -#if (DUK_UINTPTR_MAX <= 0xffffffffUL) -#define DUK_F_PACKED_TVAL_POSSIBLE -#endif -#endif - -/* DUK_SIZE_MAX (= SIZE_MAX) is often reliable */ -#if !defined(DUK_F_PACKED_TVAL_POSSIBLE) && defined(DUK_SIZE_MAX) && !defined(DUK_SIZE_MAX_COMPUTED) -#if (DUK_SIZE_MAX <= 0xffffffffUL) -#define DUK_F_PACKED_TVAL_POSSIBLE -#endif -#endif - -#undef DUK_USE_PACKED_TVAL -#if defined(DUK_F_PACKED_TVAL_POSSIBLE) -#define DUK_USE_PACKED_TVAL -#endif - -#undef DUK_F_PACKED_TVAL_POSSIBLE -#endif /* DUK_F_PACKED_TVAL_PROVIDED */ -/* Object property allocation layout has implications for memory and code - * footprint and generated code size/speed. The best layout also depends - * on whether the platform has alignment requirements or benefits from - * having mostly aligned accesses. - */ -#undef DUK_USE_HOBJECT_LAYOUT_1 -#undef DUK_USE_HOBJECT_LAYOUT_2 -#undef DUK_USE_HOBJECT_LAYOUT_3 -#if (DUK_USE_ALIGN_BY == 1) -/* On platforms without any alignment issues, layout 1 is preferable - * because it compiles to slightly less code and provides direct access - * to property keys. - */ -#define DUK_USE_HOBJECT_LAYOUT_1 -#else -/* On other platforms use layout 2, which requires some padding but - * is a bit more natural than layout 3 in ordering the entries. Layout - * 3 is currently not used. - */ -#define DUK_USE_HOBJECT_LAYOUT_2 -#endif - -/* GCC/clang inaccurate math would break compliance and probably duk_tval, - * so refuse to compile. Relax this if -ffast-math is tested to work. - */ -#if defined(__FAST_MATH__) -#error __FAST_MATH__ defined, refusing to compile -#endif - -/* - * Autogenerated defaults - */ - -#define DUK_USE_ARRAY_BUILTIN -#define DUK_USE_ARRAY_FASTPATH -#define DUK_USE_ARRAY_PROP_FASTPATH -#undef DUK_USE_ASSERTIONS -#define DUK_USE_AUGMENT_ERROR_CREATE -#define DUK_USE_AUGMENT_ERROR_THROW -#define DUK_USE_AVOID_PLATFORM_FUNCPTRS -#define DUK_USE_BASE64_FASTPATH -#define DUK_USE_BOOLEAN_BUILTIN -#define DUK_USE_BUFFEROBJECT_SUPPORT -#undef DUK_USE_BUFLEN16 -#define DUK_USE_BYTECODE_DUMP_SUPPORT -#define DUK_USE_CACHE_ACTIVATION -#define DUK_USE_CACHE_CATCHER -#define DUK_USE_CALLSTACK_LIMIT 10000 -#define DUK_USE_COMMONJS_MODULES -#define DUK_USE_COMPILER_RECLIMIT 2500 -#define DUK_USE_COROUTINE_SUPPORT -#undef DUK_USE_CPP_EXCEPTIONS -#undef DUK_USE_DATAPTR16 -#undef DUK_USE_DATAPTR_DEC16 -#undef DUK_USE_DATAPTR_ENC16 -#define DUK_USE_DATE_BUILTIN -#undef DUK_USE_DATE_FORMAT_STRING -#undef DUK_USE_DATE_GET_LOCAL_TZOFFSET -#undef DUK_USE_DATE_GET_NOW -#undef DUK_USE_DATE_PARSE_STRING -#undef DUK_USE_DATE_PRS_GETDATE -#undef DUK_USE_DEBUG -#undef DUK_USE_DEBUGGER_DUMPHEAP -#undef DUK_USE_DEBUGGER_INSPECT -#undef DUK_USE_DEBUGGER_PAUSE_UNCAUGHT -#undef DUK_USE_DEBUGGER_SUPPORT -#define DUK_USE_DEBUGGER_THROW_NOTIFY -#undef DUK_USE_DEBUGGER_TRANSPORT_TORTURE -#define DUK_USE_DEBUG_BUFSIZE 65536L -#define DUK_USE_DEBUG_LEVEL 0 -#undef DUK_USE_DEBUG_WRITE -#define DUK_USE_DOUBLE_LINKED_HEAP -#define DUK_USE_DUKTAPE_BUILTIN -#define DUK_USE_ENCODING_BUILTINS -#define DUK_USE_ERRCREATE -#define DUK_USE_ERRTHROW -#define DUK_USE_ES6 -#define DUK_USE_ES6_OBJECT_PROTO_PROPERTY -#define DUK_USE_ES6_OBJECT_SETPROTOTYPEOF -#define DUK_USE_ES6_PROXY -#define DUK_USE_ES6_REGEXP_SYNTAX -#define DUK_USE_ES6_UNICODE_ESCAPE -#define DUK_USE_ES7 -#define DUK_USE_ES7_EXP_OPERATOR -#define DUK_USE_ES8 -#define DUK_USE_ES9 -#define DUK_USE_ESBC_LIMITS -#define DUK_USE_ESBC_MAX_BYTES 2147418112L -#define DUK_USE_ESBC_MAX_LINENUMBER 2147418112L -#undef DUK_USE_EXEC_FUN_LOCAL -#undef DUK_USE_EXEC_INDIRECT_BOUND_CHECK -#undef DUK_USE_EXEC_PREFER_SIZE -#define DUK_USE_EXEC_REGCONST_OPTIMIZE -#undef DUK_USE_EXEC_TIMEOUT_CHECK -#undef DUK_USE_EXPLICIT_NULL_INIT -#undef DUK_USE_EXTSTR_FREE -#undef DUK_USE_EXTSTR_INTERN_CHECK -#undef DUK_USE_FASTINT -#define DUK_USE_FAST_REFCOUNT_DEFAULT -#undef DUK_USE_FATAL_HANDLER -#define DUK_USE_FATAL_MAXLEN 128 -#define DUK_USE_FINALIZER_SUPPORT -#undef DUK_USE_FINALIZER_TORTURE -#undef DUK_USE_FUNCPTR16 -#undef DUK_USE_FUNCPTR_DEC16 -#undef DUK_USE_FUNCPTR_ENC16 -#define DUK_USE_FUNCTION_BUILTIN -#define DUK_USE_FUNC_FILENAME_PROPERTY -#define DUK_USE_FUNC_NAME_PROPERTY -#undef DUK_USE_GC_TORTURE -#undef DUK_USE_GET_MONOTONIC_TIME -#undef DUK_USE_GET_RANDOM_DOUBLE -#undef DUK_USE_GLOBAL_BINDING -#define DUK_USE_GLOBAL_BUILTIN -#undef DUK_USE_HEAPPTR16 -#undef DUK_USE_HEAPPTR_DEC16 -#undef DUK_USE_HEAPPTR_ENC16 -#define DUK_USE_HEX_FASTPATH -#define DUK_USE_HOBJECT_ARRAY_ABANDON_LIMIT 2 -#define DUK_USE_HOBJECT_ARRAY_FAST_RESIZE_LIMIT 9 -#define DUK_USE_HOBJECT_ARRAY_MINGROW_ADD 16 -#define DUK_USE_HOBJECT_ARRAY_MINGROW_DIVISOR 8 -#define DUK_USE_HOBJECT_ENTRY_MINGROW_ADD 16 -#define DUK_USE_HOBJECT_ENTRY_MINGROW_DIVISOR 8 -#define DUK_USE_HOBJECT_HASH_PART -#define DUK_USE_HOBJECT_HASH_PROP_LIMIT 8 -#define DUK_USE_HSTRING_ARRIDX -#define DUK_USE_HSTRING_CLEN -#undef DUK_USE_HSTRING_EXTDATA -#define DUK_USE_HSTRING_LAZY_CLEN -#define DUK_USE_HTML_COMMENTS -#define DUK_USE_IDCHAR_FASTPATH -#undef DUK_USE_INJECT_HEAP_ALLOC_ERROR -#undef DUK_USE_INTERRUPT_COUNTER -#undef DUK_USE_INTERRUPT_DEBUG_FIXUP -#define DUK_USE_JC -#define DUK_USE_JSON_BUILTIN -#define DUK_USE_JSON_DECNUMBER_FASTPATH -#define DUK_USE_JSON_DECSTRING_FASTPATH -#define DUK_USE_JSON_DEC_RECLIMIT 1000 -#define DUK_USE_JSON_EATWHITE_FASTPATH -#define DUK_USE_JSON_ENC_RECLIMIT 1000 -#define DUK_USE_JSON_QUOTESTRING_FASTPATH -#undef DUK_USE_JSON_STRINGIFY_FASTPATH -#define DUK_USE_JSON_SUPPORT -#define DUK_USE_JX -#define DUK_USE_LEXER_SLIDING_WINDOW -#undef DUK_USE_LIGHTFUNC_BUILTINS -#define DUK_USE_MARK_AND_SWEEP_RECLIMIT 256 -#define DUK_USE_MATH_BUILTIN -#define DUK_USE_NATIVE_CALL_RECLIMIT 1000 -#define DUK_USE_NONSTD_ARRAY_CONCAT_TRAILER -#define DUK_USE_NONSTD_ARRAY_MAP_TRAILER -#define DUK_USE_NONSTD_ARRAY_SPLICE_DELCOUNT -#undef DUK_USE_NONSTD_FUNC_CALLER_PROPERTY -#undef DUK_USE_NONSTD_FUNC_SOURCE_PROPERTY -#define DUK_USE_NONSTD_FUNC_STMT -#define DUK_USE_NONSTD_GETTER_KEY_ARGUMENT -#define DUK_USE_NONSTD_JSON_ESC_U2028_U2029 -#define DUK_USE_NONSTD_SETTER_KEY_ARGUMENT -#define DUK_USE_NONSTD_STRING_FROMCHARCODE_32BIT -#define DUK_USE_NUMBER_BUILTIN -#define DUK_USE_OBJECT_BUILTIN -#undef DUK_USE_OBJSIZES16 -#undef DUK_USE_PARANOID_ERRORS -#define DUK_USE_PC2LINE -#define DUK_USE_PERFORMANCE_BUILTIN -#undef DUK_USE_PREFER_SIZE -#undef DUK_USE_PROMISE_BUILTIN -#define DUK_USE_PROVIDE_DEFAULT_ALLOC_FUNCTIONS -#undef DUK_USE_REFCOUNT16 -#define DUK_USE_REFCOUNT32 -#define DUK_USE_REFERENCE_COUNTING -#define DUK_USE_REFLECT_BUILTIN -#define DUK_USE_REGEXP_CANON_BITMAP -#undef DUK_USE_REGEXP_CANON_WORKAROUND -#define DUK_USE_REGEXP_COMPILER_RECLIMIT 10000 -#define DUK_USE_REGEXP_EXECUTOR_RECLIMIT 10000 -#define DUK_USE_REGEXP_SUPPORT -#undef DUK_USE_ROM_GLOBAL_CLONE -#undef DUK_USE_ROM_GLOBAL_INHERIT -#undef DUK_USE_ROM_OBJECTS -#define DUK_USE_ROM_PTRCOMP_FIRST 63488L -#undef DUK_USE_ROM_STRINGS -#define DUK_USE_SECTION_B -#undef DUK_USE_SELF_TESTS -#define DUK_USE_SHEBANG_COMMENTS -#undef DUK_USE_SHUFFLE_TORTURE -#define DUK_USE_SOURCE_NONBMP -#undef DUK_USE_STRHASH16 -#undef DUK_USE_STRHASH_DENSE -#define DUK_USE_STRHASH_SKIP_SHIFT 5 -#define DUK_USE_STRICT_DECL -#undef DUK_USE_STRICT_UTF8_SOURCE -#define DUK_USE_STRING_BUILTIN -#undef DUK_USE_STRLEN16 -#define DUK_USE_STRTAB_GROW_LIMIT 17 -#define DUK_USE_STRTAB_MAXSIZE 268435456L -#define DUK_USE_STRTAB_MINSIZE 1024 -#undef DUK_USE_STRTAB_PTRCOMP -#define DUK_USE_STRTAB_RESIZE_CHECK_MASK 255 -#define DUK_USE_STRTAB_SHRINK_LIMIT 6 -#undef DUK_USE_STRTAB_TORTURE -#undef DUK_USE_SYMBOL_BUILTIN -#define DUK_USE_TAILCALL -#define DUK_USE_TARGET_INFO "unknown" -#define DUK_USE_TRACEBACKS -#define DUK_USE_TRACEBACK_DEPTH 10 -#define DUK_USE_USER_DECLARE() /* no user declarations */ -#define DUK_USE_VALSTACK_GROW_SHIFT 2 -#define DUK_USE_VALSTACK_LIMIT 1000000L -#define DUK_USE_VALSTACK_SHRINK_CHECK_SHIFT 2 -#define DUK_USE_VALSTACK_SHRINK_SLACK_SHIFT 4 -#undef DUK_USE_VALSTACK_UNSAFE -#define DUK_USE_VERBOSE_ERRORS -#define DUK_USE_VERBOSE_EXECUTOR_ERRORS -#define DUK_USE_VOLUNTARY_GC -#define DUK_USE_ZERO_BUFFER_DATA - -/* - * You may add overriding #define/#undef directives below for - * customization. You of course cannot un-#include or un-typedef - * anything; these require direct changes above. - */ - -/* __OVERRIDE_DEFINES__ */ - -/* - * Date provider selection - * - * User may define DUK_USE_DATE_GET_NOW() etc directly, in which case we'll - * rely on an external provider. If this is not done, revert to previous - * behavior and use Unix/Windows built-in provider. - */ - -#if defined(DUK_COMPILING_DUKTAPE) - -#if defined(DUK_USE_DATE_GET_NOW) -/* External provider already defined. */ -#elif defined(DUK_USE_DATE_NOW_GETTIMEOFDAY) -#define DUK_USE_DATE_GET_NOW(ctx) duk_bi_date_get_now_gettimeofday() -#elif defined(DUK_USE_DATE_NOW_TIME) -#define DUK_USE_DATE_GET_NOW(ctx) duk_bi_date_get_now_time() -#elif defined(DUK_USE_DATE_NOW_WINDOWS) -#define DUK_USE_DATE_GET_NOW(ctx) duk_bi_date_get_now_windows() -#elif defined(DUK_USE_DATE_NOW_WINDOWS_SUBMS) -#define DUK_USE_DATE_GET_NOW(ctx) duk_bi_date_get_now_windows_subms() -#else -#error no provider for DUK_USE_DATE_GET_NOW() -#endif - -#if defined(DUK_USE_DATE_GET_LOCAL_TZOFFSET) -/* External provider already defined. */ -#elif defined(DUK_USE_DATE_TZO_GMTIME_R) || defined(DUK_USE_DATE_TZO_GMTIME_S) || defined(DUK_USE_DATE_TZO_GMTIME) -#define DUK_USE_DATE_GET_LOCAL_TZOFFSET(d) duk_bi_date_get_local_tzoffset_gmtime((d)) -#elif defined(DUK_USE_DATE_TZO_WINDOWS) -#define DUK_USE_DATE_GET_LOCAL_TZOFFSET(d) duk_bi_date_get_local_tzoffset_windows((d)) -#elif defined(DUK_USE_DATE_TZO_WINDOWS_NO_DST) -#define DUK_USE_DATE_GET_LOCAL_TZOFFSET(d) duk_bi_date_get_local_tzoffset_windows_no_dst((d)) -#else -#error no provider for DUK_USE_DATE_GET_LOCAL_TZOFFSET() -#endif - -#if defined(DUK_USE_DATE_PARSE_STRING) -/* External provider already defined. */ -#elif defined(DUK_USE_DATE_PRS_STRPTIME) -#define DUK_USE_DATE_PARSE_STRING(ctx,str) duk_bi_date_parse_string_strptime((ctx), (str)) -#elif defined(DUK_USE_DATE_PRS_GETDATE) -#define DUK_USE_DATE_PARSE_STRING(ctx,str) duk_bi_date_parse_string_getdate((ctx), (str)) -#else -/* No provider for DUK_USE_DATE_PARSE_STRING(), fall back to ISO 8601 only. */ -#endif - -#if defined(DUK_USE_DATE_FORMAT_STRING) -/* External provider already defined. */ -#elif defined(DUK_USE_DATE_FMT_STRFTIME) -#define DUK_USE_DATE_FORMAT_STRING(ctx,parts,tzoffset,flags) \ - duk_bi_date_format_parts_strftime((ctx), (parts), (tzoffset), (flags)) -#else -/* No provider for DUK_USE_DATE_FORMAT_STRING(), fall back to ISO 8601 only. */ -#endif - -#if defined(DUK_USE_GET_MONOTONIC_TIME) -/* External provider already defined. */ -#elif defined(DUK_USE_GET_MONOTONIC_TIME_CLOCK_GETTIME) -#define DUK_USE_GET_MONOTONIC_TIME(ctx) duk_bi_date_get_monotonic_time_clock_gettime() -#elif defined(DUK_USE_GET_MONOTONIC_TIME_WINDOWS_QPC) -#define DUK_USE_GET_MONOTONIC_TIME(ctx) duk_bi_date_get_monotonic_time_windows_qpc() -#else -/* No provider for DUK_USE_GET_MONOTONIC_TIME(), fall back to DUK_USE_DATE_GET_NOW(). */ -#endif - -#endif /* DUK_COMPILING_DUKTAPE */ - -/* - * Checks for legacy feature options (DUK_OPT_xxx) - */ - -#if defined(DUK_OPT_ASSERTIONS) -#error unsupported legacy feature option DUK_OPT_ASSERTIONS used -#endif -#if defined(DUK_OPT_BUFFEROBJECT_SUPPORT) -#error unsupported legacy feature option DUK_OPT_BUFFEROBJECT_SUPPORT used -#endif -#if defined(DUK_OPT_BUFLEN16) -#error unsupported legacy feature option DUK_OPT_BUFLEN16 used -#endif -#if defined(DUK_OPT_DATAPTR16) -#error unsupported legacy feature option DUK_OPT_DATAPTR16 used -#endif -#if defined(DUK_OPT_DATAPTR_DEC16) -#error unsupported legacy feature option DUK_OPT_DATAPTR_DEC16 used -#endif -#if defined(DUK_OPT_DATAPTR_ENC16) -#error unsupported legacy feature option DUK_OPT_DATAPTR_ENC16 used -#endif -#if defined(DUK_OPT_DDDPRINT) -#error unsupported legacy feature option DUK_OPT_DDDPRINT used -#endif -#if defined(DUK_OPT_DDPRINT) -#error unsupported legacy feature option DUK_OPT_DDPRINT used -#endif -#if defined(DUK_OPT_DEBUG) -#error unsupported legacy feature option DUK_OPT_DEBUG used -#endif -#if defined(DUK_OPT_DEBUGGER_DUMPHEAP) -#error unsupported legacy feature option DUK_OPT_DEBUGGER_DUMPHEAP used -#endif -#if defined(DUK_OPT_DEBUGGER_FWD_LOGGING) -#error unsupported legacy feature option DUK_OPT_DEBUGGER_FWD_LOGGING used -#endif -#if defined(DUK_OPT_DEBUGGER_FWD_PRINTALERT) -#error unsupported legacy feature option DUK_OPT_DEBUGGER_FWD_PRINTALERT used -#endif -#if defined(DUK_OPT_DEBUGGER_SUPPORT) -#error unsupported legacy feature option DUK_OPT_DEBUGGER_SUPPORT used -#endif -#if defined(DUK_OPT_DEBUGGER_TRANSPORT_TORTURE) -#error unsupported legacy feature option DUK_OPT_DEBUGGER_TRANSPORT_TORTURE used -#endif -#if defined(DUK_OPT_DEBUG_BUFSIZE) -#error unsupported legacy feature option DUK_OPT_DEBUG_BUFSIZE used -#endif -#if defined(DUK_OPT_DECLARE) -#error unsupported legacy feature option DUK_OPT_DECLARE used -#endif -#if defined(DUK_OPT_DEEP_C_STACK) -#error unsupported legacy feature option DUK_OPT_DEEP_C_STACK used -#endif -#if defined(DUK_OPT_DLL_BUILD) -#error unsupported legacy feature option DUK_OPT_DLL_BUILD used -#endif -#if defined(DUK_OPT_DPRINT) -#error unsupported legacy feature option DUK_OPT_DPRINT used -#endif -#if defined(DUK_OPT_DPRINT_COLORS) -#error unsupported legacy feature option DUK_OPT_DPRINT_COLORS used -#endif -#if defined(DUK_OPT_DPRINT_RDTSC) -#error unsupported legacy feature option DUK_OPT_DPRINT_RDTSC used -#endif -#if defined(DUK_OPT_EXEC_TIMEOUT_CHECK) -#error unsupported legacy feature option DUK_OPT_EXEC_TIMEOUT_CHECK used -#endif -#if defined(DUK_OPT_EXTERNAL_STRINGS) -#error unsupported legacy feature option DUK_OPT_EXTERNAL_STRINGS used -#endif -#if defined(DUK_OPT_EXTSTR_FREE) -#error unsupported legacy feature option DUK_OPT_EXTSTR_FREE used -#endif -#if defined(DUK_OPT_EXTSTR_INTERN_CHECK) -#error unsupported legacy feature option DUK_OPT_EXTSTR_INTERN_CHECK used -#endif -#if defined(DUK_OPT_FASTINT) -#error unsupported legacy feature option DUK_OPT_FASTINT used -#endif -#if defined(DUK_OPT_FORCE_ALIGN) -#error unsupported legacy feature option DUK_OPT_FORCE_ALIGN used -#endif -#if defined(DUK_OPT_FORCE_BYTEORDER) -#error unsupported legacy feature option DUK_OPT_FORCE_BYTEORDER used -#endif -#if defined(DUK_OPT_FUNCPTR16) -#error unsupported legacy feature option DUK_OPT_FUNCPTR16 used -#endif -#if defined(DUK_OPT_FUNCPTR_DEC16) -#error unsupported legacy feature option DUK_OPT_FUNCPTR_DEC16 used -#endif -#if defined(DUK_OPT_FUNCPTR_ENC16) -#error unsupported legacy feature option DUK_OPT_FUNCPTR_ENC16 used -#endif -#if defined(DUK_OPT_FUNC_NONSTD_CALLER_PROPERTY) -#error unsupported legacy feature option DUK_OPT_FUNC_NONSTD_CALLER_PROPERTY used -#endif -#if defined(DUK_OPT_FUNC_NONSTD_SOURCE_PROPERTY) -#error unsupported legacy feature option DUK_OPT_FUNC_NONSTD_SOURCE_PROPERTY used -#endif -#if defined(DUK_OPT_GC_TORTURE) -#error unsupported legacy feature option DUK_OPT_GC_TORTURE used -#endif -#if defined(DUK_OPT_HAVE_CUSTOM_H) -#error unsupported legacy feature option DUK_OPT_HAVE_CUSTOM_H used -#endif -#if defined(DUK_OPT_HEAPPTR16) -#error unsupported legacy feature option DUK_OPT_HEAPPTR16 used -#endif -#if defined(DUK_OPT_HEAPPTR_DEC16) -#error unsupported legacy feature option DUK_OPT_HEAPPTR_DEC16 used -#endif -#if defined(DUK_OPT_HEAPPTR_ENC16) -#error unsupported legacy feature option DUK_OPT_HEAPPTR_ENC16 used -#endif -#if defined(DUK_OPT_INTERRUPT_COUNTER) -#error unsupported legacy feature option DUK_OPT_INTERRUPT_COUNTER used -#endif -#if defined(DUK_OPT_JSON_STRINGIFY_FASTPATH) -#error unsupported legacy feature option DUK_OPT_JSON_STRINGIFY_FASTPATH used -#endif -#if defined(DUK_OPT_LIGHTFUNC_BUILTINS) -#error unsupported legacy feature option DUK_OPT_LIGHTFUNC_BUILTINS used -#endif -#if defined(DUK_OPT_NONSTD_FUNC_CALLER_PROPERTY) -#error unsupported legacy feature option DUK_OPT_NONSTD_FUNC_CALLER_PROPERTY used -#endif -#if defined(DUK_OPT_NONSTD_FUNC_SOURCE_PROPERTY) -#error unsupported legacy feature option DUK_OPT_NONSTD_FUNC_SOURCE_PROPERTY used -#endif -#if defined(DUK_OPT_NO_ARRAY_SPLICE_NONSTD_DELCOUNT) -#error unsupported legacy feature option DUK_OPT_NO_ARRAY_SPLICE_NONSTD_DELCOUNT used -#endif -#if defined(DUK_OPT_NO_AUGMENT_ERRORS) -#error unsupported legacy feature option DUK_OPT_NO_AUGMENT_ERRORS used -#endif -#if defined(DUK_OPT_NO_BROWSER_LIKE) -#error unsupported legacy feature option DUK_OPT_NO_BROWSER_LIKE used -#endif -#if defined(DUK_OPT_NO_BUFFEROBJECT_SUPPORT) -#error unsupported legacy feature option DUK_OPT_NO_BUFFEROBJECT_SUPPORT used -#endif -#if defined(DUK_OPT_NO_BYTECODE_DUMP_SUPPORT) -#error unsupported legacy feature option DUK_OPT_NO_BYTECODE_DUMP_SUPPORT used -#endif -#if defined(DUK_OPT_NO_COMMONJS_MODULES) -#error unsupported legacy feature option DUK_OPT_NO_COMMONJS_MODULES used -#endif -#if defined(DUK_OPT_NO_ES6_OBJECT_PROTO_PROPERTY) -#error unsupported legacy feature option DUK_OPT_NO_ES6_OBJECT_PROTO_PROPERTY used -#endif -#if defined(DUK_OPT_NO_ES6_OBJECT_SETPROTOTYPEOF) -#error unsupported legacy feature option DUK_OPT_NO_ES6_OBJECT_SETPROTOTYPEOF used -#endif -#if defined(DUK_OPT_NO_ES6_PROXY) -#error unsupported legacy feature option DUK_OPT_NO_ES6_PROXY used -#endif -#if defined(DUK_OPT_NO_FILE_IO) -#error unsupported legacy feature option DUK_OPT_NO_FILE_IO used -#endif -#if defined(DUK_OPT_NO_FUNC_STMT) -#error unsupported legacy feature option DUK_OPT_NO_FUNC_STMT used -#endif -#if defined(DUK_OPT_NO_JC) -#error unsupported legacy feature option DUK_OPT_NO_JC used -#endif -#if defined(DUK_OPT_NO_JSONC) -#error unsupported legacy feature option DUK_OPT_NO_JSONC used -#endif -#if defined(DUK_OPT_NO_JSONX) -#error unsupported legacy feature option DUK_OPT_NO_JSONX used -#endif -#if defined(DUK_OPT_NO_JX) -#error unsupported legacy feature option DUK_OPT_NO_JX used -#endif -#if defined(DUK_OPT_NO_MARK_AND_SWEEP) -#error unsupported legacy feature option DUK_OPT_NO_MARK_AND_SWEEP used -#endif -#if defined(DUK_OPT_NO_MS_STRINGTABLE_RESIZE) -#error unsupported legacy feature option DUK_OPT_NO_MS_STRINGTABLE_RESIZE used -#endif -#if defined(DUK_OPT_NO_NONSTD_ACCESSOR_KEY_ARGUMENT) -#error unsupported legacy feature option DUK_OPT_NO_NONSTD_ACCESSOR_KEY_ARGUMENT used -#endif -#if defined(DUK_OPT_NO_NONSTD_ARRAY_CONCAT_TRAILER) -#error unsupported legacy feature option DUK_OPT_NO_NONSTD_ARRAY_CONCAT_TRAILER used -#endif -#if defined(DUK_OPT_NO_NONSTD_ARRAY_MAP_TRAILER) -#error unsupported legacy feature option DUK_OPT_NO_NONSTD_ARRAY_MAP_TRAILER used -#endif -#if defined(DUK_OPT_NO_NONSTD_ARRAY_SPLICE_DELCOUNT) -#error unsupported legacy feature option DUK_OPT_NO_NONSTD_ARRAY_SPLICE_DELCOUNT used -#endif -#if defined(DUK_OPT_NO_NONSTD_FUNC_STMT) -#error unsupported legacy feature option DUK_OPT_NO_NONSTD_FUNC_STMT used -#endif -#if defined(DUK_OPT_NO_NONSTD_JSON_ESC_U2028_U2029) -#error unsupported legacy feature option DUK_OPT_NO_NONSTD_JSON_ESC_U2028_U2029 used -#endif -#if defined(DUK_OPT_NO_NONSTD_STRING_FROMCHARCODE_32BIT) -#error unsupported legacy feature option DUK_OPT_NO_NONSTD_STRING_FROMCHARCODE_32BIT used -#endif -#if defined(DUK_OPT_NO_OBJECT_ES6_PROTO_PROPERTY) -#error unsupported legacy feature option DUK_OPT_NO_OBJECT_ES6_PROTO_PROPERTY used -#endif -#if defined(DUK_OPT_NO_OBJECT_ES6_SETPROTOTYPEOF) -#error unsupported legacy feature option DUK_OPT_NO_OBJECT_ES6_SETPROTOTYPEOF used -#endif -#if defined(DUK_OPT_NO_OCTAL_SUPPORT) -#error unsupported legacy feature option DUK_OPT_NO_OCTAL_SUPPORT used -#endif -#if defined(DUK_OPT_NO_PACKED_TVAL) -#error unsupported legacy feature option DUK_OPT_NO_PACKED_TVAL used -#endif -#if defined(DUK_OPT_NO_PC2LINE) -#error unsupported legacy feature option DUK_OPT_NO_PC2LINE used -#endif -#if defined(DUK_OPT_NO_REFERENCE_COUNTING) -#error unsupported legacy feature option DUK_OPT_NO_REFERENCE_COUNTING used -#endif -#if defined(DUK_OPT_NO_REGEXP_SUPPORT) -#error unsupported legacy feature option DUK_OPT_NO_REGEXP_SUPPORT used -#endif -#if defined(DUK_OPT_NO_SECTION_B) -#error unsupported legacy feature option DUK_OPT_NO_SECTION_B used -#endif -#if defined(DUK_OPT_NO_SOURCE_NONBMP) -#error unsupported legacy feature option DUK_OPT_NO_SOURCE_NONBMP used -#endif -#if defined(DUK_OPT_NO_STRICT_DECL) -#error unsupported legacy feature option DUK_OPT_NO_STRICT_DECL used -#endif -#if defined(DUK_OPT_NO_TRACEBACKS) -#error unsupported legacy feature option DUK_OPT_NO_TRACEBACKS used -#endif -#if defined(DUK_OPT_NO_VERBOSE_ERRORS) -#error unsupported legacy feature option DUK_OPT_NO_VERBOSE_ERRORS used -#endif -#if defined(DUK_OPT_NO_VOLUNTARY_GC) -#error unsupported legacy feature option DUK_OPT_NO_VOLUNTARY_GC used -#endif -#if defined(DUK_OPT_NO_ZERO_BUFFER_DATA) -#error unsupported legacy feature option DUK_OPT_NO_ZERO_BUFFER_DATA used -#endif -#if defined(DUK_OPT_OBJSIZES16) -#error unsupported legacy feature option DUK_OPT_OBJSIZES16 used -#endif -#if defined(DUK_OPT_PANIC_HANDLER) -#error unsupported legacy feature option DUK_OPT_PANIC_HANDLER used -#endif -#if defined(DUK_OPT_REFCOUNT16) -#error unsupported legacy feature option DUK_OPT_REFCOUNT16 used -#endif -#if defined(DUK_OPT_SEGFAULT_ON_PANIC) -#error unsupported legacy feature option DUK_OPT_SEGFAULT_ON_PANIC used -#endif -#if defined(DUK_OPT_SELF_TESTS) -#error unsupported legacy feature option DUK_OPT_SELF_TESTS used -#endif -#if defined(DUK_OPT_SETJMP) -#error unsupported legacy feature option DUK_OPT_SETJMP used -#endif -#if defined(DUK_OPT_SHUFFLE_TORTURE) -#error unsupported legacy feature option DUK_OPT_SHUFFLE_TORTURE used -#endif -#if defined(DUK_OPT_SIGSETJMP) -#error unsupported legacy feature option DUK_OPT_SIGSETJMP used -#endif -#if defined(DUK_OPT_STRHASH16) -#error unsupported legacy feature option DUK_OPT_STRHASH16 used -#endif -#if defined(DUK_OPT_STRICT_UTF8_SOURCE) -#error unsupported legacy feature option DUK_OPT_STRICT_UTF8_SOURCE used -#endif -#if defined(DUK_OPT_STRLEN16) -#error unsupported legacy feature option DUK_OPT_STRLEN16 used -#endif -#if defined(DUK_OPT_STRTAB_CHAIN) -#error unsupported legacy feature option DUK_OPT_STRTAB_CHAIN used -#endif -#if defined(DUK_OPT_STRTAB_CHAIN_SIZE) -#error unsupported legacy feature option DUK_OPT_STRTAB_CHAIN_SIZE used -#endif -#if defined(DUK_OPT_TARGET_INFO) -#error unsupported legacy feature option DUK_OPT_TARGET_INFO used -#endif -#if defined(DUK_OPT_TRACEBACK_DEPTH) -#error unsupported legacy feature option DUK_OPT_TRACEBACK_DEPTH used -#endif -#if defined(DUK_OPT_UNDERSCORE_SETJMP) -#error unsupported legacy feature option DUK_OPT_UNDERSCORE_SETJMP used -#endif -#if defined(DUK_OPT_USER_INITJS) -#error unsupported legacy feature option DUK_OPT_USER_INITJS used -#endif - -/* - * Checks for config option consistency (DUK_USE_xxx) - */ - -#if defined(DUK_USE_32BIT_PTRS) -#error unsupported config option used (option has been removed): DUK_USE_32BIT_PTRS -#endif -#if defined(DUK_USE_ALIGN_4) -#error unsupported config option used (option has been removed): DUK_USE_ALIGN_4 -#endif -#if defined(DUK_USE_ALIGN_8) -#error unsupported config option used (option has been removed): DUK_USE_ALIGN_8 -#endif -#if defined(DUK_USE_BROWSER_LIKE) -#error unsupported config option used (option has been removed): DUK_USE_BROWSER_LIKE -#endif -#if defined(DUK_USE_BUILTIN_INITJS) -#error unsupported config option used (option has been removed): DUK_USE_BUILTIN_INITJS -#endif -#if defined(DUK_USE_BYTEORDER_FORCED) -#error unsupported config option used (option has been removed): DUK_USE_BYTEORDER_FORCED -#endif -#if defined(DUK_USE_DATAPTR_DEC16) && !defined(DUK_USE_DATAPTR16) -#error config option DUK_USE_DATAPTR_DEC16 requires option DUK_USE_DATAPTR16 (which is missing) -#endif -#if defined(DUK_USE_DATAPTR_ENC16) && !defined(DUK_USE_DATAPTR16) -#error config option DUK_USE_DATAPTR_ENC16 requires option DUK_USE_DATAPTR16 (which is missing) -#endif -#if defined(DUK_USE_DDDPRINT) -#error unsupported config option used (option has been removed): DUK_USE_DDDPRINT -#endif -#if defined(DUK_USE_DDPRINT) -#error unsupported config option used (option has been removed): DUK_USE_DDPRINT -#endif -#if defined(DUK_USE_DEBUGGER_FWD_LOGGING) -#error unsupported config option used (option has been removed): DUK_USE_DEBUGGER_FWD_LOGGING -#endif -#if defined(DUK_USE_DEBUGGER_FWD_PRINTALERT) -#error unsupported config option used (option has been removed): DUK_USE_DEBUGGER_FWD_PRINTALERT -#endif -#if defined(DUK_USE_DEBUGGER_SUPPORT) && !defined(DUK_USE_INTERRUPT_COUNTER) -#error config option DUK_USE_DEBUGGER_SUPPORT requires option DUK_USE_INTERRUPT_COUNTER (which is missing) -#endif -#if defined(DUK_USE_DEEP_C_STACK) -#error unsupported config option used (option has been removed): DUK_USE_DEEP_C_STACK -#endif -#if defined(DUK_USE_DOUBLE_BE) -#error unsupported config option used (option has been removed): DUK_USE_DOUBLE_BE -#endif -#if defined(DUK_USE_DOUBLE_BE) && defined(DUK_USE_DOUBLE_LE) -#error config option DUK_USE_DOUBLE_BE conflicts with option DUK_USE_DOUBLE_LE (which is also defined) -#endif -#if defined(DUK_USE_DOUBLE_BE) && defined(DUK_USE_DOUBLE_ME) -#error config option DUK_USE_DOUBLE_BE conflicts with option DUK_USE_DOUBLE_ME (which is also defined) -#endif -#if defined(DUK_USE_DOUBLE_LE) -#error unsupported config option used (option has been removed): DUK_USE_DOUBLE_LE -#endif -#if defined(DUK_USE_DOUBLE_LE) && defined(DUK_USE_DOUBLE_BE) -#error config option DUK_USE_DOUBLE_LE conflicts with option DUK_USE_DOUBLE_BE (which is also defined) -#endif -#if defined(DUK_USE_DOUBLE_LE) && defined(DUK_USE_DOUBLE_ME) -#error config option DUK_USE_DOUBLE_LE conflicts with option DUK_USE_DOUBLE_ME (which is also defined) -#endif -#if defined(DUK_USE_DOUBLE_ME) -#error unsupported config option used (option has been removed): DUK_USE_DOUBLE_ME -#endif -#if defined(DUK_USE_DOUBLE_ME) && defined(DUK_USE_DOUBLE_LE) -#error config option DUK_USE_DOUBLE_ME conflicts with option DUK_USE_DOUBLE_LE (which is also defined) -#endif -#if defined(DUK_USE_DOUBLE_ME) && defined(DUK_USE_DOUBLE_BE) -#error config option DUK_USE_DOUBLE_ME conflicts with option DUK_USE_DOUBLE_BE (which is also defined) -#endif -#if defined(DUK_USE_DPRINT) -#error unsupported config option used (option has been removed): DUK_USE_DPRINT -#endif -#if defined(DUK_USE_DPRINT) && !defined(DUK_USE_DEBUG) -#error config option DUK_USE_DPRINT requires option DUK_USE_DEBUG (which is missing) -#endif -#if defined(DUK_USE_DPRINT_COLORS) -#error unsupported config option used (option has been removed): DUK_USE_DPRINT_COLORS -#endif -#if defined(DUK_USE_DPRINT_RDTSC) -#error unsupported config option used (option has been removed): DUK_USE_DPRINT_RDTSC -#endif -#if defined(DUK_USE_ES6_REGEXP_BRACES) -#error unsupported config option used (option has been removed): DUK_USE_ES6_REGEXP_BRACES -#endif -#if defined(DUK_USE_ESBC_MAX_BYTES) && !defined(DUK_USE_ESBC_LIMITS) -#error config option DUK_USE_ESBC_MAX_BYTES requires option DUK_USE_ESBC_LIMITS (which is missing) -#endif -#if defined(DUK_USE_ESBC_MAX_LINENUMBER) && !defined(DUK_USE_ESBC_LIMITS) -#error config option DUK_USE_ESBC_MAX_LINENUMBER requires option DUK_USE_ESBC_LIMITS (which is missing) -#endif -#if defined(DUK_USE_EXEC_TIMEOUT_CHECK) && !defined(DUK_USE_INTERRUPT_COUNTER) -#error config option DUK_USE_EXEC_TIMEOUT_CHECK requires option DUK_USE_INTERRUPT_COUNTER (which is missing) -#endif -#if defined(DUK_USE_EXTSTR_FREE) && !defined(DUK_USE_HSTRING_EXTDATA) -#error config option DUK_USE_EXTSTR_FREE requires option DUK_USE_HSTRING_EXTDATA (which is missing) -#endif -#if defined(DUK_USE_EXTSTR_INTERN_CHECK) && !defined(DUK_USE_HSTRING_EXTDATA) -#error config option DUK_USE_EXTSTR_INTERN_CHECK requires option DUK_USE_HSTRING_EXTDATA (which is missing) -#endif -#if defined(DUK_USE_FASTINT) && !defined(DUK_USE_64BIT_OPS) -#error config option DUK_USE_FASTINT requires option DUK_USE_64BIT_OPS (which is missing) -#endif -#if defined(DUK_USE_FILE_IO) -#error unsupported config option used (option has been removed): DUK_USE_FILE_IO -#endif -#if defined(DUK_USE_FULL_TVAL) -#error unsupported config option used (option has been removed): DUK_USE_FULL_TVAL -#endif -#if defined(DUK_USE_FUNCPTR_DEC16) && !defined(DUK_USE_FUNCPTR16) -#error config option DUK_USE_FUNCPTR_DEC16 requires option DUK_USE_FUNCPTR16 (which is missing) -#endif -#if defined(DUK_USE_FUNCPTR_ENC16) && !defined(DUK_USE_FUNCPTR16) -#error config option DUK_USE_FUNCPTR_ENC16 requires option DUK_USE_FUNCPTR16 (which is missing) -#endif -#if defined(DUK_USE_HASHBYTES_UNALIGNED_U32_ACCESS) -#error unsupported config option used (option has been removed): DUK_USE_HASHBYTES_UNALIGNED_U32_ACCESS -#endif -#if defined(DUK_USE_HEAPPTR16) && defined(DUK_USE_DEBUG) -#error config option DUK_USE_HEAPPTR16 conflicts with option DUK_USE_DEBUG (which is also defined) -#endif -#if defined(DUK_USE_HEAPPTR_DEC16) && !defined(DUK_USE_HEAPPTR16) -#error config option DUK_USE_HEAPPTR_DEC16 requires option DUK_USE_HEAPPTR16 (which is missing) -#endif -#if defined(DUK_USE_HEAPPTR_ENC16) && !defined(DUK_USE_HEAPPTR16) -#error config option DUK_USE_HEAPPTR_ENC16 requires option DUK_USE_HEAPPTR16 (which is missing) -#endif -#if defined(DUK_USE_INTEGER_BE) -#error unsupported config option used (option has been removed): DUK_USE_INTEGER_BE -#endif -#if defined(DUK_USE_INTEGER_BE) && defined(DUK_USE_INTEGER_LE) -#error config option DUK_USE_INTEGER_BE conflicts with option DUK_USE_INTEGER_LE (which is also defined) -#endif -#if defined(DUK_USE_INTEGER_BE) && defined(DUK_USE_INTEGER_ME) -#error config option DUK_USE_INTEGER_BE conflicts with option DUK_USE_INTEGER_ME (which is also defined) -#endif -#if defined(DUK_USE_INTEGER_LE) -#error unsupported config option used (option has been removed): DUK_USE_INTEGER_LE -#endif -#if defined(DUK_USE_INTEGER_LE) && defined(DUK_USE_INTEGER_BE) -#error config option DUK_USE_INTEGER_LE conflicts with option DUK_USE_INTEGER_BE (which is also defined) -#endif -#if defined(DUK_USE_INTEGER_LE) && defined(DUK_USE_INTEGER_ME) -#error config option DUK_USE_INTEGER_LE conflicts with option DUK_USE_INTEGER_ME (which is also defined) -#endif -#if defined(DUK_USE_INTEGER_ME) -#error unsupported config option used (option has been removed): DUK_USE_INTEGER_ME -#endif -#if defined(DUK_USE_INTEGER_ME) && defined(DUK_USE_INTEGER_LE) -#error config option DUK_USE_INTEGER_ME conflicts with option DUK_USE_INTEGER_LE (which is also defined) -#endif -#if defined(DUK_USE_INTEGER_ME) && defined(DUK_USE_INTEGER_BE) -#error config option DUK_USE_INTEGER_ME conflicts with option DUK_USE_INTEGER_BE (which is also defined) -#endif -#if defined(DUK_USE_MARKANDSWEEP_FINALIZER_TORTURE) -#error unsupported config option used (option has been removed): DUK_USE_MARKANDSWEEP_FINALIZER_TORTURE -#endif -#if defined(DUK_USE_MARK_AND_SWEEP) -#error unsupported config option used (option has been removed): DUK_USE_MARK_AND_SWEEP -#endif -#if defined(DUK_USE_MATH_FMAX) -#error unsupported config option used (option has been removed): DUK_USE_MATH_FMAX -#endif -#if defined(DUK_USE_MATH_FMIN) -#error unsupported config option used (option has been removed): DUK_USE_MATH_FMIN -#endif -#if defined(DUK_USE_MATH_ROUND) -#error unsupported config option used (option has been removed): DUK_USE_MATH_ROUND -#endif -#if defined(DUK_USE_MS_STRINGTABLE_RESIZE) -#error unsupported config option used (option has been removed): DUK_USE_MS_STRINGTABLE_RESIZE -#endif -#if defined(DUK_USE_NONSTD_REGEXP_DOLLAR_ESCAPE) -#error unsupported config option used (option has been removed): DUK_USE_NONSTD_REGEXP_DOLLAR_ESCAPE -#endif -#if defined(DUK_USE_NO_DOUBLE_ALIASING_SELFTEST) -#error unsupported config option used (option has been removed): DUK_USE_NO_DOUBLE_ALIASING_SELFTEST -#endif -#if defined(DUK_USE_OCTAL_SUPPORT) -#error unsupported config option used (option has been removed): DUK_USE_OCTAL_SUPPORT -#endif -#if defined(DUK_USE_PACKED_TVAL_POSSIBLE) -#error unsupported config option used (option has been removed): DUK_USE_PACKED_TVAL_POSSIBLE -#endif -#if defined(DUK_USE_PANIC_ABORT) -#error unsupported config option used (option has been removed): DUK_USE_PANIC_ABORT -#endif -#if defined(DUK_USE_PANIC_EXIT) -#error unsupported config option used (option has been removed): DUK_USE_PANIC_EXIT -#endif -#if defined(DUK_USE_PANIC_HANDLER) -#error unsupported config option used (option has been removed): DUK_USE_PANIC_HANDLER -#endif -#if defined(DUK_USE_PANIC_SEGFAULT) -#error unsupported config option used (option has been removed): DUK_USE_PANIC_SEGFAULT -#endif -#if defined(DUK_USE_POW_NETBSD_WORKAROUND) -#error unsupported config option used (option has been removed): DUK_USE_POW_NETBSD_WORKAROUND -#endif -#if defined(DUK_USE_RDTSC) -#error unsupported config option used (option has been removed): DUK_USE_RDTSC -#endif -#if defined(DUK_USE_REFZERO_FINALIZER_TORTURE) -#error unsupported config option used (option has been removed): DUK_USE_REFZERO_FINALIZER_TORTURE -#endif -#if defined(DUK_USE_ROM_GLOBAL_CLONE) && !defined(DUK_USE_ROM_STRINGS) -#error config option DUK_USE_ROM_GLOBAL_CLONE requires option DUK_USE_ROM_STRINGS (which is missing) -#endif -#if defined(DUK_USE_ROM_GLOBAL_CLONE) && !defined(DUK_USE_ROM_OBJECTS) -#error config option DUK_USE_ROM_GLOBAL_CLONE requires option DUK_USE_ROM_OBJECTS (which is missing) -#endif -#if defined(DUK_USE_ROM_GLOBAL_CLONE) && defined(DUK_USE_ROM_GLOBAL_INHERIT) -#error config option DUK_USE_ROM_GLOBAL_CLONE conflicts with option DUK_USE_ROM_GLOBAL_INHERIT (which is also defined) -#endif -#if defined(DUK_USE_ROM_GLOBAL_INHERIT) && !defined(DUK_USE_ROM_STRINGS) -#error config option DUK_USE_ROM_GLOBAL_INHERIT requires option DUK_USE_ROM_STRINGS (which is missing) -#endif -#if defined(DUK_USE_ROM_GLOBAL_INHERIT) && !defined(DUK_USE_ROM_OBJECTS) -#error config option DUK_USE_ROM_GLOBAL_INHERIT requires option DUK_USE_ROM_OBJECTS (which is missing) -#endif -#if defined(DUK_USE_ROM_GLOBAL_INHERIT) && defined(DUK_USE_ROM_GLOBAL_CLONE) -#error config option DUK_USE_ROM_GLOBAL_INHERIT conflicts with option DUK_USE_ROM_GLOBAL_CLONE (which is also defined) -#endif -#if defined(DUK_USE_ROM_OBJECTS) && !defined(DUK_USE_ROM_STRINGS) -#error config option DUK_USE_ROM_OBJECTS requires option DUK_USE_ROM_STRINGS (which is missing) -#endif -#if defined(DUK_USE_ROM_STRINGS) && !defined(DUK_USE_ROM_OBJECTS) -#error config option DUK_USE_ROM_STRINGS requires option DUK_USE_ROM_OBJECTS (which is missing) -#endif -#if defined(DUK_USE_SETJMP) -#error unsupported config option used (option has been removed): DUK_USE_SETJMP -#endif -#if defined(DUK_USE_SIGSETJMP) -#error unsupported config option used (option has been removed): DUK_USE_SIGSETJMP -#endif -#if defined(DUK_USE_STRTAB_CHAIN) -#error unsupported config option used (option has been removed): DUK_USE_STRTAB_CHAIN -#endif -#if defined(DUK_USE_STRTAB_CHAIN_SIZE) -#error unsupported config option used (option has been removed): DUK_USE_STRTAB_CHAIN_SIZE -#endif -#if defined(DUK_USE_STRTAB_CHAIN_SIZE) && !defined(DUK_USE_STRTAB_CHAIN) -#error config option DUK_USE_STRTAB_CHAIN_SIZE requires option DUK_USE_STRTAB_CHAIN (which is missing) -#endif -#if defined(DUK_USE_STRTAB_PROBE) -#error unsupported config option used (option has been removed): DUK_USE_STRTAB_PROBE -#endif -#if defined(DUK_USE_STRTAB_PTRCOMP) && !defined(DUK_USE_HEAPPTR16) -#error config option DUK_USE_STRTAB_PTRCOMP requires option DUK_USE_HEAPPTR16 (which is missing) -#endif -#if defined(DUK_USE_TAILCALL) && defined(DUK_USE_NONSTD_FUNC_CALLER_PROPERTY) -#error config option DUK_USE_TAILCALL conflicts with option DUK_USE_NONSTD_FUNC_CALLER_PROPERTY (which is also defined) -#endif -#if defined(DUK_USE_UNALIGNED_ACCESSES_POSSIBLE) -#error unsupported config option used (option has been removed): DUK_USE_UNALIGNED_ACCESSES_POSSIBLE -#endif -#if defined(DUK_USE_UNDERSCORE_SETJMP) -#error unsupported config option used (option has been removed): DUK_USE_UNDERSCORE_SETJMP -#endif -#if defined(DUK_USE_USER_INITJS) -#error unsupported config option used (option has been removed): DUK_USE_USER_INITJS -#endif - -#if defined(DUK_USE_CPP_EXCEPTIONS) && !defined(__cplusplus) -#error DUK_USE_CPP_EXCEPTIONS enabled but not compiling with a C++ compiler -#endif - -/* - * Convert DUK_USE_BYTEORDER, from whatever source, into currently used - * internal defines. If detection failed, #error out. - */ - -#if defined(DUK_USE_BYTEORDER) -#if (DUK_USE_BYTEORDER == 1) -#define DUK_USE_INTEGER_LE -#define DUK_USE_DOUBLE_LE -#elif (DUK_USE_BYTEORDER == 2) -#define DUK_USE_INTEGER_LE /* integer endianness is little on purpose */ -#define DUK_USE_DOUBLE_ME -#elif (DUK_USE_BYTEORDER == 3) -#define DUK_USE_INTEGER_BE -#define DUK_USE_DOUBLE_BE -#else -#error unsupported: byte order invalid -#endif /* byte order */ -#else -#error unsupported: byte order detection failed -#endif /* defined(DUK_USE_BYTEORDER) */ - -#endif /* DUK_CONFIG_H_INCLUDED */ diff --git a/vendor/gopkg.in/olebedev/go-duktape.v3/duk_console.c b/vendor/gopkg.in/olebedev/go-duktape.v3/duk_console.c deleted file mode 100755 index 9a29903c..00000000 --- a/vendor/gopkg.in/olebedev/go-duktape.v3/duk_console.c +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Minimal 'console' binding. - * - * https://github.com/DeveloperToolsWG/console-object/blob/master/api.md - * https://developers.google.com/web/tools/chrome-devtools/debug/console/console-reference - * https://developer.mozilla.org/en/docs/Web/API/console - */ - -#include -#include -#include "duktape.h" -#include "duk_console.h" - -/* XXX: Add some form of log level filtering. */ - -/* XXX: For now logs everything to stdout, V8/Node.js logs debug/info level - * to stdout, warn and above to stderr. Should this extra do the same? - */ - -/* XXX: Should all output be written via e.g. console.write(formattedMsg)? - * This would make it easier for user code to redirect all console output - * to a custom backend. - */ - -/* XXX: Init console object using duk_def_prop() when that call is available. */ - -static duk_ret_t duk__console_log_helper(duk_context *ctx, const char *error_name) { - duk_idx_t i, n; - duk_uint_t flags; - - flags = (duk_uint_t) duk_get_current_magic(ctx); - - n = duk_get_top(ctx); - - duk_get_global_string(ctx, "console"); - duk_get_prop_string(ctx, -1, "format"); - - for (i = 0; i < n; i++) { - if (duk_check_type_mask(ctx, i, DUK_TYPE_MASK_OBJECT)) { - /* Slow path formatting. */ - duk_dup(ctx, -1); /* console.format */ - duk_dup(ctx, i); - duk_call(ctx, 1); - duk_replace(ctx, i); /* arg[i] = console.format(arg[i]); */ - } - } - - duk_pop_2(ctx); - - duk_push_string(ctx, " "); - duk_insert(ctx, 0); - duk_join(ctx, n); - - if (error_name) { - duk_push_error_object(ctx, DUK_ERR_ERROR, "%s", duk_require_string(ctx, -1)); - duk_push_string(ctx, "name"); - duk_push_string(ctx, error_name); - duk_def_prop(ctx, -3, DUK_DEFPROP_FORCE | DUK_DEFPROP_HAVE_VALUE); /* to get e.g. 'Trace: 1 2 3' */ - duk_get_prop_string(ctx, -1, "stack"); - } - - fprintf(stdout, "%s\n", duk_to_string(ctx, -1)); - if (flags & DUK_CONSOLE_FLUSH) { - fflush(stdout); - } - return 0; -} - -static duk_ret_t duk__console_assert(duk_context *ctx) { - if (duk_to_boolean(ctx, 0)) { - return 0; - } - duk_remove(ctx, 0); - - return duk__console_log_helper(ctx, "AssertionError"); -} - -static duk_ret_t duk__console_log(duk_context *ctx) { - return duk__console_log_helper(ctx, NULL); -} - -static duk_ret_t duk__console_trace(duk_context *ctx) { - return duk__console_log_helper(ctx, "Trace"); -} - -static duk_ret_t duk__console_info(duk_context *ctx) { - return duk__console_log_helper(ctx, NULL); -} - -static duk_ret_t duk__console_warn(duk_context *ctx) { - return duk__console_log_helper(ctx, NULL); -} - -static duk_ret_t duk__console_error(duk_context *ctx) { - return duk__console_log_helper(ctx, "Error"); -} - -static duk_ret_t duk__console_dir(duk_context *ctx) { - /* For now, just share the formatting of .log() */ - return duk__console_log_helper(ctx, 0); -} - -static void duk__console_reg_vararg_func(duk_context *ctx, duk_c_function func, const char *name, duk_uint_t flags) { - duk_push_c_function(ctx, func, DUK_VARARGS); - duk_push_string(ctx, "name"); - duk_push_string(ctx, name); - duk_def_prop(ctx, -3, DUK_DEFPROP_HAVE_VALUE | DUK_DEFPROP_FORCE); /* Improve stacktraces by displaying function name */ - duk_set_magic(ctx, -1, (duk_int_t) flags); - duk_put_prop_string(ctx, -2, name); -} - -void duk_console_init(duk_context *ctx, duk_uint_t flags) { - duk_push_object(ctx); - - /* Custom function to format objects; user can replace. - * For now, try JX-formatting and if that fails, fall back - * to ToString(v). - */ - duk_eval_string(ctx, - "(function (E) {" - "return function format(v){" - "try{" - "return E('jx',v);" - "}catch(e){" - "return String(v);" /* String() allows symbols, ToString() internal algorithm doesn't. */ - "}" - "};" - "})(Duktape.enc)"); - duk_put_prop_string(ctx, -2, "format"); - - duk__console_reg_vararg_func(ctx, duk__console_assert, "assert", flags); - duk__console_reg_vararg_func(ctx, duk__console_log, "log", flags); - duk__console_reg_vararg_func(ctx, duk__console_log, "debug", flags); /* alias to console.log */ - duk__console_reg_vararg_func(ctx, duk__console_trace, "trace", flags); - duk__console_reg_vararg_func(ctx, duk__console_info, "info", flags); - duk__console_reg_vararg_func(ctx, duk__console_warn, "warn", flags); - duk__console_reg_vararg_func(ctx, duk__console_error, "error", flags); - duk__console_reg_vararg_func(ctx, duk__console_error, "exception", flags); /* alias to console.error */ - duk__console_reg_vararg_func(ctx, duk__console_dir, "dir", flags); - - duk_put_global_string(ctx, "console"); - - /* Proxy wrapping: ensures any undefined console method calls are - * ignored silently. This is required specifically by the - * DeveloperToolsWG proposal (and is implemented also by Firefox: - * https://bugzilla.mozilla.org/show_bug.cgi?id=629607). - */ - - if (flags & DUK_CONSOLE_PROXY_WRAPPER) { - /* Tolerate errors: Proxy may be disabled. */ - duk_peval_string_noresult(ctx, - "(function(){" - "var D=function(){};" - "console=new Proxy(console,{" - "get:function(t,k){" - "var v=t[k];" - "return typeof v==='function'?v:D;" - "}" - "});" - "})();" - ); - } -} diff --git a/vendor/gopkg.in/olebedev/go-duktape.v3/duk_console.h b/vendor/gopkg.in/olebedev/go-duktape.v3/duk_console.h deleted file mode 100755 index 1488a95f..00000000 --- a/vendor/gopkg.in/olebedev/go-duktape.v3/duk_console.h +++ /dev/null @@ -1,14 +0,0 @@ -#if !defined(DUK_CONSOLE_H_INCLUDED) -#define DUK_CONSOLE_H_INCLUDED - -#include "duktape.h" - -/* Use a proxy wrapper to make undefined methods (console.foo()) no-ops. */ -#define DUK_CONSOLE_PROXY_WRAPPER (1 << 0) - -/* Flush output after every call. */ -#define DUK_CONSOLE_FLUSH (1 << 1) - -extern void duk_console_init(duk_context *ctx, duk_uint_t flags); - -#endif /* DUK_CONSOLE_H_INCLUDED */ diff --git a/vendor/gopkg.in/olebedev/go-duktape.v3/duk_logging.c b/vendor/gopkg.in/olebedev/go-duktape.v3/duk_logging.c deleted file mode 100755 index 9be2c1c2..00000000 --- a/vendor/gopkg.in/olebedev/go-duktape.v3/duk_logging.c +++ /dev/null @@ -1,380 +0,0 @@ -/* - * Logging support - */ - -#include -#include -#include -#include "duktape.h" -#include "duk_logging.h" - -/* XXX: uses stderr always for now, configurable? */ - -#define DUK_LOGGING_FLUSH /* Duktape 1.x: flush stderr */ - -/* 3-letter log level strings. */ -static const char duk__log_level_strings[] = { - 'T', 'R', 'C', 'D', 'B', 'G', 'I', 'N', 'F', - 'W', 'R', 'N', 'E', 'R', 'R', 'F', 'T', 'L' -}; - -/* Log method names. */ -static const char *duk__log_method_names[] = { - "trace", "debug", "info", "warn", "error", "fatal" -}; - -/* Constructor. */ -static duk_ret_t duk__logger_constructor(duk_context *ctx) { - duk_idx_t nargs; - - /* Calling as a non-constructor is not meaningful. */ - if (!duk_is_constructor_call(ctx)) { - return DUK_RET_TYPE_ERROR; - } - - nargs = duk_get_top(ctx); - duk_set_top(ctx, 1); - - duk_push_this(ctx); - - /* [ name this ] */ - - if (nargs == 0) { - /* Automatic defaulting of logger name from caller. This - * would work poorly with tail calls, but constructor calls - * are currently never tail calls, so tail calls are not an - * issue now. - */ - - duk_inspect_callstack_entry(ctx, -2); - if (duk_is_object(ctx, -1)) { - if (duk_get_prop_string(ctx, -1, "function")) { - if (duk_get_prop_string(ctx, -1, "fileName")) { - if (duk_is_string(ctx, -1)) { - duk_replace(ctx, 0); - } - } - } - } - /* Leave values on stack on purpose, ignored below. */ - - /* Stripping the filename might be a good idea - * ("/foo/bar/quux.js" -> logger name "quux"), - * but now used verbatim. - */ - } - /* The stack is unbalanced here on purpose; we only rely on the - * initial two values: [ name this ]. - */ - - if (duk_is_string(ctx, 0)) { - duk_dup(ctx, 0); - duk_put_prop_string(ctx, 1, "n"); - } else { - /* don't set 'n' at all, inherited value is used as name */ - } - - duk_compact(ctx, 1); - - return 0; /* keep default instance */ -} - -/* Default function to format objects. Tries to use toLogString() but falls - * back to toString(). Any errors are propagated out without catching. - */ -static duk_ret_t duk__logger_prototype_fmt(duk_context *ctx) { - if (duk_get_prop_string(ctx, 0, "toLogString")) { - /* [ arg toLogString ] */ - - duk_dup(ctx, 0); - duk_call_method(ctx, 0); - - /* [ arg result ] */ - return 1; - } - - /* [ arg undefined ] */ - duk_pop(ctx); - duk_to_string(ctx, 0); - return 1; -} - -/* Default function to write a formatted log line. Writes to stderr, - * appending a newline to the log line. - * - * The argument is a buffer; avoid coercing the buffer to a string to - * avoid string table traffic. - */ -static duk_ret_t duk__logger_prototype_raw(duk_context *ctx) { - const char *data; - duk_size_t data_len; - - data = (const char *) duk_require_buffer(ctx, 0, &data_len); - fwrite((const void *) data, 1, data_len, stderr); - fputc((int) '\n', stderr); -#if defined(DUK_LOGGING_FLUSH) - fflush(stderr); -#endif - return 0; -} - -/* Log frontend shared helper, magic value indicates log level. Provides - * frontend functions: trace(), debug(), info(), warn(), error(), fatal(). - * This needs to have small footprint, reasonable performance, minimal - * memory churn, etc. - */ -static duk_ret_t duk__logger_prototype_log_shared(duk_context *ctx) { - duk_double_t now; - duk_time_components comp; - duk_small_int_t entry_lev; - duk_small_int_t logger_lev; - duk_int_t nargs; - duk_int_t i; - duk_size_t tot_len; - const duk_uint8_t *arg_str; - duk_size_t arg_len; - duk_uint8_t *buf, *p; - const duk_uint8_t *q; - duk_uint8_t date_buf[32]; /* maximum format length is 24+1 (NUL), round up. */ - duk_size_t date_len; - duk_small_int_t rc; - - /* XXX: sanitize to printable (and maybe ASCII) */ - /* XXX: better multiline */ - - /* - * Logger arguments are: - * - * magic: log level (0-5) - * this: logger - * stack: plain log args - * - * We want to minimize memory churn so a two-pass approach - * is used: first pass formats arguments and computes final - * string length, second pass copies strings into a buffer - * allocated directly with the correct size. If the backend - * function plays nice, it won't coerce the buffer to a string - * (and thus intern it). - */ - - entry_lev = duk_get_current_magic(ctx); - if (entry_lev < DUK_LOG_TRACE || entry_lev > DUK_LOG_FATAL) { - /* Should never happen, check just in case. */ - return 0; - } - nargs = duk_get_top(ctx); - - /* [ arg1 ... argN this ] */ - - /* - * Log level check - */ - - duk_push_this(ctx); - - duk_get_prop_string(ctx, -1, "l"); - logger_lev = (duk_small_int_t) duk_get_int(ctx, -1); - if (entry_lev < logger_lev) { - return 0; - } - /* log level could be popped but that's not necessary */ - - now = duk_get_now(ctx); - duk_time_to_components(ctx, now, &comp); - sprintf((char *) date_buf, "%04d-%02d-%02dT%02d:%02d:%02d.%03dZ", - (int) comp.year, (int) comp.month + 1, (int) comp.day, - (int) comp.hours, (int) comp.minutes, (int) comp.seconds, - (int) comp.milliseconds); - - date_len = strlen((const char *) date_buf); - - duk_get_prop_string(ctx, -2, "n"); - duk_to_string(ctx, -1); - - /* [ arg1 ... argN this loggerLevel loggerName ] */ - - /* - * Pass 1 - */ - - /* Line format: