-
Notifications
You must be signed in to change notification settings - Fork 329
/
HoRNDIS.cpp
1589 lines (1350 loc) · 50.4 KB
/
HoRNDIS.cpp
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
/* HoRNDIS.cpp
* Implementation of IOKit-derived classes
* HoRNDIS, a RNDIS driver for Mac OS X
*
* Copyright (c) 2012 Joshua Wise.
* Copyright (c) 2018 Mikhail Iakhiaev
*
* IOKit examples from Apple's USBCDCEthernet.cpp; not much of that code remains.
*
* RNDIS logic is from linux/drivers/net/usb/rndis_host.c, which is:
*
* Copyright (c) 2005 David Brownell.
*
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "HoRNDIS.h"
#include <mach/kmod.h>
#include <libkern/version.h>
#include <IOKit/IOKitKeys.h>
#include <IOKit/usb/IOUSBHostDevice.h>
#include <IOKit/usb/IOUSBHostInterface.h>
#include <IOKit/network/IOGatedOutputQueue.h>
// May be useful for supporting suspend/resume:
// #include <IOKit/pwr_mgt/RootDomain.h>
#define V_PTR 0
#define V_PACKET 1
#define V_DEBUG 2
#define V_NOTE 3
#define V_ERROR 4
// The XCode "Debug" build is now more verbose:
#if DEBUG == 1
#define DEBUGLEVEL V_DEBUG
#else
#define DEBUGLEVEL V_NOTE
#endif
#define LOG(verbosity, s, ...) do { if (verbosity >= DEBUGLEVEL) IOLog("HoRNDIS: %s: " s "\n", __func__, ##__VA_ARGS__); } while(0)
#define super IOEthernetController
OSDefineMetaClassAndStructors(HoRNDIS, IOEthernetController);
OSDefineMetaClassAndStructors(HoRNDISInterface, IOEthernetInterface);
/*
================================================================
DESCRIPTION OF DEVICE DRIVER MATCHING (+ Info.plist description)
================================================================
The HoRNDIS driver classes are only instantiated when the MacOS matches
"IOKitPersonalities" dictionary entries to the existing devices. The matching
can be done 2 based on two different provider classes:
- IOUSBHostInterface - matches an interface under a USB device. Here, we match
based on the interface class/subclass/protocol. In order for the matching to
work, some other driver has to open the USB device and call
"setConfiguration" method with matchInterfaces=true.
The interface matching works out-of-the-box for interfaces under USB
Composite Devices (class/subclass/protocol are 0/0/0), since there is an OS
driver that opens such devices for matching.
- IOUSBHostDevice - match is performed on the whole device. Here, we match
based on class/subclass/protocol. The start method needs to call
'setConfiguration' in order for any IOUSBHostInterface instances under the
device to become available. If it specifies 'matchInterfaces', matching is
then performed on newly-created IOUSBHostInterfaces.
OUR APPROACH:
We'll match based on either device or interface, and let the probe and start
methods handle the difference. Not calling setConfiguration with matchInterfaces
for now: if it's not a USB composite device, consider that we own it.
Subsequent logic:
After MacOS finds a match based on Info.plist, it instantiates the driver class,
and calls the 'probe' method that looks at descriptors and decides if this is
really the device we care about (e.g. fine-grained filtering), and sets the
"probeXxx" variables. Then, 'start' method calls 'openUSBInterfaces' that
blindly follows the "probeXxx" variables to get the needed IOUSBHostInterface
values from the opened device.
==========================
|| DEVICE VARIATIONS
==========================
This section must document ALL different variations of the devices that we
may be dealing with, so we have the whole picture when updating the "probe"
code or "Info.plist". Notation:
* Device: 224 / 0 / 0
- bDeviceClass / bDeviceSubClass / bDeviceProtocol
* Interface Associaton[2]: 224 / 1 / 3
- [bInterfaceCount]: bFunctionClass / bFunctionSubClass / bFunctionProtocol
* Interface: 224 / 3 / 1
- bInterfaceClass / bInterfaceSubClass / bInterfaceProtocol
[*] "Stock" Android. I believe most Android phone tethering should behave
this way
* USBCompositeDevice: 0 / 0 / 0
- InterfaceAssociation[2] 224 / 1 / 3
- ControlInterface: 224 / 1 / 3
- DataInterface: 10 / 0 / 0
* Info.plist entry: RNDISControlStockAndroid(interface)
[*] Linux USB Gadget drivers. Location:
<LINUX_KERNEL>/drivers/usb/gadget/function/f_rndis.c
These show up in various embedded Linux boards, such as Beagle Board,
Analog Devices PlutoSDR, etc.
* USBCompositeDevice: 0 / 0 / 0
- InterfaceAssociation[2]: Configurable (e.g. 2/6/0, 239/4/1).
- ControlInterface: 2 / 2 / 255
- DataInterface: 10 / 0 / 0
* Info.plist entry: RNDISControlLinuxGadget(interface)
[*] Wireless Controller Device (class 224). Some Samsung phones (e.g. S7 Edge)
specify device class 224 for tethering, instead of just being a USB
composite device. The rest is the same as in "stock" Android.
Note, the other Samsung phones (e.g. S8) behave like other Android devices.
* Device: 224 / 0 / 0
- (same as "Stock" Android)
[*] Composite Device, using 0xEF/4/1 for RNDIS control: Nokia 7 Plus (issue #88)
Also may apply to Sony Xperia XZ.
This matches "RNDIS over Ethernet" specification given here:
http://www.usb.org/developers/defined_class/#BaseClassEFh
* USBCompositeDevice: 0 / 0 / 0
- InterfaceAssociation[2]: 239 / 4 / 1
- ControlInterface: 239 / 4 / 1
- DataInterface: 10 / 0 / 0
* Info.plist entry: RNDISControlMiscDeviceRoE(interface)
*/
// Detects the 224/1/3 - stock Android RNDIS control interface.
static inline bool isRNDISControlStockAndroid(const InterfaceDescriptor *idesc) {
return idesc->bInterfaceClass == 224 // Wireless Controller
&& idesc->bInterfaceSubClass == 1 // Radio Frequency
&& idesc->bInterfaceProtocol == 3; // RNDIS protocol
}
// Miscellaneous Device (0xEF), RNDIS over Ethernet: some phones, see above.
static inline bool isRNDISControlMiscDeviceRoE(const InterfaceDescriptor *idesc) {
return idesc->bInterfaceClass == 239 // Miscellaneous Device
&& idesc->bInterfaceSubClass == 4 // RNDIS?
&& idesc->bInterfaceProtocol == 1; // RNDIS over Ethernet
}
// Detects RNDIS control on BeagleBoard and possibly other embedded Linux devices.
static inline bool isRNDISControlLinuxGadget(const InterfaceDescriptor *idesc) {
return idesc->bInterfaceClass == 2 // Communications / CDC Control
&& idesc->bInterfaceSubClass == 2 // Abstract (modem)
&& idesc->bInterfaceProtocol == 255; // Vendor Specific (RNDIS).
}
// Any of the above RNDIS control interface.
static inline bool isRNDISControlInterface(const InterfaceDescriptor *idesc) {
return isRNDISControlStockAndroid(idesc)
|| isRNDISControlLinuxGadget(idesc)
|| isRNDISControlMiscDeviceRoE(idesc);
}
// Detects the class 10 - CDC data interface.
static inline bool isCDCDataInterface(const InterfaceDescriptor *idesc) {
// Check for CDC class. Sub-class and Protocol are undefined:
return idesc->bInterfaceClass == 10;
}
bool HoRNDIS::init(OSDictionary *properties) {
extern kmod_info_t kmod_info; // Getting the version from generated file.
LOG(V_NOTE, "HoRNDIS tethering driver for Mac OS X, %s", kmod_info.version);
if (super::init(properties) == false) {
LOG(V_ERROR, "initialize superclass failed");
return false;
}
LOG(V_PTR, "PTR: I am: %p", this);
fNetworkInterface = NULL;
fpNetStats = NULL;
fReadyToTransfer = false;
fNetifEnabled = false;
fEnableDisableInProgress = false;
fDataDead = false;
fProbeConfigVal = 0;
fProbeCommIfNum = 0;
fCallbackCount = 0;
fCommInterface = NULL;
fDataInterface = NULL;
fInPipe = NULL;
fOutPipe = NULL;
numFreeOutBufs = 0;
for (int i = 0; i < N_OUT_BUFS; i++) {
outbufs[i].mdp = NULL;
outbufStack[i] = i; // Value does not matter here.
}
for (int i = 0 ; i < N_IN_BUFS; i++) {
inbufs[i].mdp = NULL;
}
rndisXid = 1;
maxOutTransferSize = 0;
return true;
}
void HoRNDIS::free() {
// Here, we shall free everything allocated by the 'init'.
LOG(V_NOTE, "driver instance terminated"); // For the default level
super::free();
}
/*
==================================================
INTERFACE PROLIFERATION AND PROVIDER CLASS NAME
==================================================
PROBLEM:
Every time you connect the same Android device (or somewhat more rarely),
MacOS creates a new entry under "Network" configurations tab. These entries
keep on coming on and on, polluting the configuration.
ROOT CAUSE:
Android devices randomly-generate Ethernet MAC address for
RNDIS interface, so the system may think there is a new device
every time you connect an Android phone, and may create a new
network interface every such time.
Luckily, it does extra check when Network Provider is a USB device:
in that case, it would match based on USB data, creating an entry like:
<key>SCNetworkInterfaceInfo</key>
<dict>
<key>USB Product Name</key>
<string>Pixel 2</string>
<key>UserDefinedName</key>
<string>Pixel 2</string>
<key>idProduct</key>
<integer>20195</integer>
...
In: /Library/Preferences/SystemConfiguration/NetworkInterfaces.plist
When that works, interfaces do not proliferate (at least in most cases).
PROBLEM CAUSE:
The MacOS network daemon (or whatever it is) looks at interface's
"IOProviderClass" to see if it's USB Device. Unfortunately, it may not pick
up all the names, e.g. it may trigger off the old "IOUSBDevice", but not
the new "IOUSBHostDevice". This problem is present in El Capitan for both
device and the interface, and seems to be present in later systems for
IOUSBDevice.
FIX/HACK:
The IOUSBHostDevice and IOUSBHostInterface providers actually specify
the "IOClassNameOverride" that gives the old name. We just take this value
and update our "IOProviderClass" to that.
*/
bool HoRNDIS::start(IOService *provider) {
LOG(V_DEBUG, ">");
// Per comment in "IONetworkController.h", 'super::start' should be the
// first method called in the overridden implementation. It allocates the
// network queue for the interface. The rest of the networking
// initialization will be done by 'createNetworkInterface', once USB
// USB is ready.
if(!super::start(provider)) {
return false;
}
{ // Fixing the Provider class name.
// See "INTERFACE PROLIFERATION AND PROVIDER CLASS NAME" description.
OSObject *providerClass = provider->getProperty("IOClassNameOverride");
if (providerClass) {
setProperty(kIOProviderClassKey, providerClass);
}
}
if (!openUSBInterfaces(provider)) {
goto bailout;
}
if (!rndisInit()) {
goto bailout;
}
// NOTE: The RNDIS spec mandates the usage of Keep Alive timer; however,
// the Android does not seem to be missing its absense, so there is
// probably no use in implementing it.
LOG(V_DEBUG, "done with RNDIS initialization: can start network interface");
// Let's create the medium tables here, to avoid doing extra
// steps in 'enable'. Also, comments recommend creating medium tables
// in the 'setup' stage.
const IONetworkMedium *primaryMedium;
if (!createMediumTables(&primaryMedium) ||
!setCurrentMedium(primaryMedium)) {
goto bailout;
}
// Looks like everything's good... publish the interface!
if (!createNetworkInterface()) {
goto bailout;
}
// This call is based on traces of Thunderbolt Ethernet driver.
// That driver calls 'setLinkStatus(0x1)' before interface publish
// callback (which happens after 'start').
setLinkStatus(kIONetworkLinkValid);
LOG(V_DEBUG, "successful");
return true;
bailout:
stop(provider);
return false;
}
bool HoRNDIS::willTerminate(IOService *provider, IOOptionBits options) {
LOG(V_DEBUG, ">");
// The 'willTerminate' is called when USB device disappears - the user
// either disconnected the USB, or switched-off tethering. It's likely
// that the pending read has already invoked a callback with unreachable
// device or aborted status, and already terminated. If not, closing of
// the USB Data interface would force it to abort.
//
// Note, per comments in 'IOUSBHostInterface.h' (for some later version
// of MacOS SDK), this is the recommended place to close USB interfaces.
//
// This happens before ::stop, but after some of the read jobs fail
// with kIOReturnNotResponding (and some of the writers might fail,
// too). ::disable happens sometime after we get done here, too --
// potentially invoked by super::willTerminate.
disableNetworkQueue();
closeUSBInterfaces();
return super::willTerminate(provider, options);
}
void HoRNDIS::stop(IOService *provider) {
LOG(V_DEBUG, ">");
OSSafeReleaseNULL(fNetworkInterface);
closeUSBInterfaces(); // Just in case - supposed to be closed by now.
super::stop(provider);
}
// Convenience function: to retain and assign in one step:
template <class T> static inline T *retainT(T *ptr) {
ptr->retain();
return ptr;
}
bool HoRNDIS::openUSBInterfaces(IOService *provider) {
if (fProbeConfigVal == 0) {
// Must have been set by 'probe' before 'start' function call:
LOG(V_ERROR, "'fProbeConfigVal' has not been set, bailing out");
return false;
}
IOUSBHostDevice *device = OSDynamicCast(IOUSBHostDevice, provider);
if (device) {
// Set the device configuration, so we can start looking at the interfaces:
if (device->setConfiguration(fProbeConfigVal, false) != kIOReturnSuccess) {
LOG(V_ERROR, "Cannot set the USB Device configuration");
return false;
}
} else {
IOUSBHostInterface *iface = OSDynamicCast(IOUSBHostInterface, provider);
if (iface == NULL) {
LOG(V_ERROR, "start: BUG unexpected provider class");
return false;
}
device = iface->getDevice();
// Make sure it's the one we care about:
bool match = iface->getConfigurationDescriptor()->bConfigurationValue == fProbeConfigVal
&& iface->getInterfaceDescriptor()->bInterfaceNumber == fProbeCommIfNum;
if (!match) {
LOG(V_ERROR, "BUG! Did we see a different provider in probe?");
return false;
}
}
{ // Now, find the interfaces:
OSIterator *iterator = device->getChildIterator(gIOServicePlane);
OSObject *obj = NULL;
while(iterator != NULL && (obj = iterator->getNextObject()) != NULL) {
IOUSBHostInterface *iface = OSDynamicCast(IOUSBHostInterface, obj);
if (iface == NULL) {
continue;
}
if (iface->getConfigurationDescriptor()->bConfigurationValue !=
fProbeConfigVal) {
continue;
}
const InterfaceDescriptor *desc = iface->getInterfaceDescriptor();
uint8_t ifaceNum = desc->bInterfaceNumber;
if (!fCommInterface && ifaceNum == fProbeCommIfNum) {
LOG(V_DEBUG, "Found control interface: %d/%d/%d, opening",
desc->bInterfaceClass, desc->bInterfaceSubClass,
desc->bInterfaceProtocol);
if (!iface->open(this)) {
LOG(V_ERROR, "Could not open RNDIS control interface");
return false;
}
// Note, we retain AFTER opening the interface, because once
// 'fCommInterface' is set, the 'closeUSBInterfaces' would
// always try to close it before releasing:
fCommInterface = retainT(iface);
} else if (ifaceNum == fProbeCommIfNum + 1) {
LOG(V_DEBUG, "Found data interface: %d/%d/%d, opening",
desc->bInterfaceClass, desc->bInterfaceSubClass,
desc->bInterfaceProtocol);
if (!iface->open(this)) {
LOG(V_ERROR, "Could not open RNDIS data interface");
return false;
}
// open before retain, see above:
fDataInterface = retainT(iface);
break; // We should be done by now.
}
}
OSSafeReleaseNULL(iterator);
}
// WARNING, it is a WRONG idea to attach 'fDataInterface' as a second
// provider, because both providers would be calling 'willTerminate', and
// 'stop' methods, resulting in chaos.
if (!fCommInterface || !fDataInterface) {
LOG(V_ERROR, "could not find the required interfaces, despite seeing "
"their descriptors during 'probe' method call");
return false;
}
{ // Get the pipes for the data interface:
const EndpointDescriptor *candidate = NULL;
const InterfaceDescriptor *intDesc = fDataInterface->getInterfaceDescriptor();
const ConfigurationDescriptor *confDesc = fDataInterface->getConfigurationDescriptor();
if (intDesc->bNumEndpoints != 2) {
LOG(V_ERROR, "Expected 2 endpoints for Data Interface, got: %d", intDesc->bNumEndpoints);
return false;
}
while((candidate = StandardUSB::getNextEndpointDescriptor(
confDesc, intDesc, candidate)) != NULL) {
const bool isEPIn =
(candidate->bEndpointAddress & kEndpointDescriptorDirection) != 0;
IOUSBHostPipe *&pipe = isEPIn ? fInPipe : fOutPipe;
if (pipe == NULL) {
// Note, 'copyPipe' already performs 'retain': must not call it again.
pipe = fDataInterface->copyPipe(candidate->bEndpointAddress);
}
}
if (fInPipe == NULL || fOutPipe == NULL) {
LOG(V_ERROR, "Could not init IN/OUT pipes in the Data Interface");
return false;
}
}
return true;
}
void HoRNDIS::closeUSBInterfaces() {
fReadyToTransfer = false; // Interfaces are about to be closed.
// Close the interfaces - this would abort the transfers (if present):
if (fDataInterface) {
fDataInterface->close(this);
}
if (fCommInterface) {
fCommInterface->close(this);
}
OSSafeReleaseNULL(fInPipe);
OSSafeReleaseNULL(fOutPipe);
OSSafeReleaseNULL(fDataInterface);
OSSafeReleaseNULL(fCommInterface); // First one to open, last one to die.
}
IOService *HoRNDIS::probe(IOService *provider, SInt32 *score) {
LOG(V_DEBUG, "came in with a score of %d", *score);
{ // Check if this is a device-based matching:
IOUSBHostDevice *device = OSDynamicCast(IOUSBHostDevice, provider);
if (device) {
return probeDevice(device, score);
}
}
IOUSBHostInterface *controlIf = OSDynamicCast(IOUSBHostInterface, provider);
if (controlIf == NULL) {
LOG(V_ERROR, "unexpected provider class (wrong Info.plist)");
return NULL;
}
const InterfaceDescriptor *desc = controlIf->getInterfaceDescriptor();
LOG(V_DEBUG, "Interface-based matching, probing for device '%s', "
"interface %d/%d/%d", controlIf->getDevice()->getName(),
desc->bInterfaceClass, desc->bInterfaceSubClass,
desc->bInterfaceProtocol);
if (!isRNDISControlInterface(controlIf->getInterfaceDescriptor())) {
LOG(V_ERROR, "not RNDIS control interface (wrong Info.plist)");
return NULL;
}
const ConfigurationDescriptor *configDesc =
controlIf->getConfigurationDescriptor();
const InterfaceDescriptor *dataDesc =
StandardUSB::getNextInterfaceDescriptor(configDesc, desc);
bool match = isCDCDataInterface(dataDesc) &&
(dataDesc->bInterfaceNumber == desc->bInterfaceNumber + 1);
if (!match) {
LOG(V_DEBUG, "Could not find CDC data interface right after control");
return NULL;
}
fProbeConfigVal = configDesc->bConfigurationValue;
fProbeCommIfNum = desc->bInterfaceNumber;
*score += 100000;
return this;
}
IOService *HoRNDIS::probeDevice(IOUSBHostDevice *device, SInt32 *score) {
const DeviceDescriptor *desc = device->getDeviceDescriptor();
LOG(V_DEBUG, "Device-based matching, probing: '%s', %d/%d/%d",
device->getName(), desc->bDeviceClass, desc->bDeviceSubClass,
desc->bDeviceProtocol);
// Look through all configurations and find the one we want:
for (int i = 0; i < desc->bNumConfigurations; i++) {
const ConfigurationDescriptor *configDesc =
device->getConfigurationDescriptor(i);
if (configDesc == NULL) {
LOG(V_ERROR, "Cannot get device's configuration descriptor");
return NULL;
}
int controlIfNum = INT16_MAX; // Definitely invalid interface number.
bool foundData = false;
const InterfaceDescriptor *intDesc = NULL;
while((intDesc = StandardUSB::getNextInterfaceDescriptor(configDesc, intDesc)) != NULL) {
// If this is a device-level match, check for the control interface:
if (isRNDISControlInterface(intDesc)) { // Just check them all.
controlIfNum = intDesc->bInterfaceNumber;
continue;
}
// We check for data interface AND make sure it follows directly the
// control interface. Note the condition below would only trigger
// if we previously found an appropriate 'controlIfNum':
if (isCDCDataInterface(intDesc) &&
intDesc->bInterfaceNumber == controlIfNum + 1) {
foundData = true;
break;
}
}
if (foundData) {
// We've found it! Save the information and return:
fProbeConfigVal = configDesc->bConfigurationValue;
fProbeCommIfNum = controlIfNum;
*score += 10000;
return this;
}
}
// Did not find any interfaces we can use:
LOG(V_DEBUG, "The device '%s' does not contain the required interfaces: "
"it is not for us", device->getName());
return NULL;
}
/***** Ethernet interface bits *****/
/* We need our own createInterface (overriding the one in IOEthernetController)
* because we need our own subclass of IOEthernetInterface. Why's that, you say?
* Well, we need that because that's the only way to set a different default MTU,
* because it seems like MacOS code just assumes that any EthernetController
* driver must be able to handle al leaset 1500-byte Ethernet payload.
* Sigh...
* The MTU-limiting code may never come into play though, because the devices
* I've seen have "max_transfer_size" large enough to accomodate a max-length
* Ethernet frames. */
bool HoRNDISInterface::init(IONetworkController *controller, int mtu) {
maxmtu = mtu;
if (IOEthernetInterface::init(controller) == false) {
return false;
}
LOG(V_NOTE, "(network interface) starting up with MTU %d", mtu);
setMaxTransferUnit(mtu);
return true;
}
bool HoRNDISInterface::setMaxTransferUnit(UInt32 mtu) {
if (mtu > maxmtu) {
LOG(V_NOTE, "Excuse me, but I said you could have an MTU of %u, and you just tried to set an MTU of %d. Good try, buddy.", maxmtu, mtu);
return false;
}
IOEthernetInterface::setMaxTransferUnit(mtu);
return true;
}
/* Overrides IOEthernetController::createInterface */
IONetworkInterface *HoRNDIS::createInterface() {
LOG(V_DEBUG, ">");
HoRNDISInterface *netif = new HoRNDISInterface;
if (!netif) {
return NULL;
}
int mtuLimit = maxOutTransferSize
- (int)sizeof(rndis_data_hdr)
- 14; // Size of ethernet header (no QLANs). Checksum is not included.
if (!netif->init(this, min(ETHERNET_MTU, mtuLimit))) {
netif->release();
return NULL;
}
return netif;
}
bool HoRNDIS::createNetworkInterface() {
LOG(V_DEBUG, "attaching and registering interface");
// MTU is initialized before we get here, so this is a safe time to do this.
if (!attachInterface((IONetworkInterface **)&fNetworkInterface, true)) {
LOG(V_ERROR, "attachInterface failed?");
return false;
}
LOG(V_PTR, "fNetworkInterface: %p", fNetworkInterface);
// The 'registerService' should be called by 'attachInterface' (with second
// parameter set to true). No need to do it here.
return true;
}
/***** Interface enable and disable logic *****/
HoRNDIS::ReentryLocker::ReentryLocker(IOCommandGate *inGate, bool &inGuard)
: gate(inGate), entryGuard(inGuard), result(kIOReturnSuccess) {
// Note, please see header comment for the motivation behind
// 'ReentryLocker' and its high-level functionality.
// Wait until we exit the previously-entered enable or disable method:
while (entryGuard) {
LOG(V_DEBUG, "Delaying the re-entered call");
result = gate->commandSleep(&entryGuard);
// If "commandSleep" has failed, stop immediately, and don't
// touch the 'entryGuard':
if (isInterrupted()) {
return;
}
}
entryGuard = true; // Mark the entry into one of the protected methods.
}
HoRNDIS::ReentryLocker::~ReentryLocker() {
if (!isInterrupted()) {
entryGuard = false;
gate->commandWakeup(&entryGuard);
}
}
static IOReturn loopClearPipeStall(IOUSBHostPipe *pipe) {
IOReturn rc = kUSBHostReturnPipeStalled;
int count = 0;
// For some reason, 'clearStall' may keep on returning
// kUSBHostReturnPipeStalled many times, before finally returning success
// (Android keeps on sending packtes, each generating a stall?).
const int NUM_RETRIES = 1000;
for (; count < NUM_RETRIES && rc == kUSBHostReturnPipeStalled; count++) {
rc = pipe->clearStall(true);
}
LOG(V_DEBUG, "Called 'clearStall' %d times", count);
return rc;
}
/*!
* Calls 'pipe->io', and if there is a stall, tries to clear that
* stall and calls it again.
*/
static inline IOReturn robustIO(IOUSBHostPipe *pipe, pipebuf_t *buf,
uint32_t len) {
IOReturn rc = pipe->io(buf->mdp, len, &buf->comp);
if (rc == kUSBHostReturnPipeStalled) {
LOG(V_DEBUG, "USB Pipe is stalled. Trying to clear ...");
rc = loopClearPipeStall(pipe);
// If clearing the stall succeeded, try the IO operation again:
if (rc == kIOReturnSuccess) {
LOG(V_DEBUG, "Cleared USB Stall, Retrying the operation");
rc = pipe->io(buf->mdp, len, &buf->comp);
}
}
return rc;
}
/* Contains buffer alloc and dealloc, notably. Why do that here?
Not just because that's what Apple did. We don't want to consume these
resources when the interface is sitting disabled and unused. */
IOReturn HoRNDIS::enable(IONetworkInterface *netif) {
IOReturn rtn = kIOReturnSuccess;
LOG(V_DEBUG, "begin for thread_id=%lld", thread_tid(current_thread()));
ReentryLocker locker(this, fEnableDisableInProgress);
if (locker.isInterrupted()) {
LOG(V_ERROR, "Waiting interrupted");
return locker.getResult();
}
if (fNetifEnabled) {
LOG(V_DEBUG, "Repeated call (thread_id=%lld), returning success",
thread_tid(current_thread()));
return kIOReturnSuccess;
}
if (fCallbackCount != 0) {
LOG(V_ERROR, "Invalid state: fCallbackCount(=%d) != 0", fCallbackCount);
return kIOReturnError;
}
if (!allocateResources()) {
return kIOReturnNoMemory;
}
// Tell the other end to start transmitting.
if (!rndisSetPacketFilter(RNDIS_DEFAULT_FILTER)) {
goto bailout;
}
// The pipe stall clearning is not needed for the first "enable" call after
// pugging in the device, but it becomes necessary when "disable" is called
// after that, followed by another "enable". This happens when user runs
// "sudo ifconfig <netif> down", followed by "sudo ifconfig <netif> up"
LOG(V_DEBUG, "Clearing potential Pipe stalls on Input and Output pipes");
loopClearPipeStall(fInPipe);
loopClearPipeStall(fOutPipe);
// We can now perform reads and writes between Network stack and USB device:
fReadyToTransfer = true;
// Kick off the read requests:
for (int i = 0; i < N_IN_BUFS; i++) {
pipebuf_t &inbuf = inbufs[i];
inbuf.comp.owner = this;
inbuf.comp.action = dataReadComplete;
inbuf.comp.parameter = &inbuf;
rtn = robustIO(fInPipe, &inbuf, (uint32_t)inbuf.mdp->getLength());
if (rtn != kIOReturnSuccess) {
LOG(V_ERROR, "Failed to start the first read: %08x\n", rtn);
goto bailout;
}
fCallbackCount++;
}
// Tell the world that the link is up...
if (!setLinkStatus(kIONetworkLinkActive | kIONetworkLinkValid,
getCurrentMedium())) {
LOG(V_ERROR, "Cannot set link status");
rtn = kIOReturnError;
goto bailout;
}
// ... and then listen for packets!
getOutputQueue()->setCapacity(TRANSMIT_QUEUE_SIZE);
getOutputQueue()->start();
LOG(V_DEBUG, "txqueue started");
// Now we can say we're alive.
fNetifEnabled = true;
LOG(V_NOTE, "completed (thread_id=%lld): RNDIS network interface '%s' "
"should be live now", thread_tid(current_thread()), netif->getName());
return kIOReturnSuccess;
bailout:
disableImpl();
return rtn;
}
void HoRNDIS::disableNetworkQueue() {
// Disable the queue (no more outputPacket),
// and then flush everything in the queue.
getOutputQueue()->stop();
getOutputQueue()->flush();
getOutputQueue()->setCapacity(0);
}
IOReturn HoRNDIS::disable(IONetworkInterface *netif) {
LOG(V_DEBUG, "begin for thread_id=%lld", thread_tid(current_thread()));
// This function can be called as a consequence of:
// 1. USB Disconnect
// 2. Some action, while the device is up and running
// (e.g. "ifconfig en6 down").
// In the second case, we'll need to do more cleanup:
// ask the RNDIS device to stop transmitting, and abort the callbacks.
//
ReentryLocker locker(this, fEnableDisableInProgress);
if (locker.isInterrupted()) {
LOG(V_ERROR, "Waiting interrupted");
return locker.getResult();
}
if (!fNetifEnabled) {
LOG(V_DEBUG, "Repeated call (thread_id=%lld)", thread_tid(current_thread()));
return kIOReturnSuccess;
}
disableImpl();
LOG(V_DEBUG, "completed (thread_id=%lld)", thread_tid(current_thread()));
return kIOReturnSuccess;
}
void HoRNDIS::disableImpl() {
disableNetworkQueue();
// Stop the the new transfers. The code below would cancel the pending ones:
fReadyToTransfer = false;
// If the device has not been disconnected, ask it to stop xmitting:
if (fCommInterface) {
rndisSetPacketFilter(0);
}
// Again, based on Thunderbolt Ethernet controller traces.
// It sets the link status to 0x1 in the disable call:
setLinkStatus(kIONetworkLinkValid, 0);
// If USB interfaces are still up, abort the reader and writer:
if (fInPipe) {
fInPipe->abort(IOUSBHostIOSource::kAbortSynchronous,
kIOReturnAborted, NULL);
}
if (fOutPipe) {
fOutPipe->abort(IOUSBHostIOSource::kAbortSynchronous,
kIOReturnAborted, NULL);
}
// Make sure all the callbacks have exited:
LOG(V_DEBUG, "Callback count: %d. If not zero, delaying ...",
fCallbackCount);
while (fCallbackCount > 0) {
// No timeout: in our callbacks we trust!
getCommandGate()->commandSleep(&fCallbackCount);
}
LOG(V_DEBUG, "All callbacks exited");
// Release all resources
releaseResources();
fNetifEnabled = false;
}
bool HoRNDIS::createMediumTables(const IONetworkMedium **primary) {
IONetworkMedium *medium;
OSDictionary *mediumDict = OSDictionary::withCapacity(1);
if (mediumDict == NULL) {
LOG(V_ERROR, "Cannot allocate OSDictionary");
return false;
}
medium = IONetworkMedium::medium(kIOMediumEthernetAuto, 480 * 1000000);
IONetworkMedium::addMedium(mediumDict, medium);
medium->release(); // 'mediumDict' holds a ref now.
if (primary) {
*primary = medium;
}
bool result = publishMediumDictionary(mediumDict);
if (!result) {
LOG(V_ERROR, "Cannot publish medium dictionary!");
}
// Per comment for 'publishMediumDictionary' in NetworkController.h, the
// medium dictionary is copied and may be safely relseased after the call.
mediumDict->release();
return result;
}
bool HoRNDIS::allocateResources() {
LOG(V_DEBUG, "Allocating %d input buffers (size=%d) and %d output "
"buffers (size=%d)", N_IN_BUFS, IN_BUF_SIZE, N_OUT_BUFS, OUT_BUF_SIZE);
// Grab a memory descriptor pointer for data-in.
for (int i = 0; i < N_IN_BUFS; i++) {
inbufs[i].mdp = IOBufferMemoryDescriptor::withCapacity(IN_BUF_SIZE, kIODirectionIn);
if (!inbufs[i].mdp) {
return false;
}
inbufs[i].mdp->setLength(IN_BUF_SIZE);
LOG(V_PTR, "PTR: inbuf[%d].mdp: %p", i, inbufs[i].mdp);
}
// And a handful for data-out...
for (int i = 0; i < N_OUT_BUFS; i++) {
outbufs[i].mdp = IOBufferMemoryDescriptor::withCapacity(
OUT_BUF_SIZE, kIODirectionOut);
if (!outbufs[i].mdp) {
LOG(V_ERROR, "allocate output descriptor failed");
return false;
}
LOG(V_PTR, "PTR: outbufs[%d].mdp: %p", i, outbufs[i].mdp);
outbufs[i].mdp->setLength(OUT_BUF_SIZE);
outbufStack[i] = i;
}
numFreeOutBufs = N_OUT_BUFS;
return true;
}
void HoRNDIS::releaseResources() {
LOG(V_DEBUG, "releaseResources");
fReadyToTransfer = false; // No transfers without buffers.
for (int i = 0; i < N_OUT_BUFS; i++) {
OSSafeReleaseNULL(outbufs[i].mdp);
outbufStack[i] = i;
}
numFreeOutBufs = 0;
for (int i = 0; i < N_IN_BUFS; i++) {
OSSafeReleaseNULL(inbufs[i].mdp);
}
}
IOOutputQueue *HoRNDIS::createOutputQueue() {
LOG(V_DEBUG, ">");
// The gated Output Queue keeps things simple: everything is
// serialized, no need to worry about locks or concurrency.
// The device is not very fast, so the serial execution should be more
// than capable of keeping up.
// Note, if we ever switch to non-gated queue, we shall update the
// 'outputPacket' to access the shared state using locks + update all the
// other users of that state + may want to use locks for USB calls as well.
return IOGatedOutputQueue::withTarget(this,
getWorkLoop(), TRANSMIT_QUEUE_SIZE);
}
bool HoRNDIS::configureInterface(IONetworkInterface *netif) {
LOG(V_DEBUG, ">");
IONetworkData *nd;
if (super::configureInterface(netif) == false) {
LOG(V_ERROR, "super failed");
return false;
}
nd = netif->getNetworkData(kIONetworkStatsKey);
if (!nd || !(fpNetStats = (IONetworkStats *)nd->getBuffer())) {
LOG(V_ERROR, "network statistics buffer unavailable?");
return false;
}
LOG(V_PTR, "fpNetStats: %p", fpNetStats);
return true;
}
/***** All-purpose IOKit network routines *****/
IOReturn HoRNDIS::getPacketFilters(const OSSymbol *group, UInt32 *filters) const {
IOReturn rtn = kIOReturnSuccess;
if (group == gIOEthernetWakeOnLANFilterGroup) {
*filters = 0;
} else if (group == gIONetworkFilterGroup) {
*filters = kIOPacketFilterUnicast | kIOPacketFilterBroadcast
| kIOPacketFilterPromiscuous | kIOPacketFilterMulticast
| kIOPacketFilterMulticastAll;
} else {
rtn = super::getPacketFilters(group, filters);
}
return rtn;
}
IOReturn HoRNDIS::getMaxPacketSize(UInt32 *maxSize) const {
IOReturn rc = super::getMaxPacketSize(maxSize);
if (rc != kIOReturnSuccess) {
return rc;