-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathusb_modeswitch.c
2025 lines (1772 loc) · 62.1 KB
/
usb_modeswitch.c
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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Mode switching tool for controlling mode of 'multi-state' USB devices
Version 2.2.0, 2014/05/29
Copyright (C) 2007 - 2014 Josua Dietze (mail to "digidietze" at the domain
of the home page; or write a personal message through the forum to "Josh".
NO SUPPORT VIA E-MAIL - please use the forum for that)
Major contributions:
Command line parsing, decent usage/config output/handling, bugfixes and advanced
options added by:
Joakim Wennergren
TargetClass parameter implementation to support new Option devices/firmware:
Paul Hardwick (http://www.pharscape.org)
Created with initial help from:
"usbsnoop2libusb.pl" by Timo Lindfors (http://iki.fi/lindi/usb/usbsnoop2libusb.pl)
Config file parsing stuff borrowed from:
Guillaume Dargaud (http://www.gdargaud.net/Hack/SourceCode.html)
Hexstr2bin function borrowed from:
Jouni Malinen (http://hostap.epitest.fi/wpa_supplicant, from "common.c")
Other contributions: see README
Device information contributors are named in the "device_reference.txt" file. See
homepage.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details:
http://www.gnu.org/licenses/gpl.txt
*/
/* Recommended tab size: 4 */
#define VERSION "2.2.0"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <ctype.h>
#include <getopt.h>
#include <syslog.h>
#include <unistd.h>
#include "usb_modeswitch.h"
/* libusb 1.0 wrappers, lazy leftover */
int usb_bulk_io(struct libusb_device_handle *handle, int ep, char *bytes,
int size, int timeout)
{
int actual_length;
int r;
// usbi_dbg("endpoint %x size %d timeout %d", ep, size, timeout);
r = libusb_bulk_transfer(handle, ep & 0xff, (unsigned char *)bytes, size,
&actual_length, timeout);
/* if we timed out but did transfer some data, report as successful short
* read. FIXME: is this how libusb-0.1 works? */
if (r == 0 || (r == LIBUSB_ERROR_TIMEOUT && actual_length > 0))
return actual_length;
return r;
}
static int usb_interrupt_io(libusb_device_handle *handle, int ep, char *bytes,
int size, int timeout)
{
int actual_length;
int r;
// usbi_dbg("endpoint %x size %d timeout %d", ep, size, timeout);
r = libusb_interrupt_transfer(handle, ep & 0xff, (unsigned char *)bytes, size,
&actual_length, timeout);
/* if we timed out but did transfer some data, report as successful short
* read. FIXME: is this how libusb-0.1 works? */
if (r == 0 || (r == LIBUSB_ERROR_TIMEOUT && actual_length > 0))
return actual_length;
return (r);
}
#define LINE_DIM 1024
#define MAXLINES 50
#define BUF_SIZE 4096
#define DESCR_MAX 129
#define SEARCH_DEFAULT 0
#define SEARCH_TARGET 1
#define SEARCH_BUSDEV 2
#define SWITCH_CONFIG_MAXTRIES 5
#define SHOW_PROGRESS if (show_progress) fprintf
char *TempPP=NULL;
static struct libusb_context *ctx = NULL;
static struct libusb_device *dev;
static struct libusb_device_handle *devh;
static struct libusb_config_descriptor *active_config = NULL;
int DefaultVendor=0, DefaultProduct=0, TargetVendor=0, TargetProduct=-1, TargetClass=0;
int MessageEndpoint=0, ResponseEndpoint=0, ReleaseDelay=0;
int targetDeviceCount=0, searchMode;
int devnum=-1, busnum=-1;
int ret;
unsigned int ModeMap = 0;
#define DETACHONLY_MODE 0x00000001
#define HUAWEI_MODE 0x00000002
#define SIERRA_MODE 0x00000004
#define SONY_MODE 0x00000008
#define GCT_MODE 0x00000010
#define KOBIL_MODE 0x00000020
#define SEQUANS_MODE 0x00000040
#define MOBILEACTION_MODE 0x00000080
#define CISCO_MODE 0x00000100
#define QISDA_MODE 0x00000200
#define QUANTA_MODE 0x00000400
#define BLACKBERRY_MODE 0x00000800
#define PANTECH_MODE 0x00001000
#define HUAWEINEW_MODE 0x00002000
char verbose=0, show_progress=1, ResetUSB=0, CheckSuccess=0, config_read=0;
char NeedResponse=0, NoDriverLoading=0, InquireDevice=0, sysmode=0, mbim=0;
char StandardEject=0;
char imanufact[DESCR_MAX], iproduct[DESCR_MAX], iserial[DESCR_MAX];
char MessageContent[LINE_DIM];
char MessageContent2[LINE_DIM];
char MessageContent3[LINE_DIM];
char TargetProductList[LINE_DIM];
char DefaultProductList[5];
char ByteString[LINE_DIM/2];
char buffer[BUF_SIZE];
FILE *output;
/* Settable Interface and Configuration (for debugging mostly) (jmw) */
int Interface = -1, Configuration = 0, AltSetting = -1;
static struct option long_options[] = {
{"help", no_argument, 0, 'h'},
{"version", no_argument, 0, 'e'},
{"default-vendor", required_argument, 0, 'v'},
{"default-product", required_argument, 0, 'p'},
{"target-vendor", required_argument, 0, 'V'},
{"target-product", required_argument, 0, 'P'},
{"target-class", required_argument, 0, 'C'},
{"message-endpoint", required_argument, 0, 'm'},
{"message-content", required_argument, 0, 'M'},
{"message-content2", required_argument, 0, '2'},
{"message-content3", required_argument, 0, '3'},
{"release-delay", required_argument, 0, 'w'},
{"response-endpoint", required_argument, 0, 'r'},
{"bus-num", required_argument, 0, 'b'},
{"device-num", required_argument, 0, 'g'},
{"detach-only", no_argument, 0, 'd'},
{"huawei-mode", no_argument, 0, 'H'},
{"sierra-mode", no_argument, 0, 'S'},
{"sony-mode", no_argument, 0, 'O'},
{"qisda-mode", no_argument, 0, 'B'},
{"quanta-mode", no_argument, 0, 'E'},
{"kobil-mode", no_argument, 0, 'T'},
{"gct-mode", no_argument, 0, 'G'},
{"sequans-mode", no_argument, 0, 'N'},
{"mobileaction-mode", no_argument, 0, 'A'},
{"cisco-mode", no_argument, 0, 'L'},
{"blackberry-mode", no_argument, 0, 'Z'},
{"pantech-mode", no_argument, 0, 'F'},
{"std-eject", no_argument, 0, 'K'},
{"need-response", no_argument, 0, 'n'},
{"reset-usb", no_argument, 0, 'R'},
{"config-file", required_argument, 0, 'c'},
{"verbose", no_argument, 0, 'W'},
{"quiet", no_argument, 0, 'Q'},
{"sysmode", no_argument, 0, 'D'},
{"inquire", no_argument, 0, 'I'},
{"stdinput", no_argument, 0, 't'},
{"find-mbim", no_argument, 0, 'j'},
{"long-config", required_argument, 0, 'f'},
{"check-success", required_argument, 0, 's'},
{"interface", required_argument, 0, 'i'},
{"configuration", required_argument, 0, 'u'},
{"altsetting", required_argument, 0, 'a'},
{0, 0, 0, 0}
};
void readConfigFile(const char *configFilename)
{
ParseParamHex(configFilename, TargetVendor);
ParseParamHex(configFilename, TargetProduct);
ParseParamString(configFilename, TargetProductList);
ParseParamHex(configFilename, TargetClass);
ParseParamHex(configFilename, DefaultVendor);
ParseParamHex(configFilename, DefaultProduct);
ParseParamBoolMap(configFilename, DetachStorageOnly, ModeMap, DETACHONLY_MODE);
ParseParamBoolMap(configFilename, HuaweiMode, ModeMap, HUAWEI_MODE);
ParseParamBoolMap(configFilename, HuaweiNewMode, ModeMap, HUAWEINEW_MODE);
ParseParamBoolMap(configFilename, SierraMode, ModeMap, SIERRA_MODE);
ParseParamBoolMap(configFilename, SonyMode, ModeMap, SONY_MODE);
ParseParamBoolMap(configFilename, GCTMode, ModeMap, GCT_MODE);
ParseParamBoolMap(configFilename, KobilMode, ModeMap, KOBIL_MODE);
ParseParamBoolMap(configFilename, SequansMode, ModeMap, SEQUANS_MODE);
ParseParamBoolMap(configFilename, MobileActionMode, ModeMap, MOBILEACTION_MODE);
ParseParamBoolMap(configFilename, CiscoMode, ModeMap, CISCO_MODE);
ParseParamBoolMap(configFilename, QisdaMode, ModeMap, QISDA_MODE);
ParseParamBoolMap(configFilename, QuantaMode, ModeMap, QUANTA_MODE);
ParseParamBoolMap(configFilename, BlackberryMode, ModeMap, BLACKBERRY_MODE);
ParseParamBoolMap(configFilename, PantechMode, ModeMap, PANTECH_MODE);
ParseParamBool(configFilename, StandardEject);
ParseParamBool(configFilename, NoDriverLoading);
ParseParamHex(configFilename, MessageEndpoint);
ParseParamString(configFilename, MessageContent);
ParseParamString(configFilename, MessageContent2);
ParseParamString(configFilename, MessageContent3);
ParseParamInt(configFilename, ReleaseDelay);
ParseParamHex(configFilename, NeedResponse);
ParseParamHex(configFilename, ResponseEndpoint);
ParseParamHex(configFilename, ResetUSB);
ParseParamHex(configFilename, InquireDevice);
ParseParamInt(configFilename, CheckSuccess);
ParseParamHex(configFilename, Interface);
ParseParamHex(configFilename, Configuration);
ParseParamHex(configFilename, AltSetting);
/* TargetProductList has priority over TargetProduct */
if (TargetProduct != -1 && TargetProductList[0] != '\0') {
TargetProduct = -1;
SHOW_PROGRESS(output,"Warning: TargetProductList overrides TargetProduct!\n");
}
config_read = 1;
}
void printConfig()
{
if ( DefaultVendor )
fprintf (output,"DefaultVendor= 0x%04x\n", DefaultVendor);
if ( DefaultProduct )
fprintf (output,"DefaultProduct= 0x%04x\n", DefaultProduct);
if ( TargetVendor )
fprintf (output,"TargetVendor= 0x%04x\n", TargetVendor);
if ( TargetProduct > -1 )
fprintf (output,"TargetProduct= 0x%04x\n", TargetProduct);
if ( TargetClass )
fprintf (output,"TargetClass= 0x%02x\n", TargetClass);
if ( strlen(TargetProductList) )
fprintf (output,"TargetProductList=\"%s\"\n", TargetProductList);
if (StandardEject)
fprintf (output,"\nStandardEject=1\n");
if (ModeMap & DETACHONLY_MODE)
fprintf (output,"\nDetachStorageOnly=1\n");
if (ModeMap & HUAWEI_MODE)
fprintf (output,"HuaweiMode=1\n");
if (ModeMap & HUAWEINEW_MODE)
fprintf (output,"HuaweiNewMode=1\n");
if (ModeMap & SIERRA_MODE)
fprintf (output,"SierraMode=1\n");
if (ModeMap & SONY_MODE)
fprintf (output,"SonyMode=1\n");
if (ModeMap & QISDA_MODE)
fprintf (output,"QisdaMode=1\n");
if (ModeMap & QUANTA_MODE)
fprintf (output,"QuantaMode=1\n");
if (ModeMap & GCT_MODE)
fprintf (output,"GCTMode=1\n");
if (ModeMap & KOBIL_MODE)
fprintf (output,"KobilMode=1\n");
if (ModeMap & SEQUANS_MODE)
fprintf (output,"SequansMode=1\n");
if (ModeMap & MOBILEACTION_MODE)
fprintf (output,"MobileActionMode=1\n");
if (ModeMap & CISCO_MODE)
fprintf (output,"CiscoMode=1\n");
if (ModeMap & BLACKBERRY_MODE)
fprintf (output,"BlackberryMode=1\n");
if (ModeMap & PANTECH_MODE)
fprintf (output,"PantechMode=1\n");
if ( MessageEndpoint )
fprintf (output,"MessageEndpoint=0x%02x\n", MessageEndpoint);
if ( strlen(MessageContent) )
fprintf (output,"MessageContent=\"%s\"\n", MessageContent);
if ( strlen(MessageContent2) )
fprintf (output,"MessageContent2=\"%s\"\n", MessageContent2);
if ( strlen(MessageContent3) )
fprintf (output,"MessageContent3=\"%s\"\n", MessageContent3);
fprintf (output,"NeedResponse=%i\n", (int)NeedResponse);
if ( ResponseEndpoint )
fprintf (output,"ResponseEndpoint=0x%02x\n", ResponseEndpoint);
if ( Interface > -1 )
fprintf (output,"Interface=0x%02x\n", Interface);
if ( Configuration > 0 )
fprintf (output,"Configuration=0x%02x\n", Configuration);
if ( AltSetting > -1 )
fprintf (output,"AltSetting=0x%02x\n", AltSetting);
if ( InquireDevice )
fprintf (output,"\nInquireDevice=1\n");
if ( CheckSuccess )
fprintf (output,"Success check enabled, max. wait time %d seconds\n", CheckSuccess);
if ( sysmode )
fprintf (output,"System integration mode enabled\n");
}
int readArguments(int argc, char **argv)
{
int c, option_index = 0, count=0;
char *longConfig = NULL;
if (argc==1)
{
printHelp();
printVersion();
exit(1);
}
while (1)
{
c = getopt_long (argc, argv, "hejWQDndKHJSOBEGTNALZFRItv:p:V:P:C:m:M:2:3:w:r:c:i:u:a:s:f:b:g:",
long_options, &option_index);
/* Detect the end of the options. */
if (c == -1)
break;
count++;
switch (c)
{
case 'R': ResetUSB = 1; break;
case 'v': DefaultVendor = strtol(optarg, NULL, 16); break;
case 'p': DefaultProduct = strtol(optarg, NULL, 16); break;
case 'V': TargetVendor = strtol(optarg, NULL, 16); break;
case 'P': TargetProduct = strtol(optarg, NULL, 16); break;
case 'C': TargetClass = strtol(optarg, NULL, 16); break;
case 'm': MessageEndpoint = strtol(optarg, NULL, 16); break;
case 'M': strncpy(MessageContent, optarg, LINE_DIM); break;
case '2': strncpy(MessageContent2, optarg, LINE_DIM); break;
case '3': strncpy(MessageContent3, optarg, LINE_DIM); break;
case 'w': ReleaseDelay = strtol(optarg, NULL, 10); break;
case 'n': NeedResponse = 1; break;
case 'r': ResponseEndpoint = strtol(optarg, NULL, 16); break;
case 'K': StandardEject = 1; break;
case 'd': ModeMap = ModeMap + DETACHONLY_MODE; break;
case 'H': ModeMap = ModeMap + HUAWEI_MODE; break;
case 'J': ModeMap = ModeMap + HUAWEINEW_MODE; break;
case 'S': ModeMap = ModeMap + SIERRA_MODE; break;
case 'O': ModeMap = ModeMap + SONY_MODE; break;; break;
case 'B': ModeMap = ModeMap + QISDA_MODE; break;
case 'E': ModeMap = ModeMap + QUANTA_MODE; break;
case 'G': ModeMap = ModeMap + GCT_MODE; break;
case 'T': ModeMap = ModeMap + KOBIL_MODE; break;
case 'N': ModeMap = ModeMap + SEQUANS_MODE; break;
case 'A': ModeMap = ModeMap + MOBILEACTION_MODE; break;
case 'L': ModeMap = ModeMap + CISCO_MODE; break;
case 'Z': ModeMap = ModeMap + BLACKBERRY_MODE; break;
case 'F': ModeMap = ModeMap + PANTECH_MODE; break;
case 'c': readConfigFile(optarg); break;
case 't': readConfigFile("stdin"); break;
case 'W': verbose = 1; show_progress = 1; count--; break;
case 'Q': show_progress = 0; verbose = 0; count--; break;
case 'D': sysmode = 1; count--; break;
case 's': CheckSuccess = strtol(optarg, NULL, 10); count--; break;
case 'I': InquireDevice = 1; break;
case 'b': busnum = strtol(optarg, NULL, 10); break;
case 'g': devnum = strtol(optarg, NULL, 10); break;
case 'i': Interface = strtol(optarg, NULL, 16); break;
case 'u': Configuration = strtol(optarg, NULL, 16); break;
case 'a': AltSetting = strtol(optarg, NULL, 16); break;
case 'j': mbim = 1; break;
case 'f':
longConfig = malloc(strlen(optarg)+5);
strcpy(longConfig,"##\n");
strcat(longConfig,optarg);
strcat(longConfig,"\n");
readConfigFile(longConfig);
free(longConfig);
break;
case 'e':
printVersion();
exit(0);
break;
case 'h':
printVersion();
printHelp();
exit(0);
break;
default: /* Unsupported - error message has already been printed */
fprintf (output,"\n");
printHelp();
exit(1);
}
}
return count;
}
int main(int argc, char **argv)
{
int numDefaults=0, sonySuccess=0;
int currentConfig=0, defaultClass=0, interfaceClass=0;
struct libusb_device_descriptor descriptor;
/* Make sure we have empty strings even if not set by config */
TargetProductList[0] = '\0';
MessageContent[0] = '\0';
MessageContent2[0] = '\0';
MessageContent3[0] = '\0';
DefaultProductList[0] = '\0';
/* Useful for debugging during boot */
// output=fopen("/dev/console", "w");
output=stdout;
signal(SIGTERM, release_usb_device);
/*
* Parameter parsing, USB preparation/diagnosis, plausibility checks
*/
/* Check command arguments, use params instead of config file when given */
switch (readArguments(argc, argv)) {
case 0: /* no argument or -W, -q or -s */
break;
default: /* one or more arguments except -W, -q or -s */
if (!config_read) /* if arguments contain -c, the config file was already processed */
if (verbose) fprintf(output,"Take all parameters from the command line\n\n");
}
if (verbose) {
printVersion();
printConfig();
fprintf(output,"\n");
}
/* Some sanity checks. The default IDs are mandatory */
if (!(DefaultVendor && DefaultProduct)) {
SHOW_PROGRESS(output,"No default vendor/product ID given. Abort\n\n");
exit(1);
}
if (strlen(MessageContent)) {
if (strlen(MessageContent) % 2 != 0) {
fprintf(stderr, "Error: MessageContent hex string has uneven length. Abort\n\n");
exit(1);
}
if ( hexstr2bin(MessageContent, ByteString, strlen(MessageContent)/2) == -1) {
fprintf(stderr, "Error: MessageContent %s\n is not a hex string. Abort\n\n", MessageContent);
exit(1);
}
}
if (devnum == -1) {
searchMode = SEARCH_DEFAULT;
} else {
SHOW_PROGRESS(output,"Use given bus/device number: %03d/%03d ...\n", busnum, devnum);
searchMode = SEARCH_BUSDEV;
}
if (show_progress)
if (CheckSuccess && !(TargetVendor || TargetProduct > -1 || TargetProductList[0] != '\0') && !TargetClass)
fprintf(output,"Note: No target parameter given; success check limited\n");
if (TargetProduct > -1 && TargetProductList[0] == '\0') {
sprintf(TargetProductList,"%04x",TargetProduct);
TargetProduct = -1;
}
/* libusb initialization */
libusb_init(&ctx);
if (verbose)
libusb_set_debug(ctx, 3);
if (mbim) {
printf("%d\n", findMBIMConfig(DefaultVendor, DefaultProduct, searchMode) );
exit(0);
}
/* Count existing target devices, remember for success check */
if (searchMode != SEARCH_BUSDEV && (TargetVendor || TargetClass)) {
SHOW_PROGRESS(output,"Look for target devices ...\n");
search_devices(&targetDeviceCount, TargetVendor, TargetProductList, TargetClass, 0, SEARCH_TARGET);
if (targetDeviceCount) {
SHOW_PROGRESS(output," Found devices in target mode or class (%d)\n", targetDeviceCount);
} else
SHOW_PROGRESS(output," No devices in target mode or class found\n");
}
/* Count default devices, get the last one found */
SHOW_PROGRESS(output,"Look for default devices ...\n");
sprintf(DefaultProductList,"%04x",DefaultProduct);
dev = search_devices(&numDefaults, DefaultVendor, DefaultProductList, TargetClass, Configuration, searchMode);
if (numDefaults) {
SHOW_PROGRESS(output," Found devices in default mode (%d)\n", numDefaults);
} else {
SHOW_PROGRESS(output," No devices in default mode found. Nothing to do. Bye!\n\n");
exit(0);
}
if (dev == NULL) {
SHOW_PROGRESS(output," No bus/device match. Is device connected? Abort\n\n");
exit(0);
} else {
if (devnum == -1) {
devnum = libusb_get_device_address(dev);
busnum = libusb_get_bus_number(dev);
SHOW_PROGRESS(output,"Access device %03d on bus %03d\n", devnum, busnum);
}
libusb_open(dev, &devh);
if (devh == NULL) {
SHOW_PROGRESS(output,"Error opening the device. Abort\n\n");
exit(1);
}
}
libusb_get_active_config_descriptor(dev, &active_config);
/* Get current configuration of default device if parameter is set */
if (Configuration > -1) {
currentConfig = active_config->bConfigurationValue;
SHOW_PROGRESS(output,"Current configuration number is %d\n", currentConfig);
} else
currentConfig = 0;
libusb_get_device_descriptor(dev, &descriptor);
defaultClass = descriptor.bDeviceClass;
if (Interface == -1)
Interface = active_config->interface[0].altsetting[0].bInterfaceNumber;
SHOW_PROGRESS(output,"Use interface number %d\n", Interface);
/* Get class of default device/interface */
interfaceClass = get_interface_class();
/* Check or get endpoints */
if (strlen(MessageContent) || StandardEject || InquireDevice || ModeMap & CISCO_MODE || ModeMap & HUAWEINEW_MODE) {
if (!MessageEndpoint)
MessageEndpoint = find_first_bulk_endpoint(LIBUSB_ENDPOINT_OUT);
if (!ResponseEndpoint)
ResponseEndpoint = find_first_bulk_endpoint(LIBUSB_ENDPOINT_IN);
libusb_free_config_descriptor(active_config);
if (!MessageEndpoint) {
fprintf(stderr,"Error: message endpoint not given or found. Abort\n\n");
exit(1);
}
if (!ResponseEndpoint) {
fprintf(stderr,"Error: response endpoint not given or found. Abort\n\n");
exit(1);
}
SHOW_PROGRESS(output,"Use endpoints 0x%02x (out) and 0x%02x (in)\n", MessageEndpoint, ResponseEndpoint);
} else
libusb_free_config_descriptor(active_config);
if (interfaceClass == -1) {
fprintf(stderr, "Error: Could not get class of interface %d. Does it exist? Abort\n\n",Interface);
exit(1);
}
if (defaultClass == 0)
defaultClass = interfaceClass;
else
if (interfaceClass == 8 && defaultClass != 8) {
/* Weird device with default class other than 0 and differing interface class */
SHOW_PROGRESS(output,"Ambiguous Class/InterfaceClass: 0x%02x/0x08\n", defaultClass);
defaultClass = 8;
}
if (strlen(MessageContent) && strncmp("55534243",MessageContent,8) == 0)
if (defaultClass != 8) {
fprintf(stderr, "Error: can't use storage command in MessageContent with interface %d;\n"
" interface class is %d, expected 8. Abort\n\n", Interface, defaultClass);
exit(1);
}
if (InquireDevice && show_progress) {
if (defaultClass == 0x08) {
SHOW_PROGRESS(output,"Inquire device details; driver will be detached ...\n");
detachDriver();
if (deviceInquire() >= 0)
InquireDevice = 2;
} else
SHOW_PROGRESS(output,"Not a storage device, skip SCSI inquiry\n");
}
deviceDescription();
if (show_progress) {
fprintf(output,"\nUSB description data (for identification)\n");
fprintf(output,"-------------------------\n");
fprintf(output,"Manufacturer: %s\n", imanufact);
fprintf(output," Product: %s\n", iproduct);
fprintf(output," Serial No.: %s\n", iserial);
fprintf(output,"-------------------------\n");
}
/* Special modes are exclusive, so check for illegal combinations.
* More than one bit set?
*/
if ( ModeMap & (ModeMap-1) ) {
fprintf(output,"Multiple special modes selected; check configuration. Abort\n\n");
exit(1);
}
if ((strlen(MessageContent) || StandardEject) && ModeMap ) {
MessageContent[0] = '\0';
StandardEject = 0;
fprintf(output,"Warning: MessageContent/StandardEject ignored; can't combine with special mode\n");
}
if (StandardEject && (strlen(MessageContent2) || strlen(MessageContent3))) {
fprintf(output,"Warning: MessageContent2/3 ignored; only one allowed with StandardEject\n");
}
if ( !ModeMap && !strlen(MessageContent) && AltSetting == -1 && !Configuration && !StandardEject )
SHOW_PROGRESS(output,"Warning: no switching method given. See documentation\n");
/*
* The switching actions
*/
if (sysmode) {
openlog("usb_modeswitch", 0, LOG_SYSLOG);
syslog(LOG_NOTICE, "switch device %04x:%04x on %03d/%03d", DefaultVendor, DefaultProduct, busnum, devnum);
}
if (ModeMap & DETACHONLY_MODE) {
SHOW_PROGRESS(output,"Detach storage driver as switching method ...\n");
if (InquireDevice == 2) {
SHOW_PROGRESS(output," Any driver was already detached for inquiry. Do nothing\n");
} else {
ret = detachDriver();
if (ret == 2)
SHOW_PROGRESS(output," You may want to remove the storage driver manually\n");
}
}
if(ModeMap & HUAWEI_MODE) {
switchHuaweiMode();
}
if(ModeMap & SIERRA_MODE) {
switchSierraMode();
}
if(ModeMap & GCT_MODE) {
detachDriver();
switchGCTMode();
}
if(ModeMap & QISDA_MODE) {
switchQisdaMode();
}
if(ModeMap & KOBIL_MODE) {
detachDriver();
switchKobilMode();
}
if(ModeMap & QUANTA_MODE) {
switchQuantaMode();
}
if(ModeMap & SEQUANS_MODE) {
switchSequansMode();
}
if(ModeMap & MOBILEACTION_MODE) {
switchActionMode();
}
if(ModeMap & CISCO_MODE) {
detachDriver();
switchCiscoMode();
}
if(ModeMap & BLACKBERRY_MODE) {
detachDriver();
switchBlackberryMode();
}
if(ModeMap & PANTECH_MODE) {
detachDriver();
switchPantechMode();
}
if(ModeMap & SONY_MODE) {
if (CheckSuccess)
SHOW_PROGRESS(output,"Note: CheckSuccess ignored; Sony mode does separate checks\n");
CheckSuccess = 0; /* separate and implied success control */
sonySuccess = switchSonyMode();
}
if (StandardEject) {
SHOW_PROGRESS(output,"Sending standard EJECT sequence\n");
detachDriver();
if (MessageContent[0] != '\0')
strcpy(MessageContent3, MessageContent);
else
MessageContent3[0] = '\0';
strcpy(MessageContent,"5553424312345678000000000000061e000000000000000000000000000000");
strcpy(MessageContent2,"5553424312345679000000000000061b000000020000000000000000000000");
NeedResponse = 1;
switchSendMessage();
} else if (ModeMap & HUAWEINEW_MODE) {
SHOW_PROGRESS(output,"Using standard Huawei switching message\n");
detachDriver();
strcpy(MessageContent,"55534243123456780000000000000011062000000101000100000000000000");
NeedResponse = 0;
switchSendMessage();
} else if (strlen(MessageContent)) {
if (InquireDevice != 2)
detachDriver();
switchSendMessage();
}
if (Configuration > 0) {
if (currentConfig != Configuration) {
if (switchConfiguration()) {
currentConfig = get_current_configuration(dev);
if (currentConfig == Configuration) {
SHOW_PROGRESS(output,"The configuration was set successfully\n");
} else {
SHOW_PROGRESS(output,"Changing the configuration has failed\n");
}
}
} else {
SHOW_PROGRESS(output,"Target configuration %d found. Do nothing\n", currentConfig);
}
}
if (AltSetting != -1) {
switchAltSetting();
}
/* No "removal" check if these are set */
if ((Configuration > 0 || AltSetting > -1) && !ResetUSB) {
libusb_close(devh);
devh = 0;
}
if (ResetUSB) {
resetUSB();
devh = 0;
}
if (CheckSuccess) {
if (searchMode == SEARCH_BUSDEV && sysmode) {
SHOW_PROGRESS(output,"Bus/dev search active, refer success check to wrapper. Bye!\n\n");
printf("ok:busdev\n");
goto CLOSING;
}
if (checkSuccess()) {
if (sysmode) {
if (NoDriverLoading)
printf("ok:\n");
else
if (TargetProduct < 1)
printf("ok:no_data\n");
else
printf("ok:%04x:%04x\n", TargetVendor, TargetProduct);
}
} else
if (sysmode)
printf("fail:\n");
} else {
if (ModeMap & SONY_MODE)
if (sonySuccess) {
if (sysmode) {
syslog(LOG_NOTICE, "switched S.E. MD400 to modem mode");
printf("ok:\n"); /* ACM device, no driver action */
}
SHOW_PROGRESS(output,"-> device should be stable now. Bye!\n\n");
} else {
if (sysmode)
printf("fail:\n");
SHOW_PROGRESS(output,"-> switching was probably not completed. Bye!\n\n");
}
else
SHOW_PROGRESS(output,"-> Run lsusb to note any changes. Bye!\n\n");
}
CLOSING:
if (sysmode)
closelog();
if (devh)
libusb_close(devh);
exit(0);
}
/* Get descriptor strings if available (identification details) */
void deviceDescription ()
{
char* c;
memset (imanufact, ' ', DESCR_MAX);
memset (iproduct, ' ', DESCR_MAX);
memset (iserial, ' ', DESCR_MAX);
struct libusb_device_descriptor descriptor;
libusb_get_device_descriptor(dev, &descriptor);
int iManufacturer = descriptor.iManufacturer;
int iProduct = descriptor.iProduct;
int iSerialNumber = descriptor.iSerialNumber;
if (iManufacturer) {
ret = libusb_get_string_descriptor_ascii(devh, iManufacturer, (unsigned char *)imanufact, DESCR_MAX);
if (ret < 0)
fprintf(stderr, "Error: could not get description string \"manufacturer\"\n");
} else
strcpy(imanufact, "not provided");
c = strstr(imanufact, " ");
if (c)
memset((void*)c, '\0', 1);
if (iProduct) {
ret = libusb_get_string_descriptor_ascii(devh, iProduct, (unsigned char *)iproduct, DESCR_MAX);
if (ret < 0)
fprintf(stderr, "Error: could not get description string \"product\"\n");
} else
strcpy(iproduct, "not provided");
c = strstr(iproduct, " ");
if (c)
memset((void*)c, '\0', 1);
if (iSerialNumber) {
ret = libusb_get_string_descriptor_ascii(devh, iSerialNumber, (unsigned char *)iserial, DESCR_MAX);
if (ret < 0)
fprintf(stderr, "Error: could not get description string \"serial number\"\n");
} else
strcpy(iserial, "not provided");
c = strstr(iserial, " ");
if (c)
memset((void*)c, '\0', 1);
}
/* Print result of SCSI command INQUIRY (identification details) */
int deviceInquire ()
{
const unsigned char inquire_msg[] = {
0x55, 0x53, 0x42, 0x43, 0x12, 0x34, 0x56, 0x78,
0x24, 0x00, 0x00, 0x00, 0x80, 0x00, 0x06, 0x12,
0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
char *command;
char data[36];
int i;
command = malloc(31);
if (command == NULL) {
ret = 1;
goto out;
}
memcpy(command, inquire_msg, sizeof (inquire_msg));
ret = libusb_claim_interface(devh, Interface);
if (ret != 0) {
SHOW_PROGRESS(output," Could not claim interface (error %d). Skip device inquiry\n", ret);
goto out;
}
libusb_clear_halt(devh, MessageEndpoint);
ret = usb_bulk_io(devh, MessageEndpoint, (char *)command, 31, 0);
if (ret < 0) {
SHOW_PROGRESS(output," INQUIRY message failed (error %d)\n", ret);
goto out;
}
ret = usb_bulk_io(devh, ResponseEndpoint, data, 36, 0);
if (ret < 0) {
SHOW_PROGRESS(output," INQUIRY response failed (error %d)\n", ret);
goto out;
}
i = usb_bulk_io(devh, ResponseEndpoint, command, 13, 0);
fprintf(output,"\nSCSI inquiry data (for identification)\n");
fprintf(output,"-------------------------\n");
fprintf(output," Vendor String: ");
for (i = 8; i < 16; i++) printf("%c",data[i]);
fprintf(output,"\n");
fprintf(output," Model String: ");
for (i = 16; i < 32; i++) printf("%c",data[i]);
fprintf(output,"\n");
fprintf(output,"Revision String: ");
for (i = 32; i < 36; i++) printf("%c",data[i]);
fprintf(output,"\n-------------------------\n");
out:
if (strlen(MessageContent) == 0) {
libusb_clear_halt(devh, MessageEndpoint);
libusb_release_interface(devh, Interface);
}
free(command);
return ret;
}
/* Auxiliary function used by the wrapper */
int findMBIMConfig(int vendor, int product, int mode)
{
struct libusb_device **devs;
int resultConfig=0;
int i=0, j;
if (libusb_get_device_list(ctx, &devs) < 0) {
perror("Libusb could not access USB. Abort");
return 0;
}
SHOW_PROGRESS(output,"Search USB devices ...\n");
while ((dev = devs[i++]) != NULL) {
struct libusb_device_descriptor descriptor;
libusb_get_device_descriptor(dev, &descriptor);
if (mode == SEARCH_BUSDEV) {
if ((libusb_get_bus_number(dev) != busnum) ||
(libusb_get_device_address(dev) != devnum)) {
continue;
} else {
if (descriptor.idVendor != vendor)
continue;
if (product != descriptor.idProduct)
continue;
}
}
SHOW_PROGRESS(output,"Found device, search for MBIM configuration...\n");
// No check if there is only one configuration
if (descriptor.bNumConfigurations < 2)
return -1;
// Checking all interfaces of all configurations
for (j=0; j<descriptor.bNumConfigurations; j++) {
struct libusb_config_descriptor *config;
libusb_get_config_descriptor(dev, j, &config);
resultConfig = config->bConfigurationValue;
for (i=0; i<config->bNumInterfaces; i++) {
if ( config->interface[i].altsetting[0].bInterfaceClass == 2 )
if ( config->interface[i].altsetting[0].bInterfaceSubClass == 0x0e ) {
// found MBIM interface in this configuration
libusb_free_config_descriptor(config);
return resultConfig;
}
}
libusb_free_config_descriptor(config);
}
return -1;
}
return 0;
}
void resetUSB ()
{
int success;
int bpoint = 0;
if (!devh) {
fprintf(output,"Device handle empty, skip USB reset\n");
return;
}
if (show_progress) {
fprintf(output,"Reset USB device ");
fflush(output);
}
sleep( 1 );
do {
success = libusb_reset_device(devh);
if ( ((bpoint % 10) == 0) && show_progress ) {
fprintf(output,".");
fflush(output);
}
bpoint++;
if (bpoint > 100)
success = 1;
} while (success < 0);
if ( success ) {
SHOW_PROGRESS(output,"\n Device reset failed.\n");
} else