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 sending-data Sending data
26 
27     APIs related to writing data on a connection
28 */
29 //@{
30 #if !defined(LWS_SIZEOFPTR)
31 #define LWS_SIZEOFPTR ((int)sizeof (void *))
32 #endif
33 
34 #if defined(__x86_64__)
35 #define _LWS_PAD_SIZE 16	/* Intel recommended for best performance */
36 #else
37 #define _LWS_PAD_SIZE LWS_SIZEOFPTR   /* Size of a pointer on the target arch */
38 #endif
39 #define _LWS_PAD(n) (((n) % _LWS_PAD_SIZE) ? \
40 		((n) + (_LWS_PAD_SIZE - ((n) % _LWS_PAD_SIZE))) : (n))
41 /* last 2 is for lws-meta */
42 #define LWS_PRE _LWS_PAD(4 + 10 + 2)
43 /* used prior to 1.7 and retained for backward compatibility */
44 #define LWS_SEND_BUFFER_PRE_PADDING LWS_PRE
45 #define LWS_SEND_BUFFER_POST_PADDING 0
46 
47 #define LWS_WRITE_RAW LWS_WRITE_HTTP
48 
49 /*
50  * NOTE: These public enums are part of the abi.  If you want to add one,
51  * add it at where specified so existing users are unaffected.
52  */
53 enum lws_write_protocol {
54 	LWS_WRITE_TEXT						= 0,
55 	/**< Send a ws TEXT message,the pointer must have LWS_PRE valid
56 	 * memory behind it.
57 	 *
58 	 * The receiver expects only valid utf-8 in the payload */
59 	LWS_WRITE_BINARY					= 1,
60 	/**< Send a ws BINARY message, the pointer must have LWS_PRE valid
61 	 * memory behind it.
62 	 *
63 	 * Any sequence of bytes is valid */
64 	LWS_WRITE_CONTINUATION					= 2,
65 	/**< Continue a previous ws message, the pointer must have LWS_PRE valid
66 	 * memory behind it */
67 	LWS_WRITE_HTTP						= 3,
68 	/**< Send HTTP content */
69 
70 	/* LWS_WRITE_CLOSE is handled by lws_close_reason() */
71 	LWS_WRITE_PING						= 5,
72 	LWS_WRITE_PONG						= 6,
73 
74 	/* Same as write_http but we know this write ends the transaction */
75 	LWS_WRITE_HTTP_FINAL					= 7,
76 
77 	/* HTTP2 */
78 
79 	LWS_WRITE_HTTP_HEADERS					= 8,
80 	/**< Send http headers (http2 encodes this payload and LWS_WRITE_HTTP
81 	 * payload differently, http 1.x links also handle this correctly. so
82 	 * to be compatible with both in the future,header response part should
83 	 * be sent using this regardless of http version expected)
84 	 */
85 	LWS_WRITE_HTTP_HEADERS_CONTINUATION			= 9,
86 	/**< Continuation of http/2 headers
87 	 */
88 
89 	/****** add new things just above ---^ ******/
90 
91 	/* flags */
92 
93 	LWS_WRITE_BUFLIST = 0x20,
94 	/**< Don't actually write it... stick it on the output buflist and
95 	 *   write it as soon as possible.  Useful if you learn you have to
96 	 *   write something, have the data to write to hand but the timing is
97 	 *   unrelated as to whether the connection is writable or not, and were
98 	 *   otherwise going to have to allocate a temp buffer and write it
99 	 *   later anyway */
100 
101 	LWS_WRITE_NO_FIN = 0x40,
102 	/**< This part of the message is not the end of the message */
103 
104 	LWS_WRITE_H2_STREAM_END = 0x80,
105 	/**< Flag indicates this packet should go out with STREAM_END if h2
106 	 * STREAM_END is allowed on DATA or HEADERS.
107 	 */
108 
109 	LWS_WRITE_CLIENT_IGNORE_XOR_MASK = 0x80
110 	/**< client packet payload goes out on wire unmunged
111 	 * only useful for security tests since normal servers cannot
112 	 * decode the content if used */
113 };
114 
115 /* used with LWS_CALLBACK_CHILD_WRITE_VIA_PARENT */
116 
117 struct lws_write_passthru {
118 	struct lws *wsi;
119 	unsigned char *buf;
120 	size_t len;
121 	enum lws_write_protocol wp;
122 };
123 
124 
125 /**
126  * lws_write() - Apply protocol then write data to client
127  *
128  * \param wsi:	Websocket instance (available from user callback)
129  * \param buf:	The data to send.  For data being sent on a websocket
130  *		connection (ie, not default http), this buffer MUST have
131  *		LWS_PRE bytes valid BEFORE the pointer.
132  *		This is so the protocol header data can be added in-situ.
133  * \param len:	Count of the data bytes in the payload starting from buf
134  * \param protocol:	Use LWS_WRITE_HTTP to reply to an http connection, and one
135  *		of LWS_WRITE_BINARY or LWS_WRITE_TEXT to send appropriate
136  *		data on a websockets connection.  Remember to allow the extra
137  *		bytes before and after buf if LWS_WRITE_BINARY or LWS_WRITE_TEXT
138  *		are used.
139  *
140  * This function provides the way to issue data back to the client, for any
141  * role (h1, h2, ws, raw, etc).  It can only be called from the WRITEABLE
142  * callback.
143  *
144  * IMPORTANT NOTICE!
145  *
146  * When sending with ws protocol
147  *
148  * LWS_WRITE_TEXT,
149  * LWS_WRITE_BINARY,
150  * LWS_WRITE_CONTINUATION,
151  * LWS_WRITE_PING,
152  * LWS_WRITE_PONG,
153  *
154  * or sending on http/2... the send buffer has to have LWS_PRE bytes valid
155  * BEFORE the buffer pointer you pass to lws_write().  Since you'll probably
156  * want to use http/2 before too long, it's wise to just always do this with
157  * lws_write buffers... LWS_PRE is typically 16 bytes it's not going to hurt
158  * usually.
159  *
160  * start of alloc       ptr passed to lws_write      end of allocation
161  *       |                         |                         |
162  *       v  <-- LWS_PRE bytes -->  v                         v
163  *       [----------------  allocated memory  ---------------]
164  *              (for lws use)      [====== user buffer ======]
165  *
166  * This allows us to add protocol info before the data, and send as one packet
167  * on the network without payload copying, for maximum efficiency.
168  *
169  * So for example you need this kind of code to use lws_write with a
170  * 128-byte payload
171  *
172  *   char buf[LWS_PRE + 128];
173  *
174  *   // fill your part of the buffer... for example here it's all zeros
175  *   memset(&buf[LWS_PRE], 0, 128);
176  *
177  *   if (lws_write(wsi, &buf[LWS_PRE], 128, LWS_WRITE_TEXT) < 128) {
178  *   		... the connection is dead ...
179  *   		return -1;
180  *   }
181  *
182  * LWS_PRE is currently 16, which covers ws and h2 frame headers, and is
183  * compatible with 32 and 64-bit alignment requirements.
184  *
185  * (LWS_SEND_BUFFER_POST_PADDING is deprecated, it's now 0 and can be left off.)
186  *
187  * Return may be -1 is the write failed in a way indicating that the connection
188  * has ended already, in which case you can close your side, or a positive
189  * number that is at least the number of bytes requested to send (under some
190  * encapsulation scenarios, it can indicate more than you asked was sent).
191  *
192  * The recommended test of the return is less than what you asked indicates
193  * the connection has failed.
194  *
195  * Truncated Writes
196  * ================
197  *
198  * The OS may not accept everything you asked to write on the connection.
199  *
200  * Posix defines POLLOUT indication from poll() to show that the connection
201  * will accept more write data, but it doesn't specifiy how much.  It may just
202  * accept one byte of whatever you wanted to send.
203  *
204  * LWS will buffer the remainder automatically, and send it out autonomously.
205  *
206  * During that time, WRITABLE callbacks to user code will be suppressed and
207  * instead used internally.  After it completes, it will send an extra WRITEABLE
208  * callback to the user code, in case any request was missed.  So it is possible
209  * to receive unasked-for WRITEABLE callbacks, the user code should have enough
210  * state to know if it wants to write anything and just return if not.
211  *
212  * This is to handle corner cases where unexpectedly the OS refuses what we
213  * usually expect it to accept.  It's not recommended as the way to randomly
214  * send huge payloads, since it is being copied on to heap and is inefficient.
215  *
216  * Huge payloads should instead be sent in fragments that are around 2 x mtu,
217  * which is almost always directly accepted by the OS.  To simplify this for
218  * ws fragments, there is a helper lws_write_ws_flags() below that simplifies
219  * selecting the correct flags to give lws_write() for each fragment.
220  *
221  * In the case of RFC8441 ws-over-h2, you cannot send ws fragments larger than
222  * the max h2 frame size, typically 16KB, but should further restrict it to
223  * the same ~2 x mtu limit mentioned above.
224  */
225 LWS_VISIBLE LWS_EXTERN int
226 lws_write(struct lws *wsi, unsigned char *buf, size_t len,
227 	  enum lws_write_protocol protocol);
228 
229 /* helper for case where buffer may be const */
230 #define lws_write_http(wsi, buf, len) \
231 	lws_write(wsi, (unsigned char *)(buf), len, LWS_WRITE_HTTP)
232 
233 /**
234  * lws_write_ws_flags() - Helper for multi-frame ws message flags
235  *
236  * \param initial: the lws_write flag to use for the start fragment, eg,
237  *		   LWS_WRITE_TEXT
238  * \param is_start: nonzero if this is the first fragment of the message
239  * \param is_end: nonzero if this is the last fragment of the message
240  *
241  * Returns the correct LWS_WRITE_ flag to use for each fragment of a message
242  * in turn.
243  */
244 static LWS_INLINE int
lws_write_ws_flags(int initial,int is_start,int is_end)245 lws_write_ws_flags(int initial, int is_start, int is_end)
246 {
247 	int r;
248 
249 	if (is_start)
250 		r = initial;
251 	else
252 		r = LWS_WRITE_CONTINUATION;
253 
254 	if (!is_end)
255 		r |= LWS_WRITE_NO_FIN;
256 
257 	return r;
258 }
259 
260 /**
261  * lws_raw_transaction_completed() - Helper for flushing before close
262  *
263  * \param wsi: the struct lws to operate on
264  *
265  * Returns -1 if the wsi can close now.  However if there is buffered, unsent
266  * data, the wsi is marked as to be closed when the output buffer data is
267  * drained, and it returns 0.
268  *
269  * For raw cases where the transaction completed without failure,
270  * `return lws_raw_transaction_completed(wsi)` should better be used than
271  * return -1.
272  */
273 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
274 lws_raw_transaction_completed(struct lws *wsi);
275 
276 ///@}
277