client account for retries
[platform/upstream/libwebsockets.git] / lib / extension-permessage-deflate.c
1 /*
2  * ./lib/extension-permessage-deflate.c
3  *
4  *  Copyright (C) 2016 Andy Green <andy@warmcat.com>
5  *
6  *  This library is free software; you can redistribute it and/or
7  *  modify it under the terms of the GNU Lesser General Public
8  *  License as published by the Free Software Foundation:
9  *  version 2.1 of the License.
10  *
11  *  This library is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  *  Lesser General Public License for more details.
15  *
16  *  You should have received a copy of the GNU Lesser General Public
17  *  License along with this library; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19  *  MA  02110-1301  USA
20  */
21
22 #include "private-libwebsockets.h"
23 #include "extension-permessage-deflate.h"
24 #include <stdio.h>
25 #include <string.h>
26 #include <assert.h>
27
28 #define LWS_ZLIB_MEMLEVEL 8
29
30 const struct lws_ext_options lws_ext_pm_deflate_options[] = {
31         /* public RFC7692 settings */
32         { "server_no_context_takeover", EXTARG_NONE },
33         { "client_no_context_takeover", EXTARG_NONE },
34         { "server_max_window_bits",     EXTARG_OPT_DEC },
35         { "client_max_window_bits",     EXTARG_OPT_DEC },
36         /* ones only user code can set */
37         { "rx_buf_size",                EXTARG_DEC },
38         { "tx_buf_size",                EXTARG_DEC },
39         { "compression_level",          EXTARG_DEC },
40         { "mem_level",                  EXTARG_DEC },
41         { NULL, 0 }, /* sentinel */
42 };
43
44 LWS_VISIBLE int
45 lws_extension_callback_pm_deflate(struct lws_context *context,
46                                   const struct lws_extension *ext,
47                                   struct lws *wsi,
48                                   enum lws_extension_callback_reasons reason,
49                                   void *user, void *in, size_t len)
50 {
51         struct lws_ext_pm_deflate_priv *priv =
52                                      (struct lws_ext_pm_deflate_priv *)user;
53         struct lws_tokens *eff_buf = (struct lws_tokens *)in;
54         static unsigned char trail[] = { 0, 0, 0xff, 0xff };
55         int n, ret = 0, was_fin = 0, extra;
56         struct lws_ext_option_arg *oa;
57
58         switch (reason) {
59         case LWS_EXT_CB_OPTION_SET:
60                 oa = in;
61                 lwsl_info("%s: option set: idx %d, %s, len %d\n", __func__,
62                           oa->option_index, oa->start, oa->len);
63                 if (oa->start)
64                         priv->args[oa->option_index] = atoi(oa->start);
65                 else
66                         priv->args[oa->option_index] = 1;
67                 break;
68         case LWS_EXT_CB_OPTION_CONFIRM:
69                 if (priv->args[PMD_SERVER_MAX_WINDOW_BITS] < 8 ||
70                     priv->args[PMD_SERVER_MAX_WINDOW_BITS] > 15 ||
71                     priv->args[PMD_CLIENT_MAX_WINDOW_BITS] < 8 ||
72                     priv->args[PMD_CLIENT_MAX_WINDOW_BITS] > 15)
73                         return -1;
74                 break;
75
76         case LWS_EXT_CB_CLIENT_CONSTRUCT:
77         case LWS_EXT_CB_CONSTRUCT:
78
79                 n = LWS_MAX_SOCKET_IO_BUF;
80                 if (wsi->protocol->rx_buffer_size)
81                         n =  wsi->protocol->rx_buffer_size;
82
83                 if (n < 128) {
84                         lwsl_err(" permessage-deflate requires the protocol (%s) to have an RX buffer >= 128\n",
85                                         wsi->protocol->name);
86                         return -1;
87                 }
88
89                 /* fill in **user */
90                 priv = lws_zalloc(sizeof(*priv));
91                 *((void **)user) = priv;
92                 lwsl_ext("%s: LWS_EXT_CB_*CONSTRUCT\n", __func__);
93                 memset(priv, 0, sizeof(*priv));
94
95                 /* fill in pointer to options list */
96                 if (in)
97                         *((const struct lws_ext_options **)in) = lws_ext_pm_deflate_options;
98
99                 /* fallthru */
100
101         case LWS_EXT_CB_OPTION_DEFAULT:
102
103                 /* set the public, RFC7692 defaults... */
104
105                 priv->args[PMD_SERVER_NO_CONTEXT_TAKEOVER] = 0,
106                 priv->args[PMD_CLIENT_NO_CONTEXT_TAKEOVER] = 0;
107                 priv->args[PMD_SERVER_MAX_WINDOW_BITS] = 15;
108                 priv->args[PMD_CLIENT_MAX_WINDOW_BITS] = 15;
109
110                 /* ...and the ones the user code can override */
111
112                 priv->args[PMD_RX_BUF_PWR2] = 10; /* ie, 1024 */
113                 priv->args[PMD_TX_BUF_PWR2] = 10; /* ie, 1024 */
114                 priv->args[PMD_COMP_LEVEL] = 1;
115                 priv->args[PMD_MEM_LEVEL] = 8;
116
117                 /* cap the RX buf at the nearest power of 2 to protocol rx buf */
118
119                 n = LWS_MAX_SOCKET_IO_BUF;
120                 if (wsi->protocol->rx_buffer_size)
121                         n =  wsi->protocol->rx_buffer_size;
122
123                 extra = 7;
124                 while (n >= 1 << (extra + 1))
125                         extra++;
126
127                 if (extra < priv->args[PMD_RX_BUF_PWR2]) {
128                         priv->args[PMD_RX_BUF_PWR2] = extra;
129                         lwsl_err(" Capping pmd rx to %d\n", 1 << extra);
130                 }
131                 lwsl_err("   ok\n");
132
133                 break;
134
135         case LWS_EXT_CB_DESTROY:
136                 lwsl_ext("%s: LWS_EXT_CB_DESTROY\n", __func__);
137                 lws_free(priv->buf_rx_inflated);
138                 lws_free(priv->buf_tx_deflated);
139                 if (priv->rx_init)
140                         (void)inflateEnd(&priv->rx);
141                 if (priv->tx_init)
142                         (void)deflateEnd(&priv->tx);
143                 lws_free(priv);
144                 return ret;
145
146         case LWS_EXT_CB_PAYLOAD_RX:
147                 lwsl_ext(" %s: LWS_EXT_CB_PAYLOAD_RX: in %d, existing in %d\n",
148                          __func__, eff_buf->token_len, priv->rx.avail_in);
149                 if (!(wsi->u.ws.rsv_first_msg & 0x40))
150                         return 0;
151
152 #if 0
153                 for (n = 0; n < eff_buf->token_len; n++) {
154                         printf("%02X ", (unsigned char)eff_buf->token[n]);
155                         if ((n & 15) == 15)
156                                 printf("\n");
157                 }
158                 printf("\n");
159 #endif
160                 if (!priv->rx_init)
161                         if (inflateInit2(&priv->rx, -priv->args[PMD_SERVER_MAX_WINDOW_BITS]) != Z_OK) {
162                                 lwsl_err("%s: iniflateInit failed\n", __func__);
163                                 return -1;
164                         }
165                 priv->rx_init = 1;
166                 if (!priv->buf_rx_inflated)
167                         priv->buf_rx_inflated = lws_malloc(LWS_PRE + 7 + 5 +
168                                             (1 << priv->args[PMD_RX_BUF_PWR2]));
169                 if (!priv->buf_rx_inflated) {
170                         lwsl_err("%s: OOM\n", __func__);
171                         return -1;
172                 }
173
174                 /*
175                  * We have to leave the input stream alone if we didn't
176                  * finish with it yet.  The input stream is held in the wsi
177                  * rx buffer by the caller, so this assumption is safe while
178                  * we block new rx while draining the existing rx
179                  */
180                 if (eff_buf->token && eff_buf->token_len) {
181                         priv->rx.next_in = (unsigned char *)eff_buf->token;
182                         priv->rx.avail_in = eff_buf->token_len;
183                 }
184                 priv->rx.next_out = priv->buf_rx_inflated + LWS_PRE;
185                 eff_buf->token = (char *)priv->rx.next_out;
186                 priv->rx.avail_out = 1 << priv->args[PMD_RX_BUF_PWR2];
187
188                 if (priv->rx_held_valid) {
189                         lwsl_ext("-- RX piling on held byte --\n");
190                         *(priv->rx.next_out++) = priv->rx_held;
191                         priv->rx.avail_out--;
192                         priv->rx_held_valid = 0;
193                 }
194
195                 /* if...
196                  *
197                  *  - he has no remaining input content for this message, and
198                  *  - and this is the final fragment, and
199                  *  - we used everything that could be drained on the input side
200                  *
201                  * ...then put back the 00 00 FF FF the sender stripped as our
202                  * input to zlib
203                  */
204                 if (!priv->rx.avail_in && wsi->u.ws.final &&
205                     !wsi->u.ws.rx_packet_length) {
206                         lwsl_ext("RX APPEND_TRAILER-DO\n");
207                         was_fin = 1;
208                         priv->rx.next_in = trail;
209                         priv->rx.avail_in = sizeof(trail);
210                 }
211
212                 n = inflate(&priv->rx, Z_NO_FLUSH);
213                 lwsl_ext("inflate ret %d, avi %d, avo %d, wsifinal %d\n", n,
214                          priv->rx.avail_in, priv->rx.avail_out, wsi->u.ws.final);
215                 switch (n) {
216                 case Z_NEED_DICT:
217                 case Z_STREAM_ERROR:
218                 case Z_DATA_ERROR:
219                 case Z_MEM_ERROR:
220                         lwsl_info("zlib error inflate %d: %s\n",
221                                   n, priv->rx.msg);
222                         return -1;
223                 }
224                 /*
225                  * If we did not already send in the 00 00 FF FF, and he's
226                  * out of input, he did not EXACTLY fill the output buffer
227                  * (which is ambiguous and we will force it to go around
228                  * again by withholding a byte), and he's otherwise working on
229                  * being a FIN fragment, then do the FIN message processing
230                  * of faking up the 00 00 FF FF that the sender stripped.
231                  */
232                 if (!priv->rx.avail_in && wsi->u.ws.final &&
233                     !wsi->u.ws.rx_packet_length && !was_fin &&
234                     priv->rx.avail_out /* ambiguous as to if it is the end */
235                 ) {
236                         lwsl_ext("RX APPEND_TRAILER-DO\n");
237                         was_fin = 1;
238                         priv->rx.next_in = trail;
239                         priv->rx.avail_in = sizeof(trail);
240                         n = inflate(&priv->rx, Z_SYNC_FLUSH);
241                         lwsl_ext("RX trailer inf returned %d, avi %d, avo %d\n", n,
242                                  priv->rx.avail_in, priv->rx.avail_out);
243                         switch (n) {
244                         case Z_NEED_DICT:
245                         case Z_STREAM_ERROR:
246                         case Z_DATA_ERROR:
247                         case Z_MEM_ERROR:
248                                 lwsl_info("zlib error inflate %d: %s\n",
249                                           n, priv->rx.msg);
250                                 return -1;
251                         }
252                 }
253                 /*
254                  * we must announce in our returncode now if there is more
255                  * output to be expected from inflate, so we can decide to
256                  * set the FIN bit on this bufferload or not.  However zlib
257                  * is ambiguous when we exactly filled the inflate buffer.  It
258                  * does not give us a clue as to whether we should understand
259                  * that to mean he ended on a buffer boundary, or if there is
260                  * more in the pipeline.
261                  *
262                  * So to work around that safely, if it used all output space
263                  * exactly, we ALWAYS say there is more coming and we withhold
264                  * the last byte of the buffer to guarantee that is true.
265                  *
266                  * That still leaves us at least one byte to finish with a FIN
267                  * on, even if actually nothing more is coming from the next
268                  * inflate action itself.
269                  */
270                 if (!priv->rx.avail_out) { /* he used all available out buf */
271                         lwsl_ext("-- rx grabbing held --\n");
272                         /* snip the last byte and hold it for next time */
273                         priv->rx_held = *(--priv->rx.next_out);
274                         priv->rx_held_valid = 1;
275                 }
276
277                 eff_buf->token_len = (char *)priv->rx.next_out - eff_buf->token;
278                 priv->count_rx_between_fin += eff_buf->token_len;
279
280                 lwsl_ext("  %s: RX leaving with new effbuff len %d, "
281                          "ret %d, rx.avail_in=%d, TOTAL RX since FIN %d\n",
282                          __func__, eff_buf->token_len, priv->rx_held_valid,
283                          priv->rx.avail_in, priv->count_rx_between_fin);
284
285                 if (was_fin) {
286                         priv->count_rx_between_fin = 0;
287                         if (priv->args[PMD_SERVER_NO_CONTEXT_TAKEOVER]) {
288                                 (void)inflateEnd(&priv->rx);
289                                 priv->rx_init = 0;
290                         }
291                 }
292 #if 0
293                 for (n = 0; n < eff_buf->token_len; n++)
294                         putchar(eff_buf->token[n]);
295                 puts("\n");
296 #endif
297
298                 return priv->rx_held_valid;
299
300         case LWS_EXT_CB_PAYLOAD_TX:
301
302                 if (!priv->tx_init)
303                         if (deflateInit2(&priv->tx, priv->args[PMD_COMP_LEVEL],
304                                          Z_DEFLATED,
305                                          -priv->args[PMD_CLIENT_MAX_WINDOW_BITS +
306                                                      !wsi->context->listen_port],
307                                          priv->args[PMD_MEM_LEVEL],
308                                          Z_DEFAULT_STRATEGY) != Z_OK) {
309                                 lwsl_ext("inflateInit2 failed\n");
310                                 return 1;
311                         }
312                 priv->tx_init = 1;
313                 if (!priv->buf_tx_deflated)
314                         priv->buf_tx_deflated = lws_malloc(LWS_PRE + 7 + 5 +
315                                             (1 << priv->args[PMD_TX_BUF_PWR2]));
316                 if (!priv->buf_tx_deflated) {
317                         lwsl_err("%s: OOM\n", __func__);
318                         return -1;
319                 }
320
321                 if (eff_buf->token) {
322                         lwsl_ext("%s: TX: eff_buf length %d\n", __func__,
323                                  eff_buf->token_len);
324                         priv->tx.next_in = (unsigned char *)eff_buf->token;
325                         priv->tx.avail_in = eff_buf->token_len;
326                 }
327
328 #if 0
329                 for (n = 0; n < eff_buf->token_len; n++) {
330                         printf("%02X ", (unsigned char)eff_buf->token[n]);
331                         if ((n & 15) == 15)
332                                 printf("\n");
333                 }
334                 printf("\n");
335 #endif
336
337                 priv->tx.next_out = priv->buf_tx_deflated + LWS_PRE + 5;
338                 eff_buf->token = (char *)priv->tx.next_out;
339                 priv->tx.avail_out = 1 << priv->args[PMD_TX_BUF_PWR2];
340
341                 n = deflate(&priv->tx, Z_SYNC_FLUSH);
342                 if (n == Z_STREAM_ERROR) {
343                         lwsl_ext("%s: Z_STREAM_ERROR\n", __func__);
344                         return -1;
345                 }
346
347                 if (priv->tx_held_valid) {
348                         priv->tx_held_valid = 0;
349                         if (priv->tx.avail_out == 1 << priv->args[PMD_TX_BUF_PWR2])
350                                 /*
351                                  * we can get a situation he took something in
352                                  * but did not generate anything out, at the end
353                                  * of a message (eg, next thing he sends is 80
354                                  * 00, a zero length FIN, like Authobahn can
355                                  * send).
356                                  * If we have come back as a FIN, we must not
357                                  * place the pending trailer 00 00 FF FF, just
358                                  * the 1 byte of live data
359                                  */
360                                 *(--eff_buf->token) = priv->tx_held[0];
361                         else {
362                                 /* he generated data, prepend whole pending */
363                                 eff_buf->token -= 5;
364                                 for (n = 0; n < 5; n++)
365                                         eff_buf->token[n] = priv->tx_held[n];
366
367                         }
368                 }
369                 priv->compressed_out = 1;
370                 eff_buf->token_len = (int)(priv->tx.next_out -
371                                            (unsigned char *)eff_buf->token);
372
373                 /*
374                  * we must announce in our returncode now if there is more
375                  * output to be expected from inflate, so we can decide to
376                  * set the FIN bit on this bufferload or not.  However zlib
377                  * is ambiguous when we exactly filled the inflate buffer.  It
378                  * does not give us a clue as to whether we should understand
379                  * that to mean he ended on a buffer boundary, or if there is
380                  * more in the pipeline.
381                  *
382                  * Worse, the guy providing the stuff we are sending may not
383                  * know until after that this was, actually, the last chunk,
384                  * that can happen even if we did not fill the output buf, ie
385                  * he may send after this a zero-length FIN fragment.
386                  *
387                  * This is super difficult because we must snip the last 4
388                  * bytes in the case this is the last compressed output of the
389                  * message.  The only way to deal with it is defer sending the
390                  * last 5 bytes of each frame until the next one, when we will
391                  * be in a position to understand if that has a FIN or not.
392                  */
393
394                 extra = !!(len & LWS_WRITE_NO_FIN) || !priv->tx.avail_out;
395
396                 if (eff_buf->token_len >= 4 + extra) {
397                         lwsl_ext("tx held %d\n", 4 + extra);
398                         priv->tx_held_valid = extra;
399                         for (n = 3 + extra; n >= 0; n--)
400                                 priv->tx_held[n] = *(--priv->tx.next_out);
401                         eff_buf->token_len -= 4 + extra;
402                 }
403                 lwsl_ext("  TX rewritten with new effbuff len %d, ret %d\n",
404                          eff_buf->token_len, !priv->tx.avail_out);
405
406                 return !priv->tx.avail_out; /* 1 == have more tx pending */
407
408         case LWS_EXT_CB_PACKET_TX_PRESEND:
409                 if (!priv->compressed_out)
410                         break;
411                 priv->compressed_out = 0;
412
413                 if ((*(eff_buf->token) & 0x80) && priv->args[PMD_CLIENT_NO_CONTEXT_TAKEOVER]) {
414                         (void)deflateEnd(&priv->tx);
415                         priv->tx_init = 0;
416                 }
417
418                 n = *(eff_buf->token) & 15;
419                 /* set RSV1, but not on CONTINUATION */
420                 if (n == LWSWSOPC_TEXT_FRAME || n == LWSWSOPC_BINARY_FRAME)
421                         *eff_buf->token |= 0x40;
422 #if 0
423                 for (n = 0; n < eff_buf->token_len; n++) {
424                         printf("%02X ", (unsigned char)eff_buf->token[n]);
425                         if ((n & 15) == 15)
426                                 puts("\n");
427                 }
428                 puts("\n");
429 #endif
430                 lwsl_ext("%s: tx opcode 0x%02X\n", __func__,
431                          (unsigned char)*eff_buf->token);
432                 break;
433
434         default:
435                 break;
436         }
437
438         return 0;
439 }
440