summaryrefslogtreecommitdiff
path: root/src/usb.c
blob: db61b2fa06ff8b72808d43785189c5178137bc66 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

#include <libusb.h>

#include "logging.h"
#include "http.h"
#include "usb.h"

static int is_ippusb_interface(const struct libusb_interface_descriptor *interf)
{
	return interf->bInterfaceClass == 0x07 &&
	       interf->bInterfaceSubClass == 0x01 &&
	       interf->bInterfaceProtocol == 0x04;
}

static int count_ippoverusb_interfaces(struct libusb_config_descriptor *config)
{
	int ippusb_interface_count = 0;

	for (uint8_t interface_num = 0;
	     interface_num < config->bNumInterfaces;
	     interface_num++) {
	
		const struct libusb_interface *interface = NULL;
		interface = &config->interface[interface_num];
	
		for (int alt_num = 0;
		     alt_num < interface->num_altsetting;
		     alt_num++) {
	
			const struct libusb_interface_descriptor *alt = NULL;
			alt = &interface->altsetting[alt_num];
	
			// Check for IPP over USB interfaces
			if (!is_ippusb_interface(alt))
				continue;
	
			ippusb_interface_count++;
			break;
		}
	}

	return ippusb_interface_count;
}

struct usb_sock_t *usb_open()
{
	struct usb_sock_t *usb = calloc(1, sizeof *usb);
	int status = 1;
	status = libusb_init(&usb->context);
	if (status < 0) {
		// TODO: use libusb_error_name for better status errors
		ERR("libusb init failed with error code %d", status);
		goto error_usbinit;
	}

	libusb_device **device_list = NULL;
	ssize_t device_count = libusb_get_device_list(usb->context, &device_list);
	if (device_count < 0) {
		ERR("failed to get list of usb devices");
		goto error;
	}


	// Discover device and count interfaces ==---------------------------==
	int selected_config = -1;
	int selected_ipp_interface_count = 0;

	libusb_device *printer_device = NULL;
	for (ssize_t i = 0; i < device_count; i++) {
		libusb_device *candidate = device_list[i];
		struct libusb_device_descriptor desc;
		libusb_get_device_descriptor(candidate, &desc);

		// TODO: use libusb_cpu_to_le16 to fix endianess
		if (desc.idVendor  != 0x03f0 &&
		    desc.idProduct != 0xc511)
			continue;
		// TODO: filter on serial number

		// TODO: search only device current config
		for (uint8_t config_num = 0;
		     config_num < desc.bNumConfigurations;
		     config_num++) {
			struct libusb_config_descriptor *config = NULL;
			status = libusb_get_config_descriptor(candidate,
			                                      config_num,
			                                      &config);
			// TODO: check status

			int interface_count = count_ippoverusb_interfaces(config);
			libusb_free_config_descriptor(config);
			if (interface_count >= 2) {
				selected_config = config_num;
				selected_ipp_interface_count = interface_count;
				printer_device = candidate;
				goto found_device;
			}

			// CONFTEST: Two or more interfaces are required
			if (interface_count == 1) {
				CONF("usb device has only one ipp interface "
				    "in violation of standard");
				goto error;
			}

			ERR("usb device had no ipp-usb class interfaces");
			// TODO: if VID and PID set warn 
			// that the device is not a ipp printer
		}
	}
found_device:

	if (printer_device == NULL) {
		ERR("no printer found by that vid & pid & serial");
		goto error;
	}


	// Open the printer ==-----------------------------------------------==
	status = libusb_open(printer_device, &usb->printer);
	if (status != 0) {
		ERR("failed to open device");
		goto error;
	}


	// Open every IPP-USB interface ==-----------------------------------==
	usb->num_interfaces = selected_ipp_interface_count;
	usb->interfaces = calloc(usb->num_interfaces,
	                         sizeof(*usb->interfaces));
	if (usb->interfaces == NULL) {
		ERR("Failed to alloc interfaces");
		goto error;
	}

