PageRenderTime 55ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/client/sub_client.c

https://bitbucket.org/klkucan/mosqnet
C | 558 lines | 497 code | 30 blank | 31 comment | 132 complexity | 6ba2f6e58997d4b106de33434ea2ddd3 MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause
  1. /*
  2. Copyright (c) 2009-2012 Roger Light <roger@atchoo.org>
  3. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are met:
  6. 1. Redistributions of source code must retain the above copyright notice,
  7. this list of conditions and the following disclaimer.
  8. 2. Redistributions in binary form must reproduce the above copyright
  9. notice, this list of conditions and the following disclaimer in the
  10. documentation and/or other materials provided with the distribution.
  11. 3. Neither the name of mosquitto nor the names of its
  12. contributors may be used to endorse or promote products derived from
  13. this software without specific prior written permission.
  14. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  15. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  16. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  17. ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  18. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  19. CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  20. SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  21. INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  22. CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  23. ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  24. POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <assert.h>
  27. #include <errno.h>
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #ifndef WIN32
  32. #include <unistd.h>
  33. #else
  34. #include <process.h>
  35. #include <winsock2.h>
  36. #define snprintf sprintf_s
  37. #endif
  38. #include <mosquitto.h>
  39. /* This struct is used to pass data to callbacks.
  40. * An instance "ud" is created in main() and populated, then passed to
  41. * mosquitto_new(). */
  42. struct userdata {
  43. char **topics;
  44. int topic_count;
  45. int topic_qos;
  46. char *username;
  47. char *password;
  48. int verbose;
  49. bool quiet;
  50. };
  51. void my_message_callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message)
  52. {
  53. struct userdata *ud;
  54. assert(obj);
  55. ud = (struct userdata *)obj;
  56. if(ud->verbose){
  57. if(message->payloadlen){
  58. printf("%s %s\n", message->topic, (const char *)message->payload);
  59. }else{
  60. printf("%s (null)\n", message->topic);
  61. }
  62. fflush(stdout);
  63. }else{
  64. if(message->payloadlen){
  65. printf("%s\n", (const char *)message->payload);
  66. fflush(stdout);
  67. }
  68. }
  69. }
  70. void my_connect_callback(struct mosquitto *mosq, void *obj, int result)
  71. {
  72. int i;
  73. struct userdata *ud;
  74. assert(obj);
  75. ud = (struct userdata *)obj;
  76. if(!result){
  77. for(i=0; i<ud->topic_count; i++){
  78. mosquitto_subscribe(mosq, NULL, ud->topics[i], ud->topic_qos);
  79. }
  80. }else{
  81. if(result && !ud->quiet){
  82. fprintf(stderr, "%s\n", mosquitto_connack_string(result));
  83. }
  84. }
  85. }
  86. void my_subscribe_callback(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos)
  87. {
  88. int i;
  89. struct userdata *ud;
  90. assert(obj);
  91. ud = (struct userdata *)obj;
  92. if(!ud->quiet) printf("Subscribed (mid: %d): %d", mid, granted_qos[0]);
  93. for(i=1; i<qos_count; i++){
  94. if(!ud->quiet) printf(", %d", granted_qos[i]);
  95. }
  96. if(!ud->quiet) printf("\n");
  97. }
  98. void my_log_callback(struct mosquitto *mosq, void *obj, int level, const char *str)
  99. {
  100. printf("%s\n", str);
  101. }
  102. void print_usage(void)
  103. {
  104. printf("mosquitto_sub is a simple mqtt client that will subscribe to a single topic and print all messages it receives.\n\n");
  105. printf("Usage: mosquitto_sub [-c] [-h host] [-k keepalive] [-p port] [-q qos] [-v] -t topic ...\n");
  106. printf(" [-i id] [-I id_prefix]\n");
  107. printf(" [-d] [--quiet]\n");
  108. printf(" [-u username [-P password]]\n");
  109. printf(" [--will-topic [--will-payload payload] [--will-qos qos] [--will-retain]]\n");
  110. #ifdef WITH_TLS
  111. printf(" [{--cafile file | --capath dir} [--cert file] [--key file]]\n");
  112. #ifdef WITH_TLS_PSK
  113. printf(" [--psk hex-key --psk-identity identity]\n");
  114. #endif
  115. #endif
  116. printf(" mosquitto_sub --help\n\n");
  117. printf(" -c : disable 'clean session' (store subscription and pending messages when client disconnects).\n");
  118. printf(" -d : enable debug messages.\n");
  119. printf(" -h : mqtt host to connect to. Defaults to localhost.\n");
  120. printf(" -i : id to use for this client. Defaults to mosquitto_sub_ appended with the process id.\n");
  121. printf(" -I : define the client id as id_prefix appended with the process id. Useful for when the\n");
  122. printf(" broker is using the clientid_prefixes option.\n");
  123. printf(" -k : keep alive in seconds for this client. Defaults to 60.\n");
  124. printf(" -p : network port to connect to. Defaults to 1883.\n");
  125. printf(" -q : quality of service level to use for the subscription. Defaults to 0.\n");
  126. printf(" -t : mqtt topic to subscribe to. May be repeated multiple times.\n");
  127. printf(" -u : provide a username (requires MQTT 3.1 broker)\n");
  128. printf(" -v : print published messages verbosely.\n");
  129. printf(" -P : provide a password (requires MQTT 3.1 broker)\n");
  130. printf(" --help : display this message.\n");
  131. printf(" --quiet : don't print error messages.\n");
  132. printf(" --will-payload : payload for the client Will, which is sent by the broker in case of\n");
  133. printf(" unexpected disconnection. If not given and will-topic is set, a zero\n");
  134. printf(" length message will be sent.\n");
  135. printf(" --will-qos : QoS level for the client Will.\n");
  136. printf(" --will-retain : if given, make the client Will retained.\n");
  137. printf(" --will-topic : the topic on which to publish the client Will.\n");
  138. #ifdef WITH_TLS
  139. printf(" --cafile : path to a file containing trusted CA certificates to enable encrypted\n");
  140. printf(" certificate based communication.\n");
  141. printf(" --capath : path to a directory containing trusted CA certificates to enable encrypted\n");
  142. printf(" communication.\n");
  143. printf(" --cert : client certificate for authentication, if required by server.\n");
  144. printf(" --key : client private key for authentication, if required by server.\n");
  145. #ifdef WITH_TLS_PSK
  146. printf(" --psk : pre-shared-key in hexadecimal (no leading 0x) to enable TLS-PSK mode.\n");
  147. printf(" --psk-identity : client identity string for TLS-PSK mode.\n");
  148. #endif
  149. #endif
  150. printf("\nSee http://mosquitto.org/ for more information.\n\n");
  151. }
  152. int main(int argc, char *argv[])
  153. {
  154. char *id = NULL;
  155. char *id_prefix = NULL;
  156. int i;
  157. char *host = "localhost";
  158. int port = 1883;
  159. int keepalive = 60;
  160. bool clean_session = true;
  161. bool debug = false;
  162. struct mosquitto *mosq = NULL;
  163. int rc;
  164. char hostname[256];
  165. char err[1024];
  166. struct userdata ud;
  167. int len;
  168. char *will_payload = NULL;
  169. long will_payloadlen = 0;
  170. int will_qos = 0;
  171. bool will_retain = false;
  172. char *will_topic = NULL;
  173. char *cafile = NULL;
  174. char *capath = NULL;
  175. char *certfile = NULL;
  176. char *keyfile = NULL;
  177. char *psk = NULL;
  178. char *psk_identity = NULL;
  179. memset(&ud, 0, sizeof(struct userdata));
  180. for(i=1; i<argc; i++){
  181. if(!strcmp(argv[i], "-p") || !strcmp(argv[i], "--port")){
  182. if(i==argc-1){
  183. fprintf(stderr, "Error: -p argument given but no port specified.\n\n");
  184. print_usage();
  185. return 1;
  186. }else{
  187. port = atoi(argv[i+1]);
  188. if(port<1 || port>65535){
  189. fprintf(stderr, "Error: Invalid port given: %d\n", port);
  190. print_usage();
  191. return 1;
  192. }
  193. }
  194. i++;
  195. }else if(!strcmp(argv[i], "-c") || !strcmp(argv[i], "--disable-clean-session")){
  196. clean_session = false;
  197. }else if(!strcmp(argv[i], "--cafile")){
  198. if(i==argc-1){
  199. fprintf(stderr, "Error: --cafile argument given but no file specified.\n\n");
  200. print_usage();
  201. return 1;
  202. }else{
  203. cafile = argv[i+1];
  204. }
  205. i++;
  206. }else if(!strcmp(argv[i], "--capath")){
  207. if(i==argc-1){
  208. fprintf(stderr, "Error: --capath argument given but no directory specified.\n\n");
  209. print_usage();
  210. return 1;
  211. }else{
  212. capath = argv[i+1];
  213. }
  214. i++;
  215. }else if(!strcmp(argv[i], "--cert")){
  216. if(i==argc-1){
  217. fprintf(stderr, "Error: --cert argument given but no file specified.\n\n");
  218. print_usage();
  219. return 1;
  220. }else{
  221. certfile = argv[i+1];
  222. }
  223. i++;
  224. }else if(!strcmp(argv[i], "-d") || !strcmp(argv[i], "--debug")){
  225. debug = true;
  226. }else if(!strcmp(argv[i], "--help")){
  227. print_usage();
  228. return 0;
  229. }else if(!strcmp(argv[i], "-h") || !strcmp(argv[i], "--host")){
  230. if(i==argc-1){
  231. fprintf(stderr, "Error: -h argument given but no host specified.\n\n");
  232. print_usage();
  233. return 1;
  234. }else{
  235. host = argv[i+1];
  236. }
  237. i++;
  238. }else if(!strcmp(argv[i], "-i") || !strcmp(argv[i], "--id")){
  239. if(id_prefix){
  240. fprintf(stderr, "Error: -i and -I argument cannot be used together.\n\n");
  241. print_usage();
  242. return 1;
  243. }
  244. if(i==argc-1){
  245. fprintf(stderr, "Error: -i argument given but no id specified.\n\n");
  246. print_usage();
  247. return 1;
  248. }else{
  249. id = argv[i+1];
  250. }
  251. i++;
  252. }else if(!strcmp(argv[i], "-I") || !strcmp(argv[i], "--id-prefix")){
  253. if(id){
  254. fprintf(stderr, "Error: -i and -I argument cannot be used together.\n\n");
  255. print_usage();
  256. return 1;
  257. }
  258. if(i==argc-1){
  259. fprintf(stderr, "Error: -I argument given but no id prefix specified.\n\n");
  260. print_usage();
  261. return 1;
  262. }else{
  263. id_prefix = argv[i+1];
  264. }
  265. i++;
  266. }else if(!strcmp(argv[i], "-k") || !strcmp(argv[i], "--keepalive")){
  267. if(i==argc-1){
  268. fprintf(stderr, "Error: -k argument given but no keepalive specified.\n\n");
  269. print_usage();
  270. return 1;
  271. }else{
  272. keepalive = atoi(argv[i+1]);
  273. if(keepalive>65535){
  274. fprintf(stderr, "Error: Invalid keepalive given: %d\n", keepalive);
  275. print_usage();
  276. return 1;
  277. }
  278. }
  279. i++;
  280. }else if(!strcmp(argv[i], "--key")){
  281. if(i==argc-1){
  282. fprintf(stderr, "Error: --key argument given but no file specified.\n\n");
  283. print_usage();
  284. return 1;
  285. }else{
  286. keyfile = argv[i+1];
  287. }
  288. i++;
  289. }else if(!strcmp(argv[i], "--psk")){
  290. if(i==argc-1){
  291. fprintf(stderr, "Error: --psk argument given but no key specified.\n\n");
  292. print_usage();
  293. return 1;
  294. }else{
  295. psk = argv[i+1];
  296. }
  297. i++;
  298. }else if(!strcmp(argv[i], "--psk-identity")){
  299. if(i==argc-1){
  300. fprintf(stderr, "Error: --psk-identity argument given but no identity specified.\n\n");
  301. print_usage();
  302. return 1;
  303. }else{
  304. psk_identity = argv[i+1];
  305. }
  306. i++;
  307. }else if(!strcmp(argv[i], "-q") || !strcmp(argv[i], "--qos")){
  308. if(i==argc-1){
  309. fprintf(stderr, "Error: -q argument given but no QoS specified.\n\n");
  310. print_usage();
  311. return 1;
  312. }else{
  313. ud.topic_qos = atoi(argv[i+1]);
  314. if(ud.topic_qos<0 || ud.topic_qos>2){
  315. fprintf(stderr, "Error: Invalid QoS given: %d\n", ud.topic_qos);
  316. print_usage();
  317. return 1;
  318. }
  319. }
  320. i++;
  321. }else if(!strcmp(argv[i], "--quiet")){
  322. ud.quiet = true;
  323. }else if(!strcmp(argv[i], "-t") || !strcmp(argv[i], "--topic")){
  324. if(i==argc-1){
  325. fprintf(stderr, "Error: -t argument given but no topic specified.\n\n");
  326. print_usage();
  327. return 1;
  328. }else{
  329. ud.topic_count++;
  330. ud.topics = realloc(ud.topics, ud.topic_count*sizeof(char *));
  331. ud.topics[ud.topic_count-1] = argv[i+1];
  332. }
  333. i++;
  334. }else if(!strcmp(argv[i], "-u") || !strcmp(argv[i], "--username")){
  335. if(i==argc-1){
  336. fprintf(stderr, "Error: -u argument given but no username specified.\n\n");
  337. print_usage();
  338. return 1;
  339. }else{
  340. ud.username = argv[i+1];
  341. }
  342. i++;
  343. }else if(!strcmp(argv[i], "-v") || !strcmp(argv[i], "--verbose")){
  344. ud.verbose = 1;
  345. }else if(!strcmp(argv[i], "-P") || !strcmp(argv[i], "--pw")){
  346. if(i==argc-1){
  347. fprintf(stderr, "Error: -P argument given but no password specified.\n\n");
  348. print_usage();
  349. return 1;
  350. }else{
  351. ud.password = argv[i+1];
  352. }
  353. i++;
  354. }else if(!strcmp(argv[i], "--will-payload")){
  355. if(i==argc-1){
  356. fprintf(stderr, "Error: --will-payload argument given but no will payload specified.\n\n");
  357. print_usage();
  358. return 1;
  359. }else{
  360. will_payload = argv[i+1];
  361. will_payloadlen = strlen(will_payload);
  362. }
  363. i++;
  364. }else if(!strcmp(argv[i], "--will-qos")){
  365. if(i==argc-1){
  366. fprintf(stderr, "Error: --will-qos argument given but no will QoS specified.\n\n");
  367. print_usage();
  368. return 1;
  369. }else{
  370. will_qos = atoi(argv[i+1]);
  371. if(will_qos < 0 || will_qos > 2){
  372. fprintf(stderr, "Error: Invalid will QoS %d.\n\n", will_qos);
  373. return 1;
  374. }
  375. }
  376. i++;
  377. }else if(!strcmp(argv[i], "--will-retain")){
  378. will_retain = true;
  379. }else if(!strcmp(argv[i], "--will-topic")){
  380. if(i==argc-1){
  381. fprintf(stderr, "Error: --will-topic argument given but no will topic specified.\n\n");
  382. print_usage();
  383. return 1;
  384. }else{
  385. will_topic = argv[i+1];
  386. }
  387. i++;
  388. }else{
  389. fprintf(stderr, "Error: Unknown option '%s'.\n",argv[i]);
  390. print_usage();
  391. return 1;
  392. }
  393. }
  394. if(clean_session == false && (id_prefix || !id)){
  395. if(!ud.quiet) fprintf(stderr, "Error: You must provide a client id if you are using the -c option.\n");
  396. return 1;
  397. }
  398. if(ud.topic_count == 0){
  399. fprintf(stderr, "Error: You must specify a topic to subscribe to.\n");
  400. print_usage();
  401. return 1;
  402. }
  403. if(will_payload && !will_topic){
  404. fprintf(stderr, "Error: Will payload given, but no will topic given.\n");
  405. print_usage();
  406. return 1;
  407. }
  408. if(will_retain && !will_topic){
  409. fprintf(stderr, "Error: Will retain given, but no will topic given.\n");
  410. print_usage();
  411. return 1;
  412. }
  413. if(ud.password && !ud.username){
  414. if(!ud.quiet) fprintf(stderr, "Warning: Not using password since username not set.\n");
  415. }
  416. if((certfile && !keyfile) || (keyfile && !certfile)){
  417. fprintf(stderr, "Error: Both certfile and keyfile must be provided if one of them is.\n");
  418. print_usage();
  419. return 1;
  420. }
  421. if((cafile || capath) && psk){
  422. if(!ud.quiet) fprintf(stderr, "Error: Only one of --psk or --cafile/--capath may be used at once.\n");
  423. return 1;
  424. }
  425. if(psk && !psk_identity){
  426. if(!ud.quiet) fprintf(stderr, "Error: --psk-identity required if --psk used.\n");
  427. return 1;
  428. }
  429. mosquitto_lib_init();
  430. if(id_prefix){
  431. id = malloc(strlen(id_prefix)+10);
  432. if(!id){
  433. if(!ud.quiet) fprintf(stderr, "Error: Out of memory.\n");
  434. mosquitto_lib_cleanup();
  435. return 1;
  436. }
  437. snprintf(id, strlen(id_prefix)+10, "%s%d", id_prefix, getpid());
  438. }else if(!id){
  439. hostname[0] = '\0';
  440. gethostname(hostname, 256);
  441. hostname[255] = '\0';
  442. len = strlen("mosqsub/-") + 6 + strlen(hostname);
  443. id = malloc(len);
  444. if(!id){
  445. if(!ud.quiet) fprintf(stderr, "Error: Out of memory.\n");
  446. mosquitto_lib_cleanup();
  447. return 1;
  448. }
  449. snprintf(id, len, "mosqsub/%d-%s", getpid(), hostname);
  450. id[MOSQ_MQTT_ID_MAX_LENGTH] = '\0';
  451. snprintf(id, MOSQ_MQTT_ID_MAX_LENGTH, "mosqsub/%d-%s", getpid(), hostname);
  452. id[MOSQ_MQTT_ID_MAX_LENGTH] = '\0';
  453. }
  454. mosq = mosquitto_new(id, clean_session, &ud);
  455. if(!mosq){
  456. switch(errno){
  457. case ENOMEM:
  458. if(!ud.quiet) fprintf(stderr, "Error: Out of memory.\n");
  459. break;
  460. case EINVAL:
  461. if(!ud.quiet) fprintf(stderr, "Error: Invalid id and/or clean_session.\n");
  462. break;
  463. }
  464. mosquitto_lib_cleanup();
  465. return 1;
  466. }
  467. if(debug){
  468. mosquitto_log_callback_set(mosq, my_log_callback);
  469. }
  470. if(will_topic && mosquitto_will_set(mosq, will_topic, will_payloadlen, will_payload, will_qos, will_retain)){
  471. if(!ud.quiet) fprintf(stderr, "Error: Problem setting will.\n");
  472. mosquitto_lib_cleanup();
  473. return 1;
  474. }
  475. if(ud.username && mosquitto_username_pw_set(mosq, ud.username, ud.password)){
  476. if(!ud.quiet) fprintf(stderr, "Error: Problem setting username and password.\n");
  477. mosquitto_lib_cleanup();
  478. return 1;
  479. }
  480. if((cafile || capath) && mosquitto_tls_set(mosq, cafile, capath, certfile, keyfile, NULL)){
  481. if(!ud.quiet) fprintf(stderr, "Error: Problem setting TLS options.\n");
  482. mosquitto_lib_cleanup();
  483. return 1;
  484. }
  485. if(psk && mosquitto_tls_psk_set(mosq, psk, psk_identity, NULL)){
  486. if(!ud.quiet) fprintf(stderr, "Error: Problem setting TLS-PSK options.\n");
  487. mosquitto_lib_cleanup();
  488. return 1;
  489. }
  490. mosquitto_connect_callback_set(mosq, my_connect_callback);
  491. mosquitto_message_callback_set(mosq, my_message_callback);
  492. if(debug){
  493. mosquitto_subscribe_callback_set(mosq, my_subscribe_callback);
  494. }
  495. rc = mosquitto_connect(mosq, host, port, keepalive);
  496. if(rc){
  497. if(!ud.quiet){
  498. if(rc == MOSQ_ERR_ERRNO){
  499. #ifndef WIN32
  500. strerror_r(errno, err, 1024);
  501. #else
  502. FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, errno, 0, (LPTSTR)&err, 1024, NULL);
  503. #endif
  504. fprintf(stderr, "Error: %s\n", err);
  505. }else{
  506. fprintf(stderr, "Unable to connect (%d).\n", rc);
  507. }
  508. }
  509. return rc;
  510. mosquitto_lib_cleanup();
  511. }
  512. do{
  513. rc = mosquitto_loop(mosq, -1, 100);
  514. }while(rc == MOSQ_ERR_SUCCESS);
  515. mosquitto_destroy(mosq);
  516. mosquitto_lib_cleanup();
  517. if(rc){
  518. if(rc == MOSQ_ERR_ERRNO){
  519. fprintf(stderr, "Error: %s\n", strerror(errno));
  520. }else{
  521. fprintf(stderr, "Error: %s\n", mosquitto_strerror(rc));
  522. }
  523. }
  524. return rc;
  525. }