mqttd.c 25 KB

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