mqttd.c 28 KB

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