soup-client-message-io-http2.c 57.2 KB
Newer Older
Patrick Griffis's avatar
Patrick Griffis committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/* soup-message-io-http2.c
 *
 * Copyright 2021 Igalia S.L.
 *
 * This file is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This file is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * SPDX-License-Identifier: LGPL-2.0-or-later
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#undef G_LOG_DOMAIN
#define G_LOG_DOMAIN "libsoup-http2"

#include <glib.h>
#include <glib/gi18n-lib.h>

#include "soup-client-message-io-http2.h"

#include "soup-body-input-stream.h"
#include "soup-message-metrics-private.h"
#include "soup-message-private.h"
#include "soup-message-io-source.h"
#include "soup-message-queue-item.h"
#include "content-sniffer/soup-content-sniffer-stream.h"
#include "soup-client-input-stream.h"
#include "soup-logger-private.h"
#include "soup-uri-utils-private.h"

#include "content-decoder/soup-content-decoder.h"
#include "soup-body-input-stream-http2.h"

#include <nghttp2/nghttp2.h>

#define FRAME_HEADER_SIZE 9

typedef enum {
        STATE_NONE,
        STATE_WRITE_HEADERS,
        STATE_WRITE_DATA,
        STATE_WRITE_DONE,
        STATE_READ_HEADERS,
56
        STATE_READ_DATA_START,
Patrick Griffis's avatar
Patrick Griffis committed
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
        STATE_READ_DATA,
        STATE_READ_DONE,
} SoupHTTP2IOState;

typedef struct {
        SoupClientMessageIO iface;

        GIOStream *stream;
        GInputStream *istream;
        GOutputStream *ostream;
        guint64 connection_id;

        GMainContext *async_context;

        GHashTable *messages;

        nghttp2_session *session;

        /* Owned by nghttp2 */
        guint8 *write_buffer;
        gssize write_buffer_size;
        gssize written_bytes;

        gboolean is_shutdown;
81
82
83

        GSource *close_source;
        gboolean goaway_sent;
Patrick Griffis's avatar
Patrick Griffis committed
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
} SoupClientMessageIOHTTP2;

typedef struct {
        SoupMessageQueueItem *item;
        SoupMessage *msg;
        SoupMessageMetrics *metrics;
        GCancellable *cancellable;
        GInputStream *decoded_data_istream;
        GInputStream *body_istream;

        /* Request body logger */
        SoupLogger *logger;

        /* Both data sources */
        GCancellable *data_source_cancellable;

        /* Pollable data sources */
        GSource *data_source_poll;

        /* Non-pollable data sources */
        GByteArray *data_source_buffer;
        GError *data_source_error;
        gboolean data_source_eof;

        GSource *io_source;
        SoupClientMessageIOHTTP2 *io; /* Unowned */
        SoupMessageIOCompletionFn completion_cb;
        gpointer completion_data;
        SoupHTTP2IOState state;
113
        GError *error;
Patrick Griffis's avatar
Patrick Griffis committed
114
115
116
117
        gboolean paused;
        guint32 stream_id;
} SoupHTTP2MessageData;

118
static gboolean io_read (SoupClientMessageIOHTTP2 *, gboolean, GCancellable *, GError **);
Patrick Griffis's avatar
Patrick Griffis committed
119

120
121
122
123
124
125
126
127
128
static void
NGCHECK (int return_code)
{
        if (return_code == NGHTTP2_ERR_NOMEM)
                g_abort ();
        else if (return_code < 0)
                g_debug ("Unhandled NGHTTP2 Error: %s", nghttp2_strerror (return_code));
}

Patrick Griffis's avatar
Patrick Griffis committed
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
static const char *
frame_type_to_string (nghttp2_frame_type type)
{
        switch (type) {
        case NGHTTP2_DATA:
                return "DATA";
        case NGHTTP2_HEADERS:
                return "HEADERS";
        case NGHTTP2_PRIORITY:
                return "PRIORITY";
        case NGHTTP2_RST_STREAM:
                return "RST_STREAM";
        case NGHTTP2_SETTINGS:
                return "SETTINGS";
        case NGHTTP2_PING:
                return "PING";
        case NGHTTP2_GOAWAY:
                return "GOAWAY";
        case NGHTTP2_WINDOW_UPDATE:
                return "WINDOW_UPDATE";
149
150
151
        /* LCOV_EXCL_START */
        case NGHTTP2_PUSH_PROMISE:
                return "PUSH_PROMISE";
Patrick Griffis's avatar
Patrick Griffis committed
152
153
154
155
156
157
158
159
160
        case NGHTTP2_CONTINUATION:
                return "CONTINUATION";
        case NGHTTP2_ALTSVC:
                return "ALTSVC";
        case NGHTTP2_ORIGIN:
                return "ORIGIN";
        default:
                g_warn_if_reached ();
                return "UNKNOWN";
161
        /* LCOV_EXCL_STOP */
Patrick Griffis's avatar
Patrick Griffis committed
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
        }
}

static const char *
state_to_string (SoupHTTP2IOState state)
{
        switch (state) {
        case STATE_NONE:
                return "NONE";
        case STATE_WRITE_HEADERS:
                return "WRITE_HEADERS";
        case STATE_WRITE_DATA:
                return "WRITE_DATA";
        case STATE_WRITE_DONE:
                return "WRITE_DONE";
        case STATE_READ_HEADERS:
                return "READ_HEADERS";
179
180
        case STATE_READ_DATA_START:
                return "READ_DATA_START";
Patrick Griffis's avatar
Patrick Griffis committed
181
        case STATE_READ_DATA:
Carlos Garcia Campos's avatar
Carlos Garcia Campos committed
182
                return "READ_DATA";
Patrick Griffis's avatar
Patrick Griffis committed
183
184
185
186
187
188
189
190
        case STATE_READ_DONE:
                return "READ_DONE";
        default:
                g_assert_not_reached ();
                return "";
        }
}

191
G_GNUC_PRINTF(3, 0)
Patrick Griffis's avatar
Patrick Griffis committed
192
193
194
195
196
197
198
199
200
201
static void
h2_debug (SoupClientMessageIOHTTP2   *io,
          SoupHTTP2MessageData       *data,
          const char                 *format,
          ...)
{
        va_list args;
        char *message;
        guint32 stream_id = 0;

202
203
204
        if (g_log_writer_default_would_drop (G_LOG_LEVEL_DEBUG, G_LOG_DOMAIN))
                return;

Patrick Griffis's avatar
Patrick Griffis committed
205
206
207
208
209
210
211
212
	va_start (args, format);
	message = g_strdup_vprintf (format, args);
	va_end (args);

        if (data)
                stream_id = data->stream_id;

        g_assert (io);
213
        g_log (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, "[C%" G_GUINT64_FORMAT "-S%u] [%s] %s", io->connection_id, stream_id, data ? state_to_string (data->state) : "-", message);
Patrick Griffis's avatar
Patrick Griffis committed
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233

        g_free (message);
}

static SoupClientMessageIOHTTP2 *
get_io_data (SoupMessage *msg)
{
        return (SoupClientMessageIOHTTP2 *)soup_message_get_io_data (msg);
}

static int
get_data_io_priority (SoupHTTP2MessageData *data)
{
	if (!data->item->task)
		return G_PRIORITY_DEFAULT;

	return g_task_get_priority (data->item->task);
}

static void
234
set_error_for_data (SoupHTTP2MessageData *data,
Patrick Griffis's avatar
Patrick Griffis committed
235
236
                    GError               *error)
{
237
        h2_debug (data->io, data, "[SESSION] Error: %s", error->message);
Patrick Griffis's avatar
Patrick Griffis committed
238

239
240
241
242
243
        /* First error is probably the one we want. */
        if (!data->error)
                data->error = error;
        else
                g_error_free (error);
Patrick Griffis's avatar
Patrick Griffis committed
244
245
246
247
248
249
250
}

