summaryrefslogtreecommitdiff
path: root/libs/libcurl/src/c-hyper.c
blob: bf70002c0466a817fbc9a40811e733cb5e96fa30 (plain)
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
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
519
520
521
522
523
524
525
526
527
528
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
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
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
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
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
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
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
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
978
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
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
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
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
/***************************************************************************
 *                                  _   _ ____  _
 *  Project                     ___| | | |  _ \| |
 *                             / __| | | | |_) | |
 *                            | (__| |_| |  _ <| |___
 *                             \___|\___/|_| \_\_____|
 *
 * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
 *
 * This software is licensed as described in the file COPYING, which
 * you should have received as part of this distribution. The terms
 * are also available at https://curl.haxx.se/docs/copyright.html.
 *
 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
 * copies of the Software, and permit persons to whom the Software is
 * furnished to do so, under the terms of the COPYING file.
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
 * KIND, either express or implied.
 *
 * SPDX-License-Identifier: curl
 *
 ***************************************************************************/

/* Curl's integration with Hyper. This replaces certain functions in http.c,
 * based on configuration #defines. This implementation supports HTTP/1.1 but
 * not HTTP/2.
 */
#include "curl_setup.h"

#if !defined(CURL_DISABLE_HTTP) && defined(USE_HYPER)

#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif

#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef HAVE_NET_IF_H
#include <net/if.h>
#endif
#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif

#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif

#include <hyper.h>
#include "urldata.h"
#include "cfilters.h"
#include "sendf.h"
#include "headers.h"
#include "transfer.h"
#include "multiif.h"
#include "progress.h"
#include "content_encoding.h"
#include "ws.h"

/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
#include "memdebug.h"


static CURLcode cr_hyper_add(struct Curl_easy *data);

typedef enum {
    USERDATA_NOT_SET = 0, /* for tasks with no userdata set; must be zero */
    USERDATA_RESP_BODY
} userdata_t;

size_t Curl_hyper_recv(void *userp, hyper_context *ctx,
                       uint8_t *buf, size_t buflen)
{
  struct hyp_io_ctx *io_ctx = userp;
  struct Curl_easy *data = io_ctx->data;
  struct connectdata *conn = data->conn;
  CURLcode result;
  ssize_t nread;
  DEBUGASSERT(conn);
  (void)ctx;

  DEBUGF(infof(data, "Curl_hyper_recv(%zu)", buflen));
  result = Curl_conn_recv(data, io_ctx->sockindex,
                          (char *)buf, buflen, &nread);
  if(result == CURLE_AGAIN) {
    /* would block, register interest */
    DEBUGF(infof(data, "Curl_hyper_recv(%zu) -> EAGAIN", buflen));
    if(data->hyp.read_waker)
      hyper_waker_free(data->hyp.read_waker);
    data->hyp.read_waker = hyper_context_waker(ctx);
    if(!data->hyp.read_waker) {
      failf(data, "Couldn't make the read hyper_context_waker");
      return HYPER_IO_ERROR;
    }
    return HYPER_IO_PENDING;
  }
  else if(result) {
    failf(data, "Curl_read failed");
    return HYPER_IO_ERROR;
  }
  DEBUGF(infof(data, "Curl_hyper_recv(%zu) -> %zd", buflen, nread));
  return (size_t)nread;
}

size_t Curl_hyper_send(void *userp, hyper_context *ctx,
                       const uint8_t *buf, size_t buflen)
{
  struct hyp_io_ctx *io_ctx = userp;
  struct Curl_easy *data = io_ctx->data;
  CURLcode result;
  size_t nwrote;

  DEBUGF(infof(data, "Curl_hyper_send(%zu)", buflen));
  result = Curl_conn_send(data, io_ctx->sockindex,
                          (void *)buf, buflen, FALSE, &nwrote);
  if(result == CURLE_AGAIN) {
    DEBUGF(infof(data, "Curl_hyper_send(%zu) -> EAGAIN", buflen));
    /* would block, register interest */
    if(data->hyp.write_waker)
      hyper_waker_free(data->hyp.write_waker);
    data->hyp.write_waker = hyper_context_waker(ctx);
    if(!data->hyp.write_waker) {
      failf(data, "Couldn't make the write hyper_context_waker");
      return HYPER_IO_ERROR;
    }
    return HYPER_IO_PENDING;
  }
  else if(result) {
    failf(data, "Curl_write failed");
    return HYPER_IO_ERROR;
  }
  DEBUGF(infof(data, "Curl_hyper_send(%zu) -> %zd", buflen, nwrote));
  return (size_t)nwrote;
}

