forked from jwise/HoRNDIS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HoRNDIS.cpp
1356 lines (1085 loc) · 36.2 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.
*
* 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 <IOKit/IOKitKeys.h>
#include <IOKit/usb/USBSpec.h>
/* This is only available in the userspace IOKit.framework's usb/IOUSBLib.h, for some reason. So instead: */
#define kIOUSBInterfaceClassName "IOUSBInterface"
#define MYNAME "HoRNDIS"
#define VERSION "rel8 final"
#define V_PTR 0
#define V_DEBUG 1
#define V_NOTE 2
#define V_ERROR 3
#define DEBUGLEVEL V_NOTE
#define LOG(verbosity, s, ...) do { if (verbosity >= DEBUGLEVEL) IOLog(MYNAME ": %s: " s "\n", __func__, ##__VA_ARGS__); } while(0)
#define super IOEthernetController
OSDefineMetaClassAndStructors(HoRNDIS, IOEthernetController);
OSDefineMetaClassAndStructors(HoRNDISUSBDevice, HoRNDIS);
OSDefineMetaClassAndStructors(HoRNDISInterface, IOEthernetInterface);
bool HoRNDIS::init(OSDictionary *properties) {
int i;
LOG(V_NOTE, "HoRNDIS tethering driver for Mac OS X, by Joshua Wise (%s)", VERSION);
if (super::init(properties) == false) {
LOG(V_ERROR, "initialize super failed");
return false;
}
LOG(V_PTR, "PTR: I am: %p", this);
fNetworkInterface = NULL;
fpNetStats = NULL;
fMediumDict = NULL;
fNetifEnabled = false;
fDataDead = false;
fCommInterface = NULL;
fDataInterface = NULL;
fInPipe = NULL;
fOutPipe = NULL;
outbuf_lock = NULL;
for (i = 0; i < N_OUT_BUFS; i++) {
outbufs[i].mdp = NULL;
outbufs[i].buf = NULL;
outbufs[i].inuse = false;
}
inbuf.mdp = NULL;
inbuf.buf = NULL;
fpDevice = NULL;
xid_lock = IOLockAlloc();
xid = 1;
return true;
}
/* IOKit class wrappers */
bool HoRNDISUSBDevice::start(IOService *provider) {
IOUSBDevice *dev;
LOG(V_DEBUG, "start, as IOUSBDevice");
dev = OSDynamicCast(IOUSBDevice, provider);
if (!dev) {
LOG(V_ERROR, "cast to IOUSBDevice failed?");
return false;
}
fpDevice = dev;
return HoRNDIS::start(provider);
}
bool HoRNDIS::start(IOService *provider) {
LOG(V_DEBUG, "start");
if(!super::start(provider))
return false;
if (!fpDevice) {
stop(provider);
return false;
}
fpDevice->retain();
if (!fpDevice->open(this)) {
LOG(V_ERROR, "could not open the device at all?");
fpDevice->release();
fpDevice = NULL;
goto bailout;
}
if (!openInterfaces())
goto bailout;
if (!rndisInit())
goto bailout;
/* Looks like everything's good... publish the interface! */
if (!createNetworkInterface())
goto bailout;
LOG(V_DEBUG, "successful");
return true;
bailout:
stop(provider);
return false;
}
void HoRNDIS::stop(IOService *provider) {
LOG(V_DEBUG, "stop");
if (fNetworkInterface) {
fNetworkInterface->release();
fNetworkInterface = NULL;
}
if (fCommInterface) {
fCommInterface->close(this);
fCommInterface->release();
fCommInterface = NULL;
}
if (fDataInterface) {
fDataInterface->close(this);
fDataInterface->release();
fDataInterface = NULL;
}
if (fpDevice) {
fpDevice->close(this);
fpDevice->release();
fpDevice = NULL;
}
if (fMediumDict) {
fMediumDict->release();
fMediumDict = NULL;
}
if (xid_lock) {
IOLockFree(xid_lock);
xid_lock = NULL;
}
super::stop(provider);
}
/* Creating a workloop of our own seems to be necessary on Mac OS X 10.10 --
* otherwise, we can have not just reentrant calls to HoRNDIS::enable(), but
* also even to IOEthernetInterface::syncSIOCSIFFLAGS()! Then, ::enable()
* "takes a while", which means that on a second call to syncSIOCSIFFLAGS,
* we get reentrantly invoked, and then -- worse yet -- we fail, and it
* disables the interface, freeing resources out from under the first
* ::enable().
*
* This "seems to fix it", but it's a workaround for something that I can't
* possible know, since source for OS X 10.10 does not exist yet.
*
* "This would never have happened if Steve Jobs were still CEO."
*/
bool HoRNDIS::createWorkLoop() {
LOG(V_DEBUG, "creating workloop");
workloop = IOWorkLoop::workLoop();
return !!workloop;
}
IOWorkLoop *HoRNDIS::getWorkLoop() const {
return workloop;
}
/***** Matching, interface acquisition, and such. *****/
/* THIS IS NOT A PLACE OF HONOR.
* NO HIGHLY ESTEEMED DEED IS COMMEMORATED HERE.
* [...]
* THIS PLACE IS A MESSAGE AND PART OF A SYSTEM OF MESSAGES.
* WHAT IS HERE IS DANGEROUS AND REPULSIVE TO US.
* THIS MESSAGE IS A WARNING ABOUT DANGER.
* [...]
* WE CONSIDERED OURSELVES TO BE A POWERFUL CULTURE.
*
* -- excerpted from "Expert Judgment on Markers to Deter Inadvertent
* Human Intrusion into the Waste Isolation Pilot Plant", Sandia
* National Laboratories report SAND92-1382 / UC-721
*/
/* IOService::waitForMatchingService is kind of a difficult API to use. We
* wrap it to wait for a specific matching USB interface. */
IOService *HoRNDIS::waitForMatchingUSBInterface(uint32_t cl, uint32_t subcl, uint32_t proto) {
OSDictionary *dict;
OSDictionary *propertyDict;
OSNumber *num;
IOService *svc;
dict = IOService::serviceMatching(kIOUSBInterfaceClassName);
if (!dict)
goto nodict;
propertyDict = OSDictionary::withCapacity(3);
if (!propertyDict)
goto noprop;
num = OSNumber::withNumber((uint64_t)cl, 32);
if (!num)
goto nonum;
propertyDict->setObject(kUSBInterfaceClass, num);
num->release();
num = OSNumber::withNumber((uint64_t)subcl, 32);
if (!num)
goto nonum;
propertyDict->setObject(kUSBInterfaceSubClass, num);
num->release();
num = OSNumber::withNumber((uint64_t)proto, 32);
if (!num)
goto nonum;
propertyDict->setObject(kUSBInterfaceProtocol, num);
num->release();
dict->setObject(kIOPropertyMatchKey, propertyDict);
propertyDict->release();
svc = IOService::waitForMatchingService(dict, 1 * 1000000000 /* i.e., 1 sec */);
if (!svc)
LOG(V_NOTE, "timed out matching a %d/%d/%d", cl, subcl, proto);
dict->release();
return svc;
nonum:
propertyDict->release();
noprop:
dict->release();
nodict:
LOG(V_ERROR, "low memory error in waitForMatchingUSBInterface(%d, %d, %d)", cl, subcl, proto);
return NULL;
}
/* There are a great number of truly amazing things about Mac OS X 10.11,
* and its USB stack. It's not terribly amazing that they broke break
* subtle functionality that wasn't really guaranteed to work in the first
* place. For instance, subtle race conditions changing their "usual"
* behavior is agonizing, but I can't really harbor too much hatred in my
* heart for Apple for that.
*
* No, the thing that amazes the most, I think, is that they managed to
* break overt high-level functionality. For instance,
* IOUSBDevice::FindNextInterface sometimes only works if the fields in
* IOUSBFindInterfaceRequest are set to kIOUSBFindInterfaceDontCare. If you
* set bInterfaceClass to something that you care about and call it with a
* non-NULL initial interface, it might just return NULL instead. You can
* go ahead and call it back with don't-cares in the fields... and then
* you'll get an interface that matches perfectly. "Ha ha, sucker, sorry, I
* lied."
*
* So we reimplement it on top of the existing primitive so that we can
* actually go find an interface that we want.
*/
IOUSBInterface *HoRNDIS::FindNextMatchingInterface(IOUSBInterface *intf, uint32_t cl, uint32_t subcl, uint32_t proto) {
IOUSBFindInterfaceRequest req;
req.bInterfaceClass = kIOUSBFindInterfaceDontCare;
req.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
req.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
req.bAlternateSetting = kIOUSBFindInterfaceDontCare;
do
intf = fpDevice->FindNextInterface(intf, &req);
while (intf && intf->GetInterfaceClass() != cl && intf->GetInterfaceSubClass() != subcl && intf->GetInterfaceProtocol() != proto);
return intf;
}
bool HoRNDIS::openInterfaces() {
IOReturn rc;
IOUSBFindEndpointRequest epReq;
IOService *datasvc;
/* Set up the device's configuration. */
if (fpDevice->SetConfiguration(this, ctrlconfig, true /* start matching */) != kIOReturnSuccess) {
LOG(V_ERROR, "failed to set configuration %d?", ctrlconfig);
goto bailout0;
}
/* Go looking for the comm interface. */
datasvc = waitForMatchingUSBInterface(ctrlclass, ctrlsubclass, ctrlprotocol);
if (!datasvc) {
LOG(V_ERROR, "control interface: waitForMatchingService(%d, %d, %d) matched nothing?", ctrlclass, ctrlsubclass, ctrlprotocol);
goto bailout0;
}
fCommInterface = OSDynamicCast(IOUSBInterface, datasvc);
if (!fCommInterface) {
LOG(V_ERROR, "RNDIS control interface not available?");
datasvc->release();
goto bailout0;
}
rc = fCommInterface->open(this);
if (!rc) {
LOG(V_ERROR, "could not open RNDIS control interface?");
goto bailout1;
}
/* fCommInterface has been retained already, since it came from
* waitForMatchingService. */
/* Go looking for the data interface.
*
* This takes a little more doing, since we need the one that comes
* /immediately after/ the fCommInterface -- otherwise, we could end
* up stealing the data interface for, for example, a CDC ACM
* device. But, the complication is that it might or might not have
* been created yet. And worse, if it gets created just after we
* look, we might look for it and fail, and then
* waitForMatchingService could *still* fail, because it gets
* created just before waitForMatchingService is called!
*
* The synchronization primitive you are looking for here is called
* a "condition variable".
*
* Grumble.
*/
int counter;
counter = 10;
while ((fDataInterface = FindNextMatchingInterface(fCommInterface, 0x0A, 0x00, 0x00)) == NULL && counter--) {
datasvc = waitForMatchingUSBInterface(0x0A, 0x00, 0x00 /* req.bInterfaceClass, req.bInterfaceSubClass, req.bInterfaceProtocol */);
if (datasvc) {
/* We could have a winner, but it might be something
* else. Let FindNextInterface deal with it for us.
* Technically we should probably use an interface
* association descriptor, but I don't think that's
* exposed readily, so ... */
datasvc->release();
} else {
/* Not a winner, and we never will be - it's been a
* whole second! */
break;
}
}
if (counter <= 0) {
LOG(V_ERROR, "data interface: timed out after ten attempts to find an fDataInterface; waitForMatchingService() gave us something, but FindNextInterface couldn't find it?");
}
/* Deal with that pesky race condition by looking /just once more/. */
if (!fDataInterface) {
fDataInterface = FindNextMatchingInterface(fCommInterface, 0x0A, 0x00, 0x00);
}
if (!fDataInterface) {
LOG(V_ERROR, "data interface: we never managed to find a friend :(");
goto bailout2;
}
LOG(V_ERROR, "data interface: okay, I got one, and it was a 0x%02x/0x%02x/0x%02x", fDataInterface->GetInterfaceClass(), fDataInterface->GetInterfaceSubClass(), fDataInterface->GetInterfaceProtocol());
rc = fDataInterface->open(this);
if (!rc) {
LOG(V_ERROR, "could not open RNDIS data interface?");
goto bailout3;
}
if (fDataInterface->GetNumEndpoints() < 2) {
LOG(V_ERROR, "not enough endpoints on data interface?");
goto bailout4;
}
/* Of course, since we got this one from FindNextInterface, not from
* waitForMatchingService, we have to do lifecycle management of
* this thing on our own.
*
* I don't believe that this is safe, but race conditions can be
* avoided by appropriate haste in critical sections, I suppose.
*/
fDataInterface->retain();
/* open up the endpoints */
epReq.type = kUSBBulk;
epReq.direction = kUSBIn;
epReq.maxPacketSize = 0;
epReq.interval = 0;
fInPipe = fDataInterface->FindNextPipe(0, &epReq);
if (!fInPipe) {
LOG(V_ERROR, "no bulk input pipe");
goto bailout5;
}
LOG(V_PTR, "PTR: fInPipe: %p", fInPipe);
LOG(V_DEBUG, "bulk input pipe %p: max packet size %d, interval %d", fInPipe, epReq.maxPacketSize, epReq.interval);
epReq.direction = kUSBOut;
fOutPipe = fDataInterface->FindNextPipe(0, &epReq);
if (!fOutPipe) {
LOG(V_ERROR, "no bulk output pipe");
goto bailout5;
}
LOG(V_PTR, "PTR: fOutPipe: %p", fOutPipe);
LOG(V_DEBUG, "bulk output pipe %p: max packet size %d, interval %d", fOutPipe, epReq.maxPacketSize, epReq.interval);
/* Currently, we don't even bother to listen on the interrupt pipe. */
/* And we're done! Wasn't that easy?*/
return true;
bailout5:
fDataInterface->release();
bailout4:
fDataInterface->close(this);
bailout3:
fDataInterface = NULL;
bailout2:
fCommInterface->close(this);
bailout1:
fCommInterface->release();
fCommInterface = NULL;
bailout0:
/* Show what interfaces we saw. */
IOUSBFindInterfaceRequest req;
req.bInterfaceClass = kIOUSBFindInterfaceDontCare;
req.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
req.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
req.bAlternateSetting = kIOUSBFindInterfaceDontCare;
IOUSBInterface *ifc = NULL;
LOG(V_ERROR, "openInterfaces: before I fail, here are all the interfaces that I saw, in case you care ...");
while ((ifc = fpDevice->FindNextInterface(ifc, &req))) {
LOG(V_ERROR, "openInterfaces: class 0x%02x, subclass 0x%02x, protocol 0x%02x", ifc->GetInterfaceClass(), ifc->GetInterfaceSubClass(), ifc->GetInterfaceProtocol());
}
return false;
}
IOService *HoRNDIS::probe(IOService *provider, SInt32 *score) {
LOG(V_NOTE, "probe: came in with a score of %d", *score);
IOUSBDevice *dev = OSDynamicCast(IOUSBDevice, provider); /* XXX: error check */
/* Do we even have one of the things that we can match on? If not, return NULL. Either 2/255/2, or 224/3/1. */
const IOUSBConfigurationDescriptor *cd;
cd = dev->GetFullConfigurationDescriptor(0);
if (!cd) {
LOG(V_ERROR, "probe: failed to get a configuration descriptor for configuration 0?");
return NULL;
}
/* And look for one of the options. */
IOUSBInterfaceDescriptor *descout;
IOUSBFindInterfaceRequest req;
bool found = false;
ctrlconfig = cd->bConfigurationValue;
req.bInterfaceClass = 2;
req.bInterfaceSubClass = 2;
req.bInterfaceProtocol = 255;
if (dev->FindNextInterfaceDescriptor(cd, NULL, &req, &descout) == kIOReturnSuccess) {
LOG(V_NOTE, "probe: looks like we're good (2/2/255)");
ctrlclass = 2;
ctrlsubclass = 2;
ctrlprotocol = 255;
found = true;
}
req.bInterfaceClass = 224;
req.bInterfaceSubClass = 1;
req.bInterfaceProtocol = 3;
if (dev->FindNextInterfaceDescriptor(cd, NULL, &req, &descout) == kIOReturnSuccess) {
ctrlclass = 224;
ctrlsubclass = 1;
ctrlprotocol = 3;
LOG(V_NOTE, "probe: looks like we're good (224/1/3)");
found = true;
}
if (!found) {
LOG(V_NOTE, "probe: this composite device is not for us");
return NULL;
}
*score += 10000;
return this;
}
/***** 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. Sigh... */
bool HoRNDISInterface::init(IONetworkController * controller, int mtu) {
maxmtu = mtu;
if (IOEthernetInterface::init(controller) == false)
return false;
LOG(V_NOTE, "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() {
HoRNDISInterface * netif = new HoRNDISInterface;
if (!netif)
return NULL;
if (!netif->init(this, mtu)) {
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);
fNetworkInterface->registerService();
return true;
}
/***** Interface enable and disable logic *****/
/* Contains buffer alloc and dealloc, notably. Why do that here? Because that's what Apple did. */
IOReturn HoRNDIS::enable(IONetworkInterface *netif) {
IONetworkMedium *medium;
IOReturn rtn = kIOReturnSuccess;
LOG(V_DEBUG, "enable from tid %p", current_thread());
if (fNetifEnabled) {
LOG(V_ERROR, "already enabled?");
return kIOReturnSuccess;
}
if (!allocateResources())
return kIOReturnNoMemory;
if (!fMediumDict)
if (!createMediumTables()) {
rtn = kIOReturnNoMemory;
goto bailout;
}
setCurrentMedium(IONetworkMedium::medium(kIOMediumEthernetAuto, 480 * 1000000));
/* Kick off the first read. */
inbuf.comp.target = this;
inbuf.comp.action = dataReadComplete;
inbuf.comp.parameter = NULL;
rtn = fInPipe->Read(inbuf.mdp, &inbuf.comp, NULL);
if (rtn != kIOReturnSuccess)
goto bailout;
/* Tell the world that the link is up... */
medium = IONetworkMedium::getMediumWithType(fMediumDict, kIOMediumEthernetAuto);
setLinkStatus(kIONetworkLinkActive | kIONetworkLinkValid, medium, 480 * 1000000);
/* ... and then listen for packets! */
getOutputQueue()->setCapacity(TRANSMIT_QUEUE_SIZE);
getOutputQueue()->start();
LOG(V_DEBUG, "txqueue started");
/* Tell the other end to start transmitting. */
if (!rndisSetPacketFilter(RNDIS_DEFAULT_FILTER))
goto bailout;
/* Now we can say we're alive. */
fNetifEnabled = true;
LOG(V_DEBUG, "done from tid %p", current_thread());
return kIOReturnSuccess;
bailout:
LOG(V_ERROR, "setting up the pipes failed");
releaseResources();
return rtn;
}
IOReturn HoRNDIS::disable(IONetworkInterface * netif) {
LOG(V_DEBUG, "disable from tid %p", current_thread());
/* Disable the queue (no more outputPacket), and then flush everything in the queue. */
getOutputQueue()->stop();
getOutputQueue()->setCapacity(0);
getOutputQueue()->flush();
/* Other end should stop xmitting, too. */
rndisSetPacketFilter(0);
setLinkStatus(0, 0);
/* Release all resources */
releaseResources();
fNetifEnabled = false;
/* Terminates also close the device in 'disable'. */
if (fTerminate) {
fpDevice->close(this);
fpDevice = NULL;
}
LOG(V_DEBUG, "done from tid %p", current_thread());
return kIOReturnSuccess;
}
bool HoRNDIS::createMediumTables() {
IONetworkMedium *medium;
fMediumDict = OSDictionary::withCapacity(1);
if (fMediumDict == NULL)
return false;
LOG(V_PTR, "PTR: fMediumDict: %p", fMediumDict);
medium = IONetworkMedium::medium(kIOMediumEthernetAuto, 480 * 1000000);
IONetworkMedium::addMedium(fMediumDict, medium);
if (publishMediumDictionary(fMediumDict) != true)
return false;
return true;
}
bool HoRNDIS::allocateResources() {
int i;
LOG(V_DEBUG, "allocateResources");
/* Grab a memory descriptor pointer for data-in. */
inbuf.mdp = IOBufferMemoryDescriptor::withCapacity(MAX_BLOCK_SIZE, kIODirectionIn);
if (!inbuf.mdp)
return false;
LOG(V_PTR, "PTR: inbuf.mdp: %p", i, inbuf.mdp); /* does this i belong here? */
inbuf.mdp->setLength(MAX_BLOCK_SIZE);
inbuf.buf = (void *)inbuf.mdp->getBytesNoCopy();
/* And a handful for data-out... */
LOG(V_DEBUG, "allocating %d buffers", N_OUT_BUFS);
outbuf_lock = IOLockAlloc();
LOG(V_PTR, "PTR: outbuf_lock: %p", outbuf_lock);
for (i = 0; i < N_OUT_BUFS; i++) {
outbufs[i].mdp = IOBufferMemoryDescriptor::withCapacity(MAX_BLOCK_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(MAX_BLOCK_SIZE);
outbufs[i].buf = (UInt8*)outbufs[i].mdp->getBytesNoCopy();
outbufs[i].inuse = false;
}
return true;
}
void HoRNDIS::releaseResources() {
int i;
LOG(V_DEBUG, "releaseResources");
for (i = 0; i < N_OUT_BUFS; i++)
if (outbufs[i].mdp) {
outbufs[i].mdp->release();
outbufs[i].mdp = NULL;
}
if (inbuf.mdp) {
inbuf.mdp->release();
inbuf.mdp = NULL;
}
if (outbuf_lock) {
IOLockFree(outbuf_lock);
outbuf_lock = NULL;
}
}
IOOutputQueue* HoRNDIS::createOutputQueue() {
return IOBasicOutputQueue::withTarget(this, TRANSMIT_QUEUE_SIZE);
}
bool HoRNDIS::configureInterface(IONetworkInterface *netif) {
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 | kIOPacketFilterMulticast | kIOPacketFilterPromiscuous;
else
rtn = super::getPacketFilters(group, filters);
return rtn;
}
IOReturn HoRNDIS::getMaxPacketSize(UInt32 * maxSize) const {
*maxSize = mtu;
return kIOReturnSuccess;
}
IOReturn HoRNDIS::selectMedium(const IONetworkMedium *medium) {
setSelectedMedium(medium);
return kIOReturnSuccess;
}
IOReturn HoRNDIS::getHardwareAddress(IOEthernetAddress *ea) {
UInt32 i;
void *buf;
unsigned char *bp;
int rlen = -1;
int rv;
buf = IOMalloc(RNDIS_CMD_BUF_SZ);
if (!buf)
return kIOReturnNoMemory;
rv = rndisQuery(buf, OID_802_3_PERMANENT_ADDRESS, 48, (void **) &bp, &rlen);
if (rv < 0) {
LOG(V_ERROR, "getHardwareAddress OID failed?");
IOFree(buf, RNDIS_CMD_BUF_SZ);
return kIOReturnIOError;
}
LOG(V_DEBUG, "MAC Address %02x:%02x:%02x:%02x:%02x:%02x -- rlen %d",
bp[0], bp[1], bp[2], bp[3], bp[4], bp[5],
rlen);
for (i=0; i<6; i++)
ea->bytes[i] = bp[i];
IOFree(buf, RNDIS_CMD_BUF_SZ);
return kIOReturnSuccess;
}
IOReturn HoRNDIS::setPromiscuousMode(bool active) {
(void) active;
/* XXX This actually needs to get passed down to support 'real' RNDIS devices, but it will work okay for Android devices. */
return kIOReturnSuccess;
}
IOReturn HoRNDIS::message(UInt32 type, IOService *provider, void *argument) {
IOReturn ior;
switch (type) {
case kIOMessageServiceIsTerminated:
LOG(V_NOTE, "kIOMessageServiceIsTerminated");
if (!fNetifEnabled) {
if (fCommInterface) {
fCommInterface->close(this);
fCommInterface->release();
fCommInterface = NULL;
}
if (fDataInterface) {
fDataInterface->close(this);
fDataInterface->release();
fDataInterface = NULL;
}
fpDevice->close(this);
fpDevice = NULL;
}
fTerminate = true;
return kIOReturnSuccess;
case kIOMessageServiceIsSuspended:
LOG(V_NOTE, "kIOMessageServiceIsSuspended");
break;
case kIOMessageServiceIsResumed:
LOG(V_NOTE, "kIOMessageServiceIsResumed");
break;
case kIOMessageServiceIsRequestingClose:
LOG(V_NOTE, "kIOMessageServiceIsRequestingClose");
break;
case kIOMessageServiceWasClosed:
LOG(V_NOTE, "kIOMessageServiceWasClosed");
break;
case kIOMessageServiceBusyStateChange:
LOG(V_NOTE, "kIOMessageServiceBusyStateChange");
break;
case kIOUSBMessagePortHasBeenResumed:
LOG(V_NOTE, "kIOUSBMessagePortHasBeenResumed");
/* Try to resurrect any dead reads. */
if (fDataDead) {
ior = fInPipe->Read(inbuf.mdp, &inbuf.comp, NULL);
if (ior == kIOReturnSuccess)
fDataDead = false;
else
LOG(V_ERROR, "failed to queue Data pipe read");
}
break;
case kIOUSBMessageHubResumePort:
LOG(V_NOTE, "kIOUSBMessageHubResumePort");
break;
case kIOMessageServiceIsAttemptingOpen:
LOG(V_NOTE, "kIOMessageServiceIsAttemptingOpen");
break;
default:
LOG(V_NOTE, "unknown message type %08x", (unsigned int) type);
break;
}
return kIOReturnUnsupported;
}
/***** Packet transmit logic *****/
UInt32 HoRNDIS::outputPacket(mbuf_t packet, void *param) {
mbuf_t m;
size_t pktlen = 0;
IOReturn ior = kIOReturnSuccess;
UInt32 poolIndx;
int i;
LOG(V_DEBUG, "");
/* Count the total size of this packet */
m = packet;
while (m) {
pktlen += mbuf_len(m);
m = mbuf_next(m);
}
LOG(V_DEBUG, "%ld bytes", pktlen);
if (pktlen > (mtu + 14)) {
LOG(V_ERROR, "packet too large (%ld bytes, but I told you you could have %d!)", pktlen, mtu);
fpNetStats->outputErrors++;
return false;
}
/* Find an output buffer in the pool */
IOLockLock(outbuf_lock);
for (i = 0; i < OUT_BUF_MAX_TRIES; i++) {
uint64_t ivl, deadl;
for (poolIndx = 0; poolIndx < N_OUT_BUFS; poolIndx++)
if (!outbufs[poolIndx].inuse) {
outbufs[poolIndx].inuse = true;
break;
}
if (poolIndx != N_OUT_BUFS)
break;
/* "while", not "if". See Symphony X's seminal work on this topic, /Paradise Lost/ (2007). */
nanoseconds_to_absolutetime(OUT_BUF_WAIT_TIME, &ivl);
clock_absolutetime_interval_to_deadline(ivl, &deadl);
LOG(V_NOTE, "waiting for buffer...");
IOLockSleepDeadline(outbuf_lock, outbufs, *(AbsoluteTime *)&deadl, THREAD_INTERRUPTIBLE);
}
IOLockUnlock(outbuf_lock);
if (poolIndx == N_OUT_BUFS) {
LOG(V_ERROR, "timed out waiting for buffer");
return kIOReturnTimeout;
}
/* Start filling in the send buffer */
struct rndis_data_hdr *hdr;
hdr = (struct rndis_data_hdr *)outbufs[poolIndx].buf;
outbufs[poolIndx].inuse = true;
outbufs[poolIndx].mdp->setLength(pktlen + sizeof *hdr);
memset(hdr, 0, sizeof *hdr);
hdr->msg_type = RNDIS_MSG_PACKET;
hdr->msg_len = cpu_to_le32(pktlen + sizeof *hdr);
hdr->data_offset = cpu_to_le32(sizeof(*hdr) - 8);
hdr->data_len = cpu_to_le32(pktlen);
mbuf_copydata(packet, 0, pktlen, hdr + 1);
freePacket(packet);
/* Now, fire it off! */
outbufs[poolIndx].comp.target = this;
outbufs[poolIndx].comp.parameter = (void *)poolIndx;
outbufs[poolIndx].comp.action = dataWriteComplete;
ior = fOutPipe->Write(outbufs[poolIndx].mdp, &outbufs[poolIndx].comp);
if (ior != kIOReturnSuccess) {
LOG(V_ERROR, "write failed");
if (ior == kIOUSBPipeStalled) {
fOutPipe->Reset();
ior = fOutPipe->Write(outbufs[poolIndx].mdp, &outbufs[poolIndx].comp);
if (ior != kIOReturnSuccess) {
LOG(V_ERROR, "write really failed");
fpNetStats->outputErrors++;
return ior;
}
}
}
fpNetStats->outputPackets++;
return kIOReturnOutputSuccess;
}
void HoRNDIS::dataWriteComplete(void *obj, void *param, IOReturn rc, UInt32 remaining) {
HoRNDIS *me = (HoRNDIS *)obj;
unsigned long poolIndx = (unsigned long)param;
poolIndx = (unsigned long)param;