paho_c_pub.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. /*******************************************************************************
  2. * Copyright (c) 2012, 2018 IBM Corp., and others
  3. *
  4. * All rights reserved. This program and the accompanying materials
  5. * are made available under the terms of the Eclipse Public License v1.0
  6. * and Eclipse Distribution License v1.0 which accompany this distribution.
  7. *
  8. * The Eclipse Public License is available at
  9. * http://www.eclipse.org/legal/epl-v10.html
  10. * and the Eclipse Distribution License is available at
  11. * http://www.eclipse.org/org/documents/edl-v10.php.
  12. *
  13. * Contributors:
  14. * Ian Craggs - initial contribution
  15. * Guilherme Maciel Ferreira - add keep alive option
  16. * Ian Craggs - add full capability
  17. *******************************************************************************/
  18. #include "MQTTAsync.h"
  19. #include "pubsub_opts.h"
  20. #include <stdio.h>
  21. #include <signal.h>
  22. #include <string.h>
  23. #include <stdlib.h>
  24. #if defined(WIN32)
  25. #include <windows.h>
  26. #define sleep Sleep
  27. #else
  28. #include <unistd.h>
  29. #include <sys/time.h>
  30. #include <unistd.h>
  31. #endif
  32. #if defined(_WRS_KERNEL)
  33. #include <OsWrapper.h>
  34. #endif
  35. volatile int toStop = 0;
  36. struct pubsub_opts opts =
  37. {
  38. 1, 0, 0, 0, "\n", 100, /* debug/app options */
  39. NULL, NULL, 1, 0, 0, /* message options */
  40. MQTTVERSION_DEFAULT, NULL, "paho-c-pub", 0, 0, NULL, NULL, "localhost", "1883", NULL, 10, /* MQTT options */
  41. NULL, NULL, 0, 0, /* will options */
  42. 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* TLS options */
  43. 0, {NULL, NULL}, /* MQTT V5 options */
  44. };
  45. MQTTAsync_responseOptions pub_opts = MQTTAsync_responseOptions_initializer;
  46. MQTTProperty property;
  47. MQTTProperties props = MQTTProperties_initializer;
  48. void mysleep(int ms)
  49. {
  50. #if defined(WIN32)
  51. Sleep(ms);
  52. #else
  53. usleep(ms * 1000);
  54. #endif
  55. }
  56. void cfinish(int sig)
  57. {
  58. signal(SIGINT, NULL);
  59. toStop = 1;
  60. }
  61. int messageArrived(void* context, char* topicName, int topicLen, MQTTAsync_message* m)
  62. {
  63. /* not expecting any messages */
  64. return 1;
  65. }
  66. static int disconnected = 0;
  67. void onDisconnect5(void* context, MQTTAsync_successData5* response)
  68. {
  69. disconnected = 1;
  70. }
  71. void onDisconnect(void* context, MQTTAsync_successData* response)
  72. {
  73. disconnected = 1;
  74. }
  75. static int connected = 0;
  76. void myconnect(MQTTAsync client);
  77. int mypublish(MQTTAsync client, int datalen, char* data);
  78. void onConnectFailure5(void* context, MQTTAsync_failureData5* response)
  79. {
  80. fprintf(stderr, "Connect failed, rc %s reason code %s\n",
  81. MQTTAsync_strerror(response->code),
  82. MQTTReasonCode_toString(response->reasonCode));
  83. connected = -1;
  84. MQTTAsync client = (MQTTAsync)context;
  85. }
  86. void onConnectFailure(void* context, MQTTAsync_failureData* response)
  87. {
  88. fprintf(stderr, "Connect failed, rc %s\n", response ? MQTTAsync_strerror(response->code) : "none");
  89. connected = -1;
  90. MQTTAsync client = (MQTTAsync)context;
  91. }
  92. void onConnect5(void* context, MQTTAsync_successData5* response)
  93. {
  94. MQTTAsync client = (MQTTAsync)context;
  95. int rc = 0;
  96. if (opts.verbose)
  97. printf("Connected\n");
  98. if (opts.null_message == 1)
  99. rc = mypublish(client, 0, "");
  100. else if (opts.message)
  101. rc = mypublish(client, (int)strlen(opts.message), opts.message);
  102. else if (opts.filename)
  103. {
  104. int data_len = 0;
  105. char* buffer = readfile(&data_len, &opts);
  106. if (buffer == NULL)
  107. toStop = 1;
  108. else
  109. {
  110. rc = mypublish(client, data_len, buffer);
  111. free(buffer);
  112. }
  113. }
  114. connected = 1;
  115. }
  116. void onConnect(void* context, MQTTAsync_successData* response)
  117. {
  118. MQTTAsync client = (MQTTAsync)context;
  119. int rc = 0;
  120. if (opts.verbose)
  121. printf("Connected\n");
  122. if (opts.null_message == 1)
  123. rc = mypublish(client, 0, "");
  124. else if (opts.message)
  125. rc = mypublish(client, (int)strlen(opts.message), opts.message);
  126. else if (opts.filename)
  127. {
  128. int data_len = 0;
  129. char* buffer = readfile(&data_len, &opts);
  130. if (buffer == NULL)
  131. toStop = 1;
  132. else
  133. {
  134. rc = mypublish(client, data_len, buffer);
  135. free(buffer);
  136. }
  137. }
  138. connected = 1;
  139. }
  140. static int published = 0;
  141. void onPublishFailure5(void* context, MQTTAsync_failureData5* response)
  142. {
  143. if (opts.verbose)
  144. fprintf(stderr, "Publish failed, rc %s reason code %s\n",
  145. MQTTAsync_strerror(response->code),
  146. MQTTReasonCode_toString(response->reasonCode));
  147. published = -1;
  148. }
  149. void onPublishFailure(void* context, MQTTAsync_failureData* response)
  150. {
  151. if (opts.verbose)
  152. fprintf(stderr, "Publish failed, rc %s\n", MQTTAsync_strerror(response->code));
  153. published = -1;
  154. }
  155. void onPublish5(void* context, MQTTAsync_successData5* response)
  156. {
  157. if (opts.verbose)
  158. printf("Publish succeeded, reason code %s\n",
  159. MQTTReasonCode_toString(response->reasonCode));
  160. if (opts.null_message || opts.message || opts.filename)
  161. toStop = 1;
  162. published = 1;
  163. }
  164. void onPublish(void* context, MQTTAsync_successData* response)
  165. {
  166. if (opts.verbose)
  167. printf("Publish succeeded\n");
  168. if (opts.null_message || opts.message || opts.filename)
  169. toStop = 1;
  170. published = 1;
  171. }
  172. static int onSSLError(const char *str, size_t len, void *context)
  173. {
  174. MQTTAsync client = (MQTTAsync)context;
  175. return fprintf(stderr, "SSL error: %s\n", str);
  176. }
  177. static unsigned int onPSKAuth(const char* hint,
  178. char* identity,
  179. unsigned int max_identity_len,
  180. unsigned char* psk,
  181. unsigned int max_psk_len,
  182. void* context)
  183. {
  184. int psk_len;
  185. int k, n;
  186. int rc = 0;
  187. struct pubsub_opts* opts = context;
  188. printf("Trying TLS-PSK auth with hint: %s\n", hint);
  189. if (opts->psk == NULL || opts->psk_identity == NULL)
  190. {
  191. printf("No PSK entered\n");
  192. goto exit;
  193. }
  194. /* psk should be array of bytes. This is a quick and dirty way to
  195. * convert hex to bytes without input validation */
  196. psk_len = strlen(opts->psk) / 2;
  197. if (psk_len > max_psk_len)
  198. {
  199. printf("PSK too long\n");
  200. goto exit;
  201. }
  202. for (k=0, n=0; k < psk_len; k++, n += 2)
  203. {
  204. sscanf(&opts->psk[n], "%2hhx", &psk[k]);
  205. }
  206. /* identity should be NULL terminated string */
  207. strncpy(identity, opts->psk_identity, max_identity_len);
  208. if (identity[max_identity_len - 1] != '\0')
  209. {
  210. printf("Identity too long\n");
  211. goto exit;
  212. }
  213. /* Function should return length of psk on success. */
  214. rc = psk_len;
  215. exit:
  216. return rc;
  217. }
  218. void myconnect(MQTTAsync client)
  219. {
  220. MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
  221. MQTTAsync_SSLOptions ssl_opts = MQTTAsync_SSLOptions_initializer;
  222. MQTTAsync_willOptions will_opts = MQTTAsync_willOptions_initializer;
  223. int rc = 0;
  224. if (opts.verbose)
  225. printf("Connecting\n");
  226. if (opts.MQTTVersion == MQTTVERSION_5)
  227. {
  228. MQTTAsync_connectOptions conn_opts5 = MQTTAsync_connectOptions_initializer5;
  229. conn_opts = conn_opts5;
  230. conn_opts.onSuccess5 = onConnect5;
  231. conn_opts.onFailure5 = onConnectFailure5;
  232. conn_opts.cleanstart = 1;
  233. }
  234. else
  235. {
  236. conn_opts.onSuccess = onConnect;
  237. conn_opts.onFailure = onConnectFailure;
  238. conn_opts.cleansession = 1;
  239. }
  240. conn_opts.keepAliveInterval = opts.keepalive;
  241. conn_opts.username = opts.username;
  242. conn_opts.password = opts.password;
  243. conn_opts.MQTTVersion = opts.MQTTVersion;
  244. conn_opts.context = client;
  245. conn_opts.automaticReconnect = 1;
  246. if (opts.will_topic) /* will options */
  247. {
  248. will_opts.message = opts.will_payload;
  249. will_opts.topicName = opts.will_topic;
  250. will_opts.qos = opts.will_qos;
  251. will_opts.retained = opts.will_retain;
  252. conn_opts.will = &will_opts;
  253. }
  254. if (opts.connection && (strncmp(opts.connection, "ssl://", 6) == 0 ||
  255. strncmp(opts.connection, "wss://", 6) == 0))
  256. {
  257. if (opts.insecure)
  258. ssl_opts.verify = 0;
  259. else
  260. ssl_opts.verify = 1;
  261. ssl_opts.CApath = opts.capath;
  262. ssl_opts.keyStore = opts.cert;
  263. ssl_opts.trustStore = opts.cafile;
  264. ssl_opts.privateKey = opts.key;
  265. ssl_opts.privateKeyPassword = opts.keypass;
  266. ssl_opts.enabledCipherSuites = opts.ciphers;
  267. ssl_opts.ssl_error_cb = onSSLError;
  268. ssl_opts.ssl_error_context = client;
  269. ssl_opts.ssl_psk_cb = onPSKAuth;
  270. ssl_opts.ssl_psk_context = &opts;
  271. conn_opts.ssl = &ssl_opts;
  272. }
  273. connected = 0;
  274. if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
  275. {
  276. fprintf(stderr, "Failed to start connect, return code %s\n", MQTTAsync_strerror(rc));
  277. exit(EXIT_FAILURE);
  278. }
  279. }
  280. int mypublish(MQTTAsync client, int datalen, char* data)
  281. {
  282. int rc;
  283. if (opts.verbose)
  284. printf("Publishing data of length %d\n", datalen);
  285. rc = MQTTAsync_send(client, opts.topic, datalen, data, opts.qos, opts.retained, &pub_opts);
  286. if (opts.verbose && rc != MQTTASYNC_SUCCESS && !opts.quiet)
  287. fprintf(stderr, "Error from MQTTAsync_send: %s\n", MQTTAsync_strerror(rc));
  288. return rc;
  289. }
  290. void trace_callback(enum MQTTASYNC_TRACE_LEVELS level, char* message)
  291. {
  292. fprintf(stderr, "Trace : %d, %s\n", level, message);
  293. }
  294. int main(int argc, char** argv)
  295. {
  296. MQTTAsync_disconnectOptions disc_opts = MQTTAsync_disconnectOptions_initializer;
  297. MQTTAsync_createOptions create_opts = MQTTAsync_createOptions_initializer;
  298. MQTTAsync client;
  299. char* buffer = NULL;
  300. char* url = NULL;
  301. int rc = 0;
  302. const char* version = NULL;
  303. const char* program_name = "paho_c_pub";
  304. MQTTAsync_nameValue* infos = MQTTAsync_getVersionInfo();
  305. #if !defined(WIN32)
  306. struct sigaction sa;
  307. #endif
  308. if (argc < 2)
  309. usage(&opts, (pubsub_opts_nameValue*)infos, program_name);
  310. if (getopts(argc, argv, &opts) != 0)
  311. usage(&opts, (pubsub_opts_nameValue*)infos, program_name);
  312. if (opts.connection)
  313. url = opts.connection;
  314. else
  315. {
  316. url = malloc(100);
  317. sprintf(url, "%s:%s", opts.host, opts.port);
  318. }
  319. if (opts.verbose)
  320. printf("URL is %s\n", url);
  321. if (opts.tracelevel > 0)
  322. {
  323. MQTTAsync_setTraceCallback(trace_callback);
  324. MQTTAsync_setTraceLevel(opts.tracelevel);
  325. }
  326. create_opts.sendWhileDisconnected = 1;
  327. if (opts.MQTTVersion >= MQTTVERSION_5)
  328. create_opts.MQTTVersion = MQTTVERSION_5;
  329. rc = MQTTAsync_createWithOptions(&client, url, opts.clientid, MQTTCLIENT_PERSISTENCE_NONE, NULL, &create_opts);
  330. if (rc != MQTTASYNC_SUCCESS)
  331. {
  332. if (!opts.quiet)
  333. fprintf(stderr, "Failed to create client, return code: %s\n", MQTTAsync_strerror(rc));
  334. exit(EXIT_FAILURE);
  335. }
  336. #if defined(WIN32)
  337. signal(SIGINT, cfinish);
  338. signal(SIGTERM, cfinish);
  339. #else
  340. memset(&sa, 0, sizeof(struct sigaction));
  341. sa.sa_handler = cfinish;
  342. sa.sa_flags = 0;
  343. sigaction(SIGINT, &sa, NULL);
  344. sigaction(SIGTERM, &sa, NULL);
  345. #endif
  346. rc = MQTTAsync_setCallbacks(client, client, NULL, messageArrived, NULL);
  347. if (rc != MQTTASYNC_SUCCESS)
  348. {
  349. if (!opts.quiet)
  350. fprintf(stderr, "Failed to set callbacks, return code: %s\n", MQTTAsync_strerror(rc));
  351. exit(EXIT_FAILURE);
  352. }
  353. if (opts.MQTTVersion >= MQTTVERSION_5)
  354. {
  355. pub_opts.onSuccess5 = onPublish5;
  356. pub_opts.onFailure5 = onPublishFailure5;
  357. if (opts.message_expiry > 0)
  358. {
  359. property.identifier = MQTTPROPERTY_CODE_MESSAGE_EXPIRY_INTERVAL;
  360. property.value.integer4 = opts.message_expiry;
  361. MQTTProperties_add(&props, &property);
  362. }
  363. if (opts.user_property.name)
  364. {
  365. property.identifier = MQTTPROPERTY_CODE_USER_PROPERTY;
  366. property.value.data.data = opts.user_property.name;
  367. property.value.data.len = (int)strlen(opts.user_property.name);
  368. property.value.value.data = opts.user_property.value;
  369. property.value.value.len = (int)strlen(opts.user_property.value);
  370. MQTTProperties_add(&props, &property);
  371. }
  372. pub_opts.properties = props;
  373. }
  374. else
  375. {
  376. pub_opts.onSuccess = onPublish;
  377. pub_opts.onFailure = onPublishFailure;
  378. }
  379. myconnect(client);
  380. while (!toStop)
  381. {
  382. int data_len = 0;
  383. int delim_len = 0;
  384. if (opts.stdin_lines)
  385. {
  386. buffer = malloc(opts.maxdatalen);
  387. delim_len = (int)strlen(opts.delimiter);
  388. do
  389. {
  390. buffer[data_len++] = getchar();
  391. if (data_len > delim_len)
  392. {
  393. if (strncmp(opts.delimiter, &buffer[data_len - delim_len], delim_len) == 0)
  394. break;
  395. }
  396. } while (data_len < opts.maxdatalen);
  397. rc = mypublish(client, data_len, buffer);
  398. }
  399. else
  400. mysleep(100);
  401. }
  402. if (opts.message == 0 && opts.null_message == 0 && opts.filename == 0)
  403. free(buffer);
  404. if (opts.MQTTVersion >= MQTTVERSION_5)
  405. disc_opts.onSuccess5 = onDisconnect5;
  406. else
  407. disc_opts.onSuccess = onDisconnect;
  408. if ((rc = MQTTAsync_disconnect(client, &disc_opts)) != MQTTASYNC_SUCCESS)
  409. {
  410. if (!opts.quiet)
  411. fprintf(stderr, "Failed to start disconnect, return code: %s\n", MQTTAsync_strerror(rc));
  412. exit(EXIT_FAILURE);
  413. }
  414. while (!disconnected)
  415. mysleep(100);
  416. MQTTAsync_destroy(&client);
  417. return EXIT_SUCCESS;
  418. }