static int hyper_each_header(void *userdata,
                             const uint8_t *name,
                             size_t name_len,
                             const uint8_t *value,
                             size_t value_len)
{
  struct Curl_easy *data = (struct Curl_easy *)userdata;
  size_t len;
  char *headp;
  CURLcode result;
  int writetype;

  if(name_len + value_len + 2 > CURL_MAX_HTTP_HEADER) {
    failf(data, "Too long response header");
    data->state.hresult = CURLE_TOO_LARGE;
    return HYPER_ITER_BREAK;
  }

  Curl_dyn_reset(&data->state.headerb);
  if(name_len) {
    if(Curl_dyn_addf(&data->state.headerb, "%.*s: %.*s\r\n",
                     (int) name_len, name, (int) value_len, value))
      return HYPER_ITER_BREAK;
  }
  else {
    if(Curl_dyn_addn(&data->state.headerb, STRCONST("\r\n")))
      return HYPER_ITER_BREAK;
  }
  len = Curl_dyn_len(&data->state.headerb);
  headp = Curl_dyn_ptr(&data->state.headerb);

  result = Curl_http_header(data, headp, len);
  if(result) {
    data->state.hresult = result;
    return HYPER_ITER_BREAK;
  }

  Curl_debug(data, CURLINFO_HEADER_IN, headp, len);

  writetype = CLIENTWRITE_HEADER;
  if(data->state.hconnect)
    writetype |= CLIENTWRITE_CONNECT;
  if(data->req.httpcode/100 == 1)
    writetype |= CLIENTWRITE_1XX;
  result = Curl_client_write(data, writetype, headp, len);
  if(result) {
    data->state.hresult = CURLE_ABORTED_BY_CALLBACK;
    return HYPER_ITER_BREAK;
  }

  result = Curl_bump_headersize(data, len, FALSE);
  if(result) {
    data->state.hresult = result;
    return HYPER_ITER_BREAK;
  }
  return HYPER_ITER_CONTINUE;
}

static int hyper_body_chunk(void *userdata, const hyper_buf *chunk)
{
  char *buf = (char *)hyper_buf_bytes(chunk);
  size_t len = hyper_buf_len(chunk);
  struct Curl_easy *data = (struct Curl_easy *)userdata;
  struct SingleRequest *k = &data->req;
  CURLcode result = CURLE_OK;

  if(!k->bodywritten) {
#if defined(USE_NTLM)
    struct connectdata *conn = data->conn;
    if(conn->bits.close &&
       (((data->req.httpcode == 401) &&
         (conn->http_ntlm_state == NTLMSTATE_TYPE2)) ||
        ((data->req.httpcode == 407) &&
         (conn->proxy_ntlm_state == NTLMSTATE_TYPE2)))) {
      infof(data, "Connection closed while negotiating NTLM");
      data->state.authproblem = TRUE;
      Curl_safefree(data->req.newurl);
    }
#endif
    if(Curl_http_exp100_is_selected(data)) {
      if(data->req.httpcode < 400) {
        Curl_http_exp100_got100(data);
        if(data->hyp.send_body_waker) {
          hyper_waker_wake(data->hyp.send_body_waker);
          data->hyp.send_body_waker = NULL;
        }
      }
      else { /* >= 4xx */
        Curl_req_abort_sending(data);
      }
    }
    if(data->state.hconnect && (data->req.httpcode/100 != 2) &&
       data->state.authproxy.done) {
      data->req.done = TRUE;
      result = CURLE_OK;
    }
    else
      result = Curl_http_firstwrite(data);
    if(result || data->req.done) {
      infof(data, "Return early from hyper_body_chunk");
      data->state.hresult = result;
      return HYPER_ITER_BREAK;
    }
  }
  result = Curl_client_write(data, CLIENTWRITE_BODY, buf, len);

  if(result) {
    data->state.hresult = result;
    return HYPER_ITER_BREAK;
  }

  return HYPER_ITER_CONTINUE;
}

/*
 * Hyper does not consider the status line, the first line in an HTTP/1
 * response, to be a header. The libcurl API does. This function sends the
 * status line in the header callback. */
static CURLcode status_line(struct Curl_easy *data,
                            struct connectdata *conn,
                            uint16_t http_status,
                            int http_version,
                            const uint8_t *reason, size_t rlen)
{
  CURLcode result;
  size_t len;
  const char *vstr;
  int writetype;
  vstr = http_version == HYPER_HTTP_VERSION_1_1 ? "1.1" :
    (http_version == HYPER_HTTP_VERSION_2 ? "2" : "1.0");

  /* We need to set 'httpcodeq' for functions that check the response code in
     a single place. */
  data->req.httpcode = http_status;
  data->req.httpversion = http_version == HYPER_HTTP_VERSION_1_1 ? 11 :
                          (http_version == HYPER_HTTP_VERSION_2 ? 20 : 10);
  if(data->state.hconnect)
    /* CONNECT */
    data->info.httpproxycode = http_status;
  else {
    conn->httpversion = (unsigned char)data->req.httpversion;
    if(http_version == HYPER_HTTP_VERSION_1_0)
      data->state.httpwant = CURL_HTTP_VERSION_1_0;

    result = Curl_http_statusline(data, conn);
    if(result)
      return result;
  }

  Curl_dyn_reset(&data->state.headerb);

  result = Curl_dyn_addf(&data->state.headerb, "HTTP/%s %03d %.*s\r\n",
                         vstr,
                         (int)http_status,
                         (int)rlen, reason);
  if(result)
    return result;
  len = Curl_dyn_len(&data->state.headerb);
  Curl_debug(data, CURLINFO_HEADER_IN, Curl_dyn_ptr(&data->state.headerb),
             len);

  writetype = CLIENTWRITE_HEADER|CLIENTWRITE_STATUS;
  if(data->state.hconnect)
    writetype |= CLIENTWRITE_CONNECT;
  result = Curl_client_write(data, writetype,
                             Curl_dyn_ptr(&data->state.headerb), len);
  if(result)
    return result;

  result = Curl_bump_headersize(data, len, FALSE);
  return result;
}

