mqtt_client.c 16 KB

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