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