Why does pcap_sendpacket fail on Thunderbolt interface? - macos

In a multi platform project I am using pcap to get a list of all network interfaces, open each (user cannot select which interfaces to use) and send/receive packets (Ethernet type 0x88e1/HomePlugAV) on each. This works fine on Windows and on Mac OS X, but sometimes on Mac OS X pcap_sendpacket fails after some time on the interface that networksetup -listallhardwareports lists as "Hardware Port: Thunderbolt 1". The error is:
send: No buffer space available
When the program is run after the machine was booted, then it takes some time until the error occurs. When the error occurred once and I stop my program, the error occurs immediately when I restart my program without rebooting the machine.
ifconfig -v en9:
en9: flags=8963<UP,BROADCAST,SMART,RUNNING,PROMISC,SIMPLEX,MULTICAST> mtu 1500 index 8
eflags=80<TXSTART>
options=60<TSO4,TSO6>
ether b2:00:1e:94:9b:c1
media: autoselect <full-duplex>
status: inactive
type: Ethernet
scheduler: QFQ
networksetup -listallhardwareports (only the relevant parts):
Hardware Port: Thunderbolt 1
Device: en9
Ethernet Address: b2:00:1e:94:9b:c1
Tests show that on OS X 10.9 the interface is not up initially, but on OS X 10.9.2 and 10.9.3 the interface is up and running after booting.
On OS X 10.9 ifconfig initially says:
en5: flags=8822<BROADCAST,SMART,SIMPLEX,MULTICAST> mtu 1500 index 8
After ifconfig en5 up the problematic behavior is the same on OS X 10.9.
Why does pcap_sendpacket fail on the Thunderbolt adapter?
How can my program detect that this is a troubling interface before opening it? I know I could open the interface and try to send one packet, but I'ld prefer to do a clean detection beforehand.

As a workaround, you can ignore the "Thunderbolt 1" interface:
#include <stdio.h>
#include <pcap/pcap.h>
#include <CoreFoundation/CoreFoundation.h>
#include <SystemConfiguration/SCNetworkConfiguration.h>
const char thunderbolt[] = "Thunderbolt 1";
// Build with -framework CoreFoundation -framework SystemConfiguration
int main(int argc, char * argv[])
{
// See: https://opensource.apple.com/source/configd/configd-596.13/SystemConfiguration.fproj/SCNetworkInterface.c
// get Ethernet, Firewire, Thunderbolt, and AirPort interfaces
CFArrayRef niArrayRef = SCNetworkInterfaceCopyAll();
// Find out the thunderbolt iface
char thunderboltInterface[4] = "";
if(niArrayRef) {
CFIndex cnt = CFArrayGetCount(niArrayRef);
for(CFIndex idx = 0; idx < cnt; ++idx) {
SCNetworkInterfaceRef tSCNetworkInterfaceRef = (SCNetworkInterfaceRef)CFArrayGetValueAtIndex(niArrayRef, idx);
if(tSCNetworkInterfaceRef) {
CFStringRef BSDName = SCNetworkInterfaceGetBSDName(tSCNetworkInterfaceRef);
const char * interfaceName = (BSDName == NULL) ? "none" : CFStringGetCStringPtr(BSDName, kCFStringEncodingUTF8);
CFStringRef localizedDisplayName = SCNetworkInterfaceGetLocalizedDisplayName(tSCNetworkInterfaceRef);
const char * interfaceType = (localizedDisplayName == NULL) ? "none" : CFStringGetCStringPtr(localizedDisplayName, kCFStringEncodingUTF8);
printf("%s : %s\n", interfaceName, interfaceType);
if(strcmp(interfaceType, thunderbolt) == 0) {
// Make a copy this time
CFStringGetCString(BSDName, thunderboltInterface, sizeof(thunderboltInterface), kCFStringEncodingUTF8);
}
}
}
}
printf("%s => %s\n", thunderbolt, thunderboltInterface);
CFRelease(niArrayRef);
return 0;
}

