1 /* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */
2 /*
3  * Synchronous I/O functions for libusb
4  * Copyright © 2007-2008 Daniel Drake <dsd@gentoo.org>
5  * Copyright © 2019 Nathan Hjelm <hjelmn@cs.unm.edu>
6  * Copyright © 2019 Google LLC. All rights reserved.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22 
23 #include "libusbi.h"
24 
25 #include <string.h>
26 
27 /**
28  * @defgroup libusb_syncio Synchronous device I/O
29  *
30  * This page documents libusb's synchronous (blocking) API for USB device I/O.
31  * This interface is easy to use but has some limitations. More advanced users
32  * may wish to consider using the \ref libusb_asyncio "asynchronous I/O API" instead.
33  */
34 
sync_transfer_cb(struct libusb_transfer * transfer)35 static void LIBUSB_CALL sync_transfer_cb(struct libusb_transfer *transfer)
36 {
37 	int *completed = transfer->user_data;
38 	*completed = 1;
39 	usbi_dbg("actual_length=%d", transfer->actual_length);
40 	/* caller interprets result and frees transfer */
41 }
42 
sync_transfer_wait_for_completion(struct libusb_transfer * transfer)43 static void sync_transfer_wait_for_completion(struct libusb_transfer *transfer)
44 {
45 	int r, *completed = transfer->user_data;
46 	struct libusb_context *ctx = HANDLE_CTX(transfer->dev_handle);
47 
48 	while (!*completed) {
49 		r = libusb_handle_events_completed(ctx, completed);
50 		if (r < 0) {
51 			if (r == LIBUSB_ERROR_INTERRUPTED)
52 				continue;
53 			usbi_err(ctx, "libusb_handle_events failed: %s, cancelling transfer and retrying",
54 				 libusb_error_name(r));
55 			libusb_cancel_transfer(transfer);
56 			continue;
57 		}
58 		if (NULL == transfer->dev_handle) {
59 			/* transfer completion after libusb_close() */
60 			transfer->status = LIBUSB_TRANSFER_NO_DEVICE;
61 			*completed = 1;
62 		}
63 	}
64 }
65 
66 /** \ingroup libusb_syncio
67  * Perform a USB control transfer.
68  *
69  * The direction of the transfer is inferred from the bmRequestType field of
70  * the setup packet.
71  *
72  * The wValue, wIndex and wLength fields values should be given in host-endian
73  * byte order.
74  *
75  * \param dev_handle a handle for the device to communicate with
76  * \param bmRequestType the request type field for the setup packet
77  * \param bRequest the request field for the setup packet
78  * \param wValue the value field for the setup packet
79  * \param wIndex the index field for the setup packet
80  * \param data a suitably-sized data buffer for either input or output
81  * (depending on direction bits within bmRequestType)
82  * \param wLength the length field for the setup packet. The data buffer should
83  * be at least this size.
84  * \param timeout timeout (in milliseconds) that this function should wait
85  * before giving up due to no response being received. For an unlimited
86  * timeout, use value 0.
87  * \returns on success, the number of bytes actually transferred
88  * \returns LIBUSB_ERROR_TIMEOUT if the transfer timed out
89  * \returns LIBUSB_ERROR_PIPE if the control request was not supported by the
90  * device
91  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
92  * \returns LIBUSB_ERROR_BUSY if called from event handling context
93  * \returns LIBUSB_ERROR_INVALID_PARAM if the transfer size is larger than
94  * the operating system and/or hardware can support (see \ref asynclimits)
95  * \returns another LIBUSB_ERROR code on other failures
96  */
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)97 int API_EXPORTED libusb_control_transfer(libusb_device_handle *dev_handle,
98 	uint8_t bmRequestType, uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
99 	unsigned char *data, uint16_t wLength, unsigned int timeout)
100 {
101 	struct libusb_transfer *transfer;
102 	unsigned char *buffer;
103 	int completed = 0;
104 	int r;
105 
106 	if (usbi_handling_events(HANDLE_CTX(dev_handle)))
107 		return LIBUSB_ERROR_BUSY;
108 
109 	transfer = libusb_alloc_transfer(0);
110 	if (!transfer)
111 		return LIBUSB_ERROR_NO_MEM;
112 
113 	buffer = malloc(LIBUSB_CONTROL_SETUP_SIZE + wLength);
114 	if (!buffer) {
115 		libusb_free_transfer(transfer);
116 		return LIBUSB_ERROR_NO_MEM;
117 	}
118 
119 	libusb_fill_control_setup(buffer, bmRequestType, bRequest, wValue, wIndex,
120 		wLength);
121 	if ((bmRequestType & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT)
122 		memcpy(buffer + LIBUSB_CONTROL_SETUP_SIZE, data, wLength);
123 
124 	libusb_fill_control_transfer(transfer, dev_handle, buffer,
125 		sync_transfer_cb, &completed, timeout);
126 	transfer->flags = LIBUSB_TRANSFER_FREE_BUFFER;
127 	r = libusb_submit_transfer(transfer);
128 	if (r < 0) {
129 		libusb_free_transfer(transfer);
130 		return r;
131 	}
132 
133 	sync_transfer_wait_for_completion(transfer);
134 
135 	if ((bmRequestType & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_IN)
136 		memcpy(data, libusb_control_transfer_get_data(transfer),
137 			transfer->actual_length);
138 
139 	switch (transfer->status) {
140 	case LIBUSB_TRANSFER_COMPLETED:
141 		r = transfer->actual_length;
142 		break;
143 	case LIBUSB_TRANSFER_TIMED_OUT:
144 		r = LIBUSB_ERROR_TIMEOUT;
145 		break;
146 	case LIBUSB_TRANSFER_STALL:
147 		r = LIBUSB_ERROR_PIPE;
148 		break;
149 	case LIBUSB_TRANSFER_NO_DEVICE:
150 		r = LIBUSB_ERROR_NO_DEVICE;
151 		break;
152 	case LIBUSB_TRANSFER_OVERFLOW:
153 		r = LIBUSB_ERROR_OVERFLOW;
154 		break;
155 	case LIBUSB_TRANSFER_ERROR:
156 	case LIBUSB_TRANSFER_CANCELLED:
157 		r = LIBUSB_ERROR_IO;
158 		break;
159 	default:
160 		usbi_warn(HANDLE_CTX(dev_handle),
161 			"unrecognised status code %d", transfer->status);
162 		r = LIBUSB_ERROR_OTHER;
163 	}
164 
165 	libusb_free_transfer(transfer);
166 	return r;
167 }
168 
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)169 static int do_sync_bulk_transfer(struct libusb_device_handle *dev_handle,
170 	unsigned char endpoint, unsigned char *buffer, int length,
171 	int *transferred, unsigned int timeout, unsigned char type)
172 {
173 	struct libusb_transfer *transfer;
174 	int completed = 0;
175 	int r;
176 
177 	if (usbi_handling_events(HANDLE_CTX(dev_handle)))
178 		return LIBUSB_ERROR_BUSY;
179 
180 	transfer = libusb_alloc_transfer(0);
181 	if (!transfer)
182 		return LIBUSB_ERROR_NO_MEM;
183 
184 	libusb_fill_bulk_transfer(transfer, dev_handle, endpoint, buffer, length,
185 		sync_transfer_cb, &completed, timeout);
186 	transfer->type = type;
187 
188 	r = libusb_submit_transfer(transfer);
189 	if (r < 0) {
190 		libusb_free_transfer(transfer);
191 		return r;
192 	}
193 
194 	sync_transfer_wait_for_completion(transfer);
195 
196 	if (transferred)
197 		*transferred = transfer->actual_length;
198 
199 	switch (transfer->status) {
200 	case LIBUSB_TRANSFER_COMPLETED:
201 		r = 0;
202 		break;
203 	case LIBUSB_TRANSFER_TIMED_OUT:
204 		r = LIBUSB_ERROR_TIMEOUT;
205 		break;
206 	case LIBUSB_TRANSFER_STALL:
207 		r = LIBUSB_ERROR_PIPE;
208 		break;
209 	case LIBUSB_TRANSFER_OVERFLOW:
210 		r = LIBUSB_ERROR_OVERFLOW;
211 		break;
212 	case LIBUSB_TRANSFER_NO_DEVICE:
213 		r = LIBUSB_ERROR_NO_DEVICE;
214 		break;
215 	case LIBUSB_TRANSFER_ERROR:
216 	case LIBUSB_TRANSFER_CANCELLED:
217 		r = LIBUSB_ERROR_IO;
218 		break;
219 	default:
220 		usbi_warn(HANDLE_CTX(dev_handle),
221 			"unrecognised status code %d", transfer->status);
222 		r = LIBUSB_ERROR_OTHER;
223 	}
224 
225 	libusb_free_transfer(transfer);
226 	return r;
227 }
228 
229 /** \ingroup libusb_syncio
230  * Perform a USB bulk transfer. The direction of the transfer is inferred from
231  * the direction bits of the endpoint address.
232  *
233  * For bulk reads, the <tt>length</tt> field indicates the maximum length of
234  * data you are expecting to receive. If less data arrives than expected,
235  * this function will return that data, so be sure to check the
236  * <tt>transferred</tt> output parameter.
237  *
238  * You should also check the <tt>transferred</tt> parameter for bulk writes.
239  * Not all of the data may have been written.
240  *
241  * Also check <tt>transferred</tt> when dealing with a timeout error code.
242  * libusb may have to split your transfer into a number of chunks to satisfy
243  * underlying O/S requirements, meaning that the timeout may expire after
244  * the first few chunks have completed. libusb is careful not to lose any data
245  * that may have been transferred; do not assume that timeout conditions
246  * indicate a complete lack of I/O. See \ref asynctimeout for more details.
247  *
248  * \param dev_handle a handle for the device to communicate with
249  * \param endpoint the address of a valid endpoint to communicate with
250  * \param data a suitably-sized data buffer for either input or output
251  * (depending on endpoint)
252  * \param length for bulk writes, the number of bytes from data to be sent. for
253  * bulk reads, the maximum number of bytes to receive into the data buffer.
254  * \param transferred output location for the number of bytes actually
255  * transferred. Since version 1.0.21 (\ref LIBUSB_API_VERSION >= 0x01000105),
256  * it is legal to pass a NULL pointer if you do not wish to receive this
257  * information.
258  * \param timeout timeout (in milliseconds) that this function should wait
259  * before giving up due to no response being received. For an unlimited
260  * timeout, use value 0.
261  *
262  * \returns 0 on success (and populates <tt>transferred</tt>)
263  * \returns LIBUSB_ERROR_TIMEOUT if the transfer timed out (and populates
264  * <tt>transferred</tt>)
265  * \returns LIBUSB_ERROR_PIPE if the endpoint halted
266  * \returns LIBUSB_ERROR_OVERFLOW if the device offered more data, see
267  * \ref libusb_packetoverflow
268  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
269  * \returns LIBUSB_ERROR_BUSY if called from event handling context
270  * \returns LIBUSB_ERROR_INVALID_PARAM if the transfer size is larger than
271  * the operating system and/or hardware can support (see \ref asynclimits)
272  * \returns another LIBUSB_ERROR code on other failures
273  */
libusb_bulk_transfer(libusb_device_handle * dev_handle,unsigned char endpoint,unsigned char * data,int length,int * transferred,unsigned int timeout)274 int API_EXPORTED libusb_bulk_transfer(libusb_device_handle *dev_handle,
275 	unsigned char endpoint, unsigned char *data, int length,
276 	int *transferred, unsigned int timeout)
277 {
278 	return do_sync_bulk_transfer(dev_handle, endpoint, data, length,
279 		transferred, timeout, LIBUSB_TRANSFER_TYPE_BULK);
280 }
281 
282 /** \ingroup libusb_syncio
283  * Perform a USB interrupt transfer. The direction of the transfer is inferred
284  * from the direction bits of the endpoint address.
285  *
286  * For interrupt reads, the <tt>length</tt> field indicates the maximum length
287  * of data you are expecting to receive. If less data arrives than expected,
288  * this function will return that data, so be sure to check the
289  * <tt>transferred</tt> output parameter.
290  *
291  * You should also check the <tt>transferred</tt> parameter for interrupt
292  * writes. Not all of the data may have been written.
293  *
294  * Also check <tt>transferred</tt> when dealing with a timeout error code.
295  * libusb may have to split your transfer into a number of chunks to satisfy
296  * underlying O/S requirements, meaning that the timeout may expire after
297  * the first few chunks have completed. libusb is careful not to lose any data
298  * that may have been transferred; do not assume that timeout conditions
299  * indicate a complete lack of I/O. See \ref asynctimeout for more details.
300  *
301  * The default endpoint bInterval value is used as the polling interval.
302  *
303  * \param dev_handle a handle for the device to communicate with
304  * \param endpoint the address of a valid endpoint to communicate with
305  * \param data a suitably-sized data buffer for either input or output
306  * (depending on endpoint)
307  * \param length for bulk writes, the number of bytes from data to be sent. for
308  * bulk reads, the maximum number of bytes to receive into the data buffer.
309  * \param transferred output location for the number of bytes actually
310  * transferred. Since version 1.0.21 (\ref LIBUSB_API_VERSION >= 0x01000105),
311  * it is legal to pass a NULL pointer if you do not wish to receive this
312  * information.
313  * \param timeout timeout (in milliseconds) that this function should wait
314  * before giving up due to no response being received. For an unlimited
315  * timeout, use value 0.
316  *
317  * \returns 0 on success (and populates <tt>transferred</tt>)
318  * \returns LIBUSB_ERROR_TIMEOUT if the transfer timed out
319  * \returns LIBUSB_ERROR_PIPE if the endpoint halted
320  * \returns LIBUSB_ERROR_OVERFLOW if the device offered more data, see
321  * \ref libusb_packetoverflow
322  * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
323  * \returns LIBUSB_ERROR_BUSY if called from event handling context
324  * \returns LIBUSB_ERROR_INVALID_PARAM if the transfer size is larger than
325  * the operating system and/or hardware can support (see \ref asynclimits)
326  * \returns another LIBUSB_ERROR code on other error
327  */
libusb_interrupt_transfer(libusb_device_handle * dev_handle,unsigned char endpoint,unsigned char * data,int length,int * transferred,unsigned int timeout)328 int API_EXPORTED libusb_interrupt_transfer(libusb_device_handle *dev_handle,
329 	unsigned char endpoint, unsigned char *data, int length,
330 	int *transferred, unsigned int timeout)
331 {
332 	return do_sync_bulk_transfer(dev_handle, endpoint, data, length,
333 		transferred, timeout, LIBUSB_TRANSFER_TYPE_INTERRUPT);
334 }
335