http2: build with current nghttp2 version
[platform/upstream/curl.git] / lib / http2.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at http://curl.haxx.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  ***************************************************************************/
22
23 #include "curl_setup.h"
24
25 #ifdef USE_NGHTTP2
26 #define _MPRINTF_REPLACE
27 #include <curl/mprintf.h>
28
29 #include <nghttp2/nghttp2.h>
30 #include "urldata.h"
31 #include "http2.h"
32 #include "http.h"
33 #include "sendf.h"
34 #include "curl_base64.h"
35 #include "curl_memory.h"
36 #include "rawstr.h"
37 #include "multiif.h"
38
39 /* include memdebug.h last */
40 #include "memdebug.h"
41
42 #if (NGHTTP2_VERSION_NUM < 0x000300)
43 #error too old nghttp2 version, upgrade!
44 #endif
45
46 static int http2_perform_getsock(const struct connectdata *conn,
47                                  curl_socket_t *sock, /* points to
48                                                          numsocks
49                                                          number of
50                                                          sockets */
51                                  int numsocks)
52 {
53   const struct http_conn *httpc = &conn->proto.httpc;
54   int bitmap = GETSOCK_BLANK;
55   (void)numsocks;
56
57   /* TODO We should check underlying socket state if it is SSL socket
58      because of renegotiation. */
59   sock[0] = conn->sock[FIRSTSOCKET];
60
61   if(nghttp2_session_want_read(httpc->h2))
62     bitmap |= GETSOCK_READSOCK(FIRSTSOCKET);
63
64   if(nghttp2_session_want_write(httpc->h2))
65     bitmap |= GETSOCK_WRITESOCK(FIRSTSOCKET);
66
67   return bitmap;
68 }
69
70 static int http2_getsock(struct connectdata *conn,
71                          curl_socket_t *sock, /* points to numsocks
72                                                  number of sockets */
73                          int numsocks)
74 {
75   return http2_perform_getsock(conn, sock, numsocks);
76 }
77
78 /*
79  * HTTP2 handler interface. This isn't added to the general list of protocols
80  * but will be used at run-time when the protocol is dynamically switched from
81  * HTTP to HTTP2.
82  */
83 const struct Curl_handler Curl_handler_http2 = {
84   "HTTP2",                              /* scheme */
85   ZERO_NULL,                            /* setup_connection */
86   ZERO_NULL,                            /* do_it */
87   ZERO_NULL     ,                       /* done */
88   ZERO_NULL,                            /* do_more */
89   ZERO_NULL,                            /* connect_it */
90   ZERO_NULL,                            /* connecting */
91   ZERO_NULL,                            /* doing */
92   http2_getsock,                        /* proto_getsock */
93   http2_getsock,                        /* doing_getsock */
94   ZERO_NULL,                            /* domore_getsock */
95   http2_perform_getsock,                /* perform_getsock */
96   ZERO_NULL,                            /* disconnect */
97   ZERO_NULL,                            /* readwrite */
98   PORT_HTTP,                            /* defport */
99   CURLPROTO_HTTP,                       /* protocol */
100   PROTOPT_NONE                          /* flags */
101 };
102
103 const struct Curl_handler Curl_handler_http2_ssl = {
104   "HTTP2",                              /* scheme */
105   ZERO_NULL,                            /* setup_connection */
106   ZERO_NULL,                            /* do_it */
107   ZERO_NULL     ,                       /* done */
108   ZERO_NULL,                            /* do_more */
109   ZERO_NULL,                            /* connect_it */
110   ZERO_NULL,                            /* connecting */
111   ZERO_NULL,                            /* doing */
112   http2_getsock,                        /* proto_getsock */
113   http2_getsock,                        /* doing_getsock */
114   ZERO_NULL,                            /* domore_getsock */
115   http2_perform_getsock,                /* perform_getsock */
116   ZERO_NULL,                            /* disconnect */
117   ZERO_NULL,                            /* readwrite */
118   PORT_HTTP,                            /* defport */
119   CURLPROTO_HTTP | CURLPROTO_HTTPS,     /* protocol */
120   PROTOPT_SSL                           /* flags */
121 };
122
123 /*
124  * Store nghttp2 version info in this buffer, Prefix with a space.  Return
125  * total length written.
126  */
127 int Curl_http2_ver(char *p, size_t len)
128 {
129   nghttp2_info *h2 = nghttp2_version(0);
130   return snprintf(p, len, " nghttp2/%s", h2->version_str);
131 }
132
133 /*
134  * The implementation of nghttp2_send_callback type. Here we write |data| with
135  * size |length| to the network and return the number of bytes actually
136  * written. See the documentation of nghttp2_send_callback for the details.
137  */
138 static ssize_t send_callback(nghttp2_session *h2,
139                              const uint8_t *data, size_t length, int flags,
140                              void *userp)
141 {
142   struct connectdata *conn = (struct connectdata *)userp;
143   struct http_conn *httpc = &conn->proto.httpc;
144   ssize_t written;
145   CURLcode rc;
146   (void)h2;
147   (void)flags;
148
149   rc = 0;
150   written = ((Curl_send*)httpc->send_underlying)(conn, FIRSTSOCKET,
151                                                  data, length, &rc);
152
153   if(rc == CURLE_AGAIN) {
154     return NGHTTP2_ERR_WOULDBLOCK;
155   }
156
157   if(written == -1) {
158     failf(conn->data, "Failed sending HTTP2 data");
159     return NGHTTP2_ERR_CALLBACK_FAILURE;
160   }
161
162   if(!written)
163     return NGHTTP2_ERR_WOULDBLOCK;
164
165   return written;
166 }
167
168 static int on_frame_recv(nghttp2_session *session, const nghttp2_frame *frame,
169                          void *userp)
170 {
171   struct connectdata *conn = (struct connectdata *)userp;
172   struct http_conn *c = &conn->proto.httpc;
173   int rv;
174   (void)session;
175   (void)frame;
176   infof(conn->data, "on_frame_recv() was called with header %x\n",
177         frame->hd.type);
178   switch(frame->hd.type) {
179   case NGHTTP2_HEADERS:
180     if(frame->headers.cat != NGHTTP2_HCAT_RESPONSE)
181       break;
182     c->bodystarted = TRUE;
183     Curl_add_buffer(c->header_recvbuf, "\r\n", 2);
184     c->nread_header_recvbuf = c->len < c->header_recvbuf->size_used ?
185       c->len : c->header_recvbuf->size_used;
186
187     memcpy(c->mem, c->header_recvbuf->buffer, c->nread_header_recvbuf);
188
189     c->mem += c->nread_header_recvbuf;
190     c->len -= c->nread_header_recvbuf;
191     break;
192   case NGHTTP2_PUSH_PROMISE:
193     rv = nghttp2_submit_rst_stream(session, NGHTTP2_FLAG_NONE,
194                                    frame->hd.stream_id, NGHTTP2_CANCEL);
195     if(nghttp2_is_fatal(rv)) {
196       return rv;
197     }
198     break;
199   }
200   return 0;
201 }
202
203 static int on_invalid_frame_recv(nghttp2_session *session,
204                                  const nghttp2_frame *frame,
205                                  nghttp2_error_code error_code, void *userp)
206 {
207   struct connectdata *conn = (struct connectdata *)userp;
208   (void)session;
209   (void)frame;
210   infof(conn->data, "on_invalid_frame_recv() was called, error_code = %d\n",
211         error_code);
212   return 0;
213 }
214
215 static int on_data_chunk_recv(nghttp2_session *session, uint8_t flags,
216                               int32_t stream_id,
217                               const uint8_t *data, size_t len, void *userp)
218 {
219   struct connectdata *conn = (struct connectdata *)userp;
220   struct http_conn *c = &conn->proto.httpc;
221   size_t nread;
222   (void)session;
223   (void)flags;
224   (void)data;
225   infof(conn->data, "on_data_chunk_recv() "
226         "len = %u, stream = %x\n", len, stream_id);
227
228   if(stream_id != c->stream_id) {
229     return 0;
230   }
231
232   nread = c->len < len ? c->len : len;
233   memcpy(c->mem, data, nread);
234
235   c->mem += nread;
236   c->len -= nread;
237
238   infof(conn->data, "%zu data written\n", nread);
239
240   if(nread < len) {
241     c->data = data + nread;
242     c->datalen = len - nread;
243     return NGHTTP2_ERR_PAUSE;
244   }
245   return 0;
246 }
247
248 static int before_frame_send(nghttp2_session *session,
249                              const nghttp2_frame *frame,
250                              void *userp)
251 {
252   struct connectdata *conn = (struct connectdata *)userp;
253   struct http_conn *c = &conn->proto.httpc;
254   (void)session;
255   (void)frame;
256   infof(conn->data, "before_frame_send() was called\n");
257   if(frame->hd.type == NGHTTP2_HEADERS &&
258      frame->headers.cat == NGHTTP2_HCAT_REQUEST) {
259     /* Get stream ID of our request */
260     c->stream_id = frame->hd.stream_id;
261   }
262   return 0;
263 }
264 static int on_frame_send(nghttp2_session *session,
265                          const nghttp2_frame *frame,
266                          void *userp)
267 {
268   struct connectdata *conn = (struct connectdata *)userp;
269   (void)session;
270   (void)frame;
271   infof(conn->data, "on_frame_send() was called\n");
272   return 0;
273 }
274 static int on_frame_not_send(nghttp2_session *session,
275                              const nghttp2_frame *frame,
276                              int lib_error_code, void *userp)
277 {
278   struct connectdata *conn = (struct connectdata *)userp;
279   (void)session;
280   (void)frame;
281   infof(conn->data, "on_frame_not_send() was called, lib_error_code = %d\n",
282         lib_error_code);
283   return 0;
284 }
285 static int on_stream_close(nghttp2_session *session, int32_t stream_id,
286                            nghttp2_error_code error_code, void *userp)
287 {
288   struct connectdata *conn = (struct connectdata *)userp;
289   struct http_conn *c = &conn->proto.httpc;
290   (void)session;
291   (void)stream_id;
292   infof(conn->data, "on_stream_close() was called, error_code = %d\n",
293         error_code);
294
295   if(stream_id != c->stream_id) {
296     return 0;
297   }
298
299   c->closed = TRUE;
300
301   return 0;
302 }
303
304 static int on_unknown_frame_recv(nghttp2_session *session,
305                                  const uint8_t *head, size_t headlen,
306                                  const uint8_t *payload, size_t payloadlen,
307                                  void *userp)
308 {
309   struct connectdata *conn = (struct connectdata *)userp;
310   (void)session;
311   (void)head;
312   (void)headlen;
313   (void)payload;
314   (void)payloadlen;
315   infof(conn->data, "on_unknown_frame_recv() was called\n");
316   return 0;
317 }
318 static int on_begin_headers(nghttp2_session *session,
319                             const nghttp2_frame *frame, void *userp)
320 {
321   struct connectdata *conn = (struct connectdata *)userp;
322   (void)session;
323   (void)frame;
324   infof(conn->data, "on_begin_headers() was called\n");
325   return 0;
326 }
327
328 static const char STATUS[] = ":status";
329
330 /* frame->hd.type is either NGHTTP2_HEADERS or NGHTTP2_PUSH_PROMISE */
331 static int on_header(nghttp2_session *session, const nghttp2_frame *frame,
332                       const uint8_t *name, size_t namelen,
333                       const uint8_t *value, size_t valuelen,
334                       void *userp)
335 {
336   struct connectdata *conn = (struct connectdata *)userp;
337   struct http_conn *c = &conn->proto.httpc;
338   (void)session;
339   (void)frame;
340
341   if(frame->hd.stream_id != c->stream_id) {
342     return 0;
343   }
344
345   if(namelen == sizeof(":status") - 1 &&
346      memcmp(STATUS, name, namelen) == 0) {
347     snprintf(c->header_recvbuf->buffer, 13, "HTTP/2.0 %s", value);
348     c->header_recvbuf->buffer[12] = '\r';
349     return 0;
350   }
351   else {
352     /* convert to a HTTP1-style header */
353     infof(conn->data, "got header\n");
354     Curl_add_buffer(c->header_recvbuf, name, namelen);
355     Curl_add_buffer(c->header_recvbuf, ":", 1);
356     Curl_add_buffer(c->header_recvbuf, value, valuelen);
357     Curl_add_buffer(c->header_recvbuf, "\r\n", 2);
358   }
359
360   return 0; /* 0 is successful */
361 }
362
363 /*
364  * This is all callbacks nghttp2 calls
365  */
366 static const nghttp2_session_callbacks callbacks = {
367   send_callback,         /* nghttp2_send_callback */
368   NULL,                  /* nghttp2_recv_callback */
369   on_frame_recv,         /* nghttp2_on_frame_recv_callback */
370   on_invalid_frame_recv, /* nghttp2_on_invalid_frame_recv_callback */
371   on_data_chunk_recv,    /* nghttp2_on_data_chunk_recv_callback */
372   before_frame_send,     /* nghttp2_before_frame_send_callback */
373   on_frame_send,         /* nghttp2_on_frame_send_callback */
374   on_frame_not_send,     /* nghttp2_on_frame_not_send_callback */
375   on_stream_close,       /* nghttp2_on_stream_close_callback */
376   on_unknown_frame_recv, /* nghttp2_on_unknown_frame_recv_callback */
377   on_begin_headers,      /* nghttp2_on_begin_headers_callback */
378   on_header              /* nghttp2_on_header_callback */
379 #if NGHTTP2_VERSION_NUM >= 0x000400
380   , NULL                 /* nghttp2_select_padding_callback */
381 #endif
382 };
383
384 static ssize_t data_source_read_callback(nghttp2_session *session,
385                                          int32_t stream_id,
386                                          uint8_t *buf, size_t length,
387                                          int *eof,
388                                          nghttp2_data_source *source,
389                                          void *userp)
390 {
391   struct connectdata *conn = (struct connectdata *)userp;
392   struct http_conn *c = &conn->proto.httpc;
393   size_t nread;
394   (void)session;
395   (void)stream_id;
396   (void)eof;
397   (void)source;
398
399   nread = c->upload_len < length ? c->upload_len : length;
400   if(nread > 0) {
401     memcpy(buf, c->upload_mem, nread);
402     c->upload_mem += nread;
403     c->upload_len -= nread;
404     c->upload_left -= nread;
405   }
406
407   if(c->upload_left == 0)
408     *eof = 1;
409   else if(nread == 0)
410     return NGHTTP2_ERR_DEFERRED;
411
412   return nread;
413 }
414
415 /*
416  * The HTTP2 settings we send in the Upgrade request
417  */
418 static nghttp2_settings_entry settings[] = {
419   { NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS, 100 },
420   { NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE, NGHTTP2_INITIAL_WINDOW_SIZE },
421 };
422
423 #define H2_BUFSIZE 4096
424
425 /*
426  * Initialize nghttp2 for a Curl connection
427  */
428 CURLcode Curl_http2_init(struct connectdata *conn)
429 {
430   if(!conn->proto.httpc.h2) {
431     int rc;
432     conn->proto.httpc.inbuf = malloc(H2_BUFSIZE);
433     if(conn->proto.httpc.inbuf == NULL)
434       return CURLE_OUT_OF_MEMORY;
435
436     /* The nghttp2 session is not yet setup, do it */
437     rc = nghttp2_session_client_new(&conn->proto.httpc.h2,
438                                     &callbacks, conn);
439     if(rc) {
440       failf(conn->data, "Couldn't initialize nghttp2!");
441       return CURLE_OUT_OF_MEMORY; /* most likely at least */
442     }
443   }
444   return CURLE_OK;
445 }
446
447 /*
448  * Send a request using http2
449  */
450 CURLcode Curl_http2_send_request(struct connectdata *conn)
451 {
452   (void)conn;
453   return CURLE_OK;
454 }
455
456 /*
457  * Append headers to ask for a HTTP1.1 to HTTP2 upgrade.
458  */
459 CURLcode Curl_http2_request_upgrade(Curl_send_buffer *req,
460                                     struct connectdata *conn)
461 {
462   CURLcode result;
463   ssize_t binlen;
464   char *base64;
465   size_t blen;
466   struct SingleRequest *k = &conn->data->req;
467   uint8_t *binsettings = conn->proto.httpc.binsettings;
468
469   Curl_http2_init(conn);
470
471   /* As long as we have a fixed set of settings, we don't have to dynamically
472    * figure out the base64 strings since it'll always be the same. However,
473    * the settings will likely not be fixed every time in the future.
474    */
475
476   /* this returns number of bytes it wrote */
477   binlen = nghttp2_pack_settings_payload(binsettings, H2_BINSETTINGS_LEN,
478                                          settings,
479                                          sizeof(settings)/sizeof(settings[0]));
480   if(!binlen) {
481     failf(conn->data, "nghttp2 unexpectedly failed on pack_settings_payload");
482     return CURLE_FAILED_INIT;
483   }
484   conn->proto.httpc.binlen = binlen;
485
486   result = Curl_base64_encode(conn->data, (const char *)binsettings, binlen,
487                               &base64, &blen);
488   if(result)
489     return result;
490
491   result = Curl_add_bufferf(req,
492                             "Connection: Upgrade, HTTP2-Settings\r\n"
493                             "Upgrade: %s\r\n"
494                             "HTTP2-Settings: %s\r\n",
495                             NGHTTP2_PROTO_VERSION_ID, base64);
496   free(base64);
497
498   k->upgr101 = UPGR101_REQUESTED;
499
500   return result;
501 }
502
503 /*
504  * If the read would block (EWOULDBLOCK) we return -1. Otherwise we return
505  * a regular CURLcode value.
506  */
507 static ssize_t http2_recv(struct connectdata *conn, int sockindex,
508                           char *mem, size_t len, CURLcode *err)
509 {
510   CURLcode rc;
511   ssize_t rv;
512   ssize_t nread;
513   struct http_conn *httpc = &conn->proto.httpc;
514
515   (void)sockindex; /* we always do HTTP2 on sockindex 0 */
516
517   /* Nullify here because we call nghttp2_session_send() and they
518      might refer to the old buffer. */
519   httpc->upload_mem = NULL;
520   httpc->upload_len = 0;
521
522   if(httpc->bodystarted &&
523      httpc->nread_header_recvbuf < httpc->header_recvbuf->size_used) {
524     size_t left =
525       httpc->header_recvbuf->size_used - httpc->nread_header_recvbuf;
526     size_t ncopy = len < left ? len : left;
527     memcpy(mem, httpc->header_recvbuf->buffer + httpc->nread_header_recvbuf,
528            ncopy);
529     httpc->nread_header_recvbuf += ncopy;
530     return ncopy;
531   }
532
533   if(httpc->data) {
534     nread = len < httpc->datalen ? len : httpc->datalen;
535     memcpy(mem, httpc->data, nread);
536
537     httpc->data += nread;
538     httpc->datalen -= nread;
539
540     infof(conn->data, "%zu data written\n", nread);
541     if(httpc->datalen == 0) {
542       httpc->data = NULL;
543       httpc->datalen = 0;
544     }
545     return nread;
546   }
547
548   conn->proto.httpc.mem = mem;
549   conn->proto.httpc.len = len;
550
551   infof(conn->data, "http2_recv: %d bytes buffer\n",
552         conn->proto.httpc.len);
553
554   rc = 0;
555   nread = ((Curl_recv*)httpc->recv_underlying)(conn, FIRSTSOCKET,
556                                                httpc->inbuf, H2_BUFSIZE, &rc);
557
558   if(rc == CURLE_AGAIN) {
559     *err = rc;
560     return -1;
561   }
562
563   if(nread == -1) {
564     failf(conn->data, "Failed receiving HTTP2 data");
565     *err = rc;
566     return 0;
567   }
568
569   infof(conn->data, "nread=%zd\n", nread);
570   rv = nghttp2_session_mem_recv(httpc->h2,
571                                 (const uint8_t *)httpc->inbuf, nread);
572
573   if(nghttp2_is_fatal((int)rv)) {
574     failf(conn->data, "nghttp2_session_mem_recv() returned %d:%s\n",
575           rv, nghttp2_strerror((int)rv));
576     *err = CURLE_RECV_ERROR;
577     return 0;
578   }
579   infof(conn->data, "nghttp2_session_mem_recv() returns %zd\n", rv);
580   /* Always send pending frames in nghttp2 session, because
581      nghttp2_session_mem_recv() may queue new frame */
582   rv = nghttp2_session_send(httpc->h2);
583   if(rv != 0) {
584     *err = CURLE_SEND_ERROR;
585     return 0;
586   }
587   if(len != httpc->len) {
588     return len - conn->proto.httpc.len;
589   }
590   /* If stream is closed, return 0 to signal the http routine to close
591      the connection */
592   if(httpc->closed) {
593     return 0;
594   }
595   *err = CURLE_AGAIN;
596   return -1;
597 }
598
599 #define MAKE_NV(k, v)                                           \
600   { (uint8_t*)k, (uint8_t*)v, sizeof(k) - 1, sizeof(v) - 1 }
601
602 #define MAKE_NV2(k, v, vlen)                            \
603   { (uint8_t*)k, (uint8_t*)v, sizeof(k) - 1, vlen }
604
605 /* return number of received (decrypted) bytes */
606 static ssize_t http2_send(struct connectdata *conn, int sockindex,
607                           const void *mem, size_t len, CURLcode *err)
608 {
609   /*
610    * BIG TODO: Currently, we send request in this function, but this
611    * function is also used to send request body. It would be nice to
612    * add dedicated function for request.
613    */
614   int rv;
615   struct http_conn *httpc = &conn->proto.httpc;
616   nghttp2_nv *nva;
617   size_t nheader;
618   size_t i;
619   char *hdbuf = (char*)mem;
620   char *end;
621   nghttp2_data_provider data_prd;
622   (void)sockindex;
623
624   infof(conn->data, "http2_send len=%zu\n", len);
625
626   if(httpc->stream_id != -1) {
627     /* If stream_id != -1, we have dispatched request HEADERS, and now
628        are going to send or sending request body in DATA frame */
629     httpc->upload_mem = mem;
630     httpc->upload_len = len;
631     nghttp2_session_resume_data(httpc->h2, httpc->stream_id);
632     rv = nghttp2_session_send(httpc->h2);
633     if(nghttp2_is_fatal(rv)) {
634       *err = CURLE_SEND_ERROR;
635       return -1;
636     }
637     return len - httpc->upload_len;
638   }
639
640   /* Calculate number of headers contained in [mem, mem + len) */
641   /* Here, we assume the curl http code generate *correct* HTTP header
642      field block */
643   nheader = 0;
644   for(i = 0; i < len; ++i) {
645     if(hdbuf[i] == 0x0a) {
646       ++nheader;
647     }
648   }
649   /* We counted additional 2 \n in the first and last line. We need 3
650      new headers: :method, :path and :scheme. Therefore we need one
651      more space. */
652   nheader += 1;
653   nva = malloc(sizeof(nghttp2_nv) * nheader);
654   if(nva == NULL) {
655     *err = CURLE_OUT_OF_MEMORY;
656     return -1;
657   }
658   /* Extract :method, :path from request line */
659   end = strchr(hdbuf, ' ');
660   nva[0].name = (unsigned char *)":method";
661   nva[0].namelen = (uint16_t)strlen((char *)nva[0].name);
662   nva[0].value = (unsigned char *)hdbuf;
663   nva[0].valuelen = (uint16_t)(end - hdbuf);
664
665   hdbuf = end + 1;
666
667   end = strchr(hdbuf, ' ');
668   nva[1].name = (unsigned char *)":path";
669   nva[1].namelen = (uint16_t)strlen((char *)nva[1].name);
670   nva[1].value = (unsigned char *)hdbuf;
671   nva[1].valuelen = (uint16_t)(end - hdbuf);
672
673   nva[2].name = (unsigned char *)":scheme";
674   nva[2].namelen = (uint16_t)strlen((char *)nva[2].name);
675   if(conn->handler->flags & PROTOPT_SSL)
676     nva[2].value = (unsigned char *)"https";
677   else
678     nva[2].value = (unsigned char *)"http";
679   nva[2].valuelen = (uint16_t)strlen((char *)nva[2].value);
680
681   hdbuf = strchr(hdbuf, 0x0a);
682   ++hdbuf;
683
684   for(i = 3; i < nheader; ++i) {
685     end = strchr(hdbuf, ':');
686     assert(end);
687     if(end - hdbuf == 4 && Curl_raw_nequal("host", hdbuf, 4)) {
688       nva[i].name = (unsigned char *)":authority";
689       nva[i].namelen = (uint16_t)strlen((char *)nva[i].name);
690     }
691     else {
692       nva[i].name = (unsigned char *)hdbuf;
693       nva[i].namelen = (uint16_t)(end - hdbuf);
694     }
695     hdbuf = end + 1;
696     for(; *hdbuf == ' '; ++hdbuf);
697     end = strchr(hdbuf, 0x0d);
698     assert(end);
699     nva[i].value = (unsigned char *)hdbuf;
700     nva[i].valuelen = (uint16_t)(end - hdbuf);
701
702     hdbuf = end + 2;
703     /* Inspect Content-Length header field and retrieve the request
704        entity length so that we can set END_STREAM to the last DATA
705        frame. */
706     if(nva[i].namelen == 14 &&
707        Curl_raw_nequal("content-length", (char*)nva[i].name, 14)) {
708       size_t j;
709       for(j = 0; j < nva[i].valuelen; ++j) {
710         httpc->upload_left *= 10;
711         httpc->upload_left += nva[i].value[j] - '0';
712       }
713       infof(conn->data, "request content-length=%zu\n", httpc->upload_left);
714     }
715   }
716
717   switch(conn->data->set.httpreq) {
718   case HTTPREQ_POST:
719   case HTTPREQ_POST_FORM:
720   case HTTPREQ_PUT:
721     data_prd.read_callback = data_source_read_callback;
722     data_prd.source.ptr = NULL;
723     rv = nghttp2_submit_request(httpc->h2, 0, nva, nheader, &data_prd, NULL);
724     break;
725   default:
726     rv = nghttp2_submit_request(httpc->h2, 0, nva, nheader, NULL, NULL);
727   }
728
729   free(nva);
730
731   if(rv != 0) {
732     *err = CURLE_SEND_ERROR;
733     return -1;
734   }
735
736   rv = nghttp2_session_send(httpc->h2);
737
738   if(rv != 0) {
739     *err = CURLE_SEND_ERROR;
740     return -1;
741   }
742
743   if(httpc->stream_id != -1) {
744     /* If whole HEADERS frame was sent off to the underlying socket,
745        the nghttp2 library calls data_source_read_callback. But only
746        it found that no data available, so it deferred the DATA
747        transmission. Which means that nghttp2_session_want_write()
748        returns 0 on http2_perform_getsock(), which results that no
749        writable socket check is performed. To workaround this, we
750        issue nghttp2_session_resume_data() here to bring back DATA
751        transmission from deferred state. */
752     nghttp2_session_resume_data(httpc->h2, httpc->stream_id);
753   }
754
755   return len;
756 }
757
758 int Curl_http2_switched(struct connectdata *conn)
759 {
760   int rv;
761   CURLcode rc;
762   struct http_conn *httpc = &conn->proto.httpc;
763   /* we are switched! */
764   /* Don't know this is needed here at this moment. Original
765      handler->flags is still useful. */
766   if(conn->handler->flags & PROTOPT_SSL)
767     conn->handler = &Curl_handler_http2_ssl;
768   else
769     conn->handler = &Curl_handler_http2;
770
771   httpc->recv_underlying = (recving)conn->recv[FIRSTSOCKET];
772   httpc->send_underlying = (sending)conn->send[FIRSTSOCKET];
773   conn->recv[FIRSTSOCKET] = http2_recv;
774   conn->send[FIRSTSOCKET] = http2_send;
775   infof(conn->data, "We have switched to HTTP2\n");
776   httpc->bodystarted = FALSE;
777   httpc->closed = FALSE;
778   httpc->header_recvbuf = Curl_add_buffer_init();
779   httpc->nread_header_recvbuf = 0;
780   httpc->data = NULL;
781   httpc->datalen = 0;
782   httpc->upload_left = 0;
783   httpc->upload_mem = NULL;
784   httpc->upload_len = 0;
785
786   conn->httpversion = 20;
787
788   /* Put place holder for status line */
789   Curl_add_buffer(httpc->header_recvbuf, "HTTP/2.0 200\r\n", 14);
790
791   /* TODO: May get CURLE_AGAIN */
792   rv = (int) ((Curl_send*)httpc->send_underlying)
793     (conn, FIRSTSOCKET,
794      NGHTTP2_CLIENT_CONNECTION_HEADER,
795      NGHTTP2_CLIENT_CONNECTION_HEADER_LEN,
796      &rc);
797   assert(rv == 24);
798   if(conn->data->req.upgr101 == UPGR101_RECEIVED) {
799     /* stream 1 is opened implicitly on upgrade */
800     httpc->stream_id = 1;
801     /* queue SETTINGS frame (again) */
802     rv = nghttp2_session_upgrade(httpc->h2, httpc->binsettings,
803                                  httpc->binlen, NULL);
804     if(rv != 0) {
805       failf(conn->data, "nghttp2_session_upgrade() failed: %s(%d)",
806             nghttp2_strerror(rv), rv);
807       return -1;
808     }
809   }
810   else {
811     /* stream ID is unknown at this point */
812     httpc->stream_id = -1;
813     rv = nghttp2_submit_settings(httpc->h2, NGHTTP2_FLAG_NONE, NULL, 0);
814     if(rv != 0) {
815       failf(conn->data, "nghttp2_submit_settings() failed: %s(%d)",
816             nghttp2_strerror(rv), rv);
817       return -1;
818     }
819   }
820   return 0;
821 }
822
823 #endif