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 #include "private-lib-core.h"
26 
27 /*
28  * notice this returns number of bytes consumed, or -1
29  */
30 int
lws_issue_raw(struct lws * wsi,unsigned char * buf,size_t len)31 lws_issue_raw(struct lws *wsi, unsigned char *buf, size_t len)
32 {
33 	struct lws_context *context = lws_get_context(wsi);
34 	struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
35 	size_t real_len = len;
36 	unsigned int n, m;
37 
38 	// lwsl_notice("%s: len %d\n", __func__, (int)len);
39 	// lwsl_hexdump_level(LLL_NOTICE, buf, len);
40 
41 	/*
42 	 * Detect if we got called twice without going through the
43 	 * event loop to handle pending.  Since that guarantees extending any
44 	 * existing buflist_out it's inefficient.
45 	 */
46 	if (0 && buf && wsi->could_have_pending) {
47 		lwsl_hexdump_level(LLL_INFO, buf, len);
48 		lwsl_info("** %p: vh: %s, prot: %s, role %s: "
49 			  "Inefficient back-to-back write of %lu detected...\n",
50 			  wsi, wsi->vhost ? wsi->vhost->name : "no vhost",
51 			  wsi->protocol->name, wsi->role_ops->name,
52 			  (unsigned long)len);
53 	}
54 
55 	lws_stats_bump(pt, LWSSTATS_C_API_WRITE, 1);
56 
57 	/* just ignore sends after we cleared the truncation buffer */
58 	if (lwsi_state(wsi) == LRS_FLUSHING_BEFORE_CLOSE &&
59 	    !lws_has_buffered_out(wsi)
60 #if defined(LWS_WITH_HTTP_STREAM_COMPRESSION)
61 	    && !wsi->http.comp_ctx.may_have_more
62 #endif
63 	    )
64 		return (int)len;
65 
66 	if (buf && lws_has_buffered_out(wsi)) {
67 		lwsl_info("** %p: vh: %s, prot: %s, incr buflist_out by %lu\n",
68 			  wsi, wsi->vhost ? wsi->vhost->name : "no vhost",
69 			  wsi->protocol->name, (unsigned long)len);
70 
71 		/*
72 		 * already buflist ahead of this, add it on the tail of the
73 		 * buflist, then ignore it for now and act like we're flushing
74 		 * the buflist...
75 		 */
76 
77 		if (lws_buflist_append_segment(&wsi->buflist_out, buf, len))
78 			return -1;
79 
80 		buf = NULL;
81 		len = 0;
82 	}
83 
84 	if (wsi->buflist_out) {
85 		/* we have to drain the earliest buflist_out stuff first */
86 
87 		len = lws_buflist_next_segment_len(&wsi->buflist_out, &buf);
88 		real_len = len;
89 
90 		lwsl_debug("%s: draining %d\n", __func__, (int)len);
91 	}
92 
93 	if (!len || !buf)
94 		return 0;
95 
96 	if (!wsi->mux_substream && !lws_socket_is_valid(wsi->desc.sockfd))
97 		lwsl_err("%s: invalid sock %p\n", __func__, wsi);
98 
99 	/* limit sending */
100 	if (wsi->protocol->tx_packet_size)
101 		n = (int)wsi->protocol->tx_packet_size;
102 	else {
103 		n = (int)wsi->protocol->rx_buffer_size;
104 		if (!n)
105 			n = context->pt_serv_buf_size;
106 	}
107 	n += LWS_PRE + 4;
108 	if (n > len)
109 		n = (int)len;
110 
111 	/* nope, send it on the socket directly */
112 
113 	m = lws_ssl_capable_write(wsi, buf, n);
114 	lwsl_info("%s: ssl_capable_write (%d) says %d\n", __func__, n, m);
115 
116 	/* something got written, it can have been truncated now */
117 	wsi->could_have_pending = 1;
118 
119 	switch (m) {
120 	case LWS_SSL_CAPABLE_ERROR:
121 		/* we're going to close, let close know sends aren't possible */
122 		wsi->socket_is_permanently_unusable = 1;
123 		return -1;
124 	case LWS_SSL_CAPABLE_MORE_SERVICE:
125 		/*
126 		 * nothing got sent, not fatal.  Retry the whole thing later,
127 		 * ie, implying treat it was a truncated send so it gets
128 		 * retried
129 		 */
130 		m = 0;
131 		break;
132 	}
133 
134 	if ((int)m < 0)
135 		m = 0;
136 
137 	/*
138 	 * we were sending this from buflist_out?  Then not sending everything
139 	 * is a small matter of advancing ourselves only by the amount we did
140 	 * send in the buflist.
141 	 */
142 	if (lws_has_buffered_out(wsi)) {
143 		if (m) {
144 			lwsl_info("%p partial adv %d (vs %ld)\n", wsi, m,
145 					(long)real_len);
146 			lws_buflist_use_segment(&wsi->buflist_out, m);
147 		}
148 
149 		if (!lws_has_buffered_out(wsi)) {
150 			lwsl_info("%s: wsi %p: buflist_out flushed\n",
151 				  __func__, wsi);
152 
153 			m = (int)real_len;
154 			if (lwsi_state(wsi) == LRS_FLUSHING_BEFORE_CLOSE) {
155 				lwsl_info("*%p signalling to close now\n", wsi);
156 				return -1; /* retry closing now */
157 			}
158 
159 			if (wsi->close_when_buffered_out_drained) {
160 				wsi->close_when_buffered_out_drained = 0;
161 				return -1;
162 			}
163 
164 #if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)
165 #if defined(LWS_WITH_SERVER)
166 			if (wsi->http.deferred_transaction_completed) {
167 				lwsl_notice("%s: partial completed, doing "
168 					    "deferred transaction completed\n",
169 					    __func__);
170 				wsi->http.deferred_transaction_completed = 0;
171 				return lws_http_transaction_completed(wsi) ?
172 							-1 : (int)real_len;
173 			}
174 #endif
175 #endif
176 #if defined(LWS_ROLE_WS)
177 			/* Since buflist_out flushed, we're not inside a frame any more */
178 			if (wsi->ws)
179 				wsi->ws->inside_frame = 0;
180 #endif
181 		}
182 		/* always callback on writeable */
183 		lws_callback_on_writable(wsi);
184 
185 		return m;
186 	}
187 
188 #if defined(LWS_WITH_HTTP_STREAM_COMPRESSION)
189 	if (wsi->http.comp_ctx.may_have_more)
190 		lws_callback_on_writable(wsi);
191 #endif
192 
193 	if (m == real_len)
194 		/* what we just sent went out cleanly */
195 		return m;
196 
197 	/*
198 	 * We were not able to send everything... and we were not sending from
199 	 * an existing buflist_out.  So we are starting a fresh buflist_out, by
200 	 * buffering the unsent remainder on it.
201 	 * (it will get first priority next time the socket is writable).
202 	 */
203 	lwsl_debug("%p new partial sent %d from %lu total\n", wsi, m,
204 		    (unsigned long)real_len);
205 
206 	if (lws_buflist_append_segment(&wsi->buflist_out, buf + m,
207 				       real_len - m) < 0)
208 		return -1;
209 
210 	lws_stats_bump(pt, LWSSTATS_C_WRITE_PARTIALS, 1);
211 	lws_stats_bump(pt, LWSSTATS_B_PARTIALS_ACCEPTED_PARTS, m);
212 
213 #if defined(LWS_WITH_UDP)
214 	if (lws_wsi_is_udp(wsi)) {
215 		/* stash original destination for fulfilling UDP partials */
216 		wsi->udp->sa_pending = wsi->udp->sa;
217 		wsi->udp->salen_pending = wsi->udp->salen;
218 	}
219 #endif
220 
221 	/* since something buffered, force it to get another chance to send */
222 	lws_callback_on_writable(wsi);
223 
224 	return (int)real_len;
225 }
226 
227 int
lws_write(struct lws * wsi,unsigned char * buf,size_t len,enum lws_write_protocol wp)228 lws_write(struct lws *wsi, unsigned char *buf, size_t len,
229 	  enum lws_write_protocol wp)
230 {
231 	struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
232 #if defined(LWS_WITH_DETAILED_LATENCY)
233 	lws_usec_t us;
234 #endif
235 	int m;
236 
237 	lws_stats_bump(pt, LWSSTATS_C_API_LWS_WRITE, 1);
238 
239 	if ((int)len < 0) {
240 		lwsl_err("%s: suspicious len int %d, ulong %lu\n", __func__,
241 				(int)len, (unsigned long)len);
242 		return -1;
243 	}
244 
245 	lws_stats_bump(pt, LWSSTATS_B_WRITE, len);
246 
247 #ifdef LWS_WITH_ACCESS_LOG
248 	wsi->http.access_log.sent += len;
249 #endif
250 #if defined(LWS_WITH_SERVER_STATUS)
251 	if (wsi->vhost)
252 		wsi->vhost->conn_stats.tx += len;
253 #endif
254 #if defined(LWS_WITH_DETAILED_LATENCY)
255 	us = lws_now_usecs();
256 #endif
257 
258 	assert(wsi->role_ops);
259 	if (!wsi->role_ops->write_role_protocol)
260 		return lws_issue_raw(wsi, buf, len);
261 
262 	m = wsi->role_ops->write_role_protocol(wsi, buf, len, &wp);
263 	if (m < 0)
264 		return m;
265 
266 #if defined(LWS_WITH_DETAILED_LATENCY)
267 	if (wsi->context->detailed_latency_cb) {
268 		wsi->detlat.req_size = len;
269 		wsi->detlat.acc_size = m;
270 		wsi->detlat.type = LDLT_WRITE;
271 		if (wsi->detlat.earliest_write_req_pre_write)
272 			wsi->detlat.latencies[LAT_DUR_PROXY_PROXY_REQ_TO_WRITE] =
273 					us - wsi->detlat.earliest_write_req_pre_write;
274 		else
275 			wsi->detlat.latencies[LAT_DUR_PROXY_PROXY_REQ_TO_WRITE] = 0;
276 		wsi->detlat.latencies[LAT_DUR_USERCB] = lws_now_usecs() - us;
277 		lws_det_lat_cb(wsi->context, &wsi->detlat);
278 
279 	}
280 #endif
281 
282 	return m;
283 }
284 
285 int
lws_ssl_capable_read_no_ssl(struct lws * wsi,unsigned char * buf,int len)286 lws_ssl_capable_read_no_ssl(struct lws *wsi, unsigned char *buf, int len)
287 {
288 	struct lws_context *context = wsi->context;
289 	struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
290 	int n = 0;
291 
292 	lws_stats_bump(pt, LWSSTATS_C_API_READ, 1);
293 
294 	errno = 0;
295 #if defined(LWS_WITH_UDP)
296 	if (lws_wsi_is_udp(wsi)) {
297 		wsi->udp->salen = sizeof(wsi->udp->sa);
298 		n = recvfrom(wsi->desc.sockfd, (char *)buf, len, 0,
299 			     &wsi->udp->sa, &wsi->udp->salen);
300 	} else
301 #endif
302 		n = recv(wsi->desc.sockfd, (char *)buf, len, 0);
303 
304 	if (n >= 0) {
305 
306 		if (!n && wsi->unix_skt)
307 			return LWS_SSL_CAPABLE_ERROR;
308 
309 		/*
310 		 * See https://libwebsockets.org/
311 		 * pipermail/libwebsockets/2019-March/007857.html
312 		 */
313 		if (!n)
314 			return LWS_SSL_CAPABLE_ERROR;
315 
316 #if defined(LWS_WITH_SERVER_STATUS)
317 		if (wsi->vhost)
318 			wsi->vhost->conn_stats.rx += n;
319 #endif
320 		lws_stats_bump(pt, LWSSTATS_B_READ, n);
321 
322 		return n;
323 	}
324 
325 	if (LWS_ERRNO == LWS_EAGAIN ||
326 	    LWS_ERRNO == LWS_EWOULDBLOCK ||
327 	    LWS_ERRNO == LWS_EINTR)
328 		return LWS_SSL_CAPABLE_MORE_SERVICE;
329 
330 	lwsl_info("error on reading from skt : %d\n", LWS_ERRNO);
331 	return LWS_SSL_CAPABLE_ERROR;
332 }
333 
334 int
lws_ssl_capable_write_no_ssl(struct lws * wsi,unsigned char * buf,int len)335 lws_ssl_capable_write_no_ssl(struct lws *wsi, unsigned char *buf, int len)
336 {
337 	int n = 0;
338 #if defined(LWS_PLAT_OPTEE)
339 	ssize_t send(int sockfd, const void *buf, size_t len, int flags);
340 #endif
341 
342 #if defined(LWS_WITH_UDP)
343 	if (lws_wsi_is_udp(wsi)) {
344 		if (wsi->context->udp_loss_sim_tx_pc) {
345 			uint16_t u16;
346 			/*
347 			 * We should randomly drop some of these
348 			 */
349 
350 			if (lws_get_random(wsi->context, &u16, 2) == 2 &&
351 			    ((u16 * 100) / 0xffff) <=
352 				    wsi->context->udp_loss_sim_tx_pc) {
353 				lwsl_warn("%s: dropping udp tx\n", __func__);
354 				/* pretend it was sent */
355 				n = len;
356 				goto post_send;
357 			}
358 		}
359 		if (lws_has_buffered_out(wsi))
360 			n = sendto(wsi->desc.sockfd, (const char *)buf,
361 				   len, 0, &wsi->udp->sa_pending,
362 				   wsi->udp->salen_pending);
363 		else
364 			n = sendto(wsi->desc.sockfd, (const char *)buf,
365 				   len, 0, &wsi->udp->sa, wsi->udp->salen);
366 	} else
367 #endif
368 		if (wsi->role_ops->file_handle)
369 			n = write((int)(long long)wsi->desc.filefd, buf, len);
370 		else
371 			n = send(wsi->desc.sockfd, (char *)buf, len, MSG_NOSIGNAL);
372 //	lwsl_info("%s: sent len %d result %d", __func__, len, n);
373 
374 #if defined(LWS_WITH_UDP)
375 post_send:
376 #endif
377 	if (n >= 0)
378 		return n;
379 
380 	if (LWS_ERRNO == LWS_EAGAIN ||
381 	    LWS_ERRNO == LWS_EWOULDBLOCK ||
382 	    LWS_ERRNO == LWS_EINTR) {
383 		if (LWS_ERRNO == LWS_EWOULDBLOCK) {
384 			lws_set_blocking_send(wsi);
385 		}
386 
387 		return LWS_SSL_CAPABLE_MORE_SERVICE;
388 	}
389 
390 	lwsl_debug("ERROR writing len %d to skt fd %d err %d / errno %d\n",
391 		   len, wsi->desc.sockfd, n, LWS_ERRNO);
392 
393 	return LWS_SSL_CAPABLE_ERROR;
394 }
395 
396 int
lws_ssl_pending_no_ssl(struct lws * wsi)397 lws_ssl_pending_no_ssl(struct lws *wsi)
398 {
399 	(void)wsi;
400 #if defined(LWS_PLAT_FREERTOS)
401 	return 100;
402 #else
403 	return 0;
404 #endif
405 }
406