mqtt_client.c 16 KB

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