An open source, self-hosted, real-time port monitoring and discovery tool.
Feature/fix unknown system ports (#46)
Mostafa Wahieda869712dbb67
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a9f12a0..ef1fd86 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,12 @@All notable changes to Portracker will be documented in this file.+## [1.1.0] - 2025-08-23++### Frontend & Backend+- **System Port Name Fix**: Fixed the issue where system ports were incorrectly displayed as "unknown".+- **Consistent Status Indicators**: Improved status indicators for system ports to ensure consistency.+## [1.0.8] - 2025-08-20### Frontenddiff --git a/README.md b/README.mdindex a160f46..54520c9 100644--- a/README.md+++ b/README.md@@ -51,7 +51,13 @@ services:image: mostafawahied/portracker:latestcontainer_name: portrackerrestart: unless-stopped- pid: "host" # Required for comprehensive port detection+ pid: "host" # Required for port detection+ # Required permissions for system ports service namespace access+ cap_add:+ - SYS_PTRACE # Linux hosts: read other PIDs' /proc entries+ - SYS_ADMIN # Docker Desktop: allow namespace access for host ports (required for MacOS)+ security_opt:+ - apparmor:unconfined # Required for system portsvolumes:# Required for data persistence- ./portracker-data:/data@@ -59,9 +65,7 @@ services:- /var/run/docker.sock:/var/run/docker.sock:roports:- "4999:4999"- environment:- - DATABASE_PATH=/data/portracker.db- - PORT=4999+ # environment:# Optional: For enhanced TrueNAS features# - TRUENAS_API_KEY=your-api-key-here```@@ -79,11 +83,12 @@ docker run -d \--name portracker \--restart unless-stopped \--pid host \+ --cap-add SYS_PTRACE \+ --cap-add SYS_ADMIN \+ --security-opt apparmor=unconfined \-p 4999:4999 \-v ./portracker-data:/data \-v /var/run/docker.sock:/var/run/docker.sock:ro \- -e DATABASE_PATH=/data/portracker.db \- -e PORT=4999 \mostafawahied/portracker:latest```@@ -115,13 +120,16 @@ services:container_name: portrackerrestart: unless-stoppedpid: "host"+ cap_add:+ - SYS_PTRACE+ - SYS_ADMIN+ security_opt:+ - apparmor:unconfinedvolumes:- ./portracker-data:/dataports:- "4999:4999"environment:- - DATABASE_PATH=/data/portracker.db- - PORT=4999- DOCKER_HOST=tcp://docker-proxy:2375depends_on:- docker-proxy@@ -148,10 +156,11 @@ docker run -d \--name portracker \--restart unless-stopped \--pid host \+ --cap-add SYS_PTRACE \+ --cap-add SYS_ADMIN \+ --security-opt apparmor=unconfined \-p 4999:4999 \-v ./portracker-data:/data \- -e DATABASE_PATH=/data/portracker.db \- -e PORT=4999 \-e DOCKER_HOST=tcp://localhost:2375 \mostafawahied/portracker:latest```@@ -192,4 +201,4 @@ Contributions are welcome! Please feel free to open an issue to report a bug or## License-This project is licensed under the MIT License - see the [LICENSE](https://github.com/Mostafa-Wahied/portracker/blob/main/LICENSE)+This project is licensed under the MIT License - see the [LICENSE](https://github.com/Mostafa-Wahied/portracker/blob/main/LICENSE)\ No newline at end of filediff --git a/backend/collectors/docker_collector.js b/backend/collectors/docker_collector.jsindex 1eec458..294ab6b 100644--- a/backend/collectors/docker_collector.js+++ b/backend/collectors/docker_collector.js@@ -605,6 +605,10 @@ class DockerCollector extends BaseCollector {return ports;} catch (nsenterErr) {this.logInfo(`nsenter method failed: ${nsenterErr.message}, trying alternative methods`);+ const msg = String(nsenterErr?.message || '').toLowerCase();+ if (msg.includes('permission denied') || msg.includes('operation not permitted') || msg.includes('exit code 1')) {+ this.logWarn('Hint: nsenter requires cap_add: [SYS_ADMIN] to access the host network namespace on Docker Desktop (macOS/Windows).');+ }try {const { stdout: netNsCheck } = await execAsync("readlink /proc/self/ns/net 2>/dev/null");diff --git a/backend/collectors/truenas_collector.js b/backend/collectors/truenas_collector.jsindex 0d88ee2..dff0ada 100644--- a/backend/collectors/truenas_collector.js+++ b/backend/collectors/truenas_collector.js@@ -647,6 +647,10 @@ class TrueNASCollector extends BaseCollector {}} catch (nsenterErr) {this.logWarn(`nsenter method failed: ${nsenterErr.message}`);+ const msg = String(nsenterErr?.message || '').toLowerCase();+ if (msg.includes('permission denied') || msg.includes('operation not permitted') || msg.includes('exit code 1')) {+ this.logWarn('Hint: nsenter requires cap_add: [SYS_ADMIN] to access the host network namespace on Docker Desktop (macOS/Windows).');+ }}this.logError('All port collection methods failed');diff --git a/backend/index.js b/backend/index.jsindex 8a9ae8a..33b9cad 100644--- a/backend/index.js+++ b/backend/index.js@@ -1965,7 +1965,7 @@ app.post("/api/notes/batch", (req, res) => {});app.get("/api/ping", async (req, res) => {- const { host_ip, host_port, target_server_url, owner, internal, container_id } = req.query;+ const { host_ip, host_port, target_server_url, owner, internal, container_id, source } = req.query;const serverId = req.query.server_id;const currentDebug = req.query.debug === "true";@@ -1997,6 +1997,7 @@ app.get("/api/ping", async (req, res) => {if (host_ip) params.set('host_ip', host_ip);if (host_port) params.set('host_port', host_port);if (owner) params.set('owner', owner);+ if (source) params.set('source', source);if (currentDebug) params.set('debug', 'true');const url = `${base}/api/ping?${params.toString()}`;const resp = await fetch(url, { headers: { 'accept': 'application/json' } });@@ -2054,14 +2055,14 @@ app.get("/api/ping", async (req, res) => {});}- if (serviceInfo.type === 'system') {+ if (serviceInfo.type === 'system' || source === 'system') {return res.json({reachable: true,status: 'system',color: 'gray',- title: serviceInfo.description,- serviceType: serviceInfo.type,- serviceName: serviceInfo.name+ title: source === 'system' ? 'System service' : serviceInfo.description,+ serviceType: 'system',+ serviceName: source === 'system' ? 'System Service' : serviceInfo.name});}diff --git a/backend/lib/proc-parser.js b/backend/lib/proc-parser.jsindex bc9eb37..93ab59c 100644--- a/backend/lib/proc-parser.js+++ b/backend/lib/proc-parser.js@@ -9,16 +9,26 @@ class ProcParser {this.logger = new Logger("ProcParser", { debug: process.env.DEBUG === 'true' });const hostProcPath = process.env.HOST_PROC;-+ if (hostProcPath) {+ try {+ require('fs').statSync(path.join(hostProcPath, 'net', 'tcp'));+ this.procPath = hostProcPath;+ this.logger.debug(`Using /proc path from HOST_PROC: ${this.procPath}`);+ } catch (e) {+ this.logger.warn(`HOST_PROC provided but unusable (${hostProcPath}): ${e.message}`);+ this.procPath = procPath;+ }+ }+const procPaths = [- procPath,- '/proc',hostProcPath,'/host/proc','/hostproc',+ procPath,+ '/proc',].filter(Boolean);- this.procPath = procPath;+ this.procPath = this.procPath || procPath;for (const testPath of procPaths) {try {require('fs').statSync(path.join(testPath, 'net', 'tcp'));@@ -26,7 +36,7 @@ class ProcParser {this.logger.debug(`Using /proc path: ${this.procPath}`);break;} catch {- ;+ void 0;}}@@ -85,7 +95,10 @@ class ProcParser {/** Parse /proc/net/tcp and /proc/net/tcp6 */async getTcpPorts() {- const ports = [];+ const ports = [];+ const prelim = [];+ const inodeMap = await this._buildInodeMap();+ let resolvedOwners = 0;for (const file of ['tcp', 'tcp6']) {try {@@ -109,28 +122,65 @@ class ProcParser {if (port === 0 || port > 65535) continue;const ip = this._parseHexAddress(addrHex);- const processInfo = await this._findProcessByInode(parseInt(inode, 10));+ const inodeNum = parseInt(inode, 10);+ const processInfo = inodeMap.get(inodeNum);+ if (processInfo && processInfo.name) resolvedOwners++;- ports.push({+ const entry = {protocol: 'tcp',host_ip: ip,host_port: port,- inode: parseInt(inode, 10),+ inode: inodeNum,pid: processInfo?.pid,owner: processInfo?.name || 'unknown'- });+ };+ ports.push(entry);+ prelim.push({ inode: inodeNum });}} catch (err) {this.logger.warn(`Warning reading network file ${file}:`, err.message);}}+ this.logger.debug(`TCP parse complete: ports=${ports.length}, ownersResolved=${resolvedOwners}, inodeMapSize=${inodeMap.size}`);++ const needFallback = ports.length > 0 && resolvedOwners < Math.floor(ports.length * 0.5);+ if (needFallback) {+ const targetInodes = new Set(prelim.map(p => p.inode));+ const fallbackMap = await this._buildInodeMapForInodes(targetInodes);+ let addResolved = 0;+ for (const p of ports) {+ if (!p.owner || p.owner === 'unknown') {+ const info = fallbackMap.get(p.inode);+ if (info) {+ p.owner = info.name;+ p.pid = info.pid;+ addResolved++;+ }+ }+ }+ this.logger.debug(`TCP targeted fd-scan fallback resolved additional=${addResolved}`);+ if ((resolvedOwners + addResolved) < Math.floor(ports.length * 0.5)) {+ if (this.isContainerized) {+ this.logger.warn(+ 'Low owner resolution via /proc. Hint: On Docker Desktop (macOS/Windows), enable cap_add: [SYS_ADMIN] to allow namespace tools (nsenter) in collectors; on Linux hosts, ensure cap_add: [SYS_PTRACE] and security_opt: [apparmor:unconfined] with /proc:/host/proc:ro.'+ );+ } else {+ this.logger.warn(+ 'Low owner resolution via /proc. Hint: Grant cap_add: [SYS_PTRACE] and security_opt: [apparmor:unconfined], and mount /proc from the host if running in a container (e.g., /proc:/host/proc:ro).'+ );+ }+ }+ }return ports;}/** Parse /proc/net/udp and /proc/net/udp6 with proper filtering */async getUdpPorts(includeAll = false) {- const ports = [];+ const ports = [];+ const prelim = [];+ const inodeMap = await this._buildInodeMap();+ let resolvedOwners = 0;for (const file of ['udp', 'udp6']) {try {@@ -155,21 +205,55 @@ class ProcParser {}const ip = this._parseHexAddress(addrHex);- const processInfo = await this._findProcessByInode(parseInt(inode, 10));+ const inodeNum = parseInt(inode, 10);+ const processInfo = inodeMap.get(inodeNum);+ if (processInfo && processInfo.name) resolvedOwners++;- ports.push({+ const entry = {protocol: 'udp',host_ip: ip,host_port: port,- inode: parseInt(inode, 10),+ inode: inodeNum,pid: processInfo?.pid,owner: processInfo?.name || 'unknown'- });+ };+ ports.push(entry);+ prelim.push({ inode: inodeNum });}} catch (err) {this.logger.warn(`Warning reading network file ${file}:`, err.message);}}+ this.logger.debug(`UDP parse complete: ports=${ports.length}, ownersResolved=${resolvedOwners}, inodeMapSize=${inodeMap.size}`);++ const needFallback = ports.length > 0 && resolvedOwners < Math.floor(ports.length * 0.5);+ if (needFallback) {+ const targetInodes = new Set(prelim.map(p => p.inode));+ const fallbackMap = await this._buildInodeMapForInodes(targetInodes);+ let addResolved = 0;+ for (const p of ports) {+ if (!p.owner || p.owner === 'unknown') {+ const info = fallbackMap.get(p.inode);+ if (info) {+ p.owner = info.name;+ p.pid = info.pid;+ addResolved++;+ }+ }+ }+ this.logger.debug(`UDP targeted fd-scan fallback resolved additional=${addResolved}`);+ if ((resolvedOwners + addResolved) < Math.floor(ports.length * 0.5)) {+ if (this.isContainerized) {+ this.logger.warn(+ 'Low owner resolution via /proc. Hint: On Docker Desktop (macOS/Windows), enable cap_add: [SYS_ADMIN] to allow namespace tools (nsenter) in collectors; on Linux hosts, ensure cap_add: [SYS_PTRACE] and security_opt: [apparmor:unconfined] with /proc:/host/proc:ro.'+ );+ } else {+ this.logger.warn(+ 'Low owner resolution via /proc. Hint: Grant cap_add: [SYS_PTRACE] and security_opt: [apparmor:unconfined], and mount /proc from the host if running in a container (e.g., /proc:/host/proc:ro).'+ );+ }+ }+ }return ports;}@@ -209,6 +293,15 @@ class ProcParser {}} catch (err) {this.logger.warn(`Cannot read process information: ${err.message}`);+ if (this.isContainerized) {+ this.logger.warn(+ 'Hint: Grant cap_add: [SYS_PTRACE] and security_opt: [apparmor:unconfined]; mount host /proc as read-only (e.g., /proc:/host/proc:ro) and set HOST_PROC. On Docker Desktop, system-wide ownership mapping may require cap_add: [SYS_ADMIN] for namespace access.'+ );+ } else {+ this.logger.warn(+ 'Hint: On Linux hosts, grant cap_add: [SYS_PTRACE] and security_opt: [apparmor:unconfined] when running in a container to read other processes\' info.'+ );+ }}return listeningPorts >= 1 || canReadProcesses;@@ -235,49 +328,151 @@ class ProcParser {return '0.0.0.0';}- /** Find process by socket inode */- async _findProcessByInode(inode) {- if (this.isContainerized) {- return null;+++ /**+ * Build a cached map of socket inode -> { pid, name }+ * - Caches for a short duration to avoid repeated /proc scans+ * - Uses /proc/[pid]/comm for clean process name; falls back to cmdline+ */+ async _buildInodeMap() {+ const now = Date.now();+ const ttlMs = 2000;+ if (this._inodeMap && this._inodeMapTs && now - this._inodeMapTs < ttlMs) {+ return this._inodeMap;}-- try {- const dirs = await fs.readdir(this.procPath);-- for (const dir of dirs) {++ const map = new Map();+ const roots = Array.from(new Set([+ this.procPath,+ '/host/proc',+ '/proc',+ ]));++ let totalPids = 0;+ for (const root of roots) {+ let pids;+ try {+ pids = await fs.readdir(root);+ } catch {+ continue;+ }++ totalPids += pids.filter(p => /^\d+$/.test(p)).length;++ for (const dir of pids) {if (!/^\d+$/.test(dir)) continue;-const pid = parseInt(dir, 10);- const fdPath = path.join(this.procPath, dir, 'fd');-+ const fdPath = path.join(root, dir, 'fd');++ let procName = 'unknown';+ try {+ const comm = await fs.readFile(path.join(root, dir, 'comm'), 'utf8');+ procName = comm.trim() || 'unknown';+ } catch {+ try {+ const cmdline = await fs.readFile(path.join(root, dir, 'cmdline'), 'utf8');+ const first = (cmdline.split('\0')[0] || '').trim();+ if (first) {+ procName = first.split('/').pop();+ }+ } catch {+ void 0;+ }+ }+try {const fds = await fs.readdir(fdPath);-for (const fd of fds) {try {const link = await fs.readlink(path.join(fdPath, fd));- if (link === `socket:[${inode}]`) {- const cmdline = await fs.readFile(- path.join(this.procPath, dir, 'cmdline'),- 'utf8'- );- const name = cmdline.split('\0')[0].split('/').pop() || 'unknown';-- return { pid, name };+ const m = link.match(/^socket:\[(\d+)\]$/);+ if (m) {+ const inode = parseInt(m[1], 10);+ if (!Number.isNaN(inode)) {+ if (!map.has(inode)) map.set(inode, { pid, name: procName });+ }}} catch {- ;+ void 0;}}} catch {- ;+ void 0;}}- } catch (err) {- this.logger.warn(`Error reading process info: ${err.message}`);}-- return null;++ this._inodeMap = map;+ this._inodeMapTs = now;+ this.logger.debug(`Built inode map: entries=${map.size}, totalPidsSeen=${totalPids}, roots=${roots.join(',')}`);+ return map;+ }++ async _buildInodeMapForInodes(targetInodes) {+ const map = new Map();+ if (!targetInodes || targetInodes.size === 0) return map;+ const roots = Array.from(new Set([+ this.procPath,+ '/host/proc',+ '/proc',+ ]));+ let matched = 0;+ let pidsSeen = 0;+ let fdsChecked = 0;+ for (const root of roots) {+ let pids;+ try {+ pids = await fs.readdir(root);+ } catch {+ continue;+ }+ for (const dir of pids) {+ if (!/^\d+$/.test(dir)) continue;+ pidsSeen++;+ const pid = parseInt(dir, 10);+ const fdPath = path.join(root, dir, 'fd');+ let procName = 'unknown';+ try {+ const comm = await fs.readFile(path.join(root, dir, 'comm'), 'utf8');+ procName = comm.trim() || 'unknown';+ } catch {+ try {+ const cmdline = await fs.readFile(path.join(root, dir, 'cmdline'), 'utf8');+ const first = (cmdline.split('\0')[0] || '').trim();+ if (first) procName = first.split('/').pop();+ } catch {+ void 0;+ }+ }+ try {+ const fds = await fs.readdir(fdPath);+ for (const fd of fds) {+ fdsChecked++;+ try {+ const link = await fs.readlink(path.join(fdPath, fd));+ const m = link.match(/^socket:\[(\d+)\]$/);+ if (m) {+ const inode = parseInt(m[1], 10);+ if (targetInodes.has(inode) && !map.has(inode)) {+ map.set(inode, { pid, name: procName });+ matched++;+ if (matched >= targetInodes.size) break;+ }+ }+ } catch {+ void 0;+ }+ }+ } catch {+ void 0;+ }+ if (matched >= targetInodes.size) break;+ }+ if (matched >= targetInodes.size) break;+ }+ this.logger.debug(`Built targeted fd inode map: matched=${matched}/${targetInodes.size}, pidsSeen=${pidsSeen}, fdsChecked=${fdsChecked}`);+ return map;}/** Check if a process belongs to a Docker container */@@ -291,7 +486,7 @@ class ProcParser {return match[1].substring(0, 12);}} catch {- ;+ void 0;}return null;diff --git a/backend/lib/truenas-auto-discover.js b/backend/lib/truenas-auto-discover.jsindex befdd1f..0df7308 100644--- a/backend/lib/truenas-auto-discover.js+++ b/backend/lib/truenas-auto-discover.js@@ -222,7 +222,7 @@ function detectHostAddresses() {}}} catch {- ;+ void 0;}hostAddresses.push("host.docker.internal");diff --git a/docker-compose.yml b/docker-compose.ymlindex cdbbd3f..651dcbe 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -7,6 +7,16 @@ services:# Required for comprehensive system port detection# This allows Portracker to see all host processes for accurate port mappingpid: "host"++ # Capabilities & security (universal, required)+ # - SYS_PTRACE enables reading other processes' /proc entries on Linux hosts+ # - SYS_ADMIN enables namespace entry on Docker Desktop (macOS/Windows)+ # - apparmor:unconfined disables AppArmor restrictions that may block /proc access+ cap_add:+ - SYS_PTRACE+ - SYS_ADMIN+ security_opt:+ - apparmor:unconfinedvolumes:# Required: Data persistence for SQLite database@@ -22,12 +32,14 @@ services:# - /sys/fs/cgroup:/host/sys/fs/cgroup:roports:- - "${HOST_PORT:-4999}:4999"+ - "4999:4999"environment:# CORE CONFIGURATION (Required)- - DATABASE_PATH=/data/portracker.db- - PORT=4999+ # - DATABASE_PATH=/data/portracker.db+ # - PORT=4999+ # Tell Portracker where to find the host /proc (matches the volume above)+ # - HOST_PROC=/host/proc# DOCKER CONFIGURATION# Uncomment to use with docker-proxy for enhanced security@@ -42,7 +54,7 @@ services:# PERFORMANCE SETTINGS (Optional)# Cache duration - increase for better performance, decrease for fresher data- - CACHE_TIMEOUT_MS=60000+ # - CACHE_TIMEOUT_MS=60000# Disable caching entirely (not recommended for production)# - DISABLE_CACHE=true@@ -62,6 +74,7 @@ services:start_period: 30sretries: 3+# OPTIONAL: Enhanced Security with Docker Socket Proxy# Uncomment the entire section below for additional Docker socket security# This adds a proxy layer between Portracker and the Docker socketdiff --git a/frontend/src/components/server/PortStatusIndicator.jsx b/frontend/src/components/server/PortStatusIndicator.jsxindex 036826d..3b9a5d0 100644--- a/frontend/src/components/server/PortStatusIndicator.jsx+++ b/frontend/src/components/server/PortStatusIndicator.jsx@@ -36,6 +36,10 @@ export function PortStatusIndicator({if (port.owner) {pingApiUrl += `&owner=${encodeURIComponent(port.owner)}`;}++ if (port.source) {+ pingApiUrl += `&source=${encodeURIComponent(port.source)}`;+ }if (serverId &&@@ -71,7 +75,7 @@ export function PortStatusIndicator({clearTimeout(timeoutId);controller.abort();};- }, [port.host_ip, port.host_port, port.owner, port.internal, port.container_id, serverId, serverUrl, onProtocolChange]);+ }, [port.host_ip, port.host_port, port.owner, port.internal, port.container_id, port.source, serverId, serverUrl, onProtocolChange]);const getDotState = () => {if (checking) {diff --git a/package.json b/package.jsonindex a5b5222..f72e0f6 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "portracker",- "version": "1.0.8",+ "version": "1.1.0","description": "A multi-platform port-tracking dashboard","main": "backend/index.js","scripts": {