File: libusb-utils.c

package info (click to toggle)
libinklevel 0.9.7-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,840 kB
  • sloc: sh: 4,488; ansic: 4,422; python: 44; makefile: 26
file content (678 lines) | stat: -rw-r--r-- 14,072 bytes parent folder | download | duplicates (3)
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
/* libusb-utils.c
 *
 * (c) 2014, 2015, 2019, 2022 Markus Heinz
 *
 * This software is licensed under the terms of the GPL.
 * For details see file COPYING.
 */

#include "config.h"

#include "libusb-utils.h"

#include <libusb.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

/* 
 * Initializes libusb.
 *
 * Returns USB_SUCCESS or USB_FAILURE.
 */
int init_usb() {
  int result;

  result = libusb_init(NULL); //initialize the library for the session
  
  if (result < LIBUSB_SUCCESS) {
    
#ifdef DEBUG

    printf("Init Error: %d\n", result);

#endif

    return USB_FAILURE;
  }

#ifdef DEBUG

#if (HOST_OS == LINUX)
  
  //set verbosity level to 4
  libusb_set_option(NULL, LIBUSB_OPTION_LOG_LEVEL, LIBUSB_LOG_LEVEL_DEBUG);

#endif

#endif

  return USB_SUCCESS;
}

/*
 * Deinitializes libusb.
 */
void shutdown_usb() {
  libusb_exit(NULL); //needs to be called to end the session
}

/*
 * Finds an USB printer and returns a struct describing it. If no printer is 
 * found NULL is returned.
 */
usb_printer *find_printer(int instance) {
  libusb_device **devs; //pointer to pointer of device, 
                        //used to retrieve a list of devices
  libusb_device_handle *dev_handle; //a device handle
  ssize_t cnt; //holding number of devices in list
  int i; // loop counter
  int printers_found = 0; // used for finding the correct printer
  usb_printer *printer = NULL;

  cnt = libusb_get_device_list(NULL, &devs); //get the list of devices

  if (cnt < LIBUSB_SUCCESS) {

#ifdef DEBUG

    printf( "Get device error\n");

#endif

    return NULL;
  }

#ifdef DEBUG

  printf("%d devices in list\n", (int) cnt);

#endif

  for (i = 0; i < cnt; i++) {
    if (libusb_open(devs[i], &dev_handle)) {

#ifdef DEBUG

      printf("Could not open device\n");

#endif

    } else {
      printer = check_for_printer(dev_handle);

      if (printer != NULL) {
	printers_found++;

	if (printers_found == instance + 1) {
	  printer->device = libusb_ref_device(devs[i]);
	  libusb_close(dev_handle);
	  break;
	}
      }

      libusb_close(dev_handle);
    }
  }

#ifdef DEBUG

  if (printers_found == 0) {
    printf("Cannot find printer\n");
  } else {
    printf("Printers found: %d, requested: %d\n", printers_found, instance + 1);
  }

#endif

  libusb_free_device_list(devs, 1); //free the list, unref the devices in it

  if (printers_found == instance + 1) {
    return printer;
  } else {
    return NULL;
  }
}

/*
 * Releases a device handle. Returns USB_SUCCESS or USB_FAILURE.
 */
int release_device_handle(usb_printer *printer) {
  int r;

  r = libusb_release_interface(printer->handle, printer->interface); 
  
  if (r != LIBUSB_SUCCESS) {

#ifdef DEBUG

    printf("Cannot release interface\n");

#endif

    return USB_FAILURE;
  }

#ifdef DEBUG

  printf("Released interface %d\n", printer->interface);

#endif

#if (HOST_OS == FREEBSD)

  /*
  if (!libusb_attach_kernel_driver(printer->handle, printer->interface)) {

#ifdef DEBUG

    printf("Cannot reattach kernel driver\n");

#endif

  }
  */
#endif
  
  
  libusb_close(printer->handle); //close the device we opened
  libusb_unref_device(printer->device);

#ifdef DEBUG

  printf("Device closed\n");

#endif
  
  return USB_SUCCESS;
}

