mqtt_client.c 17 KB

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