PageRenderTime 56ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/client/pub_client.c

https://bitbucket.org/trj/mosquitto-eventloop
C | 571 lines | 515 code | 28 blank | 28 comment | 143 complexity | 239ddc5811e0af0efa13e40a10c02399 MD5 | raw file
Possible License(s): 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 <errno.h>
  27. #include <fcntl.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. #define MSGMODE_NONE 0
  40. #define MSGMODE_CMD 1
  41. #define MSGMODE_STDIN_LINE 2
  42. #define MSGMODE_STDIN_FILE 3
  43. #define MSGMODE_FILE 4
  44. #define MSGMODE_NULL 5
  45. #define STATUS_CONNECTING 0
  46. #define STATUS_CONNACK_RECVD 1
  47. static char *topic = NULL;
  48. static char *message = NULL;
  49. static long msglen = 0;
  50. static int qos = 0;
  51. static int retain = 0;
  52. static int mode = MSGMODE_NONE;
  53. static int status = STATUS_CONNECTING;
  54. static uint16_t mid_sent = 0;
  55. static bool connected = true;
  56. static char *username = NULL;
  57. static char *password = NULL;
  58. static bool disconnect_sent = false;
  59. static bool quiet = false;
  60. void my_connect_callback(void *obj, int result)
  61. {
  62. struct mosquitto *mosq = obj;
  63. int rc = MOSQ_ERR_SUCCESS;
  64. if(!result){
  65. switch(mode){
  66. case MSGMODE_CMD:
  67. case MSGMODE_FILE:
  68. case MSGMODE_STDIN_FILE:
  69. rc = mosquitto_publish(mosq, &mid_sent, topic, msglen, (uint8_t *)message, qos, retain);
  70. break;
  71. case MSGMODE_NULL:
  72. rc = mosquitto_publish(mosq, &mid_sent, topic, 0, NULL, qos, retain);
  73. break;
  74. case MSGMODE_STDIN_LINE:
  75. status = STATUS_CONNACK_RECVD;
  76. break;
  77. }
  78. if(rc){
  79. if(!quiet){
  80. switch(rc){
  81. case MOSQ_ERR_INVAL:
  82. fprintf(stderr, "Error: Invalid input. Does your topic contain '+' or '#'?\n");
  83. break;
  84. case MOSQ_ERR_NOMEM:
  85. fprintf(stderr, "Error: Out of memory when trying to publish message.\n");
  86. break;
  87. case MOSQ_ERR_NO_CONN:
  88. fprintf(stderr, "Error: Client not connected when trying to publish.\n");
  89. break;
  90. case MOSQ_ERR_PROTOCOL:
  91. fprintf(stderr, "Error: Protocol error when communicating with broker.\n");
  92. break;
  93. case MOSQ_ERR_PAYLOAD_SIZE:
  94. fprintf(stderr, "Error: Message payload is too large.\n");
  95. break;
  96. }
  97. }
  98. mosquitto_disconnect(mosq);
  99. }
  100. }else{
  101. switch(result){
  102. case 1:
  103. if(!quiet) fprintf(stderr, "Connection Refused: unacceptable protocol version\n");
  104. break;
  105. case 2:
  106. if(!quiet) fprintf(stderr, "Connection Refused: identifier rejected\n");
  107. break;
  108. case 3:
  109. if(!quiet) fprintf(stderr, "Connection Refused: broker unavailable\n");
  110. break;
  111. case 4:
  112. if(!quiet) fprintf(stderr, "Connection Refused: bad user name or password\n");
  113. break;
  114. case 5:
  115. if(!quiet) fprintf(stderr, "Connection Refused: not authorised\n");
  116. break;
  117. default:
  118. if(!quiet) fprintf(stderr, "Connection Refused: unknown reason\n");
  119. break;
  120. }
  121. }
  122. }
  123. void my_disconnect_callback(void *obj)
  124. {
  125. connected = false;
  126. }
  127. void my_publish_callback(void *obj, uint16_t mid)
  128. {
  129. struct mosquitto *mosq = obj;
  130. if(mode != MSGMODE_STDIN_LINE && disconnect_sent == false){
  131. mosquitto_disconnect(mosq);
  132. disconnect_sent = true;
  133. }
  134. }
  135. int load_stdin(void)
  136. {
  137. long pos = 0, rlen;
  138. char buf[1024];
  139. mode = MSGMODE_STDIN_FILE;
  140. while(!feof(stdin)){
  141. rlen = fread(buf, 1, 1024, stdin);
  142. message = realloc(message, pos+rlen);
  143. if(!message){
  144. if(!quiet) fprintf(stderr, "Error: Out of memory.\n");
  145. return 1;
  146. }
  147. memcpy(&(message[pos]), buf, rlen);
  148. pos += rlen;
  149. }
  150. msglen = pos;
  151. if(!msglen){
  152. if(!quiet) fprintf(stderr, "Error: Zero length input.\n");
  153. return 1;
  154. }
  155. return 0;
  156. }
  157. int load_file(const char *filename)
  158. {
  159. long pos, rlen;
  160. FILE *fptr = NULL;
  161. fptr = fopen(filename, "rb");
  162. if(!fptr){
  163. if(!quiet) fprintf(stderr, "Error: Unable to open file \"%s\".\n", filename);
  164. return 1;
  165. }
  166. mode = MSGMODE_FILE;
  167. fseek(fptr, 0, SEEK_END);
  168. msglen = ftell(fptr);
  169. if(msglen > 268435455){
  170. fclose(fptr);
  171. if(!quiet) fprintf(stderr, "Error: File \"%s\" is too large (>268,435,455 bytes).\n", filename);
  172. return 1;
  173. }
  174. if(msglen == 0){
  175. fclose(fptr);
  176. if(!quiet) fprintf(stderr, "Error: File \"%s\" is empty.\n", filename);
  177. return 1;
  178. }
  179. fseek(fptr, 0, SEEK_SET);
  180. message = malloc(msglen);
  181. if(!message){
  182. fclose(fptr);
  183. if(!quiet) fprintf(stderr, "Error: Out of memory.\n");
  184. return 1;
  185. }
  186. pos = 0;
  187. while(pos < msglen){
  188. rlen = fread(&(message[pos]), sizeof(char), msglen-pos, fptr);
  189. pos += rlen;
  190. }
  191. fclose(fptr);
  192. return 0;
  193. }
  194. void print_usage(void)
  195. {
  196. printf("mosquitto_pub is a simple mqtt client that will publish a message on a single topic and exit.\n\n");
  197. printf("Usage: mosquitto_pub [-h host] [-p port] [-q qos] [-r] {-f file | -l | -n | -m message} -t topic\n");
  198. printf(" [-i id] [-I id_prefix]\n");
  199. printf(" [-d] [--quiet]\n");
  200. printf(" [-u username [-P password]]\n");
  201. printf(" [--will-topic [--will-payload payload] [--will-qos qos] [--will-retain]]\n\n");
  202. printf(" -d : enable debug messages.\n");
  203. printf(" -f : send the contents of a file as the message.\n");
  204. printf(" -h : mqtt host to connect to. Defaults to localhost.\n");
  205. printf(" -i : id to use for this client. Defaults to mosquitto_pub_ appended with the process id.\n");
  206. printf(" -I : define the client id as id_prefix appended with the process id. Useful for when the\n");
  207. printf(" broker is using the clientid_prefixes option.\n");
  208. printf(" -l : read messages from stdin, sending a separate message for each line.\n");
  209. printf(" -m : message payload to send.\n");
  210. printf(" -n : send a null (zero length) message.\n");
  211. printf(" -p : network port to connect to. Defaults to 1883.\n");
  212. printf(" -q : quality of service level to use for all messages. Defaults to 0.\n");
  213. printf(" -r : message should be retained.\n");
  214. printf(" -s : read message from stdin, sending the entire input as a message.\n");
  215. printf(" -t : mqtt topic to publish to.\n");
  216. printf(" -u : provide a username (requires MQTT 3.1 broker)\n");
  217. printf(" -P : provide a password (requires MQTT 3.1 broker)\n");
  218. printf(" --quiet : don't print error messages.\n");
  219. printf(" --will-payload : payload for the client Will, which is sent by the broker in case of\n");
  220. printf(" unexpected disconnection. If not given and will-topic is set, a zero\n");
  221. printf(" length message will be sent.\n");
  222. printf(" --will-qos : QoS level for the client Will.\n");
  223. printf(" --will-retain : if given, make the client Will retained.\n");
  224. printf(" --will-topic : the topic on which to publish the client Will.\n");
  225. printf("\nSee http://mosquitto.org/ for more information.\n\n");
  226. }
  227. int main(int argc, char *argv[])
  228. {
  229. char *id = NULL;
  230. char *id_prefix = NULL;
  231. int i;
  232. char *host = "localhost";
  233. int port = 1883;
  234. int keepalive = 60;
  235. int opt;
  236. char buf[1024];
  237. bool debug = false;
  238. struct mosquitto *mosq = NULL;
  239. int rc;
  240. int rc2;
  241. char hostname[21];
  242. char err[1024];
  243. uint8_t *will_payload = NULL;
  244. long will_payloadlen = 0;
  245. int will_qos = 0;
  246. bool will_retain = false;
  247. char *will_topic = NULL;
  248. for(i=1; i<argc; i++){
  249. if(!strcmp(argv[i], "-p") || !strcmp(argv[i], "--port")){
  250. if(i==argc-1){
  251. fprintf(stderr, "Error: -p argument given but no port specified.\n\n");
  252. print_usage();
  253. return 1;
  254. }else{
  255. port = atoi(argv[i+1]);
  256. if(port<1 || port>65535){
  257. fprintf(stderr, "Error: Invalid port given: %d\n", port);
  258. print_usage();
  259. return 1;
  260. }
  261. }
  262. i++;
  263. }else if(!strcmp(argv[i], "-d") || !strcmp(argv[i], "--debug")){
  264. debug = true;
  265. }else if(!strcmp(argv[i], "-f") || !strcmp(argv[i], "--file")){
  266. if(mode != MSGMODE_NONE){
  267. fprintf(stderr, "Error: Only one type of message can be sent at once.\n\n");
  268. print_usage();
  269. return 1;
  270. }else if(i==argc-1){
  271. fprintf(stderr, "Error: -f argument given but no file specified.\n\n");
  272. print_usage();
  273. return 1;
  274. }else{
  275. if(load_file(argv[i+1])) return 1;
  276. }
  277. i++;
  278. }else if(!strcmp(argv[i], "-h") || !strcmp(argv[i], "--host")){
  279. if(i==argc-1){
  280. fprintf(stderr, "Error: -h argument given but no host specified.\n\n");
  281. print_usage();
  282. return 1;
  283. }else{
  284. host = argv[i+1];
  285. }
  286. i++;
  287. }else if(!strcmp(argv[i], "-i") || !strcmp(argv[i], "--id")){
  288. if(id_prefix){
  289. fprintf(stderr, "Error: -i and -I argument cannot be used together.\n\n");
  290. print_usage();
  291. return 1;
  292. }
  293. if(i==argc-1){
  294. fprintf(stderr, "Error: -i argument given but no id specified.\n\n");
  295. print_usage();
  296. return 1;
  297. }else{
  298. id = argv[i+1];
  299. }
  300. i++;
  301. }else if(!strcmp(argv[i], "-I") || !strcmp(argv[i], "--id-prefix")){
  302. if(id){
  303. fprintf(stderr, "Error: -i and -I argument cannot be used together.\n\n");
  304. print_usage();
  305. return 1;
  306. }
  307. if(i==argc-1){
  308. fprintf(stderr, "Error: -I argument given but no id prefix specified.\n\n");
  309. print_usage();
  310. return 1;
  311. }else{
  312. id_prefix = argv[i+1];
  313. }
  314. i++;
  315. }else if(!strcmp(argv[i], "-l") || !strcmp(argv[i], "--stdin-line")){
  316. if(mode != MSGMODE_NONE){
  317. fprintf(stderr, "Error: Only one type of message can be sent at once.\n\n");
  318. print_usage();
  319. return 1;
  320. }else{
  321. mode = MSGMODE_STDIN_LINE;
  322. #ifndef WIN32
  323. opt = fcntl(fileno(stdin), F_GETFL, 0);
  324. if(opt == -1 || fcntl(fileno(stdin), F_SETFL, opt | O_NONBLOCK) == -1){
  325. fprintf(stderr, "Error: Unable to set stdin to non-blocking.\n");
  326. return 1;
  327. }
  328. #endif
  329. }
  330. }else if(!strcmp(argv[i], "-m") || !strcmp(argv[i], "--message")){
  331. if(mode != MSGMODE_NONE){
  332. fprintf(stderr, "Error: Only one type of message can be sent at once.\n\n");
  333. print_usage();
  334. return 1;
  335. }else if(i==argc-1){
  336. fprintf(stderr, "Error: -m argument given but no message specified.\n\n");
  337. print_usage();
  338. return 1;
  339. }else{
  340. message = argv[i+1];
  341. msglen = strlen(message);
  342. mode = MSGMODE_CMD;
  343. }
  344. i++;
  345. }else if(!strcmp(argv[i], "-n") || !strcmp(argv[i], "--null-message")){
  346. if(mode != MSGMODE_NONE){
  347. fprintf(stderr, "Error: Only one type of message can be sent at once.\n\n");
  348. print_usage();
  349. return 1;
  350. }else{
  351. mode = MSGMODE_NULL;
  352. }
  353. }else if(!strcmp(argv[i], "-q") || !strcmp(argv[i], "--qos")){
  354. if(i==argc-1){
  355. fprintf(stderr, "Error: -q argument given but no QoS specified.\n\n");
  356. print_usage();
  357. return 1;
  358. }else{
  359. qos = atoi(argv[i+1]);
  360. if(qos<0 || qos>2){
  361. fprintf(stderr, "Error: Invalid QoS given: %d\n", qos);
  362. print_usage();
  363. return 1;
  364. }
  365. }
  366. i++;
  367. }else if(!strcmp(argv[i], "--quiet")){
  368. quiet = true;
  369. }else if(!strcmp(argv[i], "-r") || !strcmp(argv[i], "--retain")){
  370. retain = 1;
  371. }else if(!strcmp(argv[i], "-s") || !strcmp(argv[i], "--stdin-file")){
  372. if(mode != MSGMODE_NONE){
  373. fprintf(stderr, "Error: Only one type of message can be sent at once.\n\n");
  374. print_usage();
  375. return 1;
  376. }else{
  377. if(load_stdin()) return 1;
  378. }
  379. }else if(!strcmp(argv[i], "-t") || !strcmp(argv[i], "--topic")){
  380. if(i==argc-1){
  381. fprintf(stderr, "Error: -t argument given but no topic specified.\n\n");
  382. print_usage();
  383. return 1;
  384. }else{
  385. topic = argv[i+1];
  386. }
  387. i++;
  388. }else if(!strcmp(argv[i], "-u") || !strcmp(argv[i], "--username")){
  389. if(i==argc-1){
  390. fprintf(stderr, "Error: -u argument given but no username specified.\n\n");
  391. print_usage();
  392. return 1;
  393. }else{
  394. username = argv[i+1];
  395. }
  396. i++;
  397. }else if(!strcmp(argv[i], "-P") || !strcmp(argv[i], "--pw")){
  398. if(i==argc-1){
  399. fprintf(stderr, "Error: -P argument given but no password specified.\n\n");
  400. print_usage();
  401. return 1;
  402. }else{
  403. password = argv[i+1];
  404. }
  405. i++;
  406. }else if(!strcmp(argv[i], "--will-payload")){
  407. if(i==argc-1){
  408. fprintf(stderr, "Error: --will-payload argument given but no will payload specified.\n\n");
  409. print_usage();
  410. return 1;
  411. }else{
  412. will_payload = (uint8_t *)argv[i+1];
  413. will_payloadlen = strlen((char *)will_payload);
  414. }
  415. i++;
  416. }else if(!strcmp(argv[i], "--will-qos")){
  417. if(i==argc-1){
  418. fprintf(stderr, "Error: --will-qos argument given but no will QoS specified.\n\n");
  419. print_usage();
  420. return 1;
  421. }else{
  422. will_qos = atoi(argv[i+1]);
  423. if(will_qos < 0 || will_qos > 2){
  424. fprintf(stderr, "Error: Invalid will QoS %d.\n\n", will_qos);
  425. return 1;
  426. }
  427. }
  428. i++;
  429. }else if(!strcmp(argv[i], "--will-retain")){
  430. will_retain = true;
  431. }else if(!strcmp(argv[i], "--will-topic")){
  432. if(i==argc-1){
  433. fprintf(stderr, "Error: --will-topic argument given but no will topic specified.\n\n");
  434. print_usage();
  435. return 1;
  436. }else{
  437. will_topic = argv[i+1];
  438. }
  439. i++;
  440. }else{
  441. fprintf(stderr, "Error: Unknown option '%s'.\n",argv[i]);
  442. print_usage();
  443. return 1;
  444. }
  445. }
  446. if(id_prefix){
  447. id = malloc(strlen(id_prefix)+10);
  448. if(!id){
  449. if(!quiet) fprintf(stderr, "Error: Out of memory.\n");
  450. return 1;
  451. }
  452. snprintf(id, strlen(id_prefix)+10, "%s%d", id_prefix, getpid());
  453. }else if(!id){
  454. id = malloc(30);
  455. if(!id){
  456. if(!quiet) fprintf(stderr, "Error: Out of memory.\n");
  457. return 1;
  458. }
  459. memset(hostname, 0, 21);
  460. gethostname(hostname, 20);
  461. snprintf(id, 23, "mosq_pub_%d_%s", getpid(), hostname);
  462. }
  463. if(!topic || mode == MSGMODE_NONE){
  464. fprintf(stderr, "Error: Both topic and message must be supplied.\n");
  465. print_usage();
  466. return 1;
  467. }
  468. if(will_payload && !will_topic){
  469. fprintf(stderr, "Error: Will payload given, but no will topic given.\n");
  470. print_usage();
  471. return 1;
  472. }
  473. if(will_retain && !will_topic){
  474. fprintf(stderr, "Error: Will retain given, but no will topic given.\n");
  475. print_usage();
  476. return 1;
  477. }
  478. if(password && !username){
  479. if(!quiet) fprintf(stderr, "Warning: Not using password since username not set.\n");
  480. }
  481. mosquitto_lib_init();
  482. mosq = mosquitto_new(id, NULL);
  483. if(!mosq){
  484. if(!quiet) fprintf(stderr, "Error: Out of memory.\n");
  485. return 1;
  486. }
  487. if(debug){
  488. mosquitto_log_init(mosq, MOSQ_LOG_DEBUG | MOSQ_LOG_ERR | MOSQ_LOG_WARNING
  489. | MOSQ_LOG_NOTICE | MOSQ_LOG_INFO, MOSQ_LOG_STDERR);
  490. }
  491. if(will_topic && mosquitto_will_set(mosq, true, will_topic, will_payloadlen, will_payload, will_qos, will_retain)){
  492. if(!quiet) fprintf(stderr, "Error: Problem setting will.\n");
  493. return 1;
  494. }
  495. if(username && mosquitto_username_pw_set(mosq, username, password)){
  496. if(!quiet) fprintf(stderr, "Error: Problem setting username and password.\n");
  497. return 1;
  498. }
  499. mosquitto_connect_callback_set(mosq, my_connect_callback);
  500. mosquitto_disconnect_callback_set(mosq, my_disconnect_callback);
  501. mosquitto_publish_callback_set(mosq, my_publish_callback);
  502. rc = mosquitto_connect(mosq, host, port, keepalive, true);
  503. if(rc){
  504. if(!quiet){
  505. if(rc == MOSQ_ERR_ERRNO){
  506. #ifndef WIN32
  507. strerror_r(errno, err, 1024);
  508. #else
  509. FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, errno, 0, (LPTSTR)&err, 1024, NULL);
  510. #endif
  511. fprintf(stderr, "Error: %s\n", err);
  512. }else{
  513. fprintf(stderr, "Unable to connect (%d).\n", rc);
  514. }
  515. }
  516. return rc;
  517. }
  518. do{
  519. if(mode == MSGMODE_STDIN_LINE && status == STATUS_CONNACK_RECVD){
  520. if(fgets(buf, 1024, stdin)){
  521. buf[strlen(buf)-1] = '\0';
  522. rc2 = mosquitto_publish(mosq, &mid_sent, topic, strlen(buf), (uint8_t *)buf, qos, retain);
  523. if(rc2){
  524. if(!quiet) fprintf(stderr, "Error: Publish returned %d, disconnecting.\n", rc2);
  525. mosquitto_disconnect(mosq);
  526. }
  527. }else if(feof(stdin) && disconnect_sent == false){
  528. mosquitto_disconnect(mosq);
  529. disconnect_sent = true;
  530. }
  531. }
  532. rc = mosquitto_loop(mosq, -1);
  533. }while(rc == MOSQ_ERR_SUCCESS && connected);
  534. if(message && mode == MSGMODE_FILE){
  535. free(message);
  536. }
  537. mosquitto_destroy(mosq);
  538. mosquitto_lib_cleanup();
  539. return rc;
  540. }