static void
advance_state_from (SoupHTTP2MessageData *data,
                    SoupHTTP2IOState      from,
                    SoupHTTP2IOState      to)
{
251
        if (data->state != from) {
252
253
254
255
                g_warning ("Unexpected state changed %s -> %s, expected to be from %s",
                           state_to_string (data->state), state_to_string (to),
                           state_to_string (from));
        }
Patrick Griffis's avatar
Patrick Griffis committed
256
257
258

        /* State never goes backwards */
        if (to < data->state) {
259
260
261
                g_warning ("Unexpected state changed %s -> %s, expected %s -> %s\n",
                           state_to_string (data->state), state_to_string (to),
                           state_to_string (from), state_to_string (to));
Patrick Griffis's avatar
Patrick Griffis committed
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
                return;
        }

        h2_debug (data->io, data, "[SESSION] State %s -> %s",
                  state_to_string (data->state), state_to_string (to));
        data->state = to;
}

/* HTTP2 read callbacks */

static int
on_header_callback (nghttp2_session     *session,
                    const nghttp2_frame *frame,
                    const uint8_t       *name,
                    size_t               namelen,
                    const uint8_t       *value,
                    size_t               valuelen,
                    uint8_t              flags,
                    void                *user_data)
{
        SoupHTTP2MessageData *data = nghttp2_session_get_stream_user_data (session, frame->hd.stream_id);

        if (!data)
                return 0;

        SoupMessage *msg = data->msg;
        if (name[0] == ':') {
                if (strcmp ((char *)name, ":status") == 0) {
                        guint status_code = (guint)g_ascii_strtoull ((char *)value, NULL, 10);
                        soup_message_set_status (msg, status_code, NULL);
                        return 0;
                }
                g_debug ("Unknown header: %s = %s", name, value);
                return 0;
        }

        // FIXME: Encoding
        char *name_utf8 = g_utf8_make_valid ((const char *)name, namelen);
        char *value_utf8 = g_utf8_make_valid ((const char *)value, valuelen);
        soup_message_headers_append (soup_message_get_response_headers (data->msg),
                                     name_utf8, value_utf8);
        g_free (name_utf8);
        g_free (value_utf8);
        return 0;
}

static GError *
memory_stream_need_more_data_callback (SoupBodyInputStreamHttp2 *stream,
                                       GCancellable             *cancellable,
                                       gboolean                  blocking,
                                       gpointer                  user_data)
{
        SoupHTTP2MessageData *data = (SoupHTTP2MessageData*)user_data;
        GError *error = NULL;

317
318
319
        if (!nghttp2_session_want_read (data->io->session))
                return blocking ? NULL : g_error_new_literal (G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK, _("Operation would block"));
        io_read (data->io, blocking, cancellable, &error);
Patrick Griffis's avatar
Patrick Griffis committed
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337

        return error;
}

static int
on_begin_frame_callback (nghttp2_session        *session,
                         const nghttp2_frame_hd *hd,
                         void                   *user_data)
{
        SoupHTTP2MessageData *data = nghttp2_session_get_stream_user_data (session, hd->stream_id);

        h2_debug (user_data, data, "[RECV] [%s] Beginning", frame_type_to_string (hd->type));

        if (!data)
                return 0;

        switch (hd->type) {
        case NGHTTP2_HEADERS:
338
339
                if (data->state < STATE_READ_HEADERS) {
                        soup_message_set_metrics_timestamp (data->item->msg, SOUP_MESSAGE_METRICS_RESPONSE_START);
340
                        advance_state_from (data, STATE_WRITE_DONE, STATE_READ_HEADERS);
341
                }
Patrick Griffis's avatar
Patrick Griffis committed
342
                break;
343
344
345
        case NGHTTP2_DATA:
                if (data->state < STATE_READ_DATA_START) {
                        g_assert (!data->body_istream);
Patrick Griffis's avatar
Patrick Griffis committed
346
347
348
                        data->body_istream = soup_body_input_stream_http2_new (G_POLLABLE_INPUT_STREAM (data->io->istream));
                        g_signal_connect (data->body_istream, "need-more-data",
                                          G_CALLBACK (memory_stream_need_more_data_callback), data);
349
350

                        g_assert (!data->decoded_data_istream);
Patrick Griffis's avatar
Patrick Griffis committed
351
352
353
354
                        data->decoded_data_istream = soup_session_setup_message_body_input_stream (data->item->session,
                                                                                                   data->msg,
                                                                                                   data->body_istream,
                                                                                                   SOUP_STAGE_MESSAGE_BODY);
355
356
357

                        advance_state_from (data, STATE_READ_HEADERS, STATE_READ_DATA_START);
                }
Patrick Griffis's avatar
Patrick Griffis committed
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
                break;
        }

        return 0;
}

static void
handle_goaway (SoupClientMessageIOHTTP2 *io,
               guint32                   error_code,
               guint32                   last_stream_id)
{
        GHashTableIter iter;
        SoupHTTP2MessageData *data;

        g_hash_table_iter_init (&iter, io->messages);
        while (g_hash_table_iter_next (&iter, NULL, (gpointer*)&data)) {
                /* If there is no error it is a graceful shutdown and
                 * existing messages can be handled otherwise it is a fatal error */
                if ((error_code == 0 && data->stream_id > last_stream_id) ||
                     data->state < STATE_READ_DONE) {
                        /* TODO: We can restart unfinished messages */
379
                        set_error_for_data (data, g_error_new (G_IO_ERROR, G_IO_ERROR_FAILED,
Patrick Griffis's avatar
Patrick Griffis committed
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
                                            "HTTP/2 Error: %s", nghttp2_http2_strerror (error_code)));
                }
        }
}

static int
on_frame_recv_callback (nghttp2_session     *session,
                        const nghttp2_frame *frame,
                        gpointer             user_data)
{
        SoupClientMessageIOHTTP2 *io = user_data;
        SoupHTTP2MessageData *data = nghttp2_session_get_stream_user_data (session, frame->hd.stream_id);

        h2_debug (io, data, "[RECV] [%s] Recieved (%u)", frame_type_to_string (frame->hd.type), frame->hd.flags);

        if (frame->hd.type == NGHTTP2_GOAWAY) {
                handle_goaway (io, frame->goaway.error_code, frame->goaway.last_stream_id);
                io->is_shutdown = TRUE;
                return 0;
        }

        if (!data) {
                if (frame->hd.stream_id != 0 && !(frame->hd.flags & NGHTTP2_FLAG_END_STREAM))
                        g_warn_if_reached ();
                return 0;
        }

        switch (frame->hd.type) {
        case NGHTTP2_HEADERS:
                if (data->metrics)
                        data->metrics->response_header_bytes_received += frame->hd.length + FRAME_HEADER_SIZE;

                if (frame->headers.cat == NGHTTP2_HCAT_RESPONSE && frame->hd.flags & NGHTTP2_FLAG_END_HEADERS) {
                        h2_debug (io, data, "[HEADERS] status %u", soup_message_get_status (data->msg));
                        if (SOUP_STATUS_IS_INFORMATIONAL (soup_message_get_status (data->msg))) {
                                soup_message_got_informational (data->msg);
                                soup_message_cleanup_response (data->msg);
                                advance_state_from (data, STATE_READ_HEADERS, STATE_READ_DONE);
418
419
420
421
422
423
424
                                return 0;
                        }

                        if (soup_message_get_status (data->msg) == SOUP_STATUS_NO_CONTENT ||
                            frame->hd.flags & NGHTTP2_FLAG_END_STREAM) {
                                h2_debug (io, data, "Stream done");
                                advance_state_from (data, STATE_READ_HEADERS, STATE_READ_DATA);
Patrick Griffis's avatar
Patrick Griffis committed
425
426
427
428
429
430
431
                        }
                        soup_message_got_headers (data->msg);
                }
                break;
        case NGHTTP2_DATA:
                if (data->metrics)
                        data->metrics->response_body_bytes_received += frame->data.hd.length + FRAME_HEADER_SIZE;
432
                if (frame->hd.flags & NGHTTP2_FLAG_END_STREAM && data->body_istream)
433
                        soup_body_input_stream_http2_complete (SOUP_BODY_INPUT_STREAM_HTTP2 (data->body_istream));
Patrick Griffis's avatar
Patrick Griffis committed
434
435
436
                break;
        case NGHTTP2_RST_STREAM:
                if (frame->rst_stream.error_code != NGHTTP2_NO_ERROR) {
437
438
                        set_error_for_data (data, g_error_new_literal (G_IO_ERROR, G_IO_ERROR_FAILED,
                                                                       nghttp2_http2_strerror (frame->rst_stream.error_code)));
Patrick Griffis's avatar
Patrick Griffis committed
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
                }
                break;
        };

        return 0;
}