/*
 * Hyper does not pass on the last empty response header. The libcurl API
 * does. This function sends an empty header in the header callback.
 */
static CURLcode empty_header(struct Curl_easy *data)
{
  CURLcode result = Curl_http_size(data);
  if(!result) {
    result = hyper_each_header(data, NULL, 0, NULL, 0) ?
      CURLE_WRITE_ERROR : CURLE_OK;
    if(result)
      failf(data, "hyperstream: could not pass blank header");
    /* Hyper does chunked decoding itself. If it was added during
     * response header processing, remove it again. */
    Curl_cwriter_remove_by_name(data, "chunked");
  }
  return result;
}

CURLcode Curl_hyper_stream(struct Curl_easy *data,
                           struct connectdata *conn,
                           int *didwhat,
                           int select_res)
{
  hyper_response *resp = NULL;
  uint16_t http_status;
  int http_version;
  hyper_headers *headers = NULL;
  hyper_body *resp_body = NULL;
  struct hyptransfer *h = &data->hyp;
  hyper_task *task;
  hyper_task *foreach;
  const uint8_t *reasonp;
  size_t reason_len;
  CURLcode result = CURLE_OK;
  struct SingleRequest *k = &data->req;
  (void)conn;

  if(data->hyp.send_body_waker) {
    /* If there is still something to upload, wake it to give it
     * another try. */
    hyper_waker_wake(data->hyp.send_body_waker);
    data->hyp.send_body_waker = NULL;
  }

  if(select_res & CURL_CSELECT_IN) {
    if(h->read_waker)
      hyper_waker_wake(h->read_waker);
    h->read_waker = NULL;
  }
  if(select_res & CURL_CSELECT_OUT) {
    if(h->write_waker)
      hyper_waker_wake(h->write_waker);
    h->write_waker = NULL;
  }

  while(1) {
    hyper_task_return_type t;
    task = hyper_executor_poll(h->exec);
    if(!task) {
      *didwhat = KEEP_RECV;
      break;
    }
    t = hyper_task_type(task);
    if(t == HYPER_TASK_ERROR) {
      hyper_error *hypererr = hyper_task_value(task);
      hyper_task_free(task);
      if(data->state.hresult) {
        /* override Hyper's view, might not even be an error */
        result = data->state.hresult;
        infof(data, "hyperstream is done (by early callback)");
      }
      else {
        uint8_t errbuf[256];
        size_t errlen = hyper_error_print(hypererr, errbuf, sizeof(errbuf));
        hyper_code code = hyper_error_code(hypererr);
        failf(data, "Hyper: [%d] %.*s", (int)code, (int)errlen, errbuf);
        switch(code) {
        case HYPERE_ABORTED_BY_CALLBACK:
          result = CURLE_OK;
          goto out;
        case HYPERE_UNEXPECTED_EOF:
          if(!data->req.bytecount)
            result = CURLE_GOT_NOTHING;
          else
            result = CURLE_RECV_ERROR;
          goto out;
        case HYPERE_INVALID_PEER_MESSAGE:
          /* bump headerbytecount to avoid the count remaining at zero and
             appearing to not having read anything from the peer at all */
          data->req.headerbytecount++;
          result = CURLE_UNSUPPORTED_PROTOCOL; /* maybe */
          goto out;
        default:
          result = CURLE_RECV_ERROR;
          goto out;
        }
      }
      data->req.done = TRUE;
      hyper_error_free(hypererr);
      break;
    }
    else if(t == HYPER_TASK_EMPTY) {
      void *userdata = hyper_task_userdata(task);
      hyper_task_free(task);
      if(userdata == (void *)USERDATA_RESP_BODY) {
        /* end of transfer */
        data->req.done = TRUE;
        infof(data, "hyperstream is done");
        if(!k->bodywritten) {
          /* hyper does not always call the body write callback */
          result = Curl_http_firstwrite(data);
        }
        break;
      }
      else {
        /* A background task for hyper; ignore */
        DEBUGF(infof(data, "hyper: some background task done"));
        continue;
      }
    }
    else if(t == HYPER_TASK_RESPONSE) {
      resp = hyper_task_value(task);
      hyper_task_free(task);

      *didwhat = KEEP_RECV;
      if(!resp) {
        failf(data, "hyperstream: could not get response");
        result = CURLE_RECV_ERROR;
        goto out;
      }

      http_status = hyper_response_status(resp);
      http_version = hyper_response_version(resp);
      reasonp = hyper_response_reason_phrase(resp);
      reason_len = hyper_response_reason_phrase_len(resp);

      if(http_status == 417 && Curl_http_exp100_is_selected(data)) {
        infof(data, "Got 417 while waiting for a 100");
        data->state.disableexpect = TRUE;
        data->req.newurl = strdup(data->state.url);
        Curl_req_abort_sending(data);
      }

      result = status_line(data, conn,
                           http_status, http_version, reasonp, reason_len);
      if(result)
        goto out;

      headers = hyper_response_headers(resp);
      if(!headers) {
        failf(data, "hyperstream: could not get response headers");
        result = CURLE_RECV_ERROR;
        goto out;
      }

      /* the headers are already received */
      hyper_headers_foreach(headers, hyper_each_header, data);
      if(data->state.hresult) {
        result = data->state.hresult;
        goto out;
      }

      result = empty_header(data);
      if(result)
        goto out;

      k->deductheadercount =
        (100 <= http_status && 199 >= http_status) ? k->headerbytecount : 0;
#ifndef CURL_DISABLE_WEBSOCKETS
      if(k->upgr101 == UPGR101_WS) {
        if(http_status == 101) {
          /* verify the response */
          result = Curl_ws_accept(data, NULL, 0);
          if(result)
            goto out;
        }
        else {
          failf(data, "Expected 101, got %u", k->httpcode);
          result = CURLE_HTTP_RETURNED_ERROR;
          goto out;
        }
      }
#endif

      /* Curl_http_auth_act() checks what authentication methods that are
       * available and decides which one (if any) to use. It will set 'newurl'
       * if an auth method was picked. */
      result = Curl_http_auth_act(data);
      if(result)
        goto out;

      resp_body = hyper_response_body(resp);
      if(!resp_body) {
        failf(data, "hyperstream: could not get response body");
        result = CURLE_RECV_ERROR;
        goto out;
      }
      foreach = hyper_body_foreach(resp_body, hyper_body_chunk, data);
      if(!foreach) {
        failf(data, "hyperstream: body foreach failed");
        result = CURLE_OUT_OF_MEMORY;
        goto out;
      }
      hyper_task_set_userdata(foreach, (void *)USERDATA_RESP_BODY);
      if(HYPERE_OK != hyper_executor_push(h->exec, foreach)) {
        failf(data, "Couldn't hyper_executor_push the body-foreach");
        result = CURLE_OUT_OF_MEMORY;
        goto out;
      }

      hyper_response_free(resp);
      resp = NULL;
    }
    else {
      DEBUGF(infof(data, "hyper: unhandled tasktype %x", t));
    }
  } /* while(1) */

  if(!result && Curl_xfer_needs_flush(data)) {
    DEBUGF(infof(data, "Curl_hyper_stream(), connection needs flush"));
    result = Curl_xfer_flush(data);
  }

out:
  DEBUGF(infof(data, "Curl_hyper_stream() -> %d", result));
  if(resp)
    hyper_response_free(resp);
  return result;
}

