Debian Codegraph @

src/libsystemd/sd-json/json-stream.h

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 #pragma once
3
4 #include <sys/socket.h>
5
6 #include "sd-forward.h"
7
8 #include "list.h"
9 #include "log.h"
10
11 /* JsonStream provides the transport layer used by sd-varlink (and other consumers like
12 * the QMP client) for exchanging length-delimited JSON messages over a pair of file
13 * descriptors. It owns the input/output buffers, the file-descriptor passing machinery
14 * (SCM_RIGHTS), the deferred output queue, and the read/write/parse step functions. It
15 * does not implement any state machine, dispatch, callback or event-source plumbing —
16 * those concerns belong to the consumer. */
17
18 typedef struct JsonStreamQueueItem JsonStreamQueueItem;
19
20 typedef enum JsonStreamFlags {
21 JSON_STREAM_BOUNDED_READS = 1u << 0,
22 JSON_STREAM_INPUT_SENSITIVE = 1u << 1,
23 JSON_STREAM_ALLOW_FD_PASSING_INPUT = 1u << 2,
24 JSON_STREAM_ALLOW_FD_PASSING_OUTPUT = 1u << 3,
25 JSON_STREAM_CONNECTING = 1u << 4,
26 JSON_STREAM_GOT_POLLHUP = 1u << 5,
27 JSON_STREAM_WRITE_DISCONNECTED = 1u << 6,
28 JSON_STREAM_READ_DISCONNECTED = 1u << 7,
29 JSON_STREAM_PREFER_READ = 1u << 8,
30 JSON_STREAM_PREFER_WRITE = 1u << 9,
31 JSON_STREAM_OUTPUT_BUFFER_SENSITIVE = 1u << 10,
32 } JsonStreamFlags;
33
34 /* What the consumer's high-level state machine is currently doing — used by the various
35 * "what should I do right now?" APIs (get_events, wait, should_disconnect) to decide
36 * whether to ask for read events, whether transport death matters, and whether the idle
37 * timeout deadline is currently in force. */
38 typedef enum JsonStreamPhase {
39 JSON_STREAM_PHASE_READING, /* waiting for the next inbound message, no deadline */
40 JSON_STREAM_PHASE_AWAITING_REPLY, /* waiting for a reply with the idle timeout deadline */
41 JSON_STREAM_PHASE_IDLE_CLIENT, /* idle client, no in-flight call */
42 JSON_STREAM_PHASE_PENDING_OUTPUT, /* has more output queued, waiting to send */
43 JSON_STREAM_PHASE_OTHER, /* none of the above */
44 } JsonStreamPhase;
45
46 /* Consumer hooks supplied at construction time:
47 * • phase — queried by get_events / wait / should_disconnect / attach_event's prepare
48 * callback whenever the consumer's current phase is needed.
49 * • dispatch — invoked by attach_event's io and time callbacks after the stream has
50 * consumed the revents, so the consumer can drive its state machine
51 * forward. Should return 0 on success or a negative errno; the stream logs
52 * the failure and continues running. */
53 typedef JsonStreamPhase (*json_stream_phase_t)(void *userdata);
54 typedef int (*json_stream_dispatch_t)(void *userdata);
55
56 typedef struct JsonStreamParams {
57 const char *delimiter; /* message delimiter; NULL → single NUL byte (varlink), e.g. "\r\n" for QMP */
58 size_t buffer_max; /* maximum bytes buffered before -ENOBUFS; 0 = 16 MiB default */
59 size_t read_chunk; /* per-read chunk size; 0 = 64 KiB default */
60 size_t queue_max; /* maximum number of queued output items; 0 = 64 Ki default */
61
62 /* Consumer hooks (see typedefs above). */
63 json_stream_phase_t phase;
64 json_stream_dispatch_t dispatch;
65 void *userdata;
66 } JsonStreamParams;
67
68 typedef struct JsonStream {
69 char *delimiter; /* message delimiter; NULL → NUL byte (varlink), e.g. "\r\n" for QMP */
70 size_t buffer_max;
71 size_t read_chunk;
72 size_t queue_max;
73
74 char *description;
75
76 int input_fd;
77 int output_fd;
78
79 usec_t timeout; /* relative; USEC_INFINITY = no timeout */
80 usec_t last_activity; /* CLOCK_MONOTONIC */
81
82 /* Cached peer credentials */
83 struct ucred ucred;
84 bool ucred_acquired;
85 int peer_pidfd;
86
87 /* Cached socket address family. -1 = unchecked, AF_UNSPEC = checked-not-socket,
88 * otherwise the resolved family. */
89 int af;
90
91 sd_event *event;
92 sd_event_source *input_event_source;
93 sd_event_source *output_event_source;
94 sd_event_source *time_event_source;
95
96 json_stream_phase_t phase_cb;
97 json_stream_dispatch_t dispatch_cb;
98 void *userdata;
99
100 char *input_buffer;
101 size_t input_buffer_index;
102 size_t input_buffer_size;
103 size_t input_buffer_unscanned;
104
105 void *input_control_buffer;
106 size_t input_control_buffer_size;
107
108 char *output_buffer;
109 size_t output_buffer_index;
110 size_t output_buffer_size;
111
112 int *input_fds;
113 size_t n_input_fds;
114
115 int *output_fds;
116 size_t n_output_fds;
117
118 LIST_HEAD(JsonStreamQueueItem, output_queue);
119 JsonStreamQueueItem *output_queue_tail;
120 size_t n_output_queue;
121
122 JsonStreamFlags flags;
123 } JsonStream;
124
125 int json_stream_init(JsonStream *s, const JsonStreamParams *params);
126 void json_stream_done(JsonStream *s);
127
128 /* Optional description used as the prefix for the stream's debug log lines (sent/received
129 * messages, POLLHUP detection, async connect completion, etc.). The string is duped. */
130 int json_stream_set_description(JsonStream *s, const char *description);
131 const char* json_stream_get_description(const JsonStream *s);
132
133 static inline const char* json_stream_description(const JsonStream *s) {
134 return (s ? s->description : NULL) ?: "json-stream";
135 }
136
137 #define json_stream_log(s, fmt, ...) \
138 log_debug("%s: " fmt, json_stream_description(s), ##__VA_ARGS__)
139
140 #define json_stream_log_errno(s, error, fmt, ...) \
141 log_debug_errno((error), "%s: " fmt, json_stream_description(s), ##__VA_ARGS__)
142
143 /* fd ownership */
144 int json_stream_attach_fds(JsonStream *s, int input_fd, int output_fd);
145
146 /* Open an AF_UNIX SOCK_STREAM socket and connect to the given filesystem path, attaching
147 * the resulting fd to the stream. Handles paths too long for sockaddr_un by routing through
148 * O_PATH (connect_unix_path()). If the connect() returns EAGAIN/EINPROGRESS the stream's
149 * connecting state is set so that the consumer waits for POLLOUT before treating the
150 * connection as established. Returns 0 on success or successfully started async connect,
151 * negative errno on failure. */
152 int json_stream_connect_address(JsonStream *s, const char *address);
153
154 /* Adopt a pre-connected pair of fds, ensuring both are non-blocking. Equivalent to
155 * json_stream_attach_fds() but does the fd_nonblock() dance up front, so the caller can
156 * pass in fds without having to know whether they were already configured. */
157 int json_stream_connect_fd_pair(JsonStream *s, int input_fd, int output_fd);
158
159 bool json_stream_flags_set(const JsonStream *s, JsonStreamFlags flags);
160 void json_stream_set_flags(JsonStream *s, JsonStreamFlags flags, bool b);
161
162 /* Combines the transport-level disconnect signals (write/read disconnected, buffered
163 * output, POLLHUP, async connect) with the consumer's current phase (queried via the
164 * registered get_phase callback) to answer "should the consumer initiate teardown right
165 * now?". The decision logic mirrors what the original varlink transport did but stays
166 * generic enough for other JSON-line consumers. */
167 bool json_stream_should_disconnect(const JsonStream *s);
168
169 /* Enable/disable fd passing. These verify the underlying fd is an AF_UNIX socket and
170 * (for input) optionally set SO_PASSRIGHTS. */
171 int json_stream_set_allow_fd_passing_input(JsonStream *s, bool enabled, bool with_sockopt);
172 int json_stream_set_allow_fd_passing_output(JsonStream *s, bool enabled);
173
174 /* Output: enqueue a JSON variant together with an optional set of file descriptors. Fast
175 * path concatenates into the output buffer when fds is empty and the queue is empty; if fds
176 * are present or the queue is non-empty the message is queued instead, so that
177 * fd-to-message boundaries are preserved. The queue item copies the fd values; On success,
178 * ownership of the fd values transfers to the queue item (the caller must free its array
179 * without closing the fds). On failure, the fds remain untouched and the caller retains
180 * ownership. */
181 int json_stream_enqueue_full(JsonStream *s, sd_json_variant *m, const int fds[], size_t n_fds);
182
183 static inline int json_stream_enqueue(JsonStream *s, sd_json_variant *m) {
184 return json_stream_enqueue_full(s, m, NULL, 0);
185 }
186
187 int json_stream_peek_input_fd(const JsonStream *s, size_t i);
188 int json_stream_take_input_fd(JsonStream *s, size_t i);
189 size_t json_stream_get_n_input_fds(const JsonStream *s);
190
191 /* Close and free all currently received input fds (used after consuming a message). */
192 void json_stream_close_input_fds(JsonStream *s);
193
194 /* I/O steps. Same return-value contract as the original varlink_{write,read,parse_message}:
195 * 1 = made progress (call again),
196 * 0 = nothing to do (wait for I/O),
197 * <0 = error. */
198 int json_stream_write(JsonStream *s);
199 int json_stream_read(JsonStream *s);
200
201 /* Extract the next complete JSON message from the input buffer (delimited per
202 * params.delimiter). Returns 1 with *ret set on success, 0 if no full message is
203 * available yet (with *ret == NULL), <0 on parse error. The buffer slot occupied by the
204 * parsed message is erased if input_sensitive was set. */
205 int json_stream_parse(JsonStream *s, sd_json_variant **ret);
206
207 /* Status accessors used by the consumer's state machine. */
208 bool json_stream_has_buffered_input(const JsonStream *s);
209
210 /* Compute the poll events the consumer should wait for. The stream queries the consumer's
211 * phase via the registered get_phase callback. In JSON_STREAM_PHASE_READING the stream asks
212 * for POLLIN (provided the input buffer is empty and the read side is still alive); POLLOUT
213 * is added whenever there's pending output. When connecting we only ask for POLLOUT to
214 * learn when the non-blocking connect() completes. */
215 int json_stream_get_events(const JsonStream *s);
216
217 /* Block on poll() for the configured fds for at most `timeout` µs. Internally updates the
218 * connecting / got_pollhup state based on the seen revents.
219 * 1 = some event was observed (call us again),
220 * 0 = timeout,
221 * <0 = error (negative errno from ppoll_usec). */
222 int json_stream_wait(JsonStream *s, usec_t timeout);
223
224 /* Block until the output buffer is fully drained (or the write side disconnects).
225 * 1 = some bytes were written during the flush,
226 * 0 = nothing to flush,
227 * -ECONNRESET if the write side became disconnected before everything could be sent,
228 * <0 on other I/O errors. */
229 int json_stream_flush(JsonStream *s);
230
231 /* Peer credential helpers. All refuse if the stream uses different input/output fds, since
232 * peer credentials are only meaningful for a bidirectional socket.
233 * • acquire_peer_uid/gid/pid/pidfd() query the kernel on first use, cache the result,
234 * and log failures (using the stream's description). They each return 0 on success
235 * with the value in *ret, or a negative errno on failure (kernel error or invalid
236 * field).
237 * • get_peer_ucred() returns the *already-cached* ucred (set via a prior acquire or via
238 * set_peer_ucred()) without triggering a kernel query — returns -ENODATA if nothing is
239 * cached. Used by consumers that want to react to a previously-known ucred without
240 * forcing a fresh query (e.g. teardown bookkeeping). */
241 int json_stream_acquire_peer_uid(JsonStream *s, uid_t *ret);
242 int json_stream_acquire_peer_gid(JsonStream *s, gid_t *ret);
243 int json_stream_acquire_peer_pid(JsonStream *s, pid_t *ret);
244 int json_stream_acquire_peer_pidfd(JsonStream *s);
245 int json_stream_get_peer_ucred(const JsonStream *s, struct ucred *ret);
246 void json_stream_set_peer_ucred(JsonStream *s, const struct ucred *ucred);
247
248 /* Per-operation idle timeout. The deadline is computed as last_activity + timeout.
249 * Successful writes refresh last_activity automatically; the consumer should also call
250 * json_stream_mark_activity() at operation start (e.g. when initiating a method call) to
251 * reset the deadline.
252 *
253 * When the deadline elapses the time event source attached via json_stream_attach_event()
254 * fires and the consumer's dispatch callback is invoked. The consumer detects the timeout
255 * by comparing now(CLOCK_MONOTONIC) against json_stream_get_timeout(). */
256 void json_stream_set_timeout(JsonStream *s, usec_t timeout);
257 void json_stream_mark_activity(JsonStream *s);
258
259 /* Returns the absolute deadline (in CLOCK_MONOTONIC microseconds) currently in force for
260 * the consumer's phase, or USEC_INFINITY if no timeout applies (no timeout configured, no
261 * activity yet, or the current phase isn't AWAITING_REPLY). */
262 usec_t json_stream_get_timeout(const JsonStream *s);
263
264 /* sd-event integration. JsonStream owns the input/output io event sources and the time
265 * event source for its idle timeout, and installs its own internal prepare and io callbacks
266 * on them. The hooks (get_phase, io_dispatch) supplied via JsonStreamParams at construction
267 * are wired up automatically. */
268 int json_stream_attach_event(JsonStream *s, sd_event *event, int64_t priority);
269 void json_stream_detach_event(JsonStream *s);
270 sd_event* json_stream_get_event(const JsonStream *s);