static int
on_data_chunk_recv_callback (nghttp2_session *session,
                             uint8_t          flags,
                             int32_t          stream_id,
                             const uint8_t   *data,
                             size_t           len,
                             void            *user_data)
{
        SoupClientMessageIOHTTP2 *io = user_data;
        SoupHTTP2MessageData *msgdata = nghttp2_session_get_stream_user_data (session, stream_id);

        if (!msgdata)
                return NGHTTP2_ERR_CALLBACK_FAILURE;

        h2_debug (io, msgdata, "[DATA] Recieved chunk, len=%zu, flags=%u, paused=%d", len, flags, msgdata->paused);

        g_assert (msgdata->body_istream != NULL);
        soup_body_input_stream_http2_add_data (SOUP_BODY_INPUT_STREAM_HTTP2 (msgdata->body_istream), data, len);

        return 0;
}

/* HTTP2 write callbacks */

static int
on_before_frame_send_callback (nghttp2_session     *session,
                               const nghttp2_frame *frame,
                               void                *user_data)
{
        SoupHTTP2MessageData *data = nghttp2_session_get_stream_user_data (session, frame->hd.stream_id);

        if (!data)
                return 0;

        switch (frame->hd.type) {
        case NGHTTP2_HEADERS:
                advance_state_from (data, STATE_NONE, STATE_WRITE_HEADERS);
                break;
        }

        return 0;
}

static int
on_frame_send_callback (nghttp2_session     *session,
                        const nghttp2_frame *frame,
                        void                *user_data)
{
        SoupHTTP2MessageData *data = nghttp2_session_get_stream_user_data (session, frame->hd.stream_id);

        if (!data) {
                h2_debug (user_data, NULL, "[SEND] [%s]", frame_type_to_string (frame->hd.type));
                return 0;
        }

        switch (frame->hd.type) {
        case NGHTTP2_HEADERS:
                h2_debug (user_data, data, "[SEND] [HEADERS] finished=%d",
                          (frame->hd.flags & NGHTTP2_FLAG_END_HEADERS) ? 1 : 0);
                if (data->metrics)
                        data->metrics->request_header_bytes_sent += frame->hd.length + FRAME_HEADER_SIZE;

                if (frame->hd.flags & NGHTTP2_FLAG_END_HEADERS) {
                        soup_message_wrote_headers (data->msg);
                        if (soup_message_get_request_body_stream (data->msg) == NULL) {
                                advance_state_from (data, STATE_WRITE_HEADERS, STATE_WRITE_DONE);
                                soup_message_wrote_body (data->msg);
                        }
                }
                break;
        case NGHTTP2_DATA:
                h2_debug (user_data, data, "[SEND] [DATA] bytes=%zu, finished=%d",
                          frame->data.hd.length, frame->hd.flags & NGHTTP2_FLAG_END_STREAM);
519
520
                if (data->state < STATE_WRITE_DATA)
                        advance_state_from (data, STATE_WRITE_HEADERS, STATE_WRITE_DATA);
Patrick Griffis's avatar
Patrick Griffis committed
521
522
523
524
525
526
527
                if (data->metrics) {
                        data->metrics->request_body_bytes_sent += frame->hd.length + FRAME_HEADER_SIZE;
                        data->metrics->request_body_size += frame->data.hd.length;
                }
                if (frame->data.hd.length)
                        soup_message_wrote_body_data (data->msg, frame->data.hd.length);
                if (frame->hd.flags & NGHTTP2_FLAG_END_STREAM) {
528
                        advance_state_from (data, STATE_WRITE_DATA, STATE_WRITE_DONE);
Patrick Griffis's avatar
Patrick Griffis committed
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
                        soup_message_wrote_body (data->msg);
                }
                break;
        default:
                h2_debug (user_data, NULL, "[SEND] [%s]", frame_type_to_string (frame->hd.type));
                break;
        }

        return 0;
}

static int
on_frame_not_send_callback (nghttp2_session     *session,
                            const nghttp2_frame *frame,
                            int                  lib_error_code,
                            void                *user_data)
{
        SoupHTTP2MessageData *data = nghttp2_session_get_stream_user_data (session, frame->hd.stream_id);

        h2_debug (user_data, data, "[SEND] [%s] Failed: %s", frame_type_to_string (frame->hd.type),
                  nghttp2_strerror (lib_error_code));

        return 0;
}

static int
on_stream_close_callback (nghttp2_session *session,
                          int32_t          stream_id,
                          uint32_t         error_code,
                          void            *user_data)
{
        g_debug ("[S%d] [SESSION] Closed: %s", stream_id, nghttp2_http2_strerror (error_code));
        return 0;
}

static gboolean
on_data_readable (GInputStream *stream,
                  gpointer      user_data)
{
        SoupHTTP2MessageData *data = (SoupHTTP2MessageData*)user_data;

570
571
572
        g_cancellable_cancel (data->data_source_cancellable);
        g_clear_object (&data->data_source_cancellable);

573
        NGCHECK (nghttp2_session_resume_data (data->io->session, data->stream_id));
Patrick Griffis's avatar
Patrick Griffis committed
574
575
576
577
578
579
580
581
582
583
584
585
586
587

        g_clear_pointer (&data->data_source_poll, g_source_unref);
        return G_SOURCE_REMOVE;
}

static void
on_data_read (GInputStream *source,
              GAsyncResult *res,
              gpointer      user_data)
{
        SoupHTTP2MessageData *data = user_data;
        GError *error = NULL;
        gssize read = g_input_stream_read_finish (source, res, &error);

588
        h2_debug (data->io, data, "[SEND_BODY] Read %zd", read);
Patrick Griffis's avatar
Patrick Griffis committed
589

590
591
592
        g_cancellable_cancel (data->data_source_cancellable);
        g_clear_object (&data->data_source_cancellable);

Patrick Griffis's avatar
Patrick Griffis committed
593
594
595
596
597
598
599
600
601
602
        /* This operation may have outlived the message data in which
           case this will have been cancelled. */
        if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
                g_error_free (error);
                return;
        }

        if (read < 0) {
                g_byte_array_set_size (data->data_source_buffer, 0);
                data->data_source_error = g_steal_pointer (&error);
603
604
        } else if (read == 0) {
                g_byte_array_set_size (data->data_source_buffer, 0);
Patrick Griffis's avatar
Patrick Griffis committed
605
                data->data_source_eof = TRUE;
606
        } else
Patrick Griffis's avatar
Patrick Griffis committed
607
608
609
                g_byte_array_set_size (data->data_source_buffer, read);

        h2_debug (data->io, data, "[SEND_BODY] Resuming send");
610
        NGCHECK (nghttp2_session_resume_data (data->io->session, data->stream_id));
Patrick Griffis's avatar
Patrick Griffis committed
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
}

static void
log_request_data (SoupHTTP2MessageData *data,
                  const guint8         *buffer,
                  gsize                 len)
{
        if (!data->logger)
                return;

        /* NOTE: This doesn't exactly log data as it hits the network but
           rather as soon as we read it from our source which is as good
           as we can do since nghttp handles the actual io. */
        soup_logger_log_request_data (data->logger, data->msg, (const char *)buffer, len);
}