I'm guessing from
When the program is run after the machine was booted, then it takes some time until the error occurs. When the error occurred once and I stop my program, the error occurs immediately when I restart my program without rebooting the machine.
that what's probably happening here is that the interface isn't active, so packets given to it to send aren't transmitted (and the mbuf(s) for them freed), and aren't discarded, but are, instead, just left in the interface's queue to be transmitted. Eventually either the queue fills up or an attempt to allocate some resource for the packet fails, and the interface's driver returns an ENOBUFS error.
This is arguably an OS X bug.
From
In a multi platform project I am using pcap to get a list of all network interfaces, open each (user cannot select which interfaces to use) and send/receive packets (Ethernet type 0x88e1/HomePlugAV) on each.
I suspect you aren't sending on all interfaces; not all interfaces have a link-layer header type that has an Ethernet type field - for example, lo0 doesn't.
If you're constructing Ethernet packets, you would only want to send on interfaces with a link-layer header type (as returned by pcap_datalink()) of DLT_EN10MB ("10MB" is a historical artifact; it refers to all Ethernet types except for the old experimental 3MB Xerox Ethernet, which had a different link-layer header).
You probably also don't want to bother with interfaces that aren't "active" in some sense (some sense other than "is up"); unfortunately, there's no platform-independent API to determine that, so you're going to have to fall back on #ifdefs here. That would probably rule out interfaces where the packets would pile up unsent and eventually cause an ENOBUFS error.

Related

Raw socket for directing IPv6 datagrams to the kernel