/*
 * Retrieves the IEEE1284 device id. Returns USB_SUCCESS or USB_FAILURE.
 */
int get_usb_device_id(usb_printer *printer, char *buffer, size_t bufsize) {

  int length; //Length of device ID

  if (libusb_control_transfer(printer->handle,
			      LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_ENDPOINT_IN |
			      LIBUSB_RECIPIENT_INTERFACE,
			      0, printer->configuration, 
                              (printer->interface << 8) | printer->altsetting, 
			      (unsigned char *)buffer, bufsize, 5000) < 0)
    {
      *buffer = '\0';
      return USB_FAILURE;
    }

  /*
   * Extract the length of the device ID string from the first two
   * bytes.  The 1284 spec says the length is stored MSB first...
   */

  length = (((unsigned)buffer[0] & 255) << 8) |
    ((unsigned)buffer[1] & 255);

  /*
   * Check to see if the length is larger than our buffer or less than 14 bytes
   * (the minimum valid device ID is "MFG:x;MDL:y;" with 2 bytes for the 
   * length).
   *
   * If the length is out-of-range, assume that the vendor incorrectly
   * implemented the 1284 spec and re-read the length as LSB first,..
   */

  if (length > bufsize || length < 14)
    length = (((unsigned)buffer[1] & 255) << 8) |
      ((unsigned)buffer[0] & 255);

  if (length > bufsize)
    length = bufsize;

  if (length < 14)
    {
      /*
       * Invalid device ID, clear it!
       */

      *buffer = '\0';
      return USB_FAILURE;
    }

  length -= 2;

  /*
   * Copy the device ID text to the beginning of the buffer and
   * nul-terminate.
   */

  memmove(buffer, buffer + 2, length);
  buffer[length] = '\0';

  return USB_SUCCESS;
}

/*
 * Checks if the given handle belongs to a printer. If true, communication 
 * paramters for the printer will be determined and returned in a struct.
 * Otherwise NULL we be returned.
 */