static ssize_t
on_data_source_read_callback (nghttp2_session     *session,
                              int32_t              stream_id,
                              uint8_t             *buf,
                              size_t               length,
                              uint32_t            *data_flags,
                              nghttp2_data_source *source,
                              void                *user_data)
{
        SoupHTTP2MessageData *data = nghttp2_session_get_stream_user_data (session, stream_id);

        /* We support pollable streams in the best case because they
         * should perform better with one fewer copy of each buffer and no threading. */
        if (G_IS_POLLABLE_INPUT_STREAM (source->ptr) && g_pollable_input_stream_can_poll (G_POLLABLE_INPUT_STREAM (source->ptr))) {
                GPollableInputStream *in_stream = G_POLLABLE_INPUT_STREAM (source->ptr);
                GError *error = NULL;

                gssize read = g_pollable_input_stream_read_nonblocking  (in_stream, buf, length, data->cancellable, &error);

                if (read) {
647
                        h2_debug (data->io, data, "[SEND_BODY] Read %zd", read);
Patrick Griffis's avatar
Patrick Griffis committed
648
649
650
651
652
653
654
                        log_request_data (data, buf, read);
                }

                if (read < 0) {
                        if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK)) {
                                g_assert (data->data_source_poll == NULL);

655
                                h2_debug (data->io, data, "[SEND_BODY] Polling");
656
                                data->data_source_poll = g_pollable_input_stream_create_source (in_stream, data->cancellable);
Patrick Griffis's avatar
Patrick Griffis committed
657
658
659
660
661
                                g_source_set_callback (data->data_source_poll, (GSourceFunc)on_data_readable, data, NULL);
                                g_source_set_priority (data->data_source_poll, get_data_io_priority (data));
                                g_source_attach (data->data_source_poll, g_main_context_get_thread_default ());

                                g_error_free (error);
662
663
                                g_assert (!data->data_source_cancellable);
                                data->data_source_cancellable = g_cancellable_new ();
Patrick Griffis's avatar
Patrick Griffis committed
664
665
666
                                return NGHTTP2_ERR_DEFERRED;
                        }

667
                        set_error_for_data (data, g_steal_pointer (&error));
Patrick Griffis's avatar
Patrick Griffis committed
668
669
670
                        return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
                }
                else if (read == 0) {
671
                        h2_debug (data->io, data, "[SEND_BODY] EOF");
Patrick Griffis's avatar
Patrick Griffis committed
672
673
674
675
676
677
678
679
680
681
682
683
684
685
                        *data_flags |= NGHTTP2_DATA_FLAG_EOF;
                }

                return read;
        } else {
                GInputStream *in_stream = G_INPUT_STREAM (source->ptr);

                /* To support non-pollable input streams we always deffer reads
                * and read async into a local buffer. The next time around we will
                * send that buffer or error.
                */
                if (!data->data_source_buffer)
                        data->data_source_buffer = g_byte_array_new ();

686
                guint buffer_len = data->data_source_buffer->len;
Patrick Griffis's avatar
Patrick Griffis committed
687
                if (buffer_len) {
688
                        h2_debug (data->io, data, "[SEND_BODY] Sending %zu", buffer_len);
Patrick Griffis's avatar
Patrick Griffis committed
689
690
691
692
693
694
                        g_assert (buffer_len <= length); /* QUESTION: Maybe not reliable */
                        memcpy (buf, data->data_source_buffer->data, buffer_len);
                        log_request_data (data, buf, buffer_len);
                        g_byte_array_set_size (data->data_source_buffer, 0);
                        return buffer_len;
                } else if (data->data_source_eof) {
695
                        h2_debug (data->io, data, "[SEND_BODY] EOF");
Patrick Griffis's avatar
Patrick Griffis committed
696
697
698
                        *data_flags |= NGHTTP2_DATA_FLAG_EOF;
                        return 0;
                } else if (data->data_source_error) {
699
                        set_error_for_data (data, g_steal_pointer (&data->data_source_error));
Patrick Griffis's avatar
Patrick Griffis committed
700
701
                        return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
                } else {
702
                        h2_debug (data->io, data, "[SEND_BODY] Reading async");
Patrick Griffis's avatar
Patrick Griffis committed
703
                        g_byte_array_set_size (data->data_source_buffer, length);
704
705
                        g_assert (!data->data_source_cancellable);
                        data->data_source_cancellable = g_cancellable_new ();
Patrick Griffis's avatar
Patrick Griffis committed
706
707
                        g_input_stream_read_async (in_stream, data->data_source_buffer->data, length,
                                                   get_data_io_priority (data),
708
                                                   data->cancellable,
Patrick Griffis's avatar
Patrick Griffis committed
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
                                                   (GAsyncReadyCallback)on_data_read, data);
                        return NGHTTP2_ERR_DEFERRED;
                }
        }
}

/* HTTP2 IO functions */

static SoupHTTP2MessageData *
add_message_to_io_data (SoupClientMessageIOHTTP2        *io,
                        SoupMessageQueueItem      *item,
                        SoupMessageIOCompletionFn  completion_cb,
                        gpointer                   completion_data)
{
        SoupHTTP2MessageData *data = g_new0 (SoupHTTP2MessageData, 1);

        data->item = soup_message_queue_item_ref (item);
        data->msg = item->msg;
        data->metrics = soup_message_get_metrics (data->msg);
        data->cancellable = item->cancellable;
        data->completion_cb = completion_cb;
        data->completion_data = completion_data;
        data->stream_id = 0;
        data->io = io;

        if (!g_hash_table_insert (io->messages, item->msg, data))
                g_warn_if_reached ();

        return data;
}

static void
soup_http2_message_data_free (SoupHTTP2MessageData *data)
{
743
744
745
        if (data->body_istream)
                g_signal_handlers_disconnect_by_data (data->body_istream, data);

Patrick Griffis's avatar
Patrick Griffis committed
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
        g_clear_pointer (&data->item, soup_message_queue_item_unref);
        g_clear_object (&data->body_istream);
        g_clear_object (&data->decoded_data_istream);

        if (data->io_source) {
                g_source_destroy (data->io_source);
                g_clear_pointer (&data->io_source, g_source_unref);
        }

        if (data->data_source_poll)
                g_source_destroy (data->data_source_poll);
        g_clear_pointer (&data->data_source_poll, g_source_unref);

        g_clear_error (&data->data_source_error);
        g_clear_pointer (&data->data_source_buffer, g_byte_array_unref);

762
        g_clear_object (&data->data_source_cancellable);
Patrick Griffis's avatar
Patrick Griffis committed
763

764
765
        g_clear_error (&data->error);

Patrick Griffis's avatar
Patrick Griffis committed
766
767
768
        g_free (data);
}

769
770
771
772
773
static gboolean
request_header_is_valid (const char *name)
{
        static GHashTable *invalid_request_headers = NULL;

774
775
776
777
778
779
780
781
782
783
784
        if (g_once_init_enter (&invalid_request_headers)) {
                GHashTable *headers;

                headers= g_hash_table_new (soup_str_case_hash, soup_str_case_equal);
                g_hash_table_add (headers, "Connection");
                g_hash_table_add (headers, "Keep-Alive");
                g_hash_table_add (headers, "Proxy-Connection");
                g_hash_table_add (headers, "Transfer-Encoding");
                g_hash_table_add (headers, "Upgrade");

                g_once_init_leave (&invalid_request_headers, headers);
785
786
787
788
789
        }

        return !g_hash_table_contains (invalid_request_headers, name);
}

Patrick Griffis's avatar
Patrick Griffis committed
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
#define MAKE_NV(NAME, VALUE, VALUELEN)                                      \
        {                                                                   \
                (uint8_t *)NAME, (uint8_t *)VALUE, strlen (NAME), VALUELEN, \
                    NGHTTP2_NV_FLAG_NONE                                    \
        }

