mqttd.c 27 KB

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