static CURLcode debug_request(struct Curl_easy *data,
                              const char *method,
                              const char *path)
{
  char *req = aprintf("%s %s HTTP/1.1\r\n", method, path);
  if(!req)
    return CURLE_OUT_OF_MEMORY;
  Curl_debug(data, CURLINFO_HEADER_OUT, req, strlen(req));
  free(req);
  return CURLE_OK;
}

/*
 * Given a full header line "name: value" (optional CRLF in the input, should
 * be in the output), add to Hyper and send to the debug callback.
 *
 * Supports multiple headers.
 */

CURLcode Curl_hyper_header(struct Curl_easy *data, hyper_headers *headers,
                           const char *line)
{
  const char *p;
  const char *n;
  size_t nlen;
  const char *v;
  size_t vlen;
  bool newline = TRUE;
  int numh = 0;

  if(!line)
    return CURLE_OK;
  n = line;
  do {
    size_t linelen = 0;

    p = strchr(n, ':');
    if(!p)
      /* this is fine if we already added at least one header */
      return numh ? CURLE_OK : CURLE_BAD_FUNCTION_ARGUMENT;
    nlen = p - n;
    p++; /* move past the colon */
    while(*p == ' ')
      p++;
    v = p;
    p = strchr(v, '\r');
    if(!p) {
      p = strchr(v, '\n');
      if(p)
        linelen = 1; /* LF only */
      else {
        p = strchr(v, '\0');
        newline = FALSE; /* no newline */
      }
    }
    else
      linelen = 2; /* CRLF ending */
    linelen += (p - n);
    vlen = p - v;

    if(HYPERE_OK != hyper_headers_add(headers, (uint8_t *)n, nlen,
                                      (uint8_t *)v, vlen)) {
      failf(data, "hyper refused to add header '%s'", line);
      return CURLE_OUT_OF_MEMORY;
    }
    if(data->set.verbose) {
      char *ptr = NULL;
      if(!newline) {
        ptr = aprintf("%.*s\r\n", (int)linelen, line);
        if(!ptr)
          return CURLE_OUT_OF_MEMORY;
        Curl_debug(data, CURLINFO_HEADER_OUT, ptr, linelen + 2);
        free(ptr);
      }
      else
        Curl_debug(data, CURLINFO_HEADER_OUT, (char *)n, linelen);
    }
    numh++;
    n += linelen;
  } while(newline);
  return CURLE_OK;
}