usb_printer *check_for_printer(libusb_device_handle *handle) {
  libusb_device* device;
  struct libusb_device_descriptor devdesc; //Current device descriptor
  struct libusb_config_descriptor *confptr = NULL; //Pointer to current 
                                                   //configuration
  const struct libusb_interface *ifaceptr = NULL; //Pointer to current interface
  const struct libusb_interface_descriptor *altptr = NULL; //Pointer to current
                                                           //alternate setting
  const struct libusb_endpoint_descriptor *endpptr = NULL; //Pointer to current
                                                           //endpoint
  uint8_t conf,	         //Current configuration
    iface,	         //Current interface
    altset,	         //Current alternate setting
    protocol,	         //Current protocol
    endp,	         //Current endpoint
    selected_altset = 0, //Selected altset
    printer_found = 0,   //Printer found?
    read_endp,           //Read endpoint
    write_endp,          //Write endpoint
    interface = 0,       //Interface
    configuration;       //Configuration
  usb_printer *printer = NULL;

  device = libusb_get_device(handle);

  /*
   * Ignore devices with no configuration data and anything that is not
   * a printer...
   */

  if (libusb_get_device_descriptor(device, &devdesc) < LIBUSB_SUCCESS) {
    return NULL;
  }

  if (!devdesc.bNumConfigurations || !devdesc.idVendor || !devdesc.idProduct) {
    return NULL;
  }

  for (conf = 0; conf < devdesc.bNumConfigurations && !printer_found; conf++) {

    if (libusb_get_config_descriptor(device, conf, &confptr) < LIBUSB_SUCCESS) {
      return NULL;
    }

#ifdef DEBUG

    printf("configuration %d out of %d configurations\n", conf, 
           devdesc.bNumConfigurations);

#endif

    for (iface = 0; iface < confptr->bNumInterfaces && !printer_found; 
         iface++) {

      ifaceptr = &confptr->interface[iface];

#ifdef DEBUG

      printf("interface %d out of %d interfaces\n", iface, 
	     confptr->bNumInterfaces);

#endif
	
      /*
       * Some printers offer multiple interfaces...
       */

      protocol = 0;
      
      for (altset = 0; altset < ifaceptr->num_altsetting && !printer_found; 
           altset++) {

	altptr = &ifaceptr->altsetting[altset];

#ifdef DEBUG

	printf("altset %d out of %d altsets\n", altset, 
	       ifaceptr->num_altsetting);

#endif

	assert(altptr != NULL);

	/*
	 * Currently we only support unidirectional and bidirectional
	 * printers.  Future versions of this code will support the
	 * 1284.4 (packet mode) protocol as well.
	 */
	
#ifdef DEBUG

	printf ("interface class: %d\ninterface subclass: %d\n", 
		altptr->bInterfaceClass, altptr->bInterfaceSubClass);
	printf("interface protocol: %d\n",  altptr->bInterfaceProtocol);

#endif

	if (((altptr->bInterfaceClass != LIBUSB_CLASS_PRINTER ||
	      altptr->bInterfaceSubClass != 1)) ||
	    (altptr->bInterfaceProtocol != 1 &&	/* Unidirectional */
	     altptr->bInterfaceProtocol != 2) ||	/* Bidirectional */
	    altptr->bInterfaceProtocol < protocol) {
	  continue;
	}

	read_endp  = -1;
	write_endp = -1;
	
	for (endp = 0; endp < altptr->bNumEndpoints; endp++) {
	  
	  endpptr = &altptr->endpoint[endp];

	  if ((endpptr->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) ==
	      LIBUSB_TRANSFER_TYPE_BULK) {
	    if (endpptr->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) {
	      read_endp = endpptr->bEndpointAddress; 
	    } else {
	      write_endp = endpptr->bEndpointAddress;
	    }

	    interface = altptr->bInterfaceNumber;
	    selected_altset = altptr->bAlternateSetting;
	    printer_found = 1;
	  }
	}

	if (printer_found) {
	  /*
	   * Save the best match so far...
	   */
		  
	  protocol = altptr->bInterfaceProtocol;
          configuration = confptr->bConfigurationValue;

#ifdef DEBUG

	  printf("write endpoint is %d\n", write_endp);

	  if (protocol > 1)
	    printf("read endpoint is %d\n", read_endp);
          
          printf("configuration selected for communication: %d\n", 
                 configuration);
	  printf("interface selected for communication: %d\n", interface);
	  printf("alt setting selected for communication: %d\n", 
		 selected_altset);

#endif

	  printer = (usb_printer *) malloc(sizeof(usb_printer));
	  
	  if (printer != NULL) {
	    printer->handle = handle;
	    printer->read_endp = read_endp;
	    printer->write_endp = write_endp;
	    printer->interface = interface;
	    printer->altsetting = selected_altset;
            printer->configuration = configuration;
	  }

	  break;

	}
      }
    }

    libusb_free_config_descriptor(confptr);

  }

  return printer;
}

/*
 * Opens the given printer. Then the according interface is claimed and the 
 * appropiate configuration is selected. 
 * 
 * Returns USB_SUCCESS or USB_FAILURE.
 */