#define MAKE_NV2(NAME, VALUE)                                                     \
        {                                                                         \
                (uint8_t *)NAME, (uint8_t *)VALUE, strlen (NAME), strlen (VALUE), \
                    NGHTTP2_NV_FLAG_NONE                                          \
        }

#define MAKE_NV3(NAME, VALUE, FLAGS)                                              \
        {                                                                         \
                (uint8_t *)NAME, (uint8_t *)VALUE, strlen (NAME), strlen (VALUE), \
                    FLAGS                                                         \
        }

static void
send_message_request (SoupMessage          *msg,
                      SoupClientMessageIOHTTP2   *io,
                      SoupHTTP2MessageData *data)
{
        GArray *headers = g_array_new (FALSE, FALSE, sizeof (nghttp2_nv));

        GUri *uri = soup_message_get_uri (msg);
        char *host = soup_uri_get_host_for_headers (uri);
817
818
819
820
        char *authority = NULL;
        if (!soup_uri_uses_default_port (uri))
                authority = g_strdup_printf ("%s:%d", host, g_uri_get_port (uri));
        const char *authority_header = authority ? authority : host;
Patrick Griffis's avatar
Patrick Griffis committed
821
822
823
824
825
826
827
828
829
830

        char *path_and_query;
        if (soup_message_get_is_options_ping (msg))
                path_and_query = g_strdup ("*");
        else
                path_and_query = g_strdup_printf ("%s%c%s", g_uri_get_path (uri), g_uri_get_query (uri) ? '?' : '\0', g_uri_get_query (uri));

        const nghttp2_nv pseudo_headers[] = {
                MAKE_NV3 (":method", soup_message_get_method (msg), NGHTTP2_NV_FLAG_NO_COPY_VALUE),
                MAKE_NV2 (":scheme", g_uri_get_scheme (uri)),
831
                MAKE_NV2 (":authority", authority_header),
Patrick Griffis's avatar
Patrick Griffis committed
832
833
834
835
836
837
838
839
840
841
842
                MAKE_NV2 (":path", path_and_query),
        };

        for (guint i = 0; i < G_N_ELEMENTS (pseudo_headers); ++i) {
                g_array_append_val (headers, pseudo_headers[i]);
        }

        SoupMessageHeadersIter iter;
        const char *name, *value;
        soup_message_headers_iter_init (&iter, soup_message_get_request_headers (msg));
        while (soup_message_headers_iter_next (&iter, &name, &value)) {
843
                if (!request_header_is_valid (name))
Patrick Griffis's avatar
Patrick Griffis committed
844
                        continue;
845

Patrick Griffis's avatar
Patrick Griffis committed
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
                const nghttp2_nv nv = MAKE_NV2 (name, value);
                g_array_append_val (headers, nv);
        }

        GInputStream *body_stream = soup_message_get_request_body_stream (msg);
        SoupSessionFeature *logger = soup_session_get_feature_for_message (data->item->session, SOUP_TYPE_LOGGER, data->msg);
        if (logger && body_stream)
                data->logger = SOUP_LOGGER (logger);

        nghttp2_data_provider *data_provider = NULL;
        if (body_stream) {
                data_provider = g_new (nghttp2_data_provider, 1);
                data_provider->source.ptr = body_stream;
                data_provider->read_callback = on_data_source_read_callback;
        }

        data->stream_id = nghttp2_submit_request (io->session, NULL, (const nghttp2_nv *)headers->data, headers->len, data_provider, data);

864
        h2_debug (io, data, "[SESSION] Request made for %s%s", authority_header, path_and_query);
Patrick Griffis's avatar
Patrick Griffis committed
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890

        g_array_free (headers, TRUE);
        g_free (authority);
        g_free (host);
        g_free (path_and_query);
        g_free (data_provider);
}



static void
soup_client_message_io_http2_send_item (SoupClientMessageIO       *iface,
                                        SoupMessageQueueItem      *item,
                                        SoupMessageIOCompletionFn  completion_cb,
                                        gpointer                   user_data)
{
        SoupClientMessageIOHTTP2 *io = (SoupClientMessageIOHTTP2 *)iface;
        SoupHTTP2MessageData *data = add_message_to_io_data (io, item, completion_cb, user_data);

        send_message_request (item->msg, io, data);
}

static SoupHTTP2MessageData *
get_data_for_message (SoupClientMessageIOHTTP2 *io,
                      SoupMessage              *msg)
{
891
        return g_hash_table_lookup (io->messages, msg);
Patrick Griffis's avatar
Patrick Griffis committed
892
893
894
895
896
897
898
899
900
901
}

static void
soup_client_message_io_http2_finished (SoupClientMessageIO *iface,
                                       SoupMessage         *msg)
{
        SoupClientMessageIOHTTP2 *io = (SoupClientMessageIOHTTP2 *)iface;
        SoupHTTP2MessageData *data;
	SoupMessageIOCompletionFn completion_cb;
	gpointer completion_data;
902
        SoupMessageIOCompletion completion;
Patrick Griffis's avatar
Patrick Griffis committed
903
904
905

        data = get_data_for_message (io, msg);

906
907
908
        completion = data->state < STATE_READ_DONE ? SOUP_MESSAGE_IO_INTERRUPTED : SOUP_MESSAGE_IO_COMPLETE;

        h2_debug (io, data, "Finished: %s", completion == SOUP_MESSAGE_IO_COMPLETE ? "completed" : "interrupted");
Patrick Griffis's avatar
Patrick Griffis committed
909
910
911
912
913
914
915
916
917

        // ret = nghttp2_session_terminate_session (io->session, NGHTTP2_NO_ERROR);
        // g_assert (ret == 0);

	completion_cb = data->completion_cb;
	completion_data = data->completion_data;

	g_object_ref (msg);

918
919
        NGCHECK (nghttp2_submit_rst_stream (io->session, NGHTTP2_FLAG_NONE, data->stream_id,
                                            completion == SOUP_MESSAGE_IO_COMPLETE ? NGHTTP2_NO_ERROR : NGHTTP2_CANCEL));
Patrick Griffis's avatar
Patrick Griffis committed
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
        nghttp2_session_set_stream_user_data (io->session, data->stream_id, NULL);
        if (!g_hash_table_remove (io->messages, msg))
                g_warn_if_reached ();

	if (completion_cb)
		completion_cb (G_OBJECT (msg), SOUP_MESSAGE_IO_COMPLETE, completion_data);

	g_object_unref (msg);
}

static void
soup_client_message_io_http2_pause (SoupClientMessageIO *iface,
                                    SoupMessage         *msg)
{
        SoupClientMessageIOHTTP2 *io = (SoupClientMessageIOHTTP2 *)iface;
        SoupHTTP2MessageData *data = get_data_for_message (io, msg);

        h2_debug (io, data, "[SESSION] Paused");

        if (data->paused)
                g_warn_if_reached ();

942
943
944
945
946
947
        if (data->io_source) {
                g_source_destroy (data->io_source);
                g_source_unref (data->io_source);
                data->io_source = NULL;
        }

Patrick Griffis's avatar
Patrick Griffis committed
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
        data->paused = TRUE;
}

static void
soup_client_message_io_http2_unpause (SoupClientMessageIO *iface,
                                      SoupMessage         *msg)
{
        SoupClientMessageIOHTTP2 *io = (SoupClientMessageIOHTTP2 *)iface;
        SoupHTTP2MessageData *data = get_data_for_message (io, msg);

        h2_debug (io, data, "[SESSION] Unpaused");

        if (!data->paused)
                g_warn_if_reached ();

        data->paused = FALSE;
}

static void
soup_client_message_io_http2_stolen (SoupClientMessageIO *iface)
{
        g_assert_not_reached ();
}