static CURLcode request_target(struct Curl_easy *data,
                               struct connectdata *conn,
                               const char *method,
                               hyper_request *req)
{
  CURLcode result;
  struct dynbuf r;

  Curl_dyn_init(&r, DYN_HTTP_REQUEST);

  result = Curl_http_target(data, conn, &r);
  if(result)
    return result;

  if(hyper_request_set_uri(req, (uint8_t *)Curl_dyn_uptr(&r),
                                       Curl_dyn_len(&r))) {
    failf(data, "error setting uri to hyper");
    result = CURLE_OUT_OF_MEMORY;
  }
  else
    result = debug_request(data, method, Curl_dyn_ptr(&r));

  Curl_dyn_free(&r);

  return result;
}

static int uploadstreamed(void *userdata, hyper_context *ctx,
                          hyper_buf **chunk)
{
  size_t fillcount;
  struct Curl_easy *data = (struct Curl_easy *)userdata;
  CURLcode result;
  char *xfer_ulbuf;
  size_t xfer_ulblen;
  bool eos;
  int rc = HYPER_POLL_ERROR;
  (void)ctx;

  result = Curl_multi_xfer_ulbuf_borrow(data, &xfer_ulbuf, &xfer_ulblen);
  if(result)
    goto out;

  result = Curl_client_read(data, xfer_ulbuf, xfer_ulblen, &fillcount, &eos);
  if(result)
    goto out;

  if(fillcount) {
    hyper_buf *copy = hyper_buf_copy((uint8_t *)xfer_ulbuf, fillcount);
    if(copy)
      *chunk = copy;
    else {
      result = CURLE_OUT_OF_MEMORY;
      goto out;
    }
    /* increasing the writebytecount here is a little premature but we
       do not know exactly when the body is sent */
    data->req.writebytecount += fillcount;
    if(eos)
      data->req.eos_read = TRUE;
    Curl_pgrsSetUploadCounter(data, data->req.writebytecount);
    rc = HYPER_POLL_READY;
  }
  else if(eos) {
    data->req.eos_read = TRUE;
    *chunk = NULL;
    rc = HYPER_POLL_READY;
  }
  else {
    /* paused, save a waker */
    if(data->hyp.send_body_waker)
      hyper_waker_free(data->hyp.send_body_waker);
    data->hyp.send_body_waker = hyper_context_waker(ctx);
    rc = HYPER_POLL_PENDING;
  }

  if(!data->req.upload_done && data->req.eos_read) {
    DEBUGF(infof(data, "hyper: uploadstreamed(), upload is done"));
    result = Curl_req_set_upload_done(data);
  }

out:
  Curl_multi_xfer_ulbuf_release(data, xfer_ulbuf);
  data->state.hresult = result;
  DEBUGF(infof(data, "hyper: uploadstreamed() -> %d", result));
  return rc;
}

/*
 * finalize_request() sets up last headers and optional body settings
 */
static CURLcode finalize_request(struct Curl_easy *data,
                                 hyper_headers *headers,
                                 hyper_request *hyperreq,
                                 Curl_HttpReq httpreq)
{
  CURLcode result = CURLE_OK;
  struct dynbuf req;
  if((httpreq == HTTPREQ_GET) || (httpreq == HTTPREQ_HEAD)) {
    Curl_pgrsSetUploadSize(data, 0); /* no request body */
  }
  else {
    hyper_body *body;
    Curl_dyn_init(&req, DYN_HTTP_REQUEST);
    result = Curl_http_req_complete(data, &req, httpreq);
    if(result)
      return result;

    /* if the "complete" above did produce more than the closing line,
       parse the added headers */
    if(Curl_dyn_len(&req) != 2 || strcmp(Curl_dyn_ptr(&req), "\r\n")) {
      result = Curl_hyper_header(data, headers, Curl_dyn_ptr(&req));
      if(result)
        return result;
    }

    Curl_dyn_free(&req);

    body = hyper_body_new();
    hyper_body_set_userdata(body, data);
    hyper_body_set_data_func(body, uploadstreamed);

    if(HYPERE_OK != hyper_request_set_body(hyperreq, body)) {
      /* fail */
      result = CURLE_OUT_OF_MEMORY;
    }
  }

  return cr_hyper_add(data);
}

static CURLcode cookies(struct Curl_easy *data,
                        struct connectdata *conn,
                        hyper_headers *headers)
{
  struct dynbuf req;
  CURLcode result;
  Curl_dyn_init(&req, DYN_HTTP_REQUEST);

  result = Curl_http_cookies(data, conn, &req);
  if(!result)
    result = Curl_hyper_header(data, headers, Curl_dyn_ptr(&req));
  Curl_dyn_free(&req);
  return result;
}

