forked from Blendman974/faceclaw
Add tokens and faceclaw-input script, which allows using a CLI utility as an input device for the glasses
This commit is contained in:
1 parent
313ba85708
commit
ccb320c66f
32 files changed
+1785
-12
No files matched your search
@@ -0,0 +1,124 @@
|
||||
package com.faceclaw.app;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.net.InetAddress;
|
||||
import java.net.NetworkInterface;
|
||||
import java.util.Collections;
|
||||
import org.json.JSONArray;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import org.json.JSONObject;
|
||||
|
||||
/** Explicit-address, bounded, one-request-per-connection input port. JS polls on its own thread. */
|
||||
public final class FaceclawRemoteInput {
|
||||
private static final FaceclawRemoteInput INSTANCE = new FaceclawRemoteInput();
|
||||
public static FaceclawRemoteInput getInstance() { return INSTANCE; }
|
||||
private ServerSocket server;
|
||||
private Socket client;
|
||||
private String pending, reply;
|
||||
private long nextId, requestId;
|
||||
private long deadline;
|
||||
|
||||
public synchronized String start(int port) { return startAddress(port, "127.0.0.1"); }
|
||||
public synchronized String startAddress(int port, String address) {
|
||||
if (server != null) return "";
|
||||
try {
|
||||
// Numeric local addresses only; never resolve hostnames or bind a wildcard.
|
||||
if (!address.matches("[0-9.]+|[0-9a-fA-F]*:[0-9a-fA-F:.]*(%[a-zA-Z0-9_.-]+)?")) return "Invalid local address.";
|
||||
InetAddress local = InetAddress.getByName(address);
|
||||
if (local.isAnyLocalAddress() || local.isMulticastAddress() || NetworkInterface.getByInetAddress(local) == null)
|
||||
return "Address is not assigned to a local interface.";
|
||||
ServerSocket listener = new ServerSocket(port, 8, local);
|
||||
server = listener;
|
||||
Thread thread = new Thread(() -> serve(listener), "FaceclawInput");
|
||||
thread.setDaemon(true);
|
||||
thread.start();
|
||||
return "";
|
||||
} catch (Exception e) { return "Could not open local input port " + port + "."; }
|
||||
}
|
||||
public synchronized void stop() {
|
||||
try { if (server != null) server.close(); } catch (Exception ignored) {}
|
||||
try { if (client != null) client.close(); } catch (Exception ignored) {}
|
||||
server = null; client = null; pending = null; requestId = 0; reply = null;
|
||||
notifyAll();
|
||||
}
|
||||
public synchronized String nextRequest() {
|
||||
if (System.currentTimeMillis() >= deadline) { pending = null; return null; }
|
||||
String result = pending; pending = null; return result;
|
||||
}
|
||||
public synchronized void complete(long id, String value) {
|
||||
if (id == requestId && System.currentTimeMillis() < deadline) { reply = value; notifyAll(); }
|
||||
}
|
||||
private void serve(ServerSocket listener) {
|
||||
while (!listener.isClosed()) {
|
||||
try (Socket socket = listener.accept()) {
|
||||
synchronized (this) { if (server != listener) return; client = socket; }
|
||||
socket.setSoTimeout(5000);
|
||||
socket.setTcpNoDelay(true);
|
||||
long readDeadline = System.currentTimeMillis() + 5000;
|
||||
ByteArrayOutputStream body = new ByteArrayOutputStream();
|
||||
int b;
|
||||
for (;;) {
|
||||
long remaining = readDeadline - System.currentTimeMillis();
|
||||
if (remaining <= 0) throw new Exception("Read timeout");
|
||||
socket.setSoTimeout((int) remaining);
|
||||
b = socket.getInputStream().read();
|
||||
if (b == -1 || b == '\n') break;
|
||||
if (body.size() >= 65536) throw new Exception("Invalid frame");
|
||||
body.write(b);
|
||||
}
|
||||
if (b != '\n') continue;
|
||||
String text = StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(body.toByteArray())).toString();
|
||||
String response;
|
||||
synchronized (this) {
|
||||
if (server != listener) return;
|
||||
requestId = ++nextId;
|
||||
deadline = System.currentTimeMillis() + 5000;
|
||||
reply = null;
|
||||
pending = new JSONObject().put("id", requestId).put("expiresAt", deadline)
|
||||
.put("body", text).toString();
|
||||
while (reply == null && server == listener && System.currentTimeMillis() < deadline) {
|
||||
wait(Math.max(1, deadline - System.currentTimeMillis()));
|
||||
}
|
||||
response = reply != null ? reply : "{\"ok\":false,\"error\":\"timeout\",\"message\":\"Faceclaw did not respond in time.\"}";
|
||||
if (server == listener) { pending = null; reply = null; requestId = 0; }
|
||||
}
|
||||
socket.getOutputStream().write((response + "\n").getBytes(StandardCharsets.UTF_8));
|
||||
} catch (Exception ignored) {
|
||||
// Never log request bodies: they contain credentials and possibly private text.
|
||||
} finally {
|
||||
synchronized (this) { if (server == listener) client = null; }
|
||||
}
|
||||
}
|
||||
}
|
||||
public static String interfaces() {
|
||||
JSONArray result = new JSONArray();
|
||||
try {
|
||||
for (NetworkInterface device : Collections.list(NetworkInterface.getNetworkInterfaces())) {
|
||||
if (!device.isUp()) continue;
|
||||
for (InetAddress address : Collections.list(device.getInetAddresses())) {
|
||||
if (address.isLoopbackAddress() || address.isLinkLocalAddress() || address.isAnyLocalAddress()) continue;
|
||||
result.put(new JSONObject().put("name", device.getName()).put("address", address.getHostAddress())
|
||||
.put("pointToPoint", device.isPointToPoint()));
|
||||
}
|
||||
}
|
||||
} catch (Exception ignored) {}
|
||||
return result.toString();
|
||||
}
|
||||
public String randomSecret() {
|
||||
byte[] bytes = new byte[32]; new SecureRandom().nextBytes(bytes); return hex(bytes);
|
||||
}
|
||||
public String hash(String value) {
|
||||
try { return hex(MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); }
|
||||
catch (Exception e) { throw new IllegalStateException("SHA-256 unavailable", e); }
|
||||
}
|
||||
private static String hex(byte[] bytes) {
|
||||
StringBuilder result = new StringBuilder(bytes.length * 2);
|
||||
for (byte b : bytes) result.append(String.format(java.util.Locale.ROOT, "%02x", b & 255));
|
||||
return result.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
@interface FaceclawRemoteInput : NSObject
|
||||
+ (instancetype)shared;
|
||||
+ (NSString *)interfaces;
|
||||
- (NSString *)start:(int)port;
|
||||
- (NSString *)start:(int)port address:(NSString *)address;
|
||||
- (void)stop;
|
||||
- (NSString *)nextRequest;
|
||||
- (void)complete:(long long)identifier response:(NSString *)response;
|
||||
- (NSString *)randomSecret;
|
||||
- (NSString *)tokenDigest:(NSString *)value;
|
||||
@end
|
||||
@@ -0,0 +1,150 @@
|
||||
#import "FaceclawRemoteInput.h"
|
||||
#import "FaceclawCrypto.h"
|
||||
#import <Security/Security.h>
|
||||
#import <sys/socket.h>
|
||||
#import <netinet/in.h>
|
||||
#import <unistd.h>
|
||||
#import <poll.h>
|
||||
#import <ifaddrs.h>
|
||||
#import <net/if.h>
|
||||
#import <netdb.h>
|
||||
#import <arpa/inet.h>
|
||||
|
||||
@implementation FaceclawRemoteInput {
|
||||
NSCondition *_condition;
|
||||
int _server, _client;
|
||||
NSUInteger _generation;
|
||||
long long _nextId, _requestId;
|
||||
NSTimeInterval _deadline;
|
||||
NSString *_pending, *_reply;
|
||||
}
|
||||
+ (instancetype)shared {
|
||||
static FaceclawRemoteInput *instance; static dispatch_once_t once;
|
||||
dispatch_once(&once, ^{ instance = [self new]; }); return instance;
|
||||
}
|
||||
- (instancetype)init {
|
||||
if ((self = [super init])) { _condition = [NSCondition new]; _server = _client = -1; }
|
||||
return self;
|
||||
}
|
||||
- (NSString *)start:(int)port { return [self start:port address:@"127.0.0.1"]; }
|
||||
- (NSString *)start:(int)port address:(NSString *)address {
|
||||
[_condition lock];
|
||||
if (_server >= 0) { [_condition unlock]; return @""; }
|
||||
struct addrinfo hints = {0}, *resolved = NULL;
|
||||
hints.ai_flags = AI_NUMERICHOST; hints.ai_socktype = SOCK_STREAM;
|
||||
NSString *service = [NSString stringWithFormat:@"%d", port];
|
||||
if (getaddrinfo(address.UTF8String, service.UTF8String, &hints, &resolved) != 0) {
|
||||
[_condition unlock]; return @"Invalid local address.";
|
||||
}
|
||||
BOOL wildcard = resolved->ai_family == AF_INET ?
|
||||
((struct sockaddr_in *)resolved->ai_addr)->sin_addr.s_addr == INADDR_ANY :
|
||||
IN6_IS_ADDR_UNSPECIFIED(&((struct sockaddr_in6 *)resolved->ai_addr)->sin6_addr);
|
||||
if (wildcard) { freeaddrinfo(resolved); [_condition unlock]; return @"Wildcard addresses are not allowed."; }
|
||||
int fd = socket(resolved->ai_family, SOCK_STREAM, 0), yes = 1;
|
||||
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
|
||||
int result = fd < 0 ? -1 : bind(fd, resolved->ai_addr, (socklen_t)resolved->ai_addrlen);
|
||||
freeaddrinfo(resolved);
|
||||
if (result || listen(fd, 8)) {
|
||||
if (fd >= 0) close(fd); [_condition unlock]; return @"Could not open input port on this address.";
|
||||
}
|
||||
_server = fd; NSUInteger generation = ++_generation;
|
||||
[_condition unlock];
|
||||
dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{ [self serve:fd generation:generation]; });
|
||||
return @"";
|
||||
}
|
||||
- (void)stop {
|
||||
[_condition lock]; ++_generation;
|
||||
// The serving thread owns close(); shutdown interrupts its blocking I/O.
|
||||
if (_server >= 0) shutdown(_server, SHUT_RDWR);
|
||||
if (_client >= 0) shutdown(_client, SHUT_RDWR);
|
||||
_server = _client = -1; _requestId = 0; _pending = _reply = nil;
|
||||
[_condition broadcast]; [_condition unlock];
|
||||
}
|
||||
- (NSString *)nextRequest {
|
||||
[_condition lock];
|
||||
NSString *result = NSDate.date.timeIntervalSince1970 < _deadline ? _pending : nil;
|
||||
_pending = nil; [_condition unlock]; return result;
|
||||
}
|
||||
- (void)complete:(long long)identifier response:(NSString *)response {
|
||||
[_condition lock];
|
||||
if (_requestId == identifier && NSDate.date.timeIntervalSince1970 < _deadline) { _reply = response; [_condition signal]; }
|
||||
[_condition unlock];
|
||||
}
|
||||
- (void)serve:(int)listener generation:(NSUInteger)generation {
|
||||
for (;;) {
|
||||
[_condition lock]; BOOL current = generation == _generation; [_condition unlock];
|
||||
if (!current) break;
|
||||
// Poll also guarantees stop is observed on platforms where shutdown does not wake accept.
|
||||
struct pollfd p = { .fd = listener, .events = POLLIN };
|
||||
if (poll(&p, 1, 250) <= 0) continue;
|
||||
int client = accept(listener, NULL, NULL);
|
||||
if (client < 0) break;
|
||||
@autoreleasepool {
|
||||
[_condition lock]; current = generation == _generation;
|
||||
if (current) _client = client;
|
||||
[_condition unlock];
|
||||
if (!current) { close(client); break; }
|
||||
struct timeval timeout = {5, 0}; int yes = 1;
|
||||
setsockopt(client, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
|
||||
setsockopt(client, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
|
||||
setsockopt(client, SOL_SOCKET, SO_NOSIGPIPE, &yes, sizeof(yes));
|
||||
NSTimeInterval readDeadline = NSDate.date.timeIntervalSince1970 + 5;
|
||||
NSMutableData *body = [NSMutableData new]; unsigned char byte; BOOL complete = NO;
|
||||
while (body.length <= 65536) {
|
||||
NSTimeInterval remaining = readDeadline - NSDate.date.timeIntervalSince1970;
|
||||
struct pollfd input = { .fd = client, .events = POLLIN };
|
||||
if (remaining <= 0 || poll(&input, 1, (int)(remaining * 1000)) <= 0 || recv(client, &byte, 1, 0) != 1) break;
|
||||
if (byte == '\n') { complete = YES; break; }
|
||||
[body appendBytes:&byte length:1];
|
||||
}
|
||||
NSString *text = complete ? [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding] : nil;
|
||||
if (text) {
|
||||
[_condition lock];
|
||||
if (generation == _generation) {
|
||||
_requestId = ++_nextId; _deadline = NSDate.date.timeIntervalSince1970 + 5; _reply = nil;
|
||||
NSData *json = [NSJSONSerialization dataWithJSONObject:@{@"id":@(_requestId), @"expiresAt":@(_deadline * 1000), @"body":text} options:0 error:nil];
|
||||
_pending = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
|
||||
while (!_reply && generation == _generation && NSDate.date.timeIntervalSince1970 < _deadline)
|
||||
[_condition waitUntilDate:[NSDate dateWithTimeIntervalSince1970:_deadline]];
|
||||
NSString *reply = _reply ?: @"{\"ok\":false,\"error\":\"timeout\",\"message\":\"Faceclaw did not respond in time.\"}";
|
||||
if (generation == _generation) { _pending = _reply = nil; _requestId = 0; }
|
||||
[_condition unlock];
|
||||
NSData *data = [[reply stringByAppendingString:@"\n"] dataUsingEncoding:NSUTF8StringEncoding];
|
||||
NSUInteger offset = 0;
|
||||
while (offset < data.length) {
|
||||
ssize_t n = send(client, (const char *)data.bytes + offset, data.length - offset, 0);
|
||||
if (n <= 0) break; offset += n;
|
||||
}
|
||||
} else [_condition unlock];
|
||||
}
|
||||
[_condition lock]; if (generation == _generation) _client = -1; [_condition unlock];
|
||||
close(client);
|
||||
}
|
||||
}
|
||||
close(listener);
|
||||
[_condition lock]; if (generation == _generation) _server = -1; [_condition unlock];
|
||||
}
|
||||
+ (NSString *)interfaces {
|
||||
NSMutableArray *result = [NSMutableArray new]; struct ifaddrs *interfaces = NULL;
|
||||
if (getifaddrs(&interfaces) == 0) {
|
||||
for (struct ifaddrs *item = interfaces; item; item = item->ifa_next) {
|
||||
if (!item->ifa_addr || !(item->ifa_flags & IFF_UP) || (item->ifa_flags & IFF_LOOPBACK)) continue;
|
||||
int family = item->ifa_addr->sa_family;
|
||||
if (family != AF_INET && family != AF_INET6) continue;
|
||||
char address[NI_MAXHOST];
|
||||
if (getnameinfo(item->ifa_addr, item->ifa_addr->sa_len, address, sizeof(address), NULL, 0, NI_NUMERICHOST)) continue;
|
||||
[result addObject:@{@"name":@(item->ifa_name), @"address":@(address), @"pointToPoint":@((item->ifa_flags & IFF_POINTOPOINT) != 0)}];
|
||||
}
|
||||
freeifaddrs(interfaces);
|
||||
}
|
||||
return [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:result options:0 error:nil] encoding:NSUTF8StringEncoding];
|
||||
}
|
||||
- (NSString *)randomSecret {
|
||||
unsigned char bytes[32];
|
||||
if (SecRandomCopyBytes(kSecRandomDefault, sizeof(bytes), bytes) != errSecSuccess) return @"";
|
||||
NSMutableString *hex = [NSMutableString new];
|
||||
for (NSUInteger i = 0; i < sizeof(bytes); i++) [hex appendFormat:@"%02x", bytes[i]];
|
||||
return hex;
|
||||
}
|
||||
- (NSString *)tokenDigest:(NSString *)value { return [FaceclawCrypto sha256:[value dataUsingEncoding:NSUTF8StringEncoding]]; }
|
||||
@end
|
||||
@@ -11,6 +11,7 @@ module FaceclawGraphics {
|
||||
header "FaceclawConfigPort.h"
|
||||
header "FaceclawEvenHubWebView.h"
|
||||
header "FaceclawCrypto.h"
|
||||
header "FaceclawRemoteInput.h"
|
||||
header "FaceclawQrScanner.h"
|
||||
export *
|
||||
}
|
||||
Reference in new issue
Block a user