├── Sources ├── CLibUSB │ ├── CLibUSBUmbrella.h │ └── module.modulemap ├── SimpleUSB │ ├── USBError.swift │ ├── SimpleUSBBus.swift │ ├── BMRequest.swift │ ├── SimpleUSBDevice.swift │ ├── PlatformEndpointAddress.swift │ └── DeviceCommon.swift ├── PortableUSB │ └── PortableUSB.swift ├── HostFWUSB │ ├── HostFWUSBBus.swift │ └── HostFWUSBDevice.swift └── LibUSB │ ├── USBBus.swift │ └── USBDevice.swift ├── .gitignore ├── Tests ├── LinuxMain.swift └── ftdi-synchronous-serialTests │ ├── libusb_swiftTests.swift │ └── XCTestManifests.swift ├── README.md ├── Package.swift └── LICENSE.txt /Sources/CLibUSB/CLibUSBUmbrella.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | /.build 3 | /Packages 4 | /*.xcodeproj 5 | xcuserdata/ 6 | -------------------------------------------------------------------------------- /Sources/CLibUSB/module.modulemap: -------------------------------------------------------------------------------- 1 | module CLibUSB [system] { 2 | header "CLibUSBUmbrella.h" 3 | export * 4 | } 5 | -------------------------------------------------------------------------------- /Tests/LinuxMain.swift: -------------------------------------------------------------------------------- 1 | import XCTest 2 | 3 | import ftdi_synchronous_serialTests 4 | 5 | var tests = [XCTestCaseEntry]() 6 | tests += ftdi_synchronous_serialTests.__allTests() 7 | 8 | XCTMain(tests) 9 | -------------------------------------------------------------------------------- /Sources/SimpleUSB/USBError.swift: -------------------------------------------------------------------------------- 1 | // 2 | // USBError.swift 3 | // deft-simple-usb 4 | // 5 | // Created by Kit Transue on 2021-04-28. 6 | // Copyright © 2021 Kit Transue 7 | // SPDX-License-Identifier: Apache-2.0 8 | // 9 | 10 | import Foundation 11 | 12 | public enum USBError: Error { 13 | case bindingDeviceHandle(String) 14 | case getConfiguration(String) 15 | case claimInterface(String) 16 | } 17 | -------------------------------------------------------------------------------- /Tests/ftdi-synchronous-serialTests/libusb_swiftTests.swift: -------------------------------------------------------------------------------- 1 | import XCTest 2 | @testable import LibUSB 3 | 4 | final class libusb_swiftTests: XCTestCase { 5 | func testExample() { 6 | // This is an example of a functional test case. 7 | // Use XCTAssert and related functions to verify your tests produce the correct 8 | // results. 9 | // XCTAssertEqual(libusb_swift().text, "Hello, World!") 10 | } 11 | 12 | static var allTests = [ 13 | ("testExample", testExample), 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /Tests/ftdi-synchronous-serialTests/XCTestManifests.swift: -------------------------------------------------------------------------------- 1 | #if !canImport(ObjectiveC) 2 | import XCTest 3 | 4 | extension libusb_swiftTests { 5 | // DO NOT MODIFY: This is autogenerated, use: 6 | // `swift test --generate-linuxmain` 7 | // to regenerate. 8 | static let __allTests__libusb_swiftTests = [ 9 | ("testExample", testExample), 10 | ] 11 | } 12 | 13 | public func __allTests() -> [XCTestCaseEntry] { 14 | return [ 15 | testCase(libusb_swiftTests.__allTests__libusb_swiftTests), 16 | ] 17 | } 18 | #endif 19 | -------------------------------------------------------------------------------- /Sources/SimpleUSB/SimpleUSBBus.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SimpleUSBBus.swift 3 | // deft-simple-usb 4 | // 5 | // Created by Kit Transue on 2021-04-28. 6 | // Copyright © 2021 Kit Transue 7 | // SPDX-License-Identifier: Apache-2.0 8 | // 9 | 10 | /// Usermode USB services for finding (and subsequently accessing) USB-attached devices. 11 | public protocol USBBus { 12 | /// - parameter idVendor: filter found devices by vendor, if not-nil. 13 | /// - parameter idProduct: filter found devices by product, if not-nil. Requires idVendor. 14 | /// - returns: the one device that matches the search criteria 15 | /// - throws: if device is not found or criteria are not unique 16 | func findDevice(idVendor: Int?, idProduct: Int?) throws -> USBDevice 17 | } 18 | -------------------------------------------------------------------------------- /Sources/SimpleUSB/BMRequest.swift: -------------------------------------------------------------------------------- 1 | // 2 | // BMRequest.swift 3 | // deft-simple-usb 4 | // 5 | // Created by Kit Transue on 2021-04-28. 6 | // Copyright © 2021 Kit Transue 7 | // SPDX-License-Identifier: Apache-2.0 8 | // 9 | 10 | // USB spec 2.0, sec 9.3: USB Device Requests 11 | // USB spec 2.0, sec 9.3.1: bmRequestType 12 | public typealias BMRequestType = UInt8 13 | public enum ControlDirection: BMRequestType { 14 | case hostToDevice = 0b0000_0000 15 | case deviceToHost = 0b1000_0000 16 | } 17 | public enum ControlRequestType: BMRequestType { 18 | case standard = 0b00_00000 19 | case `class` = 0b01_00000 20 | case vendor = 0b10_00000 21 | case reserved = 0b11_00000 22 | } 23 | public enum ControlRequestRecipient: BMRequestType { 24 | case device = 0 25 | case interface = 1 26 | case endpoint = 2 27 | case other = 3 28 | } 29 | -------------------------------------------------------------------------------- /Sources/SimpleUSB/SimpleUSBDevice.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SimpleUSBDevice.swift 3 | // deft-simple-usb 4 | // 5 | // Created by Kit Transue on 2021-04-28. 6 | // Copyright © 2021 Kit Transue 7 | // SPDX-License-Identifier: Apache-2.0 8 | // 9 | 10 | import Foundation 11 | 12 | /// Protocol for communicating with a USB-attached device. 13 | public protocol USBDevice { 14 | /// Send a control transfer packet to the device (endpoint zero). 15 | func controlTransferOut(bRequest: UInt8, value: UInt16, wIndex: UInt16, data: Data?) 16 | 17 | /// Send data on the write endpoint. 18 | func bulkTransferOut(msg: Data) 19 | 20 | /// Fetch all data availble on the read endpoint. 21 | func bulkTransferIn() -> Data 22 | 23 | /// Timeout to use on bulk/conttrol transfer operations 24 | var timeout: TimeInterval {get set} 25 | 26 | /// Format a bmRequestType byte. 27 | /// - Note: similar to IOUSBHostPipe.IOUSBHostDeviceRequestType 28 | func controlRequest(type: ControlRequestType, direction: ControlDirection, recipient: ControlRequestRecipient) -> BMRequestType 29 | } 30 | -------------------------------------------------------------------------------- /Sources/SimpleUSB/PlatformEndpointAddress.swift: -------------------------------------------------------------------------------- 1 | // 2 | // PlatformEndpointAddress.swift 3 | // deft-simple-usb 4 | // 5 | // Created by Kit Transue on 2021-04-28. 6 | // Copyright © 2021 Kit Transue 7 | // SPDX-License-Identifier: Apache-2.0 8 | // 9 | 10 | import Foundation 11 | 12 | public struct PlatformEndpointAddress { 13 | enum EndpointDirection: RawValue { 14 | // Table 9-13. Standard Endpoint Descriptor 15 | case input = 0b1000_0000 16 | case output = 0 17 | } 18 | 19 | public let rawValue: RawValue 20 | 21 | public init(rawValue: RawValue) { 22 | self.rawValue = rawValue 23 | } 24 | 25 | // USB 2.0: 9.6.6 Endpoint: 26 | // Bit 7 is direction IN/OUT 27 | let directionMask = RawValue(EndpointDirection.input.rawValue | EndpointDirection.output.rawValue) 28 | 29 | /// Check the endpoint descriptor direction bit (bit 7) for "in" or "out." 30 | public var isWritable: Bool { 31 | get { 32 | return rawValue & directionMask == EndpointDirection.output.rawValue 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Sources/SimpleUSB/DeviceCommon.swift: -------------------------------------------------------------------------------- 1 | // 2 | // DeviceCommon.swift 3 | // deft-simple-usb 4 | // 5 | // Created by Kit Transue on 2021-04-28. 6 | // Copyright © 2021 Kit Transue 7 | // SPDX-License-Identifier: Apache-2.0 8 | // 9 | 10 | import Foundation 11 | 12 | 13 | 14 | extension USBDevice { 15 | public func controlRequest(type: ControlRequestType, direction: ControlDirection, recipient: ControlRequestRecipient) -> BMRequestType { 16 | return type.rawValue | direction.rawValue | recipient.rawValue 17 | } 18 | } 19 | 20 | public protocol DeviceCommon: USBDevice { 21 | /// Synchronously send USB control transfer. 22 | /// - returns: number of bytes transferred (if success) 23 | func controlTransfer(requestType: BMRequestType, bRequest: UInt8, wValue: UInt16, wIndex: UInt16, data: Data?, wLength: UInt16) -> Int32 24 | } 25 | 26 | extension DeviceCommon { 27 | public func controlTransferOut(bRequest: UInt8, value: UInt16, wIndex: UInt16, data: Data?) { 28 | let requestType = controlRequest(type: .vendor, direction: .hostToDevice, recipient: .device) 29 | let requestSize = data?.count ?? 0 30 | 31 | let result = controlTransfer(requestType: requestType, 32 | bRequest: bRequest, 33 | wValue: value, wIndex: wIndex, 34 | data: data, 35 | wLength: UInt16(requestSize)) 36 | 37 | guard result == requestSize else { 38 | // FIXME: should probably throw rather than abort, and maybe not all calls need to be this strict 39 | fatalError("controlTransferOut failed: transferred \(result) bytes of \(requestSize)") 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Sources/PortableUSB/PortableUSB.swift: -------------------------------------------------------------------------------- 1 | // 2 | // PortableUSB.swift 3 | // deft-simple-usb 4 | // 5 | // Created by Kit Transue on 2021-04-29. 6 | // Copyright © 2021 Kit Transue 7 | // SPDX-License-Identifier: Apache-2.0 8 | // 9 | 10 | 11 | import SimpleUSB 12 | 13 | // Note: Linking of library modules is controlled by the dependencies defined in 14 | // Package.swift, but modules that are in this pacakge **that are not part of 15 | // the dependency tree** still pass the canImport test. (And can be imported but 16 | // will cause linkage failures.) [SR-1393](https://bugs.swift.org/browse/SR-1393). 17 | // 18 | // The ideal implementation would be to use the package file to add dependencies 19 | // for the implementation the user desires, and then use canImport to decide 20 | // which of those to use in this file. 21 | // 22 | // Since we can't do that, we some big Don't-Repeat-Yourself violations here: 23 | // - the dependency logic in the package file needs to be duplicated as 24 | // conditional #if logic in the imports/implementation in this file 25 | // - we use operating system as a poor proxy for the desired implementation 26 | // 27 | // (LibUSB can be used on macOS; the open-source runtime might someday 28 | // accommodate the IOUSBHost framework; other implemenations are possible) 29 | 30 | 31 | #if USE_LIBUSB 32 | import LibUSB 33 | #endif 34 | 35 | #if USE_FWUSB 36 | import HostFWUSB 37 | #endif 38 | 39 | /// Provide a platform-independent abstraction of the usermode USB subsystem 40 | public class PortableUSB { 41 | /// Obtain a USBBus approriate for this platform. 42 | public static func platformBus() -> USBBus { 43 | #if USE_LIBUSB 44 | return LUUSBBus() 45 | #endif 46 | 47 | #if USE_FWUSB 48 | return FWUSBBus() 49 | #endif 50 | } 51 | } 52 | 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /Sources/HostFWUSB/HostFWUSBBus.swift: -------------------------------------------------------------------------------- 1 | // 2 | // HostFWUSBBus.swift 3 | // deft-simple-usb 4 | // 5 | // Created by Kit Transue on 2021-04-28. 6 | // Copyright © 2021 Kit Transue 7 | // SPDX-License-Identifier: Apache-2.0 8 | // 9 | 10 | #if SKIPMODULE // See Package.swift discussion 11 | #else 12 | import Foundation 13 | import IOUSBHost 14 | import DeftLog 15 | import SimpleUSB 16 | 17 | let logger = DeftLog.logger(label: "com.didactek.deft-simple-usb.host-fw-usb") 18 | // FIXME: how to default configuration to debug? 19 | 20 | 21 | /// Bridge to the macOS IOUSBHost usermode USB framework. 22 | /// Provide services to find devices attached to the bus. 23 | public class FWUSBBus: USBBus { 24 | enum UsbError: Error { 25 | case noDeviceMatched 26 | case deviceCriteriaNotUnique 27 | } 28 | 29 | public init() { 30 | } 31 | 32 | deinit { 33 | } 34 | 35 | /// - parameter idVendor: filter found devices by vendor, if not-nil. 36 | /// - parameter idProduct: filter found devices by product, if not-nil. Requires idVendor. 37 | /// - returns: the one device that matches the search criteria 38 | /// - throws: if device is not found or criteria are not unique 39 | public func findDevice(idVendor: Int?, idProduct: Int?) throws -> USBDevice { 40 | // scan for devices: 41 | // create a matching dictionary: 42 | 43 | // FIXME: the documentation suggests there is a IOUSBHostDevice.createMatchingDictionary 44 | // helper, but I can't find the refined-for-Swift version. 45 | let deviceSearchPattern: [IOUSBHostMatchingPropertyKey : Int] = [ 46 | .vendorID : idVendor!, 47 | .productID : idProduct!, 48 | ] 49 | let deviceDomain = [ "IOProviderClass": "IOUSBHostDevice" ] 50 | let searchRequest = (deviceSearchPattern as NSDictionary).mutableCopy() as! NSMutableDictionary 51 | searchRequest.addEntries(from: deviceDomain) 52 | 53 | #if true // FIXME: use iterator approach; throw if not unique 54 | let service = IOServiceGetMatchingService(kIOMasterPortDefault, searchRequest) 55 | guard service != 0 else { 56 | throw UsbError.noDeviceMatched 57 | } 58 | #else // iterator approach 59 | var existing: io_iterator_t = 0 60 | let _ = IOServiceGetMatchingServices(kIOMasterPortDefault, cfDeviceSearchPattern, &existing) 61 | let service = existing 62 | #endif 63 | 64 | let device = try IOUSBHostDevice.init(__ioService: service, options: [/*.deviceCapture*/], queue: nil, interestHandler: nil) 65 | 66 | return try FWUSBDevice(device: device) 67 | } 68 | } 69 | #endif 70 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Deft Simple USB 2 | 3 | Usermode support for writing custom USB device drivers in Swift on macOS and Linux. 4 | 5 | ## API 6 | 7 | ### Usage 8 | 9 | Deft Simple USB provides a synchronous API. 10 | 11 | Supports 12 | - Find device by vendor and product ID 13 | - Bulk transfer in/out to device 14 | - Control transfer requests to device 15 | 16 | ### Logging 17 | 18 | Loggers are instantiated using the [deft-log](https://github.com/didactek/deft-log.git) library 19 | using the label prefix `com.didactek.deft-simple-usb`. 20 | 21 | ## Requirements 22 | 23 | - Swift Package Manager 24 | - Swift 5.3+ 25 | - macOS or Linux 26 | 27 | Mac requirements 28 | - Xcode 12+ 29 | 30 | SPM Dependencies 31 | - deft-log (transitively: swift-log) 32 | 33 | macOS C library dependencies 34 | - (libusb is optional) 35 | 36 | Linux C library dependencies 37 | - libusb 38 | 39 | ### Support for older environments 40 | 41 | Older environments are relatively easily supported by replacing the .target(name:condition:(.when)) 42 | dependencies in the Package.swift with appropriate hardcoded descriptions. The code was 43 | largely developed with Swift 5.2. The IOUSBHost framework appeared in macOS 10.15 (Catalina), 44 | and the libusb library should be available on most platforms. 45 | 46 | 47 | ## Platform Notes 48 | 49 | ### macOS 50 | 51 | #### IOUSBHost implementation 52 | 53 | The default provider of the USBBus protocol on macOS is the HostFWUSB module, which is 54 | built on the IOUSBHost usermode framework. PortableUSB.platformBus() will vend one of these, 55 | one can be instantiated directly. 56 | 57 | There are no external dependencies, certifications, or special permissions required to build 58 | and use this implementation. 59 | 60 | #### libusb.info implementation 61 | 62 | The LibUSB module (and its bridge module CLibUSB) that provides services on Linux will 63 | also work on macOS. 64 | 65 | The Swift Package Manager will install libraries according to the Package.swift manifest. On 66 | macOS, this requires two additional tools be installed: 67 | 68 | - brew (for SPM to fetch and install libraries) 69 | - pkg-config (available from brew, for SPM to locate, validate, and link with installed libraries) 70 | 71 | A quick homebrew test should show 72 | 73 | % pkg-config --libs libusb-1.0 74 | -L/usr/local/Cellar/libusb/1.0.23/lib -lusb-1.0 75 | 76 | If brew is installed with a nonstandard prefix (e.g., somewhere under a user's home directory), 77 | you may need a symlink for pkg-config so it can be found by Xcode. (Notably, Xcode will search 78 | /usr/local/bin.) 79 | 80 | 81 | 82 | ### Linux device permissions 83 | 84 | On Linux, users will not have access to a hot-plugged USB device by default. 85 | The cleanest way to systematically grant permissions to the device is to set up a udev 86 | rule that adjusts permissions whenever the device is connected. 87 | 88 | The paths and group in the template below assume: 89 | - Configuration files are under /etc/udev/rules.d 90 | - The group 'plugdev' exists and includes the user wanting to use the device 91 | 92 | Under /etc/udev/rules.d/, create a file (suggested name: "70-gpio-ftdi-ft232h.rules") with the contents: 93 | 94 | # FTDI FT232H USB -> GPIO + serial adapter 95 | # 2020-09-07 support working with the FT232H using Swift ftdi-synchronous-serial library 96 | ACTION=="add", SUBSYSTEM=="usb", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6014", MODE="660", GROUP="plugdev" 97 | 98 | eLinux.org has a useful wiki entry on [accessing devices without sudo](https://elinux.org/Accessing_Devices_without_Sudo). 99 | 100 | 101 | ## History 102 | 103 | Extracted from the ftdi-synchronous-serial project. 104 | 105 | To overlay the full history of these files: 106 | 107 | - Clone this project 108 | - Add the ftdi project as a remote: 109 | - git remote add ftdi https://github.com/didactek/ftdi-synchronous-serial.git 110 | - git fetch ftdi SIMPLE-USB-FORKPOINT tag 111 | - Mark the replace point (tags for this are included in each repo) 112 | - git replace SIMPLE-USB-PREHISTORY SIMPLE-USB-FORKPOINT 113 | -------------------------------------------------------------------------------- /Sources/LibUSB/USBBus.swift: -------------------------------------------------------------------------------- 1 | // 2 | // USBBus.swift 3 | // deft-simple-usb 4 | // 5 | // Created by Kit Transue on 2020-08-11. 6 | // Copyright © 2020 Kit Transue 7 | // SPDX-License-Identifier: Apache-2.0 8 | // 9 | 10 | #if SKIPMODULE // See Package.swift discussion 11 | #else 12 | import Foundation 13 | import SimpleUSB 14 | import DeftLog 15 | import CLibUSB 16 | 17 | let logger = DeftLog.logger(label: "com.didactek.deft-simple-usb.libusb") 18 | 19 | /// Bridge to the C library [libusb](https://libusb.info) functions imported by CLibUSB. 20 | /// Configure the subsystem and provide services to find devices attached to the bus. 21 | public class LUUSBBus: USBBus { 22 | // FIXME: common: factor 23 | enum UsbError: Error { 24 | case noDeviceMatched 25 | case deviceCriteriaNotUnique 26 | } 27 | 28 | static func checkCall(_ rawResult: Int32, onError: (String) throws -> Never) { 29 | let result = libusb_error(rawValue: rawResult) 30 | guard result == LIBUSB_SUCCESS else { 31 | let msg = String(cString: libusb_strerror(result)) 32 | try! onError(msg) 33 | } 34 | } 35 | 36 | /// Shared libusb context, for use in libusb_init, etc. 37 | var ctx: OpaquePointer? = nil 38 | 39 | public init() { 40 | // FIXME: how to do this better, and where? 41 | logger.logLevel = .debug 42 | 43 | Self.checkCall(libusb_init(&ctx)) { msg in // deinit: libusb_exit 44 | fatalError("libusb_init failed: \(msg)") 45 | } 46 | } 47 | 48 | deinit { 49 | libusb_exit(ctx) 50 | } 51 | 52 | 53 | // Documented in protocol 54 | public func findDevice(idVendor: Int?, idProduct: Int?) throws -> USBDevice { 55 | // scan for devices: 56 | var devicesBuffer: UnsafeMutablePointer? = nil 57 | let deviceCount = libusb_get_device_list(ctx, &devicesBuffer) 58 | defer { 59 | libusb_free_device_list(devicesBuffer, 1) 60 | } 61 | guard deviceCount > 0 else { 62 | throw UsbError.noDeviceMatched 63 | } 64 | logger.trace("findDevice found \(deviceCount) devices") 65 | 66 | var details = (0 ..< deviceCount).map { deviceDetail(device: devicesBuffer![$0]!) } 67 | 68 | // try to select one device from spec 69 | if let idVendor = idVendor { 70 | details.removeAll { $0.idVendor != idVendor } 71 | } 72 | if let idProduct = idProduct { 73 | guard idVendor != nil else { 74 | fatalError("idVendor required if specifying idProduct") 75 | } 76 | details.removeAll { $0.idProduct != idProduct } 77 | } 78 | if details.isEmpty { 79 | throw UsbError.noDeviceMatched 80 | } 81 | if details.count > 1 { 82 | throw UsbError.deviceCriteriaNotUnique 83 | } 84 | return try LUUSBDevice(subsystem: self, device: details.first!.device) 85 | } 86 | 87 | 88 | /// Information obtainable from the device descriptor without opening a connection to the device. 89 | /// 90 | /// See [USB 2.0](https://www.usb.org/document-library/usb-20-specification) 9.6.1, Device 91 | struct DeviceDescription { 92 | /// libusb handle to the device 93 | let device: OpaquePointer 94 | /// USB idVendor of the device 95 | let idVendor: Int 96 | /// USB idProduct of the device 97 | let idProduct: Int 98 | /// number of configurations 99 | let bNumConfigurations: Int 100 | 101 | } 102 | 103 | /// Read the device descriptor. 104 | /// 105 | /// - Parameter device: Handle from libusb_get_device_list. 106 | /// - Note: Wraps libusb_get_device_descriptor. 107 | func deviceDetail(device: OpaquePointer) -> DeviceDescription { 108 | var descriptor = libusb_device_descriptor() 109 | let _ = libusb_get_device_descriptor(device, &descriptor) 110 | logger.trace("vendor: \(String(descriptor.idVendor, radix: 16))") 111 | logger.trace("product: \(String(descriptor.idProduct, radix: 16))") 112 | logger.trace("device has \(descriptor.bNumConfigurations) configurations") 113 | 114 | return DeviceDescription( 115 | device: device, 116 | idVendor: Int(descriptor.idVendor), 117 | idProduct: Int(descriptor.idProduct), 118 | bNumConfigurations: Int(descriptor.bNumConfigurations)) 119 | } 120 | } 121 | #endif 122 | -------------------------------------------------------------------------------- /Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version:5.3 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | // Tools version 5.3 is required for the "condition: .when(platforms:)" syntax 5 | // in dependencies. The library will build with older versions if the dependencies 6 | // are hardcoded. 7 | 8 | // NOTE: work is needed to avoid warnings/errors in LibUSB/HostFWUSB on the 9 | // platforms that aren't using them. 10 | // 11 | // FIXME: A better solution is needed. 12 | // 13 | // The Package.swift syntax doesn't offer a condition option for a target, 14 | // so it is always built on all platforms--even when it should only be 15 | // built if it is a dependency of another required component. 16 | // 17 | // See https://bugs.swift.org/browse/SR-13093 18 | // 19 | // For platforms where the library (or in the case of HostFWUSB, the framework) 20 | // is not present, the unconditional build will cause build errors. 21 | // To prevent these, all code in the LibUSB and HostFWUSB modules is wrapped 22 | // with a "#if SKIPMODULE" guard. The swiftSettings option sets this define 23 | // on platforms that don't use the module. The SKIPMODULE pattern is 24 | // awkward but effective in preventing spurious/harmless build errors. 25 | // 26 | // The build of a target on platforms that don't need/use it also produces warnings: 27 | // warning: failed to retrieve search paths with pkg-config; maybe pkg-config is not installed 28 | // warning: you may be able to install libusb-1.0 using your system-packager: brew install libusb 29 | // By making the dependency on the systemLibrary conditional 30 | // .target(name: "CLibUSB", condition: .when(platforms: [.linux])), 31 | // these warnings could be squelched in the command-line build, but not in Xcode (12.5). 32 | // We currently favor the simplicity of the common target description over the 33 | // brittleness (because of platform) that would come with cleaning up warnings in 34 | // only one build environment. 35 | import PackageDescription 36 | 37 | let package = Package( 38 | name: "deft-simple-usb", 39 | products: [ 40 | // Products define the executables and libraries produced by a package, and make them visible to other packages. 41 | .library( 42 | name: "LibUSB", 43 | targets: ["LibUSB"]), 44 | .library( 45 | name: "HostFWUSB", 46 | targets: ["HostFWUSB"]), 47 | .library( 48 | name: "SimpleUSB", 49 | targets: ["SimpleUSB"]), 50 | .library( 51 | name: "PortableUSB", 52 | targets: ["PortableUSB"]), 53 | ], 54 | dependencies: [ 55 | // Dependencies declare other packages that this package depends on. 56 | .package(url: "https://github.com/didactek/deft-log.git", from: "0.0.1"), 57 | ], 58 | targets: [ 59 | // Targets are the basic building blocks of a package. A target can define a module or a test suite. 60 | // Targets can depend on other targets in this package, and on products in packages which this package depends on. 61 | .target( 62 | name: "LibUSB", 63 | 64 | dependencies: [ 65 | "CLibUSB", 66 | "SimpleUSB", 67 | .product(name: "DeftLog", package: "deft-log")], 68 | swiftSettings: [.define("SKIPMODULE", .when(platforms: [.macOS]))]), 69 | .target( 70 | name: "HostFWUSB", 71 | dependencies: ["SimpleUSB", .product(name: "DeftLog", package: "deft-log")], 72 | swiftSettings: [.define("SKIPMODULE", .when(platforms: [.linux]))]), 73 | .target( 74 | name: "PortableUSB", 75 | dependencies: [ 76 | .target(name: "HostFWUSB", condition: .when(platforms: [.macOS])), 77 | .target(name: "LibUSB", condition: .when(platforms: [.linux])), 78 | ], 79 | swiftSettings: [ 80 | .define("USE_LIBUSB", .when(platforms: [.linux])), 81 | .define("USE_FWUSB", .when(platforms: [.macOS])) 82 | ]), 83 | .target( 84 | name: "SimpleUSB", 85 | dependencies: []), 86 | // FIXME: this generates a warning on macOS, even though the library is not needed 87 | .systemLibrary( 88 | name: "CLibUSB", 89 | pkgConfig: "libusb-1.0", 90 | providers: [ 91 | .brew(["libusb"]), 92 | .apt(["libusb-1.0-0-dev"]), 93 | ] 94 | ), 95 | .testTarget( 96 | name: "ftdi-synchronous-serialTests", 97 | dependencies: ["LibUSB"]), 98 | ] 99 | ) 100 | -------------------------------------------------------------------------------- /Sources/LibUSB/USBDevice.swift: -------------------------------------------------------------------------------- 1 | // 2 | // USBDevice.swift 3 | // deft-simple-usb 4 | // 5 | // Created by Kit Transue on 2020-08-02. 6 | // Copyright © 2020 Kit Transue 7 | // SPDX-License-Identifier: Apache-2.0 8 | // 9 | 10 | #if SKIPMODULE // See Package.swift discussion 11 | #else 12 | import Foundation 13 | import CLibUSB 14 | import SimpleUSB 15 | 16 | 17 | /// Provide control and endpoint services to a USB device using the [libusb](https://libusb.info) system library. 18 | /// Devices are obtained from the bus .findDevice method. 19 | public class LUUSBDevice: USBDevice, DeviceCommon { 20 | typealias EndpointAddress = PlatformEndpointAddress 21 | 22 | var libusbTimeout = UInt32(5000) 23 | public var timeout: TimeInterval { 24 | get { TimeInterval(Double(libusbTimeout) / 1000) } 25 | set { libusbTimeout = UInt32(newValue * 1000) } 26 | } 27 | 28 | let subsystem: LUUSBBus // keep the subsytem alive 29 | let device: OpaquePointer 30 | var handle: OpaquePointer? = nil 31 | let interfaceNumber: Int32 = 0 32 | 33 | let writeEndpoint: EndpointAddress 34 | let readEndpoint: EndpointAddress 35 | 36 | init(subsystem: LUUSBBus, device: OpaquePointer) throws { 37 | self.subsystem = subsystem 38 | self.device = device 39 | 40 | LUUSBBus.checkCall(libusb_open(device, &handle)) { msg in // deinit: libusb_close 41 | throw USBError.bindingDeviceHandle(msg) 42 | } 43 | 44 | var configurationPtr: UnsafeMutablePointer? = nil 45 | defer { 46 | libusb_free_config_descriptor(configurationPtr) 47 | } 48 | LUUSBBus.checkCall(libusb_get_active_config_descriptor(device, &configurationPtr)) { msg in 49 | throw USBError.getConfiguration(msg) 50 | } 51 | guard let configuration = configurationPtr else { 52 | throw USBError.getConfiguration("null configuration") 53 | } 54 | let configurationIndex = 0 55 | let interfacesCount = configuration[configurationIndex].bNumInterfaces 56 | logger.trace("there are \(interfacesCount) interfaces on this device") 57 | 58 | // The operating system may have loaded a default driver for this device 59 | // (e.g. on linux, the 'ftdi_sio' driver will likely be loaded for the FTDI device 60 | // to act as a UART serial adapter). Since we are rolling our own driver here, 61 | // ask libusb to unload the system-loaded driver while we are using the device. 62 | // It is OK to ask for detach on macOS. 63 | libusb_set_auto_detach_kernel_driver(handle, 1 /* non-zero is 'yes: enable' */) 64 | 65 | LUUSBBus.checkCall(libusb_claim_interface(handle, interfaceNumber)) { msg in // deinit: libusb_release_interface 66 | throw USBError.claimInterface(msg) 67 | } 68 | let interface = configuration[configurationIndex].interface[Int(interfaceNumber)] 69 | 70 | let endpointCount = interface.altsetting[0].bNumEndpoints 71 | logger.trace("Device/Interface has \(endpointCount) endpoints") 72 | let endpoints = (0 ..< endpointCount).map { interface.altsetting[0].endpoint[Int($0)] } 73 | let addresses = endpoints.map { EndpointAddress(rawValue: $0.bEndpointAddress) } 74 | writeEndpoint = addresses.first { $0.isWritable }! 75 | readEndpoint = addresses.first { !$0.isWritable }! 76 | 77 | libusb_ref_device(device) // now we won't throw 78 | logger.debug("Device connected and endpoints configured.") 79 | } 80 | 81 | deinit { 82 | libusb_release_interface(handle, interfaceNumber) 83 | libusb_close(handle) 84 | libusb_unref_device(device) 85 | } 86 | 87 | // Documented in protocol 88 | public func controlTransfer(requestType: BMRequestType, bRequest: UInt8, wValue: UInt16, wIndex: UInt16, data: Data?, wLength: UInt16) -> Int32 { 89 | // USB 2.0 9.3.4: wIndex 90 | // some interpretations (high bits 0): 91 | // as endpoint (direction:1/0:3/endpoint:4) 92 | // as interface (interface number) 93 | // semantics for ControlRequestType.standard requests are defined in 94 | // Table 9.4 Standard Device Requests 95 | // ControlRequestType.vendor semantics may vary. 96 | // FIXME: could we make .standard calls more typesafe? 97 | var dataCopy = Array(data ?? Data()) 98 | return libusb_control_transfer(handle, requestType, bRequest, wValue, wIndex, &dataCopy, wLength, libusbTimeout) 99 | } 100 | 101 | // Documented in protocol 102 | public func bulkTransferOut(msg: Data) { 103 | let outgoingCount = Int32(msg.count) 104 | 105 | var bytesTransferred = Int32(0) 106 | var msgScratchCopy = msg 107 | 108 | let result = msgScratchCopy.withUnsafeMutableBytes { unsafe in 109 | libusb_bulk_transfer(handle, writeEndpoint.rawValue, unsafe.bindMemory(to: UInt8.self).baseAddress, outgoingCount, &bytesTransferred, libusbTimeout) 110 | } 111 | guard result == 0 else { 112 | fatalError("bulkTransfer returned \(result)") 113 | } 114 | guard outgoingCount == bytesTransferred else { 115 | fatalError("not all bytes sent") 116 | } 117 | } 118 | 119 | public func bulkTransferIn() -> Data { 120 | let bufSize = 1024 // FIXME: tell the device about this! 121 | var readBuffer = Array(repeating: UInt8(0), count: bufSize) 122 | var readCount = Int32(0) 123 | let result = libusb_bulk_transfer(handle, readEndpoint.rawValue, &readBuffer, Int32(bufSize), &readCount, libusbTimeout) 124 | guard result == 0 else { 125 | let errorMessage = String(cString: libusb_error_name(result)) // must not free message 126 | fatalError("bulkTransfer read returned \(result): \(errorMessage)") 127 | } 128 | return Data(readBuffer.prefix(Int(readCount))) // FIXME: Xcode 11.6 / Swift 5.2.4: explicit constructor is needed to avoid crash in Data subrange if we just return the prefix!! This seems like a bug???? 129 | } 130 | } 131 | #endif 132 | -------------------------------------------------------------------------------- /Sources/HostFWUSB/HostFWUSBDevice.swift: -------------------------------------------------------------------------------- 1 | // 2 | // HostFWUSBDevice.swift 3 | // deft-simple-usb 4 | // 5 | // Created by Kit Transue on 2021-04-28. 6 | // Copyright © 2021 Kit Transue 7 | // SPDX-License-Identifier: Apache-2.0 8 | // 9 | 10 | #if SKIPMODULE // See Package.swift discussion 11 | #else 12 | import Foundation 13 | import IOUSBHost 14 | import SimpleUSB 15 | 16 | 17 | /// Bridge to the macOS IOUSBHostDevice class in the IOUSBHost usermode USB framework. 18 | /// Obtain a FWUSBDevice from the findDevice vendor in the USBBus provider. FWUSBDevice 19 | /// configures default configuration endpoints for bulk read and write, and provides control transfer 20 | /// support. 21 | public class FWUSBDevice: USBDevice, DeviceCommon { 22 | public var timeout = TimeInterval(5) 23 | 24 | typealias EndpointAddress = PlatformEndpointAddress 25 | 26 | let device: IOUSBHostDevice 27 | let writeEndpoint: IOUSBHostPipe 28 | let readEndpoint: IOUSBHostPipe 29 | 30 | init(device: IOUSBHostDevice) throws { 31 | logger.trace("Configuring USBDevice with descriptor \(device.deviceDescriptor!.pointee)") 32 | 33 | self.device = device 34 | 35 | let configuration = try! device.configurationDescriptor(with: 0).pointee 36 | logger.trace("Configuration with:0 is \(configuration)") 37 | 38 | // check bNumInterfaces 39 | let interfacesCount = configuration.bNumInterfaces 40 | logger.trace("Device supports \(interfacesCount) interfaces") 41 | 42 | let interfaceDescriptionPtr = IOUSBGetNextInterfaceDescriptor(device.configurationDescriptor, nil /*zeroeth previous; first is next*/) 43 | // claim interface 44 | guard let interfaceDescription = interfaceDescriptionPtr else { 45 | throw USBError.claimInterface("IOUSBGetNextInterfaceDescriptor") 46 | } 47 | logger.trace("Interface description: \(interfaceDescription.pointee)") 48 | 49 | // Create lookup for the service 50 | // FIXME: I'm sure the framework provides a better helper for constructing this; 51 | // I just can't seem to find it.... 52 | let interfaceSearchInts: [IOUSBHostMatchingPropertyKey : Int] = [ 53 | .vendorID: Int(device.deviceDescriptor!.pointee.idVendor), 54 | .productID: Int(device.deviceDescriptor!.pointee.idProduct), 55 | .interfaceNumber: 0, 56 | .configurationValue: Int(configuration.bConfigurationValue), 57 | .interfaceClass: Int(interfaceDescription.pointee.bInterfaceClass), 58 | .interfaceSubClass: Int(interfaceDescription.pointee.bInterfaceSubClass), 59 | .interfaceProtocol: Int(interfaceDescription.pointee.bInterfaceProtocol), 60 | ] 61 | let searchRequest = (interfaceSearchInts as NSDictionary).mutableCopy() as! NSMutableDictionary 62 | searchRequest.addEntries(from: ["IOProviderClass" : "IOUSBHostInterface"]) 63 | 64 | 65 | logger.trace("interface search request is \(searchRequest)") 66 | let service = IOServiceGetMatchingService(kIOMasterPortDefault, searchRequest) 67 | 68 | let interface = try! IOUSBHostInterface.init(__ioService: service, options: [], queue: nil, interestHandler: nil) 69 | 70 | var endpointPipes = [IOUSBHostPipe]() 71 | var endpointIterator = IOUSBGetNextEndpointDescriptor(interface.configurationDescriptor, interface.interfaceDescriptor, nil) 72 | logger.trace("Interface configurationDescriptor is \(interface.configurationDescriptor.pointee)") 73 | 74 | logger.trace("Interface interfaceDescriptor is \(interface.interfaceDescriptor.pointee)") 75 | while let endpointFound = endpointIterator { 76 | logger.trace("Making pipe for endpoint: \(endpointFound.pointee)") 77 | endpointPipes.append(try interface.copyPipe(withAddress: Int(endpointFound.pointee.bEndpointAddress))) 78 | endpointFound.withMemoryRebound(to: IOUSBDescriptorHeader.self, capacity: 1) { 79 | endpointIterator = IOUSBGetNextEndpointDescriptor(interface.configurationDescriptor, interface.interfaceDescriptor, $0) 80 | } 81 | } 82 | logger.trace("created \(endpointPipes.count) pipes") 83 | 84 | guard endpointPipes.count == 2 else { 85 | throw USBError.claimInterface("expected to find bulk for read and write") 86 | } 87 | 88 | writeEndpoint = endpointPipes.first(where: { EndpointAddress(rawValue: $0.endpointAddress).isWritable })! 89 | readEndpoint = endpointPipes.first(where: { !EndpointAddress(rawValue: $0.endpointAddress).isWritable })! 90 | 91 | logger.debug("Connected to device with idVendor \(device.deviceDescriptor!.pointee.idVendor); idProduct: \(device.deviceDescriptor!.pointee.idProduct)") 92 | } 93 | 94 | // Documented in protocol 95 | public func controlTransfer(requestType: BMRequestType, bRequest: UInt8, wValue: UInt16, wIndex: UInt16, data: Data?, wLength: UInt16) -> Int32 { 96 | // USB 2.0 9.3.4: wIndex 97 | // some interpretations (high bits 0): 98 | // as endpoint (direction:1/0:3/endpoint:4) 99 | // as interface (interface number) 100 | // semantics for ControlRequestType.standard requests are defined in 101 | // Table 9.4 Standard Device Requests 102 | // ControlRequestType.vendor semantics may vary. 103 | // FIXME: could we make .standard calls more typesafe? 104 | // FIXME: Using an API that is not documented in the 11.1 SDK, but instead 105 | // is discovered by looking at the Objective-C headers and either making guesses 106 | // about the NS_REFINED_FOR_SWIFT extensions or using those methods directly. 107 | // Hopefully the next SDK will be more clear about how bridging should work. 108 | 109 | let payload: NSMutableData? 110 | if let data = data { 111 | payload = NSMutableData(data: data) 112 | } else { 113 | payload = nil 114 | } 115 | 116 | let request = IOUSBDeviceRequest(bmRequestType: requestType, bRequest: bRequest, wValue: wValue, wIndex: wIndex, wLength: wLength) 117 | var transferred: Int = 0 118 | 119 | // FIXME: There are control request methods described in the IOSUSBHostPipe 120 | // Objective-C headers, but they are marked NS_REFINED_FOR_SWIFT, suggesting 121 | // there is an extension somewhere that provides a prettier API. However, 122 | // I can't seem to find that extension, so am using the hidden-but-available 123 | // method. (NS_REFINED_FOR_SWIFT mangles the method name with 124 | // a pair of leading underscores.) 125 | try! device.__send(request, //IOUSBDeviceRequest)request 126 | data: payload, //data:(nullable NSMutableData*)data 127 | bytesTransferred: &transferred, //bytesTransferred:(nullable NSUInteger*)bytesTransferred 128 | completionTimeout: timeout) //completionTimeout:(NSTimeInterval)completionTimeout 129 | return Int32(transferred) 130 | } 131 | 132 | // Documented in protocol 133 | public func bulkTransferOut(msg: Data) { 134 | let payload = NSMutableData(data: msg) 135 | 136 | var bytesSent = 0 137 | let resultsAvailable = DispatchSemaphore(value: 0) 138 | try! writeEndpoint.enqueueIORequest(with: payload, completionTimeout: timeout) { 139 | status, bytesTransferred in 140 | logger.trace("bulkTransferOut completed with status \(status); \(bytesTransferred) of \(msg.count) bytes transferred") 141 | guard status == 0 else { 142 | fatalError("bulkTransferOut IORequest failure: code \(status)") 143 | } 144 | bytesSent = bytesTransferred 145 | resultsAvailable.signal() 146 | } 147 | resultsAvailable.wait() 148 | 149 | guard msg.count == bytesSent else { 150 | fatalError("not all msg bytes sent") 151 | } 152 | } 153 | 154 | // Documented in protocol 155 | public func bulkTransferIn() -> Data { 156 | // Provide space in a local buffer to hold read results. 157 | // Note that 'capacity' and 'length' are different concepts, and it is 158 | // the length (number of intialized bytes) that is used by the IO request 159 | // machinery to infer the buffer size. 160 | let localBuffer = NSMutableData(length: Int(readEndpoint.descriptors.pointee.descriptor.wMaxPacketSize)) 161 | var bytesReceived = 0 162 | 163 | let resultsAvailable = DispatchSemaphore(value: 0) 164 | try! readEndpoint.enqueueIORequest(with: localBuffer, completionTimeout: timeout) { 165 | status, bytesTransferred in 166 | guard status == 0 else { 167 | fatalError("bulkTransfer read status: \(status)") 168 | } 169 | bytesReceived = bytesTransferred 170 | resultsAvailable.signal() 171 | } 172 | resultsAvailable.wait() 173 | 174 | return Data(localBuffer!.prefix(bytesReceived)) 175 | } 176 | } 177 | #endif 178 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | --------------------------------------------------------------------------------