mqttd.c 28 KB

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