static gboolean
soup_client_message_io_http2_in_progress (SoupClientMessageIO *iface,
                                          SoupMessage         *msg)
{
        SoupClientMessageIOHTTP2 *io = (SoupClientMessageIOHTTP2 *)iface;

978
        return io && get_data_for_message (io, msg) != NULL;
Patrick Griffis's avatar
Patrick Griffis committed
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
}

static gboolean
soup_client_message_io_http2_is_paused (SoupClientMessageIO *iface,
                                        SoupMessage         *msg)
{
        SoupClientMessageIOHTTP2 *io = (SoupClientMessageIOHTTP2 *)iface;
        SoupHTTP2MessageData *data = get_data_for_message (io, msg);

        return data->paused;
}

static gboolean
soup_client_message_io_http2_is_reusable (SoupClientMessageIO *iface)
{
        SoupClientMessageIOHTTP2 *io = (SoupClientMessageIOHTTP2 *)iface;

        if (!nghttp2_session_want_write (io->session) && !nghttp2_session_want_read (io->session))
                return FALSE;

        return !io->is_shutdown;
}

static gboolean
message_source_check (GSource *source)
{
1005
        SoupMessageIOSource *message_source = (SoupMessageIOSource *)source;
Patrick Griffis's avatar
Patrick Griffis committed
1006

1007
1008
1009
1010
1011
        if (message_source->paused) {
                if (soup_message_is_io_paused (SOUP_MESSAGE (message_source->msg)))
                        return FALSE;
                return TRUE;
        }
Patrick Griffis's avatar
Patrick Griffis committed
1012

1013
        return FALSE;
Patrick Griffis's avatar
Patrick Griffis committed
1014
1015
1016
}

static GSource *
1017
1018
soup_client_message_io_http2_get_source (SoupHTTP2MessageData    *data,
                                         SoupMessage             *msg,
Patrick Griffis's avatar
Patrick Griffis committed
1019
1020
1021
1022
1023
1024
1025
1026
1027
                                         GCancellable            *cancellable,
                                         SoupMessageIOSourceFunc  callback,
                                         gpointer                 user_data)
{
        GSource *base_source;

        /* TODO: Handle mixing writes in? */
        if (data->paused)
                base_source = cancellable ? g_cancellable_source_new (cancellable) : NULL;
1028
1029
        else if (data->state < STATE_WRITE_DONE && data->data_source_cancellable)
                base_source = g_cancellable_source_new (data->data_source_cancellable);
1030
1031
        else if (data->state < STATE_WRITE_DONE && nghttp2_session_want_write (data->io->session))
                base_source = g_pollable_output_stream_create_source (G_POLLABLE_OUTPUT_STREAM (data->io->ostream), cancellable);
1032
1033
        else if (data->state < STATE_READ_DONE && data->decoded_data_istream)
                base_source = g_pollable_input_stream_create_source (G_POLLABLE_INPUT_STREAM (data->decoded_data_istream), cancellable);
1034
1035
        else if (data->state < STATE_READ_DONE && nghttp2_session_want_read (data->io->session))
                base_source = g_pollable_input_stream_create_source (G_POLLABLE_INPUT_STREAM (data->io->istream), cancellable);
1036
1037
1038
1039
        else {
                g_warn_if_reached ();
                base_source = g_timeout_source_new (0);
        }
Patrick Griffis's avatar
Patrick Griffis committed
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058

        GSource *source = soup_message_io_source_new (base_source, G_OBJECT (msg), data->paused, message_source_check);
        g_source_set_callback (source, (GSourceFunc)callback, user_data, NULL);
        return source;
}

static void
client_stream_eof (SoupClientInputStream *stream,
                   gpointer               user_data)
{
	SoupMessage *msg = user_data;
	SoupClientMessageIOHTTP2 *io = get_io_data (msg);

        if (!io) {
                g_warn_if_reached ();
                return;
        }

        SoupHTTP2MessageData *data = get_data_for_message (io, msg);
1059
        h2_debug (io, data, "Client stream EOF");
1060
        soup_message_set_metrics_timestamp (msg, SOUP_MESSAGE_METRICS_RESPONSE_END);
1061
        advance_state_from (data, STATE_READ_DATA, STATE_READ_DONE);
1062
        g_signal_handlers_disconnect_by_func (stream, client_stream_eof, msg);
1063
        soup_message_got_body (data->msg);
Patrick Griffis's avatar
Patrick Griffis committed
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
}

static GInputStream *
soup_client_message_io_http2_get_response_istream (SoupClientMessageIO  *iface,
                                                   SoupMessage          *msg,
                                                   GError              **error)
{
        SoupClientMessageIOHTTP2 *io = (SoupClientMessageIOHTTP2 *)iface;
        SoupHTTP2MessageData *data = get_data_for_message (io, msg);
        GInputStream *client_stream, *base_stream;

        if (data->decoded_data_istream)
                base_stream = g_object_ref (data->decoded_data_istream);
        else /* For example with status_code == SOUP_STATUS_NO_CONTENT */
                base_stream = g_memory_input_stream_new ();

        client_stream = soup_client_input_stream_new (base_stream, msg);
        g_signal_connect (client_stream, "eof", G_CALLBACK (client_stream_eof), msg);

        g_object_unref (base_stream);

        return client_stream;
}

static gboolean
io_read (SoupClientMessageIOHTTP2  *io,
         gboolean             blocking,
	 GCancellable        *cancellable,
         GError             **error)
{
        guint8 buffer[8192];
        gssize read;
        int ret;

        if ((read = g_pollable_stream_read (io->istream, buffer, sizeof (buffer),
                                            blocking, cancellable, error)) < 0)
            return FALSE;

        ret = nghttp2_session_mem_recv (io->session, buffer, read);
1103
        NGCHECK (ret);
Patrick Griffis's avatar
Patrick Griffis committed
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
        return ret != 0;
}

static gboolean
io_write (SoupClientMessageIOHTTP2 *io,
         gboolean                   blocking,
	 GCancellable              *cancellable,
         GError                   **error)
{
        /* We must write all of nghttp2's buffer before we ask for more */

        if (io->written_bytes == io->write_buffer_size)
                io->write_buffer = NULL;

        if (io->write_buffer == NULL) {
                io->written_bytes = 0;
                io->write_buffer_size = nghttp2_session_mem_send (io->session, (const guint8**)&io->write_buffer);
1121
                NGCHECK (io->write_buffer_size);
Patrick Griffis's avatar
Patrick Griffis committed
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
                if (io->write_buffer_size == 0) {
                        /* Done */
                        io->write_buffer = NULL;
                        return TRUE;
                }
        }

        gssize ret = g_pollable_stream_write (io->ostream,
                                              io->write_buffer + io->written_bytes,
                                              io->write_buffer_size - io->written_bytes,
                                              blocking, cancellable, error);
        if (ret < 0)
                return FALSE;

        io->written_bytes += ret;
        return TRUE;
}

1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
static void
io_try_sniff_content (SoupHTTP2MessageData *data,
                      gboolean              blocking,
                      GCancellable         *cancellable)
{
        GError *error = NULL;

        if (soup_message_try_sniff_content (data->msg, data->decoded_data_istream, blocking, cancellable, &error)) {
                h2_debug (data->io, data, "[DATA] Sniffed content");
                advance_state_from (data, STATE_READ_DATA_START, STATE_READ_DATA);
        } else {
                h2_debug (data->io, data, "[DATA] Sniffer stream was not ready %s", error->message);

                g_clear_error (&error);
        }
}

Patrick Griffis's avatar
Patrick Griffis committed
1157
static gboolean
1158
1159
1160
1161
io_run (SoupHTTP2MessageData *data,
        gboolean              blocking,
        GCancellable         *cancellable,
        GError              **error)
