Skip to content

Commit 4126ec0

Browse files
feat(termux): hand camera broker FD across app UIDs
Remove the shared-UID requirement and authorize Termux by sender UID before passing a connected broker socket through a Binder callback. The native Termux launcher preserves the descriptor across exec and preloads fauxdev, allowing F-Droid Termux to capture without exposing the private socket path. Add the camera inventory view, a live-capture probe, and the updated fauxdev submodule. Android 14+ is required for sender identity; older Android versions remain closed pending an authenticated transport.
1 parent a6d6caa commit 4126ec0

12 files changed

Lines changed: 335 additions & 16 deletions

File tree

‎README.md‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,22 +6,22 @@ The camera starts only when you tap **Start camera** in the app. The notificatio
66

77
## Compatibility
88

9-
This first APK uses Termux's public GitHub development signing key and `com.termux` shared UID. It installs alongside **GitHub-signed Termux only**. It cannot install alongside F-Droid or Play Store Termux; do not uninstall your existing Termux or its data just to try this build. Android 12+ and ARM64 are required.
9+
The published build uses Termux's public GitHub development signing key and `com.termux` shared UID, so it installs alongside **GitHub-signed Termux only**. This local branch removes the shared UID and uses an authenticated FD handoff. A Pixel 6a (Android 17) with F-Droid Termux captured live frames, but this branch is not yet a release. The cross-UID handoff requires Android 14+; Android 12–13 remain unsupported until an authenticated alternative is implemented. Do not uninstall Termux or its data to try either build.
1010

1111
The public key does not establish trust in an APK: verify the source and artifact before installing. The expected APK signing certificate SHA-256 is `b6da01480eefd5fbf2cd3771b8d1021ec791304bdd6c4bf41d3faabad48ee5e1`.
1212

1313
## Build and use
1414

1515
Every APK and native library in CI is compiled from the source pinned in this repository. The [build workflow](.github/workflows/build.yml) fetches Termux's public key at a pinned commit, verifies its SHA-256, runs fauxdev's tests, builds the APK and Termux-native library, verifies the APK certificate, and uploads both artifacts. No locally compiled library is checked in or repackaged.
1616

17-
Install the CI APK on a device with GitHub-signed Termux. In Termux, extract the matching `camera2termux-termux-arm64.tar.gz`, then install its two files:
17+
For the published build, install the CI APK on a device with GitHub-signed Termux. This local branch can be built and tested with F-Droid Termux, but has no published artifact. In Termux, extract the matching `camera2termux-termux-arm64.tar.gz`, then install its two files:
1818

1919
```sh
2020
tar -xzf camera2termux-termux-arm64.tar.gz
2121
install -m 755 libfauxdev-termux.so "$PREFIX/lib/libfauxdev-termux.so"
2222
install -m 755 camera2termux-run "$PREFIX/bin/camera2termux-run"
2323
```
2424

25-
Open Camera2Termux, grant camera permission, and tap **Start camera**. Then use `camera2termux-run COMMAND ...` for a native Termux program that opens `/dev/video0` through V4L2. The launcher sets `FAUXDEV_VIDEO_SOCKET` and `LD_PRELOAD`; it does not enable the camera in arbitrary processes. Stop the service when finished.
25+
Open Camera2Termux, grant camera permission, and tap **Start camera**. Then use `camera2termux-run COMMAND ...` for a native Termux program that opens `/dev/video0` through V4L2. The published launcher uses the app-private socket path; this branch instead hands an already-connected FD to the command and preloads the native shim. It does not enable the camera in arbitrary processes. Stop the service when finished.
2626

27-
PRoot/glibc programs need their own fauxdev build and setup; this ARM64 Bionic library is for native Termux programs. Device-side Termux capture and F-Droid compatibility are not yet validated.
27+
PRoot/glibc programs need their own fauxdev build and setup; this ARM64 Bionic library is for native Termux programs. The local F-Droid/Pixel result does not establish compatibility across devices or Termux variants.