I’m looking to inject IPv6 datagrams available in the user space (and received through a scheme that first requires some unwrapping that's performed in the user space) to a suitable raw socket for further processing by the Linux kernel. This is fairly simple to do with IPv4 using the following code:
int fd=socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
struct sockaddr_ll sa;
memset(sa, 0, sizeof(sa));
// ip4h is the IPv4 datagram unwrapped in the user space and ready to be
// sent to the kernel
if (sendto(fd, iph, iplen, 0, (struct sockaddr *)&sa, sizeof(sa)) != iplen) {
// Error processing.
}
The above injects full IPv4 packets (including the IPv4 headers), and the IPv4 payload gets processed appropriately by the Linux stack. How should the above be modified for use with IPv6 packets? The following adjustments I tried did not work:
int fd=socket(AF_PACKET, SOCK_DGRAM, htons(ETH_P_ALL));
sa.sll_family=AF_PACKET;
sa.sll_protocol=htons(ETH_P_IPV6);
sa.sll_halen=ETH_ALEN;
sa.sll_ifindex=2; // <index of eth0>
if (sendto(fd, iph, iplen, 0, (struct sockaddr *)&sa, sizeof(sa)) != iplen) {
// Error processing.
}
Any thoughts on why the above doesn't work with raw IPv6 datagrams? 'tcpdump ip6' does show the IPv6 packets I'm inserting, which suggests the kernel sees them! It just happens to be ignoring them as well.

How to add Multicast Group under a specific interface (Windows)

I can use the command "netsh interface ip show joins" in cmd to show multicast group under each interface. But I really don't know how to add a group to a
interface, like adding a IP address 239.39.188.188 to "Interface 8: VirtualBox Host-Only Network". The simplest way would be appreciated.
Interface 3: Ethernet
Scope References Last Address
---------- ---------- ---- ---------------------
0 0 Yes 224.0.0.1
Interface 1: Loopback Interface
Scope References Last Address
---------- ---------- ---- ---------------------
0 2 Yes 239.255.255.250
Interface 8: VirtualBox Host-Only Network
Scope References Last Address
---------- ---------- ---- ---------------------
0 0 Yes 224.0.0.1
0 1 Yes 224.0.0.251
239.39.188.188 // this is what I want to add
Btw, I tried with some methods, like opening UDP socket and setting IP_ADD_MEMBERSHIP (How to add my host to Multicast Group...!). Also, I tried with a command on linux "ip maddr [ add | del ] MULTIADDR dev STRING".
After that, I observed that IP_ADD_MEMBERSHIP was set successfully. But as the result, in the above table, I cannot add a group under a specific interface.
For opening UDP socket and setting IP_ADD_MEMBERSHIP part, I coded in linux as belows.
ip_mreq mreq;
mreq.imr_multiaddr.s_addr = inet_addr(_outIP.c_str()); // _outIP is destination address(group address), interface is ethernet interface
mreq.imr_interface.s_addr = _interface.length() > 0 ? inet_addr(_interface.c_str()) : htonl(INADDR_ANY);
if (setsockopt(_udpSock,IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(struct ip_mreq)) == -1) {
cout << "Fail to add ip membership!!!!" << endl;
}
else {
cout << "Success to add ip membership!!!!" << endl;
s = sprintf(warnmsg, "Success to add ip membership!!!!");
_ofile->write(warnmsg, s);
}
You must keep the socket with which you joined the group open forever. In other words, your program must not terminate. Add a for (;;) { sleep(1000000); } or so at the end.
When you program terminates, the socket gets closed automatically and your OS (Windows or Linux, it does not matter) leaves the group again.
What happens in the OS is slightly more complex as multiple programs may join the same multicast group, so the OS keeps a reference count and the machine only leaves the group when the group is no longer references by any socket.

Portaudio not working with some USB Audio devices

I have a program that outputs audio via Portaudio. It works for the most part, but there are some USB devices that use the built-in Windows USBAudio drivers that don't work.
I don't get any error and the program shows data being processed in my program, but when the audio stream is sent to portaudio, no sound is output from the USB device. It seems as if portaudio is not initializing the device and therefore can't send the data stream to it.
Some USB devices will work on one USB port, but when I move it to a different USB port on the same computer, it will not work.
Other USB devices will not work on any USB port.
However, all the USB devices work fine when outputting sound from other programs or when using the Windows test audio output.
I cannot figure out why some USB devices work and others don;t even though they are all using the same USB drivers.
Here's the part of my code that initiates the portaudio stream:
static int paPlayCallback( const void *inputBuffer, void *output,
unsigned long framesPerBuffer,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData ){
if(Out2){
int sz= Out2->Size();
if(sz>QUEUE_SIZE)start=1;
if(sz==0){
for(int i=0;i<10;i++)
averagePower[i]= 0.0;
start=0;
}
if(start){
printf("Output queue size %d\n",sz);
while(sampleCount<OUT_BUF_SIZE)
sampleCount+= AddBuffer();
Resample((float*)output, l,r,framesPerBuffer,dev.parameters.channelCount);
DelBuffer();
return paContinue;
}
}
memset(output,0, framesPerBuffer*dev.parameters.channelCount*4);
return paContinue;
}
static void StreamFinished( void* userData )
{
// exit(-1);
}
BOOL Play(int device){
dev.info = Pa_GetDeviceInfo( device );
dev.parameters.device = device;
dev.parameters.channelCount = dev.info->maxOutputChannels;
dev.parameters.sampleFormat = paFloat32;
if((dev.sampleRate = GetSampleRate(&dev.parameters))<=0){
fprintf(stderr,"Error: Bad output device sample rate.\n");
goto error;
}
int frameSize= (int)floor(dev.sampleRate/FPS);
PaError err;
do{
err= Pa_OpenStream(
&dev.stream,
NULL,
&dev.parameters,
dev.sampleRate,
frameSize,
paClipOff,
paPlayCallback,
0);
if(err ){
fprintf(stderr,"Error: Can't open %s in WASAPI exclusive mode.\n",dev.info->name);
}
}while(err != paNoError );
error_check(Pa_SetStreamFinishedCallback( dev.stream, &StreamFinished ));
error_check(Pa_StartStream( dev.stream ));
return TRUE;
error:
return FALSE;
}
It looks like you are opening the steam in shared mode. You must explicitly set the steam to use exclusive mode with the API specific parameters.
This post should demonstrate the correct syntax.
You might verify this by modifying the windows device settings to match your stream settings. If the settings match you should be able to open the device and stream to it successfully.
You may leave the device in shared mode if you query the device to get the default sample rate and type. In shared mode you can only open the device with the default settings.
MSDN article on exclusive streams

Linux USB driver: Interrupt URBs

I suppose I actually have two separate questions, but I think that they are related enough to include them both. The context is a Linux USB device driver (not userspace).
After transmitting a request URB, how do I receive the response once my complete callback is called?
How can I use interrupt URBs for single request/response pairs, and not as actual continuous interrupt polling (as they are intended)?
So for some background, I'm working on a driver for the Microchip MCP2210 a USB-to-SPI Protocol Converter with GPIO (USB 2.0, datasheet here). This device advertises as generic HID and exposes two interrupt endpoints (an in and an out) as well as it's control endpoint.
I am starting from a working, (but alpha-quality) demo driver written by somebody else and kindly shared with the community. However, this is a HID driver and the mechanism it uses to communicate with the device is very expensive! (sending a 64 byte message requires allocating a 6k HID report struct, and allocation is sometimes performed in the context of an interrupt, requiring GFP_ATOMIC!). We'll be accessing this from an embedded low-memory device.
I'm new to USB drivers and still pretty green with Linux device drivers in general. However, I'm trying to convert this to a plain-jane USB driver (not HID) so I can use the less expensive interrupt URBs for my communications. Here is my code for transmitting my request. For the sake of (attempted) brevity, I'm not including the definition of my structs, etc, but please let me know if you need more of my code. dev->cur_cmd is where I'm keeping the current command I'm processing.
/* use a local for brevity */
cmd = dev->cur_cmd;
if (cmd->state == MCP2210_CMD_STATE_NEW) {
usb_fill_int_urb(dev->int_out_urb,
dev->udev,
usb_sndintpipe(dev->udev, dev->int_out_ep->desc.bEndpointAddress),
&dev->out_buffer,
sizeof(dev->out_buffer), /* always 64 bytes */
cmd->type->complete,
cmd,
dev->int_out_ep->desc.bInterval);
ret = usb_submit_urb(dev->int_out_urb, GFP_KERNEL);
if (ret) {
/* snipped: handle error */
}
cmd->state = MCP2210_CMD_STATE_XMITED;
}
And here is my complete fn:
/* note that by "ctrl" I mean a control command, not the control endpoint */
static void ctrl_complete(struct urb *)
{
struct mcp2210_device *dev = urb->context;
struct mcp2210_command *cmd = dev->cur_cmd;
int ret;
if (unlikely(!cmd || !cmd->dev)) {
printk(KERN_ERR "mcp2210: ctrl_complete called w/o valid cmd "
"or dev\n");
return;
}
switch (cmd->state) {
/* Time to rx the response */
case MCP2210_CMD_STATE_XMITED:
/* FIXME: I think that I need to check the response URB's
* status to find out if it was even transmitted or not */
usb_fill_int_urb(dev->int_in_urb,
dev->udev,
usb_sndintpipe(dev->udev, dev->int_in_ep->desc
.bEndpointAddress),
&dev->in_buffer,
sizeof(dev->in_buffer),
cmd->type->complete,
dev,
dev->int_in_ep->desc.bInterval);
ret = usb_submit_urb(dev->int_in_urb, GFP_KERNEL);
if (ret) {
dev_err(&dev->udev->dev,
"while attempting to rx response, "
"usb_submit_urb returned %d\n", ret);
free_cur_cmd(dev);
return;
}
cmd->state = MCP2210_CMD_STATE_RXED;
return;
/* got response, now process it */
case MCP2210_CMD_STATE_RXED:
process_response(cmd);
default:
dev_err(&dev->udev->dev, "ctrl_complete called with unexpected state: %d", cmd->state);
free_cur_cmd(dev);
};
}
So am I at least close here? Secondly, both dev->int_out_ep->desc.bInterval and dev->int_in_ep->desc.bInterval are equal to 1, will this keep sending my request every 125 microseconds? And if so, how do I say "ok, ty, now stop this interrupt". The MCP2210 offers only one configuration, one interface and that has just the two interrupt endpoints. (I know everything has the control interface, not sure where that fits into the picture though.)
Rather than spam this question with the lsusb -v, I'm going to pastebin it.
Typically, request/response communication works as follows:
Submit the response URB;
submit the request URB;
in the request completion handler, if the request was not actually sent, cancel the response URB and abort;
in the response completion handler, handle the response data.
All that asynchronous completion handler stuff is a big hassle if you have a single URB that is completed almost immediately; therefore, there is the helper function usb_interrupt_msg() which works synchronously.
URBs to be used for polling must be resubmitted (typically from the completion handler).
If you do not resubmit the URB, no polling happens.

Using a specific network interface for a socket in windows

Is there a reliable way in Windows, apart from changing the routing table, to force a newly created socket to use a specific network interface? I understand that bind() to the interface's IP address does not guarantee this.
(Ok second time lucky..)
FYI there's another question here perform connect() on specific network adapter along the same lines...
According to The Cable Guy
Windows XP and Windows Server® 2003
use the weak host model for sends and
receives for all IPv4 interfaces and
the strong host model for sends and
receives for all IPv6 interfaces. You
cannot configure this behavior. The
Next Generation TCP/IP stack in
Windows Vista and Windows Server 2008
supports strong host sends and
receives for both IPv4 and IPv6 by
default on all interfaces except the
Teredo tunneling interface for a
Teredo host-specific relay.
So to answer your question (properly, this time) in Windows XP and Windows Server 2003 IP4 no, but for IP6 yes. And for Windows Vista and Windows 2008 yes (except for certain circumstances).
Also from http://www.codeguru.com/forum/showthread.php?t=487139
On Windows, a call to bind() affects
card selection only incoming traffic,
not outgoing traffic. Thus, on a
client running in a multi-homed system
(i.e., more than one interface card),
it's the network stack that selects
the card to use, and it makes its
selection based solely on the
destination IP, which in turn is based
on the routing table. A call to bind()
will not affect the choice of the card
in any way.
It's got something to do with
something called a "Weak End System"
("Weak E/S") model. Vista changed to a
strong E/S model, so the issue might
not arise under Vista. But all prior
versions of Windows used the weak E/S
model.
With a weak E/S model, it's the
routing table that decides which card
is used for outgoing traffic in a
multihomed system.
See if these threads offer some
insight:
"Local socket binding on multihomed
host in Windows XP does not work" at
http://www.codeguru.com/forum/showthread.php?t=452337
"How to connect a port to a specified
Networkcard?" at
http://www.codeguru.com/forum/showthread.php?t=451117.
This thread mentions the
CreateIpForwardEntry() function, which
(I think) can be used to create an
entry in the routing table so that all
outgoing IP traffic with a specified
server is routed via a specified
adapter.
"Working with 2 Ethernet cards" at
http://www.codeguru.com/forum/showthread.php?t=448863
"Strange bind behavior on multihomed
system" at
http://www.codeguru.com/forum/showthread.php?t=452368
Hope that helps!
I'm not sure why you say bind is not working reliably. Granted I have not done exhaustive testing, but the following solution worked for me (Win10, Visual Studio 2019). I needed to send a broadcast message via a particular NIC, where multiple NICs might be present on a computer. In the snippet below, I want the broadcast message to go out on the NIC with IP of .202.106.
In summary:
create a socket
create a sockaddr_in address with the IP address of the NIC you want to send FROM
bind the socket to that FROM sockaddr_in
create another sockaddr_in with the IP of your broadcast address (255.255.255.255)
do a sendto, passing the socket created is step 1, and the sockaddr of the broadcast address.
`
static WSADATA wsaData;
static int ServoSendPort = 8888;
static char ServoSendNetwork[] = "192.168.202.106";
static char ServoSendBroadcast[] = "192.168.255.255";
`
... < snip >
if ( WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR )
return false;
// Make a UDP socket
SOCKET ServoSendSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
int iOptVal = TRUE;
int iOptLen = sizeof(int);
int RetVal = setsockopt(ServoSendSocket, SOL_SOCKET, SO_BROADCAST, (char*)&iOptVal, iOptLen);
// Bind it to a particular interface
sockaddr_in ServoBindAddr={0};
ServoBindAddr.sin_family = AF_INET;
ServoBindAddr.sin_addr.s_addr = inet_addr( ServoSendNetwork ); // target NIC
ServoBindAddr.sin_port = htons( ServoSendPort );
int bindRetVal = bind( ServoSendSocket, (sockaddr*) &ServoBindAddr, sizeof(ServoBindAddr) );
if (bindRetVal == SOCKET_ERROR )
{
int ErrorCode = WSAGetLastError();
CString errMsg;
errMsg.Format ( _T("rats! bind() didn't work! Error code %d\n"), ErrorCode );
OutputDebugString( errMsg );
}
// now create the address to send to...
sockaddr_in ServoSendAddr={0};
ServoSendAddr.sin_family = AF_INET;
ServoSendAddr.sin_addr.s_addr = inet_addr( ServoSendBroadcast ); //
ServoSendAddr.sin_port = htons( ServoSendPort );
...
#define NUM_BYTES_SERVO_SEND 20
unsigned char sendBuf[NUM_BYTES_SERVO_SEND];
int BufLen = NUM_BYTES_SERVO_SEND;
ServoSocketStatus = sendto(ServoSendSocket, (char*)sendBuf, BufLen, 0, (SOCKADDR *) &ServoSendAddr, sizeof(ServoSendAddr));
if(ServoSocketStatus == SOCKET_ERROR)
{
ServoUdpSendBytes = WSAGetLastError();
CString message;
message.Format(_T("Error transmitting UDP message to Servo Controller: %d."), ServoSocketStatus);
OutputDebugString(message);
return false;
}

Resources