/* called on 1xx responses */
static void http1xx_cb(void *arg, struct hyper_response *resp)
{
  struct Curl_easy *data = (struct Curl_easy *)arg;
  hyper_headers *headers = NULL;
  CURLcode result = CURLE_OK;
  uint16_t http_status;
  int http_version;
  const uint8_t *reasonp;
  size_t reason_len;

  infof(data, "Got HTTP 1xx informational");

  http_status = hyper_response_status(resp);
  http_version = hyper_response_version(resp);
  reasonp = hyper_response_reason_phrase(resp);
  reason_len = hyper_response_reason_phrase_len(resp);

  result = status_line(data, data->conn,
                       http_status, http_version, reasonp, reason_len);
  if(!result) {
    headers = hyper_response_headers(resp);
    if(!headers) {
      failf(data, "hyperstream: could not get 1xx response headers");
      result = CURLE_RECV_ERROR;
    }
  }
  data->state.hresult = result;

  if(!result) {
    /* the headers are already received */
    hyper_headers_foreach(headers, hyper_each_header, data);
    /* this callback also sets data->state.hresult on error */

    if(empty_header(data))
      result = CURLE_OUT_OF_MEMORY;
  }

  if(data->state.hresult)
    infof(data, "ERROR in 1xx, bail out");
}

/*
 * Curl_http() gets called from the generic multi_do() function when an HTTP
 * request is to be performed. This creates and sends a properly constructed
 * HTTP request.
 */