int open_device_handle(usb_printer *printer) {
  int r;
  int currentConfig;
  
  if (printer != NULL && printer->device != NULL) {
    if (libusb_open(printer->device, &printer->handle) == LIBUSB_SUCCESS) {

#ifdef DEBUG

      printf("Device opened\n");

#endif

#if (HOST_OS == LINUX)

      if (libusb_set_auto_detach_kernel_driver(printer->handle, 1) != 
	  LIBUSB_SUCCESS) {

#ifdef DEBUG

	printf("Could not set auto detach for kernel driver\n");

#endif

      }

#elif (HOST_OS == FREEBSD)
      /*
      if (libusb_kernel_driver_active(printer->handle, printer->interface)) {
        if (libusb_detach_kernel_driver(printer->handle, 
                                           printer->interface) 
            != LIBUSB_SUCCESS) {

#ifdef DEBUG

          printf("Could not detach kernel driver\n");

#endif

        }
      }
      */
#endif

#ifdef DEBUG

      printf("Trying to set configuration %d\n", printer->configuration);

#endif

      assert(printer->handle != NULL);

      r = libusb_get_configuration(printer->handle, &currentConfig);

      if (r < LIBUSB_SUCCESS) {

#ifdef DEBUG

        printf("Cannot get configuration: error %d\n", r);
        
#endif
        
        return USB_FAILURE;
      } else if (currentConfig == printer->configuration) {

#ifdef DEBUG

        printf("Configuration is already correctly\n");

#endif

      } else {
      
        r = libusb_set_configuration(printer->handle, printer->configuration);

        if (r < LIBUSB_SUCCESS) {

#ifdef DEBUG

          printf("Cannot set configuration: error %d\n", r);

#endif

        }
      }
      
#ifdef DEBUG

      printf("Trying to claim interface %d\n", printer->interface);

#endif
      r = libusb_claim_interface(printer->handle, printer->interface);

      if (r < LIBUSB_SUCCESS) {

#ifdef DEBUG

	printf("Cannot claim interface: error %d\n", r);

#endif

#if (HOST_OS == FREEBSD)

        /*
        if (!libusb_attach_kernel_driver(printer->handle, printer->interface)) {

#ifdef DEBUG

          printf("Cannot reattach kernel driver\n");

#endif

        }
        */

#endif

	libusb_close(printer->handle);
	
#ifdef DEBUG

	printf("Device closed\n");

#endif

	return USB_FAILURE;
      }
      
#ifdef DEBUG

      printf("Claimed interface %d\n", printer->interface);

#endif
  
      r = libusb_set_interface_alt_setting(printer->handle, printer->interface, 
					 printer->altsetting);

      if (r < LIBUSB_SUCCESS) {

#ifdef DEBUG

	printf("Cannot activate alternate setting: error %d\n", r);

#endif

	r = libusb_release_interface(printer->handle, printer->interface);

#ifdef DEBUG

	if (r < LIBUSB_SUCCESS) {
	  printf("Could not release interface %d: error %d\n", 
		 printer->interface, r);
	}

#endif
	
#if (HOST_OS == FREEBSD)

        /*
        if (!libusb_attach_kernel_driver(printer->handle, printer->interface)) {

#ifdef DEBUG

          printf("Cannot reattach kernel driver\n");
          
#endif

        }
        */

#endif

	libusb_close(printer->handle);

#ifdef DEBUG

	printf("Device closed\n");

#endif

	return USB_FAILURE;
      }
      
#ifdef DEBUG

      printf("Activated alternate setting %d for interface %d\n", 
	     printer->altsetting, printer->interface);

#endif
    
      return USB_SUCCESS;
    } else {
     
#ifdef DEBUG

      printf("Could not open printer\n");

#endif

      return USB_FAILURE;
    }  
  } else {
    
#ifdef DEBUG

    printf ("printer is null or device is null\n");

#endif

    return USB_FAILURE;    

  }
}

/*
 * Transfers data to or from a device. The number of transfered bytes will be
 * stored in transfered. The direction is determined by the endpoint.
 *
 *  Returns USB_SUCCESS or USB_FAILURE.
 */
int bulk_transfer(libusb_device_handle *handle, uint8_t endp,
		  char *buffer, size_t bufsize, int *transfered) {

  int result = libusb_bulk_transfer (handle, endp, (unsigned char *) buffer, 
				     bufsize, transfered, USB_TIMEOUT);
    if (result == LIBUSB_SUCCESS) {
      return USB_SUCCESS;
    } else {

#ifdef DEBUG

      printf("Data transfer failed: %d\n", result);

#endif

      return USB_FAILURE;
    }
}