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
141 * for both http and websocket protocols.
142 *
143 * IMPORTANT NOTICE!
144 *
145 * When sending with websocket protocol
146 *
147 * LWS_WRITE_TEXT,
148 * LWS_WRITE_BINARY,
149 * LWS_WRITE_CONTINUATION,
150 * LWS_WRITE_PING,
151 * LWS_WRITE_PONG,
152 *
153 * or sending on http/2,
154 *
155 * the send buffer has to have LWS_PRE bytes valid BEFORE the buffer pointer you
156 * pass to lws_write(). Since you'll probably want to use http/2 before too
157 * long, it's wise to just always do this with lws_write buffers... LWS_PRE is
158 * typically 16 bytes it's not going to hurt 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 and after the data, and send as
167 * one packet 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 * lws_write(wsi, &buf[LWS_PRE], 128, LWS_WRITE_TEXT);
178 *
179 * LWS_PRE is at least the frame nonce + 2 header + 8 length
180 * LWS_SEND_BUFFER_POST_PADDING is deprecated, it's now 0 and can be left off.
181 * The example apps no longer use it.
182 *
183 * Pad LWS_PRE to the CPU word size, so that word references
184 * to the address immediately after the padding won't cause an unaligned access
185 * error. Sometimes for performance reasons the recommended padding is even
186 * larger than sizeof(void *).
187 *
188 * In the case of sending using websocket protocol, be sure to allocate
189 * valid storage before and after buf as explained above. This scheme
190 * allows maximum efficiency of sending data and protocol in a single
191 * packet while not burdening the user code with any protocol knowledge.
192 *
193 * Return may be -1 for a fatal error needing connection close, or the
194 * number of bytes sent.
195 *
196 * Truncated Writes
197 * ================
198 *
199 * The OS may not accept everything you asked to write on the connection.
200 *
201 * Posix defines POLLOUT indication from poll() to show that the connection
202 * will accept more write data, but it doesn't specifiy how much. It may just
203 * accept one byte of whatever you wanted to send.
204 *
205 * LWS will buffer the remainder automatically, and send it out autonomously.
206 *
207 * During that time, WRITABLE callbacks will be suppressed.
208 *
209 * This is to handle corner cases where unexpectedly the OS refuses what we
210 * usually expect it to accept. You should try to send in chunks that are
211 * almost always accepted in order to avoid the inefficiency of the buffering.
212 */
213 LWS_VISIBLE LWS_EXTERN int
214 lws_write(struct lws *wsi, unsigned char *buf, size_t len,
215 enum lws_write_protocol protocol);
216
217 /* helper for case where buffer may be const */
218 #define lws_write_http(wsi, buf, len) \
219 lws_write(wsi, (unsigned char *)(buf), len, LWS_WRITE_HTTP)
220
221 /**
222 * lws_write_ws_flags() - Helper for multi-frame ws message flags
223 *
224 * \param initial: the lws_write flag to use for the start fragment, eg,
225 * LWS_WRITE_TEXT
226 * \param is_start: nonzero if this is the first fragment of the message
227 * \param is_end: nonzero if this is the last fragment of the message
228 *
229 * Returns the correct LWS_WRITE_ flag to use for each fragment of a message
230 * in turn.
231 */
232 static LWS_INLINE int
lws_write_ws_flags(int initial,int is_start,int is_end)233 lws_write_ws_flags(int initial, int is_start, int is_end)
234 {
235 int r;
236
237 if (is_start)
238 r = initial;
239 else
240 r = LWS_WRITE_CONTINUATION;
241
242 if (!is_end)
243 r |= LWS_WRITE_NO_FIN;
244
245 return r;
246 }
247
248 /**
249 * lws_raw_transaction_completed() - Helper for flushing before close
250 *
251 * \param wsi: the struct lws to operate on
252 *
253 * Returns -1 if the wsi can close now. However if there is buffered, unsent
254 * data, the wsi is marked as to be closed when the output buffer data is
255 * drained, and it returns 0.
256 *
257 * For raw cases where the transaction completed without failure,
258 * `return lws_raw_transaction_completed(wsi)` should better be used than
259 * return -1.
260 */
261 LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
262 lws_raw_transaction_completed(struct lws *wsi);
263
264 ///@}
265