CURLcode Curl_http(struct Curl_easy *data, bool *done)
{
  struct connectdata *conn = data->conn;
  struct hyptransfer *h = &data->hyp;
  hyper_io *io = NULL;
  hyper_clientconn_options *options = NULL;
  hyper_task *task = NULL; /* for the handshake */
  hyper_task *sendtask = NULL; /* for the send */
  hyper_clientconn *client = NULL;
  hyper_request *req = NULL;
  hyper_headers *headers = NULL;
  hyper_task *handshake = NULL;
  CURLcode result;
  const char *p_accept; /* Accept: string */
  const char *method;
  Curl_HttpReq httpreq;
  const char *te = NULL; /* transfer-encoding */
  hyper_code rc;

  /* Always consider the DO phase done after this function call, even if there
     may be parts of the request that is not yet sent, since we can deal with
     the rest of the request in the PERFORM phase. */
  *done = TRUE;
  result = Curl_client_start(data);
  if(result)
    goto out;

  /* Add collecting of headers written to client. For a new connection,
   * we might have done that already, but reuse
   * or multiplex needs it here as well. */
  result = Curl_headers_init(data);
  if(result)
    goto out;

  infof(data, "Time for the Hyper dance");
  memset(h, 0, sizeof(struct hyptransfer));

  result = Curl_http_host(data, conn);
  if(result)
    goto out;

  Curl_http_method(data, conn, &method, &httpreq);

  DEBUGASSERT(data->req.bytecount ==  0);

  /* setup the authentication headers */
  {
    char *pq = NULL;
    if(data->state.up.query) {
      pq = aprintf("%s?%s", data->state.up.path, data->state.up.query);
      if(!pq) {
        result = CURLE_OUT_OF_MEMORY;
        goto out;
      }
    }
    result = Curl_http_output_auth(data, conn, method, httpreq,
                                   (pq ? pq : data->state.up.path), FALSE);
    free(pq);
    if(result)
      goto out;
  }

  result = Curl_http_req_set_reader(data, httpreq, &te);
  if(result)
    goto out;

  result = Curl_http_range(data, httpreq);
  if(result)
    goto out;

  result = Curl_http_useragent(data);
  if(result)
    goto out;

  io = hyper_io_new();
  if(!io) {
    failf(data, "Couldn't create hyper IO");
    result = CURLE_OUT_OF_MEMORY;
    goto out;
  }
  /* tell Hyper how to read/write network data */
  h->io_ctx.data = data;
  h->io_ctx.sockindex = FIRSTSOCKET;
  hyper_io_set_userdata(io, &h->io_ctx);
  hyper_io_set_read(io, Curl_hyper_recv);
  hyper_io_set_write(io, Curl_hyper_send);

  /* create an executor to poll futures */
  if(!h->exec) {
    h->exec = hyper_executor_new();
    if(!h->exec) {
      failf(data, "Couldn't create hyper executor");
      result = CURLE_OUT_OF_MEMORY;
      goto out;
    }
  }

  options = hyper_clientconn_options_new();
  if(!options) {
    failf(data, "Couldn't create hyper client options");
    result = CURLE_OUT_OF_MEMORY;
    goto out;
  }
  if(conn->alpn == CURL_HTTP_VERSION_2) {
    failf(data, "ALPN protocol h2 not supported with Hyper");
    result = CURLE_UNSUPPORTED_PROTOCOL;
    goto out;
  }
  hyper_clientconn_options_set_preserve_header_case(options, 1);
  hyper_clientconn_options_set_preserve_header_order(options, 1);
  hyper_clientconn_options_http1_allow_multiline_headers(options, 1);

  hyper_clientconn_options_exec(options, h->exec);

  /* "Both the `io` and the `options` are consumed in this function call" */
  handshake = hyper_clientconn_handshake(io, options);
  if(!handshake) {
    failf(data, "Couldn't create hyper client handshake");
    result = CURLE_OUT_OF_MEMORY;
    goto out;
  }
  io = NULL;
  options = NULL;

  if(HYPERE_OK != hyper_executor_push(h->exec, handshake)) {
    failf(data, "Couldn't hyper_executor_push the handshake");
    result = CURLE_OUT_OF_MEMORY;
    goto out;
  }
  handshake = NULL; /* ownership passed on */

  task = hyper_executor_poll(h->exec);
  if(!task) {
    failf(data, "Couldn't hyper_executor_poll the handshake");
    result = CURLE_OUT_OF_MEMORY;
    goto out;
  }

  client = hyper_task_value(task);
  hyper_task_free(task);

  req = hyper_request_new();
  if(!req) {
    failf(data, "Couldn't hyper_request_new");
    result = CURLE_OUT_OF_MEMORY;
    goto out;
  }

  if(!Curl_use_http_1_1plus(data, conn)) {
    if(HYPERE_OK != hyper_request_set_version(req,
                                              HYPER_HTTP_VERSION_1_0)) {
      failf(data, "error setting HTTP version");
      result = CURLE_OUT_OF_MEMORY;
      goto out;
    }
  }

  if(hyper_request_set_method(req, (uint8_t *)method, strlen(method))) {
    failf(data, "error setting method");
    result = CURLE_OUT_OF_MEMORY;
    goto out;
  }

  result = request_target(data, conn, method, req);
  if(result)
    goto out;

  headers = hyper_request_headers(req);
  if(!headers) {
    failf(data, "hyper_request_headers");
    result = CURLE_OUT_OF_MEMORY;
    goto out;
  }

  rc = hyper_request_on_informational(req, http1xx_cb, data);
  if(rc) {
    result = CURLE_OUT_OF_MEMORY;
    goto out;
  }

  if(data->state.aptr.host) {
    result = Curl_hyper_header(data, headers, data->state.aptr.host);
    if(result)
      goto out;
  }

#ifndef CURL_DISABLE_PROXY
  if(data->state.aptr.proxyuserpwd) {
    result = Curl_hyper_header(data, headers, data->state.aptr.proxyuserpwd);
    if(result)
      goto out;
  }
#endif

  if(data->state.aptr.userpwd) {
    result = Curl_hyper_header(data, headers, data->state.aptr.userpwd);
    if(result)
      goto out;
  }

  if((data->state.use_range && data->state.aptr.rangeline)) {
    result = Curl_hyper_header(data, headers, data->state.aptr.rangeline);
    if(result)
      goto out;
  }

  if(data->set.str[STRING_USERAGENT] &&
     *data->set.str[STRING_USERAGENT] &&
     data->state.aptr.uagent) {
    result = Curl_hyper_header(data, headers, data->state.aptr.uagent);
    if(result)
      goto out;
  }

  p_accept = Curl_checkheaders(data,
                               STRCONST("Accept")) ? NULL : "Accept: */*\r\n";
  if(p_accept) {
    result = Curl_hyper_header(data, headers, p_accept);
    if(result)
      goto out;
  }
  if(te) {
    result = Curl_hyper_header(data, headers, te);
    if(result)
      goto out;
  }

#ifndef CURL_DISABLE_ALTSVC
  if(conn->bits.altused && !Curl_checkheaders(data, STRCONST("Alt-Used"))) {
    char *altused = aprintf("Alt-Used: %s:%d\r\n",
                            conn->conn_to_host.name, conn->conn_to_port);
    if(!altused) {
      result = CURLE_OUT_OF_MEMORY;
      goto out;
    }
    result = Curl_hyper_header(data, headers, altused);
    if(result)
      goto out;
    free(altused);
  }
#endif

#ifndef CURL_DISABLE_PROXY
  if(conn->bits.httpproxy && !conn->bits.tunnel_proxy &&
     !Curl_checkheaders(data, STRCONST("Proxy-Connection")) &&
     !Curl_checkProxyheaders(data, conn, STRCONST("Proxy-Connection"))) {
    result = Curl_hyper_header(data, headers, "Proxy-Connection: Keep-Alive");
    if(result)
      goto out;
  }
#endif

  Curl_safefree(data->state.aptr.ref);
  if(data->state.referer && !Curl_checkheaders(data, STRCONST("Referer"))) {
    data->state.aptr.ref = aprintf("Referer: %s\r\n", data->state.referer);
    if(!data->state.aptr.ref)
      result = CURLE_OUT_OF_MEMORY;
    else
      result = Curl_hyper_header(data, headers, data->state.aptr.ref);
    if(result)
      goto out;
  }

#ifdef HAVE_LIBZ
  /* we only consider transfer-encoding magic if libz support is built-in */
  result = Curl_transferencode(data);
  if(result)
    goto out;
  result = Curl_hyper_header(data, headers, data->state.aptr.te);
  if(result)
    goto out;
#endif

  if(!Curl_checkheaders(data, STRCONST("Accept-Encoding")) &&
     data->set.str[STRING_ENCODING]) {
    Curl_safefree(data->state.aptr.accept_encoding);
    data->state.aptr.accept_encoding =
      aprintf("Accept-Encoding: %s\r\n", data->set.str[STRING_ENCODING]);
    if(!data->state.aptr.accept_encoding)
      result = CURLE_OUT_OF_MEMORY;
    else
      result = Curl_hyper_header(data, headers,
                                 data->state.aptr.accept_encoding);
    if(result)
      goto out;
  }
  else
    Curl_safefree(data->state.aptr.accept_encoding);

  result = cookies(data, conn, headers);
  if(result)
    goto out;

  if(!result && conn->handler->protocol&(CURLPROTO_WS|CURLPROTO_WSS))
    result = Curl_ws_request(data, headers);

  result = Curl_add_timecondition(data, headers);
  if(result)
    goto out;

  result = Curl_add_custom_headers(data, FALSE, headers);
  if(result)
    goto out;

  result = finalize_request(data, headers, req, httpreq);
  if(result)
    goto out;

  Curl_debug(data, CURLINFO_HEADER_OUT, (char *)"\r\n", 2);

  if(data->req.upload_chunky && data->req.authneg) {
    data->req.upload_chunky = TRUE;
  }
  else {
    data->req.upload_chunky = FALSE;
  }
  sendtask = hyper_clientconn_send(client, req);
  if(!sendtask) {
    failf(data, "hyper_clientconn_send");
    result = CURLE_OUT_OF_MEMORY;
    goto out;
  }
  req = NULL;

  if(HYPERE_OK != hyper_executor_push(h->exec, sendtask)) {
    failf(data, "Couldn't hyper_executor_push the send");
    result = CURLE_OUT_OF_MEMORY;
    goto out;
  }
  sendtask = NULL; /* ownership passed on */

  hyper_clientconn_free(client);
  client = NULL;

  if((httpreq == HTTPREQ_GET) || (httpreq == HTTPREQ_HEAD)) {
    /* HTTP GET/HEAD download */
    Curl_pgrsSetUploadSize(data, 0); /* nothing */
    result = Curl_req_set_upload_done(data);
    if(result)
      goto out;
  }

  Curl_xfer_setup1(data, CURL_XFER_SENDRECV, -1, TRUE);
  conn->datastream = Curl_hyper_stream;

  /* clear userpwd and proxyuserpwd to avoid reusing old credentials
   * from reused connections */
  Curl_safefree(data->state.aptr.userpwd);
#ifndef CURL_DISABLE_PROXY
  Curl_safefree(data->state.aptr.proxyuserpwd);
#endif

out:
  if(result) {
    if(io)
      hyper_io_free(io);
    if(options)
      hyper_clientconn_options_free(options);
    if(handshake)
      hyper_task_free(handshake);
    if(client)
      hyper_clientconn_free(client);
    if(req)
      hyper_request_free(req);
  }
  return result;
}