‎app/src/main/AndroidManifest.xml‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
<?xml version="1.0" encoding="utf-8"?>
2-
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
3-
android:sharedUserId="com.termux">
2+
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
43
<uses-permission android:name="android.permission.CAMERA" />
54
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
65
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CAMERA" />
76
<uses-feature android:name="android.hardware.camera.any" android:required="true" />
7+
<queries>
8+
<package android:name="com.termux" />
9+
</queries>
810
<application android:label="Camera2Termux" android:theme="@android:style/Theme.Material.Light.NoActionBar" android:usesCleartextTraffic="false">
911
<activity android:name=".MainActivity" android:exported="true">
1012
<intent-filter>
@@ -13,5 +15,10 @@
1315
</intent-filter>
1416
</activity>
1517
<service android:name=".CameraService" android:exported="false" android:foregroundServiceType="camera" />
18+
<receiver android:name=".CameraFdReceiver" android:exported="true">
19+
<intent-filter>
20+
<action android:name="org.randomcoder.camera2termux.REQUEST_FD" />
21+
</intent-filter>
22+
</receiver>
1623
</application>
1724
</manifest>

‎app/src/main/cpp/CMakeLists.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ cmake_minimum_required(VERSION 3.22)
22
project(camera2termux C)
33
set(CMAKE_C_STANDARD 11)
44
add_library(fauxdev-camera SHARED
5+
camera_socket.c
56
../../../../fauxdev/android/camera_broker.c
67
../../../../fauxdev/android/yuv_rgb.c
78
../../../../fauxdev/src/transport.c)

‎app/src/main/cpp/camera_socket.c‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
#include <errno.h>
2+
#include <jni.h>
3+
#include <stddef.h>
4+
#include <string.h>
5+
#include <sys/socket.h>
6+
#include <sys/un.h>
7+
#include <unistd.h>
8+
9+
JNIEXPORT jint JNICALL
10+
Java_org_randomcoder_udroid_camera_CameraBrokerBridge_connect(JNIEnv *env, jclass type, jstring path) {
11+
(void)type;
12+
if (!path) return -EINVAL;
13+
const char *name = (*env)->GetStringUTFChars(env, path, NULL);
14+
if (!name) return -ENOMEM;
15+
struct sockaddr_un address = {.sun_family = AF_UNIX};
16+
int fd = -ENAMETOOLONG;
17+
size_t length = strlen(name);
18+
if (length < sizeof(address.sun_path)) {
19+
memcpy(address.sun_path, name, length + 1);
20+
fd = socket(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0);
21+
if (fd >= 0 && connect(fd, (const struct sockaddr *)&address,
22+
offsetof(struct sockaddr_un, sun_path) + length + 1) < 0) {
23+
int error = errno;
24+
close(fd);
25+
fd = -error;
26+
}
27+
}
28+
(*env)->ReleaseStringUTFChars(env, path, name);
29+
return fd;
30+
}

