mqttd.c 27 KB

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