rr_client.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. /*
  2. Copyright (c) 2009-2020 Roger Light <roger@atchoo.org>
  3. All rights reserved. This program and the accompanying materials
  4. are made available under the terms of the Eclipse Public License 2.0
  5. and Eclipse Distribution License v1.0 which accompany this distribution.
  6. The Eclipse Public License is available at
  7. https://www.eclipse.org/legal/epl-2.0/
  8. and the Eclipse Distribution License is available at
  9. http://www.eclipse.org/org/documents/edl-v10.php.
  10. SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
  11. Contributors:
  12. Roger Light - initial implementation and documentation.
  13. */
  14. #include "config.h"
  15. #include <assert.h>
  16. #include <errno.h>
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <string.h>
  20. #include <time.h>
  21. #ifndef WIN32
  22. #include <unistd.h>
  23. #include <signal.h>
  24. #else
  25. #include <process.h>
  26. #include <winsock2.h>
  27. #define snprintf sprintf_s
  28. #endif
  29. #include <mosquitto.h>
  30. #include <mqtt_protocol.h>
  31. #include "client_shared.h"
  32. #include "pub_shared.h"
  33. #include "sub_client_output.h"
  34. enum rr__state {
  35. rr_s_new,
  36. rr_s_connected,
  37. rr_s_subscribed,
  38. rr_s_ready_to_publish,
  39. rr_s_wait_for_response,
  40. rr_s_disconnect
  41. };
  42. static enum rr__state client_state = rr_s_new;
  43. bool process_messages = true;
  44. int msg_count = 0;
  45. struct mosquitto *g_mosq = NULL;
  46. static bool timed_out = false;
  47. static int connack_result = 0;
  48. #ifndef WIN32
  49. static void my_signal_handler(int signum)
  50. {
  51. if(signum == SIGALRM){
  52. process_messages = false;
  53. mosquitto_disconnect_v5(g_mosq, MQTT_RC_DISCONNECT_WITH_WILL_MSG, cfg.disconnect_props);
  54. timed_out = true;
  55. }
  56. }
  57. #endif
  58. int my_publish(struct mosquitto *mosq, int *mid, const char *topic, int payloadlen, void *payload, int qos, bool retain)
  59. {
  60. if(cfg.protocol_version < MQTT_PROTOCOL_V5){
  61. return mosquitto_publish_v5(mosq, mid, topic, payloadlen, payload, qos, retain, NULL);
  62. }else{
  63. return mosquitto_publish_v5(mosq, mid, topic, payloadlen, payload, qos, retain, cfg.publish_props);
  64. }
  65. }
  66. static void my_message_callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message, const mosquitto_property *properties)
  67. {
  68. UNUSED(mosq);
  69. UNUSED(obj);
  70. UNUSED(properties);
  71. print_message(&cfg, message, properties);
  72. switch(cfg.pub_mode){
  73. case MSGMODE_CMD:
  74. case MSGMODE_FILE:
  75. case MSGMODE_STDIN_FILE:
  76. case MSGMODE_NULL:
  77. client_state = rr_s_disconnect;
  78. break;
  79. case MSGMODE_STDIN_LINE:
  80. client_state = rr_s_ready_to_publish;
  81. break;
  82. }
  83. /* FIXME - check all below
  84. if(process_messages == false) return;
  85. if(cfg.retained_only && !message->retain && process_messages){
  86. process_messages = false;
  87. mosquitto_disconnect_v5(mosq, 0, cfg.disconnect_props);
  88. return;
  89. }
  90. if(message->retain && cfg.no_retain) return;
  91. if(cfg.filter_outs){
  92. for(i=0; i<cfg.filter_out_count; i++){
  93. mosquitto_topic_matches_sub(cfg.filter_outs[i], message->topic, &res);
  94. if(res) return;
  95. }
  96. }
  97. //print_message(&cfg, message);
  98. if(cfg.msg_count>0){
  99. msg_count++;
  100. if(cfg.msg_count == msg_count){
  101. process_messages = false;
  102. mosquitto_disconnect_v5(mosq, 0, cfg.disconnect_props);
  103. }
  104. }
  105. */
  106. }
  107. void my_connect_callback(struct mosquitto *mosq, void *obj, int result, int flags, const mosquitto_property *properties)
  108. {
  109. UNUSED(obj);
  110. UNUSED(flags);
  111. UNUSED(properties);
  112. connack_result = result;
  113. if(!result){
  114. client_state = rr_s_connected;
  115. mosquitto_subscribe_v5(mosq, NULL, cfg.response_topic, cfg.qos, 0, cfg.subscribe_props);
  116. }else{
  117. client_state = rr_s_disconnect;
  118. if(result){
  119. if(result == MQTT_RC_UNSUPPORTED_PROTOCOL_VERSION){
  120. err_printf(&cfg, "Connection error: %s. mosquitto_rr only supports connecting to an MQTT v5 broker\n", mosquitto_reason_string(result));
  121. }else{
  122. err_printf(&cfg, "Connection error: %s\n", mosquitto_reason_string(result));
  123. }
  124. }
  125. mosquitto_disconnect_v5(mosq, 0, cfg.disconnect_props);
  126. }
  127. }
  128. static void my_subscribe_callback(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos)
  129. {
  130. UNUSED(obj);
  131. UNUSED(mid);
  132. UNUSED(qos_count);
  133. if(granted_qos[0] < 128){
  134. client_state = rr_s_ready_to_publish;
  135. }else{
  136. client_state = rr_s_disconnect;
  137. err_printf(&cfg, "%s\n", mosquitto_reason_string(granted_qos[0]));
  138. mosquitto_disconnect_v5(mosq, 0, cfg.disconnect_props);
  139. }
  140. }
  141. void my_publish_callback(struct mosquitto *mosq, void *obj, int mid, int reason_code, const mosquitto_property *properties)
  142. {
  143. UNUSED(mosq);
  144. UNUSED(obj);
  145. UNUSED(mid);
  146. UNUSED(reason_code);
  147. UNUSED(properties);
  148. client_state = rr_s_wait_for_response;
  149. }
  150. static void print_version(void)
  151. {
  152. int major, minor, revision;
  153. mosquitto_lib_version(&major, &minor, &revision);
  154. printf("mosquitto_rr version %s running on libmosquitto %d.%d.%d.\n", VERSION, major, minor, revision);
  155. }
  156. static void print_usage(void)
  157. {
  158. int major, minor, revision;
  159. mosquitto_lib_version(&major, &minor, &revision);
  160. printf("mosquitto_rr is an mqtt client that can be used to publish a request message and wait for a response.\n");
  161. printf(" Defaults to MQTT v5, where the Request-Response feature will be used, but v3.1.1 can also be used\n");
  162. printf(" with v3.1.1 brokers.\n");
  163. printf("mosquitto_rr version %s running on libmosquitto %d.%d.%d.\n\n", VERSION, major, minor, revision);
  164. printf("Usage: mosquitto_rr {[-h host] [--unix path] [-p port] [-u username] [-P password] -t topic | -L URL} -e response-topic\n");
  165. printf(" [-c] [-k keepalive] [-q qos] [-R] [-x session-expiry-interval\n");
  166. printf(" [-F format]\n");
  167. #ifndef WIN32
  168. printf(" [-W timeout_secs]\n");
  169. #endif
  170. #ifdef WITH_SRV
  171. printf(" [-A bind_address] [--nodelay] [-S]\n");
  172. #else
  173. printf(" [-A bind_address] [--nodelay]\n");
  174. #endif
  175. printf(" [-i id] [-I id_prefix]\n");
  176. printf(" [-d] [-N] [--quiet] [-v]\n");
  177. printf(" [--will-topic [--will-payload payload] [--will-qos qos] [--will-retain]]\n");
  178. #ifdef WITH_TLS
  179. printf(" [{--cafile file | --capath dir} [--cert file] [--key file]\n");
  180. printf(" [--ciphers ciphers] [--insecure]\n");
  181. printf(" [--tls-alpn protocol]\n");
  182. printf(" [--tls-engine engine] [--keyform keyform] [--tls-engine-kpass-sha1]]\n");
  183. printf(" [--tls-use-os-certs]\n");
  184. #ifdef FINAL_WITH_TLS_PSK
  185. printf(" [--psk hex-key --psk-identity identity [--ciphers ciphers]]\n");
  186. #endif
  187. #endif
  188. #ifdef WITH_SOCKS
  189. printf(" [--proxy socks-url]\n");
  190. #endif
  191. printf(" [-D command identifier value]\n");
  192. printf(" mosquitto_rr --help\n\n");
  193. printf(" -A : bind the outgoing socket to this host/ip address. Use to control which interface\n");
  194. printf(" the client communicates over.\n");
  195. printf(" -c : disable clean session/enable persistent client mode\n");
  196. printf(" When this argument is used, the broker will be instructed not to clean existing sessions\n");
  197. printf(" for the same client id when the client connects, and sessions will never expire when the\n");
  198. printf(" client disconnects. MQTT v5 clients can change their session expiry interval with the -x\n");
  199. printf(" argument.\n");
  200. printf(" -d : enable debug messages.\n");
  201. printf(" -D : Define MQTT v5 properties. See the documentation for more details.\n");
  202. printf(" -e : Response topic. The client will subscribe to this topic to wait for a response.\n");
  203. printf(" -F : output format.\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_rr_ appended with the process id.\n");
  206. printf(" -k : keep alive in seconds for this client. Defaults to 60.\n");
  207. printf(" -L : specify user, password, hostname, port and topic as a URL in the form:\n");
  208. printf(" mqtt(s)://[username[:password]@]host[:port]/topic\n");
  209. printf(" -N : do not add an end of line character when printing the payload.\n");
  210. printf(" -p : network port to connect to. Defaults to 1883 for plain MQTT and 8883 for MQTT over TLS.\n");
  211. printf(" -P : provide a password\n");
  212. printf(" -q : quality of service level to use for communications. Defaults to 0.\n");
  213. printf(" -R : do not print stale messages (those with retain set).\n");
  214. #ifdef WITH_SRV
  215. printf(" -S : use SRV lookups to determine which host to connect to.\n");
  216. #endif
  217. printf(" -t : topic where the request message will be sent.\n");
  218. printf(" -u : provide a username\n");
  219. printf(" -v : print received messages verbosely.\n");
  220. printf(" -V : specify the version of the MQTT protocol to use when connecting.\n");
  221. printf(" Defaults to 5.\n");
  222. #ifndef WIN32
  223. printf(" -W : Specifies a timeout in seconds how long to wait for a response.\n");
  224. #endif
  225. printf(" -x : Set the session-expiry-interval property on the CONNECT packet. Applies to MQTT v5\n");
  226. printf(" clients only. Set to 0-4294967294 to specify the session will expire in that many\n");
  227. printf(" seconds after the client disconnects, or use -1, 4294967295, or ∞ for a session\n");
  228. printf(" that does not expire. Defaults to -1 if -c is also given, or 0 if -c not given.\n");
  229. printf(" --help : display this message.\n");
  230. printf(" --nodelay : disable Nagle's algorithm, to reduce socket sending latency at the possible\n");
  231. printf(" expense of more packets being sent.\n");
  232. printf(" --pretty : print formatted output rather than minimised output when using the\n");
  233. printf(" JSON output format option.\n");
  234. printf(" --quiet : don't print error messages.\n");
  235. printf(" --unix : connect to a broker through a unix domain socket instead of a TCP socket,\n");
  236. printf(" e.g. /tmp/mosquitto.sock\n");
  237. printf(" --will-payload : payload for the client Will, which is sent by the broker in case of\n");
  238. printf(" unexpected disconnection. If not given and will-topic is set, a zero\n");
  239. printf(" length message will be sent.\n");
  240. printf(" --will-qos : QoS level for the client Will.\n");
  241. printf(" --will-retain : if given, make the client Will retained.\n");
  242. printf(" --will-topic : the topic on which to publish the client Will.\n");
  243. #ifdef WITH_TLS
  244. printf(" --cafile : path to a file containing trusted CA certificates to enable encrypted\n");
  245. printf(" certificate based communication.\n");
  246. printf(" --capath : path to a directory containing trusted CA certificates to enable encrypted\n");
  247. printf(" communication.\n");
  248. printf(" --cert : client certificate for authentication, if required by server.\n");
  249. printf(" --key : client private key for authentication, if required by server.\n");
  250. printf(" --ciphers : openssl compatible list of TLS ciphers to support.\n");
  251. printf(" --tls-use-os-certs : Load and trust OS provided CA certificates.\n");
  252. printf(" --tls-version : TLS protocol version, can be one of tlsv1.3 tlsv1.2 or tlsv1.1.\n");
  253. printf(" Defaults to tlsv1.2 if available.\n");
  254. printf(" --insecure : do not check that the server certificate hostname matches the remote\n");
  255. printf(" hostname. Using this option means that you cannot be sure that the\n");
  256. printf(" remote host is the server you wish to connect to and so is insecure.\n");
  257. printf(" Do not use this option in a production environment.\n");
  258. #ifdef WITH_TLS_PSK
  259. printf(" --psk : pre-shared-key in hexadecimal (no leading 0x) to enable TLS-PSK mode.\n");
  260. printf(" --psk-identity : client identity string for TLS-PSK mode.\n");
  261. #endif
  262. #endif
  263. #ifdef WITH_SOCKS
  264. printf(" --proxy : SOCKS5 proxy URL of the form:\n");
  265. printf(" socks5h://[username[:password]@]hostname[:port]\n");
  266. printf(" Only \"none\" and \"username\" authentication is supported.\n");
  267. #endif
  268. printf("\nSee https://mosquitto.org/ for more information.\n\n");
  269. }
  270. int main(int argc, char *argv[])
  271. {
  272. int rc;
  273. #ifndef WIN32
  274. struct sigaction sigact;
  275. #endif
  276. mosquitto_lib_init();
  277. output_init();
  278. rc = client_config_load(&cfg, CLIENT_RR, argc, argv);
  279. if(rc){
  280. if(rc == 2){
  281. /* --help */
  282. print_usage();
  283. }else if(rc == 3){
  284. /* --version */
  285. print_version();
  286. }else{
  287. fprintf(stderr, "\nUse 'mosquitto_rr --help' to see usage.\n");
  288. }
  289. goto cleanup;
  290. }
  291. if(!cfg.topic || cfg.pub_mode == MSGMODE_NONE || !cfg.response_topic){
  292. fprintf(stderr, "Error: All of topic, message, and response topic must be supplied.\n");
  293. fprintf(stderr, "\nUse 'mosquitto_rr --help' to see usage.\n");
  294. goto cleanup;
  295. }
  296. rc = mosquitto_property_add_string(&cfg.publish_props, MQTT_PROP_RESPONSE_TOPIC, cfg.response_topic);
  297. if(rc){
  298. fprintf(stderr, "Error adding property RESPONSE_TOPIC.\n");
  299. goto cleanup;
  300. }
  301. rc = mosquitto_property_check_all(CMD_PUBLISH, cfg.publish_props);
  302. if(rc){
  303. err_printf(&cfg, "Error in PUBLISH properties: Duplicate response topic.\n");
  304. goto cleanup;
  305. }
  306. if(client_id_generate(&cfg)){
  307. goto cleanup;
  308. }
  309. g_mosq = mosquitto_new(cfg.id, cfg.clean_session, &cfg);
  310. if(!g_mosq){
  311. switch(errno){
  312. case ENOMEM:
  313. err_printf(&cfg, "Error: Out of memory.\n");
  314. break;
  315. case EINVAL:
  316. err_printf(&cfg, "Error: Invalid id and/or clean_session.\n");
  317. break;
  318. }
  319. goto cleanup;
  320. }
  321. if(client_opts_set(g_mosq, &cfg)){
  322. goto cleanup;
  323. }
  324. if(cfg.debug){
  325. mosquitto_log_callback_set(g_mosq, my_log_callback);
  326. }
  327. mosquitto_connect_v5_callback_set(g_mosq, my_connect_callback);
  328. mosquitto_subscribe_callback_set(g_mosq, my_subscribe_callback);
  329. mosquitto_message_v5_callback_set(g_mosq, my_message_callback);
  330. rc = client_connect(g_mosq, &cfg);
  331. if(rc){
  332. goto cleanup;
  333. }
  334. #ifndef WIN32
  335. sigact.sa_handler = my_signal_handler;
  336. sigemptyset(&sigact.sa_mask);
  337. sigact.sa_flags = 0;
  338. if(sigaction(SIGALRM, &sigact, NULL) == -1){
  339. perror("sigaction");
  340. goto cleanup;
  341. }
  342. if(cfg.timeout){
  343. alarm(cfg.timeout);
  344. }
  345. #endif
  346. do{
  347. rc = mosquitto_loop(g_mosq, -1, 1);
  348. if(client_state == rr_s_ready_to_publish){
  349. client_state = rr_s_wait_for_response;
  350. switch(cfg.pub_mode){
  351. case MSGMODE_CMD:
  352. case MSGMODE_FILE:
  353. case MSGMODE_STDIN_FILE:
  354. rc = my_publish(g_mosq, &mid_sent, cfg.topic, cfg.msglen, cfg.message, cfg.qos, cfg.retain);
  355. break;
  356. case MSGMODE_NULL:
  357. rc = my_publish(g_mosq, &mid_sent, cfg.topic, 0, NULL, cfg.qos, cfg.retain);
  358. break;
  359. case MSGMODE_STDIN_LINE:
  360. /* FIXME */
  361. break;
  362. }
  363. }
  364. }while(rc == MOSQ_ERR_SUCCESS && client_state != rr_s_disconnect);
  365. mosquitto_destroy(g_mosq);
  366. mosquitto_lib_cleanup();
  367. if(cfg.msg_count>0 && rc == MOSQ_ERR_NO_CONN){
  368. rc = 0;
  369. }
  370. client_config_cleanup(&cfg);
  371. if(timed_out){
  372. err_printf(&cfg, "Timed out\n");
  373. return MOSQ_ERR_TIMEOUT;
  374. }else if(rc){
  375. err_printf(&cfg, "Error: %s\n", mosquitto_strerror(rc));
  376. }
  377. if(connack_result){
  378. return connack_result;
  379. }else{
  380. return rc;
  381. }
  382. cleanup:
  383. mosquitto_lib_cleanup();
  384. client_config_cleanup(&cfg);
  385. return 1;
  386. }