C++ Libusb isn't bringing back serial number of device - c++

I'm currently working on a project that involves bringing information back from devices plugged in via true usb. To solve this, I'm attempting to use libusb in my C++ project. I'm on Windows 10, using C++ and QT Creator with QT version 5.2.1. I can get the vendor ID and product ID of my device with .idVendor and idProduct. However, my serial number is returning as 0 with .iSerialNumber. I'll post my code below and hopefully someone can help me figure out what I'm missing or suggest another library for me to try. Thanks!
bool CPumpFinder::pollTrueUSB(boolean &deviceFound, Device &newDevice)
{
boolean usbFound = FALSE;
boolean accuCheckFound = FALSE;
AccuGuideCom *acc = new AccuGuideCom();
libusb_device **devs; //pointer to pointer of device, used to retrieve a list of devices
libusb_context *ctx = NULL; //a libusb session
int r; //for return values
ssize_t cnt; //holding number of devices in list
r = libusb_init(&ctx); //initialize a library session
if(r < 0) {
return 1;
}
libusb_set_debug(ctx, 3); //set verbosity level to 3, as suggested in the documentation
cnt = libusb_get_device_list(ctx, &devs); //get the list of devices
if(cnt < 0) {
}
ssize_t i; //for iterating through the list
for(i = 0; i < cnt; i++) {
printdev(devs[i], usbFound, accuCheckFound); //print specs of this device
if(usbFound == TRUE)
{
if(accuCheckFound == TRUE)
{
newDevice.displayName = "ACCU-CHEK GUIDE";
newDevice.type = DEVICE_ACCUCHECKGUIDE;
newDevice.vendorID = accuVID;
newDevice.productID = accuPID;
newDevice.serial = accuSerial;
}
deviceFound = TRUE;
break;
}
}
libusb_free_device_list(devs, 1); //free the list, unref the devices in it
libusb_exit(ctx); //close the session
return deviceFound;
}
boolean CPumpFinder::printdev(libusb_device *dev, boolean &usbFound, boolean
&accuChekFound) {
libusb_device_descriptor desc;
int r = libusb_get_device_descriptor(dev, &desc);
if (r < 0) {
return usbFound;
}
uint16 vID = (uint16)desc.idVendor;
uint16 pID = (uint16)desc.idProduct; //desc.iSerialNumber
//#define ACCUCHEK_GUIDE_VENDORID (uint16)0x173A
//#define ACCUCHEK_GUIDE_PRODUCTID (uint16)0x21D5
if((vID == 5946) & (pID == 8661))
{
accuPID = pID;
accuVID = vID;
//Do serial?
accuSerial = "Test";
write_text_to_log_file("we did it");
accuChekFound = TRUE;
usbFound = TRUE;
}
if(usbFound == TRUE)
{
libusb_config_descriptor *config;
libusb_get_config_descriptor(dev, 0, &config);
const libusb_interface *inter;
const libusb_interface_descriptor *interdesc;
const libusb_endpoint_descriptor *epdesc;
for(int i=0; i<(int)config->bNumInterfaces; i++) {
inter = &config->interface[i];
for(int j=0; j<inter->num_altsetting; j++) {
interdesc = &inter->altsetting[j];
for(int k=0; k<(int)interdesc->bNumEndpoints; k++) {
epdesc = &interdesc->endpoint[k];
}
}
}
libusb_free_config_descriptor(config);
if(accuChekFound == TRUE)
{
return accuChekFound;
}
return usbFound;
}
return usbFound;
}

Related

How to block http flood connections in windows

