1 /***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
7 *
8 * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
9 *
10 * This software is licensed as described in the file COPYING, which
11 * you should have received as part of this distribution. The terms
12 * are also available at https://curl.se/docs/copyright.html.
13 *
14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15 * copies of the Software, and permit persons to whom the Software is
16 * furnished to do so, under the terms of the COPYING file.
17 *
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
20 *
21 * SPDX-License-Identifier: curl
22 *
23 ***************************************************************************/
24 #include "server_setup.h"
25 #include <stdlib.h>
26 #include <string.h>
27 #include "util.h"
28
29 /* Function
30 *
31 * Accepts a TCP connection on a custom port (IPv4 or IPv6). Speaks MQTT.
32 *
33 * Read commands from FILE (set with --config). The commands control how to
34 * act and is reset to defaults each client TCP connect.
35 *
36 * Config file keywords:
37 *
38 * TODO
39 */
40
41 /* based on sockfilt.c */
42
43 #include <signal.h>
44 #ifdef HAVE_NETINET_IN_H
45 #include <netinet/in.h>
46 #endif
47 #ifdef HAVE_NETINET_IN6_H
48 #include <netinet/in6.h>
49 #endif
50 #ifdef HAVE_ARPA_INET_H
51 #include <arpa/inet.h>
52 #endif
53 #ifdef HAVE_NETDB_H
54 #include <netdb.h>
55 #endif
56
57 #include "curlx.h" /* from the private lib dir */
58 #include "getpart.h"
59 #include "inet_pton.h"
60 #include "server_sockaddr.h"
61 #include "warnless.h"
62
63 /* include memdebug.h last */
64 #include "memdebug.h"
65
66 #ifdef USE_WINSOCK
67 #undef EINTR
68 #define EINTR 4 /* errno.h value */
69 #undef EAGAIN
70 #define EAGAIN 11 /* errno.h value */
71 #undef ENOMEM
72 #define ENOMEM 12 /* errno.h value */
73 #undef EINVAL
74 #define EINVAL 22 /* errno.h value */
75 #endif
76
77 #define DEFAULT_PORT 1883 /* MQTT default port */
78
79 #ifndef DEFAULT_LOGFILE
80 #define DEFAULT_LOGFILE "log/mqttd.log"
81 #endif
82
83 #ifndef DEFAULT_CONFIG
84 #define DEFAULT_CONFIG "mqttd.config"
85 #endif
86
87 #define MQTT_MSG_CONNECT 0x10
88 #define MQTT_MSG_CONNACK 0x20
89 #define MQTT_MSG_PUBLISH 0x30
90 #define MQTT_MSG_PUBACK 0x40
91 #define MQTT_MSG_SUBSCRIBE 0x82
92 #define MQTT_MSG_SUBACK 0x90
93 #define MQTT_MSG_DISCONNECT 0xe0
94
95 #define MQTT_CONNACK_LEN 4
96 #define MQTT_SUBACK_LEN 5
97 #define MQTT_CLIENTID_LEN 12 /* "curl0123abcd" */
98
99 struct configurable {
100 unsigned char version; /* initial version byte in the request must match
101 this */
102 bool publish_before_suback;
103 bool short_publish;
104 bool excessive_remaining;
105 unsigned char error_connack;
106 int testnum;
107 };
108
109 #define REQUEST_DUMP "server.input"
110 #define CONFIG_VERSION 5
111
112 static struct configurable config;
113
114 const char *serverlogfile = DEFAULT_LOGFILE;
115 static const char *configfile = DEFAULT_CONFIG;
116 static const char *logdir = "log";
117 static char loglockfile[256];
118
119 #ifdef USE_IPV6
120 static bool use_ipv6 = FALSE;
121 #endif
122 static const char *ipv_inuse = "IPv4";
123 static unsigned short port = DEFAULT_PORT;
124
resetdefaults(void)125 static void resetdefaults(void)
126 {
127 logmsg("Reset to defaults");
128 config.version = CONFIG_VERSION;
129 config.publish_before_suback = FALSE;
130 config.short_publish = FALSE;
131 config.excessive_remaining = FALSE;
132 config.error_connack = 0;
133 config.testnum = 0;
134 }
135
byteval(char * value)136 static unsigned char byteval(char *value)
137 {
138 unsigned long num = strtoul(value, NULL, 10);
139 return num & 0xff;
140 }
141
getconfig(void)142 static void getconfig(void)
143 {
144 FILE *fp = fopen(configfile, FOPEN_READTEXT);
145 resetdefaults();
146 if(fp) {
147 char buffer[512];
148 logmsg("parse config file");
149 while(fgets(buffer, sizeof(buffer), fp)) {
150 char key[32];
151 char value[32];
152 if(2 == sscanf(buffer, "%31s %31s", key, value)) {
153 if(!strcmp(key, "version")) {
154 config.version = byteval(value);
155 logmsg("version [%d] set", config.version);
156 }
157 else if(!strcmp(key, "PUBLISH-before-SUBACK")) {
158 logmsg("PUBLISH-before-SUBACK set");
159 config.publish_before_suback = TRUE;
160 }
161 else if(!strcmp(key, "short-PUBLISH")) {
162 logmsg("short-PUBLISH set");
163 config.short_publish = TRUE;
164 }
165 else if(!strcmp(key, "error-CONNACK")) {
166 config.error_connack = byteval(value);
167 logmsg("error-CONNACK = %d", config.error_connack);
168 }
169 else if(!strcmp(key, "Testnum")) {
170 config.testnum = atoi(value);
171 logmsg("testnum = %d", config.testnum);
172 }
173 else if(!strcmp(key, "excessive-remaining")) {
174 logmsg("excessive-remaining set");
175 config.excessive_remaining = TRUE;
176 }
177 }
178 }
179 fclose(fp);
180 }
181 else {
182 logmsg("No config file '%s' to read", configfile);
183 }
184 }
185
loghex(unsigned char * buffer,ssize_t len)186 static void loghex(unsigned char *buffer, ssize_t len)
187 {
188 char data[12000];
189 ssize_t i;
190 unsigned char *ptr = buffer;
191 char *optr = data;
192 ssize_t width = 0;
193 int left = sizeof(data);
194
195 for(i = 0; i < len && (left >= 0); i++) {
196 msnprintf(optr, left, "%02x", ptr[i]);
197 width += 2;
198 optr += 2;
199 left -= 2;
200 }
201 if(width)
202 logmsg("'%s'", data);
203 }
204
205 typedef enum {
206 FROM_CLIENT,
207 FROM_SERVER
208 } mqttdir;
209
logprotocol(mqttdir dir,const char * prefix,size_t remlen,FILE * output,unsigned char * buffer,ssize_t len)210 static void logprotocol(mqttdir dir,
211 const char *prefix, size_t remlen,
212 FILE *output,
213 unsigned char *buffer, ssize_t len)
214 {
215 char data[12000] = "";
216 ssize_t i;
217 unsigned char *ptr = buffer;
218 char *optr = data;
219 int left = sizeof(data);
220
221 for(i = 0; i < len && (left >= 0); i++) {
222 msnprintf(optr, left, "%02x", ptr[i]);
223 optr += 2;
224 left -= 2;
225 }
226 fprintf(output, "%s %s %zx %s\n",
227 dir == FROM_CLIENT ? "client" : "server",
228 prefix, remlen, data);
229 }
230
231
232 /* return 0 on success */
connack(FILE * dump,curl_socket_t fd)233 static int connack(FILE *dump, curl_socket_t fd)
234 {
235 unsigned char packet[]={
236 MQTT_MSG_CONNACK, 0x02,
237 0x00, 0x00
238 };
239 ssize_t rc;
240
241 packet[3] = config.error_connack;
242
243 rc = swrite(fd, (char *)packet, sizeof(packet));
244 if(rc > 0) {
245 logmsg("WROTE %zd bytes [CONNACK]", rc);
246 loghex(packet, rc);
247 logprotocol(FROM_SERVER, "CONNACK", 2, dump, packet, sizeof(packet));
248 }
249 if(rc == sizeof(packet)) {
250 return 0;
251 }
252 return 1;
253 }
254
255 /* return 0 on success */
suback(FILE * dump,curl_socket_t fd,unsigned short packetid)256 static int suback(FILE *dump, curl_socket_t fd, unsigned short packetid)
257 {
258 unsigned char packet[]={
259 MQTT_MSG_SUBACK, 0x03,
260 0, 0, /* filled in below */
261 0x00
262 };
263 ssize_t rc;
264 packet[2] = (unsigned char)(packetid >> 8);
265 packet[3] = (unsigned char)(packetid & 0xff);
266
267 rc = swrite(fd, (char *)packet, sizeof(packet));
268 if(rc == sizeof(packet)) {
269 logmsg("WROTE %zd bytes [SUBACK]", rc);
270 loghex(packet, rc);
271 logprotocol(FROM_SERVER, "SUBACK", 3, dump, packet, rc);
272 return 0;
273 }
274 return 1;
275 }
276
277 #ifdef QOS
278 /* return 0 on success */
puback(FILE * dump,curl_socket_t fd,unsigned short packetid)279 static int puback(FILE *dump, curl_socket_t fd, unsigned short packetid)
280 {
281 unsigned char packet[]={
282 MQTT_MSG_PUBACK, 0x00,
283 0, 0 /* filled in below */
284 };
285 ssize_t rc;
286 packet[2] = (unsigned char)(packetid >> 8);
287 packet[3] = (unsigned char)(packetid & 0xff);
288
289 rc = swrite(fd, (char *)packet, sizeof(packet));
290 if(rc == sizeof(packet)) {
291 logmsg("WROTE %zd bytes [PUBACK]", rc);
292 loghex(packet, rc);
293 logprotocol(FROM_SERVER, dump, packet, rc);
294 return 0;
295 }
296 logmsg("Failed sending [PUBACK]");
297 return 1;
298 }
299 #endif
300
301 /* return 0 on success */
disconnect(FILE * dump,curl_socket_t fd)302 static int disconnect(FILE *dump, curl_socket_t fd)
303 {
304 unsigned char packet[]={
305 MQTT_MSG_DISCONNECT, 0x00,
306 };
307 ssize_t rc = swrite(fd, (char *)packet, sizeof(packet));
308 if(rc == sizeof(packet)) {
309 logmsg("WROTE %zd bytes [DISCONNECT]", rc);
310 loghex(packet, rc);
311 logprotocol(FROM_SERVER, "DISCONNECT", 0, dump, packet, rc);
312 return 0;
313 }
314 logmsg("Failed sending [DISCONNECT]");
315 return 1;
316 }
317
318
319
320 /*
321 do
322
323 encodedByte = X MOD 128
324
325 X = X DIV 128
326
327 // if there are more data to encode, set the top bit of this byte
328
329 if ( X > 0 )
330
331 encodedByte = encodedByte OR 128
332
333 endif
334
335 'output' encodedByte
336
337 while ( X > 0 )
338
339 */
340
341 /* return number of bytes used */
encode_length(size_t packetlen,unsigned char * remlength)342 static size_t encode_length(size_t packetlen,
343 unsigned char *remlength) /* 4 bytes */
344 {
345 size_t bytes = 0;
346 unsigned char encode;
347
348 do {
349 encode = packetlen % 0x80;
350 packetlen /= 0x80;
351 if(packetlen)
352 encode |= 0x80;
353
354 remlength[bytes++] = encode;
355
356 if(bytes > 3) {
357 logmsg("too large packet!");
358 return 0;
359 }
360 } while(packetlen);
361
362 return bytes;
363 }
364
365
decode_length(unsigned char * buf,size_t buflen,size_t * lenbytes)366 static size_t decode_length(unsigned char *buf,
367 size_t buflen, size_t *lenbytes)
368 {
369 size_t len = 0;
370 size_t mult = 1;
371 size_t i;
372 unsigned char encoded = 0x80;
373
374 for(i = 0; (i < buflen) && (encoded & 0x80); i++) {
375 encoded = buf[i];
376 len += (encoded & 0x7f) * mult;
377 mult *= 0x80;
378 }
379
380 if(lenbytes)
381 *lenbytes = i;
382
383 return len;
384 }
385
386
387 /* return 0 on success */
publish(FILE * dump,curl_socket_t fd,unsigned short packetid,char * topic,char * payload,size_t payloadlen)388 static int publish(FILE *dump,
389 curl_socket_t fd, unsigned short packetid,
390 char *topic, char *payload, size_t payloadlen)
391 {
392 size_t topiclen = strlen(topic);
393 unsigned char *packet;
394 size_t payloadindex;
395 size_t remaininglength = topiclen + 2 + payloadlen;
396 size_t packetlen;
397 size_t sendamount;
398 ssize_t rc;
399 unsigned char rembuffer[4];
400 size_t encodedlen;
401
402 if(config.excessive_remaining) {
403 /* manually set illegal remaining length */
404 rembuffer[0] = 0xff;
405 rembuffer[1] = 0xff;
406 rembuffer[2] = 0xff;
407 rembuffer[3] = 0x80; /* maximum allowed here by spec is 0x7f */
408 encodedlen = 4;
409 }
410 else
411 encodedlen = encode_length(remaininglength, rembuffer);
412
413 /* one packet type byte (possibly two more for packetid) */
414 packetlen = remaininglength + encodedlen + 1;
415 packet = malloc(packetlen);
416 if(!packet)
417 return 1;
418
419 packet[0] = MQTT_MSG_PUBLISH; /* TODO: set QoS? */
420 memcpy(&packet[1], rembuffer, encodedlen);
421
422 (void)packetid;
423 /* packet_id if QoS is set */
424
425 packet[1 + encodedlen] = (unsigned char)(topiclen >> 8);
426 packet[2 + encodedlen] = (unsigned char)(topiclen & 0xff);
427 memcpy(&packet[3 + encodedlen], topic, topiclen);
428
429 payloadindex = 3 + topiclen + encodedlen;
430 memcpy(&packet[payloadindex], payload, payloadlen);
431
432 sendamount = packetlen;
433 if(config.short_publish)
434 sendamount -= 2;
435
436 rc = swrite(fd, (char *)packet, sendamount);
437 if(rc > 0) {
438 logmsg("WROTE %zd bytes [PUBLISH]", rc);
439 loghex(packet, rc);
440 logprotocol(FROM_SERVER, "PUBLISH", remaininglength, dump, packet, rc);
441 }
442 free(packet);
443 if((size_t)rc == packetlen)
444 return 0;
445 return 1;
446 }
447
448 #define MAX_TOPIC_LENGTH 65535
449 #define MAX_CLIENT_ID_LENGTH 32
450
451 static char topic[MAX_TOPIC_LENGTH + 1];
452
fixedheader(curl_socket_t fd,unsigned char * bytep,size_t * remaining_lengthp,size_t * remaining_length_bytesp)453 static int fixedheader(curl_socket_t fd,
454 unsigned char *bytep,
455 size_t *remaining_lengthp,
456 size_t *remaining_length_bytesp)
457 {
458 /* get the fixed header */
459 unsigned char buffer[10];
460
461 /* get the first two bytes */
462 ssize_t rc = sread(fd, (char *)buffer, 2);
463 size_t i;
464 if(rc < 2) {
465 logmsg("READ %zd bytes [SHORT!]", rc);
466 return 1; /* fail */
467 }
468 logmsg("READ %zd bytes", rc);
469 loghex(buffer, rc);
470 *bytep = buffer[0];
471
472 /* if the length byte has the top bit set, get the next one too */
473 i = 1;
474 while(buffer[i] & 0x80) {
475 i++;
476 rc = sread(fd, (char *)&buffer[i], 1);
477 if(rc != 1) {
478 logmsg("Remaining Length broken");
479 return 1;
480 }
481 }
482 *remaining_lengthp = decode_length(&buffer[1], i, remaining_length_bytesp);
483 logmsg("Remaining Length: %zu [%zu bytes]", *remaining_lengthp,
484 *remaining_length_bytesp);
485 return 0;
486 }
487
mqttit(curl_socket_t fd)488 static curl_socket_t mqttit(curl_socket_t fd)
489 {
490 size_t buff_size = 10*1024;
491 unsigned char *buffer = NULL;
492 ssize_t rc;
493 unsigned char byte;
494 unsigned short packet_id;
495 size_t payload_len;
496 size_t client_id_length;
497 size_t topic_len;
498 size_t remaining_length = 0;
499 size_t bytes = 0; /* remaining length field size in bytes */
500 char client_id[MAX_CLIENT_ID_LENGTH];
501 long testno;
502 FILE *stream = NULL;
503 FILE *dump;
504 char dumpfile[256];
505
506 static const char protocol[7] = {
507 0x00, 0x04, /* protocol length */
508 'M','Q','T','T', /* protocol name */
509 0x04 /* protocol level */
510 };
511 msnprintf(dumpfile, sizeof(dumpfile), "%s/%s", logdir, REQUEST_DUMP);
512 dump = fopen(dumpfile, "ab");
513 if(!dump)
514 goto end;
515
516 getconfig();
517
518 testno = config.testnum;
519
520 if(testno)
521 logmsg("Found test number %ld", testno);
522
523 buffer = malloc(buff_size);
524 if(!buffer) {
525 logmsg("Out of memory, unable to allocate buffer");
526 goto end;
527 }
528
529 do {
530 unsigned char usr_flag = 0x80;
531 unsigned char passwd_flag = 0x40;
532 unsigned char conn_flags;
533 const size_t client_id_offset = 12;
534 size_t start_usr;
535 size_t start_passwd;
536
537 /* get the fixed header */
538 rc = fixedheader(fd, &byte, &remaining_length, &bytes);
539 if(rc)
540 break;
541
542 if(remaining_length >= buff_size) {
543 buff_size = remaining_length;
544 buffer = realloc(buffer, buff_size);
545 if(!buffer) {
546 logmsg("Failed realloc of size %zu", buff_size);
547 goto end;
548 }
549 }
550
551 if(remaining_length) {
552 /* reading variable header and payload into buffer */
553 rc = sread(fd, (char *)buffer, remaining_length);
554 if(rc > 0) {
555 logmsg("READ %zd bytes", rc);
556 loghex(buffer, rc);
557 }
558 }
559
560 if(byte == MQTT_MSG_CONNECT) {
561 logprotocol(FROM_CLIENT, "CONNECT", remaining_length,
562 dump, buffer, rc);
563
564 if(memcmp(protocol, buffer, sizeof(protocol))) {
565 logmsg("Protocol preamble mismatch");
566 goto end;
567 }
568 /* ignore the connect flag byte and two keepalive bytes */
569 payload_len = (size_t)(buffer[10] << 8) | buffer[11];
570 /* first part of the payload is the client ID */
571 client_id_length = payload_len;
572
573 /* checking if user and password flags were set */
574 conn_flags = buffer[7];
575
576 start_usr = client_id_offset + payload_len;
577 if(usr_flag == (unsigned char)(conn_flags & usr_flag)) {
578 logmsg("User flag is present in CONN flag");
579 payload_len += (size_t)(buffer[start_usr] << 8) |
580 buffer[start_usr + 1];
581 payload_len += 2; /* MSB and LSB for user length */
582 }
583
584 start_passwd = client_id_offset + payload_len;
585 if(passwd_flag == (char)(conn_flags & passwd_flag)) {
586 logmsg("Password flag is present in CONN flags");
587 payload_len += (size_t)(buffer[start_passwd] << 8) |
588 buffer[start_passwd + 1];
589 payload_len += 2; /* MSB and LSB for password length */
590 }
591
592 /* check the length of the payload */
593 if((ssize_t)payload_len != (rc - 12)) {
594 logmsg("Payload length mismatch, expected %zx got %zx",
595 rc - 12, payload_len);
596 goto end;
597 }
598 /* check the length of the client ID */
599 else if((client_id_length + 1) > MAX_CLIENT_ID_LENGTH) {
600 logmsg("Too large client id");
601 goto end;
602 }
603 memcpy(client_id, &buffer[12], client_id_length);
604 client_id[client_id_length] = 0;
605
606 logmsg("MQTT client connect accepted: %s", client_id);
607
608 /* The first packet sent from the Server to the Client MUST be a
609 CONNACK Packet */
610
611 if(connack(dump, fd)) {
612 logmsg("failed sending CONNACK");
613 goto end;
614 }
615 }
616 else if(byte == MQTT_MSG_SUBSCRIBE) {
617 int error;
618 char *data;
619 size_t datalen;
620 logprotocol(FROM_CLIENT, "SUBSCRIBE", remaining_length,
621 dump, buffer, rc);
622 logmsg("Incoming SUBSCRIBE");
623
624 if(rc < 6) {
625 logmsg("Too small SUBSCRIBE");
626 goto end;
627 }
628
629 /* two bytes packet id */
630 packet_id = (unsigned short)((buffer[0] << 8) | buffer[1]);
631
632 /* two bytes topic length */
633 topic_len = (size_t)(buffer[2] << 8) | buffer[3];
634 if(topic_len != (remaining_length - 5)) {
635 logmsg("Wrong topic length, got %zu expected %zu",
636 topic_len, remaining_length - 5);
637 goto end;
638 }
639 memcpy(topic, &buffer[4], topic_len);
640 topic[topic_len] = 0;
641
642 /* there's a QoS byte (two bits) after the topic */
643
644 logmsg("SUBSCRIBE to '%s' [%d]", topic, packet_id);
645 stream = test2fopen(testno, logdir);
646 error = getpart(&data, &datalen, "reply", "data", stream);
647 if(!error) {
648 if(!config.publish_before_suback) {
649 if(suback(dump, fd, packet_id)) {
650 logmsg("failed sending SUBACK");
651 free(data);
652 goto end;
653 }
654 }
655 if(publish(dump, fd, packet_id, topic, data, datalen)) {
656 logmsg("PUBLISH failed");
657 free(data);
658 goto end;
659 }
660 free(data);
661 if(config.publish_before_suback) {
662 if(suback(dump, fd, packet_id)) {
663 logmsg("failed sending SUBACK");
664 goto end;
665 }
666 }
667 }
668 else {
669 char *def = (char *)"this is random payload yes yes it is";
670 publish(dump, fd, packet_id, topic, def, strlen(def));
671 }
672 disconnect(dump, fd);
673 }
674 else if((byte & 0xf0) == (MQTT_MSG_PUBLISH & 0xf0)) {
675 size_t topiclen;
676
677 logmsg("Incoming PUBLISH");
678 logprotocol(FROM_CLIENT, "PUBLISH", remaining_length,
679 dump, buffer, rc);
680
681 topiclen = (size_t)(buffer[1 + bytes] << 8) | buffer[2 + bytes];
682 logmsg("Got %zu bytes topic", topiclen);
683 /* TODO: verify topiclen */
684
685 #ifdef QOS
686 /* TODO: handle packetid if there is one. Send puback if QoS > 0 */
687 puback(dump, fd, 0);
688 #endif
689 /* expect a disconnect here */
690 /* get the request */
691 rc = sread(fd, (char *)&buffer[0], 2);
692
693 logmsg("READ %zd bytes [DISCONNECT]", rc);
694 loghex(buffer, rc);
695 logprotocol(FROM_CLIENT, "DISCONNECT", 0, dump, buffer, rc);
696 goto end;
697 }
698 else {
699 /* not supported (yet) */
700 goto end;
701 }
702 } while(1);
703
704 end:
705 if(buffer)
706 free(buffer);
707 if(dump)
708 fclose(dump);
709 if(stream)
710 fclose(stream);
711 return CURL_SOCKET_BAD;
712 }
713
714 /*
715 sockfdp is a pointer to an established stream or CURL_SOCKET_BAD
716
717 if sockfd is CURL_SOCKET_BAD, listendfd is a listening socket we must
718 accept()
719 */
incoming(curl_socket_t listenfd)720 static bool incoming(curl_socket_t listenfd)
721 {
722 fd_set fds_read;
723 fd_set fds_write;
724 fd_set fds_err;
725 int clients = 0; /* connected clients */
726
727 if(got_exit_signal) {
728 logmsg("signalled to die, exiting...");
729 return FALSE;
730 }
731
732 #ifdef HAVE_GETPPID
733 /* As a last resort, quit if socks5 process becomes orphan. */
734 if(getppid() <= 1) {
735 logmsg("process becomes orphan, exiting");
736 return FALSE;
737 }
738 #endif
739
740 do {
741 ssize_t rc;
742 int error = 0;
743 curl_socket_t sockfd = listenfd;
744 int maxfd = (int)sockfd;
745
746 FD_ZERO(&fds_read);
747 FD_ZERO(&fds_write);
748 FD_ZERO(&fds_err);
749
750 /* there's always a socket to wait for */
751 FD_SET(sockfd, &fds_read);
752
753 do {
754 /* select() blocking behavior call on blocking descriptors please */
755 rc = select(maxfd + 1, &fds_read, &fds_write, &fds_err, NULL);
756 if(got_exit_signal) {
757 logmsg("signalled to die, exiting...");
758 return FALSE;
759 }
760 } while((rc == -1) && ((error = SOCKERRNO) == EINTR));
761
762 if(rc < 0) {
763 logmsg("select() failed with error: (%d) %s",
764 error, strerror(error));
765 return FALSE;
766 }
767
768 if(FD_ISSET(sockfd, &fds_read)) {
769 curl_socket_t newfd = accept(sockfd, NULL, NULL);
770 if(CURL_SOCKET_BAD == newfd) {
771 error = SOCKERRNO;
772 logmsg("accept(%" FMT_SOCKET_T ", NULL, NULL) "
773 "failed with error: (%d) %s", sockfd, error, sstrerror(error));
774 }
775 else {
776 logmsg("====> Client connect, fd %" FMT_SOCKET_T ". "
777 "Read config from %s", newfd, configfile);
778 set_advisor_read_lock(loglockfile);
779 (void)mqttit(newfd); /* until done */
780 clear_advisor_read_lock(loglockfile);
781
782 logmsg("====> Client disconnect");
783 sclose(newfd);
784 }
785 }
786 } while(clients);
787
788 return TRUE;
789 }
790
sockdaemon(curl_socket_t sock,unsigned short * listenport)791 static curl_socket_t sockdaemon(curl_socket_t sock,
792 unsigned short *listenport)
793 {
794 /* passive daemon style */
795 srvr_sockaddr_union_t listener;
796 int flag;
797 int rc;
798 int totdelay = 0;
799 int maxretr = 10;
800 int delay = 20;
801 int attempt = 0;
802 int error = 0;
803
804 do {
805 attempt++;
806 flag = 1;
807 rc = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
808 (void *)&flag, sizeof(flag));
809 if(rc) {
810 error = SOCKERRNO;
811 logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
812 error, sstrerror(error));
813 if(maxretr) {
814 rc = wait_ms(delay);
815 if(rc) {
816 /* should not happen */
817 logmsg("wait_ms() failed with error: %d", rc);
818 sclose(sock);
819 return CURL_SOCKET_BAD;
820 }
821 if(got_exit_signal) {
822 logmsg("signalled to die, exiting...");
823 sclose(sock);
824 return CURL_SOCKET_BAD;
825 }
826 totdelay += delay;
827 delay *= 2; /* double the sleep for next attempt */
828 }
829 }
830 } while(rc && maxretr--);
831
832 if(rc) {
833 logmsg("setsockopt(SO_REUSEADDR) failed %d times in %d ms. Error: (%d) %s",
834 attempt, totdelay, error, strerror(error));
835 logmsg("Continuing anyway...");
836 }
837
838 /* When the specified listener port is zero, it is actually a
839 request to let the system choose a non-zero available port. */
840
841 #ifdef USE_IPV6
842 if(!use_ipv6) {
843 #endif
844 memset(&listener.sa4, 0, sizeof(listener.sa4));
845 listener.sa4.sin_family = AF_INET;
846 listener.sa4.sin_addr.s_addr = INADDR_ANY;
847 listener.sa4.sin_port = htons(*listenport);
848 rc = bind(sock, &listener.sa, sizeof(listener.sa4));
849 #ifdef USE_IPV6
850 }
851 else {
852 memset(&listener.sa6, 0, sizeof(listener.sa6));
853 listener.sa6.sin6_family = AF_INET6;
854 listener.sa6.sin6_addr = in6addr_any;
855 listener.sa6.sin6_port = htons(*listenport);
856 rc = bind(sock, &listener.sa, sizeof(listener.sa6));
857 }
858 #endif /* USE_IPV6 */
859 if(rc) {
860 error = SOCKERRNO;
861 logmsg("Error binding socket on port %hu: (%d) %s",
862 *listenport, error, sstrerror(error));
863 sclose(sock);
864 return CURL_SOCKET_BAD;
865 }
866
867 if(!*listenport) {
868 /* The system was supposed to choose a port number, figure out which
869 port we actually got and update the listener port value with it. */
870 curl_socklen_t la_size;
871 srvr_sockaddr_union_t localaddr;
872 #ifdef USE_IPV6
873 if(!use_ipv6)
874 #endif
875 la_size = sizeof(localaddr.sa4);
876 #ifdef USE_IPV6
877 else
878 la_size = sizeof(localaddr.sa6);
879 #endif
880 memset(&localaddr.sa, 0, (size_t)la_size);
881 if(getsockname(sock, &localaddr.sa, &la_size) < 0) {
882 error = SOCKERRNO;
883 logmsg("getsockname() failed with error: (%d) %s",
884 error, sstrerror(error));
885 sclose(sock);
886 return CURL_SOCKET_BAD;
887 }
888 switch(localaddr.sa.sa_family) {
889 case AF_INET:
890 *listenport = ntohs(localaddr.sa4.sin_port);
891 break;
892 #ifdef USE_IPV6
893 case AF_INET6:
894 *listenport = ntohs(localaddr.sa6.sin6_port);
895 break;
896 #endif
897 default:
898 break;
899 }
900 if(!*listenport) {
901 /* Real failure, listener port shall not be zero beyond this point. */
902 logmsg("Apparently getsockname() succeeded, with listener port zero.");
903 logmsg("A valid reason for this failure is a binary built without");
904 logmsg("proper network library linkage. This might not be the only");
905 logmsg("reason, but double check it before anything else.");
906 sclose(sock);
907 return CURL_SOCKET_BAD;
908 }
909 }
910
911 /* start accepting connections */
912 rc = listen(sock, 5);
913 if(0 != rc) {
914 error = SOCKERRNO;
915 logmsg("listen(%" FMT_SOCKET_T ", 5) failed with error: (%d) %s",
916 sock, error, sstrerror(error));
917 sclose(sock);
918 return CURL_SOCKET_BAD;
919 }
920
921 return sock;
922 }
923
924
main(int argc,char * argv[])925 int main(int argc, char *argv[])
926 {
927 curl_socket_t sock = CURL_SOCKET_BAD;
928 curl_socket_t msgsock = CURL_SOCKET_BAD;
929 int wrotepidfile = 0;
930 int wroteportfile = 0;
931 const char *pidname = ".mqttd.pid";
932 const char *portname = ".mqttd.port";
933 bool juggle_again;
934 int error;
935 int arg = 1;
936
937 while(argc > arg) {
938 if(!strcmp("--version", argv[arg])) {
939 printf("mqttd IPv4%s\n",
940 #ifdef USE_IPV6
941 "/IPv6"
942 #else
943 ""
944 #endif
945 );
946 return 0;
947 }
948 else if(!strcmp("--pidfile", argv[arg])) {
949 arg++;
950 if(argc > arg)
951 pidname = argv[arg++];
952 }
953 else if(!strcmp("--portfile", argv[arg])) {
954 arg++;
955 if(argc > arg)
956 portname = argv[arg++];
957 }
958 else if(!strcmp("--config", argv[arg])) {
959 arg++;
960 if(argc > arg)
961 configfile = argv[arg++];
962 }
963 else if(!strcmp("--logfile", argv[arg])) {
964 arg++;
965 if(argc > arg)
966 serverlogfile = argv[arg++];
967 }
968 else if(!strcmp("--logdir", argv[arg])) {
969 arg++;
970 if(argc > arg)
971 logdir = argv[arg++];
972 }
973 else if(!strcmp("--ipv6", argv[arg])) {
974 #ifdef USE_IPV6
975 ipv_inuse = "IPv6";
976 use_ipv6 = TRUE;
977 #endif
978 arg++;
979 }
980 else if(!strcmp("--ipv4", argv[arg])) {
981 /* for completeness, we support this option as well */
982 #ifdef USE_IPV6
983 ipv_inuse = "IPv4";
984 use_ipv6 = FALSE;
985 #endif
986 arg++;
987 }
988 else if(!strcmp("--port", argv[arg])) {
989 arg++;
990 if(argc > arg) {
991 char *endptr;
992 unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
993 if((endptr != argv[arg] + strlen(argv[arg])) ||
994 ((ulnum != 0UL) && ((ulnum < 1025UL) || (ulnum > 65535UL)))) {
995 fprintf(stderr, "mqttd: invalid --port argument (%s)\n",
996 argv[arg]);
997 return 0;
998 }
999 port = curlx_ultous(ulnum);
1000 arg++;
1001 }
1002 }
1003 else {
1004 puts("Usage: mqttd [option]\n"
1005 " --config [file]\n"
1006 " --version\n"
1007 " --logfile [file]\n"
1008 " --logdir [directory]\n"
1009 " --pidfile [file]\n"
1010 " --portfile [file]\n"
1011 " --ipv4\n"
1012 " --ipv6\n"
1013 " --port [port]\n");
1014 return 0;
1015 }
1016 }
1017
1018 msnprintf(loglockfile, sizeof(loglockfile), "%s/%s/mqtt-%s.lock",
1019 logdir, SERVERLOGS_LOCKDIR, ipv_inuse);
1020
1021 #ifdef _WIN32
1022 win32_init();
1023 atexit(win32_cleanup);
1024
1025 setmode(fileno(stdin), O_BINARY);
1026 setmode(fileno(stdout), O_BINARY);
1027 setmode(fileno(stderr), O_BINARY);
1028 #endif
1029
1030 install_signal_handlers(FALSE);
1031
1032 #ifdef USE_IPV6
1033 if(!use_ipv6)
1034 #endif
1035 sock = socket(AF_INET, SOCK_STREAM, 0);
1036 #ifdef USE_IPV6
1037 else
1038 sock = socket(AF_INET6, SOCK_STREAM, 0);
1039 #endif
1040
1041 if(CURL_SOCKET_BAD == sock) {
1042 error = SOCKERRNO;
1043 logmsg("Error creating socket: (%d) %s", error, sstrerror(error));
1044 goto mqttd_cleanup;
1045 }
1046
1047 {
1048 /* passive daemon style */
1049 sock = sockdaemon(sock, &port);
1050 if(CURL_SOCKET_BAD == sock) {
1051 goto mqttd_cleanup;
1052 }
1053 msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
1054 }
1055
1056 logmsg("Running %s version", ipv_inuse);
1057 logmsg("Listening on port %hu", port);
1058
1059 wrotepidfile = write_pidfile(pidname);
1060 if(!wrotepidfile) {
1061 goto mqttd_cleanup;
1062 }
1063
1064 wroteportfile = write_portfile(portname, port);
1065 if(!wroteportfile) {
1066 goto mqttd_cleanup;
1067 }
1068
1069 do {
1070 juggle_again = incoming(sock);
1071 } while(juggle_again);
1072
1073 mqttd_cleanup:
1074
1075 if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD))
1076 sclose(msgsock);
1077
1078 if(sock != CURL_SOCKET_BAD)
1079 sclose(sock);
1080
1081 if(wrotepidfile)
1082 unlink(pidname);
1083 if(wroteportfile)
1084 unlink(portname);
1085
1086 restore_signal_handlers(FALSE);
1087
1088 if(got_exit_signal) {
1089 logmsg("============> mqttd exits with signal (%d)", exit_signal);
1090 /*
1091 * To properly set the return status of the process we
1092 * must raise the same signal SIGINT or SIGTERM that we
1093 * caught and let the old handler take care of it.
1094 */
1095 raise(exit_signal);
1096 }
1097
1098 logmsg("============> mqttd quits");
1099 return 0;
1100 }
1101