Skip to content

Commit f221123

Browse files
committed
feat: add JSON string escaping and output helpers
1 parent 3328494 commit f221123

1 file changed

Lines changed: 78 additions & 0 deletions

File tree

src/print.c

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
#include "common.h"
3232
#include "cli.h"
3333
#include "proto.h"
34+
#include <inttypes.h>
3435

3536
/*
3637
* Local definitions, structures and function prototypes
@@ -93,6 +94,83 @@ static char *lkup_svcnam(struct lsof_context *ctx, int h, int p, int pr,
9394
static int printinaddr(struct lsof_context *ctx);
9495
static int human_readable_size(SZOFFTYPE sz, int print, int col);
9596

97+
/*
98+
* JSON output helpers
99+
*/
100+
101+
static void json_puts_escaped(const char *s) {
102+
const unsigned char *p = (const unsigned char *)s;
103+
while (*p) {
104+
switch (*p) {
105+
case '"':
106+
fputs("\\\"", stdout);
107+
break;
108+
case '\\':
109+
fputs("\\\\", stdout);
110+
break;
111+
case '\b':
112+
fputs("\\b", stdout);
113+
break;
114+
case '\f':
115+
fputs("\\f", stdout);
116+
break;
117+
case '\n':
118+
fputs("\\n", stdout);
119+
break;
120+
case '\r':
121+
fputs("\\r", stdout);
122+
break;
123+
case '\t':
124+
fputs("\\t", stdout);
125+
break;
126+
default:
127+
if (*p < 0x20)
128+
printf("\\u%04x", (unsigned int)*p);
129+
else
130+
putchar(*p);
131+
break;
132+
}
133+
p++;
134+
}
135+
}
136+
137+
static void json_print_str(int *sep, const char *key, const char *val) {
138+
if (*sep)
139+
putchar(',');
140+
printf("\"%s\":\"", key);
141+
json_puts_escaped(val);
142+
putchar('"');
143+
*sep = 1;
144+
}
145+
146+
static void json_print_int(int *sep, const char *key, int val) {
147+
if (*sep)
148+
putchar(',');
149+
printf("\"%s\":%d", key, val);
150+
*sep = 1;
151+
}
152+
153+
static void json_print_uint64_str(int *sep, const char *key, uint64_t val) {
154+
if (*sep)
155+
putchar(',');
156+
printf("\"%s\":\"%" PRIu64 "\"", key, val);
157+
*sep = 1;
158+
}
159+
160+
static void json_print_long(int *sep, const char *key, long val) {
161+
if (*sep)
162+
putchar(',');
163+
printf("\"%s\":%ld", key, val);
164+
*sep = 1;
165+
}
166+
167+
static void json_print_ulong(int *sep, const char *key, unsigned long val) {
168+
if (*sep)
169+
putchar(',');
170+
printf("\"%s\":%lu", key, val);
171+
*sep = 1;
172+
}
173+
96174
#if !defined(HASNORPC_H)
97175
/*
98176
* fill_portmap() -- fill the RPC portmap program name table via a conversation

0 commit comments

Comments
 (0)