	struct libusb_config_descriptor *config = NULL;
	status = libusb_get_config_descriptor(printer_device,
	                                      (uint8_t)selected_config,
	                                      &config);
	// TODO: check status
	int interfs = selected_ipp_interface_count;
	for (uint8_t interf_num = 0;
	     interf_num < config->bNumInterfaces;
	     interf_num++) {
	
		const struct libusb_interface *interf = NULL;
		interf = &config->interface[interf_num];
		for (int alt_num = 0;
		     alt_num < interf->num_altsetting;
		     alt_num++) {
	
			const struct libusb_interface_descriptor *alt = NULL;
			alt = &interf->altsetting[alt_num];

			// Skip non-IPP-USB interfaces
			if (!is_ippusb_interface(alt))
				continue;

			// Release kernel driver
			if (libusb_kernel_driver_active(usb->printer,
			                                interf_num) == 1) {
				// Only linux supports this
				// other platforms will fail
				// thus we ignore the error code
				// it either works or it does not
				libusb_detach_kernel_driver(usb->printer,
				                            interf_num);
			}

			// Claim the whole interface
			status = libusb_claim_interface(
					usb->printer,
					alt->bInterfaceNumber);
			switch (status) {
			case LIBUSB_ERROR_NOT_FOUND:
				ERR("USB Interface did not exist");
				goto error_config;
			case LIBUSB_ERROR_BUSY:
				ERR("Printer was already claimed");
				goto error_config;
			case LIBUSB_ERROR_NO_DEVICE:
				ERR("Printer was already claimed");
				goto error_config;
			case 0:
				break;
			}

			// Select the IPP-USB alt setting of the interface
			libusb_set_interface_alt_setting(usb->printer,
			                                 interf_num,
			                                 alt_num);
			interfs--;
			usb->interfaces[interfs].interface_number = interf_num;

			// TODO: add conftest for endpoint count and direction
			// Store interface's two endpoints
			for (int end_i = 0; end_i < alt->bNumEndpoints;
			     end_i++) {
				const struct libusb_endpoint_descriptor *end = NULL;
				end = &alt->endpoint[end_i];

				// TODO: handle endianness
				usb->max_packet_size = end->wMaxPacketSize;

				// High bit set means endpoint
				// is an INPUT or IN endpoint.
				uint8_t address = end->bEndpointAddress;
				struct usb_interface *uf =
						usb->interfaces + interfs;
				if (address & 0x80)
					uf->endpoint_in = address;
				else
					uf->endpoint_out = address;
			}

			break;
		}
	}
	libusb_free_config_descriptor(config);
	libusb_free_device_list(device_list, 1);


	// Pour interfaces into pool ==--------------------------------------==
	usb->num_avail = usb->num_interfaces;
	usb->interface_pool = calloc(usb->num_avail,
	                             sizeof(*usb->interface_pool));
	if (usb->interface_pool == NULL) {
		ERR("Failed to alloc interface pool");
		goto error;
	}
	for (uint32_t i = 0; i < usb->num_avail; i++) {
		usb->interface_pool[i] = i;
	}

	// High priority lock
	int status_lock = sem_init(&usb->pool_high_priority_lock, 0, 1);
	if (status_lock != 0) {
		ERR("Failed to create low priority pool lock");
		goto error;
	}
	// Low priority lock
	status_lock = sem_init(&usb->pool_low_priority_lock,
	                       0, usb->num_avail - 1);
	if (status_lock != 0) {
		ERR("Failed to create high priority pool lock");
		goto error;
	}

	return usb;

error_config:
	if (config != NULL)
		libusb_free_config_descriptor(config);
error:
	if (device_list != NULL)
		libusb_free_device_list(device_list, 1);
	if (usb != NULL) {
		if (usb->context != NULL)
			libusb_exit(usb->context);
		if (usb->interfaces != NULL)
			free(usb->interfaces);
		if (usb->interface_pool != NULL)
			free(usb->interface_pool);
		free(usb);
	}
error_usbinit:
	return NULL;
}

void usb_close(struct usb_sock_t *usb)
{
	// Release interfaces
	for (uint32_t i = 0; i < usb->num_interfaces; i++) {
		int number = usb->interfaces[i].interface_number;
		libusb_release_interface(usb->printer, number);
	}

	libusb_close(usb->printer);
	libusb_exit(usb->context);

	sem_destroy(&usb->pool_high_priority_lock);
	sem_destroy(&usb->pool_low_priority_lock);
	free(usb->interfaces);
	free(usb->interface_pool);
	free(usb);
	return;
}

