How to open device node (/dev/hidraw0) in Android app (via C++)?

2.8k views Asked by At

I am currently porting a C++ communication library from Linux to Android with JNI/NDK. The device is a USB detector for making scientific measurements. It's just a raw HID which comes up as "/dev/hidraw0"

I need to get a file descriptor ('_fileHandle') to the device, which I am doing via:

_fileHandle = open(_devicePath.c_str(), O_RDONLY | O_NONBLOCK);

where '_devicePath' is the device node "/dev/hidraw0". Unfortunately, I'm running into an issue with Android (Permissions/SELinux, most likely) and I get the following error in my logcat right after I try executing the open(...) command:

type=1400 audit(0.0:41): avc: denied { read } for name="hidraw0" dev="tmpfs" ino=229381 scontext=u:r:untrusted_app:s0:c512,c768 tcontext=u:object_r:device:s0 tclass=chr_file permissive=0

The "ls -l" of "/dev/hidraw0" is:

crw------- 1 root root 229

How can I get the device to open?

I tried to just chmod the permissions on the node and the changes don't stick (Android immediately reverts them).

Thanks!

2

There are 2 answers

0
Chemik On BEST ANSWER

@y30 was correct.

Using root commands from within my app, I got it working by setting SELinux to "Permissive" mode with the "setenforce 0" command, and then I am able to send the "chmod 666 /dev/hidraw0" command and the permissions stick - I am then able to successfully communicate with the device from my app.

It's still a bit unstable at times, though - I find sometimes the permissions don't get set from my app, even though I don't get any errors after running the commands on startup of my app, and I have to go to a terminal to manually execute the commands as root and then go back to my app.

Thanks for the help!

0
Daniel On

There is an API to handle USB devices directly. Have a look at: https://developer.android.com/guide/topics/connectivity/usb/host.html

Does it satisfy your need?