Phosphor
Qt6 / Wayland library suite for window-management tools
Loading...
Searching...
No Matches
IpcRouter.h
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 fuddlesworth
2// SPDX-License-Identifier: LGPL-2.1-or-later
3#pragma once
4
6#include <PhosphorIpc/phosphoripc_export.h>
7
8#include <QByteArray>
9#include <QHash>
10#include <QJsonArray>
11#include <QJsonObject>
12#include <QJsonValue>
13#include <QList>
14#include <QObject>
15#include <QPointer>
16#include <QSet>
17#include <QString>
18#include <QStringList>
19#include <QVariant>
20#include <QVariantList>
21#include <QtCore/qtclasshelpermacros.h>
22
23#include <memory>
24#include <optional>
25
26QT_BEGIN_NAMESPACE
27class QLocalServer;
28class QLocalSocket;
29QT_END_NAMESPACE
30
31namespace PhosphorIpc {
32
33// Central JSON-over-Unix-socket dispatcher. Owns one QLocalServer and
34// the registry of named callable QObject "targets". Speaks the
35// NDJSON wire protocol defined in IpcProtocol.h. Single-threaded:
36// must be used on the thread that owns it, normally the GUI thread
37// (Qt's QLocalServer + the QMetaObject::invokeMethod path both assume
38// that).
39//
40// Connections
41// - Each accepted client connection gets an id, unique in the process
42// and never reused (also across routers). A target reads the id of
43// the connection that runs its call with IpcCallContext::connectionId().
44// The id belongs to the router that runs the call: a target
45// registered on several routers sends its events through the one
46// that accepted the connection, or sendEvent() finds no connection.
47// - The router also reads, at accept, the process ID of the client
48// that connected (SO_PEERCRED). A target reads it with
49// IpcCallContext::connectionPid().
50// - A call answers when its method returns, unless the method defers
51// its reply (IpcCallContext::deferReply, see IpcPendingReply.h).
52// Replies carry the request id, so a deferred reply may arrive after
53// the replies to later calls on the same connection.
54// - sendEvent() writes an event to one connection. Everything written
55// to a connection (replies, errors, events) arrives in write order.
56// - connectionOpened(id) follows the accept of every connection, and
57// connectionClosed(id) its close. With setMaxConnections, a
58// connection past the cap is closed at accept instead: it gets no
59// id, and connectionRefused() follows.
60// - The router reads one request of a connection at a time. A method
61// that spins a nested event loop holds back every later request of
62// its own connection (calls, subscribes, list) until it returns, so
63// it must not wait there for another request of the same client:
64// defer the reply instead. Other connections are served meanwhile.
65//
66// Lifetime
67// - Application owns one IpcRouter (typically constructed in main()
68// alongside the QQmlApplicationEngine).
69// - Targets register their backing QObjects via registerTarget;
70// unregisterTarget drops them. Target QObjects must outlive their
71// registration (QPointer tracking handles dangling-pointer paths
72// defensively, but the contract is "drop the registration before
73// destroying the QObject").
74// - Subscribers are tracked per-(target, signal-name, socket)
75// tuple. Socket disconnect auto-prunes the subscriber set.
76// - Do not destroy the router from inside a call it runs or a signal
77// it emits (a target method, a connectionClosed slot): it is still
78// on the stack. stop() is fine there. So is deleteLater(), except
79// inside a nested event loop that a target method spins: that loop
80// runs the deletion, while the method's call is still on the stack.
81//
82// Errors
83// - start() returns false on bind failure (path conflict, perms,
84// missing XDG dir). The application logs the reason and
85// continues without IPC; failure is non-fatal.
86// - All wire-level errors are reported back to the client as
87// {"type":"error",...} responses (see IpcProtocol::ErrorCode).
88class PHOSPHORIPC_EXPORT IpcRouter : public QObject
89{
90 Q_OBJECT
91public:
92 explicit IpcRouter(QObject* parent = nullptr);
93 ~IpcRouter() override;
94 Q_DISABLE_COPY_MOVE(IpcRouter)
95
96 // The most deferred calls one connection may have waiting for their
97 // answer (IpcCallContext::deferReply). Each holds router state and
98 // whatever work its target keeps, so a client that pipelines calls to
99 // a deferring method cannot grow them without bound. A call past the
100 // cap fails with CALL_FAILED when its method returns. An answer, or
101 // the close of the connection, makes room.
102 static constexpr int MaxPendingCallsPerConnection = 256;
103
104 // Bind the listening socket. Defaults to
105 // $XDG_RUNTIME_DIR/phosphor.sock when socketPath is empty. The socket
106 // file has mode 0600, and the process umask stays as it is (it is one
107 // for every thread). A stale socket at the path (one that refuses a
108 // connection) is replaced; anything else there makes start() fail.
109 // Returns false on bind failure; safe to retry after stop().
110 bool start(const QString& socketPath = QString());
111
112 // Close the listening socket and every client connection, each of
113 // which then gets its connectionClosed. Idempotent. A target method
114 // may call it: the connection whose call runs is closed too, and the
115 // method's return value goes nowhere. What is still unwritten to a
116 // connection is dropped: stop() is stop(StopMode::Abort).
117 void stop();
118
119 // How stop() ends the client connections.
120 enum class StopMode {
121 // Close each one at once and drop what is still unwritten to it.
122 Abort,
123 // Deliver what was written to each one (replies, errors, events)
124 // first, then close it.
125 Flush,
126 };
127 // The default bound on the delivery of StopMode::Flush.
128 static constexpr int DefaultFlushTimeoutMs = 5000;
129
130 // stop() in `mode`. The router stops listening and forgets every
131 // connection at once, as stop() does: connectionClosed follows for
132 // each, from the event loop, and sendEvent() and pending replies find
133 // them closed. With StopMode::Flush, a connection that still has bytes
134 // to write closes once the client has taken them, or is aborted when
135 // `flushTimeoutMs` pass first (a client that stopped reading). The
136 // output limit bounds what is waiting, and the router reads nothing
137 // more from the connection meanwhile. The delivery goes on from the
138 // event loop and does not need the router: it is fine to destroy the
139 // router right after this call.
140 void stop(StopMode mode, int flushTimeoutMs = DefaultFlushTimeoutMs);
141
142 // The resolved socket path (after XDG fallback). Empty if
143 // start() has not been called or failed.
144 [[nodiscard]] QString socketPath() const;
145
146 // The most client connections open at once. Each holds a descriptor
147 // and router state, so a socket that other processes can reach (one
148 // forwarded to another host, for example) caps them. A connection
149 // accepted while `max` are open is closed at once, before it is read:
150 // it gets no id and no connectionOpened or connectionClosed, and
151 // connectionRefused() follows. Lowering the cap closes no open
152 // connection. 0 (the default) and below: no limit.
153 void setMaxConnections(int max);
154 [[nodiscard]] int maxConnections() const;
155 // The client connections open now: accepted, and not closed yet.
156 [[nodiscard]] int connectionCount() const;
157
158 // Register a target QObject under a name. Returns true if the
159 // registry now binds `name` to `object` (a fresh registration,
160 // OR an idempotent re-register of the same object under the same
161 // name — silent success, no warning). Returns false when the
162 // call is rejected (empty name, null object, or a different
163 // object already owns the name; the latter emits a qWarning).
164 // Marked nodiscard because callers that must pair register with
165 // unregister (e.g. IpcTarget's componentComplete/destructor
166 // pairing) NEED the result to know whether the registration is
167 // theirs to undo.
168 [[nodiscard]] bool registerTarget(const QString& name, QObject* object);
169 // Unregister the entry under `name` only if it currently binds
170 // to `object`. Mismatched calls are silently ignored so a target
171 // whose registration was rejected (duplicate name) cannot
172 // accidentally tear down the legitimate owner's binding on
173 // destruction. Pass nullptr to drop the entry unconditionally
174 // (administrative use, e.g. the shell's shutdown path).
175 // The subscriptions to the target end with it: each subscriber gets
176 // {"type":"error","id":<subscriptionId>,"code":"NO_SUCH_TARGET",...}.
177 void unregisterTarget(const QString& name, QObject* object = nullptr);
178
179 [[nodiscard]] QStringList listTargets() const;
180
181 // Look up the live QObject backing a target. Returns nullptr if
182 // the target is unknown or its backing QObject was destroyed
183 // out from under us (QPointer auto-clears).
184 [[nodiscard]] QObject* target(const QString& name) const;
185
186 // Generate the JSON Schema for one target. Walks the target
187 // QObject's metaobject; see IpcSchemaGenerator.h for the
188 // QMetaType → JSON Schema mapping. For unknown targets, returns
189 // the empty-shaped document `{target: "<name>", functions: [],
190 // signals: []}` (matches `IpcSchemaGenerator::schemaFor(name,
191 // nullptr)`). The wire dispatcher still replies with a
192 // NO_SUCH_TARGET error frame for `schema` requests on unknown
193 // targets; this convenience accessor returns the same shape a
194 // schema-generator caller would see directly.
195 [[nodiscard]] QJsonObject schemaFor(const QString& target) const;
196
197 // Structured outcome of an invoke() call. The wire dispatcher
198 // maps these onto IpcProtocol::ErrorCode strings without
199 // string-matching the human-readable message.
200 enum class InvokeOutcome {
201 Ok,
202 NoSuchTarget,
203 NoSuchFn,
204 ArgCountMismatch,
205 ArgConvertFailed,
206 InvokeFailed,
207 // The method ran and failed through IpcCallContext::sendErrorReply.
208 // The error message is the target's.
209 CallFailed,
210 // The method deferred its reply (IpcCallContext::deferReply). On
211 // a direct invoke() there is no client to answer later: the return
212 // value is dropped and the pending reply holds no call.
213 Deferred,
214 };
215
216 // Synchronously invoke target.fn(args). Returns the function's
217 // return value as a QVariant; on failure returns an invalid
218 // QVariant and populates the optional outcome / message
219 // out-params. Pass nullptr if the caller doesn't need them.
220 // A target that inherits IpcCallContext runs the method as a wire
221 // call, and can fail it with sendErrorReply (CallFailed). The call
222 // comes from no connection: IpcCallContext::connectionId() and
223 // connectionPid() are 0.
224 QVariant invoke(const QString& target, const QString& fn, const QVariantList& args,
225 InvokeOutcome* outcome = nullptr, QString* errorMessage = nullptr);
226
227 // Broadcast a JSON event to every connected subscriber that has
228 // subscribed to (target, signalName). The IpcTarget QML type's
229 // emitEvent() method is the canonical call site, plugin
230 // authors call emitEvent("countChanged", [value]) whenever a
231 // wire-visible state transition happens, which is more explicit
232 // than auto-introspecting QObject signals. Called off the router's
233 // thread it sends nothing (with a warning; debug builds assert).
234 void broadcastEvent(const QString& target, const QString& signalName, const QJsonArray& args);
235
236 // Write one event to the client connection `connectionId`, whether
237 // or not it subscribed to anything:
238 // {"type":"event","target":<target>,"signal":<signalName>,"args":[...]}
239 // The frame names the event in place of a subscriptionId, which it
240 // has none of. It is meant for a call's own output, sent to the
241 // client that made the call: take the id from
242 // IpcCallContext::connectionId() while the call runs. Declare the
243 // event as a signal on the target, as for broadcast events, so the
244 // schema lists it. The schema then also offers the signal for
245 // subscription, and a subscriber gets only what broadcastEvent sends
246 // under that name: a target that wants both kinds of listener calls
247 // both. The event goes out after everything written to the
248 // connection before it, and before what is written after it, such as
249 // the reply of IpcPendingReply::finish().
250 //
251 // Returns true when the event was queued on an open connection. A
252 // client that went away before the router noticed loses it, and
253 // connectionClosed follows. Returns false, and writes nothing, for an
254 // empty target or signal name, for an id that names no open
255 // connection of this router (unknown, or closed already), and when
256 // called off the router's thread (with a warning; debug builds
257 // assert). The same output limit applies as for broadcastEvent: a
258 // connection more than 16 MiB behind is closed (with a warning) and
259 // the call returns false.
260 bool sendEvent(quint64 connectionId, const QString& target, const QString& signalName, const QJsonArray& args);
261 // sendEvent(), which also sets `*lineBytes` (when not null) to the
262 // size of the line it wrote, its '\n' included: the bytes the client
263 // reads for this event, for a target that counts what its client has
264 // taken. 0 when it returns false.
265 bool sendEvent(quint64 connectionId, const QString& target, const QString& signalName, const QJsonArray& args,
266 qint64* lineBytes);
267
268Q_SIGNALS:
269 void targetRegistered(const QString& name);
270 void targetUnregistered(const QString& name);
271 // The router accepted the client connection `connectionId`, the id
272 // that IpcCallContext::connectionId() and connectionClosed() name
273 // later. Sent from the event loop, when the router accepts, before it
274 // reads anything the client sent. sendEvent() to the id works from
275 // the slot on.
276 void connectionOpened(quint64 connectionId);
277 // The router closed a connection at accept because maxConnections()
278 // were open. Sent once per refused connection, from the event loop.
280 // The client connection `connectionId` has closed: the client went
281 // away, the router closed it (malformed input, output limit) or
282 // stop() ran. Sent once per connection, from the event loop and
283 // never synchronously from inside a call into the router (such as
284 // sendEvent or stop), so a slot may end the connection's work and
285 // destroy its pending replies right there. A target method that
286 // spins a nested event loop can get it inside that loop, as it can
287 // any queued signal. By then sendEvent() to the id returns false and
288 // pending replies for it drop their answer.
289 //
290 // The router's destructor sends it, for the connections it closes,
291 // before it returns. A receiver that holds the router as a member and
292 // connects this to its own slot is then partly destroyed: members
293 // declared after the router are gone. Declare the router after the
294 // state the slot uses, or disconnect before the router goes.
295 void connectionClosed(quint64 connectionId);
296
297private:
298 friend class IpcCallContext;
299 friend class IpcPendingReply;
300
301 // A deferred call waiting for its answer: where the answer goes.
302 struct PendingCall
303 {
304 quint64 connectionId = 0;
305 qint64 requestId = 0;
306 };
307
308 // An open connection: its id, and the process ID of the client that
309 // connected (0 where the router could not read it).
310 struct Connection
311 {
312 quint64 id = 0;
313 qint64 pid = 0;
314 };
315
316 // invoke() for a call from `connection` (an id of 0: none) with
317 // request id `requestId`, as the wire dispatcher makes it.
318 QVariant invokeCall(const QString& target, const QString& fn, const QVariantList& args,
319 const Connection& connection, qint64 requestId, InvokeOutcome* outcome, QString* errorMessage);
320 // Registers the running call's pending reply. Called by
321 // IpcCallContext::deferReply for a call from a connection. Past
322 // MaxPendingCallsPerConnection it fails the call instead and returns a
323 // pending reply that holds no call.
324 IpcPendingReply deferCall(IpcCallContext::Call& call);
325 // Answer a pending call once: the first answer takes the call out of
326 // m_pendingCalls, and later ones find nothing. True when the answer
327 // was queued on an open connection.
328 bool finishPendingCall(quint64 token, const QJsonValue& result);
329 bool failPendingCall(quint64 token, const QString& code, const QString& message);
330 // Takes the pending call `token` out of the books, or nothing when no
331 // call waits under it.
332 std::optional<PendingCall> takePendingCall(quint64 token);
333 // The open connection with this id, or nullptr.
334 [[nodiscard]] QLocalSocket* connectedSocket(quint64 connectionId) const;
335 // Book a closed connection for connectionClosed, which the event loop
336 // (or the destructor) sends in announceClosedConnections.
337 void connectionGone(quint64 connectionId);
338 void announceClosedConnections();
339
340 // Internal subscription record: (subscriptionId, target,
341 // signalName), kept per socket in m_subscriptionsBySocket. Events
342 // arrive via broadcastEvent() rather than auto-introspected Qt
343 // signal connections (which clashed with Q_OBJECT moc-generated
344 // qt_metacall, see the explicit-broadcast rationale in
345 // IpcTarget::emitEvent).
346 struct Subscription
347 {
348 qint64 subscriptionId = 0;
349 QString target;
350 QString signalName;
351 };
352
353 void handleNewConnection();
354 // Runs readFrames for `socket`, unless a dispatch on it is on the
355 // stack already (a target method spinning a nested event loop), and
356 // deletes the socket afterwards when it closed meanwhile.
357 void handleClientReadyRead(QLocalSocket* socket);
358 void readFrames(QLocalSocket* socket);
359 void handleClientDisconnected(QLocalSocket* socket);
360 // Deletes a closed socket from the event loop, once no dispatch on
361 // it is on the stack.
362 void retireSocket(QLocalSocket* socket);
363 // stop(StopMode::Flush) for one open socket, whose router handlers
364 // are gone: closes it once its write buffer has drained, or aborts it
365 // after `flushTimeoutMs`, and then deletes it.
366 void flushAndClose(QLocalSocket* socket, int flushTimeoutMs);
367 // Ends every subscription to the target `name`: each subscriber gets
368 // a NO_SUCH_TARGET error under its subscription id.
369 void endSubscriptionsTo(const QString& name);
370 void dispatch(QLocalSocket* socket, const QByteArray& line);
371 void handleSubscribe(QLocalSocket* socket, qint64 id, const QString& targetName, const QString& signalName);
372 void handleUnsubscribe(QLocalSocket* socket, qint64 id, qint64 subscriptionId);
373 // Emit a MALFORMED_REQUEST diagnostic to `socket`, give the
374 // bytes a brief window to land in the kernel send buffer, then
375 // abort() the connection. Shared by the read-side oversize-line
376 // and malformed-frame-cap paths so they stay in lockstep if the
377 // close protocol ever changes (e.g. switching from abort() to
378 // disconnectFromServer()).
379 void closeWithMalformedDiagnostic(QLocalSocket* socket, const QString& message);
380
381 std::unique_ptr<QLocalServer> m_server;
382 QString m_socketPath;
383 // The socket file that start() made, and its identity, so that stop()
384 // removes that file and not one that took the path since.
385 QByteArray m_socketFile;
386 quint64 m_socketDevice = 0;
387 quint64 m_socketInode = 0;
388 QHash<QString, QPointer<QObject>> m_targets;
389 // Per-socket subscription list; lets disconnect cleanup walk one
390 // socket's subscriptions without scanning the whole router.
391 QHash<QLocalSocket*, QList<Subscription>> m_subscriptionsBySocket;
392 // Per-socket consecutive malformed-frame counter. Reset to zero
393 // on a successfully-parsed frame; closes the connection when the
394 // count exceeds detail::MaxConsecutiveMalformedFrames so a peer can't
395 // pin the router on parse failures indefinitely.
396 QHash<QLocalSocket*, int> m_malformedCountBySocket;
397 // The id of every open connection, both ways, and the process that
398 // connected. An entry goes when the connection closes, so a lookup by
399 // id finds only open connections.
400 QHash<QLocalSocket*, Connection> m_connectionBySocket;
401 QHash<quint64, QPointer<QLocalSocket>> m_socketByConnectionId;
402 // setMaxConnections; 0: no limit.
403 int m_maxConnections = 0;
404 // Deferred calls that wait for their answer, by pending-reply token,
405 // and the tokens of each connection's calls. A connection's entries go
406 // when it closes.
407 QHash<quint64, PendingCall> m_pendingCalls;
408 QHash<quint64, QSet<quint64>> m_pendingTokensByConnection;
409 quint64 m_lastPendingToken = 0;
410 // Sockets with a dispatch on the stack, and those of them that closed
411 // meanwhile and are deleted when it unwinds. Deleting one earlier
412 // frees it under the dispatch (and under Qt's readyRead emission).
413 QSet<QLocalSocket*> m_socketsInDispatch;
414 QSet<QLocalSocket*> m_socketsToDelete;
415 // Closed connections that connectionClosed has not been sent for yet.
416 QList<quint64> m_closedConnections;
417};
418
419} // namespace PhosphorIpc
void connectionOpened(quint64 connectionId)
QStringList listTargets() const
void connectionClosed(quint64 connectionId)
bool registerTarget(const QString &name, QObject *object)
QObject * target(const QString &name) const
void setMaxConnections(int max)
static constexpr int DefaultFlushTimeoutMs
Definition IpcRouter.h:128
bool sendEvent(quint64 connectionId, const QString &target, const QString &signalName, const QJsonArray &args)
static constexpr int MaxPendingCallsPerConnection
Definition IpcRouter.h:102
void targetUnregistered(const QString &name)
StopMode
Definition IpcRouter.h:120
InvokeOutcome
Definition IpcRouter.h:200
friend class IpcPendingReply
Definition IpcRouter.h:299
void targetRegistered(const QString &name)
void broadcastEvent(const QString &target, const QString &signalName, const QJsonArray &args)
int connectionCount() const
bool sendEvent(quint64 connectionId, const QString &target, const QString &signalName, const QJsonArray &args, qint64 *lineBytes)
QVariant invoke(const QString &target, const QString &fn, const QVariantList &args, InvokeOutcome *outcome=nullptr, QString *errorMessage=nullptr)
void unregisterTarget(const QString &name, QObject *object=nullptr)
QString socketPath() const
int maxConnections() const
IpcRouter(QObject *parent=nullptr)
bool start(const QString &socketPath=QString())
void stop(StopMode mode, int flushTimeoutMs=DefaultFlushTimeoutMs)
QJsonObject schemaFor(const QString &target) const
friend class IpcCallContext
Definition IpcRouter.h:298
Definition IpcCallContext.h:10