struct usb_conn_t *usb_conn_aquire(struct usb_sock_t *usb,
                                   int is_high_priority)
{
	int used_high_priority = 0;
	if (is_high_priority) {
		// We first take the high priority lock.
		sem_wait(&usb->pool_high_priority_lock);
		used_high_priority = 1;

		// We can then check if a low priority
		// interface is available.
		if (!sem_trywait(&usb->pool_low_priority_lock)) {
			// If a low priority is avail we take that one
			// then release the high priority interface.
			// Otherwise we use the high priority interface.
			used_high_priority = 0;
			sem_post(&usb->pool_high_priority_lock);
		}
	} else {
		sem_wait(&usb->pool_low_priority_lock);
	}

	struct usb_conn_t *conn = calloc(1, sizeof(*conn));
	if (conn == NULL) {
		ERR("failed to aloc space for usb connection");
		return NULL;
	}

	conn->parent = usb;
	conn->is_high_priority = used_high_priority;

	conn->interface_index = usb->interface_pool[--usb->num_avail];
	conn->interface = usb->interfaces + conn->interface_index;
	return conn;
}

void usb_conn_release(struct usb_conn_t *conn)
{
	// Return usb interface to pool
	uint32_t slot = conn->parent->num_avail++;
	conn->parent->interface_pool[slot] = conn->interface_index;

	// Release our interface lock
	if (conn->is_high_priority)
		sem_post(&conn->parent->pool_high_priority_lock);
	else
		sem_post(&conn->parent->pool_low_priority_lock);

	free(conn);
}

void usb_conn_packet_send(struct usb_conn_t *conn, struct http_packet_t *pkt)
{
	int size_sent = 0;
	int timeout = 1000; // in milliseconds
	size_t sent = 0;
	size_t pending = pkt->filled_size;
	size_t portions = pkt->filled_size / 512;
	portions += (pkt->filled_size % 512) > 0 ? 1 : 0;
	for (size_t i = 0; i < portions; i++) {
		int to_send = 512;
		if (pending < 512)
			to_send = (int)pending;

		int status = libusb_bulk_transfer(conn->parent->printer,
		                                  conn->interface->endpoint_out,
		                                  pkt->buffer + sent, to_send,
		                                  &size_sent, timeout);
		pending -= to_send;
		sent += to_send;
		// TODO: check status
		if (status < 0)
			ERR("usb data sending failed with status %d", status);
	}
	NOTE("sent %d bytes over usb\n", size_sent);
}

struct http_packet_t *usb_conn_packet_get(struct usb_conn_t *conn, struct http_message_t *msg)
{
	struct http_packet_t *pkt = packet_new(msg);
	if (pkt == NULL) {
		ERR("failed to create packet for incoming usb message");
		goto cleanup;
	}

	// File packet
	const int timeout = 100; // in milliseconds
	ssize_t read_size_raw = packet_pending_bytes(pkt);
	if (read_size_raw <= 0)
		goto cleanup;


	while (read_size_raw > 0 && !msg->is_completed) {
		if (read_size_raw >= INT_MAX)
			goto cleanup;
		int read_size = (int)read_size_raw;

		int gotten_size = 0;
		int status = libusb_bulk_transfer(
		                      conn->parent->printer,
		                      conn->interface->endpoint_in,
		                      pkt->buffer + pkt->filled_size,
		                      read_size,
		                      &gotten_size, timeout);
		if (status != 0 && status != LIBUSB_ERROR_TIMEOUT) {
			ERR("bulk xfer failed with error code %d", status);
			ERR("tried reading %d bytes", read_size);
			goto cleanup;
		}
		if (gotten_size == 0) {
			// TODO: timeout in case printer crashed
		}
		packet_mark_received(pkt, gotten_size);

		read_size_raw = packet_pending_bytes(pkt);
	}

	return pkt;

cleanup:
	if (pkt != NULL)
		packet_free(pkt);
	return NULL;
}