sh2lib.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. // Copyright 2017 Espressif Systems (Shanghai) PTE LTD
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include <stdlib.h>
  15. #include <stdint.h>
  16. #include <stddef.h>
  17. #include <stdio.h>
  18. #include <string.h>
  19. #include <unistd.h>
  20. #include <fcntl.h>
  21. #include <ctype.h>
  22. #include <netdb.h>
  23. #include <esp_log.h>
  24. #include "connectlib.h"
  25. #include "sh2lib.h"
  26. static const char *TAG = "sh2lib";
  27. #define DBG_FRAME_SEND 1
  28. /* SSL connection on the TCP socket that is already connected */
  29. static int do_ssl_connect(struct sh2lib_handle *hd, int sockfd, const char *hostname)
  30. {
  31. SSL_CTX *ssl_ctx = SSL_CTX_new(TLSv1_2_client_method());
  32. if (!ssl_ctx) {
  33. return -1;
  34. }
  35. unsigned char vector[] = "\x02h2";
  36. SSL_CTX_set_alpn_protos(ssl_ctx, vector, strlen((char *)vector));
  37. SSL *ssl = SSL_new(ssl_ctx);
  38. if (!ssl) {
  39. SSL_CTX_free(ssl_ctx);
  40. return -1;
  41. }
  42. SSL_set_tlsext_host_name(ssl, hostname);
  43. SSL_set_fd(ssl, sockfd);
  44. int ret = SSL_connect(ssl);
  45. if (ret < 1) {
  46. int err = SSL_get_error(ssl, ret);
  47. ESP_LOGE(TAG, "[ssl-connect] Failed SSL handshake ret=%d error=%d", ret, err);
  48. SSL_CTX_free(ssl_ctx);
  49. SSL_free(ssl);
  50. return -1;
  51. }
  52. hd->ssl_ctx = ssl_ctx;
  53. hd->ssl = ssl;
  54. hd->sockfd = sockfd;
  55. hd->hostname = strdup(hostname);
  56. int flags = fcntl(hd->sockfd, F_GETFL, 0);
  57. fcntl(hd->sockfd, F_SETFL, flags | O_NONBLOCK);
  58. return 0;
  59. }
  60. /*
  61. * The implementation of nghttp2_send_callback type. Here we write
  62. * |data| with size |length| to the network and return the number of
  63. * bytes actually written. See the documentation of
  64. * nghttp2_send_callback for the details.
  65. */
  66. static ssize_t callback_send_inner(struct sh2lib_handle *hd, const uint8_t *data,
  67. size_t length)
  68. {
  69. int rv = SSL_write(hd->ssl, data, (int)length);
  70. if (rv <= 0) {
  71. int err = SSL_get_error(hd->ssl, rv);
  72. if (err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ) {
  73. rv = NGHTTP2_ERR_WOULDBLOCK;
  74. } else {
  75. rv = NGHTTP2_ERR_CALLBACK_FAILURE;
  76. }
  77. }
  78. return rv;
  79. }
  80. static ssize_t callback_send(nghttp2_session *session, const uint8_t *data,
  81. size_t length, int flags, void *user_data)
  82. {
  83. int rv = 0;
  84. struct sh2lib_handle *hd = user_data;
  85. int copy_offset = 0;
  86. int pending_data = length;
  87. /* Send data in 1000 byte chunks */
  88. while (copy_offset != (length - 1)) {
  89. int chunk_len = pending_data > 1000 ? 1000 : pending_data;
  90. int subrv = callback_send_inner(hd, data + copy_offset, chunk_len);
  91. if (subrv <= 0) {
  92. if (copy_offset) {
  93. /* If some data was xferred, send the number of bytes
  94. * xferred */
  95. rv = copy_offset;
  96. } else {
  97. /* If not, send the error code */
  98. rv = subrv;
  99. }
  100. break;
  101. }
  102. copy_offset += chunk_len;
  103. pending_data -= chunk_len;
  104. }
  105. return rv;
  106. }
  107. /*
  108. * The implementation of nghttp2_recv_callback type. Here we read data
  109. * from the network and write them in |buf|. The capacity of |buf| is
  110. * |length| bytes. Returns the number of bytes stored in |buf|. See
  111. * the documentation of nghttp2_recv_callback for the details.
  112. */
  113. static ssize_t callback_recv(nghttp2_session *session, uint8_t *buf,
  114. size_t length, int flags, void *user_data)
  115. {
  116. struct sh2lib_handle *hd = user_data;
  117. int rv;
  118. rv = SSL_read(hd->ssl, buf, (int)length);
  119. if (rv < 0) {
  120. int err = SSL_get_error(hd->ssl, rv);
  121. if (err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ) {
  122. rv = NGHTTP2_ERR_WOULDBLOCK;
  123. } else {
  124. rv = NGHTTP2_ERR_CALLBACK_FAILURE;
  125. }
  126. } else if (rv == 0) {
  127. rv = NGHTTP2_ERR_EOF;
  128. }
  129. return rv;
  130. }
  131. char *sh2lib_frame_type_str(int type)
  132. {
  133. switch (type) {
  134. case NGHTTP2_HEADERS:
  135. return "HEADERS";
  136. break;
  137. case NGHTTP2_RST_STREAM:
  138. return "RST_STREAM";
  139. break;
  140. case NGHTTP2_GOAWAY:
  141. return "GOAWAY";
  142. break;
  143. case NGHTTP2_DATA:
  144. return "DATA";
  145. break;
  146. case NGHTTP2_SETTINGS:
  147. return "SETTINGS";
  148. break;
  149. case NGHTTP2_PUSH_PROMISE:
  150. return "PUSH_PROMISE";
  151. break;
  152. case NGHTTP2_PING:
  153. return "PING";
  154. break;
  155. default:
  156. return "other";
  157. break;
  158. }
  159. }
  160. static int callback_on_frame_send(nghttp2_session *session,
  161. const nghttp2_frame *frame, void *user_data)
  162. {
  163. ESP_LOGD(TAG, "[frame-send] frame type %s", sh2lib_frame_type_str(frame->hd.type));
  164. switch (frame->hd.type) {
  165. case NGHTTP2_HEADERS:
  166. if (nghttp2_session_get_stream_user_data(session, frame->hd.stream_id)) {
  167. ESP_LOGD(TAG, "[frame-send] C ----------------------------> S (HEADERS)");
  168. #if DBG_FRAME_SEND
  169. ESP_LOGD(TAG, "[frame-send] headers nv-len = %d", frame->headers.nvlen);
  170. const nghttp2_nv *nva = frame->headers.nva;
  171. size_t i;
  172. for (i = 0; i < frame->headers.nvlen; ++i) {
  173. ESP_LOGD(TAG, "[frame-send] %s : %s", nva[i].name, nva[i].value);
  174. }
  175. #endif
  176. }
  177. break;
  178. }
  179. return 0;
  180. }
  181. static int callback_on_frame_recv(nghttp2_session *session,
  182. const nghttp2_frame *frame, void *user_data)
  183. {
  184. ESP_LOGD(TAG, "[frame-recv][sid: %d] frame type %s", frame->hd.stream_id, sh2lib_frame_type_str(frame->hd.type));
  185. if (frame->hd.type != NGHTTP2_DATA) {
  186. return 0;
  187. }
  188. /* Subsequent processing only for data frame */
  189. sh2lib_frame_data_recv_cb_t data_recv_cb = nghttp2_session_get_stream_user_data(session, frame->hd.stream_id);
  190. if (data_recv_cb) {
  191. struct sh2lib_handle *h2 = user_data;
  192. (*data_recv_cb)(h2, NULL, 0, DATA_RECV_FRAME_COMPLETE);
  193. }
  194. return 0;
  195. }
  196. static int callback_on_stream_close(nghttp2_session *session, int32_t stream_id,
  197. uint32_t error_code, void *user_data)
  198. {
  199. ESP_LOGD(TAG, "[stream-close][sid %d]", stream_id);
  200. sh2lib_frame_data_recv_cb_t data_recv_cb = nghttp2_session_get_stream_user_data(session, stream_id);
  201. if (data_recv_cb) {
  202. struct sh2lib_handle *h2 = user_data;
  203. (*data_recv_cb)(h2, NULL, 0, DATA_RECV_RST_STREAM);
  204. }
  205. return 0;
  206. }
  207. static int callback_on_data_chunk_recv(nghttp2_session *session, uint8_t flags,
  208. int32_t stream_id, const uint8_t *data,
  209. size_t len, void *user_data)
  210. {
  211. sh2lib_frame_data_recv_cb_t data_recv_cb;
  212. ESP_LOGD(TAG, "[data-chunk][sid:%d]", stream_id);
  213. data_recv_cb = nghttp2_session_get_stream_user_data(session, stream_id);
  214. if (data_recv_cb) {
  215. ESP_LOGD(TAG, "[data-chunk] C <---------------------------- S (DATA chunk)"
  216. "%lu bytes",
  217. (unsigned long int)len);
  218. struct sh2lib_handle *h2 = user_data;
  219. (*data_recv_cb)(h2, (char *)data, len, 0);
  220. /* TODO: What to do with the return value: look for pause/abort */
  221. }
  222. return 0;
  223. }
  224. static int callback_on_header(nghttp2_session *session, const nghttp2_frame *frame,
  225. const uint8_t *name, size_t namelen, const uint8_t *value,
  226. size_t valuelen, uint8_t flags, void *user_data)
  227. {
  228. ESP_LOGD(TAG, "[hdr-recv][sid:%d] %s : %s", frame->hd.stream_id, name, value);
  229. return 0;
  230. }
  231. static int do_http2_connect(struct sh2lib_handle *hd)
  232. {
  233. int ret;
  234. nghttp2_session_callbacks *callbacks;
  235. nghttp2_session_callbacks_new(&callbacks);
  236. nghttp2_session_callbacks_set_send_callback(callbacks, callback_send);
  237. nghttp2_session_callbacks_set_recv_callback(callbacks, callback_recv);
  238. nghttp2_session_callbacks_set_on_frame_send_callback(callbacks, callback_on_frame_send);
  239. nghttp2_session_callbacks_set_on_frame_recv_callback(callbacks, callback_on_frame_recv);
  240. nghttp2_session_callbacks_set_on_stream_close_callback(callbacks, callback_on_stream_close);
  241. nghttp2_session_callbacks_set_on_data_chunk_recv_callback(callbacks, callback_on_data_chunk_recv);
  242. nghttp2_session_callbacks_set_on_header_callback(callbacks, callback_on_header);
  243. ret = nghttp2_session_client_new(&hd->http2_sess, callbacks, hd);
  244. if (ret != 0) {
  245. ESP_LOGE(TAG, "[sh2-connect] New http2 session failed");
  246. nghttp2_session_callbacks_del(callbacks);
  247. return -1;
  248. }
  249. nghttp2_session_callbacks_del(callbacks);
  250. /* Create the SETTINGS frame */
  251. ret = nghttp2_submit_settings(hd->http2_sess, NGHTTP2_FLAG_NONE, NULL, 0);
  252. if (ret != 0) {
  253. ESP_LOGE(TAG, "[sh2-connect] Submit settings failed");
  254. return -1;
  255. }
  256. return 0;
  257. }
  258. int sh2lib_connect(struct sh2lib_handle *hd, const char *uri)
  259. {
  260. memset(hd, 0, sizeof(*hd));
  261. struct uri res;
  262. /* Parse the URI */
  263. if (parse_uri(&res, uri) != 0) {
  264. ESP_LOGE(TAG, "[sh2-connect] Failed to parse URI");
  265. return -1;
  266. }
  267. /* TCP connection with the server */
  268. int sockfd = connect_to_host(res.host, res.hostlen, res.port);
  269. if (sockfd < 0) {
  270. ESP_LOGE(TAG, "[sh2-connect] Failed to connect to %s", uri);
  271. return -1;
  272. }
  273. /* SSL Connection on the socket */
  274. if (do_ssl_connect(hd, sockfd, res.host) != 0) {
  275. ESP_LOGE(TAG, "[sh2-connect] SSL Handshake failed with %s", uri);
  276. goto error;
  277. }
  278. /* HTTP/2 Connection */
  279. if (do_http2_connect(hd) != 0) {
  280. ESP_LOGE(TAG, "[sh2-connect] HTTP2 Connection failed with %s", uri);
  281. goto error;
  282. }
  283. return 0;
  284. error:
  285. sh2lib_free(hd);
  286. return -1;
  287. }
  288. void sh2lib_free(struct sh2lib_handle *hd)
  289. {
  290. if (hd->http2_sess) {
  291. nghttp2_session_del(hd->http2_sess);
  292. hd->http2_sess = NULL;
  293. }
  294. if (hd->ssl) {
  295. SSL_free(hd->ssl);
  296. hd->ssl = NULL;
  297. }
  298. if (hd->ssl_ctx) {
  299. SSL_CTX_free(hd->ssl_ctx);
  300. hd->ssl_ctx = NULL;
  301. }
  302. if (hd->sockfd) {
  303. close(hd->sockfd);
  304. hd->ssl_ctx = 0;
  305. }
  306. if (hd->hostname) {
  307. free(hd->hostname);
  308. hd->hostname = NULL;
  309. }
  310. }
  311. int sh2lib_execute(struct sh2lib_handle *hd)
  312. {
  313. int ret;
  314. ret = nghttp2_session_send(hd->http2_sess);
  315. if (ret != 0) {
  316. ESP_LOGE(TAG, "[sh2-execute] HTTP2 session send failed %d", ret);
  317. return -1;
  318. }
  319. ret = nghttp2_session_recv(hd->http2_sess);
  320. if (ret != 0) {
  321. ESP_LOGE(TAG, "[sh2-execute] HTTP2 session recv failed %d", ret);
  322. return -1;
  323. }
  324. return 0;
  325. }
  326. int sh2lib_do_get_with_nv(struct sh2lib_handle *hd, const nghttp2_nv *nva, size_t nvlen, sh2lib_frame_data_recv_cb_t recv_cb)
  327. {
  328. int ret = nghttp2_submit_request(hd->http2_sess, NULL, nva, nvlen, NULL, recv_cb);
  329. if (ret < 0) {
  330. ESP_LOGE(TAG, "[sh2-do-get] HEADERS call failed");
  331. return -1;
  332. }
  333. return ret;
  334. }
  335. int sh2lib_do_get(struct sh2lib_handle *hd, const char *path, sh2lib_frame_data_recv_cb_t recv_cb)
  336. {
  337. const nghttp2_nv nva[] = { SH2LIB_MAKE_NV(":method", "GET"),
  338. SH2LIB_MAKE_NV(":scheme", "https"),
  339. SH2LIB_MAKE_NV(":authority", hd->hostname),
  340. SH2LIB_MAKE_NV(":path", path),
  341. };
  342. return sh2lib_do_get_with_nv(hd, nva, sizeof(nva) / sizeof(nva[0]), recv_cb);
  343. }
  344. ssize_t sh2lib_data_provider_cb(nghttp2_session *session, int32_t stream_id, uint8_t *buf,
  345. size_t length, uint32_t *data_flags,
  346. nghttp2_data_source *source, void *user_data)
  347. {
  348. struct sh2lib_handle *h2 = user_data;
  349. sh2lib_putpost_data_cb_t data_cb = source->ptr;
  350. return (*data_cb)(h2, (char *)buf, length, data_flags);
  351. }
  352. int sh2lib_do_putpost_with_nv(struct sh2lib_handle *hd, const nghttp2_nv *nva, size_t nvlen,
  353. sh2lib_putpost_data_cb_t send_cb,
  354. sh2lib_frame_data_recv_cb_t recv_cb)
  355. {
  356. nghttp2_data_provider sh2lib_data_provider;
  357. sh2lib_data_provider.read_callback = sh2lib_data_provider_cb;
  358. sh2lib_data_provider.source.ptr = send_cb;
  359. int ret = nghttp2_submit_request(hd->http2_sess, NULL, nva, nvlen, &sh2lib_data_provider, recv_cb);
  360. if (ret < 0) {
  361. ESP_LOGE(TAG, "[sh2-do-putpost] HEADERS call failed");
  362. return -1;
  363. }
  364. return ret;
  365. }
  366. int sh2lib_do_post(struct sh2lib_handle *hd, const char *path,
  367. sh2lib_putpost_data_cb_t send_cb,
  368. sh2lib_frame_data_recv_cb_t recv_cb)
  369. {
  370. const nghttp2_nv nva[] = { SH2LIB_MAKE_NV(":method", "POST"),
  371. SH2LIB_MAKE_NV(":scheme", "https"),
  372. SH2LIB_MAKE_NV(":authority", hd->hostname),
  373. SH2LIB_MAKE_NV(":path", path),
  374. };
  375. return sh2lib_do_putpost_with_nv(hd, nva, sizeof(nva) / sizeof(nva[0]), send_cb, recv_cb);
  376. }
  377. int sh2lib_do_put(struct sh2lib_handle *hd, const char *path,
  378. sh2lib_putpost_data_cb_t send_cb,
  379. sh2lib_frame_data_recv_cb_t recv_cb)
  380. {
  381. const nghttp2_nv nva[] = { SH2LIB_MAKE_NV(":method", "PUT"),
  382. SH2LIB_MAKE_NV(":scheme", "https"),
  383. SH2LIB_MAKE_NV(":authority", hd->hostname),
  384. SH2LIB_MAKE_NV(":path", path),
  385. };
  386. return sh2lib_do_putpost_with_nv(hd, nva, sizeof(nva) / sizeof(nva[0]), send_cb, recv_cb);
  387. }