1
0
Fork 0
mirror of https://github.com/warmcat/libwebsockets.git synced 2025-03-09 00:00:04 +01:00
libwebsockets/lib/core-net/output.c

386 lines
9.7 KiB
C
Raw Permalink Normal View History

/*
* libwebsockets - small server side websockets and web server implementation
*
* Copyright (C) 2010 - 2019 Andy Green <andy@warmcat.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "private-lib-core.h"
/*
add explicit error for partial send This patch adds code to handle the situation that a prepared user buffer could not all be sent on the socket at once. There are two kinds of situation to handle 1) User code handles it: The connection only has extensions active that do not rewrite the buffer. In this case, the patch caused libwebsocket_write() to simply return the amount of user buffer that was consumed (this is specifically the amount of user buffer used in sending what was accepted, nothing else). So user code can just advance its buffer that much and resume sending when the socket is writable again. This continues the frame rather than starting a new one or new fragment. 2) The connections has extensions active which actually send something quite different than what the user buffer contains, for example a compression extension. In this case, libwebsockets will dynamically malloc a buffer to contain a copy of the remaining unsent data, request notifiction when writeable again, and automatically spill and free this buffer with the highest priority before passing on the writable notification to anything else. For this situation, the call to write will return that it used the whole user buffer, even though part is still rebuffered. This patch should enable libwebsockets to detect the two cases and take the appropriate action. There are also two choices for user code to deal with partial sends. 1) Leave the no_buffer_all_partial_tx member in the protocol struct at zero. The library will dyamically buffer anything you send that did not get completely written to the socket, and automatically spill it next time the socket is writable. You can use this method if your sent frames are relatvely small and unlikely to get truncated anyway. 2) Set the no_buffer_all_partial_tx member in the protocol struct. User code now needs to take care of the return value from libwebsocket_write() and deal with resending the remainder if not all of the requested amount got sent. You should use this method if you are sending large messages and want to maximize throughput and efficiency. Since the new member no_buffer_all_partial_tx will be zero by default, this patch will auto-rebuffer any partial sends by default. That's good for most cases but if you attempt to send large blocks, make sure you follow option 2) above. Signed-off-by: Andy Green <andy.green@linaro.org>
2013-10-17 08:09:19 +08:00
* notice this returns number of bytes consumed, or -1
*/
int
lws_issue_raw(struct lws *wsi, unsigned char *buf, size_t len)
{
struct lws_context *context = lws_get_context(wsi);
size_t real_len = len;
2018-09-02 14:35:37 +08:00
unsigned int n, m;
/*
* If you're looking to dump data being sent down the tls tunnel, see
* lws_ssl_capable_write() in lib/tls/mbedtls/mbedtls-ssl.c or
* lib/tls/openssl/openssl-ssl.c.
*
* There's also a corresponding lws_ssl_capable_read() in those files
* where you can enable a dump of decrypted data as soon as it was
* read.
*/
/* just ignore sends after we cleared the truncation buffer */
if (lwsi_state(wsi) == LRS_FLUSHING_BEFORE_CLOSE &&
http: compression methods Add generic http compression layer eanbled at cmake with LWS_WITH_HTTP_STREAM_COMPRESSION. This is wholly a feature of the HTTP role (used by h1 and h2 roles) and doesn't exist outside that context. Currently provides 'deflate' and 'br' compression methods for server side only. 'br' requires also -DLWS_WITH_HTTP_BROTLI=1 at cmake and the brotli libraries (available in your distro already) and dev package. Other compression methods can be added nicely using an ops struct. The built-in file serving stuff will use this is the client says he can handle it, and the mimetype of the file either starts with "text/" (html and css etc) or is the mimetype of Javascript. zlib allocates quite a bit while in use, it seems to be around 256KiB per stream. So this is only useful on relatively strong servers with lots of memory. However for some usecases where you are serving a lot of css and js assets, it's a nice help. The patch performs special treatment for http/1.1 pipelining, since the compression is performed on the fly the compressed content-length is not known until the end. So for h1 only, chunked transfer-encoding is automatically added so pipelining can continue of the connection. For h2 the chunking is neither supported nor required, so it "just works". User code can also request to add a compression transform before the reply headers were sent using the new api LWS_VISIBLE int lws_http_compression_apply(struct lws *wsi, const char *name, unsigned char **p, unsigned char *end, char decomp); ... this allows transparent compression of dynamically generated HTTP. The requested compression (eg, "deflate") is only applied if the client headers indicated it was supported, otherwise it's a NOP. Name may be NULL in which case the first compression method in the internal table at stream.c that is mentioned as acceptable by the client will be used. NOTE: the compression translation, same as h2 support, relies on the user code using LWS_WRITE_HTTP and then LWS_WRITE_HTTP_FINAL on the last part written. The internal lws fileserving code already does this.
2018-09-02 14:43:05 +08:00
!lws_has_buffered_out(wsi)
#if defined(LWS_WITH_HTTP_STREAM_COMPRESSION)
&& !wsi->http.comp_ctx.may_have_more
#endif
)
return (int)len;
if (buf && lws_has_buffered_out(wsi)) {
lwsl_wsi_info(wsi, "** prot: %s, incr buflist_out by %lu",
wsi->a.protocol->name, (unsigned long)len);
/*
* already buflist ahead of this, add it on the tail of the
* buflist, then ignore it for now and act like we're flushing
* the buflist...
*/
2018-12-13 20:05:12 +08:00
if (lws_buflist_append_segment(&wsi->buflist_out, buf, len))
return -1;
buf = NULL;
len = 0;
}
if (wsi->buflist_out) {
/* we have to drain the earliest buflist_out stuff first */
len = lws_buflist_next_segment_len(&wsi->buflist_out, &buf);
real_len = len;
http: compression methods Add generic http compression layer eanbled at cmake with LWS_WITH_HTTP_STREAM_COMPRESSION. This is wholly a feature of the HTTP role (used by h1 and h2 roles) and doesn't exist outside that context. Currently provides 'deflate' and 'br' compression methods for server side only. 'br' requires also -DLWS_WITH_HTTP_BROTLI=1 at cmake and the brotli libraries (available in your distro already) and dev package. Other compression methods can be added nicely using an ops struct. The built-in file serving stuff will use this is the client says he can handle it, and the mimetype of the file either starts with "text/" (html and css etc) or is the mimetype of Javascript. zlib allocates quite a bit while in use, it seems to be around 256KiB per stream. So this is only useful on relatively strong servers with lots of memory. However for some usecases where you are serving a lot of css and js assets, it's a nice help. The patch performs special treatment for http/1.1 pipelining, since the compression is performed on the fly the compressed content-length is not known until the end. So for h1 only, chunked transfer-encoding is automatically added so pipelining can continue of the connection. For h2 the chunking is neither supported nor required, so it "just works". User code can also request to add a compression transform before the reply headers were sent using the new api LWS_VISIBLE int lws_http_compression_apply(struct lws *wsi, const char *name, unsigned char **p, unsigned char *end, char decomp); ... this allows transparent compression of dynamically generated HTTP. The requested compression (eg, "deflate") is only applied if the client headers indicated it was supported, otherwise it's a NOP. Name may be NULL in which case the first compression method in the internal table at stream.c that is mentioned as acceptable by the client will be used. NOTE: the compression translation, same as h2 support, relies on the user code using LWS_WRITE_HTTP and then LWS_WRITE_HTTP_FINAL on the last part written. The internal lws fileserving code already does this.
2018-09-02 14:43:05 +08:00
lwsl_wsi_debug(wsi, "draining %d", (int)len);
}
2018-08-23 11:48:17 +08:00
if (!len || !buf)
return 0;
if (!wsi->mux_substream && !lws_socket_is_valid(wsi->desc.sockfd))
lwsl_wsi_err(wsi, "invalid sock");
/* limit sending */
fakewsi: replace with smaller substructure Currently we always reserve a fakewsi per pt so events that don't have a related actual wsi, like vhost-protocol-init or vhost cert init via protocol callback can make callbacks that look reasonable to user protocol handler code expecting a valid wsi every time. This patch splits out stuff that user callbacks often unconditionally expect to be in a wsi, like context pointer, vhost pointer etc into a substructure, which is composed into struct lws at the top of it. Internal references (struct lws is opaque, so there are only internal references) are all updated to go via the substructre, the compiler should make that a NOP. Helpers are added when fakewsi is used and referenced. If not PLAT_FREERTOS, we continue to provide a full fakewsi in the pt as before, although the helpers improve consistency by zeroing down the substructure. There is a huge amount of user code out there over the last 10 years that did not always have the minimal examples to follow, some of it does some unexpected things. If it is PLAT_FREERTOS, that is a newer thing in lws and users have the benefit of being able to follow the minimal examples' approach. For PLAT_FREERTOS we don't reserve the fakewsi in the pt any more, saving around 800 bytes. The helpers then create a struct lws_a (the substructure) on the stack, zero it down (but it is only like 4 pointers) and prepare it with whatever we know like the context. Then we cast it to a struct lws * and use it in the user protocol handler call. In this case, the remainder of the struct lws is undefined. However the amount of old protocol handlers that might touch things outside of the substructure in PLAT_FREERTOS is very limited compared to legacy lws user code and the saving is significant on constrained devices. User handlers should not be touching everything in a wsi every time anyway, there are several cases where there is no valid wsi to do the call with. Dereference of things outside the substructure should only happen when the callback reason shows there is a valid wsi bound to the activity (as in all the minimal examples).
2020-07-19 08:33:46 +01:00
if (wsi->a.protocol->tx_packet_size)
n = (unsigned int)wsi->a.protocol->tx_packet_size;
2017-03-16 10:46:31 +08:00
else {
n = (unsigned int)wsi->a.protocol->rx_buffer_size;
2017-03-16 10:46:31 +08:00
if (!n)
n = context->pt_serv_buf_size;
}
n += LWS_PRE + 4;
if (n > len)
n = (unsigned int)len;
2016-03-18 15:02:27 +08:00
/* nope, send it on the socket directly */
2018-09-02 14:35:37 +08:00
if (lws_fi(&wsi->fic, "sendfail"))
m = (unsigned int)LWS_SSL_CAPABLE_ERROR;
else
m = (unsigned int)lws_ssl_capable_write(wsi, buf, n);
2021-06-18 07:28:23 +01:00
lwsl_wsi_info(wsi, "ssl_capable_write (%d) says %d", n, m);
/* something got written, it can have been truncated now */
wsi->could_have_pending = 1;
switch ((int)m) {
case LWS_SSL_CAPABLE_ERROR:
/* we're going to close, let close know sends aren't possible */
wsi->socket_is_permanently_unusable = 1;
return -1;
case LWS_SSL_CAPABLE_MORE_SERVICE:
/*
* nothing got sent, not fatal. Retry the whole thing later,
* ie, implying treat it was a truncated send so it gets
* retried
*/
2018-09-02 14:35:37 +08:00
m = 0;
break;
}
if ((int)m < 0)
m = 0;
add explicit error for partial send This patch adds code to handle the situation that a prepared user buffer could not all be sent on the socket at once. There are two kinds of situation to handle 1) User code handles it: The connection only has extensions active that do not rewrite the buffer. In this case, the patch caused libwebsocket_write() to simply return the amount of user buffer that was consumed (this is specifically the amount of user buffer used in sending what was accepted, nothing else). So user code can just advance its buffer that much and resume sending when the socket is writable again. This continues the frame rather than starting a new one or new fragment. 2) The connections has extensions active which actually send something quite different than what the user buffer contains, for example a compression extension. In this case, libwebsockets will dynamically malloc a buffer to contain a copy of the remaining unsent data, request notifiction when writeable again, and automatically spill and free this buffer with the highest priority before passing on the writable notification to anything else. For this situation, the call to write will return that it used the whole user buffer, even though part is still rebuffered. This patch should enable libwebsockets to detect the two cases and take the appropriate action. There are also two choices for user code to deal with partial sends. 1) Leave the no_buffer_all_partial_tx member in the protocol struct at zero. The library will dyamically buffer anything you send that did not get completely written to the socket, and automatically spill it next time the socket is writable. You can use this method if your sent frames are relatvely small and unlikely to get truncated anyway. 2) Set the no_buffer_all_partial_tx member in the protocol struct. User code now needs to take care of the return value from libwebsocket_write() and deal with resending the remainder if not all of the requested amount got sent. You should use this method if you are sending large messages and want to maximize throughput and efficiency. Since the new member no_buffer_all_partial_tx will be zero by default, this patch will auto-rebuffer any partial sends by default. That's good for most cases but if you attempt to send large blocks, make sure you follow option 2) above. Signed-off-by: Andy Green <andy.green@linaro.org>
2013-10-17 08:09:19 +08:00
/*
* we were sending this from buflist_out? Then not sending everything
* is a small matter of advancing ourselves only by the amount we did
* send in the buflist.
add explicit error for partial send This patch adds code to handle the situation that a prepared user buffer could not all be sent on the socket at once. There are two kinds of situation to handle 1) User code handles it: The connection only has extensions active that do not rewrite the buffer. In this case, the patch caused libwebsocket_write() to simply return the amount of user buffer that was consumed (this is specifically the amount of user buffer used in sending what was accepted, nothing else). So user code can just advance its buffer that much and resume sending when the socket is writable again. This continues the frame rather than starting a new one or new fragment. 2) The connections has extensions active which actually send something quite different than what the user buffer contains, for example a compression extension. In this case, libwebsockets will dynamically malloc a buffer to contain a copy of the remaining unsent data, request notifiction when writeable again, and automatically spill and free this buffer with the highest priority before passing on the writable notification to anything else. For this situation, the call to write will return that it used the whole user buffer, even though part is still rebuffered. This patch should enable libwebsockets to detect the two cases and take the appropriate action. There are also two choices for user code to deal with partial sends. 1) Leave the no_buffer_all_partial_tx member in the protocol struct at zero. The library will dyamically buffer anything you send that did not get completely written to the socket, and automatically spill it next time the socket is writable. You can use this method if your sent frames are relatvely small and unlikely to get truncated anyway. 2) Set the no_buffer_all_partial_tx member in the protocol struct. User code now needs to take care of the return value from libwebsocket_write() and deal with resending the remainder if not all of the requested amount got sent. You should use this method if you are sending large messages and want to maximize throughput and efficiency. Since the new member no_buffer_all_partial_tx will be zero by default, this patch will auto-rebuffer any partial sends by default. That's good for most cases but if you attempt to send large blocks, make sure you follow option 2) above. Signed-off-by: Andy Green <andy.green@linaro.org>
2013-10-17 08:09:19 +08:00
*/
if (lws_has_buffered_out(wsi)) {
2018-09-02 14:35:37 +08:00
if (m) {
lwsl_wsi_info(wsi, "partial adv %d (vs %ld)",
m, (long)real_len);
2018-09-02 14:35:37 +08:00
lws_buflist_use_segment(&wsi->buflist_out, m);
}
if (!lws_has_buffered_out(wsi)) {
lwsl_wsi_info(wsi, "buflist_out flushed");
m = (unsigned int)real_len;
if (lwsi_state(wsi) == LRS_FLUSHING_BEFORE_CLOSE) {
lwsl_wsi_info(wsi, "*signalling to close now");
return -1; /* retry closing now */
}
if (wsi->close_when_buffered_out_drained) {
wsi->close_when_buffered_out_drained = 0;
return -1;
}
#if defined(LWS_ROLE_H1) || defined(LWS_ROLE_H2)
#if defined(LWS_WITH_SERVER)
if (wsi->http.deferred_transaction_completed) {
lwsl_wsi_notice(wsi, "partial completed, doing "
"deferred transaction completed");
wsi->http.deferred_transaction_completed = 0;
return lws_http_transaction_completed(wsi) ?
-1 : (int)real_len;
}
#endif
#endif
#if defined(LWS_ROLE_WS)
/* Since buflist_out flushed, we're not inside a frame any more */
if (wsi->ws)
wsi->ws->inside_frame = 0;
#endif
}
/* always callback on writeable */
lws_callback_on_writable(wsi);
add explicit error for partial send This patch adds code to handle the situation that a prepared user buffer could not all be sent on the socket at once. There are two kinds of situation to handle 1) User code handles it: The connection only has extensions active that do not rewrite the buffer. In this case, the patch caused libwebsocket_write() to simply return the amount of user buffer that was consumed (this is specifically the amount of user buffer used in sending what was accepted, nothing else). So user code can just advance its buffer that much and resume sending when the socket is writable again. This continues the frame rather than starting a new one or new fragment. 2) The connections has extensions active which actually send something quite different than what the user buffer contains, for example a compression extension. In this case, libwebsockets will dynamically malloc a buffer to contain a copy of the remaining unsent data, request notifiction when writeable again, and automatically spill and free this buffer with the highest priority before passing on the writable notification to anything else. For this situation, the call to write will return that it used the whole user buffer, even though part is still rebuffered. This patch should enable libwebsockets to detect the two cases and take the appropriate action. There are also two choices for user code to deal with partial sends. 1) Leave the no_buffer_all_partial_tx member in the protocol struct at zero. The library will dyamically buffer anything you send that did not get completely written to the socket, and automatically spill it next time the socket is writable. You can use this method if your sent frames are relatvely small and unlikely to get truncated anyway. 2) Set the no_buffer_all_partial_tx member in the protocol struct. User code now needs to take care of the return value from libwebsocket_write() and deal with resending the remainder if not all of the requested amount got sent. You should use this method if you are sending large messages and want to maximize throughput and efficiency. Since the new member no_buffer_all_partial_tx will be zero by default, this patch will auto-rebuffer any partial sends by default. That's good for most cases but if you attempt to send large blocks, make sure you follow option 2) above. Signed-off-by: Andy Green <andy.green@linaro.org>
2013-10-17 08:09:19 +08:00
return (int)m;
add explicit error for partial send This patch adds code to handle the situation that a prepared user buffer could not all be sent on the socket at once. There are two kinds of situation to handle 1) User code handles it: The connection only has extensions active that do not rewrite the buffer. In this case, the patch caused libwebsocket_write() to simply return the amount of user buffer that was consumed (this is specifically the amount of user buffer used in sending what was accepted, nothing else). So user code can just advance its buffer that much and resume sending when the socket is writable again. This continues the frame rather than starting a new one or new fragment. 2) The connections has extensions active which actually send something quite different than what the user buffer contains, for example a compression extension. In this case, libwebsockets will dynamically malloc a buffer to contain a copy of the remaining unsent data, request notifiction when writeable again, and automatically spill and free this buffer with the highest priority before passing on the writable notification to anything else. For this situation, the call to write will return that it used the whole user buffer, even though part is still rebuffered. This patch should enable libwebsockets to detect the two cases and take the appropriate action. There are also two choices for user code to deal with partial sends. 1) Leave the no_buffer_all_partial_tx member in the protocol struct at zero. The library will dyamically buffer anything you send that did not get completely written to the socket, and automatically spill it next time the socket is writable. You can use this method if your sent frames are relatvely small and unlikely to get truncated anyway. 2) Set the no_buffer_all_partial_tx member in the protocol struct. User code now needs to take care of the return value from libwebsocket_write() and deal with resending the remainder if not all of the requested amount got sent. You should use this method if you are sending large messages and want to maximize throughput and efficiency. Since the new member no_buffer_all_partial_tx will be zero by default, this patch will auto-rebuffer any partial sends by default. That's good for most cases but if you attempt to send large blocks, make sure you follow option 2) above. Signed-off-by: Andy Green <andy.green@linaro.org>
2013-10-17 08:09:19 +08:00
}
http: compression methods Add generic http compression layer eanbled at cmake with LWS_WITH_HTTP_STREAM_COMPRESSION. This is wholly a feature of the HTTP role (used by h1 and h2 roles) and doesn't exist outside that context. Currently provides 'deflate' and 'br' compression methods for server side only. 'br' requires also -DLWS_WITH_HTTP_BROTLI=1 at cmake and the brotli libraries (available in your distro already) and dev package. Other compression methods can be added nicely using an ops struct. The built-in file serving stuff will use this is the client says he can handle it, and the mimetype of the file either starts with "text/" (html and css etc) or is the mimetype of Javascript. zlib allocates quite a bit while in use, it seems to be around 256KiB per stream. So this is only useful on relatively strong servers with lots of memory. However for some usecases where you are serving a lot of css and js assets, it's a nice help. The patch performs special treatment for http/1.1 pipelining, since the compression is performed on the fly the compressed content-length is not known until the end. So for h1 only, chunked transfer-encoding is automatically added so pipelining can continue of the connection. For h2 the chunking is neither supported nor required, so it "just works". User code can also request to add a compression transform before the reply headers were sent using the new api LWS_VISIBLE int lws_http_compression_apply(struct lws *wsi, const char *name, unsigned char **p, unsigned char *end, char decomp); ... this allows transparent compression of dynamically generated HTTP. The requested compression (eg, "deflate") is only applied if the client headers indicated it was supported, otherwise it's a NOP. Name may be NULL in which case the first compression method in the internal table at stream.c that is mentioned as acceptable by the client will be used. NOTE: the compression translation, same as h2 support, relies on the user code using LWS_WRITE_HTTP and then LWS_WRITE_HTTP_FINAL on the last part written. The internal lws fileserving code already does this.
2018-09-02 14:43:05 +08:00
#if defined(LWS_WITH_HTTP_STREAM_COMPRESSION)
if (wsi->http.comp_ctx.may_have_more)
lws_callback_on_writable(wsi);
#endif
2018-09-02 14:35:37 +08:00
if (m == real_len)
/* what we just sent went out cleanly */
return (int)m;
add explicit error for partial send This patch adds code to handle the situation that a prepared user buffer could not all be sent on the socket at once. There are two kinds of situation to handle 1) User code handles it: The connection only has extensions active that do not rewrite the buffer. In this case, the patch caused libwebsocket_write() to simply return the amount of user buffer that was consumed (this is specifically the amount of user buffer used in sending what was accepted, nothing else). So user code can just advance its buffer that much and resume sending when the socket is writable again. This continues the frame rather than starting a new one or new fragment. 2) The connections has extensions active which actually send something quite different than what the user buffer contains, for example a compression extension. In this case, libwebsockets will dynamically malloc a buffer to contain a copy of the remaining unsent data, request notifiction when writeable again, and automatically spill and free this buffer with the highest priority before passing on the writable notification to anything else. For this situation, the call to write will return that it used the whole user buffer, even though part is still rebuffered. This patch should enable libwebsockets to detect the two cases and take the appropriate action. There are also two choices for user code to deal with partial sends. 1) Leave the no_buffer_all_partial_tx member in the protocol struct at zero. The library will dyamically buffer anything you send that did not get completely written to the socket, and automatically spill it next time the socket is writable. You can use this method if your sent frames are relatvely small and unlikely to get truncated anyway. 2) Set the no_buffer_all_partial_tx member in the protocol struct. User code now needs to take care of the return value from libwebsocket_write() and deal with resending the remainder if not all of the requested amount got sent. You should use this method if you are sending large messages and want to maximize throughput and efficiency. Since the new member no_buffer_all_partial_tx will be zero by default, this patch will auto-rebuffer any partial sends by default. That's good for most cases but if you attempt to send large blocks, make sure you follow option 2) above. Signed-off-by: Andy Green <andy.green@linaro.org>
2013-10-17 08:09:19 +08:00
/*
* We were not able to send everything... and we were not sending from
* an existing buflist_out. So we are starting a fresh buflist_out, by
* buffering the unsent remainder on it.
* (it will get first priority next time the socket is writable).
*/
lwsl_wsi_debug(wsi, "new partial sent %d from %lu total",
m, (unsigned long)real_len);
add explicit error for partial send This patch adds code to handle the situation that a prepared user buffer could not all be sent on the socket at once. There are two kinds of situation to handle 1) User code handles it: The connection only has extensions active that do not rewrite the buffer. In this case, the patch caused libwebsocket_write() to simply return the amount of user buffer that was consumed (this is specifically the amount of user buffer used in sending what was accepted, nothing else). So user code can just advance its buffer that much and resume sending when the socket is writable again. This continues the frame rather than starting a new one or new fragment. 2) The connections has extensions active which actually send something quite different than what the user buffer contains, for example a compression extension. In this case, libwebsockets will dynamically malloc a buffer to contain a copy of the remaining unsent data, request notifiction when writeable again, and automatically spill and free this buffer with the highest priority before passing on the writable notification to anything else. For this situation, the call to write will return that it used the whole user buffer, even though part is still rebuffered. This patch should enable libwebsockets to detect the two cases and take the appropriate action. There are also two choices for user code to deal with partial sends. 1) Leave the no_buffer_all_partial_tx member in the protocol struct at zero. The library will dyamically buffer anything you send that did not get completely written to the socket, and automatically spill it next time the socket is writable. You can use this method if your sent frames are relatvely small and unlikely to get truncated anyway. 2) Set the no_buffer_all_partial_tx member in the protocol struct. User code now needs to take care of the return value from libwebsocket_write() and deal with resending the remainder if not all of the requested amount got sent. You should use this method if you are sending large messages and want to maximize throughput and efficiency. Since the new member no_buffer_all_partial_tx will be zero by default, this patch will auto-rebuffer any partial sends by default. That's good for most cases but if you attempt to send large blocks, make sure you follow option 2) above. Signed-off-by: Andy Green <andy.green@linaro.org>
2013-10-17 08:09:19 +08:00
if (lws_buflist_append_segment(&wsi->buflist_out, buf + m,
real_len - m) < 0)
return -1;
2019-09-30 09:42:38 -07:00
#if defined(LWS_WITH_UDP)
if (lws_wsi_is_udp(wsi))
2018-03-24 08:07:00 +08:00
/* stash original destination for fulfilling UDP partials */
wsi->udp->sa46_pending = wsi->udp->sa46;
#endif
2018-03-24 08:07:00 +08:00
/* since something buffered, force it to get another chance to send */
lws_callback_on_writable(wsi);
add explicit error for partial send This patch adds code to handle the situation that a prepared user buffer could not all be sent on the socket at once. There are two kinds of situation to handle 1) User code handles it: The connection only has extensions active that do not rewrite the buffer. In this case, the patch caused libwebsocket_write() to simply return the amount of user buffer that was consumed (this is specifically the amount of user buffer used in sending what was accepted, nothing else). So user code can just advance its buffer that much and resume sending when the socket is writable again. This continues the frame rather than starting a new one or new fragment. 2) The connections has extensions active which actually send something quite different than what the user buffer contains, for example a compression extension. In this case, libwebsockets will dynamically malloc a buffer to contain a copy of the remaining unsent data, request notifiction when writeable again, and automatically spill and free this buffer with the highest priority before passing on the writable notification to anything else. For this situation, the call to write will return that it used the whole user buffer, even though part is still rebuffered. This patch should enable libwebsockets to detect the two cases and take the appropriate action. There are also two choices for user code to deal with partial sends. 1) Leave the no_buffer_all_partial_tx member in the protocol struct at zero. The library will dyamically buffer anything you send that did not get completely written to the socket, and automatically spill it next time the socket is writable. You can use this method if your sent frames are relatvely small and unlikely to get truncated anyway. 2) Set the no_buffer_all_partial_tx member in the protocol struct. User code now needs to take care of the return value from libwebsocket_write() and deal with resending the remainder if not all of the requested amount got sent. You should use this method if you are sending large messages and want to maximize throughput and efficiency. Since the new member no_buffer_all_partial_tx will be zero by default, this patch will auto-rebuffer any partial sends by default. That's good for most cases but if you attempt to send large blocks, make sure you follow option 2) above. Signed-off-by: Andy Green <andy.green@linaro.org>
2013-10-17 08:09:19 +08:00
return (int)real_len;
}
int
lws_write(struct lws *wsi, unsigned char *buf, size_t len,
enum lws_write_protocol wp)
{
int m;
if ((int)len < 0) {
lwsl_wsi_err(wsi, "suspicious len int %d, ulong %lu",
(int)len, (unsigned long)len);
return -1;
}
#ifdef LWS_WITH_ACCESS_LOG
wsi->http.access_log.sent += len;
#endif
assert(wsi->role_ops);
if (!lws_rops_fidx(wsi->role_ops, LWS_ROPS_write_role_protocol))
m = lws_issue_raw(wsi, buf, len);
else
m = lws_rops_func_fidx(wsi->role_ops, LWS_ROPS_write_role_protocol).
write_role_protocol(wsi, buf, len, &wp);
#if defined(LWS_WITH_SYS_METRICS)
if (wsi->a.vhost)
lws_metric_event(wsi->a.vhost->mt_traffic_tx, (char)
(m < 0 ? METRES_NOGO : METRES_GO), len);
#endif
return m;
}
int
lws_ssl_capable_read_no_ssl(struct lws *wsi, unsigned char *buf, size_t len)
{
int n = 0, en;
2017-05-07 10:02:03 +08:00
errno = 0;
2019-09-30 09:42:38 -07:00
#if defined(LWS_WITH_UDP)
2018-03-24 08:07:00 +08:00
if (lws_wsi_is_udp(wsi)) {
socklen_t slt = sizeof(wsi->udp->sa46);
n = (int)recvfrom(wsi->desc.sockfd, (char *)buf,
#if defined(WIN32)
(int)
#endif
len, 0,
sa46_sockaddr(&wsi->udp->sa46), &slt);
2018-03-24 08:07:00 +08:00
} else
2019-09-30 09:42:38 -07:00
#endif
n = (int)recv(wsi->desc.sockfd, (char *)buf,
#if defined(WIN32)
(int)
#endif
len, 0);
en = LWS_ERRNO;
if (n >= 0) {
if (!n && wsi->unix_skt)
goto do_err;
/*
* See https://libwebsockets.org/
* pipermail/libwebsockets/2019-March/007857.html
*/
if (!n && !wsi->unix_skt)
goto do_err;
#if defined(LWS_WITH_SYS_METRICS) && defined(LWS_WITH_SERVER)
fakewsi: replace with smaller substructure Currently we always reserve a fakewsi per pt so events that don't have a related actual wsi, like vhost-protocol-init or vhost cert init via protocol callback can make callbacks that look reasonable to user protocol handler code expecting a valid wsi every time. This patch splits out stuff that user callbacks often unconditionally expect to be in a wsi, like context pointer, vhost pointer etc into a substructure, which is composed into struct lws at the top of it. Internal references (struct lws is opaque, so there are only internal references) are all updated to go via the substructre, the compiler should make that a NOP. Helpers are added when fakewsi is used and referenced. If not PLAT_FREERTOS, we continue to provide a full fakewsi in the pt as before, although the helpers improve consistency by zeroing down the substructure. There is a huge amount of user code out there over the last 10 years that did not always have the minimal examples to follow, some of it does some unexpected things. If it is PLAT_FREERTOS, that is a newer thing in lws and users have the benefit of being able to follow the minimal examples' approach. For PLAT_FREERTOS we don't reserve the fakewsi in the pt any more, saving around 800 bytes. The helpers then create a struct lws_a (the substructure) on the stack, zero it down (but it is only like 4 pointers) and prepare it with whatever we know like the context. Then we cast it to a struct lws * and use it in the user protocol handler call. In this case, the remainder of the struct lws is undefined. However the amount of old protocol handlers that might touch things outside of the substructure in PLAT_FREERTOS is very limited compared to legacy lws user code and the saving is significant on constrained devices. User handlers should not be touching everything in a wsi every time anyway, there are several cases where there is no valid wsi to do the call with. Dereference of things outside the substructure should only happen when the callback reason shows there is a valid wsi bound to the activity (as in all the minimal examples).
2020-07-19 08:33:46 +01:00
if (wsi->a.vhost)
lws_metric_event(wsi->a.vhost->mt_traffic_rx,
METRES_GO /* rx */, (unsigned int)n);
#endif
2018-03-24 08:07:00 +08:00
return n;
}
if (en == LWS_EAGAIN ||
en == LWS_EWOULDBLOCK ||
en == LWS_EINTR)
return LWS_SSL_CAPABLE_MORE_SERVICE;
do_err:
#if defined(LWS_WITH_SYS_METRICS) && defined(LWS_WITH_SERVER)
if (wsi->a.vhost)
lws_metric_event(wsi->a.vhost->mt_traffic_rx, METRES_NOGO, 0u);
#endif
lwsl_wsi_info(wsi, "error on reading from skt : %d, errno %d", n, en);
return LWS_SSL_CAPABLE_ERROR;
}
int
lws_ssl_capable_write_no_ssl(struct lws *wsi, unsigned char *buf, size_t len)
{
int n = 0;
2019-01-11 17:14:04 +08:00
#if defined(LWS_PLAT_OPTEE)
ssize_t send(int sockfd, const void *buf, size_t len, int flags);
2019-01-11 17:14:04 +08:00
#endif
2019-09-30 09:42:38 -07:00
#if defined(LWS_WITH_UDP)
2018-03-24 08:07:00 +08:00
if (lws_wsi_is_udp(wsi)) {
if (lws_fi(&wsi->fic, "udp_tx_loss")) {
/* pretend it was sent */
n = (int)(ssize_t)len;
goto post_send;
2019-09-08 08:08:55 +01:00
}
if (lws_has_buffered_out(wsi))
n = (int)sendto(wsi->desc.sockfd, (const char *)buf,
#if defined(WIN32)
(int)
#endif
len, 0, sa46_sockaddr(&wsi->udp->sa46_pending),
sa46_socklen(&wsi->udp->sa46_pending));
2018-03-24 08:07:00 +08:00
else
n = (int)sendto(wsi->desc.sockfd, (const char *)buf,
#if defined(WIN32)
(int)
#endif
len, 0, sa46_sockaddr(&wsi->udp->sa46),
sa46_socklen(&wsi->udp->sa46));
2018-03-24 08:07:00 +08:00
} else
2019-09-30 09:42:38 -07:00
#endif
if (wsi->role_ops->file_handle)
n = (int)write((int)(lws_intptr_t)wsi->desc.filefd, buf,
#if defined(WIN32)
(int)
#endif
len);
else
n = (int)send(wsi->desc.sockfd, (char *)buf,
#if defined(WIN32)
(int)
#endif
len, MSG_NOSIGNAL);
// lwsl_info("%s: sent len %d result %d", __func__, len, n);
2019-09-08 08:08:55 +01:00
2019-09-30 09:42:38 -07:00
#if defined(LWS_WITH_UDP)
2019-09-08 08:08:55 +01:00
post_send:
2019-09-30 09:42:38 -07:00
#endif
if (n >= 0)
return n;
if (LWS_ERRNO == LWS_EAGAIN ||
LWS_ERRNO == LWS_EWOULDBLOCK ||
LWS_ERRNO == LWS_EINTR) {
if (LWS_ERRNO == LWS_EWOULDBLOCK) {
lws_set_blocking_send(wsi);
}
return LWS_SSL_CAPABLE_MORE_SERVICE;
}
lwsl_wsi_debug(wsi, "ERROR writing len %d to skt fd %d err %d / errno %d",
(int)(ssize_t)len, wsi->desc.sockfd, n, LWS_ERRNO);
2018-03-11 11:26:06 +08:00
return LWS_SSL_CAPABLE_ERROR;
}
int
lws_ssl_pending_no_ssl(struct lws *wsi)
{
(void)wsi;
#if defined(LWS_PLAT_FREERTOS)
return 100;
#else
return 0;
#endif
}