1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2019 - 2020 Andy Green <andy@warmcat.com>
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to
8  * deal in the Software without restriction, including without limitation the
9  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10  * sell copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22  * IN THE SOFTWARE.
23  *
24  * included from libwebsockets.h
25  *
26  *
27  * Secure Streams is a *payload-only* client communication channel where all the
28  * details about the connection are held in a systemwide policy database and
29  * are keyed by the streamtype field... the user of the communication channel
30  * does not know or manage the choice of endpoint, tls CA, or even wire
31  * protocol.  The advantage is he then does not have any dependency on any of
32  * those and they can be changed just by changing the policy database without
33  * touching the code using the stream.
34  *
35  * There are two ways secure streams interfaces to user code:
36  *
37  * 1) [Linux / RTOS] the natural, smallest interface is to call back to user
38  *    code that only operates directly from the lws event loop thread context
39  *    (direct callbacks from lws_ss_t)
40  *
41  *    lws_thread( [user code] ---- lws )
42  *
43  * 2) [Linux] where the user code is in a different process and communicates
44  *    asynchronously via a proxy socket
45  *
46  *    user_process{ [user code] | shim | socket-}------ lws_process{ lws }
47  *
48  * In the second, IPC, case, all packets are prepended by one or more bytes
49  * indicating the packet type and serializing any associated data, known as
50  * Serialized Secure Streams or SSS.
51  *
52  * Serialized Secure Streams
53  * -------------------------
54  *
55  * On the transport, adjacent packets may be coalesced, that is, the original
56  * packet sizes are lost and two or more packets are combined.  For that reason
57  * the serialization format always contains a 1-byte type and then a 2-byte
58  * frame length.
59  *
60  * Client to proxy
61  *
62  * - Proxied connection setup
63  *
64  *   -  0: LWSSS_SER_TXPRE_STREAMTYPE
65  *   -  1: 2-byte MSB-first rest-of-frame length
66  *   -  3: 1-byte Client SSS protocol version (introduced in SSSv1)
67  *   -  4: 4-byte Client PID (introduced in SSSv1)
68  *   -  8: 4-byte MSB-first initial tx credit
69  *   - 12: the streamtype name with no NUL
70  *
71  * - Proxied tx
72  *
73  *   -  0: LWSSS_SER_TXPRE_TX_PAYLOAD
74  *   -  1: 2 byte MSB-first rest-of-frame length
75  *   -  3: 4-byte MSB-first flags
76  *   -  7: 4-byte MSB-first us between client requested write and wrote to proxy
77  *   - 11: 8-byte MSB-first us resolution unix time client wrote to proxy
78  *   - 19: payload
79  *
80  * - Proxied secure stream destroy
81  *
82  *   -  0: LWSSS_SER_TXPRE_DESTROYING
83  *   -  1: 00, 00
84  *
85  * - Proxied metadata - sent when one metadata item set clientside
86  *
87  *   -  0: LWSSS_SER_TXPRE_METADATA
88  *   -  1: 2-byte MSB-first rest-of-frame length
89  *   -  3: 1-byte metadata name length
90  *   -  4: metadata name
91  *   -  ...: metadata value (for rest of packet)
92  *
93  * - TX credit management - sent when using tx credit apis, cf METADATA
94  *
95  *   - 0: LWSSS_SER_TXPRE_TXCR_UPDATE
96  *   - 1: 2-byte MSB-first rest-of-frame length 00, 04
97  *   - 3: 4-byte additional tx credit adjust value
98  *
99  * - Stream timeout management - forwarded when user applying or cancelling t.o.
100  *
101  *   -  0: LWSSS_SER_TXPRE_TIMEOUT_UPDATE
102  *   -  1: 2-byte MSB-first rest-of-frame length 00, 04
103  *   -  3: 4-byte MSB-first unsigned 32-bit timeout, 0 = use policy, -1 = cancel
104  *
105  * - Passing up payload length hint
106  *
107  *   -  0: LWSSS_SER_TXPRE_PAYLOAD_LENGTH_HINT
108  *   -  1: 2-byte MSB-first rest-of-frame length 00, 04
109  *   -  3: 4-byte MSB-first unsigned 32-bit payload length hint
110  *
111  * Proxy to client
112  *
113  * - Proxied connection setup result
114  *
115  *   -  0: LWSSS_SER_RXPRE_CREATE_RESULT
116  *   -  1: 2 byte MSB-first rest-of-frame length (usually 00, 03)
117  *   -  3: 1 byte result, 0 = success.  On failure, proxy will close connection.
118  *   -  4: 4 byte client dsh allocation recommended for stream type, from policy
119  *         (introduced in SSSv1)
120  *   -  8: 2 byte MSB-first initial tx credit
121  *   - 10: if present, comma-sep list of rideshare types from policy
122  *
123  * - Proxied rx
124  *
125  *   -  0: LWSSS_SER_RXPRE_RX_PAYLOAD
126  *   -  1: 2 byte MSB-first rest-of-frame length
127  *   -  3: 4-byte MSB-first flags
128  *   -  7: 4-byte MSB-first us between inbound read and wrote to client
129  *   - 11: 8-byte MSB-first us resolution unix time proxy wrote to client
130  *   - 17: (rideshare name len + rideshare name if flags & LWSSS_FLAG_RIDESHARE)
131  *          payload
132  *
133  * - Proxied tx credit
134  *
135  *   -  0: LWSSS_SER_RXPRE_TXCR_UPDATE
136  *   -  1: 00, 04
137  *   -  3: 4-byte MSB-first addition tx credit bytes
138  *
139  * - Proxied rx metadata
140  *
141  *   -  0: LWSSS_SER_RXPRE_METADATA
142  *   -  1: 2-byte MSB-first rest-of-frame length
143  *   -  3: 1-byte metadata name length
144  *   -  4: metadata name
145  *   -  ...: metadata value (for rest of packet)
146  *
147  * - Proxied state (8 or 11 byte packet)
148  *
149  *   -  0: LWSSS_SER_RXPRE_CONNSTATE
150  *   -  1: 00, 05 if state < 256, else 00, 08
151  *   -  3: 1 byte state index if state < 256, else 4-byte MSB-first state index
152  *   -  4 or 7: 4-byte MSB-first ordinal
153  *
154  * - Proxied performance information
155  *
156  *   -  0: LWSSS_SER_RXPRE_PERF
157  *   -  1: 2-byte MSB-first rest-of-frame length
158  *   -  3: ... performance JSON (for rest of packet)
159  *
160  * Proxied tx may be read by the proxy but rejected due to lack of buffer space
161  * at the proxy.  For that reason, tx must be held at the sender until it has
162  * been acknowledged or denied.
163  *
164  * Sinks
165  * -----
166  *
167  * Sinks are logical "servers", you can register as a sink for a particular
168  * streamtype by using the lws_ss_create() api with ssi->register_sink set to 1.
169  *
170  * For directly fulfilled Secure Streams, new streams of that streamtype bind
171  * to the rx, tx and state handlers given when it was registered.
172  *
173  *  - When new streams are created the registered sink handler for (*state) is
174  *    called with event LWSSSCS_SINK_JOIN and the new client stream handle in
175  *    the h_src parameter.
176  *
177  *  - When the client stream sends something to the sink, it calls the sink's
178  *    (*rx) with the client stream's
179  */
180 
181 /** \defgroup secstr Secure Streams
182 * ##Secure Streams
183 *
184 * Secure Streams related apis
185 */
186 ///@{
187 
188 #define LWS_SS_MTU 1540
189 
190 struct lws_ss_handle;
191 typedef uint32_t lws_ss_tx_ordinal_t;
192 
193 /*
194  * connection state events
195  *
196  * If you add states, take care about the state names and state transition
197  * validity enforcement tables too
198  */
199 typedef enum {
200 	/* zero means unset */
201 	LWSSSCS_CREATING		= 1,
202 	LWSSSCS_DISCONNECTED,
203 	LWSSSCS_UNREACHABLE,		/* oridinal arg = 1 = caused by dns
204 					 * server reachability failure */
205 	LWSSSCS_AUTH_FAILED,
206 	LWSSSCS_CONNECTED,
207 	LWSSSCS_CONNECTING,
208 	LWSSSCS_DESTROYING,
209 	LWSSSCS_POLL,
210 	LWSSSCS_ALL_RETRIES_FAILED,	/* all retries in bo policy failed */
211 	LWSSSCS_QOS_ACK_REMOTE,		/* remote peer received and acked tx */
212 	LWSSSCS_QOS_NACK_REMOTE,
213 	LWSSSCS_QOS_ACK_LOCAL,		/* local proxy accepted our tx */
214 	LWSSSCS_QOS_NACK_LOCAL,		/* local proxy refused our tx */
215 	LWSSSCS_TIMEOUT,		/* optional timeout timer fired */
216 
217 	LWSSSCS_SERVER_TXN,
218 	LWSSSCS_SERVER_UPGRADE,		/* the server protocol upgraded */
219 
220 	LWSSSCS_SINK_JOIN,		/* sinks get this when a new source
221 					 * stream joins the sink */
222 	LWSSSCS_SINK_PART,		/* sinks get this when a new source
223 					 * stream leaves the sink */
224 
225 	LWSSSCS_USER_BASE = 1000
226 } lws_ss_constate_t;
227 
228 enum {
229 	LWSSS_FLAG_SOM						= (1 << 0),
230 	/* payload contains the start of new message */
231 	LWSSS_FLAG_EOM						= (1 << 1),
232 	/* payload contains the end of message */
233 	LWSSS_FLAG_POLL						= (1 << 2),
234 	/* Not a real transmit... poll for rx if protocol needs it */
235 	LWSSS_FLAG_RELATED_START				= (1 << 3),
236 	/* Appears in a zero-length message indicating a message group of zero
237 	 * or more messages is now starting. */
238 	LWSSS_FLAG_RELATED_END					= (1 << 4),
239 	/* Appears in a zero-length message indicating a message group of zero
240 	 * or more messages has now finished. */
241 	LWSSS_FLAG_RIDESHARE					= (1 << 5),
242 	/* Serialized payload starts with non-default rideshare name length and
243 	 * name string without NUL, then payload */
244 	LWSSS_FLAG_PERF_JSON					= (1 << 6),
245 	/* This RX is JSON performance data, only on streams with "perf" flag
246 	 * set */
247 
248 	/*
249 	 * In the case the secure stream is proxied across a process or thread
250 	 * boundary, eg by proxying through a socket for IPC, metadata must be
251 	 * carried in-band.  A byte is prepended to each rx payload to
252 	 * differentiate what it is.
253 	 *
254 	 * Secure streams where the user is called back directly does not need
255 	 * any of this and only pure payloads are passed.
256 	 *
257 	 * rx (received by client) prepends for proxied connections
258 	 */
259 
260 	LWSSS_SER_RXPRE_RX_PAYLOAD				= 0x55,
261 	LWSSS_SER_RXPRE_CREATE_RESULT,
262 	LWSSS_SER_RXPRE_CONNSTATE,
263 	LWSSS_SER_RXPRE_TXCR_UPDATE,
264 	LWSSS_SER_RXPRE_METADATA,
265 	LWSSS_SER_RXPRE_TLSNEG_ENCLAVE_SIGN,
266 	LWSSS_SER_RXPRE_PERF,
267 
268 	/* tx (send by client) prepends for proxied connections */
269 
270 	LWSSS_SER_TXPRE_STREAMTYPE				= 0xaa,
271 	LWSSS_SER_TXPRE_ONWARD_CONNECT,
272 	LWSSS_SER_TXPRE_DESTROYING,
273 	LWSSS_SER_TXPRE_TX_PAYLOAD,
274 	LWSSS_SER_TXPRE_METADATA,
275 	LWSSS_SER_TXPRE_TXCR_UPDATE,
276 	LWSSS_SER_TXPRE_TIMEOUT_UPDATE,
277 	LWSSS_SER_TXPRE_PAYLOAD_LENGTH_HINT,
278 	LWSSS_SER_TXPRE_TLSNEG_ENCLAVE_SIGNED,
279 };
280 
281 typedef enum {
282 	LPCSPROX_WAIT_INITIAL_TX = 1, /* after connect, must send streamtype */
283 	LPCSPROX_REPORTING_FAIL, /* stream creation failed, wait to to tell */
284 	LPCSPROX_REPORTING_OK, /* stream creation succeeded, wait to to tell */
285 	LPCSPROX_OPERATIONAL, /* ready for payloads */
286 	LPCSPROX_DESTROYED,
287 
288 	LPCSCLI_SENDING_INITIAL_TX,  /* after connect, must send streamtype */
289 	LPCSCLI_WAITING_CREATE_RESULT,   /* wait to hear if proxy ss create OK */
290 	LPCSCLI_LOCAL_CONNECTED,	      /* we are in touch with the proxy */
291 	LPCSCLI_ONWARD_CONNECT,	      /* request onward ss connection */
292 	LPCSCLI_OPERATIONAL, /* ready for payloads */
293 
294 } lws_ss_conn_states_t;
295 
296 /*
297  * Returns from state() callback can tell the caller what the user code
298  * wants to do
299  */
300 
301 typedef enum lws_ss_state_return {
302 	LWSSSSRET_TX_DONT_SEND		=  1, /* (*tx) only, or failure */
303 
304 	LWSSSSRET_OK			=  0, /* no error */
305 	LWSSSSRET_DISCONNECT_ME		= -1, /* caller should disconnect us */
306 	LWSSSSRET_DESTROY_ME		= -2, /* caller should destroy us */
307 } lws_ss_state_return_t;
308 
309 /**
310  * lws_ss_info_t: information about stream to be created
311  *
312  * Prepare this struct with information about what the stream type is and how
313  * the stream should interface with your code, and pass it to lws_ss_create()
314  * to create the requested stream.
315  */
316 
317 enum {
318 	LWSSSINFLAGS_REGISTER_SINK			=	(1 << 0),
319 	/**< If set, we're not creating a specific stream, but registering
320 	 * ourselves as the "sink" for .streamtype.  It's analogous to saying
321 	 * we want to be the many-to-one "server" for .streamtype; when other
322 	 * streams are created with that streamtype, they should be forwarded
323 	 * to this stream owner, where they join and part from the sink via
324 	 * (*state) LWSSSCS_SINK_JOIN / _PART events, the new client handle
325 	 * being provided in the h_src parameter.
326 	 */
327 	LWSSSINFLAGS_PROXIED				=	(1 << 1),
328 	/**< Set if the stream is being created as a stand-in at the proxy */
329 	LWSSSINFLAGS_SERVER				=	(1 << 2),
330 	/**< Set on the server object copy of the ssi / info to indicate that
331 	 * stream creation using this ssi is for Accepted connections belonging
332 	 * to a server */
333 	LWSSSINFLAGS_ACCEPTED				=	(1 << 3),
334 	/**< Set on the accepted object copy of the ssi / info to indicate that
335 	 * we are an accepted connection from a server's listening socket */
336 };
337 
338 typedef lws_ss_state_return_t (*lws_sscb_rx)(void *userobj, const uint8_t *buf,
339 					     size_t len, int flags);
340 typedef lws_ss_state_return_t (*lws_sscb_tx)(void *userobj,
341 					     lws_ss_tx_ordinal_t ord,
342 					     uint8_t *buf, size_t *len,
343 					     int *flags);
344 typedef lws_ss_state_return_t (*lws_sscb_state)(void *userobj, void *h_src,
345 						lws_ss_constate_t state,
346 						lws_ss_tx_ordinal_t ack);
347 
348 struct lws_ss_policy;
349 
350 typedef struct lws_ss_info {
351 	const char *streamtype; /**< type of stream we want to create */
352 	size_t	    user_alloc; /**< size of user allocation */
353 	size_t	    handle_offset; /**< offset of handle stg in user_alloc type,
354 				    set to offsetof(mytype, my_handle_member) */
355 	size_t	    opaque_user_data_offset;
356 	/**< offset of opaque user data ptr in user_alloc type, set to
357 	     offsetof(mytype, opaque_ud_member) */
358 
359 #if defined(LWS_WITH_SECURE_STREAMS_CPP)
360 	const struct lws_ss_policy	*policy;
361 	/**< Normally NULL, or a locally-generated policy to apply to this
362 	 * connection instead of a named streamtype */
363 #endif
364 
365 #if defined(LWS_WITH_SYS_FAULT_INJECTION)
366 	lws_fi_ctx_t				fic;
367 	/**< Attach external Fault Injection context to the stream, hierarchy
368 	 * is ss->context */
369 #endif
370 
371 	lws_sscb_rx rx;
372 	/**< callback with rx payload for this stream */
373 	lws_sscb_tx tx;
374 	/**< callback to send payload on this stream... 0 = send as set in
375 	 * len and flags, 1 = do not send anything (ie, not even 0 len frame) */
376 	lws_sscb_state state;
377 	/**< advisory cb about state of stream and QoS status if applicable...
378 	 * h_src is only used with sinks and LWSSSCS_SINK_JOIN/_PART events.
379 	 * Return nonzero to indicate you want to destroy the stream. */
380 	int	    manual_initial_tx_credit;
381 	/**< 0 = manage any tx credit automatically, nonzero explicitly sets the
382 	 * peer stream to have the given amount of tx credit, if the protocol
383 	 * can support it.
384 	 *
385 	 * In the special case of _lws_smd streamtype, this is used to indicate
386 	 * the connection's rx class mask.
387 	 * */
388 	uint32_t	client_pid;
389 	/**< used in proxy / serialization case to hold the client pid this
390 	 * proxied connection is to be tagged with
391 	 */
392 	uint8_t		flags;
393 	uint8_t		sss_protocol_version;
394 	/**< used in proxy / serialization case to hold the SS serialization
395 	 * protocol level to use with this peer... clients automatically request
396 	 * the most recent version they were built with
397 	 * (LWS_SSS_CLIENT_PROTOCOL_VERSION) and the proxy stores the requested
398 	 * version in here
399 	 */
400 
401 } lws_ss_info_t;
402 
403 /**
404  * lws_ss_create() - Create secure stream
405  *
406  * \param context: the lws context to create this inside
407  * \param tsi: service thread index to create on (normally 0)
408  * \param ssi: pointer to lws_ss_info_t filled in with info about desired stream
409  * \param opaque_user_data: opaque data to set in the stream's user object
410  * \param ppss: pointer to secure stream handle pointer set on exit
411  * \param ppayload_fmt: NULL or pointer to a string ptr to take payload format
412  *			name from the policy
413  *
414  * Requests a new secure stream described by \p ssi be created.  If successful,
415  * the stream is created, its state callback called with LWSSSCS_CREATING, \p *ppss
416  * is set to point to the handle, and it returns 0.  If it failed, it returns
417  * nonzero.
418  *
419  * Along with the opaque stream object, streams overallocate
420  *
421  * 1) a user data struct whose size is set in ssi
422  * 2) nauth plugin instantiation data (size set in the plugin struct)
423  * 3) sauth plugin instantiation data (size set in the plugin struct)
424  * 4) space for a copy of the stream type name
425  *
426  * The user data struct is initialized to all zeros, then the .handle_offset and
427  * .opaque_user_data_offset fields of the ssi are used to prepare the user data
428  * struct with the ss handle that was created, and a copy of the
429  * opaque_user_data pointer given as an argument.
430  *
431  * If you want to set up the stream with specific information, point to it in
432  * opaque_user_data and use the copy of that pointer in your user data member
433  * for it starting from the LWSSSCS_CREATING state call.
434  *
435  * Since different endpoints chosen by the policy may require different payload
436  * formats, \p ppayload_fmt is set to point to the name of the needed payload
437  * format from the policy database if non-NULL.
438  */
439 LWS_VISIBLE LWS_EXTERN int
440 lws_ss_create(struct lws_context *context, int tsi, const lws_ss_info_t *ssi,
441 	      void *opaque_user_data, struct lws_ss_handle **ppss,
442 	      struct lws_sequencer *seq_owner, const char **ppayload_fmt);
443 
444 /**
445  * lws_ss_destroy() - Destroy secure stream
446  *
447  * \param ppss: pointer to lws_ss_t pointer to be destroyed
448  *
449  * Destroys the lws_ss_t pointed to by \p *ppss, and sets \p *ppss to NULL.
450  */
451 LWS_VISIBLE LWS_EXTERN void
452 lws_ss_destroy(struct lws_ss_handle **ppss);
453 
454 /**
455  * lws_ss_request_tx() - Schedule stream for tx
456  *
457  * \param pss: pointer to lws_ss_t representing stream that wants to transmit
458  *
459  * Schedules a write on the stream represented by \p pss.  When it's possible to
460  * write on this stream, the \p *tx callback will occur with an empty buffer for
461  * the stream owner to fill in.
462  *
463  * Returns 0 or LWSSSSRET_SS_HANDLE_DESTROYED
464  */
465 LWS_VISIBLE LWS_EXTERN lws_ss_state_return_t
466 lws_ss_request_tx(struct lws_ss_handle *pss);
467 
468 /**
469  * lws_ss_request_tx() - Schedule stream for tx
470  *
471  * \param pss: pointer to lws_ss_t representing stream that wants to transmit
472  * \param len: the length of the write in bytes
473  *
474  * Schedules a write on the stream represented by \p pss.  When it's possible to
475  * write on this stream, the \p *tx callback will occur with an empty buffer for
476  * the stream owner to fill in.
477  *
478  * This api variant should be used when it's possible the payload will go out
479  * over h1 with x-web-form-urlencoded or similar Content-Type.
480  */
481 LWS_VISIBLE LWS_EXTERN lws_ss_state_return_t
482 lws_ss_request_tx_len(struct lws_ss_handle *pss, unsigned long len);
483 
484 /**
485  * lws_ss_client_connect() - Attempt the client connect
486  *
487  * \param h: secure streams handle
488  *
489  * Starts the connection process for the secure stream.
490  *
491  * Can return any of the lws_ss_state_return_t values depending on user
492  * state callback returns.
493  *
494  * LWSSSSRET_OK means the connection is ongoing.
495  *
496  */
497 LWS_VISIBLE LWS_EXTERN lws_ss_state_return_t
498 lws_ss_client_connect(struct lws_ss_handle *h);
499 
500 /**
501  * lws_ss_get_sequencer() - Return parent sequencer pointer if any
502  *
503  * \param h: secure streams handle
504  *
505  * Returns NULL if the secure stream is not associated with a sequencer.
506  * Otherwise returns a pointer to the owning sequencer.  You can use this to
507  * identify which sequencer to direct messages to, from the secure stream
508  * callback.
509  */
510 LWS_VISIBLE LWS_EXTERN struct lws_sequencer *
511 lws_ss_get_sequencer(struct lws_ss_handle *h);
512 
513 /**
514  * lws_ss_proxy_create() - Start a unix domain socket proxy for Secure Streams
515  *
516  * \param context: lws_context
517  * \param bind: if port is 0, unix domain path with leading @ for abstract.
518  *		if port nonzero, NULL, or network interface to bind listen to
519  * \param port: tcp port to listen on
520  *
521  * Creates a vhost that listens either on an abstract namespace unix domain
522  * socket (port = 0) or a tcp listen socket (port nonzero).  If bind is NULL
523  * and port is 0, the abstract unix domain socket defaults to "proxy.ss.lws".
524  *
525  * Client connections to this proxy to Secure Streams are fulfilled using the
526  * policy local to the proxy and the data passed between the client and the
527  * proxy using serialized Secure Streams protocol.
528  */
529 LWS_VISIBLE LWS_EXTERN int
530 lws_ss_proxy_create(struct lws_context *context, const char *bind, int port);
531 
532 /**
533  * lws_ss_state_name() - convenience helper to get a printable conn state name
534  *
535  * \param state: the connection state index
536  *
537  * Returns a printable name for the connection state index passed in.
538  */
539 LWS_VISIBLE LWS_EXTERN const char *
540 lws_ss_state_name(int state);
541 
542 /**
543  * lws_ss_get_context() - convenience helper to recover the lws context
544  *
545  * \param h: secure streams handle
546  *
547  * Returns the lws context.  Dispenses with the need to pass a copy of it into
548  * your secure streams handler.
549  */
550 LWS_VISIBLE LWS_EXTERN struct lws_context *
551 lws_ss_get_context(struct lws_ss_handle *h);
552 
553 #define LWSSS_TIMEOUT_FROM_POLICY				0
554 
555 /**
556  * lws_ss_start_timeout() - start or restart the timeout on the stream
557  *
558  * \param h: secure streams handle
559  * \param timeout_ms: LWSSS_TIMEOUT_FROM_POLICY for policy value, else use timeout_ms
560  *
561  * Starts or restarts the stream's own timeout timer.  If the specified time
562  * passes without lws_ss_cancel_timeout() being called on the stream, then the
563  * stream state callback receives LWSSSCS_TIMEOUT
564  *
565  * The process being protected by the timeout is up to the user code, it may be
566  * arbitrarily long and cross multiple protocol transactions or involve other
567  * streams.  It's up to the user to decide when to start and when / if to cancel
568  * the stream timeout.
569  */
570 LWS_VISIBLE LWS_EXTERN void
571 lws_ss_start_timeout(struct lws_ss_handle *h, unsigned int timeout_ms);
572 
573 /**
574  * lws_ss_cancel_timeout() - remove any timeout on the stream
575  *
576  * \param h: secure streams handle
577  *
578  * Disable any timeout that was applied to the stream by lws_ss_start_timeout().
579  */
580 LWS_VISIBLE LWS_EXTERN void
581 lws_ss_cancel_timeout(struct lws_ss_handle *h);
582 
583 /**
584  * lws_ss_to_user_object() - convenience helper to get user object from handle
585  *
586  * \param h: secure streams handle
587  *
588  * Returns the user allocation related to the handle.  Normally you won't need
589  * this since it's available in the rx, tx and state callbacks as "userdata"
590  * already.
591  */
592 LWS_VISIBLE LWS_EXTERN void *
593 lws_ss_to_user_object(struct lws_ss_handle *h);
594 
595 /**
596  * lws_ss_rideshare() - find the current streamtype when types rideshare
597  *
598  * \param h: the stream handle
599  *
600  * Under some conditions, the payloads may be structured using protocol-
601  * specific formatting, eg, http multipart mime.  It's possible to map the
602  * logical partitions in the payload to different stream types using
603  * the policy "rideshare" feature.
604  *
605  * This api lets the callback code find out which rideshare stream type the
606  * current payload chunk belongs to.
607  */
608 LWS_VISIBLE LWS_EXTERN const char *
609 lws_ss_rideshare(struct lws_ss_handle *h);
610 
611 
612 /**
613  * lws_ss_set_metadata() - allow user to bind external data to defined ss metadata
614  *
615  * \param h: secure streams handle
616  * \param name: metadata name from the policy
617  * \param value: pointer to user-managed data to bind to name
618  * \param len: length of the user-managed data in value
619  *
620  * Binds user-managed data to the named metadata item from the ss policy.
621  * If present, the metadata item is handled in a protocol-specific way using
622  * the associated policy information.  For example, in the policy
623  *
624  *  	"\"metadata\":"		"["
625  *		"{\"uptag\":"  "\"X-Upload-Tag:\"},"
626  *		"{\"ctype\":"  "\"Content-Type:\"},"
627  *		"{\"xctype\":" "\"\"}"
628  *	"],"
629  *
630  * when the policy is using h1 is interpreted to add h1 headers of the given
631  * name with the value of the metadata on the left.
632  *
633  * Return 0 if OK or nonzero if, eg, metadata name does not exist on the
634  * streamtype.  You must check the result of this, eg, transient OOM can cause
635  * these to fail and you should retry later.
636  */
637 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
638 lws_ss_set_metadata(struct lws_ss_handle *h, const char *name,
639 		    const void *value, size_t len);
640 
641 /**
642  * lws_ss_alloc_set_metadata() - copy data and bind to ss metadata
643  *
644  * \param h: secure streams handle
645  * \param name: metadata name from the policy
646  * \param value: pointer to user-managed data to bind to name
647  * \param len: length of the user-managed data in value
648  *
649  * Same as lws_ss_set_metadata(), but allocates a heap buffer for the data
650  * first and takes a copy of it, so the original can go out of scope
651  * immediately after.
652  */
653 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
654 lws_ss_alloc_set_metadata(struct lws_ss_handle *h, const char *name,
655 			  const void *value, size_t len);
656 
657 /**
658  * lws_ss_get_metadata() - get current value of stream metadata item
659  *
660  * \param h: secure streams handle
661  * \param name: metadata name from the policy
662  * \param value: pointer to pointer to be set to point at the value
663  * \param len: pointer to size_t to set to the length of the value
664  *
665  * Binds user-managed data to the named metadata item from the ss policy.
666  * If present, the metadata item is handled in a protocol-specific way using
667  * the associated policy information.  For example, in the policy
668  *
669  *  	"\"metadata\":"		"["
670  *		"{\"uptag\":"  "\"X-Upload-Tag:\"},"
671  *		"{\"ctype\":"  "\"Content-Type:\"},"
672  *		"{\"xctype\":" "\"\"}"
673  *	"],"
674  *
675  * when the policy is using h1 is interpreted to add h1 headers of the given
676  * name with the value of the metadata on the left.
677  *
678  * Return 0 if \p *value and \p *len set OK, or nonzero if, eg, metadata \p name does
679  * not exist on the streamtype.
680  *
681  * The pointed-to values may only exist until the next time around the event
682  * loop.
683  */
684 LWS_VISIBLE LWS_EXTERN int
685 lws_ss_get_metadata(struct lws_ss_handle *h, const char *name,
686 		    const void **value, size_t *len);
687 
688 /**
689  * lws_ss_server_ack() - indicate how we feel about what the server has sent
690  *
691  * \param h: ss handle of accepted connection
692  * \param nack: 0 means we are OK with it, else some problem
693  *
694  * For SERVER secure streams
695  *
696  * Depending on the protocol, the server sending us something may be
697  * transactional, ie, built into it sending something is the idea we will
698  * respond somehow out-of-band; HTTP is like this with, eg, 200 response code.
699  *
700  * Calling this with nack=0 indicates that when we later respond, we want to
701  * acknowledge the transaction (eg, it means a 200 if http underneath), if
702  * nonzero that the transaction should act like it failed.
703  *
704  * If the underlying protocol doesn't understand transactions (eg, ws) then this
705  * has no effect either way.
706  */
707 LWS_VISIBLE LWS_EXTERN void
708 lws_ss_server_ack(struct lws_ss_handle *h, int nack);
709 
710 typedef void (*lws_sssfec_cb)(struct lws_ss_handle *h, void *arg);
711 
712 /**
713  * lws_ss_server_foreach_client() - callback for each live client connected to server
714  *
715  * \param h: server ss handle
716  * \param cb: the callback
717  * \param arg: arg passed to callback
718  *
719  * For SERVER secure streams
720  *
721  * Call the callback \p cb once for each client ss connected to the server,
722  * passing \p arg as an additional callback argument each time.
723  */
724 LWS_VISIBLE LWS_EXTERN void
725 lws_ss_server_foreach_client(struct lws_ss_handle *h, lws_sssfec_cb cb,
726 			     void *arg);
727 
728 /**
729  * lws_ss_change_handlers() - helper for dynamically changing stream handlers
730  *
731  * \param h: ss handle
732  * \param rx: the new RX handler
733  * \param tx: the new TX handler
734  * \param state: the new state handler
735  *
736  * Handlers set to NULL are left unchanged.
737  *
738  * This works on any handle, client or server and takes effect immediately.
739  *
740  * Depending on circumstances this may be helpful when
741  *
742  * a) a server stream undergoes an LWSSSCS_SERVER_UPGRADE (as in http -> ws) and
743  * the payloads in the new protocol have a different purpose that is best
744  * handled in their own rx and tx callbacks, and
745  *
746  * b) you may want to serve several different, possibly large things based on
747  * what was requested.  Setting a customized handler allows clean encapsulation
748  * of the different serving strategies.
749  *
750  * If the stream is long-lived, like ws, you should set the changed handler back
751  * to the default when the transaction wanting it is completed.
752  */
753 LWS_VISIBLE LWS_EXTERN void
754 lws_ss_change_handlers(struct lws_ss_handle *h, lws_sscb_rx rx, lws_sscb_tx tx,
755 		       lws_sscb_state state);
756 
757 /**
758  * lws_ss_add_peer_tx_credit() - allow peer to transmit more to us
759  *
760  * \param h: secure streams handle
761  * \param add: additional tx credit (signed)
762  *
763  * Indicate to remote peer that we can accept \p add bytes more payload being
764  * sent to us.
765  */
766 LWS_VISIBLE LWS_EXTERN int
767 lws_ss_add_peer_tx_credit(struct lws_ss_handle *h, int32_t add);
768 
769 /**
770  * lws_ss_get_est_peer_tx_credit() - get our current estimate of peer's tx credit
771  *
772  * \param h: secure streams handle
773  *
774  * Based on what credit we gave it, and what we have received, report our
775  * estimate of peer's tx credit usable to transmit to us.  This may be outdated
776  * in that some or all of its credit may already have been expended by sending
777  * stuff to us that is in flight already.
778  */
779 LWS_VISIBLE LWS_EXTERN int
780 lws_ss_get_est_peer_tx_credit(struct lws_ss_handle *h);
781 
782 LWS_VISIBLE LWS_EXTERN const char *
783 lws_ss_tag(struct lws_ss_handle *h);
784 
785 
786 #if defined(LWS_WITH_SECURE_STREAMS_AUTH_SIGV4)
787 /**
788  * lws_ss_sigv4_set_aws_key() - set aws credential into system blob
789  *
790  * \param context: lws_context
791  * \param idx:     the system blob index specified in the policy, currently
792  *                  up to 4 blobs.
793  * \param keyid:   aws access keyid
794  * \param key:     aws access key
795  *
796  * Return 0 if OK or nonzero if e.g. idx is invalid; system blob heap appending
797  * fails.
798  */
799 
800 LWS_VISIBLE LWS_EXTERN int
801 lws_ss_sigv4_set_aws_key(struct lws_context* context, uint8_t idx,
802 		                const char * keyid, const char * key);
803 
804 /**
805  * lws_aws_filesystem_credentials_helper() - read aws credentials from file
806  *
807  * \param path: path to read, ~ at start is converted to $HOME contents if any
808  * \param kid: eg, "aws_access_key_id"
809  * \param ak: eg, "aws_secret_access_key"
810  * \param aws_keyid: pointer to pointer for allocated keyid from credentials file
811  * \param aws_key: pointer to pointer for allocated key from credentials file
812  *
813  * Return 0 if both *aws_keyid and *aws_key allocated from the config file, else
814  * nonzero, and neither *aws_keyid or *aws_key are allocated.
815  *
816  * If *aws_keyid and *aws_key are set, it's the user's responsibility to
817  * free() them when they are no longer needed.
818  */
819 
820 LWS_VISIBLE LWS_EXTERN int
821 lws_aws_filesystem_credentials_helper(const char *path, const char *kid,
822 				      const char *ak, char **aws_keyid,
823 				      char **aws_key);
824 
825 #endif
826 
827 ///@}
828 
829