mqtt_client.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. #include "mqtt_client.h"
  2. #include "hbase.h"
  3. #include "hlog.h"
  4. #include "herr.h"
  5. #include "hendian.h"
  6. static unsigned short mqtt_next_mid() {
  7. static unsigned short s_mid = 0;
  8. return ++s_mid;
  9. }
  10. static int mqtt_client_send(mqtt_client_t* cli, const void* buf, int len) {
  11. // thread-safe
  12. hmutex_lock(&cli->mutex_);
  13. int nwrite = hio_write(cli->io, buf, len);
  14. hmutex_unlock(&cli->mutex_);
  15. return nwrite;
  16. }
  17. static int mqtt_send_head(hio_t* io, int type, int length) {
  18. mqtt_client_t* cli = (mqtt_client_t*)hevent_userdata(io);
  19. mqtt_head_t head;
  20. memset(&head, 0, sizeof(head));
  21. head.type = type;
  22. head.length = length;
  23. unsigned char headbuf[8] = { 0 };
  24. int headlen = mqtt_head_pack(&head, headbuf);
  25. return mqtt_client_send(cli, headbuf, headlen);
  26. }
  27. static int mqtt_send_head_with_mid(hio_t* io, int type, unsigned short mid) {
  28. mqtt_client_t* cli = (mqtt_client_t*)hevent_userdata(io);
  29. mqtt_head_t head;
  30. memset(&head, 0, sizeof(head));
  31. head.type = type;
  32. if (head.type == MQTT_TYPE_PUBREL) {
  33. head.qos = 1;
  34. }
  35. head.length = 2;
  36. unsigned char headbuf[8] = { 0 };
  37. unsigned char* p = headbuf;
  38. int headlen = mqtt_head_pack(&head, p);
  39. p += headlen;
  40. PUSH16(p, mid);
  41. return mqtt_client_send(cli, headbuf, headlen + 2);
  42. }
  43. static void mqtt_send_ping(hio_t* io) {
  44. mqtt_send_head(io, MQTT_TYPE_PINGREQ, 0);
  45. }
  46. static void mqtt_send_pong(hio_t* io) {
  47. mqtt_send_head(io, MQTT_TYPE_PINGRESP, 0);
  48. }
  49. static void mqtt_send_disconnect(hio_t* io) {
  50. mqtt_send_head(io, MQTT_TYPE_DISCONNECT, 0);
  51. }
  52. /*
  53. * MQTT_TYPE_CONNECT
  54. * 2 + protocol_name + 1 protocol_version + 1 conn_flags + 2 keepalive + 2 + [client_id] +
  55. * [2 + will_topic + 2 + will_payload] +
  56. * [2 + username] + [2 + password]
  57. */
  58. static int mqtt_client_login(mqtt_client_t* cli) {
  59. int len = 2 + 1 + 1 + 2 + 2;
  60. unsigned short cid_len = 0,
  61. will_topic_len = 0,
  62. will_payload_len = 0,
  63. username_len = 0,
  64. password_len = 0;
  65. unsigned char conn_flags = 0;
  66. // protocol_name_len
  67. len += cli->protocol_version == MQTT_PROTOCOL_V31 ? 6 : 4;
  68. if (*cli->client_id) {
  69. cid_len = strlen(cli->client_id);
  70. } else {
  71. cid_len = 20;
  72. hv_random_string(cli->client_id, cid_len);
  73. hlogi("MQTT client_id: %.*s", (int)cid_len, cli->client_id);
  74. }
  75. len += cid_len;
  76. if (cid_len == 0) cli->clean_session = 1;
  77. if (cli->clean_session) {
  78. conn_flags |= MQTT_CONN_CLEAN_SESSION;
  79. }
  80. if (cli->will && cli->will->topic && cli->will->payload) {
  81. will_topic_len = cli->will->topic_len ? cli->will->topic_len : strlen(cli->will->topic);
  82. will_payload_len = cli->will->payload_len ? cli->will->payload_len : strlen(cli->will->payload);
  83. if (will_topic_len && will_payload_len) {
  84. conn_flags |= MQTT_CONN_HAS_WILL;
  85. conn_flags |= ((cli->will->qos & 3) << 3);
  86. if (cli->will->retain) {
  87. conn_flags |= MQTT_CONN_WILL_RETAIN;
  88. }
  89. len += 2 + will_topic_len;
  90. len += 2 + will_payload_len;
  91. }
  92. }
  93. if (*cli->username) {
  94. username_len = strlen(cli->username);
  95. if (username_len) {
  96. conn_flags |= MQTT_CONN_HAS_USERNAME;
  97. len += 2 + username_len;
  98. }
  99. }
  100. if (*cli->password) {
  101. password_len = strlen(cli->password);
  102. if (password_len) {
  103. conn_flags |= MQTT_CONN_HAS_PASSWORD;
  104. len += 2 + password_len;
  105. }
  106. }
  107. mqtt_head_t head;
  108. memset(&head, 0, sizeof(head));
  109. head.type = MQTT_TYPE_CONNECT;
  110. head.length = len;
  111. int buflen = mqtt_estimate_length(&head);
  112. unsigned char* buf = NULL;
  113. HV_STACK_ALLOC(buf, buflen);
  114. unsigned char* p = buf;
  115. int headlen = mqtt_head_pack(&head, p);
  116. p += headlen;
  117. // TODO: Not implement MQTT_PROTOCOL_V5
  118. if (cli->protocol_version == MQTT_PROTOCOL_V31) {
  119. PUSH16(p, 6);
  120. PUSH_N(p, MQTT_PROTOCOL_NAME_v31, 6);
  121. } else {
  122. PUSH16(p, 4);
  123. PUSH_N(p, MQTT_PROTOCOL_NAME, 4);
  124. }
  125. PUSH8(p, cli->protocol_version);
  126. PUSH8(p, conn_flags);
  127. PUSH16(p, cli->keepalive);
  128. PUSH16(p, cid_len);
  129. if (cid_len > 0) {
  130. PUSH_N(p, cli->client_id, cid_len);
  131. }
  132. if (conn_flags & MQTT_CONN_HAS_WILL) {
  133. PUSH16(p, will_topic_len);
  134. PUSH_N(p, cli->will->topic, will_topic_len);
  135. PUSH16(p, will_payload_len);
  136. PUSH_N(p, cli->will->payload, will_payload_len);
  137. }
  138. if (conn_flags & MQTT_CONN_HAS_USERNAME) {
  139. PUSH16(p, username_len);
  140. PUSH_N(p, cli->username, username_len);
  141. }
  142. if (conn_flags & MQTT_CONN_HAS_PASSWORD) {
  143. PUSH16(p, password_len);
  144. PUSH_N(p, cli->password, password_len);
  145. }
  146. int nwrite = mqtt_client_send(cli, buf, p - buf);
  147. HV_STACK_FREE(buf);
  148. return nwrite < 0 ? nwrite : 0;
  149. }
  150. static void reconnect_timer_cb(htimer_t* timer) {
  151. mqtt_client_t* cli = (mqtt_client_t*)hevent_userdata(timer);
  152. if (cli == NULL) return;
  153. cli->reconn_timer = NULL;
  154. mqtt_client_reconnect(cli);
  155. }
  156. static void on_close(hio_t* io) {
  157. mqtt_client_t* cli = (mqtt_client_t*)hevent_userdata(io);
  158. if (cli->cb) {
  159. cli->head.type = MQTT_TYPE_DISCONNECT;
  160. cli->cb(cli, cli->head.type);
  161. }
  162. // reconnect
  163. if (cli->reconn_setting && reconn_setting_can_retry(cli->reconn_setting)) {
  164. uint32_t delay = reconn_setting_calc_delay(cli->reconn_setting);
  165. cli->reconn_timer = htimer_add(cli->loop, reconnect_timer_cb, delay, 1);
  166. hevent_set_userdata(cli->reconn_timer, cli);
  167. }
  168. }
  169. static void on_packet(hio_t* io, void* buf, int len) {
  170. mqtt_client_t* cli = (mqtt_client_t*)hevent_userdata(io);
  171. unsigned char* p = (unsigned char*)buf;
  172. unsigned char* end = p + len;
  173. memset(&cli->head, 0, sizeof(mqtt_head_t));
  174. int headlen = mqtt_head_unpack(&cli->head, p, len);
  175. if (headlen <= 0) return;
  176. p += headlen;
  177. switch (cli->head.type) {
  178. // case MQTT_TYPE_CONNECT:
  179. case MQTT_TYPE_CONNACK:
  180. {
  181. if (cli->head.length < 2) {
  182. hloge("MQTT CONNACK malformed!");
  183. hio_close(io);
  184. return;
  185. }
  186. unsigned char conn_flags = 0, rc = 0;
  187. POP8(p, conn_flags);
  188. POP8(p, rc);
  189. if (rc != MQTT_CONNACK_ACCEPTED) {
  190. cli->error = rc;
  191. hloge("MQTT CONNACK error=%d", cli->error);
  192. hio_close(io);
  193. return;
  194. }
  195. if (cli->keepalive) {
  196. hio_set_heartbeat(io, cli->keepalive * 1000, mqtt_send_ping);
  197. }
  198. }
  199. break;
  200. case MQTT_TYPE_PUBLISH:
  201. {
  202. if (cli->head.length < 2) {
  203. hloge("MQTT PUBLISH malformed!");
  204. hio_close(io);
  205. return;
  206. }
  207. memset(&cli->message, 0, sizeof(mqtt_message_t));
  208. POP16(p, cli->message.topic_len);
  209. if (end - p < cli->message.topic_len) {
  210. hloge("MQTT PUBLISH malformed!");
  211. hio_close(io);
  212. return;
  213. }
  214. // NOTE: Not deep copy
  215. cli->message.topic = (char*)p;
  216. p += cli->message.topic_len;
  217. if (cli->head.qos > 0) {
  218. if (end - p < 2) {
  219. hloge("MQTT PUBLISH malformed!");
  220. hio_close(io);
  221. return;
  222. }
  223. POP16(p, cli->mid);
  224. }
  225. cli->message.payload_len = end - p;
  226. if (cli->message.payload_len > 0) {
  227. // NOTE: Not deep copy
  228. cli->message.payload = (char*)p;
  229. }
  230. cli->message.qos = cli->head.qos;
  231. if (cli->message.qos == 0) {
  232. // Do nothing
  233. } else if (cli->message.qos == 1) {
  234. mqtt_send_head_with_mid(io, MQTT_TYPE_PUBACK, cli->mid);
  235. } else if (cli->message.qos == 2) {
  236. mqtt_send_head_with_mid(io, MQTT_TYPE_PUBREC, cli->mid);
  237. }
  238. }
  239. break;
  240. case MQTT_TYPE_PUBACK:
  241. case MQTT_TYPE_PUBREC:
  242. case MQTT_TYPE_PUBREL:
  243. case MQTT_TYPE_PUBCOMP:
  244. {
  245. if (cli->head.length < 2) {
  246. hloge("MQTT PUBACK malformed!");
  247. hio_close(io);
  248. return;
  249. }
  250. POP16(p, cli->mid);
  251. if (cli->head.type == MQTT_TYPE_PUBREC) {
  252. mqtt_send_head_with_mid(io, MQTT_TYPE_PUBREL, cli->mid);
  253. } else if (cli->head.type == MQTT_TYPE_PUBREL) {
  254. mqtt_send_head_with_mid(io, MQTT_TYPE_PUBCOMP, cli->mid);
  255. }
  256. }
  257. break;
  258. // case MQTT_TYPE_SUBSCRIBE:
  259. // break;
  260. case MQTT_TYPE_SUBACK:
  261. {
  262. if (cli->head.length < 2) {
  263. hloge("MQTT SUBACK malformed!");
  264. hio_close(io);
  265. return;
  266. }
  267. POP16(p, cli->mid);
  268. }
  269. break;
  270. // case MQTT_TYPE_UNSUBSCRIBE:
  271. // break;
  272. case MQTT_TYPE_UNSUBACK:
  273. {
  274. if (cli->head.length < 2) {
  275. hloge("MQTT UNSUBACK malformed!");
  276. hio_close(io);
  277. return;
  278. }
  279. POP16(p, cli->mid);
  280. }
  281. break;
  282. case MQTT_TYPE_PINGREQ:
  283. mqtt_send_pong(io);
  284. return;
  285. case MQTT_TYPE_PINGRESP:
  286. return;
  287. case MQTT_TYPE_DISCONNECT:
  288. hio_close(io);
  289. return;
  290. default:
  291. hloge("MQTT client received wrong type=%d", (int)cli->head.type);
  292. hio_close(io);
  293. return;
  294. }
  295. if (cli->cb) {
  296. cli->cb(cli, cli->head.type);
  297. }
  298. }
  299. static void on_connect(hio_t* io) {
  300. mqtt_client_t* cli = (mqtt_client_t*)hevent_userdata(io);
  301. if (cli->cb) {
  302. cli->head.type = MQTT_TYPE_CONNECT;
  303. cli->cb(cli, cli->head.type);
  304. }
  305. if (cli->reconn_setting) {
  306. reconn_setting_reset(cli->reconn_setting);
  307. }
  308. static unpack_setting_t mqtt_unpack_setting;
  309. mqtt_unpack_setting.mode = UNPACK_BY_LENGTH_FIELD;
  310. mqtt_unpack_setting.package_max_length = DEFAULT_MQTT_PACKAGE_MAX_LENGTH;
  311. mqtt_unpack_setting.body_offset = 2;
  312. mqtt_unpack_setting.length_field_offset = 1;
  313. mqtt_unpack_setting.length_field_bytes = 1;
  314. mqtt_unpack_setting.length_field_coding = ENCODE_BY_VARINT;
  315. hio_set_unpack(io, &mqtt_unpack_setting);
  316. // start recv packet
  317. hio_setcb_read(io, on_packet);
  318. hio_read(io);
  319. mqtt_client_login(cli);
  320. }
  321. mqtt_client_t* mqtt_client_new(hloop_t* loop) {
  322. if (loop == NULL) {
  323. loop = hloop_new(HLOOP_FLAG_AUTO_FREE);
  324. if (loop == NULL) return NULL;
  325. }
  326. mqtt_client_t* cli = NULL;
  327. HV_ALLOC_SIZEOF(cli);
  328. if (cli == NULL) return NULL;
  329. cli->loop = loop;
  330. cli->protocol_version = MQTT_PROTOCOL_V311;
  331. cli->keepalive = DEFAULT_MQTT_KEEPALIVE;
  332. hmutex_init(&cli->mutex_);
  333. return cli;
  334. }
  335. void mqtt_client_free(mqtt_client_t* cli) {
  336. if (!cli) return;
  337. hmutex_destroy(&cli->mutex_);
  338. if (cli->reconn_timer) {
  339. htimer_del(cli->reconn_timer);
  340. cli->reconn_timer = NULL;
  341. }
  342. if (cli->ssl_ctx && cli->alloced_ssl_ctx) {
  343. hssl_ctx_free(cli->ssl_ctx);
  344. cli->ssl_ctx = NULL;
  345. }
  346. HV_FREE(cli->reconn_setting);
  347. HV_FREE(cli->will);
  348. HV_FREE(cli);
  349. }
  350. void mqtt_client_run (mqtt_client_t* cli) {
  351. if (!cli || !cli->loop) return;
  352. hloop_run(cli->loop);
  353. }
  354. void mqtt_client_stop(mqtt_client_t* cli) {
  355. if (!cli || !cli->loop) return;
  356. hloop_stop(cli->loop);
  357. }
  358. void mqtt_client_set_id(mqtt_client_t* cli, const char* id) {
  359. if (!cli || !id) return;
  360. hv_strncpy(cli->client_id, id, sizeof(cli->client_id));
  361. }
  362. void mqtt_client_set_will(mqtt_client_t* cli, mqtt_message_t* will) {
  363. if (!cli || !will) return;
  364. if (cli->will == NULL) {
  365. HV_ALLOC_SIZEOF(cli->will);
  366. }
  367. memcpy(cli->will, will, sizeof(mqtt_message_t));
  368. }
  369. void mqtt_client_set_auth(mqtt_client_t* cli, const char* username, const char* password) {
  370. if (!cli) return;
  371. if (username) {
  372. hv_strncpy(cli->username, username, sizeof(cli->username));
  373. }
  374. if (password) {
  375. hv_strncpy(cli->password, password, sizeof(cli->password));
  376. }
  377. }
  378. void mqtt_client_set_callback(mqtt_client_t* cli, mqtt_client_cb cb) {
  379. if (!cli) return;
  380. cli->cb = cb;
  381. }
  382. void mqtt_client_set_userdata(mqtt_client_t* cli, void* userdata) {
  383. if (!cli) return;
  384. cli->userdata = userdata;
  385. }
  386. void* mqtt_client_get_userdata(mqtt_client_t* cli) {
  387. if (!cli) return NULL;
  388. return cli->userdata;
  389. }
  390. int mqtt_client_get_last_error(mqtt_client_t* cli) {
  391. if (!cli) return -1;
  392. return cli->error;
  393. }
  394. int mqtt_client_set_ssl_ctx(mqtt_client_t* cli, hssl_ctx_t ssl_ctx) {
  395. cli->ssl_ctx = ssl_ctx;
  396. return 0;
  397. }
  398. int mqtt_client_new_ssl_ctx(mqtt_client_t* cli, hssl_ctx_opt_t* opt) {
  399. opt->endpoint = HSSL_CLIENT;
  400. hssl_ctx_t ssl_ctx = hssl_ctx_new(opt);
  401. if (ssl_ctx == NULL) return ERR_NEW_SSL_CTX;
  402. cli->alloced_ssl_ctx = true;
  403. return mqtt_client_set_ssl_ctx(cli, ssl_ctx);
  404. }
  405. int mqtt_client_set_reconnect(mqtt_client_t* cli, reconn_setting_t* reconn) {
  406. if (reconn == NULL) {
  407. HV_FREE(cli->reconn_setting);
  408. return 0;
  409. }
  410. if (cli->reconn_setting == NULL) {
  411. HV_ALLOC_SIZEOF(cli->reconn_setting);
  412. }
  413. *cli->reconn_setting = *reconn;
  414. return 0;
  415. }
  416. int mqtt_client_reconnect(mqtt_client_t* cli) {
  417. mqtt_client_connect(cli, cli->host, cli->port, cli->ssl);
  418. return 0;
  419. }
  420. int mqtt_client_connect(mqtt_client_t* cli, const char* host, int port, int ssl) {
  421. if (!cli) return -1;
  422. hv_strncpy(cli->host, host, sizeof(cli->host));
  423. cli->port = port;
  424. cli->ssl = ssl;
  425. hio_t* io = hio_create_socket(cli->loop, host, port, HIO_TYPE_TCP, HIO_CLIENT_SIDE);
  426. if (io == NULL) return -1;
  427. if (ssl) {
  428. if (cli->ssl_ctx) {
  429. hio_set_ssl_ctx(io, cli->ssl_ctx);
  430. }
  431. hio_enable_ssl(io);
  432. }
  433. cli->io = io;
  434. hevent_set_userdata(io, cli);
  435. hio_setcb_connect(io, on_connect);
  436. hio_setcb_close(io, on_close);
  437. return hio_connect(io);
  438. }
  439. int mqtt_client_disconnect(mqtt_client_t* cli) {
  440. if (!cli || !cli->io) return -1;
  441. // cancel reconnect first
  442. mqtt_client_set_reconnect(cli, NULL);
  443. mqtt_send_disconnect(cli->io);
  444. return hio_close(cli->io);
  445. }
  446. int mqtt_client_publish(mqtt_client_t* cli, mqtt_message_t* msg) {
  447. if (!cli || !cli->io || !msg) return -1;
  448. int topic_len = msg->topic_len ? msg->topic_len : strlen(msg->topic);
  449. int payload_len = msg->payload_len ? msg->payload_len : strlen(msg->payload);
  450. int len = 2 + topic_len + payload_len;
  451. if (msg->qos > 0) len += 2; // mid
  452. unsigned short mid = 0;
  453. mqtt_head_t head;
  454. memset(&head, 0, sizeof(head));
  455. head.type = MQTT_TYPE_PUBLISH;
  456. head.qos = msg->qos & 3;
  457. head.retain = msg->retain;
  458. head.length = len;
  459. int buflen = mqtt_estimate_length(&head);
  460. // NOTE: send payload alone
  461. buflen -= payload_len;
  462. unsigned char* buf = NULL;
  463. HV_STACK_ALLOC(buf, buflen);
  464. unsigned char* p = buf;
  465. int headlen = mqtt_head_pack(&head, p);
  466. p += headlen;
  467. PUSH16(p, topic_len);
  468. PUSH_N(p, msg->topic, topic_len);
  469. if (msg->qos) {
  470. mid = mqtt_next_mid();
  471. PUSH16(p, mid);
  472. }
  473. hmutex_lock(&cli->mutex_);
  474. // send head + topic + mid
  475. int nwrite = hio_write(cli->io, buf, p - buf);
  476. HV_STACK_FREE(buf);
  477. if (nwrite < 0) {
  478. goto unlock;
  479. }
  480. // send payload
  481. nwrite = hio_write(cli->io, msg->payload, payload_len);
  482. unlock:
  483. hmutex_unlock(&cli->mutex_);
  484. return nwrite < 0 ? nwrite : mid;
  485. }
  486. int mqtt_client_subscribe(mqtt_client_t* cli, const char* topic, int qos) {
  487. if (!cli || !cli->io || !topic) return -1;
  488. int topic_len = strlen(topic);
  489. int len = 2 + 2 + topic_len + 1;
  490. mqtt_head_t head;
  491. memset(&head, 0, sizeof(head));
  492. head.type = MQTT_TYPE_SUBSCRIBE;
  493. head.qos = 1;
  494. head.length = len;
  495. int buflen = mqtt_estimate_length(&head);
  496. unsigned char* buf = NULL;
  497. HV_STACK_ALLOC(buf, buflen);
  498. unsigned char* p = buf;
  499. int headlen = mqtt_head_pack(&head, p);
  500. p += headlen;
  501. unsigned short mid = mqtt_next_mid();
  502. PUSH16(p, mid);
  503. PUSH16(p, topic_len);
  504. PUSH_N(p, topic, topic_len);
  505. PUSH8(p, qos & 3);
  506. // send head + mid + topic + qos
  507. int nwrite = mqtt_client_send(cli, buf, p - buf);
  508. HV_STACK_FREE(buf);
  509. return nwrite < 0 ? nwrite : mid;
  510. }
  511. int mqtt_client_unsubscribe(mqtt_client_t* cli, const char* topic) {
  512. if (!cli || !cli->io || !topic) return -1;
  513. int topic_len = strlen(topic);
  514. int len = 2 + 2 + topic_len;
  515. mqtt_head_t head;
  516. memset(&head, 0, sizeof(head));
  517. head.type = MQTT_TYPE_UNSUBSCRIBE;
  518. head.qos = 1;
  519. head.length = len;
  520. int buflen = mqtt_estimate_length(&head);
  521. unsigned char* buf = NULL;
  522. HV_STACK_ALLOC(buf, buflen);
  523. unsigned char* p = buf;
  524. int headlen = mqtt_head_pack(&head, p);
  525. p += headlen;
  526. unsigned short mid = mqtt_next_mid();
  527. PUSH16(p, mid);
  528. PUSH16(p, topic_len);
  529. PUSH_N(p, topic, topic_len);
  530. // send head + mid + topic
  531. int nwrite = mqtt_client_send(cli, buf, p - buf);
  532. HV_STACK_FREE(buf);
  533. return nwrite < 0 ? nwrite : mid;
  534. }