Skip to content
Open
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
21 changes: 11 additions & 10 deletions src/print.c
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ static void fill_porttab(struct lsof_context *ctx);
static char *lkup_port(struct lsof_context *ctx, int p, int pr, int src);
static char *lkup_svcnam(struct lsof_context *ctx, int h, int p, int pr,
int ss);
static int printinaddr(struct lsof_context *ctx);
static int formatinaddr(struct lsof_context *ctx);
static int human_readable_size(SZOFFTYPE sz, int print, int col);

/*
Expand Down Expand Up @@ -1191,10 +1191,10 @@ void print_file(struct lsof_context *ctx) {
}

/*
* printinaddr() - print Internet addresses
* formatinaddr() - format Internet addresses in Namech
*/

static int printinaddr(struct lsof_context *ctx) {
static int formatinaddr(struct lsof_context *ctx) {
int i, len, src;
char *host, *port;
int nl = Namechl - 1;
Expand Down Expand Up @@ -1333,11 +1333,7 @@ static int printinaddr(struct lsof_context *ctx) {
nl -= len + 1;
}
}
if (Namech[0]) {
safestrprt(Namech, stdout, 0);
return (1);
}
return (0);
return (Namech[0] != '\0');
}

/*
Expand Down Expand Up @@ -1441,8 +1437,10 @@ void printname(struct lsof_context *ctx, int nl) /* NL status */
/*
* If the file has Internet addresses, print them.
*/
if (printinaddr(ctx))
if (formatinaddr(ctx)) {
safestrprt(Namech, stdout, 0);
ps++;
}
goto print_nma;
}
if (((Lf->ntype == N_BLK) || (Lf->ntype == N_CHR)) && Lf->dev_def &&
Expand Down Expand Up @@ -1988,7 +1986,10 @@ static void json_print_file(struct lsof_context *ctx, int *sep) {
}
#endif /* defined(HASFSTRUCT) */

if (FieldSel[LSOF_FIX_NAME].st && Lf->nm) {
if (FieldSel[LSOF_FIX_NAME].st && (Lf->li[0].af || Lf->li[1].af) &&
formatinaddr(ctx)) {
json_print_str(sep, "name", Namech);
} else if (FieldSel[LSOF_FIX_NAME].st && Lf->nm) {
json_print_str(sep, "name", Lf->nm);
}

Expand Down
59 changes: 59 additions & 0 deletions tests/case-30-json-output.bash
Original file line number Diff line number Diff line change
Expand Up @@ -67,5 +67,64 @@ assert d['processes'] == [], 'empty result should have empty processes array'
fi
echo "PASS: -J -t mutual exclusivity" >> $report

# Network names must include the same endpoints as -Fn, in both JSON modes.
python3 - "$lsof" <<'PY' || exit 1
import json
import os
import socket
import subprocess
import sys

listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listener.bind(("127.0.0.1", 0))
listener.listen(1)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(listener.getsockname())
accepted, _ = listener.accept()
udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp.bind(("0.0.0.0", 0))
sockets = [listener, client, accepted, udp]
ipv6 = None
try:
ipv6 = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
ipv6.bind(("::1", 0))
ipv6.listen(1)
except OSError as e:
if ipv6 is not None:
ipv6.close()
print(f"SKIP: IPv6 endpoint coverage unavailable: {e}")
else:
sockets.append(ipv6)
base = [sys.argv[1], "-nP", "-a", "-p", str(os.getpid()), "-i"]

def run(options):
result = subprocess.run(base + options, capture_output=True, text=True,
timeout=10)
assert result.returncode == 0, result.stderr
return result.stdout

names = {}
for line in run(["-Ffn"]).splitlines():
if line.startswith("f"):
fd = line[1:]
elif line.startswith("n"):
names[fd] = line[1:]
assert set(names) == {str(s.fileno()) for s in sockets}, names
assert names[str(listener.fileno())] == f"127.0.0.1:{listener.getsockname()[1]}"
assert names[str(udp.fileno())] == f"*:{udp.getsockname()[1]}"
for mode in ("-J", "-j"):
for fields in ([], ["-Ffn"]):
output = run([mode] + fields)
files = (json.loads(output)["processes"][0]["files"] if mode == "-J"
else [json.loads(line) for line in output.splitlines()])
actual = {f["fd"]: f.get("name") for f in files}
assert actual == names, (mode, fields, actual, names)
output = run([mode, "-Ff"])
files = (json.loads(output)["processes"][0]["files"] if mode == "-J"
else [json.loads(line) for line in output.splitlines()])
assert all("name" not in f for f in files), (mode, files)
print("PASS: JSON/JSONL socket endpoints match -Fn and honor field selection")
PY

exit 0
} > $report 2>&1
Loading