Patrick Griffis's avatar
Patrick Griffis committed
1162
{
1163
        gboolean progress = FALSE;
1164
1165
1166
1167

        if (data->state == STATE_READ_DATA_START)
                io_try_sniff_content (data, blocking, cancellable);

1168
1169
        if (data->state < STATE_WRITE_DONE && nghttp2_session_want_write (data->io->session))
                progress = io_write (data->io, blocking, cancellable, error);
1170
        else if (data->state < STATE_READ_DONE && nghttp2_session_want_read (data->io->session)) {
1171
                progress = io_read (data->io, blocking, cancellable, error);
1172
1173
1174
1175
1176

                if (progress && data->state == STATE_READ_DATA_START)
                        io_try_sniff_content (data, blocking, cancellable);
        }

1177
        return progress;
Patrick Griffis's avatar
Patrick Griffis committed
1178
1179
1180
}

static gboolean
1181
1182
1183
1184
1185
1186
io_run_until (SoupClientMessageIOHTTP2 *io,
              SoupMessage              *msg,
              gboolean                  blocking,
              SoupHTTP2IOState          state,
              GCancellable             *cancellable,
              GError                  **error)
Patrick Griffis's avatar
Patrick Griffis committed
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
{
        SoupHTTP2MessageData *data = get_data_for_message (io, msg);
	gboolean progress = TRUE, done;
	GError *my_error = NULL;

	if (g_cancellable_set_error_if_cancelled (cancellable, error))
		return FALSE;
	else if (!io) {
		g_set_error_literal (error, G_IO_ERROR,
				     G_IO_ERROR_CANCELLED,
				     _("Operation was cancelled"));
		return FALSE;
	}

	g_object_ref (msg);

1203
	while (progress && get_io_data (msg) == io && !data->paused && !data->data_source_cancellable && data->state < state)
1204
                progress = io_run (data, blocking, cancellable, &my_error);
Patrick Griffis's avatar
Patrick Griffis committed
1205

1206
1207
1208
1209
1210
1211
1212
1213
        if (my_error) {
                g_propagate_error (error, my_error);
                g_object_unref (msg);
                return FALSE;
        }

	if (data->error) {
                g_propagate_error (error, g_steal_pointer (&data->error));
Patrick Griffis's avatar
Patrick Griffis committed
1214
1215
		g_object_unref (msg);
		return FALSE;
1216
1217
1218
        }

        if (get_io_data (msg) != io) {
Patrick Griffis's avatar
Patrick Griffis committed
1219
1220
1221
1222
1223
1224
1225
1226
1227
		g_set_error_literal (error, G_IO_ERROR,
				     G_IO_ERROR_CANCELLED,
				     _("Operation was cancelled"));
		g_object_unref (msg);
		return FALSE;
	}

	done = data->state >= state;

1228
	if (data->paused || (!blocking && !done)) {
Patrick Griffis's avatar
Patrick Griffis committed
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
		g_set_error_literal (error, G_IO_ERROR,
				     G_IO_ERROR_WOULD_BLOCK,
				     _("Operation would block"));
		g_object_unref (msg);
		return FALSE;
	}

	g_object_unref (msg);
	return done;
}


static gboolean
soup_client_message_io_http2_run_until_read (SoupClientMessageIO  *iface,
                                             SoupMessage          *msg,
                                             GCancellable         *cancellable,
                                             GError              **error)
{
1247
1248
        SoupClientMessageIOHTTP2 *io = (SoupClientMessageIOHTTP2 *)iface;

1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
        if (io_run_until (io, msg, TRUE, STATE_READ_DATA, cancellable, error))
                return TRUE;

        soup_message_set_metrics_timestamp (msg, SOUP_MESSAGE_METRICS_RESPONSE_END);

        if (get_io_data (msg) == io)
                soup_client_message_io_http2_finished (iface, msg);
        else
                g_warn_if_reached ();

        return FALSE;
Patrick Griffis's avatar
Patrick Griffis committed
1260
1261
1262
}

static gboolean
1263
1264
1265
1266
1267
soup_client_message_io_http2_skip (SoupClientMessageIO *iface,
                                   SoupMessage         *msg,
                                   gboolean             blocking,
                                   GCancellable        *cancellable,
                                   GError             **error)
Patrick Griffis's avatar
Patrick Griffis committed
1268
{
1269
        SoupClientMessageIOHTTP2 *io = (SoupClientMessageIOHTTP2 *)iface;
1270
1271
1272
1273
        SoupHTTP2MessageData *data;

        if (g_cancellable_set_error_if_cancelled (cancellable, error))
                return FALSE;
1274

1275
1276
1277
1278
1279
1280
1281
        data = get_data_for_message (io, msg);
        if (!data || data->state == STATE_READ_DONE)
                return TRUE;

        h2_debug (io, data, "Skip");
        NGCHECK (nghttp2_submit_rst_stream (io->session, NGHTTP2_FLAG_NONE, data->stream_id, NGHTTP2_STREAM_CLOSED));
        return TRUE;
Patrick Griffis's avatar
Patrick Griffis committed
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
}

static void
soup_client_message_io_http2_run (SoupClientMessageIO *iface,
                                  SoupMessage         *msg,
		                  gboolean             blocking)
{
        g_assert_not_reached ();
}

static void io_run_until_read_async (SoupMessage *msg,
                                     GTask       *task);

static gboolean
io_run_until_read_ready (SoupMessage *msg,
                         gpointer     user_data)
{
        GTask *task = user_data;

        io_run_until_read_async (msg, task);

        return G_SOURCE_REMOVE;
}

static void
io_run_until_read_async (SoupMessage *msg,
                         GTask       *task)
{
        SoupClientMessageIOHTTP2 *io = get_io_data (msg);
        SoupHTTP2MessageData *data = get_data_for_message (io, msg);
        GError *error = NULL;

        if (data->io_source) {
                g_source_destroy (data->io_source);
                g_clear_pointer (&data->io_source, g_source_unref);
        }

1319
        if (io_run_until (io, msg, FALSE,
Patrick Griffis's avatar
Patrick Griffis committed
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
                          STATE_READ_DATA,
                          g_task_get_cancellable (task),
                          &error)) {
                g_task_return_boolean (task, TRUE);
                g_object_unref (task);
                return;
        }

        if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK)) {
                g_error_free (error);
1330
1331
1332
                data->io_source = soup_client_message_io_http2_get_source (data, msg, g_task_get_cancellable (task),
                                                                           (SoupMessageIOSourceFunc)io_run_until_read_ready,
                                                                           task);
Patrick Griffis's avatar
Patrick Griffis committed
1333
1334
1335
1336
1337
		g_source_set_priority (data->io_source, g_task_get_priority (task));
                g_source_attach (data->io_source, io->async_context);
                return;
        }

1338
1339
        soup_message_set_metrics_timestamp (msg, SOUP_MESSAGE_METRICS_RESPONSE_END);

Patrick Griffis's avatar
Patrick Griffis committed
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
        if (get_io_data (msg) == io)
                soup_client_message_io_http2_finished ((SoupClientMessageIO *)io, msg);
        else
                g_warn_if_reached ();

        g_task_return_error (task, error);
        g_object_unref (task);
}

static void
soup_client_message_io_http2_run_until_read_async (SoupClientMessageIO *iface,
                                                   SoupMessage         *msg,
                                                   int                  io_priority,
                                                   GCancellable        *cancellable,
                                                   GAsyncReadyCallback  callback,
                                                   gpointer             user_data)
{
        GTask *task;

        task = g_task_new (msg, cancellable, callback, user_data);
	g_task_set_priority (task, io_priority);
        io_run_until_read_async (msg, task);
}

1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
static void io_close_async (SoupClientMessageIOHTTP2 *io,
                            GTask                    *task);

static gboolean
io_close_ready (GTask *task)
{
        SoupClientMessageIOHTTP2 *io = g_task_get_task_data (task);

        io_close_async (io, task);

        return G_SOURCE_REMOVE;
}

