lsquic_stream.c revision bea64822
1/* Copyright (c) 2017 - 2018 LiteSpeed Technologies Inc.  See LICENSE. */
2/*
3 * lsquic_stream.c -- stream processing
4 *
5 * To clear up terminology, here are some of our stream states (in order).
6 * They are not codified, but they are referred to in both code and comments.
7 *
8 *  CLOSED      STREAM_U_READ_DONE and STREAM_U_WRITE_DONE are set.  At this
9 *                point, on_close() gets called.
10 *  FINISHED    FIN or RST has been sent to peer.  Stream is scheduled to be
11 *                finished (freed): it gets put onto the `service_streams'
12 *                list for connection to clean it up.
13 *  DESTROYED   All remaining memory associated with the stream is released.
14 *                If on_close() has not been called yet, it is called now.
15 *                The stream pointer is now invalid.
16 *
17 * When connection is aborted, a stream may go directly to DESTROYED state.
18 */
19
20#include <assert.h>
21#include <errno.h>
22#include <inttypes.h>
23#include <stdarg.h>
24#include <stdlib.h>
25#include <string.h>
26#include <sys/queue.h>
27#include <stddef.h>
28
29#include "lsquic.h"
30
31#include "lsquic_int_types.h"
32#include "lsquic_packet_common.h"
33#include "lsquic_packet_in.h"
34#include "lsquic_malo.h"
35#include "lsquic_conn_flow.h"
36#include "lsquic_rtt.h"
37#include "lsquic_sfcw.h"
38#include "lsquic_stream.h"
39#include "lsquic_conn_public.h"
40#include "lsquic_util.h"
41#include "lsquic_mm.h"
42#include "lsquic_headers_stream.h"
43#include "lsquic_frame_reader.h"
44#include "lsquic_conn.h"
45#include "lsquic_data_in_if.h"
46#include "lsquic_parse.h"
47#include "lsquic_packet_out.h"
48#include "lsquic_engine_public.h"
49#include "lsquic_senhist.h"
50#include "lsquic_pacer.h"
51#include "lsquic_cubic.h"
52#include "lsquic_send_ctl.h"
53#include "lsquic_ev_log.h"
54
55#define LSQUIC_LOGGER_MODULE LSQLM_STREAM
56#define LSQUIC_LOG_CONN_ID stream->conn_pub->lconn->cn_cid
57#define LSQUIC_LOG_STREAM_ID stream->id
58#include "lsquic_logger.h"
59
60#define SM_BUF_SIZE QUIC_MAX_PACKET_SZ
61
62static void
63drop_frames_in (lsquic_stream_t *stream);
64
65static void
66maybe_schedule_call_on_close (lsquic_stream_t *stream);
67
68static int
69stream_wantread (lsquic_stream_t *stream, int is_want);
70
71static int
72stream_wantwrite (lsquic_stream_t *stream, int is_want);
73
74static ssize_t
75stream_write_to_packets (lsquic_stream_t *, struct lsquic_reader *, size_t);
76
77static ssize_t
78save_to_buffer (lsquic_stream_t *, struct lsquic_reader *, size_t len);
79
80static int
81stream_flush (lsquic_stream_t *stream);
82
83static int
84stream_flush_nocheck (lsquic_stream_t *stream);
85
86static void
87maybe_remove_from_write_q (lsquic_stream_t *stream, enum stream_flags flag);
88
89
90#if LSQUIC_KEEP_STREAM_HISTORY
91/* These values are printable ASCII characters for ease of printing the
92 * whole history in a single line of a log message.
93 *
94 * The list of events is not exhaustive: only most interesting events
95 * are recorded.
96 */
97enum stream_history_event
98{
99    SHE_EMPTY              =  '\0',     /* Special entry.  No init besides memset required */
100    SHE_PLUS               =  '+',      /* Special entry: previous event occured more than once */
101    SHE_REACH_FIN          =  'a',
102    SHE_BLOCKED_OUT        =  'b',
103    SHE_CREATED            =  'C',
104    SHE_FRAME_IN           =  'd',
105    SHE_FRAME_OUT          =  'D',
106    SHE_RESET              =  'e',
107    SHE_WINDOW_UPDATE      =  'E',
108    SHE_FIN_IN             =  'f',
109    SHE_FINISHED           =  'F',
110    SHE_GOAWAY_IN          =  'g',
111    SHE_USER_WRITE_HEADER  =  'h',
112    SHE_HEADERS_IN         =  'H',
113    SHE_ONCLOSE_SCHED      =  'l',
114    SHE_ONCLOSE_CALL       =  'L',
115    SHE_ONNEW              =  'N',
116    SHE_SET_PRIO           =  'p',
117    SHE_USER_READ          =  'r',
118    SHE_SHUTDOWN_READ      =  'R',
119    SHE_RST_IN             =  's',
120    SHE_RST_OUT            =  't',
121    SHE_FLUSH              =  'u',
122    SHE_USER_WRITE_DATA    =  'w',
123    SHE_SHUTDOWN_WRITE     =  'W',
124    SHE_CLOSE              =  'X',
125    SHE_FORCE_FINISH       =  'Z',
126};
127
128static void
129sm_history_append (lsquic_stream_t *stream, enum stream_history_event sh_event)
130{
131    enum stream_history_event prev_event;
132    sm_hist_idx_t idx;
133    int plus;
134
135    idx = (stream->sm_hist_idx - 1) & SM_HIST_IDX_MASK;
136    plus = SHE_PLUS == stream->sm_hist_buf[idx];
137    idx = (idx - plus) & SM_HIST_IDX_MASK;
138    prev_event = stream->sm_hist_buf[idx];
139
140    if (prev_event == sh_event && plus)
141        return;
142
143    if (prev_event == sh_event)
144        sh_event = SHE_PLUS;
145    stream->sm_hist_buf[ stream->sm_hist_idx++ & SM_HIST_IDX_MASK ] = sh_event;
146
147    if (0 == (stream->sm_hist_idx & SM_HIST_IDX_MASK))
148        LSQ_DEBUG("history: [%.*s]", (int) sizeof(stream->sm_hist_buf),
149                                                        stream->sm_hist_buf);
150}
151
152#   define SM_HISTORY_APPEND(stream, event) sm_history_append(stream, event)
153#   define SM_HISTORY_DUMP_REMAINING(stream) do {                           \
154        if (stream->sm_hist_idx & SM_HIST_IDX_MASK)                         \
155            LSQ_DEBUG("history: [%.*s]",                                    \
156                (int) ((stream)->sm_hist_idx & SM_HIST_IDX_MASK),           \
157                (stream)->sm_hist_buf);                                     \
158    } while (0)
159#else
160#   define SM_HISTORY_APPEND(stream, event)
161#   define SM_HISTORY_DUMP_REMAINING(stream)
162#endif
163
164
165static int
166stream_inside_callback (const lsquic_stream_t *stream)
167{
168    return stream->conn_pub->enpub->enp_flags & ENPUB_PROC;
169}
170
171
172static void
173maybe_conn_to_tickable (lsquic_stream_t *stream)
174{
175    if (!stream_inside_callback(stream))
176        lsquic_engine_add_conn_to_tickable(stream->conn_pub->enpub,
177                                           stream->conn_pub->lconn);
178}
179
180
181/* Here, "readable" means that the user is able to read from the stream. */
182static void
183maybe_conn_to_tickable_if_readable (lsquic_stream_t *stream)
184{
185    if (!stream_inside_callback(stream) && lsquic_stream_readable(stream))
186    {
187        lsquic_engine_add_conn_to_tickable(stream->conn_pub->enpub,
188                                           stream->conn_pub->lconn);
189    }
190}
191
192
193/* Here, "writeable" means that data can be put into packets to be
194 * scheduled to be sent out.
195 *
196 * If `check_can_send' is false, it means that we do not need to check
197 * whether packets can be sent.  This check was already performed when
198 * we packetized stream data.
199 */
200static void
201maybe_conn_to_tickable_if_writeable (lsquic_stream_t *stream,
202                                                    int check_can_send)
203{
204    if (!stream_inside_callback(stream) &&
205            (!check_can_send
206             || lsquic_send_ctl_can_send(stream->conn_pub->send_ctl)) &&
207          ! lsquic_send_ctl_have_delayed_packets(stream->conn_pub->send_ctl))
208    {
209        lsquic_engine_add_conn_to_tickable(stream->conn_pub->enpub,
210                                           stream->conn_pub->lconn);
211    }
212}
213
214
215static int
216stream_stalled (const lsquic_stream_t *stream)
217{
218    return 0 == (stream->stream_flags & (STREAM_WANT_WRITE|STREAM_WANT_READ)) &&
219           ((STREAM_U_READ_DONE|STREAM_U_WRITE_DONE) & stream->stream_flags)
220                                    != (STREAM_U_READ_DONE|STREAM_U_WRITE_DONE);
221}
222
223
224/* TODO: The logic to figure out whether the stream is connection limited
225 * should be taken out of the constructor.  The caller should specify this
226 * via one of enum stream_ctor_flags.
227 */
228lsquic_stream_t *
229lsquic_stream_new_ext (uint32_t id, struct lsquic_conn_public *conn_pub,
230                       const struct lsquic_stream_if *stream_if,
231                       void *stream_if_ctx, unsigned initial_window,
232                       unsigned initial_send_off,
233                       enum stream_ctor_flags ctor_flags)
234{
235    lsquic_cfcw_t *cfcw;
236    lsquic_stream_t *stream;
237
238    stream = calloc(1, sizeof(*stream));
239    if (!stream)
240        return NULL;
241
242    stream->stream_if = stream_if;
243    stream->id        = id;
244    stream->conn_pub  = conn_pub;
245    stream->sm_onnew_arg = stream_if_ctx;
246    if (!initial_window)
247        initial_window = 16 * 1024;
248    if (LSQUIC_STREAM_HANDSHAKE == id ||
249        (conn_pub->hs && LSQUIC_STREAM_HEADERS == id))
250        cfcw = NULL;
251    else
252    {
253        cfcw = &conn_pub->cfcw;
254        stream->stream_flags |= STREAM_CONN_LIMITED;
255        if (conn_pub->hs)
256            stream->stream_flags |= STREAM_USE_HEADERS;
257        lsquic_stream_set_priority_internal(stream, LSQUIC_STREAM_DEFAULT_PRIO);
258    }
259    lsquic_sfcw_init(&stream->fc, initial_window, cfcw, conn_pub, id);
260    if (!initial_send_off)
261        initial_send_off = 16 * 1024;
262    stream->max_send_off = initial_send_off;
263    if (ctor_flags & SCF_USE_DI_HASH)
264        stream->data_in = data_in_hash_new(conn_pub, id, 0);
265    else
266        stream->data_in = data_in_nocopy_new(conn_pub, id);
267    LSQ_DEBUG("created stream %u @%p", id, stream);
268    SM_HISTORY_APPEND(stream, SHE_CREATED);
269    if (ctor_flags & SCF_DI_AUTOSWITCH)
270        stream->stream_flags |= STREAM_AUTOSWITCH;
271    if (ctor_flags & SCF_CALL_ON_NEW)
272        lsquic_stream_call_on_new(stream);
273    if (ctor_flags & SCF_DISP_RW_ONCE)
274        stream->stream_flags |= STREAM_RW_ONCE;
275    return stream;
276}
277
278
279void
280lsquic_stream_call_on_new (lsquic_stream_t *stream)
281{
282    assert(!(stream->stream_flags & STREAM_ONNEW_DONE));
283    if (!(stream->stream_flags & STREAM_ONNEW_DONE))
284    {
285        LSQ_DEBUG("calling on_new_stream");
286        SM_HISTORY_APPEND(stream, SHE_ONNEW);
287        stream->stream_flags |= STREAM_ONNEW_DONE;
288        stream->st_ctx = stream->stream_if->on_new_stream(stream->sm_onnew_arg,
289                                                          stream);
290    }
291}
292
293
294static void
295decr_conn_cap (struct lsquic_stream *stream, size_t incr)
296{
297    if (stream->stream_flags & STREAM_CONN_LIMITED)
298    {
299        assert(stream->conn_pub->conn_cap.cc_sent >= incr);
300        stream->conn_pub->conn_cap.cc_sent -= incr;
301    }
302}
303
304
305static void
306drop_buffered_data (struct lsquic_stream *stream)
307{
308    decr_conn_cap(stream, stream->sm_n_buffered);
309    stream->sm_n_buffered = 0;
310    if (stream->stream_flags & STREAM_WRITE_Q_FLAGS)
311        maybe_remove_from_write_q(stream, STREAM_WRITE_Q_FLAGS);
312}
313
314
315void
316lsquic_stream_destroy (lsquic_stream_t *stream)
317{
318    stream->stream_flags |= STREAM_U_WRITE_DONE|STREAM_U_READ_DONE;
319    if ((stream->stream_flags & (STREAM_ONNEW_DONE|STREAM_ONCLOSE_DONE)) ==
320                                                            STREAM_ONNEW_DONE)
321    {
322        stream->stream_flags |= STREAM_ONCLOSE_DONE;
323        stream->stream_if->on_close(stream, stream->st_ctx);
324    }
325    if (stream->stream_flags & STREAM_SENDING_FLAGS)
326        TAILQ_REMOVE(&stream->conn_pub->sending_streams, stream, next_send_stream);
327    if (stream->stream_flags & STREAM_WANT_READ)
328        TAILQ_REMOVE(&stream->conn_pub->read_streams, stream, next_read_stream);
329    if (stream->stream_flags & STREAM_WRITE_Q_FLAGS)
330        TAILQ_REMOVE(&stream->conn_pub->write_streams, stream, next_write_stream);
331    if (stream->stream_flags & STREAM_SERVICE_FLAGS)
332        TAILQ_REMOVE(&stream->conn_pub->service_streams, stream, next_service_stream);
333    drop_buffered_data(stream);
334    lsquic_sfcw_consume_rem(&stream->fc);
335    drop_frames_in(stream);
336    free(stream->push_req);
337    free(stream->uh);
338    free(stream->sm_buf);
339    LSQ_DEBUG("destroyed stream %u @%p", stream->id, stream);
340    SM_HISTORY_DUMP_REMAINING(stream);
341    free(stream);
342}
343
344
345static int
346stream_is_finished (const lsquic_stream_t *stream)
347{
348    return lsquic_stream_is_closed(stream)
349           /* n_unacked checks that no outgoing packets that reference this
350            * stream are outstanding:
351            */
352        && 0 == stream->n_unacked
353           /* This checks that no packets that reference this stream will
354            * become outstanding:
355            */
356        && 0 == (stream->stream_flags & STREAM_SEND_RST)
357        && ((stream->stream_flags & STREAM_FORCE_FINISH)
358          || ((stream->stream_flags & (STREAM_FIN_SENT |STREAM_RST_SENT))
359           && (stream->stream_flags & (STREAM_FIN_RECVD|STREAM_RST_RECVD))));
360}
361
362
363static void
364maybe_finish_stream (lsquic_stream_t *stream)
365{
366    if (0 == (stream->stream_flags & STREAM_FINISHED) &&
367                                                    stream_is_finished(stream))
368    {
369        LSQ_DEBUG("stream %u is now finished", stream->id);
370        SM_HISTORY_APPEND(stream, SHE_FINISHED);
371        if (0 == (stream->stream_flags & STREAM_SERVICE_FLAGS))
372            TAILQ_INSERT_TAIL(&stream->conn_pub->service_streams, stream,
373                                                    next_service_stream);
374        stream->stream_flags |= STREAM_FREE_STREAM|STREAM_FINISHED;
375    }
376}
377
378
379static void
380maybe_schedule_call_on_close (lsquic_stream_t *stream)
381{
382    if ((stream->stream_flags & (STREAM_U_READ_DONE|STREAM_U_WRITE_DONE|
383                     STREAM_ONNEW_DONE|STREAM_ONCLOSE_DONE|STREAM_CALL_ONCLOSE))
384            == (STREAM_U_READ_DONE|STREAM_U_WRITE_DONE|STREAM_ONNEW_DONE))
385    {
386        if (0 == (stream->stream_flags & STREAM_SERVICE_FLAGS))
387            TAILQ_INSERT_TAIL(&stream->conn_pub->service_streams, stream,
388                                                    next_service_stream);
389        stream->stream_flags |= STREAM_CALL_ONCLOSE;
390        LSQ_DEBUG("scheduled calling on_close for stream %u", stream->id);
391        SM_HISTORY_APPEND(stream, SHE_ONCLOSE_SCHED);
392    }
393}
394
395
396void
397lsquic_stream_call_on_close (lsquic_stream_t *stream)
398{
399    assert(stream->stream_flags & STREAM_ONNEW_DONE);
400    stream->stream_flags &= ~STREAM_CALL_ONCLOSE;
401    if (!(stream->stream_flags & STREAM_SERVICE_FLAGS))
402        TAILQ_REMOVE(&stream->conn_pub->service_streams, stream,
403                                                    next_service_stream);
404    if (0 == (stream->stream_flags & STREAM_ONCLOSE_DONE))
405    {
406        LSQ_DEBUG("calling on_close for stream %u", stream->id);
407        stream->stream_flags |= STREAM_ONCLOSE_DONE;
408        SM_HISTORY_APPEND(stream, SHE_ONCLOSE_CALL);
409        stream->stream_if->on_close(stream, stream->st_ctx);
410    }
411    else
412        assert(0);
413}
414
415
416int
417lsquic_stream_readable (const lsquic_stream_t *stream)
418{
419    /* A stream is readable if one of the following is true: */
420    return
421        /* - It is already finished: in that case, lsquic_stream_read() will
422         *   return 0.
423         */
424            (stream->stream_flags & STREAM_FIN_REACHED)
425        /* - The stream is reset, by either side.  In this case,
426         *   lsquic_stream_read() will return -1 (we want the user to be
427         *   able to collect the error).
428         */
429        ||  (stream->stream_flags & STREAM_RST_FLAGS)
430        /* - Either we are not in HTTP mode or the HTTP headers have been
431         *   received and the headers or data from the stream can be read.
432         */
433        ||  (!((stream->stream_flags & (STREAM_USE_HEADERS|STREAM_HAVE_UH))
434                                                        == STREAM_USE_HEADERS)
435            && (stream->uh != NULL
436                ||  stream->data_in->di_if->di_get_frame(stream->data_in,
437                                                        stream->read_offset)))
438    ;
439}
440
441
442size_t
443lsquic_stream_write_avail (const struct lsquic_stream *stream)
444{
445    uint64_t stream_avail, conn_avail;
446
447    stream_avail = stream->max_send_off - stream->tosend_off
448                                                - stream->sm_n_buffered;
449    if (stream->stream_flags & STREAM_CONN_LIMITED)
450    {
451        conn_avail = lsquic_conn_cap_avail(&stream->conn_pub->conn_cap);
452        if (conn_avail < stream_avail)
453            return conn_avail;
454    }
455
456    return stream_avail;
457}
458
459
460int
461lsquic_stream_update_sfcw (lsquic_stream_t *stream, uint64_t max_off)
462{
463    if (max_off > lsquic_sfcw_get_max_recv_off(&stream->fc) &&
464                    !lsquic_sfcw_set_max_recv_off(&stream->fc, max_off))
465    {
466        return -1;
467    }
468    if (lsquic_sfcw_fc_offsets_changed(&stream->fc))
469    {
470        if (!(stream->stream_flags & STREAM_SENDING_FLAGS))
471            TAILQ_INSERT_TAIL(&stream->conn_pub->sending_streams, stream,
472                                                    next_send_stream);
473        stream->stream_flags |= STREAM_SEND_WUF;
474    }
475    return 0;
476}
477
478
479int
480lsquic_stream_frame_in (lsquic_stream_t *stream, stream_frame_t *frame)
481{
482    uint64_t max_off;
483    int got_next_offset;
484    enum ins_frame ins_frame;
485
486    assert(frame->packet_in);
487
488    SM_HISTORY_APPEND(stream, SHE_FRAME_IN);
489    LSQ_DEBUG("received stream frame, stream %u, offset 0x%"PRIX64", len %u; "
490        "fin: %d", stream->id, frame->data_frame.df_offset, frame->data_frame.df_size, !!frame->data_frame.df_fin);
491
492    if ((stream->stream_flags & (STREAM_USE_HEADERS|STREAM_HEAD_IN_FIN)) ==
493                                (STREAM_USE_HEADERS|STREAM_HEAD_IN_FIN))
494    {
495        lsquic_packet_in_put(stream->conn_pub->mm, frame->packet_in);
496        lsquic_malo_put(frame);
497        return -1;
498    }
499
500    got_next_offset = frame->data_frame.df_offset == stream->read_offset;
501    ins_frame = stream->data_in->di_if->di_insert_frame(stream->data_in, frame, stream->read_offset);
502    if (INS_FRAME_OK == ins_frame)
503    {
504        /* Update maximum offset in the flow controller and check for flow
505         * control violation:
506         */
507        max_off = frame->data_frame.df_offset + frame->data_frame.df_size;
508        if (0 != lsquic_stream_update_sfcw(stream, max_off))
509            return -1;
510        if (frame->data_frame.df_fin)
511        {
512            SM_HISTORY_APPEND(stream, SHE_FIN_IN);
513            stream->stream_flags |= STREAM_FIN_RECVD;
514            maybe_finish_stream(stream);
515        }
516        if ((stream->stream_flags & STREAM_AUTOSWITCH) &&
517                (stream->data_in->di_flags & DI_SWITCH_IMPL))
518        {
519            stream->data_in = stream->data_in->di_if->di_switch_impl(
520                                        stream->data_in, stream->read_offset);
521            if (!stream->data_in)
522            {
523                stream->data_in = data_in_error_new();
524                return -1;
525            }
526        }
527        if (got_next_offset)
528            /* Checking the offset saves di_get_frame() call */
529            maybe_conn_to_tickable_if_readable(stream);
530        return 0;
531    }
532    else if (INS_FRAME_DUP == ins_frame)
533    {
534        return 0;
535    }
536    else
537    {
538        assert(INS_FRAME_ERR == ins_frame);
539        return -1;
540    }
541}
542
543
544static void
545drop_frames_in (lsquic_stream_t *stream)
546{
547    if (stream->data_in)
548    {
549        stream->data_in->di_if->di_destroy(stream->data_in);
550        /* To avoid checking whether `data_in` is set, just set to the error
551         * data-in stream.  It does the right thing after incoming data is
552         * dropped.
553         */
554        stream->data_in = data_in_error_new();
555    }
556}
557
558
559static void
560maybe_elide_stream_frames (struct lsquic_stream *stream)
561{
562    if (!(stream->stream_flags & STREAM_FRAMES_ELIDED))
563    {
564        if (stream->n_unacked)
565            lsquic_send_ctl_elide_stream_frames(stream->conn_pub->send_ctl,
566                                                stream->id);
567        stream->stream_flags |= STREAM_FRAMES_ELIDED;
568    }
569}
570
571
572int
573lsquic_stream_rst_in (lsquic_stream_t *stream, uint64_t offset,
574                      uint32_t error_code)
575{
576
577    if (stream->stream_flags & STREAM_RST_RECVD)
578    {
579        LSQ_DEBUG("ignore duplicate RST_STREAM frame");
580        return 0;
581    }
582
583    SM_HISTORY_APPEND(stream, SHE_RST_IN);
584    /* This flag must always be set, even if we are "ignoring" it: it is
585     * used by elision code.
586     */
587    stream->stream_flags |= STREAM_RST_RECVD;
588
589    if (lsquic_sfcw_get_max_recv_off(&stream->fc) > offset)
590    {
591        LSQ_INFO("stream %u: RST_STREAM invalid: its offset 0x%"PRIX64" is "
592            "smaller than that of byte following the last byte we have seen: "
593            "0x%"PRIX64, stream->id, offset,
594            lsquic_sfcw_get_max_recv_off(&stream->fc));
595        return -1;
596    }
597
598    if (!lsquic_sfcw_set_max_recv_off(&stream->fc, offset))
599    {
600        LSQ_INFO("stream %u: RST_STREAM invalid: its offset 0x%"PRIX64
601            " violates flow control", stream->id, offset);
602        return -1;
603    }
604
605    /* Let user collect error: */
606    maybe_conn_to_tickable_if_readable(stream);
607
608    lsquic_sfcw_consume_rem(&stream->fc);
609    drop_frames_in(stream);
610    drop_buffered_data(stream);
611    maybe_elide_stream_frames(stream);
612
613    if (!(stream->stream_flags &
614                        (STREAM_SEND_RST|STREAM_RST_SENT|STREAM_FIN_SENT)))
615        lsquic_stream_reset_ext(stream, 7 /* QUIC_RST_ACKNOWLEDGEMENT */, 0);
616
617    stream->stream_flags |= STREAM_RST_RECVD;
618
619    maybe_finish_stream(stream);
620    maybe_schedule_call_on_close(stream);
621
622    return 0;
623}
624
625
626uint64_t
627lsquic_stream_fc_recv_off (lsquic_stream_t *stream)
628{
629    assert(stream->stream_flags & STREAM_SEND_WUF);
630    stream->stream_flags &= ~STREAM_SEND_WUF;
631    if (!(stream->stream_flags & STREAM_SENDING_FLAGS))
632        TAILQ_REMOVE(&stream->conn_pub->sending_streams, stream, next_send_stream);
633    return lsquic_sfcw_get_fc_recv_off(&stream->fc);
634}
635
636
637void
638lsquic_stream_blocked_frame_sent (lsquic_stream_t *stream)
639{
640    assert(stream->stream_flags & STREAM_SEND_BLOCKED);
641    SM_HISTORY_APPEND(stream, SHE_BLOCKED_OUT);
642    stream->stream_flags &= ~STREAM_SEND_BLOCKED;
643    if (!(stream->stream_flags & STREAM_SENDING_FLAGS))
644        TAILQ_REMOVE(&stream->conn_pub->sending_streams, stream, next_send_stream);
645}
646
647
648void
649lsquic_stream_rst_frame_sent (lsquic_stream_t *stream)
650{
651    assert(stream->stream_flags & STREAM_SEND_RST);
652    SM_HISTORY_APPEND(stream, SHE_RST_OUT);
653    stream->stream_flags &= ~STREAM_SEND_RST;
654    if (!(stream->stream_flags & STREAM_SENDING_FLAGS))
655        TAILQ_REMOVE(&stream->conn_pub->sending_streams, stream, next_send_stream);
656    stream->stream_flags |= STREAM_RST_SENT;
657    maybe_finish_stream(stream);
658}
659
660
661static size_t
662read_uh (lsquic_stream_t *stream, unsigned char *dst, size_t len)
663{
664    struct uncompressed_headers *uh = stream->uh;
665    size_t n_avail = uh->uh_size - uh->uh_off;
666    if (n_avail < len)
667        len = n_avail;
668    memcpy(dst, uh->uh_headers + uh->uh_off, len);
669    uh->uh_off += len;
670    if (uh->uh_off == uh->uh_size)
671    {
672        LSQ_DEBUG("read all uncompressed headers for stream %u", stream->id);
673        free(uh);
674        stream->uh = NULL;
675        if (stream->stream_flags & STREAM_HEAD_IN_FIN)
676        {
677            stream->stream_flags |= STREAM_FIN_REACHED;
678            SM_HISTORY_APPEND(stream, SHE_REACH_FIN);
679        }
680    }
681    return len;
682}
683
684
685/* This function returns 0 when EOF is reached.
686 */
687ssize_t
688lsquic_stream_readv (lsquic_stream_t *stream, const struct iovec *iov,
689                     int iovcnt)
690{
691    size_t total_nread, nread;
692    int processed_frames, read_unc_headers, iovidx;
693    unsigned char *p, *end;
694
695    SM_HISTORY_APPEND(stream, SHE_USER_READ);
696
697#define NEXT_IOV() do {                                             \
698    ++iovidx;                                                       \
699    while (iovidx < iovcnt && 0 == iov[iovidx].iov_len)             \
700        ++iovidx;                                                   \
701    if (iovidx < iovcnt)                                            \
702    {                                                               \
703        p = iov[iovidx].iov_base;                                   \
704        end = p + iov[iovidx].iov_len;                              \
705    }                                                               \
706    else                                                            \
707        p = end = NULL;                                             \
708} while (0)
709
710#define AVAIL() (end - p)
711
712    if (stream->stream_flags & STREAM_RST_FLAGS)
713    {
714        errno = ECONNRESET;
715        return -1;
716    }
717    if (stream->stream_flags & STREAM_U_READ_DONE)
718    {
719        errno = EBADF;
720        return -1;
721    }
722    if (stream->stream_flags & STREAM_FIN_REACHED)
723        return 0;
724
725    total_nread = 0;
726    processed_frames = 0;
727
728    iovidx = -1;
729    NEXT_IOV();
730
731    if (stream->uh && AVAIL())
732    {
733        read_unc_headers = 1;
734        do
735        {
736            nread = read_uh(stream, p, AVAIL());
737            p += nread;
738            total_nread += nread;
739            if (p == end)
740                NEXT_IOV();
741        }
742        while (stream->uh && AVAIL());
743    }
744    else
745        read_unc_headers = 0;
746
747    struct data_frame *data_frame;
748    while (AVAIL() && (data_frame = stream->data_in->di_if->di_get_frame(stream->data_in, stream->read_offset)))
749    {
750        ++processed_frames;
751        size_t navail = data_frame->df_size - data_frame->df_read_off;
752        size_t ntowrite = AVAIL();
753        if (navail < ntowrite)
754            ntowrite = navail;
755        memcpy(p, data_frame->df_data + data_frame->df_read_off, ntowrite);
756        p += ntowrite;
757        data_frame->df_read_off += ntowrite;
758        stream->read_offset += ntowrite;
759        total_nread += ntowrite;
760        if (data_frame->df_read_off == data_frame->df_size)
761        {
762            const int fin = data_frame->df_fin;
763            stream->data_in->di_if->di_frame_done(stream->data_in, data_frame);
764            if ((stream->stream_flags & STREAM_AUTOSWITCH) &&
765                    (stream->data_in->di_flags & DI_SWITCH_IMPL))
766            {
767                stream->data_in = stream->data_in->di_if->di_switch_impl(
768                                            stream->data_in, stream->read_offset);
769                if (!stream->data_in)
770                {
771                    stream->data_in = data_in_error_new();
772                    return -1;
773                }
774            }
775            if (fin)
776            {
777                stream->stream_flags |= STREAM_FIN_REACHED;
778                break;
779            }
780        }
781        if (p == end)
782            NEXT_IOV();
783    }
784
785    LSQ_DEBUG("%s: read %zd bytes, read offset %"PRIu64, __func__,
786                                        total_nread, stream->read_offset);
787
788    if (processed_frames)
789    {
790        lsquic_sfcw_set_read_off(&stream->fc, stream->read_offset);
791        if (lsquic_sfcw_fc_offsets_changed(&stream->fc))
792        {
793            if (!(stream->stream_flags & STREAM_SENDING_FLAGS))
794                TAILQ_INSERT_TAIL(&stream->conn_pub->sending_streams, stream, next_send_stream);
795            stream->stream_flags |= STREAM_SEND_WUF;
796            maybe_conn_to_tickable_if_writeable(stream, 1);
797        }
798    }
799
800    if (processed_frames || read_unc_headers)
801    {
802        return total_nread;
803    }
804    else
805    {
806        assert(0 == total_nread);
807        errno = EWOULDBLOCK;
808        return -1;
809    }
810}
811
812
813ssize_t
814lsquic_stream_read (lsquic_stream_t *stream, void *buf, size_t len)
815{
816    struct iovec iov = { .iov_base = buf, .iov_len = len, };
817    return lsquic_stream_readv(stream, &iov, 1);
818}
819
820
821static void
822stream_shutdown_read (lsquic_stream_t *stream)
823{
824    if (!(stream->stream_flags & STREAM_U_READ_DONE))
825    {
826        SM_HISTORY_APPEND(stream, SHE_SHUTDOWN_READ);
827        stream->stream_flags |= STREAM_U_READ_DONE;
828        stream_wantread(stream, 0);
829        maybe_finish_stream(stream);
830    }
831}
832
833
834static void
835stream_shutdown_write (lsquic_stream_t *stream)
836{
837    if (stream->stream_flags & STREAM_U_WRITE_DONE)
838        return;
839
840    SM_HISTORY_APPEND(stream, SHE_SHUTDOWN_WRITE);
841    stream->stream_flags |= STREAM_U_WRITE_DONE;
842    stream_wantwrite(stream, 0);
843
844    /* Don't bother to check whether there is anything else to write if
845     * the flags indicate that nothing else should be written.
846     */
847    if (!(stream->stream_flags &
848                    (STREAM_FIN_SENT|STREAM_SEND_RST|STREAM_RST_SENT)))
849    {
850        if (stream->sm_n_buffered == 0)
851        {
852            if (0 == lsquic_send_ctl_turn_on_fin(stream->conn_pub->send_ctl,
853                                                 stream))
854            {
855                LSQ_DEBUG("turned on FIN flag in the yet-unsent STREAM frame");
856                stream->stream_flags |= STREAM_FIN_SENT;
857            }
858            else
859            {
860                LSQ_DEBUG("have to create a separate STREAM frame with FIN "
861                          "flag in it");
862                (void) stream_flush_nocheck(stream);
863            }
864        }
865        else
866            (void) stream_flush_nocheck(stream);
867    }
868}
869
870
871int
872lsquic_stream_shutdown (lsquic_stream_t *stream, int how)
873{
874    LSQ_DEBUG("shutdown(stream: %u; how: %d)", stream->id, how);
875    if (lsquic_stream_is_closed(stream))
876    {
877        LSQ_INFO("Attempt to shut down a closed stream %u", stream->id);
878        errno = EBADF;
879        return -1;
880    }
881    /* 0: read, 1: write: 2: read and write
882     */
883    if (how < 0 || how > 2)
884    {
885        errno = EINVAL;
886        return -1;
887    }
888
889    if (how)
890        stream_shutdown_write(stream);
891    if (how != 1)
892        stream_shutdown_read(stream);
893
894    maybe_finish_stream(stream);
895    maybe_schedule_call_on_close(stream);
896    if (how)
897        maybe_conn_to_tickable_if_writeable(stream, 1);
898
899    return 0;
900}
901
902
903void
904lsquic_stream_shutdown_internal (lsquic_stream_t *stream)
905{
906    LSQ_DEBUG("internal shutdown of stream %u", stream->id);
907    if (LSQUIC_STREAM_HANDSHAKE == stream->id
908        || ((stream->stream_flags & STREAM_USE_HEADERS) &&
909                                LSQUIC_STREAM_HEADERS == stream->id))
910    {
911        LSQ_DEBUG("add flag to force-finish special stream %u", stream->id);
912        stream->stream_flags |= STREAM_FORCE_FINISH;
913        SM_HISTORY_APPEND(stream, SHE_FORCE_FINISH);
914    }
915    maybe_finish_stream(stream);
916    maybe_schedule_call_on_close(stream);
917}
918
919
920static void
921fake_reset_unused_stream (lsquic_stream_t *stream)
922{
923    stream->stream_flags |=
924        STREAM_RST_RECVD    /* User will pick this up on read or write */
925      | STREAM_RST_SENT     /* Don't send anything else on this stream */
926    ;
927
928    /* Cancel all writes to the network scheduled for this stream: */
929    if (stream->stream_flags & STREAM_SENDING_FLAGS)
930        TAILQ_REMOVE(&stream->conn_pub->sending_streams, stream,
931                                                next_send_stream);
932    stream->stream_flags &= ~STREAM_SENDING_FLAGS;
933
934    LSQ_DEBUG("fake-reset stream %u%s",
935                    stream->id, stream_stalled(stream) ? " (stalled)" : "");
936    maybe_finish_stream(stream);
937    maybe_schedule_call_on_close(stream);
938}
939
940
941/* This function should only be called for locally-initiated streams whose ID
942 * is larger than that received in GOAWAY frame.  This may occur when GOAWAY
943 * frame sent by peer but we have not yet received it and created a stream.
944 * In this situation, we mark the stream as reset, so that user's on_read or
945 * on_write event callback picks up the error.  That, in turn, should result
946 * in stream being closed.
947 *
948 * If we have received any data frames on this stream, this probably indicates
949 * a bug in peer code: it should not have sent GOAWAY frame with stream ID
950 * lower than this.  However, we still try to handle it gracefully and peform
951 * a shutdown, as if the stream was not reset.
952 */
953void
954lsquic_stream_received_goaway (lsquic_stream_t *stream)
955{
956    SM_HISTORY_APPEND(stream, SHE_GOAWAY_IN);
957    if (0 == stream->read_offset &&
958                            stream->data_in->di_if->di_empty(stream->data_in))
959        fake_reset_unused_stream(stream);       /* Normal condition */
960    else
961    {   /* This is odd, let's handle it the best we can: */
962        LSQ_WARN("GOAWAY received but have incoming data: shut down instead");
963        lsquic_stream_shutdown_internal(stream);
964    }
965}
966
967
968uint64_t
969lsquic_stream_read_offset (const lsquic_stream_t *stream)
970{
971    return stream->read_offset;
972}
973
974
975static int
976stream_wantread (lsquic_stream_t *stream, int is_want)
977{
978    const int old_val = !!(stream->stream_flags & STREAM_WANT_READ);
979    const int new_val = !!is_want;
980    if (old_val != new_val)
981    {
982        if (new_val)
983        {
984            if (!old_val)
985                TAILQ_INSERT_TAIL(&stream->conn_pub->read_streams, stream,
986                                                            next_read_stream);
987            stream->stream_flags |= STREAM_WANT_READ;
988        }
989        else
990        {
991            stream->stream_flags &= ~STREAM_WANT_READ;
992            if (old_val)
993                TAILQ_REMOVE(&stream->conn_pub->read_streams, stream,
994                                                            next_read_stream);
995        }
996    }
997    return old_val;
998}
999
1000
1001static void
1002maybe_put_onto_write_q (lsquic_stream_t *stream, enum stream_flags flag)
1003{
1004    assert(STREAM_WRITE_Q_FLAGS & flag);
1005    if (!(stream->stream_flags & STREAM_WRITE_Q_FLAGS))
1006        TAILQ_INSERT_TAIL(&stream->conn_pub->write_streams, stream,
1007                                                        next_write_stream);
1008    stream->stream_flags |= flag;
1009}
1010
1011
1012static void
1013maybe_remove_from_write_q (lsquic_stream_t *stream, enum stream_flags flag)
1014{
1015    assert(STREAM_WRITE_Q_FLAGS & flag);
1016    if (stream->stream_flags & flag)
1017    {
1018        stream->stream_flags &= ~flag;
1019        if (!(stream->stream_flags & STREAM_WRITE_Q_FLAGS))
1020            TAILQ_REMOVE(&stream->conn_pub->write_streams, stream,
1021                                                        next_write_stream);
1022    }
1023}
1024
1025
1026static int
1027stream_wantwrite (lsquic_stream_t *stream, int is_want)
1028{
1029    const int old_val = !!(stream->stream_flags & STREAM_WANT_WRITE);
1030    const int new_val = !!is_want;
1031    if (old_val != new_val)
1032    {
1033        if (new_val)
1034            maybe_put_onto_write_q(stream, STREAM_WANT_WRITE);
1035        else
1036            maybe_remove_from_write_q(stream, STREAM_WANT_WRITE);
1037    }
1038    return old_val;
1039}
1040
1041
1042int
1043lsquic_stream_wantread (lsquic_stream_t *stream, int is_want)
1044{
1045    if (!(stream->stream_flags & STREAM_U_READ_DONE))
1046    {
1047        if (is_want)
1048            maybe_conn_to_tickable_if_readable(stream);
1049        return stream_wantread(stream, is_want);
1050    }
1051    else
1052    {
1053        errno = EBADF;
1054        return -1;
1055    }
1056}
1057
1058
1059int
1060lsquic_stream_wantwrite (lsquic_stream_t *stream, int is_want)
1061{
1062    if (0 == (stream->stream_flags & STREAM_U_WRITE_DONE))
1063    {
1064        if (is_want)
1065            maybe_conn_to_tickable_if_writeable(stream, 1);
1066        return stream_wantwrite(stream, is_want);
1067    }
1068    else
1069    {
1070        errno = EBADF;
1071        return -1;
1072    }
1073}
1074
1075
1076#define USER_PROGRESS_FLAGS (STREAM_WANT_READ|STREAM_WANT_WRITE|            \
1077    STREAM_WANT_FLUSH|STREAM_U_WRITE_DONE|STREAM_U_READ_DONE|STREAM_SEND_RST)
1078
1079
1080static void
1081stream_dispatch_read_events_loop (lsquic_stream_t *stream)
1082{
1083    unsigned no_progress_count, no_progress_limit;
1084    enum stream_flags flags;
1085    uint64_t size;
1086
1087    no_progress_limit = stream->conn_pub->enpub->enp_settings.es_progress_check;
1088
1089    no_progress_count = 0;
1090    while ((stream->stream_flags & STREAM_WANT_READ)
1091                                            && lsquic_stream_readable(stream))
1092    {
1093        flags = stream->stream_flags & USER_PROGRESS_FLAGS;
1094        size  = stream->read_offset;
1095
1096        stream->stream_if->on_read(stream, stream->st_ctx);
1097
1098        if (no_progress_limit && size == stream->read_offset &&
1099                        flags == (stream->stream_flags & USER_PROGRESS_FLAGS))
1100        {
1101            ++no_progress_count;
1102            if (no_progress_count >= no_progress_limit)
1103            {
1104                LSQ_WARN("broke suspected infinite loop (%u callback%s without "
1105                    "progress) in user code reading from stream",
1106                    no_progress_count,
1107                    no_progress_count == 1 ? "" : "s");
1108                break;
1109            }
1110        }
1111        else
1112            no_progress_count = 0;
1113    }
1114}
1115
1116
1117static void
1118stream_dispatch_write_events_loop (lsquic_stream_t *stream)
1119{
1120    unsigned no_progress_count, no_progress_limit;
1121    enum stream_flags flags;
1122
1123    no_progress_limit = stream->conn_pub->enpub->enp_settings.es_progress_check;
1124
1125    no_progress_count = 0;
1126    stream->stream_flags |= STREAM_LAST_WRITE_OK;
1127    while ((stream->stream_flags & (STREAM_WANT_WRITE|STREAM_LAST_WRITE_OK))
1128                                == (STREAM_WANT_WRITE|STREAM_LAST_WRITE_OK)
1129           && lsquic_stream_write_avail(stream))
1130    {
1131        flags = stream->stream_flags & USER_PROGRESS_FLAGS;
1132
1133        stream->stream_if->on_write(stream, stream->st_ctx);
1134
1135        if (no_progress_limit &&
1136            flags == (stream->stream_flags & USER_PROGRESS_FLAGS))
1137        {
1138            ++no_progress_count;
1139            if (no_progress_count >= no_progress_limit)
1140            {
1141                LSQ_WARN("broke suspected infinite loop (%u callback%s without "
1142                    "progress) in user code writing to stream",
1143                    no_progress_count,
1144                    no_progress_count == 1 ? "" : "s");
1145                break;
1146            }
1147        }
1148        else
1149            no_progress_count = 0;
1150    }
1151}
1152
1153
1154static void
1155stream_dispatch_read_events_once (lsquic_stream_t *stream)
1156{
1157    if ((stream->stream_flags & STREAM_WANT_READ) && lsquic_stream_readable(stream))
1158    {
1159        stream->stream_if->on_read(stream, stream->st_ctx);
1160    }
1161}
1162
1163
1164static void
1165maybe_mark_as_blocked (lsquic_stream_t *stream)
1166{
1167    struct lsquic_conn_cap *cc;
1168
1169    if (stream->max_send_off == stream->tosend_off + stream->sm_n_buffered)
1170    {
1171        if (stream->blocked_off < stream->max_send_off)
1172        {
1173            stream->blocked_off = stream->max_send_off + stream->sm_n_buffered;
1174            if (!(stream->stream_flags & STREAM_SENDING_FLAGS))
1175                TAILQ_INSERT_TAIL(&stream->conn_pub->sending_streams, stream,
1176                                                            next_send_stream);
1177            stream->stream_flags |= STREAM_SEND_BLOCKED;
1178            LSQ_DEBUG("marked stream-blocked at stream offset "
1179                                            "%"PRIu64, stream->blocked_off);
1180        }
1181        else
1182            LSQ_DEBUG("stream is blocked, but BLOCKED frame for offset %"PRIu64
1183                " has been, or is about to be, sent", stream->blocked_off);
1184    }
1185
1186    if ((stream->stream_flags & STREAM_CONN_LIMITED)
1187        && (cc = &stream->conn_pub->conn_cap,
1188                stream->sm_n_buffered == lsquic_conn_cap_avail(cc)))
1189    {
1190        if (cc->cc_blocked < cc->cc_max)
1191        {
1192            cc->cc_blocked = cc->cc_max;
1193            stream->conn_pub->lconn->cn_flags |= LSCONN_SEND_BLOCKED;
1194            LSQ_DEBUG("marked connection-blocked at connection offset "
1195                                                    "%"PRIu64, cc->cc_max);
1196        }
1197        else
1198            LSQ_DEBUG("stream has already been marked connection-blocked "
1199                "at offset %"PRIu64, cc->cc_blocked);
1200    }
1201}
1202
1203
1204void
1205lsquic_stream_dispatch_read_events (lsquic_stream_t *stream)
1206{
1207    assert(stream->stream_flags & STREAM_WANT_READ);
1208
1209    if (stream->stream_flags & STREAM_RW_ONCE)
1210        stream_dispatch_read_events_once(stream);
1211    else
1212        stream_dispatch_read_events_loop(stream);
1213}
1214
1215
1216void
1217lsquic_stream_dispatch_write_events (lsquic_stream_t *stream)
1218{
1219    int progress;
1220    uint64_t tosend_off;
1221    unsigned short n_buffered;
1222    enum stream_flags flags;
1223
1224    assert(stream->stream_flags & STREAM_WRITE_Q_FLAGS);
1225    flags = stream->stream_flags & STREAM_WRITE_Q_FLAGS;
1226    tosend_off = stream->tosend_off;
1227    n_buffered = stream->sm_n_buffered;
1228
1229    if (stream->stream_flags & STREAM_WANT_FLUSH)
1230        (void) stream_flush(stream);
1231
1232    if (stream->stream_flags & STREAM_RW_ONCE)
1233    {
1234        if ((stream->stream_flags & STREAM_WANT_WRITE)
1235            && lsquic_stream_write_avail(stream))
1236        {
1237            stream->stream_if->on_write(stream, stream->st_ctx);
1238        }
1239    }
1240    else
1241        stream_dispatch_write_events_loop(stream);
1242
1243    /* Progress means either flags or offsets changed: */
1244    progress = !((stream->stream_flags & STREAM_WRITE_Q_FLAGS) == flags &&
1245                        stream->tosend_off == tosend_off &&
1246                            stream->sm_n_buffered == n_buffered);
1247
1248    if (stream->stream_flags & STREAM_WRITE_Q_FLAGS)
1249    {
1250        if (progress)
1251        {   /* Move the stream to the end of the list to ensure fairness. */
1252            TAILQ_REMOVE(&stream->conn_pub->write_streams, stream,
1253                                                            next_write_stream);
1254            TAILQ_INSERT_TAIL(&stream->conn_pub->write_streams, stream,
1255                                                            next_write_stream);
1256        }
1257    }
1258}
1259
1260
1261static size_t
1262inner_reader_empty_size (void *ctx)
1263{
1264    return 0;
1265}
1266
1267
1268static size_t
1269inner_reader_empty_read (void *ctx, void *buf, size_t count)
1270{
1271    return 0;
1272}
1273
1274
1275static int
1276stream_flush (lsquic_stream_t *stream)
1277{
1278    struct lsquic_reader empty_reader;
1279    ssize_t nw;
1280
1281    assert(stream->stream_flags & STREAM_WANT_FLUSH);
1282    assert(stream->sm_n_buffered > 0 ||
1283        /* Flushing is also used to packetize standalone FIN: */
1284        ((stream->stream_flags & (STREAM_U_WRITE_DONE|STREAM_FIN_SENT))
1285                                                    == STREAM_U_WRITE_DONE));
1286
1287    empty_reader.lsqr_size = inner_reader_empty_size;
1288    empty_reader.lsqr_read = inner_reader_empty_read;
1289    empty_reader.lsqr_ctx  = NULL;  /* pro forma */
1290    nw = stream_write_to_packets(stream, &empty_reader, 0);
1291
1292    if (nw >= 0)
1293    {
1294        assert(nw == 0);    /* Empty reader: must have read zero bytes */
1295        return 0;
1296    }
1297    else
1298        return -1;
1299}
1300
1301
1302static int
1303stream_flush_nocheck (lsquic_stream_t *stream)
1304{
1305    stream->sm_flush_to = stream->tosend_off + stream->sm_n_buffered;
1306    maybe_put_onto_write_q(stream, STREAM_WANT_FLUSH);
1307    LSQ_DEBUG("will flush up to offset %"PRIu64, stream->sm_flush_to);
1308
1309    return stream_flush(stream);
1310}
1311
1312
1313int
1314lsquic_stream_flush (lsquic_stream_t *stream)
1315{
1316    if (stream->stream_flags & STREAM_U_WRITE_DONE)
1317    {
1318        LSQ_DEBUG("cannot flush closed stream");
1319        errno = EBADF;
1320        return -1;
1321    }
1322
1323    if (0 == stream->sm_n_buffered)
1324    {
1325        LSQ_DEBUG("flushing 0 bytes: noop");
1326        return 0;
1327    }
1328
1329    return stream_flush_nocheck(stream);
1330}
1331
1332
1333/* The flush threshold is the maximum size of stream data that can be sent
1334 * in a full packet.
1335 */
1336static size_t
1337flush_threshold (const lsquic_stream_t *stream)
1338{
1339    enum packet_out_flags flags;
1340    enum lsquic_packno_bits bits;
1341    unsigned packet_header_sz, stream_header_sz;
1342    size_t threshold;
1343
1344    bits = lsquic_send_ctl_packno_bits(stream->conn_pub->send_ctl);
1345    flags = bits << POBIT_SHIFT;
1346    if (!(stream->conn_pub->lconn->cn_flags & LSCONN_TCID0))
1347        flags |= PO_CONN_ID;
1348
1349    packet_header_sz = lsquic_po_header_length(flags);
1350    stream_header_sz = stream->conn_pub->lconn->cn_pf
1351            ->pf_calc_stream_frame_header_sz(stream->id, stream->tosend_off);
1352
1353    threshold = stream->conn_pub->lconn->cn_pack_size - QUIC_PACKET_HASH_SZ
1354              - packet_header_sz - stream_header_sz;
1355    return threshold;
1356}
1357
1358
1359#define COMMON_WRITE_CHECKS() do {                                          \
1360    if ((stream->stream_flags & (STREAM_USE_HEADERS|STREAM_HEADERS_SENT))   \
1361                                                   == STREAM_USE_HEADERS)   \
1362    {                                                                       \
1363        LSQ_WARN("Attempt to write to stream before sending HTTP headers"); \
1364        errno = EILSEQ;                                                     \
1365        return -1;                                                          \
1366    }                                                                       \
1367    if (stream->stream_flags & STREAM_RST_FLAGS)                            \
1368    {                                                                       \
1369        LSQ_INFO("Attempt to write to stream after it had been reset");     \
1370        errno = ECONNRESET;                                                 \
1371        return -1;                                                          \
1372    }                                                                       \
1373    if (stream->stream_flags & (STREAM_U_WRITE_DONE|STREAM_FIN_SENT))       \
1374    {                                                                       \
1375        LSQ_WARN("Attempt to write to stream after it was closed for "      \
1376                                                                "writing"); \
1377        errno = EBADF;                                                      \
1378        return -1;                                                          \
1379    }                                                                       \
1380} while (0)
1381
1382
1383struct frame_gen_ctx
1384{
1385    lsquic_stream_t      *fgc_stream;
1386    struct lsquic_reader *fgc_reader;
1387    /* We keep our own count of how many bytes were read from reader because
1388     * some readers are external.  The external caller does not have to rely
1389     * on our count, but it can.
1390     */
1391    size_t                fgc_nread_from_reader;
1392};
1393
1394
1395static size_t
1396frame_gen_size (void *ctx)
1397{
1398    struct frame_gen_ctx *fg_ctx = ctx;
1399    size_t available, remaining;
1400
1401    /* Make sure we are not writing past available size: */
1402    remaining = fg_ctx->fgc_reader->lsqr_size(fg_ctx->fgc_reader->lsqr_ctx);
1403    available = lsquic_stream_write_avail(fg_ctx->fgc_stream);
1404    if (available < remaining)
1405        remaining = available;
1406
1407    return remaining + fg_ctx->fgc_stream->sm_n_buffered;
1408}
1409
1410
1411static int
1412frame_gen_fin (void *ctx)
1413{
1414    struct frame_gen_ctx *fg_ctx = ctx;
1415    return fg_ctx->fgc_stream->stream_flags & STREAM_U_WRITE_DONE
1416        && 0 == fg_ctx->fgc_stream->sm_n_buffered
1417        /* Do not use frame_gen_size() as it may chop the real size: */
1418        && 0 == fg_ctx->fgc_reader->lsqr_size(fg_ctx->fgc_reader->lsqr_ctx);
1419}
1420
1421
1422static void
1423incr_conn_cap (struct lsquic_stream *stream, size_t incr)
1424{
1425    if (stream->stream_flags & STREAM_CONN_LIMITED)
1426    {
1427        stream->conn_pub->conn_cap.cc_sent += incr;
1428        assert(stream->conn_pub->conn_cap.cc_sent
1429                                    <= stream->conn_pub->conn_cap.cc_max);
1430    }
1431}
1432
1433
1434static size_t
1435frame_gen_read (void *ctx, void *begin_buf, size_t len, int *fin)
1436{
1437    struct frame_gen_ctx *fg_ctx = ctx;
1438    unsigned char *p = begin_buf;
1439    unsigned char *const end = p + len;
1440    lsquic_stream_t *const stream = fg_ctx->fgc_stream;
1441    size_t n_written, available, n_to_write;
1442
1443    if (stream->sm_n_buffered > 0)
1444    {
1445        if (len <= stream->sm_n_buffered)
1446        {
1447            memcpy(p, stream->sm_buf, len);
1448            memmove(stream->sm_buf, stream->sm_buf + len,
1449                                                stream->sm_n_buffered - len);
1450            stream->sm_n_buffered -= len;
1451            stream->tosend_off += len;
1452            *fin = frame_gen_fin(fg_ctx);
1453            return len;
1454        }
1455        memcpy(p, stream->sm_buf, stream->sm_n_buffered);
1456        p += stream->sm_n_buffered;
1457        stream->sm_n_buffered = 0;
1458    }
1459
1460    available = lsquic_stream_write_avail(fg_ctx->fgc_stream);
1461    n_to_write = end - p;
1462    if (n_to_write > available)
1463        n_to_write = available;
1464    n_written = fg_ctx->fgc_reader->lsqr_read(fg_ctx->fgc_reader->lsqr_ctx, p,
1465                                              n_to_write);
1466    p += n_written;
1467    fg_ctx->fgc_nread_from_reader += n_written;
1468    *fin = frame_gen_fin(fg_ctx);
1469    stream->tosend_off += p - (const unsigned char *) begin_buf;
1470    incr_conn_cap(stream, n_written);
1471    return p - (const unsigned char *) begin_buf;
1472}
1473
1474
1475static void
1476check_flush_threshold (lsquic_stream_t *stream)
1477{
1478    if ((stream->stream_flags & STREAM_WANT_FLUSH) &&
1479                            stream->tosend_off >= stream->sm_flush_to)
1480    {
1481        LSQ_DEBUG("flushed to or past required offset %"PRIu64,
1482                                                    stream->sm_flush_to);
1483        maybe_remove_from_write_q(stream, STREAM_WANT_FLUSH);
1484    }
1485}
1486
1487
1488static struct lsquic_packet_out *
1489get_brand_new_packet (struct lsquic_send_ctl *ctl, unsigned need_at_least,
1490                      const struct lsquic_stream *stream)
1491{
1492    return lsquic_send_ctl_new_packet_out(ctl, need_at_least);
1493}
1494
1495
1496static struct lsquic_packet_out * (* const get_packet[])(
1497    struct lsquic_send_ctl *, unsigned, const struct lsquic_stream *) =
1498{
1499    lsquic_send_ctl_get_packet_for_stream,
1500    get_brand_new_packet,
1501};
1502
1503
1504static enum { SWTP_OK, SWTP_STOP, SWTP_ERROR }
1505stream_write_to_packet (struct frame_gen_ctx *fg_ctx, const size_t size)
1506{
1507    lsquic_stream_t *const stream = fg_ctx->fgc_stream;
1508    const struct parse_funcs *const pf = stream->conn_pub->lconn->cn_pf;
1509    struct lsquic_send_ctl *const send_ctl = stream->conn_pub->send_ctl;
1510    unsigned stream_header_sz, need_at_least, off;
1511    lsquic_packet_out_t *packet_out;
1512    int len, s, hsk;
1513
1514    stream_header_sz = pf->pf_calc_stream_frame_header_sz(stream->id,
1515                                                        stream->tosend_off);
1516    need_at_least = stream_header_sz + (size > 0);
1517    hsk = LSQUIC_STREAM_HANDSHAKE == stream->id;
1518    packet_out = get_packet[hsk](send_ctl, need_at_least, stream);
1519    if (!packet_out)
1520        return SWTP_STOP;
1521
1522    off = packet_out->po_data_sz;
1523    len = pf->pf_gen_stream_frame(
1524                packet_out->po_data + packet_out->po_data_sz,
1525                lsquic_packet_out_avail(packet_out), stream->id,
1526                stream->tosend_off,
1527                frame_gen_fin(fg_ctx), size, frame_gen_read, fg_ctx);
1528    if (len < 0)
1529    {
1530        LSQ_ERROR("could not generate stream frame");
1531        return SWTP_ERROR;
1532    }
1533
1534    EV_LOG_GENERATED_STREAM_FRAME(LSQUIC_LOG_CONN_ID, pf,
1535                            packet_out->po_data + packet_out->po_data_sz, len);
1536    lsquic_send_ctl_incr_pack_sz(send_ctl, packet_out, len);
1537    packet_out->po_frame_types |= 1 << QUIC_FRAME_STREAM;
1538    if (0 == lsquic_packet_out_avail(packet_out))
1539        packet_out->po_flags |= PO_STREAM_END;
1540    s = lsquic_packet_out_add_stream(packet_out, stream->conn_pub->mm,
1541                                     stream, QUIC_FRAME_STREAM, off, len);
1542    if (s != 0)
1543    {
1544        LSQ_ERROR("adding stream to packet failed: %s", strerror(errno));
1545        return SWTP_ERROR;
1546    }
1547
1548    check_flush_threshold(stream);
1549
1550    /* XXX: I don't like it that this is here */
1551    if (hsk && !(packet_out->po_flags & PO_HELLO))
1552    {
1553        lsquic_packet_out_zero_pad(packet_out);
1554        packet_out->po_flags |= PO_HELLO;
1555        lsquic_send_ctl_scheduled_one(send_ctl, packet_out);
1556    }
1557
1558    return SWTP_OK;
1559}
1560
1561
1562static void
1563abort_connection (struct lsquic_stream *stream)
1564{
1565    if (0 == (stream->stream_flags & STREAM_SERVICE_FLAGS))
1566        TAILQ_INSERT_TAIL(&stream->conn_pub->service_streams, stream,
1567                                                next_service_stream);
1568    stream->stream_flags |= STREAM_ABORT_CONN;
1569    LSQ_WARN("connection will be aborted");
1570    maybe_conn_to_tickable(stream);
1571}
1572
1573
1574static ssize_t
1575stream_write_to_packets (lsquic_stream_t *stream, struct lsquic_reader *reader,
1576                         size_t thresh)
1577{
1578    size_t size;
1579    ssize_t nw;
1580    unsigned seen_ok;
1581    struct frame_gen_ctx fg_ctx = {
1582        .fgc_stream = stream,
1583        .fgc_reader = reader,
1584        .fgc_nread_from_reader = 0,
1585    };
1586
1587    seen_ok = 0;
1588    while ((size = frame_gen_size(&fg_ctx), thresh ? size >= thresh : size > 0)
1589           || frame_gen_fin(&fg_ctx))
1590    {
1591        switch (stream_write_to_packet(&fg_ctx, size))
1592        {
1593        case SWTP_OK:
1594            if (!seen_ok++)
1595                maybe_conn_to_tickable_if_writeable(stream, 0);
1596            if (frame_gen_fin(&fg_ctx))
1597            {
1598                stream->stream_flags |= STREAM_FIN_SENT;
1599                goto end;
1600            }
1601            else
1602                break;
1603        case SWTP_STOP:
1604            stream->stream_flags &= ~STREAM_LAST_WRITE_OK;
1605            goto end;
1606        default:
1607            abort_connection(stream);
1608            stream->stream_flags &= ~STREAM_LAST_WRITE_OK;
1609            return -1;
1610        }
1611    }
1612
1613    if (thresh)
1614    {
1615        assert(size < thresh);
1616        assert(size >= stream->sm_n_buffered);
1617        size -= stream->sm_n_buffered;
1618        if (size > 0)
1619        {
1620            nw = save_to_buffer(stream, reader, size);
1621            if (nw < 0)
1622                return -1;
1623            fg_ctx.fgc_nread_from_reader += nw; /* Make this cleaner? */
1624        }
1625    }
1626    else
1627    {
1628        /* We count flushed data towards both stream and connection limits,
1629         * so we should have been able to packetize all of it:
1630         */
1631        assert(0 == stream->sm_n_buffered);
1632        assert(size == 0);
1633    }
1634
1635    maybe_mark_as_blocked(stream);
1636
1637  end:
1638    return fg_ctx.fgc_nread_from_reader;
1639}
1640
1641
1642/* Perform an implicit flush when we hit connection limit while buffering
1643 * data.  This is to prevent a (theoretical) stall:
1644 *
1645 * Imagine a number of streams, all of which buffered some data.  The buffered
1646 * data is up to connection cap, which means no further writes are possible.
1647 * None of them flushes, which means that data is not sent and connection
1648 * WINDOW_UPDATE frame never arrives from peer.  Stall.
1649 */
1650static int
1651maybe_flush_stream (struct lsquic_stream *stream)
1652{
1653    if (stream->sm_n_buffered > 0
1654          && (stream->stream_flags & STREAM_CONN_LIMITED)
1655            && lsquic_conn_cap_avail(&stream->conn_pub->conn_cap) == 0)
1656        return stream_flush_nocheck(stream);
1657    else
1658        return 0;
1659}
1660
1661
1662static ssize_t
1663save_to_buffer (lsquic_stream_t *stream, struct lsquic_reader *reader,
1664                                                                size_t len)
1665{
1666    size_t avail, n_written;
1667
1668    assert(stream->sm_n_buffered + len <= SM_BUF_SIZE);
1669
1670    if (!stream->sm_buf)
1671    {
1672        stream->sm_buf = malloc(SM_BUF_SIZE);
1673        if (!stream->sm_buf)
1674            return -1;
1675    }
1676
1677    avail = lsquic_stream_write_avail(stream);
1678    if (avail < len)
1679        len = avail;
1680
1681    n_written = reader->lsqr_read(reader->lsqr_ctx,
1682                        stream->sm_buf + stream->sm_n_buffered, len);
1683    stream->sm_n_buffered += n_written;
1684    incr_conn_cap(stream, n_written);
1685    LSQ_DEBUG("buffered %zd bytes; %hu bytes are now in buffer",
1686              n_written, stream->sm_n_buffered);
1687    if (0 != maybe_flush_stream(stream))
1688        return -1;
1689    return n_written;
1690}
1691
1692
1693static ssize_t
1694stream_write (lsquic_stream_t *stream, struct lsquic_reader *reader)
1695{
1696    size_t thresh, len;
1697
1698    thresh = flush_threshold(stream);
1699    len = reader->lsqr_size(reader->lsqr_ctx);
1700    if (stream->sm_n_buffered + len <= SM_BUF_SIZE &&
1701                                    stream->sm_n_buffered + len < thresh)
1702        return save_to_buffer(stream, reader, len);
1703    else
1704        return stream_write_to_packets(stream, reader, thresh);
1705}
1706
1707
1708ssize_t
1709lsquic_stream_write (lsquic_stream_t *stream, const void *buf, size_t len)
1710{
1711    struct iovec iov = { .iov_base = (void *) buf, .iov_len = len, };
1712    return lsquic_stream_writev(stream, &iov, 1);
1713}
1714
1715
1716struct inner_reader_iovec {
1717    const struct iovec       *iov;
1718    const struct iovec *end;
1719    unsigned                  cur_iovec_off;
1720};
1721
1722
1723static size_t
1724inner_reader_iovec_read (void *ctx, void *buf, size_t count)
1725{
1726    struct inner_reader_iovec *const iro = ctx;
1727    unsigned char *p = buf;
1728    unsigned char *const end = p + count;
1729    unsigned n_tocopy;
1730
1731    while (iro->iov < iro->end && p < end)
1732    {
1733        n_tocopy = iro->iov->iov_len - iro->cur_iovec_off;
1734        if (n_tocopy > (unsigned) (end - p))
1735            n_tocopy = end - p;
1736        memcpy(p, (unsigned char *) iro->iov->iov_base + iro->cur_iovec_off,
1737                                                                    n_tocopy);
1738        p += n_tocopy;
1739        iro->cur_iovec_off += n_tocopy;
1740        if (iro->iov->iov_len == iro->cur_iovec_off)
1741        {
1742            ++iro->iov;
1743            iro->cur_iovec_off = 0;
1744        }
1745    }
1746
1747    return p + count - end;
1748}
1749
1750
1751static size_t
1752inner_reader_iovec_size (void *ctx)
1753{
1754    struct inner_reader_iovec *const iro = ctx;
1755    const struct iovec *iov;
1756    size_t size;
1757
1758    size = 0;
1759    for (iov = iro->iov; iov < iro->end; ++iov)
1760        size += iov->iov_len;
1761
1762    return size - iro->cur_iovec_off;
1763}
1764
1765
1766ssize_t
1767lsquic_stream_writev (lsquic_stream_t *stream, const struct iovec *iov,
1768                                                                    int iovcnt)
1769{
1770    COMMON_WRITE_CHECKS();
1771    SM_HISTORY_APPEND(stream, SHE_USER_WRITE_DATA);
1772
1773    struct inner_reader_iovec iro = {
1774        .iov = iov,
1775        .end = iov + iovcnt,
1776        .cur_iovec_off = 0,
1777    };
1778    struct lsquic_reader reader = {
1779        .lsqr_read = inner_reader_iovec_read,
1780        .lsqr_size = inner_reader_iovec_size,
1781        .lsqr_ctx  = &iro,
1782    };
1783
1784    return stream_write(stream, &reader);
1785}
1786
1787
1788ssize_t
1789lsquic_stream_writef (lsquic_stream_t *stream, struct lsquic_reader *reader)
1790{
1791    COMMON_WRITE_CHECKS();
1792    SM_HISTORY_APPEND(stream, SHE_USER_WRITE_DATA);
1793    return stream_write(stream, reader);
1794}
1795
1796
1797int
1798lsquic_stream_send_headers (lsquic_stream_t *stream,
1799                            const lsquic_http_headers_t *headers, int eos)
1800{
1801    if ((stream->stream_flags & (STREAM_USE_HEADERS|STREAM_HEADERS_SENT|
1802                                                     STREAM_U_WRITE_DONE))
1803                == STREAM_USE_HEADERS)
1804    {
1805        int s = lsquic_headers_stream_send_headers(stream->conn_pub->hs,
1806                    stream->id, headers, eos, lsquic_stream_priority(stream));
1807        if (0 == s)
1808        {
1809            SM_HISTORY_APPEND(stream, SHE_USER_WRITE_HEADER);
1810            stream->stream_flags |= STREAM_HEADERS_SENT;
1811            if (eos)
1812                stream->stream_flags |= STREAM_FIN_SENT;
1813            LSQ_INFO("sent headers for stream %u", stream->id);
1814        }
1815        else
1816            LSQ_WARN("could not send headers: %s", strerror(errno));
1817        return s;
1818    }
1819    else
1820    {
1821        LSQ_WARN("cannot send headers for stream %u in this state", stream->id);
1822        errno = EBADMSG;
1823        return -1;
1824    }
1825}
1826
1827
1828void
1829lsquic_stream_window_update (lsquic_stream_t *stream, uint64_t offset)
1830{
1831    if (offset > stream->max_send_off)
1832    {
1833        SM_HISTORY_APPEND(stream, SHE_WINDOW_UPDATE);
1834        LSQ_DEBUG("stream %u: update max send offset from 0x%"PRIX64" to "
1835            "0x%"PRIX64, stream->id, stream->max_send_off, offset);
1836        stream->max_send_off = offset;
1837    }
1838    else
1839        LSQ_DEBUG("stream %u: new offset 0x%"PRIX64" is not larger than old "
1840            "max send offset 0x%"PRIX64", ignoring", stream->id, offset,
1841            stream->max_send_off);
1842}
1843
1844
1845/* This function is used to update offsets after handshake completes and we
1846 * learn of peer's limits from the handshake values.
1847 */
1848int
1849lsquic_stream_set_max_send_off (lsquic_stream_t *stream, unsigned offset)
1850{
1851    LSQ_DEBUG("setting max_send_off to %u", offset);
1852    if (offset > stream->max_send_off)
1853    {
1854        lsquic_stream_window_update(stream, offset);
1855        return 0;
1856    }
1857    else if (offset < stream->tosend_off)
1858    {
1859        LSQ_INFO("new offset (%u bytes) is smaller than the amount of data "
1860            "already sent on this stream (%"PRIu64" bytes)", offset,
1861            stream->tosend_off);
1862        return -1;
1863    }
1864    else
1865    {
1866        stream->max_send_off = offset;
1867        return 0;
1868    }
1869}
1870
1871
1872void
1873lsquic_stream_reset (lsquic_stream_t *stream, uint32_t error_code)
1874{
1875    lsquic_stream_reset_ext(stream, error_code, 1);
1876}
1877
1878
1879void
1880lsquic_stream_reset_ext (lsquic_stream_t *stream, uint32_t error_code,
1881                         int do_close)
1882{
1883    if (stream->stream_flags & (STREAM_SEND_RST|STREAM_RST_SENT))
1884    {
1885        LSQ_INFO("reset already sent");
1886        return;
1887    }
1888
1889    SM_HISTORY_APPEND(stream, SHE_RESET);
1890
1891    LSQ_INFO("reset stream %u, error code 0x%X", stream->id, error_code);
1892    stream->error_code = error_code;
1893
1894    if (!(stream->stream_flags & STREAM_SENDING_FLAGS))
1895        TAILQ_INSERT_TAIL(&stream->conn_pub->sending_streams, stream,
1896                                                        next_send_stream);
1897    stream->stream_flags &= ~STREAM_SENDING_FLAGS;
1898    stream->stream_flags |= STREAM_SEND_RST;
1899
1900    drop_buffered_data(stream);
1901    maybe_elide_stream_frames(stream);
1902    maybe_schedule_call_on_close(stream);
1903
1904    if (do_close)
1905        lsquic_stream_close(stream);
1906    else
1907        maybe_conn_to_tickable_if_writeable(stream, 1);
1908}
1909
1910
1911unsigned
1912lsquic_stream_id (const lsquic_stream_t *stream)
1913{
1914    return stream->id;
1915}
1916
1917
1918struct lsquic_conn *
1919lsquic_stream_conn (const lsquic_stream_t *stream)
1920{
1921    return stream->conn_pub->lconn;
1922}
1923
1924
1925int
1926lsquic_stream_close (lsquic_stream_t *stream)
1927{
1928    LSQ_DEBUG("lsquic_stream_close(stream %u) called", stream->id);
1929    SM_HISTORY_APPEND(stream, SHE_CLOSE);
1930    if (lsquic_stream_is_closed(stream))
1931    {
1932        LSQ_INFO("Attempt to close an already-closed stream %u", stream->id);
1933        errno = EBADF;
1934        return -1;
1935    }
1936    stream_shutdown_write(stream);
1937    stream_shutdown_read(stream);
1938    maybe_schedule_call_on_close(stream);
1939    maybe_finish_stream(stream);
1940    maybe_conn_to_tickable_if_writeable(stream, 1);
1941    return 0;
1942}
1943
1944
1945#ifndef NDEBUG
1946#if __GNUC__
1947__attribute__((weak))
1948#endif
1949#endif
1950void
1951lsquic_stream_acked (lsquic_stream_t *stream)
1952{
1953    assert(stream->n_unacked);
1954    --stream->n_unacked;
1955    LSQ_DEBUG("stream %u ACKed; n_unacked: %u", stream->id, stream->n_unacked);
1956    if (0 == stream->n_unacked)
1957        maybe_finish_stream(stream);
1958}
1959
1960
1961void
1962lsquic_stream_push_req (lsquic_stream_t *stream,
1963                        struct uncompressed_headers *push_req)
1964{
1965    assert(!stream->push_req);
1966    stream->push_req = push_req;
1967    stream->stream_flags |= STREAM_U_WRITE_DONE;    /* Writing not allowed */
1968}
1969
1970
1971int
1972lsquic_stream_is_pushed (const lsquic_stream_t *stream)
1973{
1974    return 1 & ~stream->id;
1975}
1976
1977
1978int
1979lsquic_stream_push_info (const lsquic_stream_t *stream,
1980        uint32_t *ref_stream_id, const char **headers, size_t *headers_sz)
1981{
1982    if (lsquic_stream_is_pushed(stream))
1983    {
1984        assert(stream->push_req);
1985        *ref_stream_id = stream->push_req->uh_stream_id;
1986        *headers       = stream->push_req->uh_headers;
1987        *headers_sz    = stream->push_req->uh_size;
1988        return 0;
1989    }
1990    else
1991        return -1;
1992}
1993
1994
1995int
1996lsquic_stream_uh_in (lsquic_stream_t *stream, struct uncompressed_headers *uh)
1997{
1998    if ((stream->stream_flags & (STREAM_USE_HEADERS|STREAM_HAVE_UH)) == STREAM_USE_HEADERS)
1999    {
2000        SM_HISTORY_APPEND(stream, SHE_HEADERS_IN);
2001        LSQ_DEBUG("received uncompressed headers for stream %u", stream->id);
2002        stream->stream_flags |= STREAM_HAVE_UH;
2003        if (uh->uh_flags & UH_FIN)
2004            stream->stream_flags |= STREAM_FIN_RECVD|STREAM_HEAD_IN_FIN;
2005        stream->uh = uh;
2006        if (uh->uh_oth_stream_id == 0)
2007        {
2008            if (uh->uh_weight)
2009                lsquic_stream_set_priority_internal(stream, uh->uh_weight);
2010        }
2011        else
2012            LSQ_NOTICE("don't know how to depend on stream %u",
2013                                                        uh->uh_oth_stream_id);
2014        return 0;
2015    }
2016    else
2017    {
2018        LSQ_ERROR("received unexpected uncompressed headers for stream %u", stream->id);
2019        return -1;
2020    }
2021}
2022
2023
2024unsigned
2025lsquic_stream_priority (const lsquic_stream_t *stream)
2026{
2027    return 256 - stream->sm_priority;
2028}
2029
2030
2031int
2032lsquic_stream_set_priority_internal (lsquic_stream_t *stream, unsigned priority)
2033{
2034    /* The user should never get a reference to the special streams,
2035     * but let's check just in case:
2036     */
2037    if (LSQUIC_STREAM_HANDSHAKE == stream->id
2038        || ((stream->stream_flags & STREAM_USE_HEADERS) &&
2039                                LSQUIC_STREAM_HEADERS == stream->id))
2040        return -1;
2041    if (priority < 1 || priority > 256)
2042        return -1;
2043    stream->sm_priority = 256 - priority;
2044    lsquic_send_ctl_invalidate_bpt_cache(stream->conn_pub->send_ctl);
2045    LSQ_DEBUG("set priority to %u", priority);
2046    SM_HISTORY_APPEND(stream, SHE_SET_PRIO);
2047    return 0;
2048}
2049
2050
2051int
2052lsquic_stream_set_priority (lsquic_stream_t *stream, unsigned priority)
2053{
2054    if (0 == lsquic_stream_set_priority_internal(stream, priority))
2055    {
2056        if ((stream->stream_flags & (STREAM_USE_HEADERS|STREAM_HEADERS_SENT)) ==
2057                                       (STREAM_USE_HEADERS|STREAM_HEADERS_SENT))
2058        {
2059            /* We need to send headers only if we are a) using HEADERS stream
2060             * and b) we already sent initial headers.  If initial headers
2061             * have not been sent yet, stream priority will be sent in the
2062             * HEADERS frame.
2063             */
2064            return lsquic_headers_stream_send_priority(stream->conn_pub->hs,
2065                                                    stream->id, 0, 0, priority);
2066        }
2067        else
2068            return 0;
2069    }
2070    else
2071        return -1;
2072}
2073
2074
2075lsquic_stream_ctx_t *
2076lsquic_stream_get_ctx (const lsquic_stream_t *stream)
2077{
2078    return stream->st_ctx;
2079}
2080
2081
2082int
2083lsquic_stream_refuse_push (lsquic_stream_t *stream)
2084{
2085    if (lsquic_stream_is_pushed(stream) &&
2086                !(stream->stream_flags & (STREAM_RST_SENT|STREAM_SEND_RST)))
2087    {
2088        LSQ_DEBUG("refusing pushed stream: send reset");
2089        lsquic_stream_reset_ext(stream, 8 /* QUIC_REFUSED_STREAM */, 1);
2090        return 0;
2091    }
2092    else
2093        return -1;
2094}
2095
2096
2097size_t
2098lsquic_stream_mem_used (const struct lsquic_stream *stream)
2099{
2100    size_t size;
2101
2102    size = sizeof(stream);
2103    if (stream->sm_buf)
2104        size += SM_BUF_SIZE;
2105    if (stream->data_in)
2106        size += stream->data_in->di_if->di_mem_used(stream->data_in);
2107
2108    return size;
2109}
2110
2111
2112lsquic_cid_t
2113lsquic_stream_cid (const struct lsquic_stream *stream)
2114{
2115    return LSQUIC_LOG_CONN_ID;
2116}
2117