Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions NativeScript/NativeScript.mm
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#include <mach-o/getsect.h>
#include "inspector/JsV8InspectorClient.h"
#include "runtime/Console.h"
#include "runtime/DevTunnel.h"
#include "runtime/Helpers.h"
#include "runtime/ModuleInternal.h"
#include "runtime/ModuleInternalCallbacks.h"
Expand Down Expand Up @@ -241,6 +242,9 @@ - (instancetype)initializeWithConfig:(Config*)config {
RuntimeConfig.MetadataPtr = ResolveMetadataPtr(config);
RuntimeConfig.IsDebug = [config IsDebug];
RuntimeConfig.LogToSystemConsole = [config LogToSystemConsole];
if (RuntimeConfig.IsDebug) {
tns::devtunnel::Init();
}

Runtime::Initialize();
DestroyMainRuntime();
Expand Down
60 changes: 60 additions & 0 deletions NativeScript/runtime/DevTunnel.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
#ifndef DevTunnel_h
#define DevTunnel_h

#include <cstdint>
#include <optional>
#include <string>
#include <vector>

namespace tns {
namespace devtunnel {

// The runtime's side of NativeScriptDevTunnel.framework (DevTunnelSPI.h),
// which debug builds embed. Everything here works from any thread.

struct TunnelRequest {
std::string name;
uint16_t preferredPort;
};

struct Tunnel {
std::string name;
uint16_t port;
};

struct TunnelInfo {
std::string bundleId;
// 0 while nothing is open.
uint16_t tunnelPort = 0;
std::vector<Tunnel> tunnels;
};

struct RequestResult {
// Set on success.
std::optional<TunnelInfo> info;
std::string error;
};

// Attaches the framework, which registers for the tool's TunnelRequest
// notification. Debug builds call it once at startup; later calls do nothing.
void Init();

// Whether the framework is embedded, built for this runtime, and the app is a
// debug build.
bool DevTunnelAvailable();

// Opens the tunnel port if needed (on `tunnelPort` or the first free port
// above it, else the framework's default) and a port per new tunnel name;
// existing names keep their ports. A token turns on authentication for every
// later connection to the tunnel port.
RequestResult Request(const std::vector<TunnelRequest>& tunnels,
std::optional<uint16_t> tunnelPort = std::nullopt,
std::optional<std::string> token = std::nullopt);

// What is open, whoever asked for it; empty without the framework.
std::optional<TunnelInfo> Info();

} // namespace devtunnel
} // namespace tns

#endif /* DevTunnel_h */
111 changes: 111 additions & 0 deletions NativeScript/runtime/DevTunnel.mm
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
#include "DevTunnel.h"
#include <Foundation/Foundation.h>
#include <dlfcn.h>
#include <os/log.h>
#include "DevTunnelSPI.h"
#include "Helpers.h"
#include "RuntimeConfig.h"

namespace tns {
namespace devtunnel {

namespace {

const char* BundleId() {
static const std::string bundleId = []() -> std::string {
NSString* identifier = [[NSBundle mainBundle] bundleIdentifier];
return identifier != nil ? std::string(identifier.UTF8String) : std::string();
}();
return bundleId.c_str();
}

const NSDevTunnelHost kHost = {
.version = NS_DEV_TUNNEL_SPI_VERSION,
.size = sizeof(NSDevTunnelHost),
.isDebug = []() -> bool { return RuntimeConfig.IsDebug; },
// NSLog's arguments read as <private> on a device; tools find the ports
// in this line.
.log = [](const char* message) { os_log(OS_LOG_DEFAULT, "%{public}s", message); },
.bundleId = BundleId,
};

// Once per process: dyld loads the framework, when the app embeds it, before
// the runtime starts.
const NSDevTunnelTunnel* Connected() {
static const NSDevTunnelTunnel* tunnel = []() -> const NSDevTunnelTunnel* {
if (!RuntimeConfig.IsDebug) {
return nullptr;
}
auto connect = reinterpret_cast<NSDevTunnelConnectFunction>(
dlsym(RTLD_DEFAULT, NS_DEV_TUNNEL_CONNECT_SYMBOL));
if (connect == nullptr) {
return nullptr;
}
const NSDevTunnelTunnel* connected = connect(&kHost);
if (connected == nullptr) {
return nullptr;
}
if (connected->version != NS_DEV_TUNNEL_SPI_VERSION ||
connected->size != sizeof(NSDevTunnelTunnel)) {
Log("NativeScript: ignoring %s, built for another runtime version",
NS_DEV_TUNNEL_CONNECT_SYMBOL);
return nullptr;
}
return connected;
}();
return tunnel;
}

TunnelInfo Convert(const NSDevTunnelInfo& raw) {
TunnelInfo info;
info.bundleId = raw.bundleId;
info.tunnelPort = raw.tunnelPort;
for (uint32_t i = 0; i < raw.count && i < NS_DEV_TUNNEL_MAX_TUNNELS; i++) {
info.tunnels.push_back({raw.tunnels[i].name, raw.tunnels[i].port});
}
return info;
}

} // namespace

void Init() { Connected(); }

bool DevTunnelAvailable() { return Connected() != nullptr; }

RequestResult Request(const std::vector<TunnelRequest>& tunnels, std::optional<uint16_t> tunnelPort,
std::optional<std::string> token) {
RequestResult result;
const NSDevTunnelTunnel* tunnel = Connected();
if (tunnel == nullptr) {
result.error = RuntimeConfig.IsDebug ? "the dev tunnel framework is not embedded in this app"
: "the dev tunnel works in debug builds only";
return result;
}
std::vector<NSDevTunnelSpec> specs;
specs.reserve(tunnels.size());
for (const TunnelRequest& request : tunnels) {
specs.push_back({request.name.c_str(), request.preferredPort});
}
NSDevTunnelInfo raw;
char error[256] = "";
if (tunnel->request(specs.data(), specs.size(), tunnelPort.value_or(0),
token.has_value() ? token->c_str() : nullptr, &raw, error, sizeof(error))) {
result.info = Convert(raw);
} else {
result.error = error;
}
return result;
}

std::optional<TunnelInfo> Info() {
const NSDevTunnelTunnel* tunnel = Connected();
if (tunnel == nullptr) {
return std::nullopt;
}
NSDevTunnelInfo raw;
tunnel->info(&raw);
return Convert(raw);
}

} // namespace devtunnel
} // namespace tns
78 changes: 78 additions & 0 deletions NativeScript/runtime/DevTunnelSPI.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
#ifndef DevTunnelSPI_h
#define DevTunnelSPI_h

// The interface between the runtime and NativeScriptDevTunnel.framework, the
// dev tunnel apps embed in debug builds only. The runtime looks up
// NS_DEV_TUNNEL_CONNECT_SYMBOL with dlsym and hands the framework a Host; the
// framework answers with its Tunnel table. Both sides check version and size
// and refuse any other, so a stale framework copy is ignored rather than
// misread. C only: the framework is written in C and sees nothing else of the
// runtime.

#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>

#ifdef __cplusplus
extern "C" {
#endif

#define NS_DEV_TUNNEL_SPI_VERSION 1
#define NS_DEV_TUNNEL_CONNECT_SYMBOL "NativeScriptDevTunnelConnect"

#define NS_DEV_TUNNEL_MAX_NAME 32
#define NS_DEV_TUNNEL_MAX_TUNNELS 16
#define NS_DEV_TUNNEL_MAX_BUNDLE_ID 255

typedef struct NSDevTunnelHost {
uint32_t version;
uint32_t size;
// The framework opens nothing unless this is true.
bool (*isDebug)(void);
// Any thread. Writes `message` to the system log, readable on a device.
void (*log)(const char* message);
// The app's bundle identifier; never null.
const char* (*bundleId)(void);
} NSDevTunnelHost;

typedef struct NSDevTunnelSpec {
const char* name;
uint16_t preferredPort;
} NSDevTunnelSpec;

typedef struct NSDevTunnelEntry {
char name[NS_DEV_TUNNEL_MAX_NAME + 1];
uint16_t port;
} NSDevTunnelEntry;

typedef struct NSDevTunnelInfo {
char bundleId[NS_DEV_TUNNEL_MAX_BUNDLE_ID + 1];
// 0 while nothing is open.
uint16_t tunnelPort;
uint32_t count;
NSDevTunnelEntry tunnels[NS_DEV_TUNNEL_MAX_TUNNELS];
} NSDevTunnelInfo;

typedef struct NSDevTunnelTunnel {
uint32_t version;
uint32_t size;
// Any thread. Opens the tunnel port if needed (preferring `tunnelPort`, or
// the framework's default when 0) and a port for each tunnel whose name is
// new; existing names keep their ports. A non-empty `token` turns on
// authentication; null or empty leaves it as it is. True fills `info`;
// false writes a message to `error`.
bool (*request)(const NSDevTunnelSpec* tunnels, size_t count,
uint16_t tunnelPort, const char* token, NSDevTunnelInfo* info,
char* error, size_t errorSize);
// Any thread.
void (*info)(NSDevTunnelInfo* info);
} NSDevTunnelTunnel;

typedef const NSDevTunnelTunnel* (*NSDevTunnelConnectFunction)(
const NSDevTunnelHost* host);

#ifdef __cplusplus
}
#endif

#endif /* DevTunnelSPI_h */
22 changes: 22 additions & 0 deletions NativeScriptDevTunnel/Info.plist
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
</dict>
</plist>
Loading
Loading