1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
|
/*
Copyright (c) 2009-2014 Roger Light <roger@atchoo.org>
Copyright (c) 2013-2015 V.Krishn <vkrishn@insteps.net>
All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v1.0
and Eclipse Distribution License v1.0 which accompany this distribution.
The Eclipse Public License is available at
http://www.eclipse.org/legal/epl-v10.html
and the Eclipse Distribution License is available at
http://www.eclipse.org/org/documents/edl-v10.php.
Contributors:
Roger Light - initial implementation and documentation.
*/
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libgen.h>
#ifndef WIN32
#include <unistd.h>
#else
#include <sysstat.h>
#include <process.h>
#include <winsock2.h>
#define snprintf sprintf_s
#endif
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <mosquitto.h>
#include "client_shared.h"
bool process_messages = true;
int msg_count = 0;
/*
@(#)Purpose: Create all directories in path
@(#)Author: J Leffler
@(#)Copyright: (C) JLSS 1990-91,1997-98,2001,2005,2008,2012
@(#)Note: Modified by vkrishn@insteps.net
*/
/* ------------------------------------------------------------- */
typedef struct stat Stat;
static int do_mkdir(const char *path, mode_t mode)
{
Stat st;
int status = 0;
if (stat(path, &st) != 0) {
/* Directory does not exist. EEXIST for race condition */
if (mkdir(path, mode) != 0 && errno != EEXIST)
status = -1;
} else if (!S_ISDIR(st.st_mode)) {
errno = ENOTDIR;
status = -1;
}
return(status);
}
int mkpath(const char *path, mode_t mode)
{
char *pp;
char *sp;
int status;
char *copypath = strdup(path);
status = 0;
pp = copypath;
while (status == 0 && (sp = strchr(pp, '/')) != 0) {
if (sp != pp) {
/* Neither root nor double slash in path */
*sp = '\0';
status = do_mkdir(copypath, mode);
*sp = '/';
}
pp = sp + 1;
}
if (status == 0)
status = do_mkdir(path, mode);
free(copypath);
return (status);
}
/* ------------------------------------------------------------- */
/* Expand --fmask string options for output filename.
DateTime string expansion for --fmask
*/
/* ------------------------------------------------------------- */
#define FMASK_EPOCH 0
#define FMASK_DATE 1
#define FMASK_YEAR 2
#define FMASK_MONTH 3
#define FMASK_DAY 4
#define FMASK_DATETIME 5
#define FMASK_TIME 6
#define FMASK_HOUR 7
#define FMASK_MINUTE 8
#define FMASK_SECOND 9
const char *datetime(int fmt)
{
int n;
int size = 16; /* limit 16 bytes. */
char *dt;
if ((dt = malloc(size)) == NULL)
return NULL;
time_t current;
struct tm *now;
current = time(NULL);
now = localtime(¤t);
switch(fmt) {
case FMASK_EPOCH:
n = snprintf(dt, size, "%02d", (int)current);
break;
case FMASK_DATE:
n = snprintf(dt, size, "%02d-%02d-%02d",
now->tm_year+1900, now->tm_mon+1, now->tm_mday);
break;
case FMASK_YEAR:
n = snprintf(dt, size, "%02d", now->tm_year+1900);
break;
case FMASK_MONTH:
n = snprintf(dt, size, "%02d", now->tm_mon+1);
break;
case FMASK_DAY:
n = snprintf(dt, size, "%02d", now->tm_mday);
break;
case FMASK_DATETIME:
n = snprintf(dt, size, "%02d%02d%02d-%02d%02d%02d",
now->tm_year+1900, now->tm_mon+1, now->tm_mday,
now->tm_hour, now->tm_min, now->tm_sec);
break;
case FMASK_TIME:
n = snprintf(dt, size, "%02d-%02d-%02d",
now->tm_hour, now->tm_min, now->tm_sec);
break;
case FMASK_HOUR:
n = snprintf(dt, size, "%02d", now->tm_hour);
break;
case FMASK_MINUTE:
n = snprintf(dt, size, "%02d", now->tm_min);
break;
case FMASK_SECOND:
n = snprintf(dt, size, "%02d", now->tm_sec);
break;
default:
return NULL;
break;
}
if (n > -1 && n < size) {
return dt;
} else {
free(dt);
return NULL;
}
}
/* ------------------------------------------------------------- */
/* Expand/resolve fmask token string. */
/* ------------------------------------------------------------- */
void *_setfmask(char *token, void *obj)
{
struct mosq_config *cfg;
assert(obj);
cfg = (struct mosq_config *)obj;
char *str2, *subtoken;
char *saveptr2;
char *to = cfg->ftoken; /* limit 1000 bytes. */
const char *dt;
for (str2 = token; ; str2 = NULL) {
subtoken = strtok_r(str2, "@", &saveptr2);
if (subtoken == NULL)
break;
/* format type */
if(!strcmp(subtoken, "epoch")) {
dt = datetime(0);
} else if(!strcmp(subtoken, "date")) {
dt = datetime(1);
} else if(!strcmp(subtoken, "year")) {
dt = datetime(2);
} else if(!strcmp(subtoken, "month")) {
dt = datetime(3);
} else if(!strcmp(subtoken, "day")) {
dt = datetime(4);
} else if(!strcmp(subtoken, "datetime")) {
dt = datetime(5);
} else if(!strcmp(subtoken, "time")) {
dt = datetime(6);
} else if(!strcmp(subtoken, "hour")) {
dt = datetime(7);
} else if(!strcmp(subtoken, "min")) {
dt = datetime(8);
} else if(!strcmp(subtoken, "sec")) {
dt = datetime(9);
} else if(!strcmp(subtoken, "topic")) {
dt = cfg->fmask_topic;
} else if(!strcmp(subtoken, "topic1")) {
dt = cfg->topics[0];
} else if(!strcmp(subtoken, "topic2")) {
dt = cfg->topics[1];
} else if(!strcmp(subtoken, "topic3")) {
dt = cfg->topics[2];
} else if(!strcmp(subtoken, "topic4")) {
dt = cfg->topics[3];
} else if(!strcmp(subtoken, "topic5")) {
dt = cfg->topics[4];
} else if(!strcmp(subtoken, "topic6")) {
dt = cfg->topics[5];
} else if(!strcmp(subtoken, "topic7")) {
dt = cfg->topics[6];
} else if(!strcmp(subtoken, "topic8")) {
dt = cfg->topics[7];
} else if(!strcmp(subtoken, "topic9")) {
dt = cfg->topics[8];
} else if(!strcmp(subtoken, "id")) {
dt = cfg->idtext;
} else {
dt = strdup (subtoken);
}
to = stpcpy (to, dt);
to = stpcpy (to, "-");
}
to[strlen(to)-1] = '\0';
return 0;
}
/* Expand --fmask string options for output filename. */
/* ------------------------------------------------------------- */
void *_fmask(char *fmask, void *obj)
{
struct mosq_config *cfg;
assert(obj);
cfg = (struct mosq_config *)obj;
char *str1, *token;
char *saveptr1;
char *path;
path = strdup (fmask);
char *to = cfg->ffmask; /* limit 1000 bytes. */
to = stpcpy (to, "/");
for (str1 = path; ; str1 = NULL) {
token = strtok_r(str1, "/", &saveptr1);
if (token == NULL)
break;
/* format type */
_setfmask(token, cfg);
to = stpcpy (to, cfg->ftoken);
to = stpcpy (to, "/");
}
to[strlen(to)-1] = '\0';
return 0;
}
/*
File open with given mode.
returns file descriptor (fd)
*/
/* ------------------------------------------------------------- */
FILE *_mosquitto_fopen(const char *path, const char *mode)
{
#ifdef WIN32
char buf[MAX_PATH];
int rc;
rc = ExpandEnvironmentStrings(path, buf, MAX_PATH);
if(rc == 0 || rc == MAX_PATH) {
return NULL;
}else {
return fopen(buf, mode);
}
#else
return fopen(path, mode);
#endif
}
void my_message_file_callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message)
{
struct mosq_config *cfg;
int i;
bool res;
assert(obj);
cfg = (struct mosq_config *)obj;
if(message->retain && cfg->no_retain) return;
if(cfg->filter_outs){
for(i=0; i<cfg->filter_out_count; i++){
mosquitto_topic_matches_sub(cfg->filter_outs[i], message->topic, &res);
if(res) return;
}
}
cfg->fmask_topic = message->topic;
FILE *fptr = NULL;
_fmask(cfg->fmask, cfg);
char *path, *prog;
path = strdup (cfg->ffmask);
prog = strdup (cfg->ffmask);
path = dirname (path);
prog = basename (prog);
mkpath(path, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
if(cfg->overwrite) {
fptr = _mosquitto_fopen(cfg->ffmask, "w");
} else {
fptr = _mosquitto_fopen(cfg->ffmask, "a");
}
if(!fptr){
fprintf(stderr, "Error: cannot open outfile, using stdout.\n");
// need to do normal stdout
//mosquitto_message_callback_set(mosq, "my_message_callback");
} else{
if(cfg->verbose){
if(message->payloadlen){
fprintf(fptr, "%s ", message->topic);
fwrite(message->payload, 1, message->payloadlen, fptr);
if(cfg->eol){
fprintf(fptr, "\n");
}
}else{
if(cfg->eol){
fprintf(fptr, "%s (null)\n", message->topic);
}
}
}else{
if(message->payloadlen){
fwrite(message->payload, 1, message->payloadlen, fptr);
if(cfg->eol){
fprintf(fptr, "\n");
}
}
}
fclose(fptr);
}
}
void my_message_callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message)
{
struct mosq_config *cfg;
int i;
bool res;
if(process_messages == false) return;
assert(obj);
cfg = (struct mosq_config *)obj;
if(message->retain && cfg->no_retain) return;
if(cfg->filter_outs){
for(i=0; i<cfg->filter_out_count; i++){
mosquitto_topic_matches_sub(cfg->filter_outs[i], message->topic, &res);
if(res) return;
}
}
if(cfg->verbose){
if(message->payloadlen){
printf("%s ", message->topic);
fwrite(message->payload, 1, message->payloadlen, stdout);
if(cfg->eol){
printf("\n");
}
}else{
if(cfg->eol){
printf("%s (null)\n", message->topic);
}
}
fflush(stdout);
}else{
if(message->payloadlen){
fwrite(message->payload, 1, message->payloadlen, stdout);
if(cfg->eol){
printf("\n");
}
fflush(stdout);
}
}
if(cfg->msg_count>0){
msg_count++;
if(cfg->msg_count == msg_count){
process_messages = false;
mosquitto_disconnect(mosq);
}
}
}
void my_connect_callback(struct mosquitto *mosq, void *obj, int result)
{
int i;
struct mosq_config *cfg;
assert(obj);
cfg = (struct mosq_config *)obj;
if(!result){
for(i=0; i<cfg->topic_count; i++){
mosquitto_subscribe(mosq, NULL, cfg->topics[i], cfg->qos);
}
}else{
if(result && !cfg->quiet){
fprintf(stderr, "%s\n", mosquitto_connack_string(result));
}
}
}
void my_subscribe_callback(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos)
{
int i;
struct mosq_config *cfg;
assert(obj);
cfg = (struct mosq_config *)obj;
if(!cfg->quiet) printf("Subscribed (mid: %d): %d", mid, granted_qos[0]);
for(i=1; i<qos_count; i++){
if(!cfg->quiet) printf(", %d", granted_qos[i]);
}
if(!cfg->quiet) printf("\n");
}
void my_log_callback(struct mosquitto *mosq, void *obj, int level, const char *str)
{
printf("%s\n", str);
}
void print_usage(void)
{
int major, minor, revision;
mosquitto_lib_version(&major, &minor, &revision);
printf("mosquitto_sub is a simple mqtt client that will subscribe to a single topic and print all messages it receives.\n");
printf("mosquitto_sub version %s running on libmosquitto %d.%d.%d.\n\n", VERSION, major, minor, revision);
printf("Usage: mosquitto_sub [-c] [-h host] [-k keepalive] [-p port] [-q qos] [-R] -t topic ...\n");
printf(" [-C msg_count] [-T filter_out]\n");
#ifdef WITH_SRV
printf(" [-A bind_address] [-S]\n");
#else
printf(" [-A bind_address]\n");
#endif
printf(" [-i id] [-I id_prefix]\n");
printf(" [-d] [-N] [--quiet] [-v]\n");
printf(" [-u username [-P password]]\n");
printf(" [--fmask outfile [--overwrite]]\n");
printf(" [--will-topic [--will-payload payload] [--will-qos qos] [--will-retain]]\n");
#ifdef WITH_TLS
printf(" [{--cafile file | --capath dir} [--cert file] [--key file]\n");
printf(" [--ciphers ciphers] [--insecure]]\n");
#ifdef WITH_TLS_PSK
printf(" [--psk hex-key --psk-identity identity [--ciphers ciphers]]\n");
#endif
#endif
#ifdef WITH_SOCKS
printf(" [--proxy socks-url]\n");
#endif
printf(" mosquitto_sub --help\n\n");
printf(" -A : bind the outgoing socket to this host/ip address. Use to control which interface\n");
printf(" the client communicates over.\n");
printf(" -c : disable 'clean session' (store subscription and pending messages when client disconnects).\n");
printf(" -C : disconnect and exit after receiving the 'msg_count' messages.\n");
printf(" -d : enable debug messages.\n");
printf(" -h : mqtt host to connect to. Defaults to localhost.\n");
printf(" -i : id to use for this client. Defaults to mosquitto_sub_ appended with the process id.\n");
printf(" -I : define the client id as id_prefix appended with the process id. Useful for when the\n");
printf(" broker is using the clientid_prefixes option.\n");
printf(" -k : keep alive in seconds for this client. Defaults to 60.\n");
printf(" -N : do not add an end of line character when printing the payload.\n");
printf(" -p : network port to connect to. Defaults to 1883.\n");
printf(" -P : provide a password (requires MQTT 3.1 broker)\n");
printf(" -q : quality of service level to use for the subscription. Defaults to 0.\n");
printf(" -R : do not print stale messages (those with retain set).\n");
#ifdef WITH_SRV
printf(" -S : use SRV lookups to determine which host to connect to.\n");
#endif
printf(" -t : mqtt topic to subscribe to. May be repeated multiple times.\n");
printf(" -T : topic string to filter out of results. May be repeated.\n");
printf(" -u : provide a username (requires MQTT 3.1 broker)\n");
printf(" -v : print published messages verbosely.\n");
printf(" -V : specify the version of the MQTT protocol to use when connecting.\n");
printf(" Can be mqttv31 or mqttv311. Defaults to mqttv31.\n");
printf(" --help : display this message.\n");
printf(" --quiet : don't print error messages.\n");
printf(" --fmask : path to message outfile\n");
printf(" allowed masks are:\n");
printf(" @[epoch|date|year|month|day|datetime|hour|min|sec|id|topic[1-9]] \n");
printf(" eg. --fmask='@id@date@topic' for file id-2010-12-21-topicname\n");
printf(" --overwrite : overwrite the existing output file.\n");
printf(" --will-payload : payload for the client Will, which is sent by the broker in case of\n");
printf(" unexpected disconnection. If not given and will-topic is set, a zero\n");
printf(" length message will be sent.\n");
printf(" --will-qos : QoS level for the client Will.\n");
printf(" --will-retain : if given, make the client Will retained.\n");
printf(" --will-topic : the topic on which to publish the client Will.\n");
#ifdef WITH_TLS
printf(" --cafile : path to a file containing trusted CA certificates to enable encrypted\n");
printf(" certificate based communication.\n");
printf(" --capath : path to a directory containing trusted CA certificates to enable encrypted\n");
printf(" communication.\n");
printf(" --cert : client certificate for authentication, if required by server.\n");
printf(" --key : client private key for authentication, if required by server.\n");
printf(" --ciphers : openssl compatible list of TLS ciphers to support.\n");
printf(" --tls-version : TLS protocol version, can be one of tlsv1.2 tlsv1.1 or tlsv1.\n");
printf(" Defaults to tlsv1.2 if available.\n");
printf(" --insecure : do not check that the server certificate hostname matches the remote\n");
printf(" hostname. Using this option means that you cannot be sure that the\n");
printf(" remote host is the server you wish to connect to and so is insecure.\n");
printf(" Do not use this option in a production environment.\n");
#ifdef WITH_TLS_PSK
printf(" --psk : pre-shared-key in hexadecimal (no leading 0x) to enable TLS-PSK mode.\n");
printf(" --psk-identity : client identity string for TLS-PSK mode.\n");
#endif
#endif
#ifdef WITH_SOCKS
printf(" --proxy : SOCKS5 proxy URL of the form:\n");
printf(" socks5h://[username[:password]@]hostname[:port]\n");
printf(" Only \"none\" and \"username\" authentication is supported.\n");
#endif
printf("\nSee http://mosquitto.org/ for more information.\n\n");
}
int main(int argc, char *argv[])
{
struct mosq_config cfg;
struct mosquitto *mosq = NULL;
int rc;
rc = client_config_load(&cfg, CLIENT_SUB, argc, argv);
if(rc){
client_config_cleanup(&cfg);
if(rc == 2){
/* --help */
print_usage();
}else{
fprintf(stderr, "\nUse 'mosquitto_sub --help' to see usage.\n");
}
return 1;
}
mosquitto_lib_init();
if(client_id_generate(&cfg, "mosqsub")){
return 1;
}
mosq = mosquitto_new(cfg.id, cfg.clean_session, &cfg);
cfg.idtext = cfg.id;
if(!mosq){
switch(errno){
case ENOMEM:
if(!cfg.quiet) fprintf(stderr, "Error: Out of memory.\n");
break;
case EINVAL:
if(!cfg.quiet) fprintf(stderr, "Error: Invalid id and/or clean_session.\n");
break;
}
mosquitto_lib_cleanup();
return 1;
}
if(client_opts_set(mosq, &cfg)){
return 1;
}
if(cfg.debug){
mosquitto_log_callback_set(mosq, my_log_callback);
mosquitto_subscribe_callback_set(mosq, my_subscribe_callback);
}
mosquitto_connect_callback_set(mosq, my_connect_callback);
if(cfg.isfmask) {
mosquitto_message_callback_set(mosq, my_message_file_callback);
} else {
mosquitto_message_callback_set(mosq, my_message_callback);
}
rc = client_connect(mosq, &cfg);
if(rc) return rc;
rc = mosquitto_loop_forever(mosq, -1, 1);
mosquitto_destroy(mosq);
mosquitto_lib_cleanup();
if(cfg.msg_count>0 && rc == MOSQ_ERR_NO_CONN){
rc = 0;
}
if(rc){
fprintf(stderr, "Error: %s\n", mosquitto_strerror(rc));
}
return rc;
}
|