commit 939fc6441cfbc9dc979be05fe088784779b3c9f9 from: spoollord date: Wed Jan 16 23:21:47 2019 UTC Initial commit. commit - /dev/null commit + 939fc6441cfbc9dc979be05fe088784779b3c9f9 blob - /dev/null blob + ac610607f059527ced5fe5d2b1521639694c5289 (mode 644) --- /dev/null +++ LICENSE.md @@ -0,0 +1,13 @@ +Copyright (c) 2019 Tracey Emery + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. blob - /dev/null blob + dd84c43f77625c298ccc9d44d5790cefc0ac3504 (mode 644) --- /dev/null +++ Makefile @@ -0,0 +1,3 @@ +SUBDIR = thingsd thingsctl + +.include blob - /dev/null blob + 4aaa30a19a611da86241959da44b4e8807a2ebd7 (mode 644) --- /dev/null +++ README.md @@ -0,0 +1,66 @@ +thingsd for OpenBSD +==================== + +The thingsd OpenBSD proxy daemon provides a mechanism for clients and client +processes to communicate with an array of serial and IoT things. At its core, +thingsd is primarily a packet repeater in that it waits for packets to swap +between subscriber clients and things. However, thingsd also provides password +control over those connections, including client limits. + +Prerequisites +------------- + +* OpenBSD 6.4 or higher + +Files +----- + +* `/usr/local/sbin/thingsd` +* `/usr/local/man/man8/thingsd.8` +* `/etc/examples/thingsd.conf` +* `/usr/local/man/man5/thingsd.conf.5` +* `/etc/rc.d/thingsd` +* `/usr/local/sbin/thingsctl` +* `/usr/local/man/man8/thingsctl.8` + +Usage +----- + +Compile and install. + + make + make install + doas cp examples/etc/rc.d/thingsd /etc/rc.d/ + +Edit thingsd.conf according to `man thingsd.conf`. Your settings will depend +on your machine and the things you have setup. + +Once the thingsd.conf is edited, run `rcctl enable thingsd` and +`rcctl start thingsd`. The thingsd daemon can also be run manually from the +command line. To keep thingsd from daemonizing, run `thingsd -d` from the +command line. + +To test your setup, connect to your machine running thingsd with netcat: + + nc SERVERNAME PORT + +Then paste in a subscription packet for your setup: + + ~~~subscribe{{name,"CLIENT"},{things{thing{"dev","passwd"}}}} + +You should start receiving packets from your setup thing. + +Further examples can be found in the src/examples directory above. + +Todo +---- + +* Finish thingsctl functions +* Implement TLS + +Author +------ + +[Tracey Emery](https://github.com/spoollord/) + +See the [License](LICENSE.md) file for more information. blob - /dev/null blob + 1dae85c27d3382ffac3cef59504c7a8af8040783 (mode 644) --- /dev/null +++ thingsctl/Makefile @@ -0,0 +1,21 @@ +PROG= thingsctl + +SRCS+= thingsctl.c + +INC_C_DIR= /usr/local +BINDIR?= ${INC_C_DIR}/sbin +MANDIR?= ${INC_C_DIR}/man/man + +DEBUG= -g -DDEBUG=3 -O0 + +CFLAGS+= -Wall -I${.CURDIR} +CFLAGS+= -Wstrict-prototypes -Wmissing-prototypes +CFLAGS+= -Wmissing-declarations +CFLAGS+= -Wshadow -Wpointer-arith +CFLAGS+= -Wsign-compare -pthread + +CLEANFILES+= y.tab.h + +MAN= thingsctl.8 + +.include blob - /dev/null blob + 13d5a2d73351ea3fb91fa5c43e382db20ef6bad6 (mode 644) --- /dev/null +++ thingsctl/thingsctl.8 @@ -0,0 +1,33 @@ +.\" +.\" Copyright (c) 2016-2019 Tracey Emery +.\" +.\" Permission to use, copy, modify, and distribute this software for any +.\" purpose with or without fee is hereby granted, provided that the above +.\" copyright notice and this permission notice appear in all copies. +.\" +.\" THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +.\" WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +.\" MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +.\" ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +.\" WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +.\" ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +.\" OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +.\" + +.Dd $Mdocdate: January 26 2016 $ +.Dt THINGSCTL 1 +.Os +.Sh NAME +.Nm thingsctl +.Nd thingsd control utility +.Sh SYNOPSIS +.Nm thingsctl +.Op Fl sv +.Op Fl d Ar host : Ns Ar port +.Op Fl f Ar thing +.Op Ar command args ... +.Sh DESCRIPTION +The +.Nm +program is a control utility for the thingsd proxy daemon. +.Pp blob - /dev/null blob + e53212ee333bc156aa10c4d21a120d3acd5e17a9 (mode 644) --- /dev/null +++ thingsctl/thingsctl.c @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2016-2019 Tracey Emery + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include + +int main(int, char *[]); + +int +main(int argc, char *argv[]) +{ + return EXIT_SUCCESS; +} blob - /dev/null blob + a49d06e6233b26b7dcda3483638f6e5e01b90b8d (mode 644) --- /dev/null +++ thingsd/Makefile @@ -0,0 +1,28 @@ +PROG= thingsd + +SRCS= parse.y +SRCS+= log.c serial.c sockets.c client.c events.c + +SRCS+= thingsd.c + +INC_C_DIR= /usr/local +BINDIR?= ${INC_C_DIR}/sbin +MANDIR?= ${INC_C_DIR}/man/man + + + +LDADD= -levent -ltls -lssl -lcrypto -lutil -pthread +DPADD= ${LIBEVENT} ${LIBTLS} ${LIBSSL} ${LIBCRYPTO} ${LIBUTIL} +DEBUG= -g -DDEBUG=3 -O0 + +CFLAGS+= -Wall -I${.CURDIR} +CFLAGS+= -Wstrict-prototypes -Wmissing-prototypes +CFLAGS+= -Wmissing-declarations +CFLAGS+= -Wshadow -Wpointer-arith +CFLAGS+= -Wsign-compare -pthread + +CLEANFILES+= y.tab.h + +MAN= thingsd.8 thingsd.conf.5 + +.include blob - /dev/null blob + ce75703120b885f23fef4917aeb99bdb685793de (mode 644) --- /dev/null +++ thingsd/client.c @@ -0,0 +1,269 @@ +/* + * Copyright (c) 2016-2019 Tracey Emery + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "thingsd.h" + +void +clt_conn(int fd, short event, void *arg) +{ + struct sockaddr_storage ss; + struct clt *clt; + struct thgsd *pthgsd = (struct thgsd *)arg; + struct sock *sock = NULL; + evbuffercb cltrd = clt_rd; + evbuffercb cltwr = clt_wr; + int clt_fd; + socklen_t len = sizeof(ss); + + if ((clt_fd = accept4(fd, (struct sockaddr *)&ss, &len, + SOCK_NONBLOCK)) == -1) { + log_info("clt accept failed"); + return; + } + if ((clt = calloc(1, sizeof(*clt))) == NULL) + goto err; + if ((sock = get_sock(pthgsd, fd)) == NULL) + goto err; + if ((clt->sub_names = (char **)malloc(pthgsd->max_sub * + sizeof(char *))) == NULL) + fatalx("no client subscription names malloc"); + /* check for unlimited clts */ + sock->clt_cnt++; + pthgsd->clt_cnt++; + if (sock->max_clts > 0 && sock->clt_cnt > sock->max_clts) { + log_info("%s max clients reached", sock->name); + sock->clt_cnt--; + pthgsd->clt_cnt--; + goto err; + } + clt->port = sock->port; + clt->sock = sock; + clt->subscribed = false; + clt->evb = evbuffer_new(); + if (clt->evb == NULL) + goto err; + clt->fd = clt_fd; + clt->bev = bufferevent_new(clt->fd, cltrd, cltwr, clt_err, pthgsd); + if (clt->bev == NULL) + goto err; + bufferevent_base_set(pthgsd->eb, clt->bev); + bufferevent_setwatermark(clt->bev, EV_READ, 0, BUFF); + bufferevent_enable(clt->bev, EV_READ); + clt->join_time = time(NULL); + log_info("client connected"); + start_clt_chk(pthgsd); + TAILQ_INSERT_TAIL(&pthgsd->clts, clt, entry); + return; + err: + log_info("client error"); + sock->clt_cnt--; + pthgsd->clt_cnt--; + if (clt_fd != -1) { + close(clt_fd); + free(clt); + } +} + +void +clt_del(struct thgsd *pthgsd, struct clt *pclt) +{ + struct thg *thg; + struct clt *clt, *tclt; + size_t n; + + TAILQ_FOREACH_SAFE(clt, &pthgsd->clts, entry, tclt) { + if (clt == pclt) { + if (clt->bev != NULL) + bufferevent_free(clt->bev); + close(clt->fd); + for (n = 0; n < clt->le; n++) + TAILQ_FOREACH(thg, &pthgsd->thgs, entry) + if (strcmp(clt->sub_names[n], + thg->name) == 0) + thg->clt_cnt--; + pthgsd->clt_cnt--; + clt->sock->clt_cnt--; + if (clt->subscribed == false) + log_info("client disconnected"); + else + log_info("client disconnected: %s", clt->name); + TAILQ_REMOVE(&pthgsd->clts, clt, entry); + free(clt); + break; + } + } +} + +void +clt_rd(struct bufferevent *bev, void *arg) +{ + struct thgsd *pthgsd = (struct thgsd *)arg; + struct thg *thg = NULL; + struct clt *clt = NULL, *tclt; + size_t len, n; + int fd = bev->ev_read.ev_fd; + char *pkt; + + TAILQ_FOREACH(tclt, &pthgsd->clts, entry) { + if (tclt->fd == fd) { + clt = tclt; + if (clt == NULL) + return; + break; + } + } + clt->evb = EVBUFFER_INPUT(bev); + len = EVBUFFER_LENGTH(clt->evb); + if ((pkt = calloc(len, sizeof(*pkt))) == NULL) + return; + if (clt->subscribed == false) { + /* allow one shot at subscription so we don't get hammered */ + bufferevent_disable(clt->bev, EV_READ); + evbuffer_remove(clt->evb, pkt, len); + /* peak into packet and ensure it's a subscription packet */ + if (pkt[0] == 0x7E && pkt[1] == 0x7E && pkt[2] == 0x7E) { + memmove(pkt, pkt+3, len+3+1); + parse_buf(clt, pkt); + free(pkt); + if (clt->subscribed) + bufferevent_enable(clt->bev, EV_READ|EV_WRITE); + } + } else if (clt->subscribed) { + /* write to thgs */ + for (n = 0; n < clt->le; n++) { + TAILQ_FOREACH(thg, &pthgsd->thgs, entry) { + if (strcmp(clt->sub_names[n], thg->name) == 0 && + clt->port == thg->port) { + if (thg->exists) + clt_wr_thgs(clt, thg, len); + else + evbuffer_drain(clt->evb, len); + } + } + } + free(pkt); + } +} + +void +clt_wr_thgs(struct clt *clt, struct thg *thg, size_t len) +{ + char *pkt; + + if ((pkt = calloc(len, sizeof(*pkt))) == NULL) + return; + switch (thg->type) { + case TCP: + case DEV: + if (thg->persist == false) { + if ((thg->fd = open_clt_sock(thg->ipaddr, + thg->conn_port)) == -1) { + log_info("temporary ipaddr connection failed"); + return; + } + evbuffer_remove(clt->evb, pkt, len); + write(thg->fd, pkt, len); + close(thg->fd); + thg->fd = -1; + } else { + if (thg->fd != -1) { + bufferevent_write_buffer(thg->bev, clt->evb); + evbuffer_drain(clt->evb, len); + } + } + free(pkt); + break; + default: + evbuffer_remove(clt->evb, pkt, len); + write(thg->fd, pkt, len); + free(pkt); + break; + } +} + +void +clt_wr(struct bufferevent *bev, void *arg) +{ +} + +void +clt_err(struct bufferevent *bev, short error, void *arg) +{ + struct thgsd *pthgsd = (struct thgsd *)arg; + struct clt *clt; + int fd = bev->ev_read.ev_fd; + + if ((error & EVBUFFER_EOF) == 0) + log_info("client socket error, disconnecting"); + /* client disconnect */ + TAILQ_FOREACH(clt, &pthgsd->clts, entry) { + if (clt->fd == fd) { + clt_del(pthgsd, clt); + break; + } + } +} + +void +clt_do_chk(struct thgsd *pthgsd) +{ + struct clt *clt; + time_t ctime = time(NULL); + + TAILQ_FOREACH(clt, &pthgsd->clts, entry) { + if (clt->subscribed == false) { + if ((ctime - clt->join_time) >= CLT_SUB_TIME) + clt_del(pthgsd, clt); + break; + } + } +} + +void +*clt_chk(void *arg) +{ + struct thgsd *pthgsd = (struct thgsd *)arg; + void (*tfptr)(struct thgsd *); + + tfptr = pthgsd->clt_fptr; + sleep(CLT_SUB_TIME); + (void)(*tfptr)(pthgsd); + return NULL; +} + +void +start_clt_chk(struct thgsd *pthgsd) +{ + pthread_t tclt_chk; + int rclt_chk; + + rclt_chk = pthread_create(&tclt_chk, NULL, clt_chk, (void *)pthgsd); + if (rclt_chk) { + log_info("thread creation failed"); + clt_chk((void *) pthgsd); + } +} blob - /dev/null blob + c022d9075f7874d94609d69e59ac2907baecb3c5 (mode 644) --- /dev/null +++ thingsd/events.c @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2019 Tracey Emery + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include +#include +#include + +#include +#include +#include + +#include "thingsd.h" + +void +udp_evt(int fd, short event, void *arg) +{ + struct thgsd *pthgsd = (struct thgsd *)arg; + struct thg *thg = NULL, *tthg; + struct clt *clt; + char pkt[BUFF]; + int len; + size_t n; + socklen_t *addrlen = NULL; + struct sockaddr *addr = NULL; + + memset(pkt, 0, sizeof(pkt)); + TAILQ_FOREACH(tthg, &pthgsd->thgs, entry) { + if (tthg->fd == fd) { + thg = tthg; + break; + } + } + len = recvfrom(fd, pkt, sizeof(pkt), 0, addr, addrlen); + if (len > 0) { + /* write to clients */ + TAILQ_FOREACH(clt, &pthgsd->clts, entry) { + for (n = 0; n < clt->le; n++) { + if (strcmp(clt->sub_names[n], thg->name) == 0) + bufferevent_write(clt->bev, pkt, len); + } + } + } +} blob - /dev/null blob + 957c7da949d7f6b4f3e29f7a4baec2f33a469200 (mode 644) --- /dev/null +++ thingsd/examples/README.md @@ -0,0 +1,2 @@ +#thingsd +Examples of usage. blob - /dev/null blob + b4cd01f53de060e741a60c508fc7f3feb6db5e97 (mode 644) --- /dev/null +++ thingsd/examples/clients/README.md @@ -0,0 +1,9 @@ +#thingsd + +Example clients. + +From terminal: +``` +nc HOST PORT +paste: ~~~subscribe{{name,"nc_tester"},{things{thing{"thing_name", "thing_passwd"}}}} +``` blob - /dev/null blob + cd503cbde018301f08240bebdf37b80eb30e9bf1 (mode 644) --- /dev/null +++ thingsd/examples/clients/php/test_esp.php @@ -0,0 +1,50 @@ + 500) { + $slp += 9000; + } else { + $slp += 10000; + } + + $slp /= 10; + + if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) { + die(""); + } + + if (socket_connect($sock, $host, $port) === false) { + die(""); + } + $msg_array = array('stationid' => 'weather_station', 'key' => '3b5912b9015c', 'slp' => $slp * 1.0); + $msg_json = json_encode($msg_array); + $msg_json .= "}"; + + $slength = strlen($subscribe); + $jlength = strlen($msg_json); + + socket_write($sock, $subscribe, $slength); + sleep(1); + socket_write($sock, $msg_json, $jlength); + + sleep(1); + socket_close($sock); + +} blob - /dev/null blob + 68f55580682ce677d4a5b6a08a489b56395018ab (mode 644) --- /dev/null +++ thingsd/examples/etc/README.md @@ -0,0 +1,3 @@ +#thingsd + +Configuration and rc.d examples. blob - /dev/null blob + 25bd3008a5baedb78a70e44c7601a809399e92f1 (mode 755) --- /dev/null +++ thingsd/examples/etc/rc.d/thingsd @@ -0,0 +1,9 @@ +#!/bin/sh + +daemon="/usr/local/sbin/thingsd" + +. /etc/rc.d/rc.subr + +rc_reload=NO + +rc_cmd $1 blob - /dev/null blob + 682e7f25f6b4003059de0901cac6ad5dbff7164a (mode 644) --- /dev/null +++ thingsd/examples/etc/thingsd.conf @@ -0,0 +1,67 @@ +# +# Global Options +# + +# Default global things listening port for client connections +default port 50000 + +# Default bind interface +bind interface "re1" + +# Default maximum number of clients for each thing +max clients 2 + +# Maximum subscription requests per client +max subscriptions 5 + +# Thing reconnect timer in seconds +# this is approximate to the event base timer +# default is 30 seconds +# min is 10 seconds +# max is 600 seconds +connection retry 60 + +# Daemon verbosity +log verbose 1 + +# +# Device Setup +# + +thing "thing1" { + location "/dev/ttyU0" { + baud 9600 + listen on port 50002 + max clients 1 + data 8 + parity "none" + stop 1 + } +} + +thing "thing2" { + ipaddr "10.0.0.1" { + connect on port 8080 + max clients 2 + persistent 0 + password "Mother" + } +} + +thing "thing3" { + ipaddr "10.0.0.2" { + connect on port 80 + listen on port 51000 + bind interface "lo0" + password "Father" + } +} + +thing "software_thing4" { + udp "my_listener" { + receive on port 8080 + listen on port 51000 + password "Sister" + } +} + blob - /dev/null blob + 48061985f6b549a38284895b1d77e4a3e3edfc6d (mode 644) --- /dev/null +++ thingsd/examples/hotplug/README.md @@ -0,0 +1,5 @@ +#thingsd + +OpenBSD hotplug example scripts. + +devices[0]="FTDI_iSerial|ttyDeviceNameToUse" blob - /dev/null blob + bef9257f7985ac718ba86500b7d9dd00cdb6977e (mode 755) --- /dev/null +++ thingsd/examples/hotplug/attach @@ -0,0 +1,44 @@ +#!/bin/sh + +cdev="cua." +tdev="tty." +#IFS="|" + +things[0]="A800HGEI|databee" + +DEVCLASS=$1 +DEVNAME=$2 + +case $DEVCLASS in +5) + # tty thing + for i in ${things[@]}; + do + driver= + IFS="|" + set -A thing $i + serial=${thing[0]} + cname=$cdev${thing[1]} + tname=$tdev${thing[1]} + driver=$(usbdevs -dv | grep -A1 $serial | grep -v $serial | tr -s " ") + if [[ -n $driver ]]; then + clndev="/dev/cuaU$(dmesg | grep $driver | tail -1 | cut -d' ' -f1 | grep -o [0-9])" + tlndev="/dev/ttyU$(dmesg | grep $driver | tail -1 | cut -d' ' -f1 | grep -o [0-9])" + cfndev="/dev/$cname" + tfndev="/dev/$tname" + if [[ -e "$cfndev" ]] || [[ -e "$tfndev" ]]; then + logger -i "attach: usb-serial thing not in list" + else + ln -s $clndev $cfndev + ln -s $tlndev $tfndev + logger -i "attach: attached $cfndev" + logger -i "attach: attached $tfndev" + fi + else + logger -i "attach: hotplug attach error" + fi + done +;; +esac + +exit 0 blob - /dev/null blob + 1eb14ddd57253799aa81e687c1fac60d1a8d0cef (mode 755) --- /dev/null +++ thingsd/examples/hotplug/detach @@ -0,0 +1,38 @@ +#!/bin/sh + +cdev="cua." +tdev="tty." +#IFS="|" + +things[0]="A800HGEI|databee" + +DEVCLASS=$1 +DEVNAME=$2 + +case $DEVCLASS in +5) + # tty thing + for i in ${things[@]}; + do + driver= + IFS="|" + set -A thing $i + serial=${thing[0]} + cname=$cdev${thing[1]} + tname=$tdev${thing[1]} + driver=$(usbdevs -dv | grep -A1 $serial | grep -v $serial | tr -s " ") + cfndev="/dev/$cname" + tfndev="/dev/$tname" + if [[ -n $driver ]]; then + logger -i "detach: usb-serial thing not in list" + else + rm $cfndev + rm $tfndev + logger -i "detach: $cfndev removed" + logger -i "detach: $tfndev removed" + fi + done +;; +esac + +exit 0 blob - /dev/null blob + 0fe9a6e76a8d522e8640b71aa77b8ff5bb86e12a (mode 644) --- /dev/null +++ thingsd/log.c @@ -0,0 +1,216 @@ +/* + * Copyright (c) 2003, 2004 Henning Brauer + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include +#include +#include +#include +#include +#include +#include + +static int debug; +static int verbose; +const char *log_procname; + +void log_init(int, int); +void log_procinit(const char *); +void log_setverbose(int); +int log_getverbose(void); +void log_warn(const char *, ...) + __attribute__((__format__ (printf, 1, 2))); +void log_warnx(const char *, ...) + __attribute__((__format__ (printf, 1, 2))); +void log_info(const char *, ...) + __attribute__((__format__ (printf, 1, 2))); +void log_debug(const char *, ...) + __attribute__((__format__ (printf, 1, 2))); +void logit(int, const char *, ...) + __attribute__((__format__ (printf, 2, 3))); +void vlog(int, const char *, va_list) + __attribute__((__format__ (printf, 2, 0))); +__dead void fatal(const char *, ...) + __attribute__((__format__ (printf, 1, 2))); +__dead void fatalx(const char *, ...) + __attribute__((__format__ (printf, 1, 2))); + +void +log_init(int n_debug, int facility) +{ + extern char *__progname; + + debug = n_debug; + verbose = n_debug; + log_procinit(__progname); + + if (!debug) + openlog(__progname, LOG_PID | LOG_NDELAY, facility); + + tzset(); +} + +void +log_procinit(const char *procname) +{ + if (procname != NULL) + log_procname = procname; +} + +void +log_setverbose(int v) +{ + verbose = v; +} + +int +log_getverbose(void) +{ + return (verbose); +} + +void +logit(int pri, const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + vlog(pri, fmt, ap); + va_end(ap); +} + +void +vlog(int pri, const char *fmt, va_list ap) +{ + char *nfmt; + int saved_errno = errno; + + if (debug) { + /* best effort in out of mem situations */ + if (asprintf(&nfmt, "%s\n", fmt) == -1) { + vfprintf(stderr, fmt, ap); + fprintf(stderr, "\n"); + } else { + vfprintf(stderr, nfmt, ap); + free(nfmt); + } + fflush(stderr); + } else + vsyslog(pri, fmt, ap); + + errno = saved_errno; +} + +void +log_warn(const char *emsg, ...) +{ + char *nfmt; + va_list ap; + int saved_errno = errno; + + /* best effort to even work in out of memory situations */ + if (emsg == NULL) + logit(LOG_ERR, "%s", strerror(saved_errno)); + else { + va_start(ap, emsg); + + if (asprintf(&nfmt, "%s: %s", emsg, + strerror(saved_errno)) == -1) { + /* we tried it... */ + vlog(LOG_ERR, emsg, ap); + logit(LOG_ERR, "%s", strerror(saved_errno)); + } else { + vlog(LOG_ERR, nfmt, ap); + free(nfmt); + } + va_end(ap); + } + + errno = saved_errno; +} + +void +log_warnx(const char *emsg, ...) +{ + va_list ap; + + va_start(ap, emsg); + vlog(LOG_ERR, emsg, ap); + va_end(ap); +} + +void +log_info(const char *emsg, ...) +{ + va_list ap; + + va_start(ap, emsg); + vlog(LOG_INFO, emsg, ap); + va_end(ap); +} + +void +log_debug(const char *emsg, ...) +{ + va_list ap; + + if (verbose > 1) { + va_start(ap, emsg); + vlog(LOG_DEBUG, emsg, ap); + va_end(ap); + } +} + +static void +vfatalc(int code, const char *emsg, va_list ap) +{ + static char s[BUFSIZ]; + const char *sep; + + if (emsg != NULL) { + (void)vsnprintf(s, sizeof(s), emsg, ap); + sep = ": "; + } else { + s[0] = '\0'; + sep = ""; + } + if (code) + logit(LOG_CRIT, "%s: %s%s%s", + log_procname, s, sep, strerror(code)); + else + logit(LOG_CRIT, "%s%s%s", log_procname, sep, s); +} + +void +fatal(const char *emsg, ...) +{ + va_list ap; + + va_start(ap, emsg); + vfatalc(errno, emsg, ap); + va_end(ap); + exit(1); +} + +void +fatalx(const char *emsg, ...) +{ + va_list ap; + + va_start(ap, emsg); + vfatalc(0, emsg, ap); + va_end(ap); + exit(1); +} blob - /dev/null blob + 4f77ed6d9eea124869a69f768f8075fae15b76be (mode 644) --- /dev/null +++ thingsd/parse.y @@ -0,0 +1,785 @@ +/* + * Copyright (c) 2016-2019 Tracey Emery + * Copyright (c) 2002, 2003, 2004 Henning Brauer + * Copyright (c) 2001 Markus Friedl. All rights reserved. + * Copyright (c) 2001 Daniel Hartmeier. All rights reserved. + * Copyright (c) 2001 Theo de Raadt. All rights reserved. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +%{ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "thingsd.h" + +TAILQ_HEAD(files, file) files = TAILQ_HEAD_INITIALIZER(files); + +static struct file { + TAILQ_ENTRY(file) entry; + FILE *stream; + char *name; + int lineno; + int errors; +} *file, *topfile; + +extern struct thgsd *pthgsd; +extern struct dthgs *pdthgs; + +struct clt *clt, *tclt; +struct file *pushfile(const char *); +struct file *pushbuff(u_char *); +struct thg *newthg; + +const int baudrates[18] = {50, 75, 110, 134, 150, 200, + 300, 600, 1200, 1800, 2400, 4800, 9600, + 38400, 57600, 76800, 115200}; +const int cbauds = (sizeof(baudrates) / + sizeof(const int)); +const char *parity[4] = {"none", "odd", "even", "space"}; +const int sparity = (sizeof(parity) / + sizeof(const char *)); + +int bc, pc, my_fd; +int popfile(void); +int popbuff(void); +int yyparse(void); +int yylex(void); +int yy_flush_buffer(void); /* look up */ +int yyerror(const char *, ...) + __attribute__((__format__ (printf, 1, 2))) + __attribute__((__nonnull__ (1))); +int kw_cmp(const void *, const void *); +int lookup(char *); +int lgetc(int); +int lungetc(int); +int findeol(void); + +size_t n; + +char *my_name; + +typedef struct { + union { + int number; + char *string; + } v; + int lineno; +} YYSTYPE; +%} + +%token BAUD DATA PARITY STOP HARDWARE SOFTWARE PASSWORD NAME RETRY PERSISTENT +%token LOG VERBOSE CONNECT THING LISTEN LOCATION IPADDR UDP THINGS CONNECTION +%token DEFAULT PORT MAX CLIENTS SUBSCRIPTIONS BIND INTERFACE SUBSCRIBE ERROR +%token RECEIVE +%token STRING +%token NUMBER + +%% +grammar : /* empty */ + | grammar '\n' + | grammar main '\n' + | grammar dosub + | grammar error '\n' { file->errors++; } + ; +main : DEFAULT PORT NUMBER { + pthgsd->port = $3; + } + | maxclients + | maxsubs + | bindopts1 + | logging + | thing + | thgretry + ; +dosub : SUBSCRIBE '{' subopts '}' + ; +subopts : { + /* empty */ + } '{' name '}' ',' '{' things '}' + ; +name : NAME ',' STRING { + /* test we're us and set name */ + TAILQ_FOREACH(clt, &pthgsd->clts, entry) { + if (clt == tclt) { + clt->name = $3; + my_name = $3; + break; + } + } + } +; +things : THINGS '{' subthgs2 '}' + ; +subthgs2 : subthgs2 subthgs + | subthgs + ; +subthgs : THING '{' STRING ',' STRING '}' optcomma { + struct thg *thg; + bool fail = false; + + /* check for duplicate name and subscriptions */ + TAILQ_FOREACH(clt, &pthgsd->clts, entry) { + if (strcmp(clt->name, my_name) == 0) { + if (my_fd != clt->fd) { + fail = true; + log_info("client exists"); + } + for (n = 0; n < clt->le; n++) + if (strcmp(clt->sub_names[n], + $3) == 0) + fail = true; + break; + } + } + /* + * fail from previous tests + * check correct port + * test max subscriptions + * subscribe + */ + TAILQ_FOREACH(thg, &pthgsd->thgs, entry) { + if (fail) + continue; + if (thg->port != clt->port) + continue; + if (strcmp(thg->name, $3) == 0) + if (strcmp(thg->password, $5) == 0) { + if (clt->subs++ >= + pthgsd->max_sub) { + log_info("max " \ + "subscriptions " \ + "reached"); + continue; + } + clt->subscribed = true; + clt->sub_names[clt->le] + = thg->name; + clt->le++; + thg->clt_cnt++; + log_info("client %s subscribed" \ + " to %s", clt->name, + thg->name); + continue; + } + } + } + ; +optcomma : ',' optcomma + | /* emtpy */ + ; +logging : LOG VERBOSE NUMBER { + if (pthgsd->debug == 0) + pthgsd->verbose = $3; + } + ; +bindopts1 : BIND INTERFACE STRING { + pthgsd->iface = $3; + } + ; +bindopts2 : BIND INTERFACE STRING { + newthg->iface = $3; + } + ; +maxclients : MAX CLIENTS NUMBER { + pthgsd->max_clt = $3; + } + ; +maxclientssub : MAX CLIENTS NUMBER { + newthg->max_clt = $3; + } + ; +thgretry : CONNECTION RETRY NUMBER { + if ($3 >= MIN_RTRY && $3 <= MAX_RTRY) + pthgsd->conn_rtry = $3; + } + ; +maxsubs : MAX SUBSCRIPTIONS NUMBER { + pthgsd->max_sub = $3; + } + ; +locopts : /* empty */ + | '{' optnl locopts2 '}' + ; +locopts2 : locopts2 locopts1 nl + | locopts1 optnl + ; +locopts1 : LISTEN STRING PORT NUMBER { + newthg->port = $4; + } + | BAUD NUMBER { + newthg->baud = -1; + for (bc = 0; bc < cbauds; bc++) { + if ($2 == baudrates[bc]) { + newthg->baud = $2; + continue; + } + } + if (newthg->baud == -1) { + yyerror("baud rate syntax error"); + YYERROR; + } + } + | DATA NUMBER { + if ($2 > 8 || $2 < 5) { + yyerror("data bits syntax error"); + YYERROR; + } else + newthg->data_bits = $2; + } + | PARITY STRING { + for (pc = 0; pc < sparity; pc++) { + if (strcmp($2, parity[pc]) == 0) { + newthg->parity = $2; + continue; + } + } + if (newthg->parity == NULL) { + yyerror("parity syntax error"); + YYERROR; + } + } + | STOP NUMBER { + if ($2 > 2 || $2 < 1) { + yyerror("stop bits syntax error"); + YYERROR; + } else if ($2 > 0) + newthg->stop_bits = $2; + } + | HARDWARE NUMBER { + if ($2 > 1 || $2 < 0) { + yyerror("hardware syntax error"); + YYERROR; + } else if ($2 > 0) + newthg->hw_ctl = true; + } + | SOFTWARE NUMBER { + if ($2 > 1 || $2 < 0) { + yyerror("software syntax error"); + YYERROR; + } else + newthg->sw_ctl = true; + } + | PASSWORD STRING { + newthg->password = $2; + } + | bindopts2 + | maxclientssub + ; +socopts2 : socopts2 socopts1 nl + | socopts1 optnl + ; +socopts1 : LISTEN STRING PORT NUMBER { + newthg->port = $4; + } + | CONNECT STRING PORT NUMBER { + newthg->conn_port = $4; + } + | RECEIVE STRING PORT NUMBER { + newthg->conn_port = $4; + } + | PASSWORD STRING { + newthg->password = $2; + } + | PERSISTENT NUMBER { + if ($2) + newthg->persist = true; + else + newthg->persist = false; + } + | bindopts2 + | maxclientssub + ; +thingopts2 : thingopts2 thingopts1 nl + | thingopts1 optnl + ; +thingopts1 : LOCATION STRING { + newthg->location = $2; + } locopts + | IPADDR STRING { + newthg->ipaddr = $2; + } '{' optnl socopts2 '}' + | UDP STRING { + newthg->udp = $2; + } '{' optnl socopts2 '}' + ; +thing : THING STRING { + newthg = new_thg($2); + newthg->location = NULL; + newthg->ipaddr = NULL; + newthg->udp = NULL; + newthg->max_clt = pthgsd->max_clt; + newthg->port = pthgsd->port; + newthg->baud = DEFAULT_BAUD; + newthg->iface = pthgsd->iface; + newthg->conn_port = -1; + newthg->data_bits = -1; + newthg->parity = NULL; + newthg->stop_bits = -1; + newthg->hw_ctl = false; + newthg->sw_ctl = false; + newthg->password = ""; + newthg->persist = true; + } '{' optnl thingopts2 '}' { + if (newthg->ipaddr != NULL && newthg->conn_port == -1) { + yyerror("ipaddr connect port empty"); + YYERROR; + } + if (newthg->ipaddr != NULL && + newthg->location != NULL) { + yyerror("too many ipaddr device arguments"); + YYERROR; + } + if (newthg->udp != NULL && newthg->conn_port == -1) { + yyerror("udp receive port empty"); + YYERROR; + } + if (newthg->udp != NULL && newthg->location != NULL) { + yyerror("too many udp device arguments"); + YYERROR; + } + if (pthgsd->port == 0) { + yyerror("could not set default port"); + YYERROR; + } + TAILQ_INSERT_TAIL(&pthgsd->thgs, newthg, entry); + } + ; +optnl : '\n' optnl + | /* empty */ + ; +nl : '\n' optnl + ; +%% +struct keywords { + const char *k_name; + int k_val; +}; + +int +yyerror(const char *fmt, ...) +{ + va_list ap; + char *msg; + + file->errors++; + va_start(ap, fmt); + if (vasprintf(&msg, fmt, ap) == -1) + fatalx("yyerror vasprintf"); + va_end(ap); + log_warnx("%s:%d: %s", file->name, yylval.lineno, msg); + free(msg); + return (0); +} + +int +kw_cmp(const void *k, const void *e) +{ + return (strcmp(k, ((const struct keywords *)e)->k_name)); +} + +int lookup(char *s) { + /* this has to be sorted always */ + static const struct keywords keywords[] = { + {"baud", BAUD}, + {"bind", BIND}, + {"clients", CLIENTS}, + {"connect", CONNECT}, + {"connection", CONNECTION}, + {"data", DATA}, + {"default", DEFAULT}, + {"hardware", HARDWARE}, + {"interface", INTERFACE}, + {"ipaddr", IPADDR}, + {"listen", LISTEN}, + {"location", LOCATION}, + {"log", LOG}, + {"max", MAX}, + {"name", NAME}, + {"parity", PARITY}, + {"password", PASSWORD}, + {"persistent", PERSISTENT}, + {"port", PORT}, + {"receive", RECEIVE}, + {"retry", RETRY}, + {"software", SOFTWARE}, + {"stop", STOP}, + {"subscribe", SUBSCRIBE}, + {"subscriptions", SUBSCRIPTIONS}, + {"thing", THING}, + {"things", THINGS}, + {"udp", UDP}, + {"verbose", VERBOSE} + }; + const struct keywords *p; + p = bsearch(s, keywords, sizeof(keywords)/sizeof(keywords[0]), + sizeof(keywords[0]), kw_cmp); + if (p) + return (p->k_val); + else + return (STRING); +} + +#define MAXPUSHBACK 128 +u_char *parsebuf; +int parseindex; +u_char pushback_buffer[MAXPUSHBACK]; +int pushback_index = 0; + +int +lgetc(int quotec) +{ + int c, next; + + if (parsebuf) { + /* Read character from the parsebuffer instead of file input */ + if (parseindex >= 0) { + c = parsebuf[parseindex++]; + if (c != '\0') + return (c); + parsebuf = NULL; + } else + parseindex++; + } + if (pushback_index) + return (pushback_buffer[--pushback_index]); + if (quotec) { + if (parseindex > 0) { + /* malformed packet */ + yyerror("reached end of packet while parsing " + "quoted string"); + return (-1); + } + if ((c = getc(file->stream)) == EOF) { + yyerror("reached end of file while parsing " + "quoted string"); + if (file == topfile || popfile() == EOF) + return (EOF); + return (quotec); + } + return (c); + } + if (parseindex == 0) { + while ((c = getc(file->stream)) == '\\') { + next = getc(file->stream); + if (next != '\n') { + c = next; + break; + } + yylval.lineno = file->lineno; + file->lineno++; + } + } + while (c == EOF) { + if (file == topfile || popfile() == EOF) + return (EOF); + c = getc(file->stream); + } + parseindex = 0; + return (c); +} + +int +lungetc(int c) +{ + if (c == EOF) + return (EOF); + if (parsebuf) { + parseindex--; + if (parseindex >= 0) + return (c); + } + if (pushback_index < MAXPUSHBACK-1) + return (pushback_buffer[pushback_index++] = c); + else + return (EOF); +} + +int +findeol(void) +{ + int c; + + parsebuf = NULL; + /* skip to either EOF or the first real EOL */ + while (1) { + if (pushback_index) + c = pushback_buffer[--pushback_index]; + else + c = lgetc(0); + if (c == '\n') { + file->lineno++; + break; + } + if (c == EOF) + break; + } + return (ERROR); +} + +int +yylex(void) +{ + u_char buf[8096]; + u_char *p; + int quotec, next, c; + int token; + + p = buf; + while ((c = lgetc(0)) == ' ' || c == '\t') + ; /* nothing */ + yylval.lineno = file->lineno; + if (c == '#') + while ((c = lgetc(0)) != '\n' && c != EOF) + ; /* nothing */ + switch (c) { + case '\'': + case '"': + quotec = c; + while (1) { + if ((c = lgetc(quotec)) == EOF) + return (0); + if (c == '\n') { + file->lineno++; + continue; + } else if (c == '\\') { + if ((next = lgetc(quotec)) == EOF) + return (0); + if (next == quotec || c == ' ' || c == '\t') + c = next; + else if (next == '\n') { + file->lineno++; + continue; + } else + lungetc(next); + } else if (c == quotec) { + *p = '\0'; + break; + } else if (c == '\0') { + yyerror("syntax error"); + return (findeol()); + } + if (p + 1 >= buf + sizeof(buf) - 1) { + yyerror("string too long"); + return (findeol()); + } + *p++ = c; + } + yylval.v.string = strdup(buf); + if (yylval.v.string == NULL) + fatal("yylex: strdup"); + return (STRING); + } +#define allowed_to_end_number(x) \ + (isspace(x) || x == ')' || x ==',' || x == '/' || x == '}' || x == '=') + if (c == '-' || isdigit(c)) { + do { + *p++ = c; + if ((unsigned)(p-buf) >= sizeof(buf)) { + yyerror("string too long"); + return (findeol()); + } + } while ((c = lgetc(0)) != EOF && isdigit(c)); + lungetc(c); + if (p == buf + 1 && buf[0] == '-') + goto nodigits; + if (c == EOF || allowed_to_end_number(c)) { + const char *errstr = NULL; + + *p = '\0'; + yylval.v.number = strtonum(buf, LLONG_MIN, + LLONG_MAX, &errstr); + if (errstr) { + yyerror("\"%s\" invalid number: %s", + buf, errstr); + return (findeol()); + } + return (NUMBER); + } else { +nodigits: + while (p > buf + 1) + lungetc(*--p); + c = *--p; + if (c == '-') + return (c); + } + } +#define allowed_in_string(x) \ + (isalnum(x) || (ispunct(x) && x != '(' && x != ')' && \ + x != '{' && x != '}' && x != '<' && x != '>' && \ + x != '!' && x != '=' && x != '/' && x != '#' && \ + x != ',')) + if (isalnum(c) || c == ':' || c == '_' || c == '*') { + do { + *p++ = c; + if ((unsigned)(p-buf) >= sizeof(buf)) { + yyerror("string too long"); + return (findeol()); + } + } while ((c = lgetc(0)) != EOF && (allowed_in_string(c))); + lungetc(c); + *p = '\0'; + if ((token = lookup(buf)) == STRING) + if ((yylval.v.string = strdup(buf)) == NULL) + fatal("yylex: strdup"); + return (token); + } + if (c == '\n') { + yylval.lineno = file->lineno; + file->lineno++; + } + if (c == EOF) + return (0); + return (c); +} + +struct file * +pushfile(const char *name) +{ + struct file *nfile; + + if ((nfile = calloc(1, sizeof(struct file))) == NULL) { + log_warn("malloc"); + return (NULL); + } + if ((nfile->name = strdup(name)) == NULL) { + log_warn("malloc"); + free(nfile); + return (NULL); + } + if ((nfile->stream = fopen(nfile->name, "r")) == NULL) { + log_warn("%s", nfile->name); + free(nfile->name); + free(nfile); + return (NULL); + } + nfile->lineno = 1; + TAILQ_INSERT_TAIL(&files, nfile, entry); + return (nfile); +} + +struct file * +pushbuff(u_char *pkt) +{ + struct file *bfile; + + if ((bfile = calloc(1, sizeof(struct file))) == NULL) { + log_warn("malloc"); + return (NULL); + } + if ((bfile->name = strdup("subscribe buffer")) == NULL) { + log_warn("malloc"); + free(bfile); + return (NULL); + } + if ((parsebuf = pkt) == NULL) { + log_warn("%s", bfile->name); + free(bfile->name); + free(bfile); + return (NULL); + } + bfile->lineno = 1; + TAILQ_INSERT_TAIL(&files, bfile, entry); + return (bfile); +} + +int +popfile(void) +{ + struct file *prev; + + if ((prev = TAILQ_PREV(file, files, entry)) != NULL) + prev->errors += file->errors; + + TAILQ_REMOVE(&files, file, entry); + fclose(file->stream); + free(file->name); + free(file); + file = prev; + return (file ? 0 : EOF); +} + +int +popbuff(void) +{ + struct file *prev; + + if ((prev = TAILQ_PREV(file, files, entry)) != NULL) + prev->errors += file->errors; + TAILQ_REMOVE(&files, file, entry); + free(file->name); + free(file); + file = prev; + return (file ? 0 : EOF); +} + +int +parse_conf(const char *filename) +{ + int errors; + + pthgsd->conn_rtry = CONN_RTRY; + pthgsd->iface = NULL; + pthgsd->clt_fptr = clt_do_chk; + + TAILQ_INIT(&pthgsd->thgs); + TAILQ_INIT(&pthgsd->socks); + TAILQ_INIT(&pthgsd->clts); + TAILQ_INIT(&pdthgs->zthgs); + + if ((file = pushfile(filename)) == NULL) + return (-1); + topfile = file; + yyparse(); + errors = file->errors; + popfile(); + return (errors ? -1 : 0); +} + +int +parse_buf(struct clt *pclt, u_char *pkt) +{ + int errors; + + tclt = pclt; + my_fd = tclt->fd; + if ((file = pushbuff(pkt)) == NULL) + return (-1); + topfile = file; + yyparse(); + errors = file->errors; + popbuff(); + return (errors ? -1 : 0); +} + +struct thg * +new_thg(char *name) +{ + struct thg *thg; + + if ((thg = calloc(1, sizeof(*thg))) == NULL) + fatalx("no thg calloc"); + if ((thg->name = strdup(name)) == NULL) + fatalx("no thg name"); + return (thg); +}; blob - /dev/null blob + ea59f6a58db95a7e0fcd6197056cac593251f382 (mode 644) --- /dev/null +++ thingsd/serial.c @@ -0,0 +1,218 @@ +/* + * Copyright (c) 2016-2019 Tracey Emery + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "thingsd.h" + +extern struct dthgs *pdthgs; + +void +open_thgs(struct thgsd *pthgsd, bool reconn) +{ + struct thg *thg; + struct dthg *dthg; + struct termios s_opts; + int fd; + int baudrate = 0, stop = 0; + evbuffercb sockrd = sock_rd; + evbuffercb sockwr = sock_wr; + + TAILQ_FOREACH(thg, &pthgsd->thgs, entry) { + if (thg->exists) + continue; + if (thg->location != NULL) { + thg->type = DEV; + /* + * Just a reminder to set the ownership of your serial + * devices to _thingsd. Otherwise, a disconnected + * and reconnected thing will not be able to + * successfully open(2) the file descriptor. + */ + fd = open(thg->location, O_RDWR | O_NONBLOCK | O_NOCTTY + | O_NDELAY); + if (fd == -1) { + log_info("failed to open %s", thg->location); + if (reconn) + return; + dthg = new_dthg(thg); + pthgsd->exists = true; + pthgsd->dcount++; + thg->fd = -1; + thg->exists = false; + TAILQ_INSERT_TAIL(&pdthgs->zthgs, dthg, entry); + return; + } else { + /* load current s_opts */ + tcgetattr(fd, &s_opts); + /* set baud */ + switch (thg->baud) { + case 50: + baudrate = B50; + break; + case 75: + baudrate = B75; + break; + case 110: + baudrate = B110; + break; + case 134: + baudrate = B134; + break; + case 150: + baudrate = B150; + break; + case 200: + baudrate = B200; + break; + case 300: + baudrate = B300; + break; + case 600: + baudrate = B600; + break; + case 1200: + baudrate = B1200; + break; + case 1800: + baudrate = B1800; + break; + case 2400: + baudrate = B2400; + break; + case 4800: + baudrate = B4800; + break; + case 9600: + baudrate = B9600; + break; + case 19200: + baudrate = B19200; + break; + case 38400: + baudrate = B38400; + break; + case 57600: + baudrate = B57600; + break; + case 76800: + baudrate = B76800; + break; + case 115200: + baudrate = B115200; + break; + } + cfsetispeed(&s_opts, baudrate); + cfsetospeed(&s_opts, baudrate); + /* enable and set local */ + s_opts.c_cflag |= (CLOCAL | CREAD); + /* set data bits */ + if (thg->data_bits != -1) { + s_opts.c_cflag &= ~CSIZE; + switch(thg->data_bits) { + case 5: + stop = CS5; + break; + case 6: + stop = CS6; + break; + case 7: + stop = CS7; + break; + case 8: + stop = CS8; + break; + } + s_opts.c_cflag |= stop; + } + /* set parity */ + if (thg->parity != NULL) { + s_opts.c_cflag &= ~PARENB; + /* enable parity checking */ + if (strcmp(thg->parity, "odd") == 0) { + s_opts.c_cflag |= PARENB; + s_opts.c_cflag |= PARODD; + s_opts.c_iflag |= (INPCK | + ISTRIP); + } else if (strcmp(thg->parity, + "even") == 0) { + s_opts.c_cflag |= PARENB; + s_opts.c_cflag &= ~PARODD; + s_opts.c_iflag |= (INPCK | + ISTRIP); + } + } + /* set stop bits */ + if (thg->stop_bits != -1) { + if (thg->stop_bits == 2) + s_opts.c_cflag |= CSTOPB; + else + s_opts.c_cflag &= ~CSTOPB; + } + /* set hardware control */ + if (thg->hw_ctl == false) { + s_opts.c_cflag &= ~CRTSCTS; + } else { + s_opts.c_cflag |= CRTSCTS; + } + /* set software control */ + if (thg->sw_ctl == false) { + s_opts.c_iflag &= ~(IXON | IXOFF | + IXANY); + } else { + s_opts.c_iflag |= (IXON | IXOFF | + IXANY); + } + /* set input/output as raw */ + s_opts.c_lflag &= ~(ICANON | ECHO | ECHOE | + ISIG); + s_opts.c_oflag &= ~OPOST; + /* Set the new options for the port */ + tcsetattr(fd, TCSANOW, &s_opts); + if ((thg->fd = fd) == '\0') { + log_info("serial device not opened"); + if (reconn) + return; + thg->exists = false; + add_reconn(thg); + return; + } + thg->bev = bufferevent_new(thg->fd, sockrd, + sockwr, sock_err, pthgsd); + bufferevent_base_set(pthgsd->eb, thg->bev); + if (thg->bev == NULL) + fatalx("ipaddr bev error"); + thg->evb = evbuffer_new(); + if (thg->evb == NULL) + fatalx("ipaddr evb error"); + bufferevent_enable(thg->bev, EV_READ|EV_WRITE); + } + if (reconn) { + thg->exists = true; + log_info("reconnected: %s", thg->name); + } + } + } +} blob - /dev/null blob + e778477a08f35d0e09b228c6c7be4731104e4779 (mode 644) --- /dev/null +++ thingsd/sockets.c @@ -0,0 +1,390 @@ +/* + * Copyright (c) 2016-2019 Tracey Emery + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "thingsd.h" + +extern struct dthgs *pdthgs; + +void +create_socks(struct thgsd *pthgsd, bool reconn) +{ + struct thg *thg; + struct sock *sock, *tsock, *conn_sock = NULL; + char *iface = NULL; + int csock, conn_csock; + bool fail = false; + evbuffercb sockrd = sock_rd; + evbuffercb sockwr = sock_wr; + + TAILQ_FOREACH(thg, &pthgsd->thgs, entry) { + if (reconn) { + if (thg->exists) + continue; + if (thg->type == TCP) + goto recreate; + else + continue; + } + sock = new_sock(thg->port); + sock->max_clts += thg->max_clt; + sock->name = thg->name; + if (thg->iface != NULL) + iface = get_ifaddrs(thg->iface); + if (thg->type == DEV) { + if((csock = sock->fd = create_sock(thg->port, iface, + TCP)) == -1) + log_info("fd create socket failed"); + else if (thg->fd != -1) + thg->exists = true; + else { + thg->exists = false; + } + } + if (thg->udp != NULL) { + /* create fd for udp instead of serial device */ + thg->type = UDP; + conn_sock = new_sock(thg->conn_port); + if ((csock = sock->fd = create_sock(thg->port, iface, + TCP)) == -1) + log_info("udp create socket failed"); + else + thg->exists = true; + if ((conn_csock = conn_sock->fd = + create_sock(thg->conn_port, iface, + thg->type)) == -1) + log_info("udp create socket failed"); + else + thg->exists = true; + thg->fd = conn_sock->fd; + } + recreate: + if (thg->ipaddr != NULL) { + thg->type = TCP; + if (thg->persist == 1) { + if ((thg->fd = open_clt_sock(thg->ipaddr, + thg->conn_port)) == -1) { + log_info("ipaddr connection failed"); + if (reconn) + continue; + thg->exists = false; + add_reconn(thg); + } else + thg->exists = true; + if (thg->fd != -1) { + thg->bev = bufferevent_new(thg->fd, + sockrd, sockwr, sock_err, pthgsd); + if (thg->bev == NULL) + fatalx("ipaddr bev error"); + thg->evb = evbuffer_new(); + if (thg->evb == NULL) + fatalx("ipaddr evb error"); + bufferevent_enable(thg->bev, + EV_READ|EV_WRITE); + } + } else + thg->fd = -1; + if (reconn == false) { + if ((csock = sock->fd = create_sock(thg->port, + iface, TCP)) == -1) { + log_info("tcp create socket failed"); + thg->exists = false; + add_reconn(thg); + } else { + if (thg->fd != -1) + thg->exists = true; + } + } + } + if (reconn && thg->exists) { + log_info("reconnected: %s", thg->name); + continue; + } + if (csock == -1 || conn_csock == -1) + fatalx("socket creation failed"); + else if (csock == -2 || conn_csock == -2) { + fail = true; + TAILQ_FOREACH(tsock, &pthgsd->socks, entry) { + if (thg->port == tsock->port) { + fail = false; + break; + } + } + if (fail) + fatalx("can't set socket port"); + else { + log_info(" -socket exists: skipping"); + fail = true; + } + } + if (fail == false) + TAILQ_INSERT_TAIL(&pthgsd->socks, sock, entry); + if (thg->type == UDP) + TAILQ_INSERT_TAIL(&pthgsd->socks, conn_sock, entry); + if (sock->fd > 0) { + event_set(sock->ev, sock->fd, EV_READ|EV_PERSIST, + clt_conn, pthgsd); + if (event_add(sock->ev, NULL)) + fatalx("event add sock"); + } + if (conn_sock != NULL && conn_sock->fd > 0) { + event_set(conn_sock->ev, conn_sock->fd, + EV_READ|EV_PERSIST, udp_evt, pthgsd); + if (event_add(conn_sock->ev, NULL)) + fatalx("event add conn_sock"); + } + } +} + +int +create_sock(int iport, char *iface, int type) +{ + struct addrinfo addr_hints, *addr_res, *loop_res; + char port[6]; + int sock_fd, gai, o_val = 1, flags; + + snprintf(port, sizeof(port), "%d", iport); + memset(&addr_hints, 0, sizeof(addr_hints)); + addr_hints.ai_family = AF_UNSPEC; + switch (type) { + case UDP: + addr_hints.ai_socktype = SOCK_DGRAM; + addr_hints.ai_flags = AI_PASSIVE|AI_ADDRCONFIG; + addr_hints.ai_protocol = 0; + break; + case TCP: + default: + addr_hints.ai_socktype = SOCK_STREAM; + addr_hints.ai_flags |= AI_PASSIVE; + break; + } + if ((gai = getaddrinfo(iface, port, &addr_hints, &addr_res)) != 0) { + fatalx("getaddrinfo failed: %s", gai_strerror(gai)); + return -1; + } + for (loop_res = addr_res; loop_res != NULL; + loop_res = loop_res->ai_next) { + if ((sock_fd = socket(loop_res->ai_family, + loop_res->ai_socktype, loop_res->ai_protocol)) == -1) { + fatalx("unable to create socket"); + return -1; + } + if (setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &o_val, + sizeof(int)) == -1) { + fatalx("setsockopt error"); + freeaddrinfo(addr_res); + return -1; + } + /* non-blocking */ + flags = fcntl(sock_fd, F_GETFL); + flags |= O_NONBLOCK; + fcntl(sock_fd, F_SETFL, flags); + if (bind(sock_fd, loop_res->ai_addr, + loop_res->ai_addrlen) == -1) { + close(sock_fd); + log_warnx("%s%s", "bind address busy\n", + " -checking existing sockets"); + return -2; + } + break; + } + if (loop_res == NULL) { + fatalx("can't bind to port"); + freeaddrinfo(addr_res); + return -1; + } + freeaddrinfo(addr_res); + if (type == TCP) { + if (listen(sock_fd, SOMAXCONN) == -1) { + fatal("unable to listen on socket"); + return -1; + } + } + return sock_fd; +} + +int +open_clt_sock(char *ip_addr, int cport) +{ + struct addrinfo hints, *res, *res0; + int client_fd, error; + char port[6]; + + memset(&hints, 0, sizeof(hints)); + snprintf(port, sizeof(port), "%d", cport); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + error = getaddrinfo(ip_addr, port, &hints, &res0); + if (error) + fatalx("getaddrinfo: %s", gai_strerror(error)); + client_fd = -1; + for (res = res0; res; res = res->ai_next) { + client_fd = socket(res->ai_family, res->ai_socktype, + res->ai_protocol); + if (client_fd == -1) + continue; + if (connect(client_fd, res->ai_addr, res->ai_addrlen) == -1) { + close(client_fd); + client_fd = -1; + continue; + } + break; + } + if (client_fd == -1) + log_warnx("can't connect ip: %s", ip_addr); + freeaddrinfo(res0); + return client_fd; +} + +char * +get_ifaddrs(char *name) +{ + struct ifaddrs *ifap; + struct sockaddr *sa; + char *addr = NULL; + + if (getifaddrs(&ifap) == -1) + fatalx("getifaddrs error"); + while (ifap) { + if ((ifap->ifa_addr) && + ((ifap->ifa_addr->sa_family == AF_INET) || + (ifap->ifa_addr->sa_family == AF_INET6))) { + if (ifap->ifa_addr->sa_family == AF_INET) { + struct sockaddr_in *in = + (struct sockaddr_in *) ifap->ifa_addr; + sa = (struct sockaddr *) in; + } + if (ifap->ifa_addr->sa_family == AF_INET6) { + struct sockaddr_in6 *in6 = + (struct sockaddr_in6*) ifap->ifa_addr; + sa = (struct sockaddr *) in6; + } + if (getnameinfo(sa, sa->sa_len, addr, + sizeof(char) * NI_MAXHOST, NULL, 0, NI_NAMEREQD | + NI_NUMERICHOST)) + log_warnx("getnameinfo error"); + if ((strcmp(name, ifap->ifa_name) == 0) && + addr != '\0') { + freeifaddrs(ifap); + return addr; + } + } + ifap = ifap->ifa_next; + } + freeifaddrs(ifap); + return NULL; +} + +struct sock * +new_sock(int port) +{ + struct sock *sock; + + if ((sock = calloc(1, sizeof(*sock))) == NULL) + fatalx("no sock calloc"); + if ((sock->ev = calloc(1, sizeof(*sock->ev))) == NULL) + fatalx("no sock->ev calloc"); + sock->port = port; + return (sock); +}; + +struct sock * +get_sock(struct thgsd *pthgsd, int val) +{ + struct sock *sock = NULL; + + TAILQ_FOREACH(sock, &pthgsd->socks, entry) { + if (sock->fd == val || sock->port == val) + return sock; + } + return NULL; +} + +void +sock_rd(struct bufferevent *bev, void *arg) +{ + struct thgsd *pthgsd = (struct thgsd *)arg; + struct thg *thg = NULL, *tthg; + struct clt *clt; + size_t len; + int fd = bev->ev_read.ev_fd; + size_t n; + char *pkt; + + TAILQ_FOREACH(tthg, &pthgsd->thgs, entry) { + if (tthg->fd == fd) { + thg = tthg; + break; + } + } + thg->evb = EVBUFFER_INPUT(bev); + len = EVBUFFER_LENGTH(thg->evb); + if ((pkt = calloc(len, sizeof(*pkt))) == NULL) + return; + if (thg->clt_cnt == 0) { + evbuffer_drain(thg->evb, len); + return; + } else + evbuffer_remove(thg->evb, pkt, len); + /* write to clients */ + TAILQ_FOREACH(clt, &pthgsd->clts, entry) { + for (n = 0; n < clt->le; n++) { + if (strcmp(clt->sub_names[n], thg->name) == 0) + bufferevent_write(clt->bev, pkt, len); + } + } + free(pkt); +} + +void +sock_wr(struct bufferevent *bev, void *arg) +{ +} + +void +sock_err(struct bufferevent *bev, short error, void *arg) +{ + struct thgsd *pthgsd = (struct thgsd *)arg; + struct thg *thg = NULL; + int fd = bev->ev_read.ev_fd; + + if ((error & EVBUFFER_ERROR) == 0 || error & EVBUFFER_TIMEOUT) { + TAILQ_FOREACH(thg, &pthgsd->thgs, entry) { + if (thg->fd == fd && thg->persist) { + bufferevent_free(thg->bev); + close(thg->fd); + thg->fd = -1; + thg->exists = false; + add_reconn(thg); + log_info("thing error: %s disconnected", + thg->name); + } + } + } +} blob - /dev/null blob + 9b479d32b5a5b3965a948ec69e6bb40b2d77e9b9 (mode 644) --- /dev/null +++ thingsd/thingsd.8 @@ -0,0 +1,120 @@ +.\" +.\" Copyright (c) 2016-2019 Tracey Emery +.\" +.\" Permission to use, copy, modify, and distribute this software for any +.\" purpose with or without fee is hereby granted, provided that the above +.\" copyright notice and this permission notice appear in all copies. +.\" +.\" THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +.\" WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +.\" MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +.\" ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +.\" WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +.\" ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +.\" OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +.\" +.Dd $Mdocdate: December 19 2018 $ +.Dt THINGSD 8 +.Os +.Sh NAME +.Nm thingsd +.Nd things proxy daemon +.Sh SYNOPSIS +.Nm thingsd +.Bk -words +.Op Fl d +.Ek +.Sh DESCRIPTION +The +.Nm +proxy daemon provides a mechanism for clients and client processes to +communicate with an array of serial and IoT things. At its core, +.Nm +is primarily a packet repeater in that it polls for packets to swap between +subscriber clients and things. However, +.Nm +also provides password control over those connections, including client limits. +.Pp +.Nm +can connect directly to serial things, IoT IP things, and single socket +connections. It also provides for UDP listeners. +.Pp +The options are as follows: +.Bl -tag -width "-f fileXXX" +.It Fl d +Do not daemonize. If this option is specified, +.Nm +will run in the foreground and log to +.Em stderr . +.It Fl v +This option allows +.Nm +to send DEBUG priority messages to syslog. +.El +.Pp +Example things tested: XBee, NF24, ESP8266. +.Pp +Subscribers to a thing pass a simple, human-readable packet to +.Nm . +. The format is as follows, without the line breaks and tabs. +This example is only for initial readability and help in understanding +the format! +.Pp +Subscription packets must begin with 3 * 0x7E +.Bd -literal -offset indent +~~~subscribe{ + {name,"CLIENTNAME"}, + {things{ + thing{"dev1","password1"}, + thing{"dev2","password2"} + } + } +} +.Ed +.Pp +An accurate example packet: +.Bd -literal -offset indent +~~~subscribe{{name,"CLIENTNAME"},{things{thing{"dev1","password1"}}}} +.Ed +.Pp +.Nm +is usually started at boot time, and can be enabled by adding +.Nm +to the +.Va pkg_scripts +line in +.Pa /etc/rc.conf.local . +See +.Xr rc 8 +and +.Xr rc.conf 8 +for more information on the boot process and enabling daemons. +.Pp +When +.Nm +starts up, it reads settings from its configuration file, typically +.Xr thingsd.conf 5 , +and creates sockets and file descriptor connections. +.Sh FILES +.Bl -tag -width "/var/run/thingsdd.sockXXX" -compact +.It Pa /etc/thingsd.conf +Default configuration file. +.It Pa /var/run/thingsd.sock +Socket file for communication with +.Xr thingsctl 8 . +.El +.Sh SEE ALSO +.Xr thingsd.conf 5 , +.Xr thingsctl 8 , +.Xr rc 8 , +.Xr rc.conf 8 +.Sh STANDARDS +.Rs +.Re +.Sh HISTORY +The busybeed program first began development on +.Ox 5.9 . The +.Nm +program refactoring and rename began on +.Ox 6.4 . thingsd name by Matthew Graybosch . + blob - /dev/null blob + 9568051c1559591083d75ddb9e23f13d875a4fed (mode 644) --- /dev/null +++ thingsd/thingsd.c @@ -0,0 +1,260 @@ +/* + * Copyright (c) 2016-2019 Tracey Emery + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "thingsd.h" + +__dead void usage(void); +int main(int, char *[]); +void do_reconn(void); +void thingsd_sighdlr(int, short, void *); +void thingsd_shutdown(struct dthgs *); + +struct thgsd *pthgsd; +struct dthgs *pdthgs; + +__dead void +usage(void) +{ + fprintf(stderr, "usage: %s [-dv]\n", getprogname()); + exit(1); +} + +void +thingsd_sighdlr(int sig, short event, void *arg) +{ + struct dthgs *zdthgs = (struct dthgs *)arg; + + switch (sig) { + case SIGQUIT: + case SIGTERM: + case SIGINT: + case SIGHUP: + thingsd_shutdown(zdthgs); + break; + case SIGPIPE: + /* ignore */ + break; + default: + fatalx("unexpected signal"); + } +} + +int +main(int argc, char *argv[]) +{ + int ch; + struct timeval eb_timeout; + + if ((pthgsd = calloc(1, sizeof(*pthgsd))) == NULL) + fatalx("no thgsd calloc"); + if ((pdthgs = calloc(1, sizeof(*pdthgs))) == NULL) + fatalx("no dthgs calloc"); + + while ((ch = getopt(argc, argv, "dv")) != -1) { + switch (ch) { + case 'd': + pthgsd->debug++; + break; + case 'v': + pthgsd->verbose++; + break; + default: + usage(); + } + } + + /* log to stderr until daemonized */ + log_init(pthgsd->debug ? pthgsd->debug : 1, LOG_DAEMON); + argc -= optind; + if (argc > 0) + usage(); + + if (parse_conf(PATH_CONF)) + fatalx("config parsing failed"); + if (geteuid()) + fatalx("need root privileges"); + + log_init(pthgsd->debug, LOG_DAEMON); + log_setverbose(pthgsd->verbose); + + /* make parent daemon */ + log_procinit("parent"); + if (!pthgsd->debug && daemon(1, 0) == -1) + fatalx("daemon"); + + log_info("%s started", getprogname()); + + pthgsd->eb = event_init(); + pdthgs->run = 1; + + open_thgs(pthgsd, false); + create_socks(pthgsd, false); + + signal_set(&pthgsd->evsigquit, SIGQUIT, thingsd_sighdlr, pdthgs); + signal_set(&pthgsd->evsigterm, SIGTERM, thingsd_sighdlr, pdthgs); + signal_set(&pthgsd->evsigint, SIGINT, thingsd_sighdlr, pdthgs); + signal_set(&pthgsd->evsighup, SIGHUP, thingsd_sighdlr, pdthgs); + + signal_add(&pthgsd->evsigquit, NULL); + signal_add(&pthgsd->evsigterm, NULL); + signal_add(&pthgsd->evsigint, NULL); + signal_add(&pthgsd->evsighup, NULL); + + if ((pthgsd->pw = getpwnam(TH_USER)) != NULL) { + if(setuid(pthgsd->pw->pw_uid) != 0) + err(1, "unable to set user id of %s: %s", TH_USER, + strerror(errno)); + } else + log_info("running as root. %s user not found", TH_USER); + + if (unveil("/dev", "rw") == -1) + err(1, "unveil"); + if (pledge("stdio rpath wpath inet proc tty dns", NULL) == -1) + err(1, "pledge"); + + /* begin thing watchdog */ + eb_timeout.tv_sec = EB_TIMEOUT; + eb_timeout.tv_usec = 0; + + while (pdthgs->run) { + if (pthgsd->exists) { + do_reconn(); + } + event_base_loopexit(pthgsd->eb, &eb_timeout); + event_base_dispatch(pthgsd->eb); + } + + thingsd_shutdown(pdthgs); + return EXIT_SUCCESS; +} + +struct dthg +*new_dthg(struct thg *pthg) +{ + struct dthg *dthg; + + if ((dthg = calloc(1, sizeof(*dthg))) == NULL) + fatalx("no calloc dthg"); + dthg->name = pthg->name; + dthg->type = pthg->type; + dthg->dtime = time(NULL); + return dthg; +} + +void +add_reconn(struct thg *pthg) +{ + struct dthg *dthg; + + dthg = new_dthg(pthg); + pthgsd->exists = true; + pthgsd->dcount++; + TAILQ_INSERT_TAIL(&pdthgs->zthgs, dthg, entry); +} + +void +do_reconn(void) +{ + struct dthg *dthg, *tdthg; + struct thg *thg; + + TAILQ_FOREACH_SAFE(dthg, &pdthgs->zthgs, entry, tdthg) { + if ((size_t)(time(NULL) - dthg->dtime) > + pthgsd->conn_rtry) { + dthg->dtime = time(NULL); + log_info("attempting to reconnect %s", dthg->name); + switch (dthg->type) { + case DEV: + open_thgs(pthgsd, true); + break; + case TCP: + create_socks(pthgsd, true); + break; + } + } + } + TAILQ_FOREACH_SAFE(dthg, &pdthgs->zthgs, entry, tdthg) { + TAILQ_FOREACH(thg, &pthgsd->thgs, entry) { + if (strcmp(thg->name, dthg->name) == 0 && thg->exists) { + TAILQ_REMOVE(&pdthgs->zthgs, dthg, entry); + pthgsd->dcount--; + free(dthg); + return; + } + } + } + if (pthgsd->dcount == 0) + pthgsd->exists = false; +} + +void +thingsd_shutdown(struct dthgs *zdthgs) +{ + struct thg *thg, *tthg; + struct sock *sock, *tsock; + struct clt *clt, *tclt; + struct dthg *dthg, *tdthg; + const char *progname = getprogname(); + + zdthgs->run = 0; + /* clean up things */ + TAILQ_FOREACH_SAFE(thg, &pthgsd->thgs, entry, tthg) { + close(thg->fd); + TAILQ_REMOVE(&pthgsd->thgs, thg, entry); + free(thg); + } + /* clean up dead things */ + TAILQ_FOREACH_SAFE(dthg, &pdthgs->zthgs, entry, tdthg) { + TAILQ_REMOVE(&pdthgs->zthgs, dthg, entry); + free(dthg); + } + /* clean up sockets */ + TAILQ_FOREACH_SAFE(sock, &pthgsd->socks, entry, tsock) { + close(sock->fd); + TAILQ_REMOVE(&pthgsd->socks, sock, entry); + free(sock); + } + /* clean up clts */ + TAILQ_FOREACH_SAFE(clt, &pthgsd->clts, entry, tclt) { + close(clt->fd); + free(clt->sub_names); + TAILQ_REMOVE(&pthgsd->clts, clt, entry); + free(clt); + } + log_info("%s terminated", progname); + event_base_free(pthgsd->eb); + free(pdthgs); + free(pthgsd); + exit(0); +} blob - /dev/null blob + bdcc8630201ad061c841889e445d2a490560cb45 (mode 644) --- /dev/null +++ thingsd/thingsd.conf.5 @@ -0,0 +1,240 @@ +.\" +.\" Copyright (c) 2016-2019 Tracey Emery +.\" +.\" Permission to use, copy, modify, and distribute this software for any +.\" purpose with or without fee is hereby granted, provided that the above +.\" copyright notice and this permission notice appear in all copies. +.\" +.\" THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +.\" WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +.\" MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +.\" ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +.\" WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +.\" ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +.\" OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +.\" +.Dd $Mdocdate: December 19 2018 $ +.Dt THINGSD.CONF 5 +.Os +.Sh NAME +.Nm thingsd.conf +.Nd thingsd daemon configuration file +.Sh DESCRIPTION +.Nm +is the configuration file for the things proxy daemon, +.Xr thingsd 8 . +.Sh SECTIONS +.Nm +is divided into two main sections: +.Bl -tag -width xxxx +.It Sy Global Configuration +Global settings for +.Xr thingsd 8 . +Do note that global settings should never be placed after the things section +has been defined. +.It Sy things +things are the configuration areas for each thing a client can communicate +with. +.El +.Pp +The current line can be extended over multiple lines using a backslash +.Pq Sq \e . +Comments can be put anywhere in the file using a hash mark +.Pq Sq # , +and extend to the end of the current line. +Care should be taken when commenting out multi-line text: +the comment is effective until the end of the entire block. +.Pp +Argument names not beginning with a letter, digit, or underscore +must be quoted. +.Ed +.Sh GLOBAL CONFIGURATION +Here are the settings that can be set globally: +.Bl -tag -width Ds +.It Ic default port Ar number +Set the default port for things to communicate on. This is a required setting. +.It Ic bind interface Ar string +Specify a single interface to create sockets on. If this is not set, +.Xr thingsd 8 +will attempt to open the default port on all network interfaces. +.It Ic max clients Ar number +Set the default maximum number of clients allowed to connect to each +.Xr thingsd 8 thing. +.It Ic max subscriptions Ar number +Set the maximum number of things a client can subscribe to at a time. +.It Ic connection retry Ar number +Set the lost connection thing watchdog interval. Default is 30 +seconds. Range is 30-600 seconds. +.It Ic log verbose Ar number +Turn on verbose logging. (This option is currently disabled.) +.El +.Sh thingS +things represent a serial thing or a TCP/IP host for +.Xr thingsd 8 +to communicate with. +.Xr thingsd 8 +will setup sockets and bind to things depending on the settings for each +thing. +.Bl -tag -width Ds +.It Ic baud Ar number +Set the baud rate for a serial thing +.Ar location . +.It Ic bind interface Ar string +Specify a single interface to create a +.Ar location +or +.Ar ipaddr +thing socket. +.It Ic data Ar number +Set the data bits for a serial thing +.Ar location . +.It Ic connect on port Ar number +Set the TCP/IP port to connect to for an +.Ar ipaddr +thing. This setting is required for +.Ar ipaddr +things. +.It Ic thing Ar string Brq ... +Declaration of a thing for +.Xr thingsd 8 +to setup and the name +.Xr thingsd 8 +will use for client subscriptions. +.It Ic hardware Ar number +Set to 1 to turn on hardware control for a serial thing +.Ar location . +OpenBSD doesn't use this. It's commented out in +.Xr thingsd 8 . +.It Ic ipaddr Ar string Brq ... +Create a +.Ar thing +connection to an IPV4 hostname or IP address. IPV6 is not implemented yet. +.It Ic listen on port Ar number +Set a local socket port for a +.Ar location , +.Ar udp , +or +.Ar ipaddr +thing, other than the global default port. +.It Ic location Ar string Brq ... +Create a +.Ar thing +connection to serial interface. These are any valid /dev things, for example +/dev/ttyU0. +.It Ic max clients Ar number +Set the maximum clients allowed to connect to a thing +.Ar location +or +.Ar ipaddr . +.It Ic parity Ar string +Set the parity for a serial thing +.Ar location . +Parity options are none, odd, even, or space. +.It Ic password Ar string +Set the subscription password for a thing +.Ar location +or +.Ar ipaddr . +.It Ic persistent Ar number +Set whether +.Xr thingsd 8 +binds to an +.Ar ipaddr +thing. If +.Ar persistent +is set to 0, +.Xr thingsd 8 +will create a socket, send a client packet, and close that socket. Clients +cannot receive on a non-persistent +.Ar ipaddr +thing. +.It Ic receive on port Ar number +Set the +.Ar udp +port to listen on for a UDP packet. This setting is required for +.Ar udp +things. +.It Ic software Ar number +Set to 1 to turn on software control for a serial thing +.Ar location . +.It Ic stop Ar number +Set the stop bit for a serial thing +.Ar location . +.It Ic udp Ar string Brq ... +Create a +.Ar thing +which listens for user datagram protocol packets. + +.El +.Sh FILES +.Bl -tag -width Ds -compact +.It Pa /etc/thingsd.conf +.Xr thingsd 8 +configuration file. +.El +.Sh EXAMPLES +This configuration file would create a serial thing and a TCP/IP host thing. +The serial thing would communicate on the default port, while the local network +ipaddr thing would communicate on a separate port. +.Bd -literal -offset indent + +# +# Global Options +# + +default port 50000 + +max clients 10 + +max suscriptions 5 + +thing "serial_thing" { + location "/dev/ttyU0" { + baud 9600 + max clients 1 + data 8 + parity "none" + stop 1 + #no password required for our one allowed client + } +} + +thing "ipaddr_thing" { + ipaddr "10.0.0.1" { + connect on port 8080 + listen on port 50010 + password "password" + } +} + +thing "udp_thing" { + udp "my_name" { + receive on port 8095 + listen on port 50010 + password "password" + } +} +.Ed +.Pp +.Sh SEE ALSO +.Xr thingsctl 8 , +.Xr thingsd 8 +.Sh HISTORY +The +.Nm +file format first appeared with busybeed developed on +.Ox 5.9 . +.Sh AUTHORS +.An -nosplit +The +.Xr thingsd 8 +program was written by +.An Tracey Emery Aq Mt tracey@traceyemery.com , +with extensive reading and perusing of +.Xr ntpd 8 +and +.Xr relayd 8 . +Thank you to the real programmers who came before me. +.Sh CAVEATS +.Xr thingsd 8 +None yet. blob - /dev/null blob + d320e7a144da300ba5fcc0eb98a0eedcf1b6009c (mode 644) --- /dev/null +++ thingsd/thingsd.h @@ -0,0 +1,200 @@ +/* + * Copyright (c) 2016-2019 Tracey Emery + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#ifndef _THINGSD_H +#define _THINGSD_H + +#include +#include + +#include +#include +#include +#include + +#define PATH_CONF "/etc/thingsd.conf" +#define TH_USER "_thingsd" +#define CONN_RTRY 30 +#define MIN_RTRY 10 +#define MAX_RTRY 600 +#define DEFAULT_BAUD 9600 +#define CLT_SUB_TIME 5 +#define BUFF 1024 +#define DTHG_CHK 2 +#define EB_TIMEOUT 10 + +enum socktypes { + TCP, + UDP, + DEV +}; + +struct dthgs { + TAILQ_HEAD(zthgs, dthg) zthgs; + volatile sig_atomic_t run; +}; + +struct dthg { + TAILQ_ENTRY(dthg) entry; + char *name; + int type; + time_t dtime; +}; + +struct thg { + TAILQ_ENTRY(thg) entry; + struct bufferevent *bev; + struct evbuffer *evb; + bool exists; + bool hw_ctl; + bool persist; + bool sw_ctl; + char *iface; + char *ipaddr; + char *name; + char *parity; + char *password; + char *location; + char *udp; + int fd; + int baud; + int conn_port; + int data_bits; + int max_clt; + int port; + int stop_bits; + int type; + size_t clt_cnt; +}; + +struct sock { + TAILQ_ENTRY(sock) entry; + struct event *ev; + struct bufferevent *bev; + struct evbuffer *evb; + char *name; + int fd; + int port; + size_t clt_cnt; + size_t max_clts; +}; + +struct clt { + TAILQ_ENTRY(clt) entry; + struct evbuffer *evb; + struct bufferevent *bev; + struct sock *sock; + bool subscribed; + char *name; + char **sub_names; + int fd; + int port; + time_t join_time; + size_t le; + size_t subs; +}; + +struct thgsd { + /* things things */ + TAILQ_HEAD(thgs, thg) thgs; + TAILQ_HEAD(socks, sock) socks; + TAILQ_HEAD(clts, clt) clts; + struct event_base *eb; + struct passwd *pw; + char *iface; + int max_clt; + int port; + size_t debug; + size_t clt_cnt; + size_t conn_rtry; + size_t max_sub; + size_t verbose; + void (*clt_fptr)(struct thgsd *); + + /* disconnected things parts */ + bool exists; + int dcount; + + /* signal handlers */ + struct event evsigquit; + struct event evsigterm; + struct event evsigint; + struct event evsighup; +}; + +/* thingsd.c */ +struct dthg *new_dthg(struct thg *); +void add_reconn(struct thg *); + +/* parse.y */ +struct thg *new_thg(char *); +int parse_conf(const char *); +int parse_buf(struct clt *, u_char *); + +/* serial.c */ +void open_thgs(struct thgsd *, bool); + +/* sockets.c */ +struct sock *new_sock(int); +struct sock *get_sock(struct thgsd *, int); +char *get_ifaddrs(char *); +void create_socks(struct thgsd *, bool); +void sock_rd(struct bufferevent *, void *); +void sock_wr(struct bufferevent *, void *); +void sock_err(struct bufferevent *, short, void *); +int create_sock(int, char *, int); +int open_clt_sock(char *, int); + +/* things.c */ +pid_t thgs_main(struct thgsd *, const char *); + +/* events.c */ +void udp_evt(int, short, void *); + +/* client.c */ +void clt_conn(int, short, void *); +void clt_del(struct thgsd *, struct clt *); +void clt_rd(struct bufferevent *, void *); +void clt_wr(struct bufferevent *, void *); +void clt_err(struct bufferevent *, short, void *); +void start_clt_chk(struct thgsd *); +void *clt_chk(void *); +void clt_do_chk(struct thgsd *); +void clt_wr_thgs(struct clt *, struct thg *, + size_t); + +/* log.c */ +void log_init(int, int); +void log_procinit(const char *); +void log_setverbose(int); +int log_getverbose(void); +void log_warn(const char *, ...) + __attribute__((__format__ (printf, 1, 2))); +void log_warnx(const char *, ...) + __attribute__((__format__ (printf, 1, 2))); +void log_info(const char *, ...) + __attribute__((__format__ (printf, 1, 2))); +void log_debug(const char *, ...) + __attribute__((__format__ (printf, 1, 2))); +void logit(int, const char *, ...) + __attribute__((__format__ (printf, 2, 3))); +void vlog(int, const char *, va_list) + __attribute__((__format__ (printf, 2, 0))); +__dead void fatal(const char *, ...) + __attribute__((__format__ (printf, 1, 2))); +__dead void fatalx(const char *, ...) + __attribute__((__format__ (printf, 1, 2))); +#endif /* _THINGSD_H */