mqttd.c 25 KB

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