‎app/src/main/java/org/randomcoder/udroid/camera/CameraBrokerBridge.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,7 @@ final class CameraBrokerBridge {
55
static native boolean prepare();
66
static native int run(String socketPath);
77
static native void stop();
8+
static native int connect(String socketPath);
9+
static native String inventory();
810
private CameraBrokerBridge() {}
911
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package org.randomcoder.udroid.camera;
2+
3+
import android.content.BroadcastReceiver;
4+
import android.content.Context;
5+
import android.content.Intent;
6+
import android.content.pm.ApplicationInfo;
7+
import android.content.pm.PackageManager;
8+
import android.os.Build;
9+
import android.os.IBinder;
10+
import android.os.Parcel;
11+
import android.os.ParcelFileDescriptor;
12+
import android.os.Process;
13+
import android.util.Log;
14+
import java.io.File;
15+
16+
/** Hands the running broker's socket to a Termux-side Binder callback. */
17+
public final class CameraFdReceiver extends BroadcastReceiver {
18+
static final String ACTION = "org.randomcoder.camera2termux.REQUEST_FD";
19+
static final int TRANSACTION_FD = IBinder.FIRST_CALL_TRANSACTION;
20+
21+
@Override public void onReceive(Context context, Intent intent) {
22+
// shortcut: sender UID is available only on API 34+, keep older Android closed until authenticated transport exists.
23+
if (!ACTION.equals(intent.getAction()) || Build.VERSION.SDK_INT < 34) return;
24+
int uid = getSentFromUid();
25+
Log.i("Camera2Termux", "Camera FD request from UID " + uid);
26+
int termuxUid;
27+
try {
28+
termuxUid = context.getPackageManager().getPackageUid("com.termux", 0);
29+
} catch (PackageManager.NameNotFoundException error) {
30+
return;
31+
}
32+
boolean debugShell = uid == Process.SHELL_UID &&
33+
(context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
34+
if (uid != termuxUid && !debugShell) {
35+
Log.w("Camera2Termux", "Rejected camera FD request from UID " + uid);
36+
return;
37+
}
38+
IBinder callback = intent.getExtras() == null ? null : intent.getExtras().getBinder("callback");
39+
if (callback == null) return;
40+
File path = new File(context.getFilesDir(), "camera.sock");
41+
int socketFd = CameraBrokerBridge.connect(path.getAbsolutePath());
42+
if (socketFd < 0) {
43+
Log.e("Camera2Termux", "Camera broker connect failed: errno " + -socketFd);
44+
return;
45+
}
46+
try (ParcelFileDescriptor fd = ParcelFileDescriptor.adoptFd(socketFd)) {
47+
Parcel data = Parcel.obtain();
48+
try {
49+
fd.writeToParcel(data, 0);
50+
if (!callback.transact(TRANSACTION_FD, data, null, IBinder.FLAG_ONEWAY))
51+
Log.e("Camera2Termux", "Camera FD callback rejected the transaction");
52+
} finally {
53+
data.recycle();
54+
}
55+
} catch (Exception error) {
56+
Log.e("Camera2Termux", "Camera FD handoff failed", error);
57+
}
58+
}
59+
60+
}

‎app/src/main/java/org/randomcoder/udroid/camera/CameraService.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ public final class CameraService extends Service {
4242
Notification notification = new Notification.Builder(this, CHANNEL)
4343
.setSmallIcon(android.R.drawable.ic_menu_camera)
4444
.setContentTitle("Camera available to Termux")
45-
.setContentText("Camera2Termux is streaming only while this service runs")
45+
.setContentText("Camera available while service runs; capture starts when a client streams")
4646
.setOngoing(true)
4747
.addAction(new Notification.Action.Builder(null, "Stop", stopAction).build())
4848
.build();
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
package org.randomcoder.udroid.camera;
2+
3+
import android.content.Context;
4+
import android.content.ComponentName;
5+
import android.content.Intent;
6+
import android.app.BroadcastOptions;
7+
import android.content.pm.ApplicationInfo;
8+
import android.os.Binder;
9+
import android.os.Bundle;
10+
import android.os.IBinder;
11+
import android.os.Looper;
12+
import android.os.Parcel;
13+
import android.os.ParcelFileDescriptor;
14+
import android.os.Process;
15+
import android.system.Os;
16+
import android.system.OsConstants;
17+
import java.io.File;
18+
import java.lang.reflect.Method;
19+
import java.util.ArrayList;
20+
import java.util.Map;
21+
import java.util.concurrent.CountDownLatch;
22+
import java.util.concurrent.TimeUnit;
23+
import java.util.concurrent.atomic.AtomicReference;
24+
25+
/** Receives an authorized broker FD, then replaces this app_process helper with a Termux command. */
26+
public final class CameraTermuxLauncher {
27+
public static void main(String[] args) throws Exception {
28+
if (args.length == 0) throw new IllegalArgumentException("Usage: camera2termux-run COMMAND [ARG...]");
29+
Looper.prepareMainLooper();
30+
// app_process has no app Context; use Termux's UID and package identity for the broadcast.
31+
Class<?> threadClass = Class.forName("android.app.ActivityThread");
32+
Object thread = threadClass.getMethod("systemMain").invoke(null);
33+
Context system = (Context) threadClass.getMethod("getSystemContext").invoke(thread);
34+
String caller = Process.myUid() == Process.SHELL_UID ? "com.android.shell" : "com.termux";
35+
ApplicationInfo info = system.getPackageManager().getApplicationInfo(caller, 0);
36+
Object loaded = threadClass.getMethod("getPackageInfoNoCheck", ApplicationInfo.class).invoke(thread, info);
37+
Method create = Class.forName("android.app.ContextImpl").getDeclaredMethod(
38+
"createAppContext", threadClass, Class.forName("android.app.LoadedApk"));
39+
create.setAccessible(true);
40+
Context context = (Context) create.invoke(null, thread, loaded);
41+
CountDownLatch received = new CountDownLatch(1);
42+
AtomicReference<ParcelFileDescriptor> brokerFd = new AtomicReference<>();
43+
AtomicReference<Exception> failure = new AtomicReference<>();
44+
IBinder callback = new Binder() {
45+
@Override protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) {
46+
if (code != CameraFdReceiver.TRANSACTION_FD) return false;
47+
ParcelFileDescriptor fd = null;
48+
try {
49+
fd = ParcelFileDescriptor.CREATOR.createFromParcel(data);
50+
if (!OsConstants.S_ISSOCK(Os.fstat(fd.getFileDescriptor()).st_mode))
51+
throw new IllegalStateException("Received descriptor is not a socket");
52+
brokerFd.set(fd);
53+
fd = null;
54+
} catch (Exception error) {
55+
failure.set(error);
56+
} finally {
57+
if (fd != null) try { fd.close(); } catch (Exception ignored) { }
58+
}
59+
received.countDown();
60+
return true;
61+
}
62+
};
63+
Bundle extras = new Bundle();
64+
extras.putBinder("callback", callback);
65+
Intent request = new Intent(CameraFdReceiver.ACTION)
66+
.setComponent(new ComponentName("org.randomcoder.camera2termux",
67+
"org.randomcoder.udroid.camera.CameraFdReceiver"))
68+
.putExtras(extras);
69+
context.sendBroadcast(request, null, BroadcastOptions.makeBasic()
70+
.setShareIdentityEnabled(true).toBundle());
71+
if (!received.await(10, TimeUnit.SECONDS)) throw new IllegalStateException("No camera FD received");
72+
if (failure.get() != null) throw failure.get();
73+
try (ParcelFileDescriptor fd = brokerFd.get()) {
74+
if (fd == null) throw new IllegalStateException("Camera FD callback returned nothing");
75+
String prefix = System.getenv("PREFIX");
76+
if (prefix == null || prefix.isEmpty()) prefix = "/data/data/com.termux/files/usr";
77+
String library = prefix + "/lib/libfauxdev-termux.so";
78+
if (!new File(library).isFile())
79+
throw new IllegalStateException("Missing Termux camera library: " + library);
80+
String command = resolveCommand(args[0], System.getenv("PATH"));
81+
int flags = Os.fcntlInt(fd.getFileDescriptor(), OsConstants.F_GETFD, 0);
82+
Os.fcntlInt(fd.getFileDescriptor(), OsConstants.F_SETFD, flags & ~OsConstants.FD_CLOEXEC);
83+
ArrayList<String> environment = new ArrayList<>();
84+
for (Map.Entry<String, String> entry : System.getenv().entrySet()) {
85+
if (!entry.getKey().equals("LD_PRELOAD") && !entry.getKey().equals("FAUXDEV_VIDEO_FD") &&
86+
!entry.getKey().equals("FAUXDEV_VIDEO_SOCKET"))
87+
environment.add(entry.getKey() + "=" + entry.getValue());
88+
}
89+
String preload = System.getenv("LD_PRELOAD");
90+
environment.add("LD_PRELOAD=" + library + (preload == null ? "" : ":" + preload));
91+
environment.add("FAUXDEV_VIDEO_FD=" + fd.getFd());
92+
Os.execve(command, args, environment.toArray(new String[0]));
93+
}
94+
}
95+
96+
private static String resolveCommand(String name, String path) {
97+
if (name.contains("/")) return new File(name).getAbsolutePath();
98+
if (path != null) for (String directory : path.split(":")) {
99+
File candidate = new File(directory, name);
100+
if (candidate.isFile() && candidate.canExecute()) return candidate.getAbsolutePath();
101+
}
102+
throw new IllegalArgumentException("Command not found: " + name);
103+
}
104+
}

‎app/src/main/java/org/randomcoder/udroid/camera/MainActivity.java‎

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,19 @@
22

33
import android.Manifest;
44
import android.app.Activity;
5+
import android.app.AlertDialog;
56
import android.content.Intent;
67
import android.content.pm.PackageManager;
8+
import android.graphics.Typeface;
79
import android.os.Bundle;
810
import android.widget.Button;
911
import android.widget.LinearLayout;
12+
import android.widget.ScrollView;
1013
import android.widget.TextView;
1114

1215
public final class MainActivity extends Activity {
1316
private static final int CAMERA_REQUEST = 1;
17+
private static final int INVENTORY_REQUEST = 2;
1418
private TextView status;
1519

1620
@Override public void onCreate(Bundle state) {
@@ -20,8 +24,7 @@ public final class MainActivity extends Activity {
2024
int padding = (int) (24 * getResources().getDisplayMetrics().density);
2125
layout.setPadding(padding, padding, padding, padding);
2226
TextView help = new TextView(this);
23-
help.setText("Camera2Termux\n\nStart the camera here, then run a native Termux program with camera2termux-run.\n\nSocket: "
24-
+ new java.io.File(getFilesDir(), "camera.sock").getAbsolutePath());
27+
help.setText("Camera2Termux\n\nStart the camera here, then use camera2termux-run in native Termux. Camera sharing is experimental; stop the service when finished.");
2528
layout.addView(help);
2629
status = new TextView(this);
2730
status.setText("Camera is off");
@@ -41,6 +44,14 @@ public final class MainActivity extends Activity {
4144
status.setText("Camera stopped");
4245
});
4346
layout.addView(stop);
47+
Button inventory = new Button(this);
48+
inventory.setText("Camera inventory");
49+
inventory.setOnClickListener(v -> {
50+
if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED)
51+
showInventory();
52+
else requestPermissions(new String[]{Manifest.permission.CAMERA}, INVENTORY_REQUEST);
53+
});
54+
layout.addView(inventory);
4455
setContentView(layout);
4556
}
4657

@@ -49,9 +60,29 @@ public final class MainActivity extends Activity {
4960
if (requestCode == CAMERA_REQUEST) {
5061
if (results.length > 0 && results[0] == PackageManager.PERMISSION_GRANTED) startCamera();
5162
else status.setText("Camera permission denied");
63+
} else if (requestCode == INVENTORY_REQUEST) {
64+
if (results.length > 0 && results[0] == PackageManager.PERMISSION_GRANTED) showInventory();
65+
else status.setText("Camera permission denied");
5266
}
5367
}
5468

69+
private void showInventory() {
70+
String report = CameraBrokerBridge.inventory();
71+
TextView text = new TextView(this);
72+
text.setText(report);
73+
text.setTextIsSelectable(true);
74+
text.setTypeface(Typeface.MONOSPACE);
75+
int padding = (int) (16 * getResources().getDisplayMetrics().density);
76+
text.setPadding(padding, padding, padding, padding);
77+
ScrollView scroll = new ScrollView(this);
78+
scroll.addView(text);
79+
new AlertDialog.Builder(this)
80+
.setTitle("Camera inventory")
81+
.setView(scroll)
82+
.setPositiveButton("Close", null)
83+
.show();
84+
}
85+
5586
private void startCamera() {
5687
try {
5788
startForegroundService(new Intent(this, CameraService.class).setAction(CameraService.START));

0 commit comments

Comments
 (0)