I have an application made in c ++ that acts as a server. Gameserver.exe
The problem is that they manage to attack gameserver.exe with http flood connections, for example http://ip:port
The attacks are sent from an application called "railgun"
How can I block or prevent these http connections?
Currently I use an anti flood in the gameserver.exe application which is basically this.
int gObjGetIPIndex(char* IpAddress)
{
int Ret = -1;
for (int x = 0; x < LastIPList; x++)
{
if (IPList[x][0] == IpAddress[0])
{
if (strcmp(IPList[x], IpAddress) == 0)
{
return x;
break;
}
}
}
Ret = LastIPList;
sprintf(IPList[LastIPList], "%s", IpAddress);
LastIPList++;
if (LastIPList >= 2000)LastIPList = 0;
return Ret;
}
short gObjAdd(SOCKET socket, char* IpAddress, int aIndex) // OK stdafx.h ?
{
if (OBJECT_RANGE(aIndex) == 0)
{
return -1;
}
if (gObj[aIndex].Connected != OBJECT_OFFLINE)
{
return -1;
}
//========================================
// Anti Flood Fix 13/08/2020
//========================================
if (gServerInfo.m_EnableAntiflood == 1)
{
int IPIndex = gObjGetIPIndex(IpAddress);
DWORD CurTick = GetTickCount();
if ((CurTick - LastConnect[IPIndex]) < 1000)
{
LastConnect[IPIndex] = CurTick;
LogAdd(LOG_RED, "[AntiFlood][%d] BlockAttack (%s)", aIndex, IpAddress);
return -1;
}
LastConnect[IPIndex] = CurTick;
}
Thanks for your time.

CoreAudio Stuff From C++ to Swift

How to convert the code below to swift? Someone help.
I want to convert this cpp code to swift, from project FreeStreamer.
But some C++ struct and some C callback drive me crazy.
Help.
Here is the code from audio_stream.h and audio_stream.cpp
// var
queued_packet_t *m_queuedHead;
queued_packet_t *m_queuedTail;
queued_packet_t *m_playPacket;
std::list <queued_packet_t*> m_processedPackets;
//struct
typedef struct queued_packet {
UInt64 identifier;
AudioStreamPacketDescription desc;
struct queued_packet *next;
char data[];
} queued_packet_t;
//function one
OSStatus Audio_Stream::encoderDataCallback(AudioConverterRef inAudioConverter, UInt32 *ioNumberDataPackets, AudioBufferList *ioData, AudioStreamPacketDescription **outDataPacketDescription, void *inUserData) {
Audio_Stream *THIS = (Audio_Stream *)inUserData;
pthread_mutex_trylock(&THIS->m_packetQueueMutex);
// Dequeue one packet per time for the decoder
queued_packet_t *front = THIS->m_playPacket;
if (!front) {
/* Don't deadlock */
AS_LOCK_TRACE("encoderDataCallback 2: unlock\n");
pthread_mutex_unlock(&THIS->m_packetQueueMutex);
pthread_mutex_trylock(&THIS->m_streamStateMutex);
THIS->m_converterRunOutOfData = true;
pthread_mutex_unlock(&THIS->m_streamStateMutex);
*ioNumberDataPackets = 0;
ioData->mBuffers[0].mDataByteSize = 0;
return noErr;
}
*ioNumberDataPackets = 1;
ioData->mBuffers[0].mData = front->data;
ioData->mBuffers[0].mDataByteSize = front->desc.mDataByteSize;
ioData->mBuffers[0].mNumberChannels = THIS->m_srcFormat.mChannelsPerFrame;
if (outDataPacketDescription) {
*outDataPacketDescription = &front->desc;
}
THIS->m_playPacket = front->next;
THIS->m_processedPackets.push_front(front);
AS_LOCK_TRACE("encoderDataCallback 5: unlock\n");
pthread_mutex_unlock(&THIS->m_packetQueueMutex);
return noErr;
}
//function two
void Audio_Stream::streamDataCallback(void *inClientData, UInt32 inNumberBytes, UInt32 inNumberPackets, const void *inInputData, AudioStreamPacketDescription *inPacketDescriptions) {
AS_TRACE("%s: inNumberBytes %u, inNumberPackets %u\n", __FUNCTION__, (unsigned int)inNumberBytes, (unsigned int)inNumberPackets);
Audio_Stream *THIS = static_cast<Audio_Stream*>(inClientData);
if (!THIS->m_audioStreamParserRunning) {
AS_TRACE("%s: stray callback detected!\n", __PRETTY_FUNCTION__);
return;
}
for (int i = 0; i < inNumberPackets; i++) {
/* Allocate the packet */
UInt32 size = inPacketDescriptions[i].mDataByteSize;
queued_packet_t *packet = (queued_packet_t *)malloc(sizeof(queued_packet_t) + size);
packet->identifier = THIS->m_packetIdentifier;
// If the stream didn't provide bitRate (m_bitRate == 0), then let's calculate it
if (THIS->m_bitRate == 0 && THIS->m_bitrateBufferIndex < kAudioStreamBitrateBufferSize) {
// Only keep sampling for one buffer cycle; this is to keep the counters (for instance) duration
// stable.
THIS->m_bitrateBuffer[THIS->m_bitrateBufferIndex++] = 8 * inPacketDescriptions[i].mDataByteSize / THIS->m_packetDuration;
if (THIS->m_bitrateBufferIndex == kAudioStreamBitrateBufferSize) {
if (THIS->m_delegate) {
THIS->m_delegate->bitrateAvailable();
}
}
}
AS_LOCK_TRACE("streamDataCallback: lock\n");
pthread_mutex_trylock(&THIS->m_packetQueueMutex);
/* Prepare the packet */
packet->next = NULL;
packet->desc = inPacketDescriptions[i];
packet->desc.mStartOffset = 0;
memcpy(packet->data, (const char *)inInputData + inPacketDescriptions[i].mStartOffset,
size);
if (THIS->m_queuedHead == NULL) {
THIS->m_queuedHead = THIS->m_queuedTail = THIS->m_playPacket = packet;
} else {
THIS->m_queuedTail->next = packet;
THIS->m_queuedTail = packet;
}
THIS->m_cachedDataSize += size;
THIS->m_packetIdentifier++;
AS_LOCK_TRACE("streamDataCallback: unlock\n");
pthread_mutex_unlock(&THIS->m_packetQueueMutex);
}
THIS->determineBufferingLimits();
}
All the FreeStreamer project has been rewrite wieth Swift 3.0 in here FreePlayer
Answer can be found here AudioStream

libusb_get_device_list seg fault

I am writing a file explorer application in Qt C++ and have a libUSB function (QList UsbDevice::getDeviceList()) which gets all attached USB devices, checks each one for my products vendor and product ID's, claims them and the returns them in an array. This all works fine and I get the device I want, however I have added a refresh button which should update the device list shown in a drop-down list (it basically calls the getDeviceList function again) but it seg faults when calling:
int numDevices = libusb_get_device_list(NULL, &usbDevices);
the second time around and I can't for the life of me see why. If someone could check over the code below and see if I have missed something stupid that would be very helpful.
QList<UsbDevice*> UsbDevice::getDeviceList()
{
unsigned char manf[256] = {'\0'};
QList<UsbDevice*> usbDeviceList;
libusb_device **usbDevices;
struct libusb_device_descriptor desc;
int numDevices = libusb_get_device_list(NULL, &usbDevices);
if(numDevices < 0)
{
libusb_free_device_list(usbDevices, 1);
return usbDeviceList;
}
QString error;
for(int i=0; i!=numDevices; ++i)
{
libusb_device *dev = usbDevices[i];
libusb_get_device_descriptor(dev, &desc);
if((desc.idVendor != VendorUsbId) && (desc.idProduct != ProductUsbId))
continue;
libusb_device_handle *handle = NULL;
libusb_config_descriptor *conf_desc = NULL;
int result = 0;
result = libusb_open(dev, &handle);
if(result < 0)
{
if(result == -3)
{
}
error = QString(libusb_error_name(result));
continue;
}
int config = 1;
if( handle == NULL)
{
continue;
}
result = libusb_set_configuration(handle, config);
if(result < 0)
{
error = QString(libusb_error_name(result));
continue;
}
result = libusb_get_config_descriptor(dev, 0, &conf_desc);
if(result < 0)
{
error = QString(libusb_error_name(result));
continue;
}
result = libusb_claim_interface(handle, 0);
if(result < 0)
{
error = QString(libusb_error_name(result));
continue;
}
result = libusb_get_string_descriptor_ascii(handle, desc.iProduct, manf, sizeof(manf));
if(result < 0)
{
error = QString(libusb_error_name(result));
continue;
}
UsbDevice *newDevice = new UsbDevice();
newDevice->setDeviceName(QString((char*)manf));
newDevice->setHandle(handle);
usbDeviceList << newDevice;
}
libusb_free_device_list(usbDevices, 1);
return usbDeviceList;
}
You are calling libusb_init() at the beginning of your program, but you are also calling libusb_exit() at the beginning : before calling a.exec().
Your first call probably happens in MainWindow constructor ?
You could instead subclass QApplication, call libusb_init() in the constructor and libusb_exit() in the destructor.

How to get Serial Port profile SDP record for remote device

I am trying to write an application that pairs a remote bluetooth device with Windows Mobile/CE handheld and get the service of the device.
I noticed that when you manually pair a device and set the service through the system(eg. go to settings->Bluetooth-> add device) it generates an sdprecord value in the following registry
HKLM/Software/Microsoft/Bluetooth/Device/{deviceAddress}/{*Service_UUID*}.
I am basically trying to implement this in my program.
I followed the following documentations:
http://msdn.microsoft.com/en-us/library/ms883458.aspx
http://msdn.microsoft.com/en-us/library/ms883398.aspx
and then convert the SDPrecord into binary and write it to the registry:
RegSetValueEx(hSerialPortKey,_T("sdprecord"),0,REG_BINARY,(BYTE*)&pRecord,sizeof(pRecord)*2+1);
The result is not the same as what I would get when I manually pair the device.
What am I doing wrong? How can I retrieve the SDP record? Thank you in advance.
Below is my code
BTHNS_RESTRICTIONBLOB RBlob;
memset(&RBlob,0,sizeof(BTHNS_RESTRICTIONBLOB));
RBlob.type = SDP_SERVICE_SEARCH_ATTRIBUTE_REQUEST;
RBlob.numRange = 1;
RBlob.uuids[0].uuidType= SDP_ST_UUID16;//SDP_ST_UUID128;
RBlob.uuids[0].u.uuid16= SerialPortServiceClassID_UUID16;
RBlob.pRange[0].minAttribute =SDP_ATTRIB_PROTOCOL_DESCRIPTOR_LIST;
RBlob.pRange[0].maxAttribute = SDP_ATTRIB_PROTOCOL_DESCRIPTOR_LIST;
SOCKADDR_BTH sa;
memset (&sa, 0, sizeof(SOCKADDR_BTH));
BTH_ADDR *pDeviceAddr = &devAddress;
*(BTH_ADDR *)(&sa.btAddr) = *pDeviceAddr;
sa.addressFamily = AF_BTH;
CSADDR_INFO csai;
memset(&csai,0,sizeof(CSADDR_INFO));
csai.RemoteAddr.lpSockaddr = (sockaddr*)&sa;
csai.RemoteAddr.iSockaddrLength = sizeof(sa);
BLOB blob;
blob.cbSize = sizeof(BTHNS_RESTRICTIONBLOB);
blob.pBlobData = (BYTE *)&RBlob;
WSAQUERYSET wsaq;
memset(&wsaq,0,sizeof(WSAQUERYSET));
wsaq.dwSize = sizeof(WSAQUERYSET);
wsaq.dwNumberOfCsAddrs = 1;
wsaq.dwNameSpace = NS_BTH;
wsaq.lpBlob = &blob;
wsaq.lpcsaBuffer = &csai;
wsaq.lpServiceClassId = &serialPortUUID;
//Initialising winsock
WSADATA data;
int result = WSAStartup(MAKEWORD(2, 2), &data);//initializing winsock
if (hLib == NULL)
{
return S_FALSE;
}
result = WSALookupServiceBegin (&wsaq,0, &hLookup);
while (result ==ERROR_SUCCESS )
{
BYTE sdpBuffer[4096];
memset(sdpBuffer,0,sizeof(sdpBuffer));
LPWSAQUERYSET pResult = (LPWSAQUERYSET)&sdpBuffer;
dwSize = sizeof(sdpBuffer);
pResult->dwSize = sizeof(WSAQUERYSET);
pResult->dwNameSpace = NS_BTH;
pResult->lpBlob = NULL;
pResult->lpServiceClassId = &serialPortUUID;
result = WSALookupServiceNext(hLookup,0,&dwSize,pResult);
if(result == -1 )
{
int error;
error = WSAGetLastError();
if (error == WSA_E_NO_MORE)
break;
}
else
{
//Get SDP record
if (pResult != NULL)
{
if (ERROR_SUCCESS != ServiceAndAttributeSearchParse(pResult->lpBlob->pBlobData,pResult->lpBlob->cbSize,&pRecordArg,&ulRecords)) { //error handling}
ULONG recordIndex;
for (recordIndex = 0; recordIndex < ulRecords; recordIndex++) {
pRecord = pRecordArg[recordIndex];}
I think the code should be ok.Here's my code
int FindRFCOMMChannel (unsigned char *pStream, int cStream, unsigned char *pChann)
{
ISdpRecord **pRecordArg;
int cRecordArg = 0;
*pChann = 0;
int hr = ServiceAndAttributeSearch(pStream, cStream, &pRecordArg, (ULONG *)&cRecordArg);
if (hr != ERROR_SUCCESS)
{
BT_ERROR( CBTRFCOMMMgr, PerformServiceSearch, "ServiceAndAttributeSearch ERROR %d\n");
return hr;
}
for (int i = 0; (! *pChann) && (i < cRecordArg); i++)
{
ISdpRecord *pRecord = pRecordArg[i]; // particular record to examine in this loop
CNodeDataFreeString protocolList; // contains SDP_ATTRIB_PROTOCOL_DESCRIPTOR_LIST data, if available
if (ERROR_SUCCESS != pRecord->GetAttribute(SDP_ATTRIB_PROTOCOL_DESCRIPTOR_LIST,&protocolList) ||
(protocolList.type != SDP_TYPE_CONTAINER))
continue;
ISdpNodeContainer *pRecordContainer = protocolList.u.container;
int cProtocols = 0;
NodeData protocolDescriptor; // information about a specific protocol (i.e. L2CAP, RFCOMM, ...)
pRecordContainer->GetNodeCount((DWORD *)&cProtocols);
for (int j = 0; (! *pChann) && (j < cProtocols); j++) {
pRecordContainer->GetNode(j,&protocolDescriptor);
if (protocolDescriptor.type != SDP_TYPE_CONTAINER)
continue;
ISdpNodeContainer *pProtocolContainer = protocolDescriptor.u.container;
int cProtocolAtoms = 0;
pProtocolContainer->GetNodeCount((DWORD *)&cProtocolAtoms);
for (int k = 0; (! *pChann) && (k < cProtocolAtoms); k++) {
NodeData nodeAtom; // individual data element, such as what protocol this is or RFCOMM channel id.
pProtocolContainer->GetNode(k,&nodeAtom);
if (IsRfcommUuid(&nodeAtom)) {
if (k+1 == cProtocolAtoms) {
// misformatted response. Channel ID should follow RFCOMM uuid
break;
}
NodeData channelID;
pProtocolContainer->GetNode(k+1,&channelID);
*pChann = (unsigned char)GetChannel(&channelID);
break; // formatting error
}
}
}
}
for (i = 0; i < cRecordArg; i++)
pRecordArg[i]->Release();
CoTaskMemFree(pRecordArg);
return (*pChann != 0) ? 1:0;
}
int IsRfcommUuid(NodeData *pNode) {
if (pNode->type != SDP_TYPE_UUID)
return FALSE;
if (pNode->specificType == SDP_ST_UUID16)
return (pNode->u.uuid16 == RFCOMM_PROTOCOL_UUID16);
else if (pNode->specificType == SDP_ST_UUID32)
return (pNode->u.uuid32 == RFCOMM_PROTOCOL_UUID16);
else if (pNode->specificType == SDP_ST_UUID128)
return (0 == memcmp(&RFCOMM_PROTOCOL_UUID,&pNode->u.uuid128,sizeof(GUID)));
return FALSE;
}
int GetChannel (NodeData *pChannelNode) {
if (pChannelNode->specificType == SDP_ST_UINT8)
return pChannelNode->u.uint8;
else if (pChannelNode->specificType == SDP_ST_INT8)
return pChannelNode->u.int8;
else if (pChannelNode->specificType == SDP_ST_UINT16)
return pChannelNode->u.uint16;
else if (pChannelNode->specificType == SDP_ST_INT16)
return pChannelNode->u.int16;
else if (pChannelNode->specificType == SDP_ST_UINT32)
return pChannelNode->u.uint32;
else if (pChannelNode->specificType == SDP_ST_INT32)
return pChannelNode->u.int32;
return 0;
}

FMOD playSound throws an error about invalid parameter

I've tried building some sort of audio manager after openAL failed to deliver on certain machines so I found out about fmod. However after few hours of changes in code nothing really works. My playSound call seems to be bugging.
An invalid parameter was passed to this function.
This is exactly what an errorcheck output gives me.
Code...let's get from start:
typedef std::map<std::string, FMOD::Sound*> SoundPool;
SoundPool m_sounds;
FMOD::Channel* m_soundChannels[MAX_SOUNDS];
FMOD::System* m_soundSystem;
and then:
FMOD::System_Create(&m_soundSystem);
m_soundSystem->init(32, FMOD_INIT_NORMAL, NULL);
for(int i = 0; i < MAX_SOUNDS; i++)
m_soundChannels[i] = 0;
and later:
void CResourceManager::PlaySound(std::string filename, float volume)
{
for(int i = 0; i < MAX_SOUNDS; i++)
{
if(m_soundChannels[i] == 0)
{
if(volume > 1.0f) volume = 1.0f;
FMOD_RESULT result = m_soundSystem->playSound(FMOD_CHANNEL_FREE,
m_sounds[filename], false, &m_soundChannels[i]);
if(result != FMOD_OK)
{
std::cout << FMOD_ErrorString(result); //// here's the error
}
m_soundChannels[i]->setVolume(volume);
break;
}
}
}
void CResourceManager::Update()
{
m_soundSystem->update();
for(int i = 0; i < MAX_SOUNDS; i++)
{
if(m_soundChannels[i] != 0)
{
bool playing;
m_soundChannels[i]->isPlaying(&playing);
if(!playing)
m_soundChannels[i] = 0;
}
}
}
bool CResourceManager::AddSound( std::string filename )
{
FMOD_RESULT result = m_soundSystem->createSound(filename.c_str(),
FMOD_LOOP_NORMAL, NULL, &m_sounds[filename]);
if(result == FMOD_OK)
return true;
return false;
}