1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010 - 2019 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 
25 /*! \defgroup client Client related functions
26  * ##Client releated functions
27  * \ingroup lwsapi
28  *
29  * */
30 ///@{
31 
32 /** enum lws_client_connect_ssl_connection_flags - flags that may be used
33  * with struct lws_client_connect_info ssl_connection member to control if
34  * and how SSL checks apply to the client connection being created
35  */
36 
37 enum lws_client_connect_ssl_connection_flags {
38 	LCCSCF_USE_SSL 				= (1 << 0),
39 	LCCSCF_ALLOW_SELFSIGNED			= (1 << 1),
40 	LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK	= (1 << 2),
41 	LCCSCF_ALLOW_EXPIRED			= (1 << 3),
42 	LCCSCF_ALLOW_INSECURE			= (1 << 4),
43 	LCCSCF_H2_QUIRK_NGHTTP2_END_STREAM	= (1 << 5),
44 	LCCSCF_H2_QUIRK_OVERFLOWS_TXCR		= (1 << 6),
45 	LCCSCF_H2_AUTH_BEARER			= (1 << 7),
46 	LCCSCF_H2_HEXIFY_AUTH_TOKEN		= (1 << 8),
47 	LCCSCF_H2_MANUAL_RXFLOW			= (1 << 9),
48 	LCCSCF_HTTP_MULTIPART_MIME		= (1 << 10),
49 	LCCSCF_HTTP_X_WWW_FORM_URLENCODED	= (1 << 11),
50 	LCCSCF_HTTP_NO_FOLLOW_REDIRECT		= (1 << 12),
51 
52 	LCCSCF_PIPELINE				= (1 << 16),
53 		/**< Serialize / pipeline multiple client connections
54 		 * on a single connection where possible.
55 		 *
56 		 * HTTP/1.0: possible if Keep-Alive: yes sent by server
57 		 * HTTP/1.1: always possible... uses pipelining
58 		 * HTTP/2:   always possible... uses parallel streams
59 		 */
60 	LCCSCF_MUXABLE_STREAM			= (1 << 17),
61 	LCCSCF_H2_PRIOR_KNOWLEDGE		= (1 << 18),
62 	LCCSCF_WAKE_SUSPEND__VALIDITY		= (1 << 19),
63 	/* our validity checks are important enough to wake from suspend */
64 	LCCSCF_PRIORITIZE_READS			= (1 << 20),
65 	/**<
66 	 * Normally lws balances reads and writes on all connections, so both
67 	 * are possible even on busy connections, and we go around the event
68 	 * loop more often to facilitate that, even if there is pending data.
69 	 *
70 	 * This flag indicates that you want to handle any pending reads on this
71 	 * connection without yielding the service loop for anything else.  This
72 	 * means you may block other connection processing in favour of incoming
73 	 * data processing on this one if it receives back to back incoming rx.
74 	 */
75 	LCCSCF_SECSTREAM_CLIENT			= (1 << 21),
76 	/**< used to mark client wsi as bound to secure stream */
77 	LCCSCF_SECSTREAM_PROXY_LINK		= (1 << 22),
78 	/**< client is a link between SS client and SS proxy */
79 	LCCSCF_SECSTREAM_PROXY_ONWARD		= (1 << 23),
80 	/**< client the SS proxy's onward connection */
81 
82 	LCCSCF_IP_LOW_LATENCY			= (1 << 24),
83 	/**< set the "low delay" bit on the IP packets of this connection */
84 	LCCSCF_IP_HIGH_THROUGHPUT		= (1 << 25),
85 	/**< set the "high throughput" bit on the IP packets of this
86 	 *   connection */
87 	LCCSCF_IP_HIGH_RELIABILITY		= (1 << 26),
88 	/**< set the "high reliability" bit on the IP packets of this
89 	 *   connection */
90 	LCCSCF_IP_LOW_COST			= (1 << 27),
91 	/**< set the "minimize monetary cost" bit on the IP packets of this
92 	 *   connection */
93 	LCCSCF_CONMON				= (1 << 28),
94 	/**< If LWS_WITH_CONMON enabled for build, keeps a copy of the
95 	 * getaddrinfo results so they can be queried subsequently */
96 };
97 
98 /** struct lws_client_connect_info - parameters to connect with when using
99  *				    lws_client_connect_via_info() */
100 
101 struct lws_client_connect_info {
102 	struct lws_context *context;
103 	/**< lws context to create connection in */
104 	const char *address;
105 	/**< remote address to connect to */
106 	int port;
107 	/**< remote port to connect to */
108 	int ssl_connection;
109 	/**< 0, or a combination of LCCSCF_ flags */
110 	const char *path;
111 	/**< uri path */
112 	const char *host;
113 	/**< content of host header */
114 	const char *origin;
115 	/**< content of origin header */
116 	const char *protocol;
117 	/**< list of ws protocols we could accept */
118 	int ietf_version_or_minus_one;
119 	/**< deprecated: currently leave at 0 or -1 */
120 	void *userdata;
121 	/**< if non-NULL, use this as wsi user_data instead of malloc it */
122 	const void *client_exts;
123 	/**< UNUSED... provide in info.extensions at context creation time */
124 	const char *method;
125 	/**< if non-NULL, do this http method instead of ws[s] upgrade.
126 	 * use "GET" to be a simple http client connection.  "RAW" gets
127 	 * you a connected socket that lws itself will leave alone once
128 	 * connected. */
129 	struct lws *parent_wsi;
130 	/**< if another wsi is responsible for this connection, give it here.
131 	 * this is used to make sure if the parent closes so do any
132 	 * child connections first. */
133 	const char *uri_replace_from;
134 	/**< if non-NULL, when this string is found in URIs in
135 	 * text/html content-encoding, it's replaced with uri_replace_to */
136 	const char *uri_replace_to;
137 	/**< see uri_replace_from */
138 	struct lws_vhost *vhost;
139 	/**< vhost to bind to (used to determine related SSL_CTX) */
140 	struct lws **pwsi;
141 	/**< if not NULL, store the new wsi here early in the connection
142 	 * process.  Although we return the new wsi, the call to create the
143 	 * client connection does progress the connection somewhat and may
144 	 * meet an error that will result in the connection being scrubbed and
145 	 * NULL returned.  While the wsi exists though, he may process a
146 	 * callback like CLIENT_CONNECTION_ERROR with his wsi: this gives the
147 	 * user callback a way to identify which wsi it is that faced the error
148 	 * even before the new wsi is returned and even if ultimately no wsi
149 	 * is returned.
150 	 */
151 	const char *iface;
152 	/**< NULL to allow routing on any interface, or interface name or IP
153 	 * to bind the socket to */
154 	const char *local_protocol_name;
155 	/**< NULL: .protocol is used both to select the local protocol handler
156 	 *         to bind to and as the list of remote ws protocols we could
157 	 *         accept.
158 	 *   non-NULL: this protocol name is used to bind the connection to
159 	 *             the local protocol handler.  .protocol is used for the
160 	 *             list of remote ws protocols we could accept */
161 	const char *alpn;
162 	/**< NULL: allow lws default ALPN list, from vhost if present or from
163 	 *       list of roles built into lws
164 	 * non-NULL: require one from provided comma-separated list of alpn
165 	 *           tokens
166 	 */
167 
168 	struct lws_sequencer *seq;
169 	/**< NULL, or an lws_seq_t that wants to be given messages about
170 	 * this wsi's lifecycle as it connects, errors or closes.
171 	 */
172 
173 	void *opaque_user_data;
174 	/**< This data has no meaning to lws but is applied to the client wsi
175 	 *   and can be retrieved by user code with lws_get_opaque_user_data().
176 	 *   It's also provided with sequencer messages if the wsi is bound to
177 	 *   an lws_seq_t.
178 	 */
179 
180 	const lws_retry_bo_t *retry_and_idle_policy;
181 	/**< optional retry and idle policy to apply to this connection.
182 	 *   Currently only the idle parts are applied to the connection.
183 	 */
184 
185 	int		manual_initial_tx_credit;
186 	/**< if LCCSCF_H2_MANUAL_REFLOW is set, this becomes the initial tx
187 	 * credit for the stream.
188 	 */
189 
190 	uint8_t		sys_tls_client_cert;
191 	/**< 0 means no client cert.  1+ means apply lws_system client cert 0+
192 	 * to the client connection.
193 	 */
194 
195 	uint8_t		priority;
196 	/**< 0 means normal priority... otherwise sets the IP priority on
197 	 * packets coming from this connection, from 1 - 7.  Setting 7
198 	 * (network management priority) requires CAP_NET_ADMIN capability but
199 	 * the others can be set by anyone.
200 	 */
201 
202 #if defined(LWS_ROLE_MQTT)
203 	const lws_mqtt_client_connect_param_t *mqtt_cp;
204 #else
205 	void		*mqtt_cp;
206 #endif
207 
208 #if defined(LWS_WITH_SYS_FAULT_INJECTION)
209 	lws_fi_ctx_t				fic;
210 	/**< Attach external Fault Injection context to the client wsi,
211 	 * hierarchy is wsi -> vhost -> context */
212 #endif
213 	/* for convenience, available when FI disabled in build */
214 	const char				*fi_wsi_name;
215 	/**< specific Fault Injection namespace name for wsi created for this
216 	 * connection, allows targeting by "wsi=XXX/..." if you give XXX here.
217 	 */
218 
219 	uint16_t	keep_warm_secs;
220 	/**< 0 means 5s.  If the client connection to the endpoint becomes idle,
221 	 * defer closing it for this many seconds in case another outgoing
222 	 * connection to the same endpoint turns up.
223 	 */
224 
225 	/* Add new things just above here ---^
226 	 * This is part of the ABI, don't needlessly break compatibility
227 	 *
228 	 * The below is to ensure later library versions with new
229 	 * members added above will see 0 (default) even if the app
230 	 * was not built against the newer headers.
231 	 */
232 
233 	void *_unused[4]; /**< dummy */
234 };
235 
236 /**
237  * lws_client_connect_via_info() - Connect to another websocket server
238  * \param ccinfo: pointer to lws_client_connect_info struct
239  *
240  *	This function creates a connection to a remote server using the
241  *	information provided in ccinfo.
242  */
243 LWS_VISIBLE LWS_EXTERN struct lws *
244 lws_client_connect_via_info(const struct lws_client_connect_info *ccinfo);
245 
246 /**
247  * lws_init_vhost_client_ssl() - also enable client SSL on an existing vhost
248  *
249  * \param info: client ssl related info
250  * \param vhost: which vhost to initialize client ssl operations on
251  *
252  * You only need to call this if you plan on using SSL client connections on
253  * the vhost.  For non-SSL client connections, it's not necessary to call this.
254  *
255  * The following members of info are used during the call
256  *
257  *	 - options must have LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT set,
258  *	     otherwise the call does nothing
259  *	 - provided_client_ssl_ctx must be NULL to get a generated client
260  *	     ssl context, otherwise you can pass a prepared one in by setting it
261  *	 - ssl_cipher_list may be NULL or set to the client valid cipher list
262  *	 - ssl_ca_filepath may be NULL or client cert filepath
263  *	 - ssl_cert_filepath may be NULL or client cert filepath
264  *	 - ssl_private_key_filepath may be NULL or client cert private key
265  *
266  * You must create your vhost explicitly if you want to use this, so you have
267  * a pointer to the vhost.  Create the context first with the option flag
268  * LWS_SERVER_OPTION_EXPLICIT_VHOSTS and then call lws_create_vhost() with
269  * the same info struct.
270  */
271 LWS_VISIBLE LWS_EXTERN int
272 lws_init_vhost_client_ssl(const struct lws_context_creation_info *info,
273 			  struct lws_vhost *vhost);
274 /**
275  * lws_http_client_read() - consume waiting received http client data
276  *
277  * \param wsi: client connection
278  * \param buf: pointer to buffer pointer - fill with pointer to your buffer
279  * \param len: pointer to chunk length - fill with max length of buffer
280  *
281  * This is called when the user code is notified client http data has arrived.
282  * The user code may choose to delay calling it to consume the data, for example
283  * waiting until an onward connection is writeable.
284  *
285  * For non-chunked connections, up to len bytes of buf are filled with the
286  * received content.  len is set to the actual amount filled before return.
287  *
288  * For chunked connections, the linear buffer content contains the chunking
289  * headers and it cannot be passed in one lump.  Instead, this function will
290  * call back LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ with in pointing to the
291  * chunk start and len set to the chunk length.  There will be as many calls
292  * as there are chunks or partial chunks in the buffer.
293  */
294 LWS_VISIBLE LWS_EXTERN int
295 lws_http_client_read(struct lws *wsi, char **buf, int *len);
296 
297 /**
298  * lws_http_client_http_response() - get last HTTP response code
299  *
300  * \param wsi: client connection
301  *
302  * Returns the last server response code, eg, 200 for client http connections.
303  *
304  * You should capture this during the LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP
305  * callback, because after that the memory reserved for storing the related
306  * headers is freed and this value is lost.
307  */
308 LWS_VISIBLE LWS_EXTERN unsigned int
309 lws_http_client_http_response(struct lws *wsi);
310 
311 /**
312  * lws_tls_client_vhost_extra_cert_mem() - add more certs to vh client tls ctx
313  *
314  * \param vh: the vhost to give more client certs to
315  * \param der: pointer to der format additional cert
316  * \param der_len: size in bytes of der
317  *
318  * After the vhost is created with one cert for client verification, you
319  * can add additional, eg, intermediate, certs to the client tls context
320  * of the vhost, for use with validating the incoming server cert(s).
321  */
322 LWS_VISIBLE LWS_EXTERN int
323 lws_tls_client_vhost_extra_cert_mem(struct lws_vhost *vh,
324 		const uint8_t *der, size_t der_len);
325 
326 /**
327  * lws_client_http_body_pending() - control if client connection needs to send body
328  *
329  * \param wsi: client connection
330  * \param something_left_to_send: nonzero if need to send more body, 0 (default)
331  * 				if nothing more to send
332  *
333  * If you will send payload data with your HTTP client connection, eg, for POST,
334  * when you set the related http headers in
335  * LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER callback you should also call
336  * this API with something_left_to_send nonzero, and call
337  * lws_callback_on_writable(wsi);
338  *
339  * After sending the headers, lws will call your callback with
340  * LWS_CALLBACK_CLIENT_HTTP_WRITEABLE reason when writable.  You can send the
341  * next part of the http body payload, calling lws_callback_on_writable(wsi);
342  * if there is more to come, or lws_client_http_body_pending(wsi, 0); to
343  * let lws know the last part is sent and the connection can move on.
344  */
345 LWS_VISIBLE LWS_EXTERN void
346 lws_client_http_body_pending(struct lws *wsi, int something_left_to_send);
347 
348 /**
349  * lws_client_http_multipart() - issue appropriate multipart header or trailer
350  *
351  * \param wsi: client connection
352  * \param name: multipart header name field, or NULL if end of multipart
353  * \param filename: multipart header filename field, or NULL if none
354  * \param content_type: multipart header content-type part, or NULL if none
355  * \param p: pointer to position in buffer
356  * \param end: end of buffer
357  *
358  * This issues a multipart mime boundary, or terminator if name = NULL.
359  *
360  * Returns 0 if OK or nonzero if couldn't fit in buffer
361  */
362 LWS_VISIBLE LWS_EXTERN int
363 lws_client_http_multipart(struct lws *wsi, const char *name,
364 			  const char *filename, const char *content_type,
365 			  char **p, char *end);
366 
367 /**
368  * lws_http_basic_auth_gen() - helper to encode client basic auth string
369  *
370  * \param user: user name
371  * \param pw: password
372  * \param buf: where to store base64 result
373  * \param len: max usable size of buf
374  *
375  * Encodes a username and password in Basic Auth format for use with the
376  * Authorization header.  On return, buf is filled with something like
377  * "Basic QWxhZGRpbjpPcGVuU2VzYW1l".
378  */
379 LWS_VISIBLE LWS_EXTERN int
380 lws_http_basic_auth_gen(const char *user, const char *pw, char *buf, size_t len);
381 
382 /**
383  * lws_tls_session_is_reused() - returns nonzero if tls session was cached
384  *
385  * \param wsi: the wsi
386  *
387  * Returns zero if the tls session is fresh, else nonzero if the tls session was
388  * taken from the cache.  If lws is built with LWS_WITH_TLS_SESSIONS and the vhost
389  * was created with the option LWS_SERVER_OPTION_ENABLE_TLS_SESSION_CACHE, then
390  * on full tls session establishment of a client connection, the session is added
391  * to the tls cache.
392  *
393  * This lets you find out if your session was new (0) or from the cache (nonzero),
394  * it'a mainly useful for stats and testing.
395  */
396 LWS_VISIBLE LWS_EXTERN int
397 lws_tls_session_is_reused(struct lws *wsi);
398 
399 ///@}
400