sh2lib.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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. int flags = fcntl(hd->sockfd, F_GETFL, 0);
  56. fcntl(hd->sockfd, F_SETFL, flags | O_NONBLOCK);
  57. return 0;
  58. }
  59. /*
  60. * The implementation of nghttp2_send_callback type. Here we write
  61. * |data| with size |length| to the network and return the number of
  62. * bytes actually written. See the documentation of
  63. * nghttp2_send_callback for the details.
  64. */
  65. static ssize_t callback_send_inner(struct sh2lib_handle *hd, const uint8_t *data,
  66. size_t length)
  67. {
  68. int rv = SSL_write(hd->ssl, data, (int)length);
  69. if (rv <= 0) {
  70. int err = SSL_get_error(hd->ssl, rv);
  71. if (err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ) {
  72. rv = NGHTTP2_ERR_WOULDBLOCK;
  73. } else {
  74. rv = NGHTTP2_ERR_CALLBACK_FAILURE;
  75. }
  76. }
  77. return rv;
  78. }
  79. static ssize_t callback_send(nghttp2_session *session, const uint8_t *data,
  80. size_t length, int flags, void *user_data)
  81. {
  82. int rv = 0;
  83. struct sh2lib_handle *hd = user_data;
  84. int copy_offset = 0;
  85. int pending_data = length;
  86. /* Send data in 1000 byte chunks */
  87. while (copy_offset != (length - 1)) {
  88. int chunk_len = pending_data > 1000 ? 1000 : pending_data;
  89. int subrv = callback_send_inner(hd, data + copy_offset, chunk_len);
  90. if (subrv <= 0) {
  91. if (copy_offset) {
  92. /* If some data was xferred, send the number of bytes
  93. * xferred */
  94. rv = copy_offset;
  95. } else {
  96. /* If not, send the error code */
  97. rv = subrv;
  98. }
  99. break;
  100. }
  101. copy_offset += chunk_len;
  102. pending_data -= chunk_len;
  103. }
  104. return rv;
  105. }
  106. /*
  107. * The implementation of nghttp2_recv_callback type. Here we read data
  108. * from the network and write them in |buf|. The capacity of |buf| is
  109. * |length| bytes. Returns the number of bytes stored in |buf|. See
  110. * the documentation of nghttp2_recv_callback for the details.
  111. */
  112. static ssize_t callback_recv(nghttp2_session *session, uint8_t *buf,
  113. size_t length, int flags, void *user_data)
  114. {
  115. struct sh2lib_handle *hd = user_data;
  116. int rv;
  117. rv = SSL_read(hd->ssl, buf, (int)length);
  118. if (rv < 0) {
  119. int err = SSL_get_error(hd->ssl, rv);
  120. if (err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ) {
  121. rv = NGHTTP2_ERR_WOULDBLOCK;
  122. } else {
  123. rv = NGHTTP2_ERR_CALLBACK_FAILURE;
  124. }
  125. } else if (rv == 0) {
  126. rv = NGHTTP2_ERR_EOF;
  127. }
  128. return rv;
  129. }
  130. char *sh2lib_frame_type_str(int type)
  131. {
  132. switch (type) {
  133. case NGHTTP2_HEADERS:
  134. return "HEADERS";
  135. break;
  136. case NGHTTP2_RST_STREAM:
  137. return "RST_STREAM";
  138. break;
  139. case NGHTTP2_GOAWAY:
  140. return "GOAWAY";
  141. break;
  142. case NGHTTP2_DATA:
  143. return "DATA";
  144. break;
  145. case NGHTTP2_SETTINGS:
  146. return "SETTINGS";
  147. break;
  148. case NGHTTP2_PUSH_PROMISE:
  149. return "PUSH_PROMISE";
  150. break;
  151. case NGHTTP2_PING:
  152. return "PING";
  153. break;
  154. default:
  155. return "other";
  156. break;
  157. }
  158. }
  159. static int callback_on_frame_send(nghttp2_session *session,
  160. const nghttp2_frame *frame, void *user_data)
  161. {
  162. ESP_LOGD(TAG, "[frame-send] frame type %s", sh2lib_frame_type_str(frame->hd.type));
  163. switch (frame->hd.type) {
  164. case NGHTTP2_HEADERS:
  165. if (nghttp2_session_get_stream_user_data(session, frame->hd.stream_id)) {
  166. ESP_LOGD(TAG, "[frame-send] C ----------------------------> S (HEADERS)");
  167. #if DBG_FRAME_SEND
  168. ESP_LOGD(TAG, "[frame-send] headers nv-len = %d", frame->headers.nvlen);
  169. const nghttp2_nv *nva = frame->headers.nva;
  170. size_t i;
  171. for (i = 0; i < frame->headers.nvlen; ++i) {
  172. ESP_LOGD(TAG, "[frame-send] %s : %s", nva[i].name, nva[i].value);
  173. }
  174. #endif
  175. }
  176. break;
  177. }
  178. return 0;
  179. }
  180. static int callback_on_frame_recv(nghttp2_session *session,
  181. const nghttp2_frame *frame, void *user_data)
  182. {
  183. ESP_LOGD(TAG, "[frame-recv][sid: %d] frame type %s", frame->hd.stream_id, sh2lib_frame_type_str(frame->hd.type));
  184. if (frame->hd.type != NGHTTP2_DATA) {
  185. return 0;
  186. }
  187. /* Subsequent processing only for data frame */
  188. sh2lib_frame_data_recv_cb_t data_recv_cb = nghttp2_session_get_stream_user_data(session, frame->hd.stream_id);
  189. if (data_recv_cb) {
  190. struct sh2lib_handle *h2 = user_data;
  191. (*data_recv_cb)(h2, NULL, 0, DATA_RECV_FRAME_COMPLETE);
  192. }
  193. return 0;
  194. }
  195. static int callback_on_stream_close(nghttp2_session *session, int32_t stream_id,
  196. uint32_t error_code, void *user_data)
  197. {
  198. ESP_LOGD(TAG, "[stream-close][sid %d]", stream_id);
  199. sh2lib_frame_data_recv_cb_t data_recv_cb = nghttp2_session_get_stream_user_data(session, stream_id);
  200. if (data_recv_cb) {
  201. struct sh2lib_handle *h2 = user_data;
  202. (*data_recv_cb)(h2, NULL, 0, DATA_RECV_RST_STREAM);
  203. }
  204. return 0;
  205. }
  206. static int callback_on_data_chunk_recv(nghttp2_session *session, uint8_t flags,
  207. int32_t stream_id, const uint8_t *data,
  208. size_t len, void *user_data)
  209. {
  210. sh2lib_frame_data_recv_cb_t data_recv_cb;
  211. ESP_LOGD(TAG, "[data-chunk][sid:%d]", stream_id);
  212. data_recv_cb = nghttp2_session_get_stream_user_data(session, stream_id);
  213. if (data_recv_cb) {
  214. ESP_LOGD(TAG, "[data-chunk] C <---------------------------- S (DATA chunk)"
  215. "%lu bytes",
  216. (unsigned long int)len);
  217. struct sh2lib_handle *h2 = user_data;
  218. (*data_recv_cb)(h2, (char *)data, len, 0);
  219. /* TODO: What to do with the return value: look for pause/abort */
  220. }
  221. return 0;
  222. }
  223. static int callback_on_header(nghttp2_session *session, const nghttp2_frame *frame,
  224. const uint8_t *name, size_t namelen, const uint8_t *value,
  225. size_t valuelen, uint8_t flags, void *user_data)
  226. {
  227. ESP_LOGD(TAG, "[hdr-recv][sid:%d] %s : %s", frame->hd.stream_id, name, value);
  228. return 0;
  229. }
  230. static int do_http2_connect(struct sh2lib_handle *hd)
  231. {
  232. int ret;
  233. nghttp2_session_callbacks *callbacks;
  234. nghttp2_session_callbacks_new(&callbacks);
  235. nghttp2_session_callbacks_set_send_callback(callbacks, callback_send);
  236. nghttp2_session_callbacks_set_recv_callback(callbacks, callback_recv);
  237. nghttp2_session_callbacks_set_on_frame_send_callback(callbacks, callback_on_frame_send);
  238. nghttp2_session_callbacks_set_on_frame_recv_callback(callbacks, callback_on_frame_recv);
  239. nghttp2_session_callbacks_set_on_stream_close_callback(callbacks, callback_on_stream_close);
  240. nghttp2_session_callbacks_set_on_data_chunk_recv_callback(callbacks, callback_on_data_chunk_recv);
  241. nghttp2_session_callbacks_set_on_header_callback(callbacks, callback_on_header);
  242. ret = nghttp2_session_client_new(&hd->http2_sess, callbacks, hd);
  243. if (ret != 0) {
  244. ESP_LOGE(TAG, "[sh2-connect] New http2 session failed");
  245. nghttp2_session_callbacks_del(callbacks);
  246. return -1;
  247. }
  248. nghttp2_session_callbacks_del(callbacks);
  249. /* Create the SETTINGS frame */
  250. ret = nghttp2_submit_settings(hd->http2_sess, NGHTTP2_FLAG_NONE, NULL, 0);
  251. if (ret != 0) {
  252. ESP_LOGE(TAG, "[sh2-connect] Submit settings failed");
  253. return -1;
  254. }
  255. return 0;
  256. }
  257. int sh2lib_connect(struct sh2lib_handle *hd, const char *uri)
  258. {
  259. memset(hd, 0, sizeof(*hd));
  260. struct uri res;
  261. /* Parse the URI */
  262. if (parse_uri(&res, uri) != 0) {
  263. ESP_LOGE(TAG, "[sh2-connect] Failed to parse URI");
  264. return -1;
  265. }
  266. /* TCP connection with the server */
  267. int sockfd = connect_to_host(res.host, res.hostlen, res.port);
  268. if (sockfd < 0) {
  269. ESP_LOGE(TAG, "[sh2-connect] Failed to connect to %s", uri);
  270. return -1;
  271. }
  272. /* SSL Connection on the socket */
  273. if (do_ssl_connect(hd, sockfd, res.host) != 0) {
  274. ESP_LOGE(TAG, "[sh2-connect] SSL Handshake failed with %s", uri);
  275. goto error;
  276. }
  277. /* HTTP/2 Connection */
  278. if (do_http2_connect(hd) != 0) {
  279. ESP_LOGE(TAG, "[sh2-connect] HTTP2 Connection failed with %s", uri);
  280. goto error;
  281. }
  282. return 0;
  283. error:
  284. sh2lib_free(hd);
  285. return -1;
  286. }
  287. void sh2lib_free(struct sh2lib_handle *hd)
  288. {
  289. if (hd->http2_sess) {
  290. nghttp2_session_del(hd->http2_sess);
  291. hd->http2_sess = NULL;
  292. }
  293. if (hd->ssl) {
  294. SSL_free(hd->ssl);
  295. hd->ssl = NULL;
  296. }
  297. if (hd->ssl_ctx) {
  298. SSL_CTX_free(hd->ssl_ctx);
  299. hd->ssl_ctx = NULL;
  300. }
  301. if (hd->sockfd) {
  302. close(hd->sockfd);
  303. hd->ssl_ctx = 0;
  304. }
  305. }
  306. int sh2lib_execute(struct sh2lib_handle *hd)
  307. {
  308. int ret;
  309. ret = nghttp2_session_send(hd->http2_sess);
  310. if (ret != 0) {
  311. ESP_LOGE(TAG, "[sh2-execute] HTTP2 session send failed %d", ret);
  312. return -1;
  313. }
  314. ret = nghttp2_session_recv(hd->http2_sess);
  315. if (ret != 0) {
  316. ESP_LOGE(TAG, "[sh2-execute] HTTP2 session recv failed %d", ret);
  317. return -1;
  318. }
  319. return 0;
  320. }
  321. 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)
  322. {
  323. int ret = nghttp2_submit_request(hd->http2_sess, NULL, nva, nvlen, NULL, recv_cb);
  324. if (ret < 0) {
  325. ESP_LOGE(TAG, "[sh2-do-get] HEADERS call failed");
  326. return -1;
  327. }
  328. return ret;
  329. }
  330. int sh2lib_do_get(struct sh2lib_handle *hd, const char *path, sh2lib_frame_data_recv_cb_t recv_cb)
  331. {
  332. #define HTTP2_PATH_NV ":path"
  333. const nghttp2_nv nva[] = { SH2LIB_MAKE_NV(":method", "GET"),
  334. SH2LIB_MAKE_NV(":scheme", "https"),
  335. {(uint8_t *)HTTP2_PATH_NV, (uint8_t *)path, strlen(HTTP2_PATH_NV), strlen(path), NGHTTP2_NV_FLAG_NONE},
  336. };
  337. return sh2lib_do_get_with_nv(hd, nva, sizeof(nva) / sizeof(nva[0]), recv_cb);
  338. }
  339. ssize_t sh2lib_data_provider_cb(nghttp2_session *session, int32_t stream_id, uint8_t *buf,
  340. size_t length, uint32_t *data_flags,
  341. nghttp2_data_source *source, void *user_data)
  342. {
  343. struct sh2lib_handle *h2 = user_data;
  344. sh2lib_putpost_data_cb_t data_cb = source->ptr;
  345. return (*data_cb)(h2, (char *)buf, length, data_flags);
  346. }
  347. int sh2lib_do_putpost_with_nv(struct sh2lib_handle *hd, const nghttp2_nv *nva, size_t nvlen,
  348. sh2lib_putpost_data_cb_t send_cb,
  349. sh2lib_frame_data_recv_cb_t recv_cb)
  350. {
  351. nghttp2_data_provider sh2lib_data_provider;
  352. sh2lib_data_provider.read_callback = sh2lib_data_provider_cb;
  353. sh2lib_data_provider.source.ptr = send_cb;
  354. int ret = nghttp2_submit_request(hd->http2_sess, NULL, nva, nvlen, &sh2lib_data_provider, recv_cb);
  355. if (ret < 0) {
  356. ESP_LOGE(TAG, "[sh2-do-putpost] HEADERS call failed");
  357. return -1;
  358. }
  359. return ret;
  360. }
  361. int sh2lib_do_post(struct sh2lib_handle *hd, const char *path,
  362. sh2lib_putpost_data_cb_t send_cb,
  363. sh2lib_frame_data_recv_cb_t recv_cb)
  364. {
  365. const nghttp2_nv nva[] = { SH2LIB_MAKE_NV(":method", "POST"),
  366. SH2LIB_MAKE_NV(":scheme", "https"),
  367. SH2LIB_MAKE_NV(":path", path),
  368. };
  369. return sh2lib_do_putpost_with_nv(hd, nva, sizeof(nva) / sizeof(nva[0]), send_cb, recv_cb);
  370. }
  371. int sh2lib_do_put(struct sh2lib_handle *hd, const char *path,
  372. sh2lib_putpost_data_cb_t send_cb,
  373. sh2lib_frame_data_recv_cb_t recv_cb)
  374. {
  375. const nghttp2_nv nva[] = { SH2LIB_MAKE_NV(":method", "PUT"),
  376. SH2LIB_MAKE_NV(":scheme", "https"),
  377. SH2LIB_MAKE_NV(":path", path),
  378. };
  379. return sh2lib_do_putpost_with_nv(hd, nva, sizeof(nva) / sizeof(nva[0]), send_cb, recv_cb);
  380. }