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