void Curl_hyper_done(struct Curl_easy *data)
{
  struct hyptransfer *h = &data->hyp;
  if(h->exec) {
    hyper_executor_free(h->exec);
    h->exec = NULL;
  }
  if(h->read_waker) {
    hyper_waker_free(h->read_waker);
    h->read_waker = NULL;
  }
  if(h->write_waker) {
    hyper_waker_free(h->write_waker);
    h->write_waker = NULL;
  }
  if(h->send_body_waker) {
    hyper_waker_free(h->send_body_waker);
    h->send_body_waker = NULL;
  }
}

static CURLcode cr_hyper_unpause(struct Curl_easy *data,
                                 struct Curl_creader *reader)
{
  (void)reader;
  if(data->hyp.send_body_waker) {
    hyper_waker_wake(data->hyp.send_body_waker);
    data->hyp.send_body_waker = NULL;
  }
  return CURLE_OK;
}

/* Hyper client reader, handling unpausing */
static const struct Curl_crtype cr_hyper_protocol = {
  "cr-hyper",
  Curl_creader_def_init,
  Curl_creader_def_read,
  Curl_creader_def_close,
  Curl_creader_def_needs_rewind,
  Curl_creader_def_total_length,
  Curl_creader_def_resume_from,
  Curl_creader_def_rewind,
  cr_hyper_unpause,
  Curl_creader_def_is_paused,
  Curl_creader_def_done,
  sizeof(struct Curl_creader)
};

static CURLcode cr_hyper_add(struct Curl_easy *data)
{
  struct Curl_creader *reader = NULL;
  CURLcode result;

  result = Curl_creader_create(&reader, data, &cr_hyper_protocol,
                               CURL_CR_PROTOCOL);
  if(!result)
    result = Curl_creader_add(data, reader);

  if(result && reader)
    Curl_creader_free(data, reader);
  return result;
}

#endif /* !defined(CURL_DISABLE_HTTP) && defined(USE_HYPER) */