static gboolean
io_try_write (SoupClientMessageIOHTTP2 *io,
              GTask                    *task)
{
        GError *error = NULL;

        while (nghttp2_session_want_write (io->session) && !error)
                io_write (io, FALSE, FALSE, &error);

        if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK)) {
                io->close_source = g_pollable_output_stream_create_source (G_POLLABLE_OUTPUT_STREAM (io->ostream), NULL);
                g_source_set_callback (io->close_source, (GSourceFunc)io_close_ready, task, NULL);
                g_source_attach (io->close_source, g_main_context_get_thread_default ());
                return FALSE;
        }

        if (error) {
                g_task_return_error (task, error);
                g_object_unref (task);
                return FALSE;
        }

        return TRUE;
}

static void
io_close_async (SoupClientMessageIOHTTP2 *io,
                GTask                    *task)
{
        if (io->close_source) {
                g_source_destroy (io->close_source);
                g_clear_pointer (&io->close_source, g_source_unref);
        }

        /* Finish any pending write */
        if (!io_try_write (io, task))
                return;

        if (!io->goaway_sent) {
                io->goaway_sent = TRUE;
                NGCHECK (nghttp2_session_terminate_session (io->session, NGHTTP2_NO_ERROR));

                /* Write the goaway frame */
                if (!io_try_write (io, task))
                        return;
        }

        g_task_return_boolean (task, TRUE);
        g_object_unref (task);
}

static void
soup_client_message_io_http2_close_async (SoupClientMessageIO *iface,
                                          SoupConnection      *conn,
                                          GAsyncReadyCallback  callback)
{
        SoupClientMessageIOHTTP2 *io = (SoupClientMessageIOHTTP2 *)iface;
        GTask *task;

        task = g_task_new (conn, NULL, callback, NULL);
        g_task_set_task_data (task, io, NULL);
        io_close_async (io, task);
}

Patrick Griffis's avatar
Patrick Griffis committed
1441
1442
1443
1444
1445
static gboolean
soup_client_message_io_http2_is_open (SoupClientMessageIO *iface)
{
        SoupClientMessageIOHTTP2 *io = (SoupClientMessageIOHTTP2 *)iface;

1446
        return nghttp2_session_want_read (io->session) || nghttp2_session_want_write (io->session);
Patrick Griffis's avatar
Patrick Griffis committed
1447
1448
1449
1450
1451
1452
1453
}

static void
soup_client_message_io_http2_destroy (SoupClientMessageIO *iface)
{
        SoupClientMessageIOHTTP2 *io = (SoupClientMessageIOHTTP2 *)iface;

1454
1455
1456
1457
        if (io->close_source) {
                g_source_destroy (io->close_source);
                g_source_unref (io->close_source);
        }
Patrick Griffis's avatar
Patrick Griffis committed
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
        g_clear_object (&io->stream);
        g_clear_pointer (&io->async_context, g_main_context_unref);
        g_clear_pointer (&io->session, nghttp2_session_del);
        g_clear_pointer (&io->messages, g_hash_table_unref);

        g_free (io);
}

static const SoupClientMessageIOFuncs io_funcs = {
        soup_client_message_io_http2_destroy,
        soup_client_message_io_http2_finished,
        soup_client_message_io_http2_stolen,
        soup_client_message_io_http2_send_item,
        soup_client_message_io_http2_get_response_istream,
        soup_client_message_io_http2_pause,
        soup_client_message_io_http2_unpause,
        soup_client_message_io_http2_is_paused,
        soup_client_message_io_http2_run,
        soup_client_message_io_http2_run_until_read,
        soup_client_message_io_http2_run_until_read_async,
1478
        soup_client_message_io_http2_close_async,
1479
        soup_client_message_io_http2_skip,
Patrick Griffis's avatar
Patrick Griffis committed
1480
1481
1482
1483
1484
        soup_client_message_io_http2_is_open,
        soup_client_message_io_http2_in_progress,
        soup_client_message_io_http2_is_reusable
};

1485
G_GNUC_PRINTF(1, 0)
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
static void
debug_nghttp2 (const char *format,
               va_list     args)
{
        char *message;
        gsize len;

        if (g_log_writer_default_would_drop (G_LOG_LEVEL_DEBUG, "nghttp2"))
                return;

        message = g_strdup_vprintf (format, args);
        len = strlen (message);
        if (len >= 1 && message[len - 1] == '\n')
                message[len - 1] = '\0';
        g_log ("nghttp2", G_LOG_LEVEL_DEBUG, "[NGHTTP2] %s", message);
        g_free (message);
}

Patrick Griffis's avatar
Patrick Griffis committed
1504
1505
1506
static void
soup_client_message_io_http2_init (SoupClientMessageIOHTTP2 *io)
{
1507
1508
1509
1510
1511
1512
        static gsize nghttp2_debug_init = 0;
        if (g_once_init_enter (&nghttp2_debug_init)) {
                nghttp2_set_debug_vprintf_callback(debug_nghttp2);
                g_once_init_leave (&nghttp2_debug_init, 1);
        }

Patrick Griffis's avatar
Patrick Griffis committed
1513
        nghttp2_session_callbacks *callbacks;
1514
        NGCHECK (nghttp2_session_callbacks_new (&callbacks));
Patrick Griffis's avatar
Patrick Griffis committed
1515
1516
1517
1518
1519
1520
1521
1522
1523
        nghttp2_session_callbacks_set_on_header_callback (callbacks, on_header_callback);
        nghttp2_session_callbacks_set_on_frame_recv_callback (callbacks, on_frame_recv_callback);
        nghttp2_session_callbacks_set_on_data_chunk_recv_callback (callbacks, on_data_chunk_recv_callback);
        nghttp2_session_callbacks_set_on_begin_frame_callback (callbacks, on_begin_frame_callback);
        nghttp2_session_callbacks_set_before_frame_send_callback (callbacks, on_before_frame_send_callback);
        nghttp2_session_callbacks_set_on_frame_not_send_callback (callbacks, on_frame_not_send_callback);
        nghttp2_session_callbacks_set_on_frame_send_callback (callbacks, on_frame_send_callback);
        nghttp2_session_callbacks_set_on_stream_close_callback (callbacks, on_stream_close_callback);

1524
        NGCHECK (nghttp2_session_client_new (&io->session, callbacks, io));
Patrick Griffis's avatar
Patrick Griffis committed
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
        nghttp2_session_callbacks_del (callbacks);

        io->messages = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, (GDestroyNotify)soup_http2_message_data_free);

        io->iface.funcs = &io_funcs;
}

#define INITIAL_WINDOW_SIZE (32 * 1024 * 1024) /* 32MB matches other implementations */
#define MAX_HEADER_TABLE_SIZE 65536 /* Match size used by Chromium/Firefox */

SoupClientMessageIO *
soup_client_message_io_http2_new (GIOStream *stream, guint64 connection_id)
{
        SoupClientMessageIOHTTP2 *io = g_new0 (SoupClientMessageIOHTTP2, 1);
        soup_client_message_io_http2_init (io);

        io->stream = g_object_ref (stream);
        io->istream = g_io_stream_get_input_stream (io->stream);
        io->ostream = g_io_stream_get_output_stream (io->stream);
        io->connection_id = connection_id;

        io->async_context = g_main_context_ref_thread_default ();

1548
        NGCHECK (nghttp2_session_set_local_window_size (io->session, NGHTTP2_FLAG_NONE, 0, INITIAL_WINDOW_SIZE));
Patrick Griffis's avatar
Patrick Griffis committed
1549
1550
1551
1552
1553
1554

        const nghttp2_settings_entry settings[] = {
                { NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE, INITIAL_WINDOW_SIZE },
                { NGHTTP2_SETTINGS_HEADER_TABLE_SIZE, MAX_HEADER_TABLE_SIZE },
                { NGHTTP2_SETTINGS_ENABLE_PUSH, 0 },
        };
1555
        NGCHECK (nghttp2_submit_settings (io->session, NGHTTP2_FLAG_NONE, settings, G_N_ELEMENTS (settings)));
Patrick Griffis's avatar
Patrick Griffis committed
1556
1557
1558

        return (SoupClientMessageIO *)io;
}