commit 454c547f3a69f214aac910def7487fd3fee914cd from: Tracey Emery via: GitHub date: Sun Jul 26 19:48:47 2020 UTC Merge pull request #1 from basepr1me/proc_version Merge proc_version branch commit - 24ffb139191238b206dc06c73aa1d9e62b84e1a7 commit + 454c547f3a69f214aac910def7487fd3fee914cd blob - /dev/null blob + 800796731efe95a67428f1ab1ca7860a9683ca08 (mode 644) --- /dev/null +++ .gitignore @@ -0,0 +1,9 @@ +**/obj +**/*.d +**/*.o +.gitignore +**/.gitignore +**/parse.c +**/parse.h +thingsd/thingsd +thingsctl/thingsctl blob - d89a0719982d2c21c3220c149107c0e8722c252f blob + 1a8e1b5d5c75495eb0dce4e6fce1fb30a6928171 --- thingsctl/Makefile +++ thingsctl/Makefile @@ -2,9 +2,9 @@ PROG= thingsctl SRCS+= thingsctl.c parser.c -INC_C_DIR= /usr/local -BINDIR?= ${INC_C_DIR}/sbin -MANDIR?= ${INC_C_DIR}/man/man +PREFIX= /usr/local +BINDIR?= ${PREFIX}/sbin +MANDIR?= ${PREFIX}/man/man LDADD= -lutil CFLAGS+= -Wall -I${.CURDIR} blob - 431c0514f82264890bbc3db82575a9933bc7b0ee blob + 22a2e411f40c066e961c8c972579b1b260cb9994 --- thingsctl/parser.c +++ thingsctl/parser.c @@ -20,25 +20,27 @@ #include #include #include -#include #include #include #include #include #include +#include #include #include #include +#include "proc.h" #include "thingsd.h" #include "parser.h" enum token_type { NOTOKEN, ENDTOKEN, - KEYWORD, - CLTNAME, - THGNAME, + CLIENTNAME, + SOCKETNAME, + THINGNAME, + KEYWORD }; struct token { @@ -48,44 +50,74 @@ struct token { const struct token *next; }; -static const struct token t_main[]; -static const struct token t_log[]; static const struct token t_list[]; -static const struct token t_ctl_name[]; -static const struct token t_thg_name[]; +static const struct token t_log[]; +static const struct token t_main[]; +static const struct token t_show[]; +static const struct token t_client_name[]; +static const struct token t_kill_name[]; +static const struct token t_thing_name[]; +static const struct token t_socket_name[]; +static const struct token t_pkt_thing[]; static const struct token t_main[] = { - {KEYWORD, "list", NONE, t_list}, + {KEYWORD, "echo", SHOW_PACKETS, t_pkt_thing}, + {KEYWORD, "kill", NONE, t_kill_name}, + {KEYWORD, "list", LIST, t_list}, {KEYWORD, "log", NONE, t_log}, - {KEYWORD, "kill", KILL_CLT, t_ctl_name}, - {KEYWORD, "show", SHOW_PKTS, t_thg_name}, + {KEYWORD, "reload", RELOAD, NULL}, + {KEYWORD, "show", SHOW, t_show}, {ENDTOKEN, "", NONE, NULL} }; static const struct token t_log[] = { + {KEYWORD, "brief", LOG_BRIEF, NULL}, {KEYWORD, "debug", LOG_DEBUG, NULL}, {KEYWORD, "verbose", LOG_VERBOSE, NULL}, - {KEYWORD, "brief", LOG_BRIEF, NULL}, {ENDTOKEN, "", NONE, NULL} }; static const struct token t_list[] = { - {KEYWORD, "clients", LIST_CLTS, NULL}, - {KEYWORD, "things", LIST_THGS, NULL}, - {KEYWORD, "sockets", LIST_SOCKS, NULL}, - {ENDTOKEN, "", NONE, NULL} + {KEYWORD, "clients", LIST_CLIENTS, NULL}, + {KEYWORD, "sockets", LIST_SOCKETS, NULL}, + {KEYWORD, "things", LIST_THINGS, NULL}, + {ENDTOKEN, "", NONE, NULL} }; -static const struct token t_ctl_name[] = { - {CLTNAME, "", NONE, NULL}, - {ENDTOKEN, "", NONE, NULL} +static const struct token t_show[] = { + {KEYWORD, "client", NONE, t_client_name}, + {KEYWORD, "control", SHOW_CONTROL, NULL}, + {KEYWORD, "parent", SHOW_PARENT, NULL}, + {KEYWORD, "socket", NONE, t_socket_name}, + {KEYWORD, "thing", NONE, t_thing_name}, + {ENDTOKEN, "", NONE, NULL} }; -static const struct token t_thg_name[] = { - {THGNAME, "", NONE, NULL}, - {ENDTOKEN, "", NONE, NULL} +static const struct token t_thing_name[] = { + {THINGNAME, "", LIST_THINGS, NULL}, + {ENDTOKEN, "", NONE, NULL} }; +static const struct token t_client_name[] = { + {CLIENTNAME, "", LIST_CLIENTS, NULL}, + {ENDTOKEN, "", NONE, NULL} +}; + +static const struct token t_kill_name[] = { + {CLIENTNAME, "", KILL_CLIENT, NULL}, + {ENDTOKEN, "", NONE, NULL} +}; + +static const struct token t_socket_name[] = { + {SOCKETNAME, "", LIST_SOCKETS, NULL}, + {ENDTOKEN, "", NONE, NULL} +}; + +static const struct token t_pkt_thing[] = { + {THINGNAME, "", NONE, NULL}, + {ENDTOKEN, "", NONE, NULL} +}; + static const struct token *match_token(const char *, const struct token *, struct parse_result *); static void show_valid_args(const struct token *); @@ -127,6 +159,7 @@ static const struct token * match_token(const char *word, const struct token *table, struct parse_result *res) { + size_t n; u_int i, match; const struct token *t = NULL; @@ -140,6 +173,22 @@ match_token(const char *word, const struct token *tabl t = &table[i]; } break; + case THINGNAME: + case CLIENTNAME: + case SOCKETNAME: + if (!match && word != NULL && strlen(word) > 0) { + memset(res->name, 0, + sizeof(res->name)); + n = strlcpy(res->name, word, + sizeof(res->name)); + if (n >= sizeof(res->name)) + err(1, "name too long"); + match++; + t = &table[i]; + if (t->value) + res->action = t->value; + } + break; case KEYWORD: if (word != NULL && strncmp(word, table[i].keyword, strlen(word)) == 0) { @@ -149,20 +198,6 @@ match_token(const char *word, const struct token *tabl res->action = t->value; } break; - case CLTNAME: - if (!match && word != NULL && strlen(word) > 0) { - res->clt_name = strdup(word); - match++; - t = &table[i]; - } - break; - case THGNAME: - if (!match && word != NULL && strlen(word) > 0) { - res->thg_name = strdup(word); - match++; - t = &table[i]; - } - break; case ENDTOKEN: break; } @@ -191,15 +226,18 @@ show_valid_args(const struct token *table) case NOTOKEN: fprintf(stderr, " \n"); break; + case THINGNAME: + fprintf(stderr, " \n"); + break; + case SOCKETNAME: + fprintf(stderr, " \n"); + break; + case CLIENTNAME: + fprintf(stderr, " \n"); + break; case KEYWORD: fprintf(stderr, " %s\n", table[i].keyword); break; - case CLTNAME: - fprintf(stderr, " \n"); - break; - case THGNAME: - fprintf(stderr, " \n"); - break; case ENDTOKEN: break; } blob - fb5db2d2af3a2db8d1c598d0a671d12b145a93f3 blob + 4a71ae5857fad0e1bae5314e2de781e9dedeaa45 --- thingsctl/parser.h +++ thingsctl/parser.h @@ -17,20 +17,24 @@ enum actions { NONE, + KILL_CLIENT, + LIST, + LIST_CLIENTS, + LIST_SOCKETS, + LIST_THINGS, + LOG_BRIEF, LOG_DEBUG, LOG_VERBOSE, - LOG_BRIEF, - LIST_CLTS, - LIST_THGS, - LIST_SOCKS, - KILL_CLT, - SHOW_PKTS, + RELOAD, + SHOW, + SHOW_CONTROL, + SHOW_PACKETS, + SHOW_PARENT, }; struct parse_result { - char *clt_name; - char *thg_name; - enum actions action; + enum actions action; + char name[THINGSD_MAXNAME]; }; struct parse_result *parse(int, char *[]); blob - a61c6268de48d7570eaed8b9ecbb79082c02a396 blob + 163c4341b7e9445c742f1acf71e5391c6f176492 --- thingsctl/thingsctl.8 +++ thingsctl/thingsctl.8 @@ -44,6 +44,12 @@ to communicate with .Pp The following commands are available: .Bl -tag -width Ds +.It Cm echo Ar string +Echo a thing's packets by its name. +A thing could be sending hostile data! +Use at your own risk. +.It Cm kill Ar string +Disconnect a subscribed client from thingsd by client name. .It Cm list clients Show all clients connected to things. .It Cm list sockets @@ -57,13 +63,16 @@ Disable verbose logging. Enable verbose logging. .It Cm log debug Enable very noisy debug logging. -.It Cm kill Ar string -Disconnect a subscribed client from thingsd by client name. -.It Cm show Ar string -View string version of a thing's packets by its name. -Showing packets blocks all other calls. -A thing could be sending binary data! -Use at your own risk. +.It Cm show client Ar string +Show the data for a single client by name. +.It Cm show control +Return control process logging verbosity. +.It Cm show parent +Return parent process logging verbosity. +.It Cm show socket Ar string +Show the data for a single socket by name. +.It Cm show thing Ar string +Show the data for a single thing by name. .El .Sh FILES .Bl -tag -width "/var/run/thingsd.sockXX" -compact @@ -75,8 +84,3 @@ socket used for communication with .Sh SEE ALSO .Xr thingsd.conf 5 , .Xr thingsd 8 -.Sh HISTORY -The -.Nm -program first appeared in -.Ox 6.5 . blob - ebf1f89e9b0a3fbe0507873680fdddc97eacc91f blob + 655da0ab34ce892b14d8c19f9560e1c200d4110a --- thingsctl/thingsctl.c +++ thingsctl/thingsctl.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019 - 2020 Tracey Emery + * Copyright (c) 2019, 2020 Tracey Emery * Copyright (c) 2005 Claudio Jeker * Copyright (c) 2004, 2005 Esben Norby * Copyright (c) 2003 Henning Brauer @@ -23,7 +23,6 @@ #include #include #include -#include #include #include @@ -31,21 +30,24 @@ #include #include #include +#include #include #include #include #include +#include "proc.h" #include "thingsd.h" #include "parser.h" -__dead void usage(void); -int show_list_msg(struct imsg *); -void print_clts(struct clt_imsg *); -void print_thgs(struct thg_imsg *); -void print_socks(struct sock_imsg *); +__dead void usage(void); +int list_things_msg(struct imsg *); +int list_clients_msg(struct imsg *); +int list_sockets_msg(struct imsg *); +int show_parent_msg(struct imsg *); +int show_control_msg(struct imsg *); -struct imsgbuf *ibuf; +struct imsgbuf *ibuf; __dead void usage(void) @@ -66,13 +68,10 @@ main(int argc, char *argv[]) int ctl_sock; int done = 0; int n, verbose = 0; - int ch; - int type; - char *sockname, *ctl_pkt; + int ch, v = 0; + char *sockname, *ctl_pkt = NULL; - sockname = strdup(THINGSD_SOCK); - if (sockname == NULL) - err(1, "strdup"); + sockname = THINGSD_SOCKET; while ((ch = getopt(argc, argv, "s:")) != -1) { switch (ch) { case 's': @@ -108,13 +107,13 @@ main(int argc, char *argv[]) imsg_init(ibuf, ctl_sock); done = 0; - /* Check for root-only actions */ + /* Check for root only actions */ switch (res->action) { case LOG_DEBUG: case LOG_VERBOSE: case LOG_BRIEF: - case KILL_CLT: - case SHOW_PKTS: + case KILL_CLIENT: + case SHOW_PACKETS: if (geteuid() != 0) errx(1, "need root privileges"); break; @@ -124,45 +123,72 @@ main(int argc, char *argv[]) /* Process user request. */ switch (res->action) { - case SHOW_PKTS: - imsg_compose(ibuf, IMSG_SHOW_PKTS, 0, 0, -1, - res->thg_name, strlen(res->thg_name)); - free(res->thg_name); - break; - case KILL_CLT: - imsg_compose(ibuf, IMSG_KILL_CLT, 0, 0, -1, - res->clt_name, strlen(res->clt_name)); - printf("kill request for client \"%s\" sent\n", res->clt_name); - free(res->clt_name); + case KILL_CLIENT: + imsg_compose(ibuf, IMSG_KILL_CLIENT, 0, 0, -1, + res->name, strlen(res->name)); + printf("\nKill request sent for client '%s'.\n", res->name); done = 1; break; + case LIST_CLIENTS: + imsg_compose(ibuf, IMSG_GET_INFO_CLIENTS_REQUEST, 0, + 0, -1, res->name, sizeof(res->name)); + break; + case LIST_SOCKETS: + imsg_compose(ibuf, IMSG_GET_INFO_SOCKETS_REQUEST, 0, + 0, -1, res->name, sizeof(res->name)); + break; + case LIST_THINGS: + imsg_compose(ibuf, IMSG_GET_INFO_THINGS_REQUEST, 0, + 0, -1, res->name, sizeof(res->name)); + break; case LOG_DEBUG: - verbose |= L_VERBOSE2; + verbose++; /* FALLTHROUGH */ case LOG_VERBOSE: - verbose |= L_VERBOSE1; + verbose++; /* FALLTHROUGH */ case LOG_BRIEF: - imsg_compose(ibuf, IMSG_THGS_LOG_VERBOSE, 0, 0, -1, + imsg_compose(ibuf, IMSG_CTL_VERBOSE, 0, 0, -1, &verbose, sizeof(verbose)); - printf("logging request sent\n"); + printf("\nLogging request sent.\n"); done = 1; break; - case LIST_CLTS: - type = THGS_LIST_CLTS; - imsg_compose(ibuf, IMSG_THGS_LIST, 0, 0, -1, &type, - sizeof(type)); + case SHOW_CONTROL: + imsg_compose(ibuf, IMSG_GET_INFO_CONTROL_REQUEST, 0, + 0, -1, NULL, 0); break; - case LIST_THGS: - type = THGS_LIST_THGS; - imsg_compose(ibuf, IMSG_THGS_LIST, 0, 0, -1, &type, - sizeof(type)); + case SHOW_PACKETS: + printf("\nEchoing thing packets may have unexcpected "); + printf("consequences!\n"); + printf("Are you sure you want to echo packets? (y|n) "); + ch = getchar(); + if (ch == 'y' || ch == 'Y') { + printf("Waiting for incoming packets\n"); + imsg_compose(ibuf, IMSG_SHOW_PACKETS_REQUEST, 0, + 0, -1, res->name, sizeof(res->name)); + } else + printf("Echo packets ignored\n"); + printf("\n"); break; - case LIST_SOCKS: - type = THGS_LIST_SOCKS; - imsg_compose(ibuf, IMSG_THGS_LIST, 0, 0, -1, &type, - sizeof(type)); + case SHOW_PARENT: + imsg_compose(ibuf, IMSG_GET_INFO_PARENT_REQUEST, 0, + 0, -1, NULL, 0); break; + case RELOAD: + printf("\nAll things and sockets will be reset.\n"); + printf("This can have unintended consequences!\n"); + printf("For example, all clients will have to reconnect.\n\n"); + printf("Are you sure you want to reload the config? (y|n) "); + ch = getchar(); + if (ch == 'y' || ch == 'Y') { + imsg_compose(ibuf, IMSG_CTL_RESET, 0, 0, -1, &v, + sizeof(v)); + printf("Reload request sent\n"); + } else + printf("Reload request ignored\n"); + printf("\n"); + done = 1; + break; default: usage(); } @@ -170,6 +196,7 @@ main(int argc, char *argv[]) while (ibuf->w.queued) if (msgbuf_write(&ibuf->w) <= 0 && errno != EAGAIN) err(1, "write error"); + while (!done) { if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN) errx(1, "imsg_read error"); @@ -183,26 +210,38 @@ main(int argc, char *argv[]) break; switch (res->action) { - case SHOW_PKTS: - if (imsg.hdr.type == IMSG_CTL_END) { + case LIST_CLIENTS: + done = list_clients_msg(&imsg); + break; + case LIST_SOCKETS: + done = list_sockets_msg(&imsg); + break; + case LIST_THINGS: + done = list_things_msg(&imsg); + break; + case SHOW_CONTROL: + done = show_control_msg(&imsg); + break; + case SHOW_PACKETS: + if (imsg.hdr.type == + IMSG_SHOW_PACKETS_END_DATA) { done = 1; break; } - if ((ctl_pkt = calloc(IMSG_DATA_SIZE(imsg), + if ((ctl_pkt = calloc(IMSG_DATA_SIZE(&imsg), sizeof(*ctl_pkt))) == NULL) errx(1, "calloc ctl_pkt"); if ((ctl_pkt = strndup(imsg.data, - IMSG_DATA_SIZE(imsg))) == NULL) { + IMSG_DATA_SIZE(&imsg))) == NULL) { free(ctl_pkt); break; } printf("%s\n", ctl_pkt); free(ctl_pkt); + ctl_pkt = NULL; break; - case LIST_CLTS: - case LIST_THGS: - case LIST_SOCKS: - done = show_list_msg(&imsg); + case SHOW_PARENT: + done = show_parent_msg(&imsg); break; default: break; @@ -210,117 +249,183 @@ main(int argc, char *argv[]) imsg_free(&imsg); } } + printf("\n"); close(ctl_sock); + free(ctl_pkt); free(ibuf); - free(sockname); return (0); } int -show_list_msg(struct imsg *imsg) +show_parent_msg(struct imsg *imsg) { - struct clt_imsg *comp_clt; - struct thg_imsg *comp_thg; - struct sock_imsg *comp_sock; + struct thingsd_parent_info *npi; switch (imsg->hdr.type) { - case IMSG_LIST_CLTS: - comp_clt = (struct clt_imsg *)imsg->data; - print_clts(comp_clt); + case IMSG_GET_INFO_PARENT_DATA: + npi = imsg->data; + printf("\nParent says: Logging level is "); + if (npi->verbose == 2) + printf("debug"); + else if (npi->verbose == 1) + printf("verbose"); + else + printf("brief"); + printf(" (%d).\n", npi->verbose); break; - case IMSG_LIST_THGS: - comp_thg = (struct thg_imsg *)imsg->data; - print_thgs(comp_thg); + case IMSG_GET_INFO_PARENT_END_DATA: + return (1); + default: break; - case IMSG_LIST_SOCKS: - comp_sock = (struct sock_imsg *)imsg->data; - print_socks(comp_sock); + } + + return (0); +} + +int +show_control_msg(struct imsg *imsg) +{ + struct thingsd_control_info *nci; + + switch (imsg->hdr.type) { + case IMSG_GET_INFO_CONTROL_DATA: + nci = imsg->data; + printf("\nControl says: Logging level is "); + if (nci->verbose == 2) + printf("debug"); + else if (nci->verbose == 1) + printf("verbose"); + else + printf("brief"); + printf(" (%d).\n", nci->verbose); break; - case IMSG_CTL_END: + case IMSG_GET_INFO_CONTROL_END_DATA: return (1); default: break; } + return (0); } -void -print_clts(struct clt_imsg *pclts) +int +list_things_msg(struct imsg *imsg) { - if (pclts->subscribed == false) - return; + struct thing *nti; - printf("Client Name:\t\t\t%s\n", pclts->name); - printf("\tfd:\t\t\t%d\n", pclts->fd); - printf("\tPort:\t\t\t%d\n", pclts->port); - if (pclts->tls == true) - printf("\tTLS:\t\t\tyes\n"); - printf("\tSubscriptions:\t\t%zu\n", pclts->subs); + switch (imsg->hdr.type) { + case IMSG_GET_INFO_THINGS_DATA: + nti = (struct thing *) imsg->data; + + printf("\nThing Name:\t\t\t%s\n", nti->name); + switch(nti->type) { + case TCP: + printf("\tIP Addr:\t\t%s\n", nti->ipaddr); + printf("\tConnect Port:\t\t%d\n", nti->conn_port); + printf("\tPersists:\t\t%d\n", nti->persist); + break; + case UDP: + printf("\tUDP Listener:\t\t%s\n", nti->udp); + printf("\tConnect Port:\t\t%d\n", nti->rcv_port); + break; + case DEV: + printf("\tDevice:\t\t\t%s\n", nti->location); + printf("\tBaud:\t\t\t%d\n", nti->baud); + printf("\tData:\t\t\t%d\n", nti->data_bits); + printf("\tStop:\t\t\t%d\n", nti->stop_bits); + printf("\tHardware:\t\t%d\n", nti->hw_ctl); + printf("\tSoftware:\t\t%d\n", nti->sw_ctl); + printf("\tParity:\t\t\t%s\n", nti->parity); + break; + } + if (strncmp(nti->iface, "", PKT_BUFF) == 0) + printf("\tBind Interface:\t\tall\n"); + else + printf("\tBind Interface:\t\t%s\n", nti->iface); + printf("\tListen Port:\t\t%d\n", nti->port); + if (nti->max_clients == 0) + printf("\tMax Clients:\t\tunlimited\n"); + else + printf("\tMax Clients:\t\t%d\n", nti->max_clients); + printf("\tPassword:\t\t%s\n", nti->password); + printf("\tClient Count:\t\t%zu\n", nti->client_cnt); + if (nti->tls == false) + break; + printf("\tTLS:\t\t\t%d\n", nti->tls); + printf("\tCert:\t\t\t%s\n", nti->tls_cert_file); + printf("\tKey:\t\t\t%s\n", nti->tls_key_file); + printf("\tCA:\t\t\t%s\n", nti->tls_ca_file); + printf("\tCRL:\t\t\t%s\n", nti->tls_crl_file); + printf("\tOCSP:\t\t\t%s\n", nti->tls_ocsp_staple_file); + + break; + case IMSG_GET_INFO_THINGS_END_DATA: + return (1); + default: + break; + } + + return (0); } -void -print_thgs(struct thg_imsg *pthgs) +int +list_clients_msg(struct imsg *imsg) { - if (pthgs->exists == false) - return; + struct client *nci; - printf("Thing Name:\t\t\t%s\n", pthgs->name); - switch(pthgs->type) { - case TCP: - printf("\tIP Addr:\t\t%s\n", pthgs->ipaddr); - printf("\tConnect Port:\t\t%d\n", pthgs->conn_port); - printf("\tPersists:\t\t%d\n", pthgs->persist); + switch (imsg->hdr.type) { + case IMSG_GET_INFO_CLIENTS_DATA: + nci = (struct client *) imsg->data; + + if (nci->subscribed == false) + break; + + printf("\nClient Name:\t\t\t%s\n", nci->name); + printf("\tfd:\t\t\t%d\n", nci->fd); + printf("\tPort:\t\t\t%d\n", nci->port); + if (nci->tls == true) + printf("\tTLS:\t\t\tyes\n"); + printf("\tSubscriptions:\t\t%zu\n", nci->subs); break; - case UDP: - printf("\tUDP Listener:\t\t%s\n", pthgs->udp); - printf("\tConnect Port:\t\t%d\n", pthgs->conn_port); + case IMSG_GET_INFO_CLIENTS_END_DATA: + return (1); + default: break; - case DEV: - printf("\tDevice:\t\t\t%s\n", pthgs->location); - printf("\tBaud:\t\t\t%d\n", pthgs->baud); - printf("\tData:\t\t\t%d\n", pthgs->data_bits); - printf("\tStop:\t\t\t%d\n", pthgs->stop_bits); - printf("\tHardware:\t\t%d\n", pthgs->hw_ctl); - printf("\tSoftware:\t\t%d\n", pthgs->sw_ctl); - printf("\tParity:\t\t\t%s\n", pthgs->parity); - break; } - if (strncmp(pthgs->iface, "", BUFF) == 0) - printf("\tBind Interface:\t\tall\n"); - else - printf("\tBind Interface:\t\t%s\n", pthgs->iface); - printf("\tListen Port:\t\t%d\n", pthgs->port); - if (pthgs->max_clt == 0) - printf("\tMax Clients:\t\tunlimited\n"); - else - printf("\tMax Clients:\t\t%d\n", pthgs->max_clt); - printf("\tPassword:\t\t%s\n", pthgs->password); - printf("\tClient Count:\t\t%zu\n", pthgs->clt_cnt); - if (pthgs->tls == false) - return; - printf("\tTLS:\t\t\t%d\n", pthgs->tls); - printf("\tCert:\t\t\t%s\n", pthgs->tls_cert_file); - printf("\tKey:\t\t\t%s\n", pthgs->tls_key_file); - printf("\tCA:\t\t\t%s\n", pthgs->tls_ca_file); - printf("\tCRL:\t\t\t%s\n", pthgs->tls_crl_file); - printf("\tOCSP:\t\t\t%s\n", pthgs->tls_ocsp_staple_file); + + return (0); } -void -print_socks(struct sock_imsg *psocks) +int +list_sockets_msg(struct imsg *imsg) { - if (strcmp(psocks->name, "") == 0) - printf("Socket Name:\t\t\tReceive socket\n"); - else - printf("Socket Name:\t\t\t%s\n", psocks->name); - printf("\tfd:\t\t\t%d\n", psocks->fd); - printf("\tPort:\t\t\t%d\n", psocks->port); - if (psocks->tls == true) - printf("\tTLS:\t\t\tyes\n\n"); - printf("\tClient Count:\t\t%zu\n", psocks->clt_cnt); - if (psocks->max_clts == 0) - printf("\tMax Clients:\t\tunlimited\n"); - else - printf("\tMax Clients:\t\t%zu\n", psocks->max_clts); + struct socket *nsi; + + switch (imsg->hdr.type) { + case IMSG_GET_INFO_SOCKETS_DATA: + nsi = (struct socket *) imsg->data; + + printf("\n"); + if (strcmp(nsi->name, "") == 0) + printf("Socket Name:\t\t\tReceive socket\n"); + else + printf("Socket Name:\t\t\t%s\n", nsi->name); + printf("\tfd:\t\t\t%d\n", nsi->fd); + printf("\tPort:\t\t\t%d\n", nsi->port); + if (nsi->tls == true) + printf("\tTLS:\t\t\tyes\n\n"); + printf("\tClient Count:\t\t%zu\n", nsi->client_cnt); + if (nsi->max_clients == 0) + printf("\tMax Clients:\t\tunlimited\n"); + else + printf("\tMax Clients:\t\t%zu\n", nsi->max_clients); + break; + case IMSG_GET_INFO_SOCKETS_END_DATA: + return (1); + default: + break; + } + + return (0); } blob - 54611db824a2fecc6fb211b1a206b7e0285a9c36 blob + 13a0d75dae084822bbb8fd4568a780752d16ad3f --- thingsd/Makefile +++ thingsd/Makefile @@ -1,28 +1,24 @@ -PROG= thingsd +PROG = thingsd +SRCS = config.c control.c things.c log.c thingsd.c parse.y proc.c \ + tls.c serial.c sockets.c events.c client.c -SRCS= parse.y -SRCS+= log.c serial.c sockets.c client.c events.c tls.c control.c -SRCS+= things.c +MAN = thingsd.8 thingsd.conf.5 -SRCS+= thingsd.c +PREFIX= /usr/local +BINDIR?= ${PREFIX}/sbin +MANDIR?= ${PREFIX}/man/man -INC_C_DIR= /usr/local -BINDIR?= ${INC_C_DIR}/sbin -MANDIR?= ${INC_C_DIR}/man/man +CFLAGS += -Wall -I${.CURDIR} +CFLAGS += -Wstrict-prototypes -Wmissing-prototypes +CFLAGS += -Wmissing-declarations +CFLAGS += -Wshadow -Wpointer-arith +CFLAGS += -Wsign-compare -pthread +YFLAGS = +LDADD = -levent -ltls -lssl -lcrypto -lutil -pthread +DPADD = ${LIBEVENT} ${LIBTLS} ${LIBSSL} ${LIBCRYPTO} ${LIBUTIL} -LDADD= -levent -ltls -lssl -lcrypto -lutil -pthread -DPADD= ${LIBEVENT} ${LIBTLS} ${LIBSSL} ${LIBCRYPTO} ${LIBUTIL} - -CFLAGS+= -Wall -I${.CURDIR} -CFLAGS+= -Wstrict-prototypes -Wmissing-prototypes -CFLAGS+= -Wmissing-declarations -CFLAGS+= -Wshadow -Wpointer-arith -CFLAGS+= -Wsign-compare -pthread - CLEANFILES+= y.tab.h DEBUG= -g -O2 -MAN= thingsd.8 thingsd.conf.5 - .include blob - cb23de46052b7ebd733ccc7b071997d130dd2631 blob + 48b06133f16e921c35a6b1d8232ae92b4c721f41 --- thingsd/client.c +++ thingsd/client.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2019 Tracey Emery + * Copyright (c) 2016, 2019, 2020 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 @@ -20,6 +20,7 @@ #include #include +#include #include #include #include @@ -27,322 +28,364 @@ #include #include +#include "proc.h" #include "thingsd.h" -extern void bufferevent_read_pressure_cb(struct evbuffer *, size_t, - size_t, void *); +extern void bufferevent_read_pressure_cb(struct evbuffer *, size_t, size_t, + void *); void -clt_conn(int fd, short event, void *arg) +client_conn(int fd, short event, void *arg) { struct sockaddr_storage ss; - struct clt *clt; - struct thgsd *pthgsd = (struct thgsd *)arg; - struct sock *sock = NULL; - int clt_fd; + struct client *client; + struct thingsd *env = (struct thingsd *)arg; + struct socket *sock = NULL; + int client_fd; socklen_t len = sizeof(ss); - if ((clt_fd = accept4(fd, (struct sockaddr *)&ss, &len, + if ((client_fd = accept4(fd, (struct sockaddr *)&ss, &len, SOCK_NONBLOCK)) == -1) { - log_warnx("clt accept failed"); + log_warnx("client accept failed"); return; } - if ((clt = calloc(1, sizeof(*clt))) == NULL) + + if ((client = calloc(1, sizeof(*client))) == NULL) goto err; - if ((clt->ev = calloc(1, sizeof(*clt->ev))) == NULL) + if ((client->ev = calloc(1, sizeof(*client->ev))) == NULL) goto err; - if ((sock = get_sock(pthgsd, fd)) == NULL) + if ((sock = get_socket(env, fd)) == NULL) goto err; if (sock->tls) { - if (tls_accept_socket(sock->tls_ctx, &clt->tls_ctx, clt_fd) - == -1) { + if (tls_accept_socket(sock->tls_ctx, &client->tls_ctx, + client_fd) == -1) { log_warnx("tls accept failed: %s", tls_error(sock->tls_ctx)); 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) { + + *client->sub_names = (char *) calloc(env->max_subs, + sizeof(client->sub_names)); + if (*client->sub_names == NULL) + fatalx("calloc client->sub_names"); + + /* check for unlimited clients */ + sock->client_cnt++; + env->client_cnt++; + if (sock->max_clients > 0 && sock->client_cnt > sock->max_clients) { log_debug("%s: %s max clients reached", __func__, sock->name); - sock->clt_cnt--; - pthgsd->clt_cnt--; - free(clt->sub_names); + sock->client_cnt--; + env->client_cnt--; + free(*client->sub_names); goto err; } - clt->port = sock->port; - clt->sock = sock; - clt->subscribed = false; - clt->evb = evbuffer_new(); - if (clt->evb == NULL) { - sock->clt_cnt--; - pthgsd->clt_cnt--; - free(clt->sub_names); + + client->port = sock->port; + client->socket = sock; + client->subscribed = false; + client->evb = evbuffer_new(); + + if (client->evb == NULL) { + sock->client_cnt--; + env->client_cnt--; + free(*client->sub_names); goto err; } - clt->fd = clt_fd; - clt->join_time = time(NULL); - TAILQ_INSERT_TAIL(&pthgsd->clts, clt, entry); + + client->fd = client_fd; + client->join_time = time(NULL); + + TAILQ_INSERT_TAIL(env->clients, client, entry); if (sock->tls) { - clt->tls = true; - event_del(clt->ev); - event_set(clt->ev, clt->fd, EV_READ|EV_PERSIST, - sock_tls_handshake, pthgsd); - if (event_add(clt->ev, NULL)) { - free(clt->sub_names); + client->tls = true; + event_del(client->ev); + event_set(client->ev, client->fd, EV_READ | EV_PERSIST, + socket_tls_handshake, env); + if (event_add(client->ev, NULL)) { + free(*client->sub_names); goto err; } return; } - clt_add(pthgsd, clt); + + client_add(env, client); + return; - err: +err: log_debug("%s: client error", __func__); - if (clt_fd != -1) - close(clt_fd); + if (client_fd != -1) + close(client_fd); if (sock->tls) - tls_free(clt->tls_ctx); - free(clt->ev); - free(clt); + tls_free(client->tls_ctx); + free(client->ev); + free(client); } void -clt_add(struct thgsd *pthgsd, struct clt *pclt) +client_add(struct thingsd *env, struct client *client) { - struct clt *clt = pclt; - struct sock *sock = clt->sock; - evbuffercb cltrd = clt_rd; - evbuffercb cltwr = clt_wr; + struct socket *sock = client->socket; + evbuffercb clientrd = client_rd; + evbuffercb clientwr = client_wr; - log_debug("%s: client connected, %d", __func__, clt->fd); - clt->bev = bufferevent_new(clt->fd, cltrd, cltwr, clt_err, pthgsd); - if (clt->bev == NULL) { - sock->clt_cnt--; - pthgsd->clt_cnt--; + log_debug("%s: client connected, %d", __func__, client->fd); + + client->bev = bufferevent_new(client->fd, clientrd, clientwr, + client_err, env); + + if (client->bev == NULL) { + sock->client_cnt--; + env->client_cnt--; goto err; } - if (clt->tls) { - event_set(&clt->bev->ev_read, clt->fd, EV_READ, - clt_tls_readcb, clt->bev); - event_set(&clt->bev->ev_write, clt->fd, EV_WRITE, - clt_tls_writecb, clt->bev); + + if (client->tls) { + event_set(&client->bev->ev_read, client->fd, EV_READ, + client_tls_readcb, client->bev); + event_set(&client->bev->ev_write, client->fd, EV_WRITE, + client_tls_writecb, client->bev); } - bufferevent_setwatermark(clt->bev, EV_READ, 0, BUFF); - bufferevent_enable(clt->bev, EV_READ); + + bufferevent_setwatermark(client->bev, EV_READ, 0, PKT_BUFF); + bufferevent_enable(client->bev, EV_READ); + return; - err: +err: log_debug("%s: client error", __func__); - if (clt->fd != -1) - close(clt->fd); + if (client->fd != -1) + close(client->fd); if (sock->tls) - tls_free(clt->tls_ctx); - free(clt->ev); - free(clt); + tls_free(client->tls_ctx); + free(client->ev); + free(client); } void -clt_del(struct thgsd *pthgsd, struct clt *pclt) +client_del(struct thingsd *env, struct client *client) { - struct thg *thg; - struct clt *clt, *tclt; + struct thing *thing; + struct client *pclient, *tclient; size_t n; - TAILQ_FOREACH_SAFE(clt, &pthgsd->clts, entry, tclt) { - if (clt->fd == pclt->fd) { - if (clt->tls) - tls_free(clt->tls_ctx); - 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) + TAILQ_FOREACH_SAFE(pclient, env->clients, entry, tclient) { + if (pclient->fd == client->fd) { + if (pclient->tls) + tls_free(pclient->tls_ctx); + + for (n = 0; n < pclient->le; n++) + TAILQ_FOREACH(thing, env->things, entry) + if (strcmp(pclient->sub_names[n], + thing->name) == 0) + thing->client_cnt--; + + env->client_cnt--; + pclient->socket->client_cnt--; + + if (pclient->subscribed == false) log_debug("%s: client disconnected", __func__); else - log_info("client disconnected: %s", clt->name); - if (clt->bev != NULL) - bufferevent_free(clt->bev); - close(clt->fd); - TAILQ_REMOVE(&pthgsd->clts, clt, entry); - free(clt->ev); - free(clt->sub_names); - free(clt->name); - free(clt); + log_info("client disconnected: %s", + pclient->name); + + if (pclient->bev != NULL) + bufferevent_free(pclient->bev); + + close(pclient->fd); + TAILQ_REMOVE(env->clients, pclient, entry); + free(pclient->ev); + free(*pclient->sub_names); + free(pclient); break; } } } void -clt_rd(struct bufferevent *bev, void *arg) +client_rd(struct bufferevent *bev, void *arg) { - struct thgsd *pthgsd = (struct thgsd *)arg; - struct thg *thg = NULL; - struct clt *clt = NULL, *tclt; + struct thingsd *env = (struct thingsd *)arg; + struct thing *thing = NULL; + struct client *client = NULL, *tclient; size_t len, n; int fd = bev->ev_read.ev_fd; - char *pkt, *npkt; + char *pkt = NULL, *npkt = NULL; - TAILQ_FOREACH(tclt, &pthgsd->clts, entry) { - if (tclt->fd == fd) { - clt = tclt; - if (clt == NULL) + TAILQ_FOREACH(tclient, env->clients, entry) { + if (tclient->fd == fd) { + client = tclient; + if (client == NULL) return; break; } } - clt->evb = EVBUFFER_INPUT(bev); - len = EVBUFFER_LENGTH(clt->evb); - if (clt->subscribed == false) { + + client->evb = EVBUFFER_INPUT(bev); + len = EVBUFFER_LENGTH(client->evb); + + if (client->subscribed == false) { /* allow one shot at subscription so we don't get hammered */ if ((pkt = calloc(len, sizeof(*pkt))) == NULL) return; + if ((npkt = calloc(len, sizeof(*npkt))) == NULL) return; - bufferevent_disable(clt->bev, EV_READ); - evbuffer_remove(clt->evb, pkt, len); + + bufferevent_disable(client->bev, EV_READ); + evbuffer_remove(client->evb, pkt, len); + /* peak into packet and ensure it's a subscription packet */ if (pkt[0] == 0x7E && pkt[1] == 0x7E && pkt[2] == 0x7E) { memmove(npkt, pkt+3, len-3); - parse_buf(clt, npkt, len-3); - if (clt->subscribed) - bufferevent_enable(clt->bev, EV_READ|EV_WRITE); + parse_buf(client, npkt, len-3); + if (client->subscribed) + bufferevent_enable(client->bev, + EV_READ | EV_WRITE); } - free(pkt); - free(npkt); - } 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 if (client->subscribed) { + /* write to things */ + for (n = 0; n < client->le; n++) { + TAILQ_FOREACH(thing, env->things, entry) { + if (strcmp(client->sub_names[n], + thing->name) == 0 && + client->port == thing->port) { + + if (thing->exists) + client_wr_things(client, thing, + len); else - evbuffer_drain(clt->evb, len); + evbuffer_drain(client->evb, + len); + } } } } + free(pkt); + free(npkt); } void -clt_tls_readcb(int fd, short event, void *arg) +client_tls_readcb(int fd, short event, void *arg) { struct bufferevent *bufev = (struct bufferevent *)arg; - struct thgsd *pthgsd = bufev->cbarg; - struct clt *clt = NULL, *tclt; - char pkt[BUFF]; + struct thingsd *env = bufev->cbarg; + struct client *client = NULL, *tclient; + char pkt[PKT_BUFF]; ssize_t ret; size_t len; int toread = EVBUFFER_READ; - TAILQ_FOREACH(tclt, &pthgsd->clts, entry) { - if (tclt->fd == fd) - clt = tclt; + TAILQ_FOREACH(tclient, env->clients, entry) { + if (tclient->fd == fd) + client = tclient; } + memset(pkt, 0, sizeof(pkt)); - ret = tls_read(clt->tls_ctx, pkt, BUFF); + + ret = tls_read(client->tls_ctx, pkt, PKT_BUFF); if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT) { goto retry; } else if (ret < 0) { toread |= EVBUFFER_ERROR; goto err; } + len = ret; if (len == 0) { toread |= EVBUFFER_EOF; goto err; } + if (evbuffer_add(bufev->input, pkt, len) == -1) { toread |= EVBUFFER_ERROR; goto err; } + event_add(&bufev->ev_read, NULL); + len = EVBUFFER_LENGTH(bufev->input); if (bufev->wm_read.low != 0 && len < bufev->wm_read.low) return; + if (bufev->wm_read.high != 0 && len > bufev->wm_read.high) { struct evbuffer *buf = bufev->input; event_del(&bufev->ev_read); evbuffer_setcb(buf, bufferevent_read_pressure_cb, bufev); return; } + if (bufev->readcb != NULL) (*bufev->readcb)(bufev, bufev->cbarg); + return; - retry: +retry: event_del(&bufev->ev_read); event_add(&bufev->ev_read, NULL); return; - err: +err: (*bufev->errorcb)(bufev, toread, bufev->cbarg); } void -clt_wr_thgs(struct clt *clt, struct thg *thg, size_t len) +client_wr_things(struct client *client, struct thing *thing, size_t len) { char *pkt; if ((pkt = calloc(len, sizeof(*pkt))) == NULL) return; - switch (thg->type) { + switch (thing->type) { case TCP: case DEV: - if (thg->persist == false) { - if ((thg->fd = open_clt_sock(thg->ipaddr, - thg->conn_port)) == -1) { + if (thing->persist == false) { + if ((thing->fd = open_client_socket(thing->ipaddr, + thing->conn_port)) == -1) { log_warnx("%s: temporary ipaddr connection" " failed", __func__); return; } - evbuffer_remove(clt->evb, pkt, len); - write(thg->fd, pkt, len); - close(thg->fd); - thg->fd = -1; + evbuffer_remove(client->evb, pkt, len); + write(thing->fd, pkt, len); + close(thing->fd); + thing->fd = -1; } else { - if (thg->fd != -1) { - bufferevent_write_buffer(thg->bev, clt->evb); - evbuffer_drain(clt->evb, len); + if (thing->fd != -1) { + bufferevent_write_buffer(thing->bev, client->evb); + evbuffer_drain(client->evb, len); } } free(pkt); break; default: - evbuffer_remove(clt->evb, pkt, len); - write(thg->fd, pkt, len); + evbuffer_remove(client->evb, pkt, len); + write(thing->fd, pkt, len); free(pkt); break; } } void -clt_wr(struct bufferevent *bev, void *arg) +client_wr(struct bufferevent *bev, void *arg) { } void -clt_tls_writecb(int fd, short event, void *arg) +client_tls_writecb(int fd, short event, void *arg) { struct bufferevent *bufev = (struct bufferevent *)arg; - struct thgsd *pthgsd = bufev->cbarg; - struct clt *clt = NULL, *tclt; + struct thingsd *env = bufev->cbarg; + struct client *client = NULL, *tclient; ssize_t ret; size_t len; int towrite = EVBUFFER_WRITE; - TAILQ_FOREACH(tclt, &pthgsd->clts, entry) { - if (tclt->fd == fd) - clt = tclt; + TAILQ_FOREACH(tclient, env->clients, entry) { + if (tclient->fd == fd) + client = tclient; } + if (EVBUFFER_LENGTH(bufev->output)) { - ret = tls_write(clt->tls_ctx, + ret = tls_write(client->tls_ctx, EVBUFFER_DATA(bufev->output), EVBUFFER_LENGTH(bufev->output)); if (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT) { @@ -354,50 +397,54 @@ clt_tls_writecb(int fd, short event, void *arg) len = ret; evbuffer_drain(bufev->output, len); } + if (EVBUFFER_LENGTH(bufev->output) != 0) { event_del(&bufev->ev_write); event_add(&bufev->ev_write, NULL); } + if (bufev->writecb != NULL && EVBUFFER_LENGTH(bufev->output) <= bufev->wm_write.low) (*bufev->writecb)(bufev, bufev->cbarg); + return; - retry: +retry: event_del(&bufev->ev_write); event_add(&bufev->ev_write, NULL); return; - err: +err: (*bufev->errorcb)(bufev, towrite, bufev->cbarg); } void -clt_err(struct bufferevent *bev, short error, void *arg) +client_err(struct bufferevent *bev, short error, void *arg) { - struct thgsd *pthgsd = (struct thgsd *)arg; - struct clt *clt; + struct thingsd *env = (struct thingsd *)arg; + struct client *client; int fd = bev->ev_read.ev_fd; if ((error & EVBUFFER_EOF) == 0) log_warnx("%s: client socket error, disconnecting", __func__); + /* client disconnect */ - TAILQ_FOREACH(clt, &pthgsd->clts, entry) { - if (clt->fd == fd) { - clt_del(pthgsd, clt); + TAILQ_FOREACH(client, env->clients, entry) { + if (client->fd == fd) { + client_del(env, client); break; } } } void -clt_do_chk(struct thgsd *pthgsd) +client_do_chk(struct thingsd *env) { - struct clt *clt; + struct client *client; 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); + TAILQ_FOREACH(client, env->clients, entry) { + if (client->subscribed == false) { + if ((ctime - client->join_time) >= CLIENT_SUB_TIME) { + client_del(env, client); break; } } @@ -405,28 +452,78 @@ clt_do_chk(struct thgsd *pthgsd) } void -*clt_chk(void *arg) +*client_chk(void *arg) { - struct thgsd *pthgsd = (struct thgsd *)arg; - void (*tfptr)(struct thgsd *); + struct thingsd *env = (struct thingsd *)arg; + void (*tfptr)(struct thingsd *); - tfptr = pthgsd->clt_fptr; + tfptr = env->client_fptr; while(1) { - sleep(CLT_SUB_CHK); - (void)(*tfptr)(pthgsd); + sleep(CLIENT_SUB_CHK); + (void)(*tfptr)(env); } pthread_exit(NULL); } void -start_clt_chk(struct thgsd *pthgsd) +start_client_chk(struct thingsd *env) { - pthread_t tclt_chk; - int rclt_chk; + pthread_t tclient_chk; + int rclient_chk; - rclt_chk = pthread_create(&tclt_chk, NULL, clt_chk, (void *)pthgsd); - if (rclt_chk) { + rclient_chk = pthread_create(&tclient_chk, NULL, client_chk, + (void *)env); + if (rclient_chk) { log_warnx("%s: thread creation failed", __func__); - clt_chk((void *) pthgsd); + client_chk((void *) env); } } + +void +clients_show_info(struct privsep *ps, struct imsg *imsg) +{ + char filter[THINGSD_MAXNAME]; + struct client *client, nci; + size_t n; + + switch (imsg->hdr.type) { + case IMSG_GET_INFO_CLIENTS_REQUEST: + + memcpy(filter, imsg->data, sizeof(filter)); + + TAILQ_FOREACH(client, thingsd_env->clients, entry) { + if (filter[0] == '\0' || memcmp(filter, + client->name, sizeof(filter)) == 0) { + + n = strlcpy(nci.name, client->name, + sizeof(nci.name)); + if (n >= sizeof(nci.name)) + fatalx("%s: nci.name too long", + __func__); + + nci.subscribed = client->subscribed; + nci.fd = client->fd; + nci.port = client->port; + nci.tls = client->tls; + nci.subs = client->subs; + + if (proc_compose_imsg(ps, PROC_CONTROL, -1, + IMSG_GET_INFO_CLIENTS_DATA, + imsg->hdr.peerid, -1, &nci, + sizeof(nci)) == -1) + return; + + } + } + + if (proc_compose_imsg(ps, PROC_CONTROL, -1, + IMSG_GET_INFO_CLIENTS_END_DATA, imsg->hdr.peerid, + -1, &nci, sizeof(nci)) == -1) + return; + + break; + default: + log_debug("%s: error handling imsg", __func__); + break; + } +} blob - e1d5350bcd093615d794447b08ac3d97f184e169 blob + 6e0725ae6c10055e095a96cd200120a61bb8993e --- thingsd/control.c +++ thingsd/control.c @@ -1,4 +1,6 @@ /* + * Copyright (c) 2020 Tracey Emery + * Copyright (c) 2010-2015 Reyk Floeter * Copyright (c) 2003, 2004 Henning Brauer * * Permission to use, copy, modify, and distribute this software for any @@ -13,107 +15,199 @@ * 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 #include +#include -#include "things.h" +#include "proc.h" #include "thingsd.h" -#include "control.h" -#define CONTROL_BACKLOG 5 +#define CONTROL_BACKLOG 5 -struct ctl_conn *control_connbyfd(int); -struct ctl_conn *control_connbypid(pid_t); +struct ctl_connlist ctl_conns; -int show_ctl, show_fd; +struct ctl_conn *control_connbyfd(int); +void control_accept(int, short, void *); +void control_close(struct privsep *, struct imsg *, int, + struct control_sock *); +void control_dispatch_imsg(int, short, void *); +int control_dispatch_parent(int, struct privsep_proc *, struct imsg *); +void control_imsg_forward(struct imsg *); +void control_run(struct privsep *, struct privsep_proc *, void *); -void control_close(int); +static struct privsep_proc procs[] = { + { "parent", PROC_PARENT, control_dispatch_parent }, +}; +void +control(struct privsep *ps, struct privsep_proc *p) +{ + proc_run(ps, p, procs, nitems(procs), control_run, NULL); +} + +void +control_run(struct privsep *ps, struct privsep_proc *p, void *arg) +{ + if (pledge("stdio cpath unix recvfd", NULL) == -1) + fatal("pledge"); +} + int -control_init(char *path) +control_dispatch_parent(int fd, struct privsep_proc *p, struct imsg *imsg) { + struct ctl_conn *c; + + switch (imsg->hdr.type) { + case IMSG_SHOW_PACKETS_DATA: + case IMSG_SHOW_PACKETS_END_DATA: + case IMSG_GET_INFO_PARENT_DATA: + case IMSG_GET_INFO_PARENT_END_DATA: + case IMSG_GET_INFO_THINGS_DATA: + case IMSG_GET_INFO_THINGS_END_DATA: + case IMSG_GET_INFO_CLIENTS_DATA: + case IMSG_GET_INFO_CLIENTS_END_DATA: + case IMSG_GET_INFO_SOCKETS_DATA: + case IMSG_GET_INFO_SOCKETS_END_DATA: + if ((c = control_connbyfd(imsg->hdr.peerid)) == NULL) { + log_warnx("%s: fd %d: not found", + __func__, imsg->hdr.peerid); + return (-1); + } + imsg_compose_event(&c->iev, imsg->hdr.type, + 0, 0, -1, imsg->data, IMSG_DATA_SIZE(imsg)); + break; + case IMSG_CTL_RESET: + /* We don't have anything to do to reset. */ + break; + default: + return (-1); + } + return (0); +} + +int +control_init(struct privsep *ps, struct control_sock *cs) +{ struct sockaddr_un sun; int fd; - mode_t old_umask; + mode_t old_umask, mode; - if ((fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, - 0)) == -1) { + if (cs->cs_name == NULL) + return (0); + + if ((fd = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, 0)) == -1) { log_warn("%s: socket", __func__); return (-1); } - memset(&sun, 0, sizeof(sun)); sun.sun_family = AF_UNIX; - strlcpy(sun.sun_path, path, sizeof(sun.sun_path)); + if (strlcpy(sun.sun_path, cs->cs_name, + sizeof(sun.sun_path)) >= sizeof(sun.sun_path)) { + log_warn("%s: %s name too long", __func__, cs->cs_name); + close(fd); + return (-1); + } - if (unlink(path) == -1) + if (unlink(cs->cs_name) == -1) if (errno != ENOENT) { - log_warn("%s: unlink %s", __func__, path); + log_warn("%s: unlink %s", __func__, cs->cs_name); close(fd); return (-1); } - old_umask = umask(S_IXUSR|S_IXGRP|S_IWOTH|S_IROTH|S_IXOTH); + if (cs->cs_restricted) { + old_umask = umask(S_IXUSR|S_IXGRP|S_IXOTH); + mode = S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH; + } else { + old_umask = umask(S_IXUSR|S_IXGRP|S_IWOTH|S_IROTH|S_IXOTH); + mode = S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP; + } + if (bind(fd, (struct sockaddr *)&sun, sizeof(sun)) == -1) { - log_warn("%s: bind: %s", __func__, path); + log_warn("%s: bind: %s", __func__, cs->cs_name); close(fd); - umask(old_umask); + (void)umask(old_umask); return (-1); } - umask(old_umask); - if (chmod(path, - S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH) == -1) { + (void)umask(old_umask); + + if (chmod(cs->cs_name, mode) == -1) { log_warn("%s: chmod", __func__); close(fd); - (void)unlink(path); + (void)unlink(cs->cs_name); return (-1); } - return (fd); + cs->cs_fd = fd; + cs->cs_env = ps; + + return (0); } int -control_listen(void) +control_listen(struct control_sock *cs) { - if (listen(control_state.fd, CONTROL_BACKLOG) == -1) { + if (cs->cs_name == NULL) + return (0); + + if (listen(cs->cs_fd, CONTROL_BACKLOG) == -1) { log_warn("%s: listen", __func__); return (-1); } - event_set(&control_state.ev, control_state.fd, EV_READ, - control_accept, NULL); - event_add(&control_state.ev, NULL); - evtimer_set(&control_state.evt, control_accept, NULL); + event_set(&cs->cs_ev, cs->cs_fd, EV_READ, + control_accept, cs); + event_add(&cs->cs_ev, NULL); + evtimer_set(&cs->cs_evt, control_accept, cs); return (0); } void -control_accept(int listenfd, short event, void *bula) +control_cleanup(struct control_sock *cs) { + if (cs->cs_name == NULL) + return; + + event_del(&cs->cs_ev); + event_del(&cs->cs_evt); +} + +/* ARGSUSED */ +void +control_accept(int listenfd, short event, void *arg) +{ + struct control_sock *cs = arg; int connfd; socklen_t len; struct sockaddr_un sun; struct ctl_conn *c; - event_add(&control_state.ev, NULL); + event_add(&cs->cs_ev, NULL); if ((event & EV_TIMEOUT)) return; + len = sizeof(sun); - if ((connfd = accept4(listenfd, (struct sockaddr *)&sun, &len, - SOCK_CLOEXEC | SOCK_NONBLOCK)) == -1) { + if ((connfd = accept4(listenfd, + (struct sockaddr *)&sun, &len, SOCK_NONBLOCK)) == -1) { /* * Pause accept if we are out of file descriptors, or * libevent will haunt us here too. @@ -121,25 +215,36 @@ control_accept(int listenfd, short event, void *bula) if (errno == ENFILE || errno == EMFILE) { struct timeval evtpause = { 1, 0 }; - event_del(&control_state.ev); - evtimer_add(&control_state.evt, &evtpause); + event_del(&cs->cs_ev); + evtimer_add(&cs->cs_evt, &evtpause); } else if (errno != EWOULDBLOCK && errno != EINTR && errno != ECONNABORTED) - log_warn("%s: accept4", __func__); + log_warn("%s: accept", __func__); return; } if ((c = calloc(1, sizeof(struct ctl_conn))) == NULL) { - log_warn("%s: calloc", __func__); + log_warn("%s", __func__); close(connfd); return; } + if (getsockopt(connfd, SOL_SOCKET, SO_PEERCRED, + &c->peercred, &len) != 0) { + log_warn("%s: failed to get peer credentials", __func__); + close(connfd); + free(c); + return; + } + imsg_init(&c->iev.ibuf, connfd); + c->iev.handler = control_dispatch_imsg; c->iev.events = EV_READ; - event_set(&c->iev.ev, c->iev.ibuf.fd, c->iev.events, c->iev.handler, - &c->iev); + c->iev.data = cs; + + event_set(&c->iev.ev, c->iev.ibuf.fd, c->iev.events, + c->iev.handler, c->iev.data); event_add(&c->iev.ev, NULL); TAILQ_INSERT_TAIL(&ctl_conns, c, entry); @@ -148,7 +253,7 @@ control_accept(int listenfd, short event, void *bula) struct ctl_conn * control_connbyfd(int fd) { - struct ctl_conn *c; + struct ctl_conn *c; TAILQ_FOREACH(c, &ctl_conns, entry) { if (c->iev.ibuf.fd == fd) @@ -158,33 +263,22 @@ control_connbyfd(int fd) return (c); } -struct ctl_conn * -control_connbypid(pid_t pid) -{ - struct ctl_conn *c; - - TAILQ_FOREACH(c, &ctl_conns, entry) { - if (c->iev.ibuf.pid == pid) - break; - } - - return (c); -} - void -control_close(int fd) +control_close(struct privsep *ps, struct imsg *imsg, int fd, + struct control_sock *cs) { - struct ctl_conn *c; + struct ctl_conn *c; - main_imsg_compose_thgs(IMSG_CTL_END, 0, NULL, 0); - if ((c = control_connbyfd(fd)) == NULL) { - log_warnx("%s: fd %d: not found", __func__, fd); + log_warn("%s: fd %d: not found", __func__, fd); return; } - if (fd == show_fd) - show_ctl = 0; + if (proc_compose_imsg(ps, PROC_PARENT, -1, + IMSG_SHOW_PACKETS_END_DATA, 0, -1, + &fd, sizeof(fd)) == -1) + log_warn("fd not sent to parent to close"); + msgbuf_clear(&c->iev.ibuf.w); TAILQ_REMOVE(&ctl_conns, c, entry); @@ -192,129 +286,158 @@ control_close(int fd) close(c->iev.ibuf.fd); /* Some file descriptors are available again. */ - if (evtimer_pending(&control_state.evt, NULL)) { - evtimer_del(&control_state.evt); - event_add(&control_state.ev, NULL); + if (evtimer_pending(&cs->cs_evt, NULL)) { + evtimer_del(&cs->cs_evt); + event_add(&cs->cs_ev, NULL); } free(c); } +/* ARGSUSED */ void -control_dispatch_imsg(int fd, short event, void *bula) +control_dispatch_imsg(int fd, short event, void *arg) { + struct thingsd_control_info nci; + + struct control_sock *cs = arg; + struct privsep *ps = cs->cs_env; struct ctl_conn *c; struct imsg imsg; - enum thgs_list_type type; - ssize_t n; + int n, v, ret = 0; uid_t euid; gid_t egid; - int verbose; + if (getpeereid(fd, &euid, &egid) == -1) + return; + if ((c = control_connbyfd(fd)) == NULL) { - log_warnx("%s: fd %d: not found", __func__, fd); + log_warn("%s: fd %d: not found", __func__, fd); return; } if (event & EV_READ) { if (((n = imsg_read(&c->iev.ibuf)) == -1 && errno != EAGAIN) || n == 0) { - control_close(fd); + control_close(ps, &imsg, fd, cs); return; } } + if (event & EV_WRITE) { if (msgbuf_write(&c->iev.ibuf.w) <= 0 && errno != EAGAIN) { - control_close(fd); + control_close(ps, &imsg, fd, cs); return; } } - if (getpeereid(fd, &euid, &egid) == -1) { - control_close(fd); - return; - } - for (;;) { if ((n = imsg_get(&c->iev.ibuf, &imsg)) == -1) { - control_close(fd); + control_close(ps, &imsg, fd, cs); return; } + if (n == 0) break; - if (show_ctl) { - control_close(fd); - return; + + switch (imsg.hdr.type) { + case IMSG_SHOW_PACKETS_REQUEST: + case IMSG_KILL_CLIENT: + case IMSG_GET_INFO_PARENT_REQUEST: + case IMSG_GET_INFO_THINGS_REQUEST: + case IMSG_GET_INFO_CLIENTS_REQUEST: + case IMSG_GET_INFO_SOCKETS_REQUEST: + case IMSG_GET_INFO_CONTROL_REQUEST: + break; + default: + if (c->peercred.uid != 0) { + log_warnx("denied request %d from uid %d", + imsg.hdr.type, c->peercred.uid); + ret = EPERM; + goto fail; + } + break; } + control_imsg_forward(&imsg); + switch (imsg.hdr.type) { - case IMSG_THGS_LOG_VERBOSE: - case IMSG_KILL_CLT: - case IMSG_SHOW_PKTS: - if (euid != 0) { - imsg_free(&imsg); - control_close(fd); + case IMSG_CTL_NOTIFY: + if (c->flags & CTL_CONN_NOTIFY) { + log_debug("%s: " + "client requested notify more than once", + __func__); + ret = EINVAL; + goto fail; + } + c->flags |= CTL_CONN_NOTIFY; + break; + case IMSG_CTL_VERBOSE: + IMSG_SIZE_CHECK(&imsg, &v); + memcpy(&v, imsg.data, sizeof(v)); + log_setverbose(v); + proc_forward_imsg(ps, &imsg, PROC_PARENT, -1); + break; + case IMSG_GET_INFO_CONTROL_REQUEST: + nci.verbose = log_getverbose(); + imsg_compose_event(&c->iev, + IMSG_GET_INFO_CONTROL_DATA, 0, 0, -1, + &nci, sizeof(struct thingsd_control_info)); + imsg_compose_event(&c->iev, + IMSG_GET_INFO_CONTROL_END_DATA, 0, 0, -1, + &nci, sizeof(struct thingsd_control_info)); + break; + case IMSG_KILL_CLIENT: + case IMSG_SHOW_PACKETS_REQUEST: + case IMSG_GET_INFO_PARENT_REQUEST: + case IMSG_GET_INFO_THINGS_REQUEST: + case IMSG_GET_INFO_CLIENTS_REQUEST: + case IMSG_GET_INFO_SOCKETS_REQUEST: + imsg.hdr.peerid = fd; + + if (euid == 0 && + imsg.hdr.type == + IMSG_GET_INFO_THINGS_REQUEST) + imsg.hdr.type = + IMSG_GET_INFO_THINGS_REQUEST_ROOT; + + if (proc_compose_imsg(ps, PROC_PARENT, -1, + imsg.hdr.type, imsg.hdr.peerid, -1, + imsg.data, IMSG_DATA_SIZE(&imsg)) == -1) { + control_close(ps, &imsg, fd, cs); return; } break; - default: + case IMSG_CTL_RESET: + proc_forward_imsg(ps, &imsg, PROC_PARENT, -1); break; - } - - switch (imsg.hdr.type) { - case IMSG_SHOW_PKTS: - show_ctl = 1; - show_fd = fd; - main_imsg_compose_thgs(imsg.hdr.type, imsg.hdr.pid, - imsg.data, IMSG_DATA_SIZE(imsg)); - break; - case IMSG_KILL_CLT: - main_imsg_compose_thgs(imsg.hdr.type, 0, imsg.data, - IMSG_DATA_SIZE(imsg)); - break; - case IMSG_THGS_LIST: - if (IMSG_DATA_SIZE(imsg) != - sizeof(enum thgs_list_type)) - break; - memcpy(&type, imsg.data, sizeof(type)); - if (type == THGS_LIST_THGS && euid == 0) { - type = THGS_LIST_THGS_ROOT; - main_imsg_compose_thgs(imsg.hdr.type, 0, - &type, sizeof(type)); - } - else - main_imsg_compose_thgs(imsg.hdr.type, 0, - imsg.data, IMSG_DATA_SIZE(imsg)); - break; - case IMSG_THGS_LOG_VERBOSE: - if (IMSG_DATA_SIZE(imsg) != sizeof(verbose)) - break; - /* forward to other process */ - main_imsg_compose_thgs(imsg.hdr.type, 0, - imsg.data, IMSG_DATA_SIZE(imsg)); - - memcpy(&verbose, imsg.data, sizeof(verbose)); - log_setverbose(verbose); - break; default: - log_debug("%s: error handling imsg %d", __func__, - imsg.hdr.type); + log_debug("%s: error handling imsg %d", + __func__, imsg.hdr.type); + control_close(ps, &imsg, fd, cs); break; } imsg_free(&imsg); } imsg_event_add(&c->iev); + return; + +fail: + imsg_compose_event(&c->iev, IMSG_CTL_FAIL, + 0, 0, -1, &ret, sizeof(ret)); + imsg_flush(&c->iev.ibuf); + control_close(ps, &imsg, fd, cs); } -int -control_imsg_relay(struct imsg *imsg) +void +control_imsg_forward(struct imsg *imsg) { - struct ctl_conn *c; + struct ctl_conn *c; - if ((c = control_connbypid(imsg->hdr.pid)) == NULL) - return (0); - - return (imsg_compose_event(&c->iev, imsg->hdr.type, 0, imsg->hdr.pid, - -1, imsg->data, IMSG_DATA_SIZE(*imsg))); + TAILQ_FOREACH(c, &ctl_conns, entry) + if (c->flags & CTL_CONN_NOTIFY) + imsg_compose_event(&c->iev, imsg->hdr.type, + imsg->hdr.peerid, imsg->hdr.pid, -1, imsg->data, + imsg->hdr.len - IMSG_HEADER_SIZE); } blob - /dev/null blob + 28b7bbb98735131a022c655a7a274115314a240f (mode 644) --- /dev/null +++ thingsd/config.c @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2020 Tracey Emery + * Copyright (c) 2015 Reyk Floeter + * + * 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 +#include +#include + +#include "proc.h" +#include "thingsd.h" + +int +config_init(struct thingsd *env) +{ + struct privsep *ps = &env->thingsd_ps; + unsigned int what; + + /* Global configuration. */ + if (privsep_process == PROC_PARENT) + env->prefork_things = THINGS_NUMPROC; + + ps->ps_what[PROC_PARENT] = CONFIG_ALL; + ps->ps_what[PROC_THINGS] = CONFIG_THINGS; + + /* Other configuration. */ + what = ps->ps_what[privsep_process]; + if (what & CONFIG_THINGS) { + env->things = calloc(1, sizeof(*env->things)); + if (env->things == NULL) + return (-1); + env->sockets = calloc(1, sizeof(*env->sockets)); + if (env->sockets == NULL) + return (-1); + env->clients = calloc(1, sizeof(*env->clients)); + if (env->clients == NULL) + return (-1); + env->dead_things = calloc(1, sizeof(*env->dead_things)); + if (env->dead_things == NULL) + return (-1); + env->dead_things->dead_things_list = calloc(1, + sizeof(*env->dead_things->dead_things_list)); + if (env->dead_things->dead_things_list == NULL) + return (-1); + env->packet_clients = calloc(1, sizeof(*env->packet_clients)); + if (env->packet_clients == NULL) + return (-1); + TAILQ_INIT(env->things); + TAILQ_INIT(env->sockets); + TAILQ_INIT(env->clients); + TAILQ_INIT(env->dead_things->dead_things_list); + TAILQ_INIT(env->packet_clients); + } + return (0); +} + +void +config_purge(struct thingsd *env, unsigned int reset) +{ + struct privsep *ps = &env->thingsd_ps; + struct thing *thing; + unsigned int what; + + what = ps->ps_what[privsep_process]; + if (what & CONFIG_THINGS) { + while ((thing = TAILQ_FIRST(env->things)) != NULL) { + TAILQ_REMOVE(env->things, thing, entry); + free(thing); + } + } +} + +int +config_setreset(struct thingsd *env, unsigned int reset) +{ + struct privsep *ps = &env->thingsd_ps; + unsigned int id; + + for (id = 0; id < PROC_MAX; id++) { + if (id == privsep_process) + continue; + proc_compose(ps, id, IMSG_CTL_RESET, &reset, sizeof(reset)); + } + + return (0); +} + +int +config_getreset(struct thingsd *env, struct imsg *imsg) +{ + unsigned int mode; + + IMSG_SIZE_CHECK(imsg, &mode); + memcpy(&mode, imsg->data, sizeof(mode)); + + config_purge(env, mode); + + return (0); +} blob - e9916b2f4c78a0b6e3c37f8e6845888ad2631dc7 (mode 644) blob + /dev/null --- thingsd/control.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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 "log.h" - -struct { - struct event ev; - struct event evt; - int fd; -} control_state; - -struct ctl_conn { - TAILQ_ENTRY(ctl_conn) entry; - struct imsgev iev; -}; - -int control_init(char *); -int control_listen(void); -void control_accept(int, short, void *); -void control_dispatch_imsg(int, short, void *); -int control_imsg_relay(struct imsg *); blob - baa56d9b42416df38e2f6602c44d72fdf7e68c5f blob + d741d2a36d7bd88c792c0c20a638f121ace62d92 --- thingsd/events.c +++ thingsd/events.c @@ -19,39 +19,49 @@ #include #include +#include #include #include +#include "proc.h" #include "thingsd.h" void -udp_evt(int fd, short event, void *arg) +udp_event(int fd, short event, void *arg) { - struct thgsd *pthgsd = (struct thgsd *)arg; - struct thg *thg = NULL, *tthg; - struct clt *clt; - char pkt[BUFF]; + struct thingsd *env = (struct thingsd *)arg; + struct thing *thing = NULL, *tthing; + struct client *client; + char pkt[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; + + TAILQ_FOREACH(tthing, env->things, entry) { + if (tthing->fd == fd) { + thing = tthing; 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); + TAILQ_FOREACH(client, env->clients, entry) { + for (n = 0; n < client->le; n++) { + if (strcmp(client->sub_names[n], + thing->name) == 0) + bufferevent_write(client->bev, pkt, + len); } } - send_ctl_pkt(thg->name, pkt, len); + + if (env->packet_client_count > 0) + send_to_packet_client(env, thing->name, pkt, len); + } } blob - 1c88ec0b926f4fd763588d3237839beeca02cd6a blob + 9171fe536316314c873d6e389f19fb23c264155e --- thingsd/examples/etc/thingsd.conf +++ thingsd/examples/etc/thingsd.conf @@ -2,6 +2,9 @@ # Global Options # +# Run 10 processes to greatly improve performance +prefork 10 + # Default global things listening port for client connections default port 50000 blob - c275d08591e6cef647966d452b9a488d2731f579 blob + 76f9c43f5839f078ef3da617ff1fab3210afbe27 --- thingsd/log.c +++ thingsd/log.c @@ -22,23 +22,40 @@ #include #include -#include +static int debug; +static int verbose; +const char *log_procname; -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); + log_procinit(getprogname()); if (!debug) - openlog(__progname, LOG_PID | LOG_NDELAY, facility); + openlog(getprogname(), LOG_PID | LOG_NDELAY, facility); tzset(); } @@ -65,7 +82,7 @@ log_getverbose(void) void logit(int pri, const char *fmt, ...) { - va_list ap; + va_list ap; va_start(ap, fmt); vlog(pri, fmt, ap); @@ -75,8 +92,8 @@ logit(int pri, const char *fmt, ...) void vlog(int pri, const char *fmt, va_list ap) { - char *nfmt; - int saved_errno = errno; + char *nfmt; + int saved_errno = errno; if (debug) { /* best effort in out of mem situations */ @@ -97,23 +114,23 @@ vlog(int pri, const char *fmt, va_list ap) void log_warn(const char *emsg, ...) { - char *nfmt; - va_list ap; - int saved_errno = errno; + 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)); + logit(LOG_CRIT, "%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)); + vlog(LOG_CRIT, emsg, ap); + logit(LOG_CRIT, "%s", strerror(saved_errno)); } else { - vlog(LOG_ERR, nfmt, ap); + vlog(LOG_CRIT, nfmt, ap); free(nfmt); } va_end(ap); @@ -125,17 +142,17 @@ log_warn(const char *emsg, ...) void log_warnx(const char *emsg, ...) { - va_list ap; + va_list ap; va_start(ap, emsg); - vlog(LOG_ERR, emsg, ap); + vlog(LOG_CRIT, emsg, ap); va_end(ap); } void log_info(const char *emsg, ...) { - va_list ap; + va_list ap; va_start(ap, emsg); vlog(LOG_INFO, emsg, ap); @@ -145,11 +162,11 @@ log_info(const char *emsg, ...) void log_debug(const char *emsg, ...) { - va_list ap; + va_list ap; if (verbose > 1) { va_start(ap, emsg); - vlog(LOG_INFO, emsg, ap); + vlog(LOG_DEBUG, emsg, ap); va_end(ap); } } @@ -157,8 +174,8 @@ log_debug(const char *emsg, ...) static void vfatalc(int code, const char *emsg, va_list ap) { - static char s[BUFSIZ]; - const char *sep; + static char s[BUFSIZ]; + const char *sep; if (emsg != NULL) { (void)vsnprintf(s, sizeof(s), emsg, ap); @@ -177,7 +194,7 @@ vfatalc(int code, const char *emsg, va_list ap) void fatal(const char *emsg, ...) { - va_list ap; + va_list ap; va_start(ap, emsg); vfatalc(errno, emsg, ap); @@ -188,7 +205,7 @@ fatal(const char *emsg, ...) void fatalx(const char *emsg, ...) { - va_list ap; + va_list ap; va_start(ap, emsg); vfatalc(0, emsg, ap); blob - 5fb2a6288e718aa69dceb45175bc5e931a542702 (mode 644) blob + /dev/null --- thingsd/log.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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. - */ - -#ifndef LOG_H -#define LOG_H - -#include -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 /* LOG_H */ blob - f5a9ab73674773ed85b2677618e9c1fd81a4bf74 blob + 2e5a116be9387d32a0c4dddbe0e796619cce0392 --- thingsd/parse.y +++ thingsd/parse.y @@ -1,6 +1,7 @@ /* - * Copyright (c) 2016-2019 Tracey Emery - * Copyright (c) 2007 - 2015 Reyk Floeter + * Copyright (c) 2016-2019, 2020 Tracey Emery + * Copyright (c) 2004, 2005 Esben Norby + * Copyright (c) 2004 Ryan McBride * Copyright (c) 2002, 2003, 2004 Henning Brauer * Copyright (c) 2001 Markus Friedl. All rights reserved. * Copyright (c) 2001 Daniel Hartmeier. All rights reserved. @@ -20,23 +21,35 @@ */ %{ -#include -#include +#include #include +#include +#include +#include +#include + +#include + #include +#include +#include #include +#include #include #include -#include #include +#include +#include +#include #include +#include #include +#include "proc.h" #include "thingsd.h" TAILQ_HEAD(files, file) files = TAILQ_HEAD_INITIALIZER(files); - static struct file { TAILQ_ENTRY(file) entry; FILE *stream; @@ -44,124 +57,381 @@ static struct file { 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, pkt_len; -int popfile(void); -int popbuff(void); -int yyparse(void); -int yylex(void); -int yy_flush_buffer(void); /* look up */ -int yyerror(const char *, ...) +struct file *pushfile(const char *, int); +struct file *pushbuff(u_char *); +int popfile(void); +int popbuff(void); +int check_file_secrecy(int, const char *); +int yyparse(void); +int yylex(void); +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); -int load_tls(struct thg *); +int kw_cmp(const void *, const void *); +int lookup(char *); +int lgetc(int); +int lungetc(int); +int findeol(void); +int load_tls(struct thing *); -size_t n; +TAILQ_HEAD(symhead, sym) symhead = TAILQ_HEAD_INITIALIZER(symhead); +struct sym { + TAILQ_ENTRY(sym) entry; + int used; + int persist; + char *nam; + char *val; +}; -char *my_name; +int symset(const char *, const char *, int); +char *symget(const char *); +void clear_config(struct thingsd *xconf); + +static int errors; + +static struct thing *new_thing; + +const int baudrates[18] = {50, 75, 110, 134, 150, 200, + 300, 600, 1200, 1800, 2400, 4800, 9600, + 38400, 57600, 76800, 115200}; +const char *parity[4] = {"none", "odd", "even", "space"}; +struct client *client, *tclient; +char my_name[THINGSD_MAXTEXT]; +int my_fd, pkt_len; +size_t pn; + +struct thing *conf_new_thing(char *); +void *conf_del_thing(struct thing *); + typedef struct { union { - int number; + int64_t number; char *string; } v; int lineno; } YYSTYPE; + %} -%token BAUD DATA PARITY STOP HARDWARE SOFTWARE PASSWORD NAME RETRY PERSISTENT -%token VERBOSE CONNECT THING LISTEN LOCATION IPADDR UDP THINGS CONNECTION -%token DEFAULT PORT MAX CLIENTS SUBSCRIPTIONS BIND INTERFACE SUBSCRIBE TLS -%token ERROR RECEIVE CERTIFICATE CIPHERS CLIENT CA CRL OPTIONAL DHE ECDHE KEY -%token OCSP PROTOCOLS ON -%token STRING -%token NUMBER -%type opttls +%token BAUD BIND CA CERTIFICATE CIPHERS CLIENT CLIENTS CONNECT CONNECTION CRL +%token DATA DEFAULT DHE ECDHE ERROR HARDWARE INCLUDE INTERFACE IPADDR KEY +%token LISTEN LOCATION MAX NAME OCSP ON OPTIONAL PARITY PASSWORD PERSISTENT +%token PORT PREFORK PROTOCOLS RECEIVE RETRY SOFTWARE STOP SUBSCRIBE +%token SUBSCRIPTIONS THING THINGS TLS UDP VERBOSE +%token STRING +%token NUMBER +%type string +%type opttls + %% + grammar : /* empty */ + | grammar include '\n' | grammar '\n' - | grammar main '\n' + | grammar conf_main '\n' | grammar dosub - | grammar error '\n' { file->errors++; } + | grammar error '\n' { file->errors++; } + | grammar thing '\n' + | grammar varset '\n' ; -opttls : /*empty*/ { + +conf_main : bindopts1 + | DEFAULT PORT NUMBER { + thingsd_env->port = $3; + } + | maxclients + | maxsubs + | PREFORK NUMBER { + thingsd_env->prefork_things = $2; + if ($2 <= 0 || $2 > PROC_MAX_INSTANCES) { + yyerror("invalid number of preforked " + "servers: %lld", $2); + YYERROR; + } + } + | thingretry + ; + +bindopts1 : BIND INTERFACE STRING { + pn = strlcpy(thingsd_env->iface, $3, + sizeof(thingsd_env->iface)); + if (pn >= sizeof(thingsd_env->iface)) + fatalx("%s: thingsd_env->iface too long", + __func__); + free($3); + } + ; + +bindopts2 : BIND INTERFACE STRING { + pn = strlcpy(new_thing->iface, $3, + sizeof(new_thing->iface)); + if (pn >= sizeof(new_thing->iface)) + fatalx("%s: new_thing->iface too long", + __func__); + free($3); + } + ; + +dosub : SUBSCRIBE '{' optnl subopts '}' + ; + +include : INCLUDE STRING { + struct file *nfile; + + if ((nfile = pushfile($2, 1)) == NULL) { + yyerror("failed to include file %s", $2); + free($2); + YYERROR; + } + free($2); + + file = nfile; + lungetc('\n'); + } + ; + +locationopts : /* empty */ + | '{' optnl locationopts2 '}' + ; + +locationopts1 : bindopts2 + | BAUD NUMBER { + int bc; + const int bauds = (sizeof(baudrates) / + sizeof(const int)); + + new_thing->baud = -1; + for (bc = 0; bc < bauds; bc++) { + if ($2 == baudrates[bc]) { + new_thing->baud = $2; + continue; + } + } + if (new_thing->baud == -1) { + yyerror("baud rate syntax error"); + YYERROR; + } + } + | DATA NUMBER { + if ($2 > 8 || $2 < 5) { + yyerror("data bits syntax error"); + YYERROR; + } else + new_thing->data_bits = $2; + } + | HARDWARE NUMBER { + if ($2 > 1 || $2 < 0) { + yyerror("hardware syntax error"); + YYERROR; + } else if ($2 > 0) + new_thing->hw_ctl = true; + } + | LISTEN ON opttls PORT NUMBER { + struct thing *thing; + + TAILQ_FOREACH(thing, thingsd_env->things, entry) { + if (thing->port == $5 && (thing->tls || $3)) { + yyerror("tls port already used"); + YYERROR; + } + } + new_thing->port = $5; + } + | maxclientssub + | PASSWORD STRING { + pn = strlcpy(new_thing->password, $2, + sizeof(new_thing->password)); + if (pn >= sizeof(new_thing->password)) + fatalx("%s: new_thing->password too long", + __func__); + free($2); + } + | PARITY STRING { + int pc; + const int parities = (sizeof(parity) / + sizeof(const char *)); + + for (pc = 0; pc < parities; pc++) { + if (strcmp($2, parity[pc]) == 0) { + pn = strlcpy(new_thing->parity, $2, + sizeof(new_thing->parity)); + if (pn >= sizeof(new_thing->parity)) + fatalx("%s: new_thing->parity " + "too long", __func__); + free($2); + continue; + } + } + if (strlen(new_thing->parity) == 0) { + free($2); + yyerror("parity syntax error"); + YYERROR; + } + } + | SOFTWARE NUMBER { + if ($2 > 1 || $2 < 0) { + yyerror("software syntax error"); + YYERROR; + } else + new_thing->sw_ctl = true; + } + | STOP NUMBER { + if ($2 > 2 || $2 < 1) { + yyerror("stop bits syntax error"); + YYERROR; + } else if ($2 > 0) + new_thing->stop_bits = $2; + } + | TLS tlsopts { + if (new_thing->tls == false) { + yyerror("tls options without tls listener"); + YYERROR; + } + } + ; + +locationopts2 : locationopts2 locationopts1 nl + | locationopts1 optnl + ; + +maxclients : MAX CLIENTS NUMBER { + thingsd_env->max_clients = $3; + } + ; + +maxclientssub : MAX CLIENTS NUMBER { + new_thing->max_clients = $3; + } + ; + +maxsubs : MAX SUBSCRIPTIONS NUMBER { + thingsd_env->max_subs = $3; + } + ; + +name : NAME optcomma STRING { + /* test we're us and set name */ + TAILQ_FOREACH(client, thingsd_env->clients, entry) { + if (client == tclient) { + memset(&my_name, 0, sizeof(my_name)); + pn = strlcpy(client->name, $3, + sizeof(client->name)); + if (pn >= sizeof(client->name)) + fatalx("%s: client->name too " + "long", __func__); + pn = strlcpy(my_name, $3, + sizeof(my_name)); + if (pn >= sizeof(my_name)) + fatalx("%s: my_name too long ", + __func__); + break; + } + } + free($3); + } + ; + +nl : '\n' optnl + ; + +optcomma : ',' optcomma + | /* empty */ + ; + +optnl : '\n' optnl /* zero or more newlines */ + | /* empty */ + ; + +opttls : /* empty */ { $$ = 0; - newthg->tls = false; + new_thing->tls = false; } | TLS { $$ = 1; - newthg->tls = true; + new_thing->tls = true; } ; -main : DEFAULT PORT NUMBER { - pthgsd->port = $3; + +socketopts1 : CONNECT ON PORT NUMBER { + new_thing->conn_port = $4; } - | maxclients - | maxsubs - | bindopts1 - | thing - | thgretry + | LISTEN ON opttls PORT NUMBER { + struct thing *thing; + TAILQ_FOREACH(thing, thingsd_env->things, entry) { + if (thing->port == $5 && (thing->tls || $3)) { + yyerror("tls port already used"); + YYERROR; + } + } + new_thing->port = $5; + } + | RECEIVE ON PORT NUMBER { + new_thing->rcv_port = $4; + } + | PASSWORD STRING { + pn = strlcpy(new_thing->password, $2, + sizeof(new_thing->password)); + if (pn >= sizeof(new_thing->password)) + fatalx("%s: new_thing->password too long", + __func__); + free($2); + } + | PERSISTENT NUMBER { + if ($2) + new_thing->persist = true; + else + new_thing->persist = false; + } + | TLS tlsopts { + if (new_thing->tls == false) { + yyerror("tls options without tls listener"); + YYERROR; + } + } + | bindopts2 + | maxclientssub ; -dosub : SUBSCRIBE '{' subopts '}' + +socketopts2 : socketopts2 socketopts1 nl + | socketopts1 optnl ; + +string : string STRING { + if (asprintf(&$$, "%s %s", $1, $2) == -1) { + free($1); + free($2); + yyerror("string: asprintf"); + YYERROR; + } + free($1); + free($2); + } + | STRING + ; + subopts : { - /* empty */ - } '{' name '}' ',' '{' things '}' + } '{' name '}' optcomma '{' 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; +subthings : THING '{' STRING optcomma STRING '}' optcomma { + struct thing *thing; + bool fail = false; + size_t n; + /* check for duplicate name and subscriptions */ - TAILQ_FOREACH(clt, &pthgsd->clts, entry) { - if (clt->name == NULL || my_name == NULL) + TAILQ_FOREACH(client, thingsd_env->clients, entry) { + if (strlen(client->name) == 0 || + strlen(my_name) == 0) continue; - if (strcmp(clt->name, my_name) == 0) { - if (my_fd != clt->fd) { + if (strcmp(client->name, my_name) == 0) { + if (my_fd != client->fd) { fail = true; log_warnx("client exists"); } - for (n = 0; n < clt->le; n++) - if (strcmp(clt->sub_names[n], + for (n = 0; n < client->le; n++) + if (strcmp(client->sub_names[n], $3) == 0) fail = true; break; @@ -173,277 +443,204 @@ subthgs : THING '{' STRING ',' STRING '}' optcomma { * test max subscriptions * subscribe */ - TAILQ_FOREACH(thg, &pthgsd->thgs, entry) { + TAILQ_FOREACH(thing, thingsd_env->things, entry) { if (fail) continue; - if (thg->port != clt->port) + if (thing->port != client->port) continue; - if (strcmp(thg->name, $3) == 0) - if (strcmp(thg->password, $5) == 0) { - if (clt->subs++ >= - pthgsd->max_sub) { + if (strcmp(thing->name, $3) == 0) + if (strcmp(thing->password, $5) == 0) { + if (client->subs++ >= + thingsd_env->max_subs) { log_warn("max " "subscriptions " "reached"); continue; } - clt->subscribed = true; - clt->sub_names[clt->le] - = thg->name; - clt->le++; - thg->clt_cnt++; + client->subscribed = true; + n = strlcpy(client-> + sub_names[client->le], + thing->name, + sizeof(client->sub_names)); + client->le++; + thing->client_cnt++; log_info("client %s subscribed " - "to %s", clt->name, - thg->name); + "to %s", client->name, + thing->name); continue; } } free($3); free($5); - } + }; + +subthings2 : subthings2 subthings nl + | subthings optnl ; -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 ON opttls PORT NUMBER { - struct thg *thg; - TAILQ_FOREACH(thg, &pthgsd->thgs, entry) { - if (thg->port == $5 && (thg->tls || $3)) { - yyerror("tls port already used"); - YYERROR; - } - } - newthg->port = $5; - } - | 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; +thing : THING STRING { + new_thing = conf_new_thing($2); + + if (strlen(thingsd_env->iface) != 0) { + pn = strlcpy(new_thing->iface, + thingsd_env->iface, sizeof(new_thing->iface)); + if (pn >= sizeof(new_thing->iface)) + fatalx("%s: new_thing->iface too long", + __func__); } 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 { - if ((newthg->password = strdup($2)) == NULL) - fatalx("out of memory"); - free($2); - } - | bindopts2 - | maxclientssub - | TLS tlsopts { - if (newthg->tls == false) { - yyerror("tls options without tls listener"); - YYERROR; - } - } - ; -socopts2 : socopts2 socopts1 nl - | socopts1 optnl - ; -socopts1 : LISTEN ON opttls PORT NUMBER { - struct thg *thg; + memset(new_thing->iface, 0, + sizeof(new_thing->iface)); - TAILQ_FOREACH(thg, &pthgsd->thgs, entry) { - if (thg->port == $5 && (thg->tls || $3)) { - yyerror("tls port already used"); - YYERROR; - } - } - newthg->port = $5; - } - | CONNECT ON PORT NUMBER { - newthg->conn_port = $4; - } - | RECEIVE ON PORT NUMBER { - newthg->conn_port = $4; - } - | PASSWORD STRING { - if ((newthg->password = strdup($2)) == NULL) - fatalx("out of memory"); - free($2); - } - | PERSISTENT NUMBER { - if ($2) - newthg->persist = true; - else - newthg->persist = false; - } - | bindopts2 - | maxclientssub - | TLS tlsopts { - if (newthg->tls == false) { - yyerror("tls options without tls listener"); - YYERROR; - } - } - ; -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->persist = true; - newthg->password = ""; + memset(new_thing->location, 0, + sizeof(new_thing->location)); + memset(new_thing->ipaddr, 0, sizeof(new_thing->ipaddr)); + memset(new_thing->udp, 0, sizeof(new_thing->udp)); + memset(new_thing->password, 0, + sizeof(new_thing->password)); + memset(new_thing->parity, 0, sizeof(new_thing->parity)); - newthg->tls_protocols = TLS_PROTOCOLS_DEFAULT; - newthg->tls_flags = 0; - if ((newthg->tls_cert_file = strdup(TLS_CERT)) == NULL) - fatalx("out of memory"); - if ((newthg->tls_key_file = strdup(TLS_KEY)) == NULL) - fatalx("out of memory"); - strlcpy(newthg->tls_ciphers, TLS_CIPHERS, - sizeof(newthg->tls_ciphers)); - strlcpy(newthg->tls_dhe_params, TLS_DHE_PARAMS, - sizeof(newthg->tls_dhe_params)); - strlcpy(newthg->tls_ecdhe_curves, TLS_ECDHE_CURVES, - sizeof(newthg->tls_ecdhe_curves)); + new_thing->max_clients = thingsd_env->max_clients; + new_thing->port = thingsd_env->port; + new_thing->baud = DEFAULT_BAUD; + new_thing->conn_port = -1; + new_thing->data_bits = -1; + new_thing->stop_bits = -1; + new_thing->hw_ctl = false; + new_thing->sw_ctl = false; + new_thing->persist = true; + + new_thing->tls_protocols = TLS_PROTOCOLS_DEFAULT; + new_thing->tls_flags = 0; + + memset(new_thing->tls_cert_file, 0, + sizeof(new_thing->tls_cert_file)); + pn = strlcpy(new_thing->tls_cert_file, TLS_CERT, + sizeof(new_thing->tls_cert_file)); + if (pn >= sizeof(new_thing->tls_cert_file)) + fatalx("%s: new_thing->tls_cert_file too long", + __func__); + memset(new_thing->tls_key_file, 0, + sizeof(new_thing->tls_key_file)); + pn = strlcpy(new_thing->tls_key_file, TLS_KEY, + sizeof(new_thing->tls_key_file)); + if (pn >= sizeof(new_thing->tls_key_file)) + fatalx("%s: new_thing->tls_key_file too long", + __func__); + pn = strlcpy(new_thing->tls_ciphers, TLS_CIPHERS, + sizeof(new_thing->tls_ciphers)); + if (pn >= sizeof(new_thing->tls_ciphers)) + fatalx("thing strlcpy"); + pn = strlcpy(new_thing->tls_dhe_params, TLS_DHE_PARAMS, + sizeof(new_thing->tls_dhe_params)); + if (pn >= sizeof(new_thing->tls_dhe_params)) + fatalx("thing strlcpy"); + pn = strlcpy(new_thing->tls_ecdhe_curves, + TLS_ECDHE_CURVES, + sizeof(new_thing->tls_ecdhe_curves)); + if (pn >= sizeof(new_thing->tls_ecdhe_curves)) + fatalx("thing strlcpy"); + free($2); } '{' optnl thingopts2 '}' { - if (newthg->ipaddr != NULL && newthg->conn_port == -1) { + if (strlen(new_thing->ipaddr) != 0 && + new_thing->conn_port == -1) { yyerror("ipaddr connect port empty"); YYERROR; } - if (newthg->ipaddr != NULL && - newthg->location != NULL) { + if (strlen(new_thing->ipaddr) != 0 && + strlen(new_thing->location) != 0) { yyerror("too many ipaddr device arguments"); YYERROR; } - if (newthg->udp != NULL && newthg->conn_port == -1) { + if (strlen(new_thing->udp) != 0 && + new_thing->rcv_port == -1) { yyerror("udp receive port empty"); YYERROR; } - if (newthg->udp != NULL && newthg->location != NULL) { + if (strlen(new_thing->udp) != 0 && + strlen(new_thing->location) != 0) { yyerror("too many udp device arguments"); YYERROR; } - if (pthgsd->port == 0) { + if (thingsd_env->port == 0) { yyerror("could not set default port"); YYERROR; } - if (newthg->tls) - if (load_tls(newthg) == -2) + if (new_thing->tls) + if (load_tls(new_thing) == -2) YYABORT; - TAILQ_INSERT_TAIL(&pthgsd->thgs, newthg, entry); } ; + +thingopts1 : IPADDR STRING { + if (strlen($2) == 0) { + yyerror("ipaddr string empty"); + YYERROR; + } + pn = strlcpy(new_thing->ipaddr, $2, + sizeof(new_thing->ipaddr)); + if (pn >= sizeof(new_thing->ipaddr)) + fatalx("%s: new_thing->ipaddr too long", + __func__); + free($2); + } '{' optnl socketopts2 '}' + | LOCATION STRING { + pn = strlcpy(new_thing->location, $2, + sizeof(new_thing->location)); + if (pn >= sizeof(new_thing->location)) + fatalx("%s: new_thing->location too long", + __func__); + free($2); + } locationopts + | UDP STRING { + pn = strlcpy(new_thing->udp, $2, + sizeof(new_thing->udp)); + if (pn >= sizeof(new_thing->udp)) + fatalx("%s: new_thing->udp too long", + __func__); + free($2); + } '{' optnl socketopts2 '}' + ; + +thingopts2 : thingopts2 thingopts1 nl + | thingopts1 optnl + ; + +thingretry : CONNECTION RETRY NUMBER { + if ($3 >= MIN_RETRY && $3 <= MAX_RETRY) + thingsd_env->conn_retry = $3; + } + ; + +things : THINGS '{' subthings2 '}' + ; + +tlscltopt : /* empty */ + | tlscltopt CRL STRING { + new_thing->tls_flags = TLSFLAG_CRL; + pn = strlcpy(new_thing->tls_crl_file, $3, + sizeof(new_thing->tls_crl_file)); + if (pn >= sizeof(new_thing->tls_crl_file)) + fatalx("%s: new_thing->tls_crl_file too long", + __func__); + free($3); + } + | tlscltopt OPTIONAL { + new_thing->tls_flags |= TLSFLAG_OPTIONAL; + } + ; + tlsopts : CERTIFICATE STRING { - free(newthg->tls_cert_file); - if ((newthg->tls_cert_file = strdup($2)) == NULL) - fatalx("out of memory"); + pn = strlcpy(new_thing->tls_cert_file, $2, + sizeof(new_thing->tls_cert_file)); + if (pn >= sizeof(new_thing->tls_cert_file)) + fatalx("%s: new_thing->tls_cert_file too long", + __func__); free($2); } - | KEY STRING { - free(newthg->tls_key_file); - if ((newthg->tls_key_file = strdup($2)) == NULL) - fatalx("out of memory"); - free($2); - } - | OCSP STRING { - free(newthg->tls_ocsp_staple_file); - if ((newthg->tls_ocsp_staple_file = strdup($2)) == NULL) - fatalx("out of memory"); - free($2); - } | CIPHERS STRING { - if (strlcpy(newthg->tls_ciphers, $2, - sizeof(newthg->tls_ciphers)) >= - sizeof(newthg->tls_ciphers)) { + if (strlcpy(new_thing->tls_ciphers, $2, + sizeof(new_thing->tls_ciphers)) >= + sizeof(new_thing->tls_ciphers)) { yyerror("ciphers too long"); free($2); YYERROR; @@ -451,16 +648,18 @@ tlsopts : CERTIFICATE STRING { free($2); } | CLIENT CA STRING tlscltopt { - newthg->tls_flags |= TLSFLAG_CA; - free(newthg->tls_ca_file); - if ((newthg->tls_ca_file = strdup($3)) == NULL) - fatalx("out of memory"); + new_thing->tls_flags |= TLSFLAG_CA; + pn = strlcpy(new_thing->tls_ca_file, $3, + sizeof(new_thing->tls_ca_file)); + if (pn >= sizeof(new_thing->tls_ca_file)) + fatalx("%s: new_thing->tls_ca_file too long", + __func__); free($3); } | DHE STRING { - if (strlcpy(newthg->tls_dhe_params, $2, - sizeof(newthg->tls_dhe_params)) >= - sizeof(newthg->tls_dhe_params)) { + if (strlcpy(new_thing->tls_dhe_params, $2, + sizeof(new_thing->tls_dhe_params)) >= + sizeof(new_thing->tls_dhe_params)) { yyerror("dhe too long"); free($2); YYERROR; @@ -468,18 +667,34 @@ tlsopts : CERTIFICATE STRING { free($2); } | ECDHE STRING { - if (strlcpy(newthg->tls_ecdhe_curves, $2, - sizeof(newthg->tls_ecdhe_curves)) >= - sizeof(newthg->tls_ecdhe_curves)) { + if (strlcpy(new_thing->tls_ecdhe_curves, $2, + sizeof(new_thing->tls_ecdhe_curves)) >= + sizeof(new_thing->tls_ecdhe_curves)) { yyerror("ecdhe too long"); free($2); YYERROR; } free($2); } + | KEY STRING { + pn = strlcpy(new_thing->tls_key_file, $2, + sizeof(new_thing->tls_key_file)); + if (pn >= sizeof(new_thing->tls_key_file)) + fatalx("%s: new_thing->tls_key_file too long", + __func__); + free($2); + } + | OCSP STRING { + pn = strlcpy(new_thing->tls_ocsp_staple_file, $2, + sizeof(new_thing->tls_ocsp_staple_file)); + if (pn >= sizeof(new_thing->tls_ocsp_staple_file)) + fatalx("%s: new_thing->tls_ocsp_staple_file " + "too long", __func__); + free($2); + } | PROTOCOLS STRING { if (tls_config_parse_protocols( - &newthg->tls_protocols, $2) != 0) { + &new_thing->tls_protocols, $2) != 0) { yyerror("invalid tls protocols"); free($2); YYERROR; @@ -487,27 +702,27 @@ tlsopts : CERTIFICATE STRING { free($2); } ; -tlscltopt : /* empty */ - | tlscltopt CRL STRING { - newthg->tls_flags = TLSFLAG_CRL; - free(newthg->tls_crl_file); - if ((newthg->tls_crl_file = strdup($3)) == NULL) - fatalx("out of memory"); + +varset : STRING '=' string { + char *s = $1; + if (thingsd_env->thingsd_verbose) + printf("%s = \"%s\"\n", $1, $3); + while (*s++) { + if (isspace((unsigned char)*s)) { + yyerror("macro name cannot contain " + "whitespace"); + YYERROR; + } + } + if (symset($1, $3, 0) == -1) + fatal("cannot store variable"); + free($1); free($3); } - | tlscltopt OPTIONAL { - newthg->tls_flags |= TLSFLAG_OPTIONAL; - } ; -optcomma : ',' optcomma - | /* emtpy */ - ; -optnl : '\n' optnl - | /* empty */ - ; -nl : '\n' optnl - ; + %% + struct keywords { const char *k_name; int k_val; @@ -535,14 +750,17 @@ 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 */ +int +lookup(char *s) +{ + /* This has to be sorted always. */ static const struct keywords keywords[] = { { "baud", BAUD }, { "bind", BIND }, { "ca", CA }, { "certificate", CERTIFICATE }, { "ciphers", CIPHERS }, + { "client", CLIENT }, { "clients", CLIENTS }, { "connect", CONNECT }, { "connection", CONNECTION }, @@ -552,6 +770,7 @@ int lookup(char *s) { { "dhe", DHE }, { "ecdhe", ECDHE }, { "hardware", HARDWARE }, + { "include", INCLUDE }, { "interface", INTERFACE }, { "ipaddr", IPADDR }, { "key", KEY }, @@ -565,8 +784,9 @@ int lookup(char *s) { { "parity", PARITY }, { "password", PASSWORD }, { "persistent", PERSISTENT }, - { "protocols", PROTOCOLS }, { "port", PORT }, + { "prefork", PREFORK }, + { "protocols", PROTOCOLS }, { "receive", RECEIVE }, { "retry", RETRY }, { "software", SOFTWARE }, @@ -580,8 +800,10 @@ int lookup(char *s) { { "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 @@ -589,18 +811,19 @@ int lookup(char *s) { } #define MAXPUSHBACK 128 -u_char *parsebuf; -int parseindex; -u_char pushback_buffer[MAXPUSHBACK]; -int pushback_index = 0; +unsigned char *parsebuf; +int parseindex; +unsigned char pushback_buffer[MAXPUSHBACK]; +int pushback_index = 0; + int lgetc(int quotec) { - int c = 0, next; + int c, next; if (parsebuf) { - /* Read character from the parsebuffer instead of file input */ + /* Read character from the parsebuffer instead of input. */ if (parseindex >= 0) { if (parsebuf == NULL) return(0); @@ -608,13 +831,15 @@ lgetc(int quotec) return(0); c = parsebuf[parseindex++]; if (c != '\0') - return(c); + return (c); parsebuf = NULL; } else parseindex++; } + if (pushback_index) return (pushback_buffer[--pushback_index]); + if (quotec) { if (parseindex > 0) { /* malformed packet */ @@ -624,13 +849,14 @@ lgetc(int quotec) } if ((c = getc(file->stream)) == EOF) { yyerror("reached end of file while parsing " - "quoted string"); + "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); @@ -642,11 +868,13 @@ lgetc(int quotec) file->lineno++; } } + while (c == EOF) { if (file == topfile || popfile() == EOF) return (EOF); c = getc(file->stream); } + parseindex = 0; return (c); } @@ -673,7 +901,8 @@ findeol(void) int c; parsebuf = NULL; - /* skip to either EOF or the first real EOL */ + + /* Skip to either EOF or the first real EOL. */ while (1) { if (pushback_index) c = pushback_buffer[--pushback_index]; @@ -692,18 +921,47 @@ findeol(void) int yylex(void) { - u_char buf[8096]; - u_char *p; - int quotec, next, c; - int token; + unsigned char buf[8096]; + unsigned char *p, *val; + int quotec, next, c; + int token; +top: p = buf; while ((c = lgetc(0)) == ' ' || c == '\t') ; /* nothing */ + yylval.lineno = file->lineno; if (c == '#') while ((c = lgetc(0)) != '\n' && c != EOF) ; /* nothing */ + if (c == '$' && parsebuf == NULL) { + while (1) { + if ((c = lgetc(0)) == EOF) + return (0); + + if (p + 1 >= buf + sizeof(buf) - 1) { + yyerror("string too long"); + return (findeol()); + } + if (isalnum(c) || c == '_') { + *p++ = c; + continue; + } + *p = '\0'; + lungetc(c); + break; + } + val = symget(buf); + if (val == NULL) { + yyerror("macro '%s' not defined", buf); + return (findeol()); + } + parsebuf = val; + parseindex = 0; + goto top; + } + switch (c) { case '\'': case '"': @@ -739,11 +997,13 @@ yylex(void) } yylval.v.string = strdup(buf); if (yylval.v.string == NULL) - fatalx("yylex: strdup"); + err(1, "yylex: strdup"); return (STRING); } + #define allowed_to_end_number(x) \ (isspace(x) || x == ')' || x ==',' || x == '/' || x == '}' || x == '=') + if (c == '-' || isdigit(c)) { do { *p++ = c; @@ -776,12 +1036,14 @@ nodigits: return (c); } } + #define allowed_in_string(x) \ (isalnum(x) || (ispunct(x) && x != '(' && x != ')' && \ - x != '{' && x != '}' && x != '<' && x != '>' && \ - x != '!' && x != '=' && x != '/' && x != '#' && \ + x != '{' && x != '}' && \ + x != '!' && x != '=' && x != '#' && \ x != ',')) - if (isalnum(c) || c == ':' || c == '_' || c == '*') { + + if (isalnum(c) || c == ':' || c == '_') { do { *p++ = c; if ((unsigned)(p-buf) >= sizeof(buf)) { @@ -793,7 +1055,7 @@ nodigits: *p = '\0'; if ((token = lookup(buf)) == STRING) if ((yylval.v.string = strdup(buf)) == NULL) - fatalx("yylex: strdup"); + err(1, "yylex: strdup"); return (token); } if (c == '\n') { @@ -805,17 +1067,37 @@ nodigits: return (c); } +int +check_file_secrecy(int fd, const char *fname) +{ + struct stat st; + + if (fstat(fd, &st)) { + log_warn("cannot stat %s", fname); + return (-1); + } + if (st.st_uid != 0 && st.st_uid != getuid()) { + log_warnx("%s: owner not root or current user", fname); + return (-1); + } + if (st.st_mode & (S_IWGRP | S_IXGRP | S_IRWXO)) { + log_warnx("%s: thing writable or world read/writable", fname); + return (-1); + } + return (0); +} + struct file * -pushfile(const char *name) +pushfile(const char *name, int secret) { struct file *nfile; if ((nfile = calloc(1, sizeof(struct file))) == NULL) { - log_warn("malloc"); + log_warn("calloc"); return (NULL); } if ((nfile->name = strdup(name)) == NULL) { - log_warn("malloc"); + log_warn("strdup"); free(nfile); return (NULL); } @@ -824,6 +1106,12 @@ pushfile(const char *name) free(nfile->name); free(nfile); return (NULL); + } else if (secret && + check_file_secrecy(fileno(nfile->stream), nfile->name)) { + fclose(nfile->stream); + free(nfile->name); + free(nfile); + return (NULL); } nfile->lineno = 1; TAILQ_INSERT_TAIL(&files, nfile, entry); @@ -886,78 +1174,197 @@ popbuff(void) } int -parse_conf(const char *filename) +parse_config(const char *filename) { - int errors; + struct sym *sym, *next; - 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); + file = pushfile(filename, 0); + if (file == NULL) { + log_warn("failed to open %s", filename); + return (0); + } topfile = file; + + TAILQ_INIT(thingsd_env->things); + thingsd_env->client_fptr = client_do_chk; + thingsd_env->conn_retry = CONN_RETRY; + thingsd_env->dead_things->run = 1; + yyparse(); errors = file->errors; popfile(); - return (errors ? -1 : 0); + + /* Free macros and check which have not been used. */ + TAILQ_FOREACH_SAFE(sym, &symhead, entry, next) { + if ((thingsd_env->thingsd_verbose > 1) && !sym->used) + fprintf(stderr, "warning: macro '%s' not used\n", + sym->nam); + if (!sym->persist) { + free(sym->nam); + free(sym->val); + TAILQ_REMOVE(&symhead, sym, entry); + free(sym); + } + } + + if (errors) + return (-1); + + return (0); } int -parse_buf(struct clt *pclt, u_char *pkt, int len) +symset(const char *nam, const char *val, int persist) { - int errors; + struct sym *sym; + TAILQ_FOREACH(sym, &symhead, entry) { + if (strcmp(nam, sym->nam) == 0) + break; + } + + if (sym != NULL) { + if (sym->persist == 1) + return (0); + else { + free(sym->nam); + free(sym->val); + TAILQ_REMOVE(&symhead, sym, entry); + free(sym); + } + } + if ((sym = calloc(1, sizeof(*sym))) == NULL) + return (-1); + + sym->nam = strdup(nam); + if (sym->nam == NULL) { + free(sym); + return (-1); + } + sym->val = strdup(val); + if (sym->val == NULL) { + free(sym->nam); + free(sym); + return (-1); + } + sym->used = 0; + sym->persist = persist; + TAILQ_INSERT_TAIL(&symhead, sym, entry); + return (0); +} + +int +cmdline_symset(char *s) +{ + char *sym, *val; + int ret; + size_t len; + + if ((val = strrchr(s, '=')) == NULL) + return (-1); + + len = strlen(s) - strlen(val) + 1; + if ((sym = malloc(len)) == NULL) + errx(1, "cmdline_symset: malloc"); + + strlcpy(sym, s, len); + + ret = symset(sym, val + 1, 1); + free(sym); + + return (ret); +} + +char * +symget(const char *nam) +{ + struct sym *sym; + + TAILQ_FOREACH(sym, &symhead, entry) { + if (strcmp(nam, sym->nam) == 0) { + sym->used = 1; + return (sym->val); + } + } + return (NULL); +} + +int +parse_buf(struct client *pclient, u_char *pkt, int len) +{ pkt_len = len; - tclt = pclt; - my_fd = tclt->fd; + tclient = pclient; + my_fd = tclient->fd; + if ((file = pushbuff(pkt)) == NULL) return (-1); + topfile = file; yyparse(); errors = file->errors; + popbuff(); free(file); + return (errors ? -1 : 0); } -struct thg * -new_thg(char *name) +struct thing * +conf_new_thing(char *name) { - struct thg *thg; + struct thing *thing; + size_t n; - if ((thg = calloc(1, sizeof(*thg))) == NULL) - fatalx("no thg calloc"); - if ((thg->name = strdup(name)) == NULL) - fatalx("no thg name"); - return (thg); -}; + TAILQ_FOREACH(thing, thingsd_env->things, entry) { + if (strcmp(name, thing->name) == 0) + return (thing); + } + thing = calloc(1, sizeof(*thing)); + if (thing == NULL) + errx(1, "get_thing: calloc"); + n = strlcpy(thing->name, name, sizeof(thing->name)); + if (n >= sizeof(thing->name)) + fatalx("%s: thing->name too long", __func__); + + TAILQ_INSERT_TAIL(thingsd_env->things, thing, entry); + + return (thing); +} + +void +clear_config(struct thingsd *xconf) +{ + struct thing *thing; + + while ((thing = TAILQ_FIRST(xconf->things)) != NULL) { + TAILQ_REMOVE(xconf->things, thing, entry); + free(thing); + } + + free(xconf); +} + int -load_tls(struct thg *pthg) +load_tls(struct thing *thing) { - if (tls_load_keypair(pthg) == -1) { + if (tls_load_keypair(thing) == -1) { log_warnx("%s:%d: thing \"%s\": failed to load public/private" - " keys", file->name, yylval.lineno, pthg->name); + " keys", file->name, yylval.lineno, thing->name); return -1; } - if (tls_load_ca(pthg) == -1) { - yyerror("failed to load ca cert(s) for thing %s", pthg->name); + if (tls_load_ca(thing) == -1) { + yyerror("failed to load ca cert(s) for thing %s", thing->name); return -2; } - if (tls_load_crl(pthg) == -1) { - yyerror("failed to load crl(s) for thing %s", pthg->name); - free(pthg); + if (tls_load_crl(thing) == -1) { + yyerror("failed to load crl(s) for thing %s", thing->name); + free(thing); return -2; } - if (tls_load_ocsp(pthg) == -1) { - yyerror("failed to load ocsp staple for thing %s", pthg->name); - free(pthg); + if (tls_load_ocsp(thing) == -1) { + yyerror("failed to load ocsp staple for thing %s", thing->name); + free(thing); return -2; } return 0; blob - /dev/null blob + fc65e060564fdddd45bc820eebc9784288adab06 (mode 644) --- /dev/null +++ thingsd/proc.c @@ -0,0 +1,843 @@ +/* + * Copyright (c) 2010 - 2016 Reyk Floeter + * Copyright (c) 2008 Pierre-Yves Ritschard + * + * 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 "proc.h" + +void proc_exec(struct privsep *, struct privsep_proc *, unsigned int, + int, char **); +void proc_setup(struct privsep *, struct privsep_proc *, unsigned int); +void proc_open(struct privsep *, int, int); +void proc_accept(struct privsep *, int, enum privsep_procid, + unsigned int); +void proc_close(struct privsep *); +int proc_ispeer(struct privsep_proc *, unsigned int, enum privsep_procid); +void proc_shutdown(struct privsep_proc *); +void proc_sig_handler(int, short, void *); +void proc_range(struct privsep *, enum privsep_procid, int *, int *); +int proc_dispatch_null(int, struct privsep_proc *, struct imsg *); + +int +proc_ispeer(struct privsep_proc *procs, unsigned int nproc, + enum privsep_procid type) +{ + unsigned int i; + + for (i = 0; i < nproc; i++) + if (procs[i].p_id == type) + return (1); + + return (0); +} + +enum privsep_procid +proc_getid(struct privsep_proc *procs, unsigned int nproc, + const char *proc_name) +{ + struct privsep_proc *p; + unsigned int proc; + + for (proc = 0; proc < nproc; proc++) { + p = &procs[proc]; + if (strcmp(p->p_title, proc_name)) + continue; + + return (p->p_id); + } + + return (PROC_MAX); +} + +void +proc_exec(struct privsep *ps, struct privsep_proc *procs, unsigned int nproc, + int argc, char **argv) +{ + unsigned int proc, nargc, i, proc_i; + char **nargv; + struct privsep_proc *p; + char num[32]; + int fd; + + /* Prepare the new process argv. */ + nargv = calloc(argc + 5, sizeof(char *)); + if (nargv == NULL) + fatal("%s: calloc", __func__); + + /* Copy call argument first. */ + nargc = 0; + nargv[nargc++] = argv[0]; + + /* Set process name argument and save the position. */ + nargv[nargc++] = "-P"; + proc_i = nargc; + nargc++; + + /* Point process instance arg to stack and copy the original args. */ + nargv[nargc++] = "-I"; + nargv[nargc++] = num; + for (i = 1; i < (unsigned int) argc; i++) + nargv[nargc++] = argv[i]; + + nargv[nargc] = NULL; + + for (proc = 0; proc < nproc; proc++) { + p = &procs[proc]; + + /* Update args with process title. */ + nargv[proc_i] = (char *)(uintptr_t)p->p_title; + + /* Fire children processes. */ + for (i = 0; i < ps->ps_instances[p->p_id]; i++) { + /* Update the process instance number. */ + snprintf(num, sizeof(num), "%u", i); + + fd = ps->ps_pipes[p->p_id][i].pp_pipes[PROC_PARENT][0]; + ps->ps_pipes[p->p_id][i].pp_pipes[PROC_PARENT][0] = -1; + + switch (fork()) { + case -1: + fatal("%s: fork", __func__); + break; + case 0: + /* First create a new session */ + if (setsid() == -1) + fatal("setsid"); + + /* Prepare parent socket. */ + if (fd != PROC_PARENT_SOCK_FILENO) { + if (dup2(fd, PROC_PARENT_SOCK_FILENO) + == -1) + fatal("dup2"); + } else if (fcntl(fd, F_SETFD, 0) == -1) + fatal("fcntl"); + + execvp(argv[0], nargv); + fatal("%s: execvp", __func__); + break; + default: + /* Close child end. */ + close(fd); + break; + } + } + } + + free(nargv); +} + +void +proc_connect(struct privsep *ps) +{ + struct imsgev *iev; + unsigned int src, dst, inst; + + /* Don't distribute any sockets if we are not really going to run. */ + if (ps->ps_noaction) + return; + + for (dst = 0; dst < PROC_MAX; dst++) { + /* We don't communicate with ourselves. */ + if (dst == PROC_PARENT) + continue; + + for (inst = 0; inst < ps->ps_instances[dst]; inst++) { + iev = &ps->ps_ievs[dst][inst]; + imsg_init(&iev->ibuf, ps->ps_pp->pp_pipes[dst][inst]); + event_set(&iev->ev, iev->ibuf.fd, iev->events, + iev->handler, iev->data); + event_add(&iev->ev, NULL); + } + } + + /* Distribute the socketpair()s for everyone. */ + for (src = 0; src < PROC_MAX; src++) + for (dst = src; dst < PROC_MAX; dst++) { + /* Parent already distributed its fds. */ + if (src == PROC_PARENT || dst == PROC_PARENT) + continue; + + proc_open(ps, src, dst); + } +} + +void +proc_init(struct privsep *ps, struct privsep_proc *procs, unsigned int nproc, + int argc, char **argv, enum privsep_procid proc_id) +{ + struct privsep_proc *p = NULL; + struct privsep_pipes *pa, *pb; + unsigned int proc; + unsigned int dst; + int fds[2]; + + /* Don't initiate anything if we are not really going to run. */ + if (ps->ps_noaction) + return; + + if (proc_id == PROC_PARENT) { + privsep_process = PROC_PARENT; + proc_setup(ps, procs, nproc); + + /* + * Create the children sockets so we can use them + * to distribute the rest of the socketpair()s using + * proc_connect() later. + */ + for (dst = 0; dst < PROC_MAX; dst++) { + /* Don't create socket for ourselves. */ + if (dst == PROC_PARENT) + continue; + + for (proc = 0; proc < ps->ps_instances[dst]; proc++) { + pa = &ps->ps_pipes[PROC_PARENT][0]; + pb = &ps->ps_pipes[dst][proc]; + if (socketpair(AF_UNIX, + SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, + PF_UNSPEC, fds) == -1) + fatal("%s: socketpair", __func__); + + pa->pp_pipes[dst][proc] = fds[0]; + pb->pp_pipes[PROC_PARENT][0] = fds[1]; + } + } + + /* Engage! */ + proc_exec(ps, procs, nproc, argc, argv); + return; + } + + /* Initialize a child */ + for (proc = 0; proc < nproc; proc++) { + if (procs[proc].p_id != proc_id) + continue; + p = &procs[proc]; + break; + } + if (p == NULL || p->p_init == NULL) + fatalx("%s: process %d missing process initialization", + __func__, proc_id); + + p->p_init(ps, p); + + fatalx("failed to initiate child process"); +} + +void +proc_accept(struct privsep *ps, int fd, enum privsep_procid dst, + unsigned int n) +{ + struct privsep_pipes *pp = ps->ps_pp; + struct imsgev *iev; + + if (ps->ps_ievs[dst] == NULL) { +#if DEBUG > 1 + log_debug("%s: %s src %d %d to dst %d %d not connected", + __func__, ps->ps_title[privsep_process], + privsep_process, ps->ps_instance + 1, + dst, n + 1); +#endif + close(fd); + return; + } + + if (pp->pp_pipes[dst][n] != -1) { + log_warnx("%s: duplicated descriptor", __func__); + close(fd); + return; + } else + pp->pp_pipes[dst][n] = fd; + + iev = &ps->ps_ievs[dst][n]; + imsg_init(&iev->ibuf, fd); + event_set(&iev->ev, iev->ibuf.fd, iev->events, iev->handler, iev->data); + event_add(&iev->ev, NULL); +} + +void +proc_setup(struct privsep *ps, struct privsep_proc *procs, unsigned int nproc) +{ + unsigned int i, j, src, dst, id; + struct privsep_pipes *pp; + + /* Initialize parent title, ps_instances and procs. */ + ps->ps_title[PROC_PARENT] = "parent"; + + for (src = 0; src < PROC_MAX; src++) + /* Default to 1 process instance */ + if (ps->ps_instances[src] < 1) + ps->ps_instances[src] = 1; + + for (src = 0; src < nproc; src++) { + procs[src].p_ps = ps; + if (procs[src].p_cb == NULL) + procs[src].p_cb = proc_dispatch_null; + + id = procs[src].p_id; + ps->ps_title[id] = procs[src].p_title; + if ((ps->ps_ievs[id] = calloc(ps->ps_instances[id], + sizeof(struct imsgev))) == NULL) + fatal("%s: calloc", __func__); + + /* With this set up, we are ready to call imsg_init(). */ + for (i = 0; i < ps->ps_instances[id]; i++) { + ps->ps_ievs[id][i].handler = proc_dispatch; + ps->ps_ievs[id][i].events = EV_READ; + ps->ps_ievs[id][i].proc = &procs[src]; + ps->ps_ievs[id][i].data = &ps->ps_ievs[id][i]; + } + } + + /* + * Allocate pipes for all process instances (incl. parent) + * + * - ps->ps_pipes: N:M mapping + * N source processes connected to M destination processes: + * [src][instances][dst][instances], for example + * [PROC_RELAY][3][PROC_CA][3] + * + * - ps->ps_pp: per-process 1:M part of ps->ps_pipes + * Each process instance has a destination array of socketpair fds: + * [dst][instances], for example + * [PROC_PARENT][0] + */ + for (src = 0; src < PROC_MAX; src++) { + /* Allocate destination array for each process */ + if ((ps->ps_pipes[src] = calloc(ps->ps_instances[src], + sizeof(struct privsep_pipes))) == NULL) + fatal("%s: calloc", __func__); + + for (i = 0; i < ps->ps_instances[src]; i++) { + pp = &ps->ps_pipes[src][i]; + + for (dst = 0; dst < PROC_MAX; dst++) { + /* Allocate maximum fd integers */ + if ((pp->pp_pipes[dst] = + calloc(ps->ps_instances[dst], + sizeof(int))) == NULL) + fatal("%s: calloc", __func__); + + /* Mark fd as unused */ + for (j = 0; j < ps->ps_instances[dst]; j++) + pp->pp_pipes[dst][j] = -1; + } + } + } + + ps->ps_pp = &ps->ps_pipes[privsep_process][ps->ps_instance]; +} + +void +proc_kill(struct privsep *ps) +{ + char *cause; + pid_t pid; + int len, status; + + if (privsep_process != PROC_PARENT) + return; + + proc_close(ps); + + do { + pid = waitpid(WAIT_ANY, &status, 0); + if (pid <= 0) + continue; + + if (WIFSIGNALED(status)) { + len = asprintf(&cause, "terminated; signal %d", + WTERMSIG(status)); + } else if (WIFEXITED(status)) { + if (WEXITSTATUS(status) != 0) + len = asprintf(&cause, "exited abnormally"); + else + len = 0; + } else + len = -1; + + if (len == 0) { + /* child exited OK, don't print a warning message */ + } else if (len != -1) { + log_warnx("lost child: pid %u %s", pid, cause); + free(cause); + } else + log_warnx("lost child: pid %u", pid); + } while (pid != -1 || (pid == -1 && errno == EINTR)); +} + +void +proc_open(struct privsep *ps, int src, int dst) +{ + struct privsep_pipes *pa, *pb; + struct privsep_fd pf; + int fds[2]; + unsigned int i, j; + + /* Exchange pipes between process. */ + for (i = 0; i < ps->ps_instances[src]; i++) { + for (j = 0; j < ps->ps_instances[dst]; j++) { + /* Don't create sockets for ourself. */ + if (src == dst && i == j) + continue; + + pa = &ps->ps_pipes[src][i]; + pb = &ps->ps_pipes[dst][j]; + if (socketpair(AF_UNIX, + SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, + PF_UNSPEC, fds) == -1) + fatal("%s: socketpair", __func__); + + pa->pp_pipes[dst][j] = fds[0]; + pb->pp_pipes[src][i] = fds[1]; + + pf.pf_procid = src; + pf.pf_instance = i; + if (proc_compose_imsg(ps, dst, j, IMSG_CTL_PROCFD, + -1, pb->pp_pipes[src][i], &pf, sizeof(pf)) == -1) + fatal("%s: proc_compose_imsg", __func__); + + pf.pf_procid = dst; + pf.pf_instance = j; + if (proc_compose_imsg(ps, src, i, IMSG_CTL_PROCFD, + -1, pa->pp_pipes[dst][j], &pf, sizeof(pf)) == -1) + fatal("%s: proc_compose_imsg", __func__); + + /* + * We have to flush to send the descriptors and close + * them to avoid the fd ramp on startup. + */ + if (proc_flush_imsg(ps, src, i) == -1 || + proc_flush_imsg(ps, dst, j) == -1) + fatal("%s: imsg_flush", __func__); + } + } +} + +void +proc_close(struct privsep *ps) +{ + unsigned int dst, n; + struct privsep_pipes *pp; + + if (ps == NULL) + return; + + pp = ps->ps_pp; + + for (dst = 0; dst < PROC_MAX; dst++) { + if (ps->ps_ievs[dst] == NULL) + continue; + + for (n = 0; n < ps->ps_instances[dst]; n++) { + if (pp->pp_pipes[dst][n] == -1) + continue; + + /* Cancel the fd, close and invalidate the fd */ + event_del(&(ps->ps_ievs[dst][n].ev)); + imsg_clear(&(ps->ps_ievs[dst][n].ibuf)); + close(pp->pp_pipes[dst][n]); + pp->pp_pipes[dst][n] = -1; + } + free(ps->ps_ievs[dst]); + } +} + +void +proc_shutdown(struct privsep_proc *p) +{ + struct privsep *ps = p->p_ps; + + if (p->p_id == PROC_CONTROL && ps) + control_cleanup(&ps->ps_csock); + + if (p->p_shutdown != NULL) + (*p->p_shutdown)(); + + proc_close(ps); + + log_info("%s, %s exiting, pid %d", getprogname(), p->p_title, getpid()); + + exit(0); +} + +void +proc_sig_handler(int sig, short event, void *arg) +{ + struct privsep_proc *p = arg; + + switch (sig) { + case SIGINT: + case SIGTERM: + proc_shutdown(p); + break; + case SIGCHLD: + case SIGHUP: + case SIGPIPE: + case SIGUSR1: + /* ignore */ + break; + default: + fatalx("proc_sig_handler: unexpected signal"); + /* NOTREACHED */ + } +} + +void +proc_run(struct privsep *ps, struct privsep_proc *p, + struct privsep_proc *procs, unsigned int nproc, + void (*run)(struct privsep *, struct privsep_proc *, void *), void *arg) +{ + struct passwd *pw; + const char *root; + struct control_sock *rcs; + + log_procinit(p->p_title); + + /* Set the process group of the current process */ + setpgid(0, 0); + + if (p->p_id == PROC_CONTROL && ps->ps_instance == 0) { + if (control_init(ps, &ps->ps_csock) == -1) + fatalx("%s: control_init", __func__); + TAILQ_FOREACH(rcs, &ps->ps_rcsocks, cs_entry) + if (control_init(ps, rcs) == -1) + fatalx("%s: control_init", __func__); + } + + /* Use non-standard user */ + if (p->p_pw != NULL) + pw = p->p_pw; + else + pw = ps->ps_pw; + + /* Change root directory */ + if (p->p_chroot != NULL) + root = p->p_chroot; + else + root = pw->pw_dir; + + if (chroot(root) == -1) + fatal("proc_run: chroot"); + if (chdir("/") == -1) + fatal("proc_run: chdir(\"/\")"); + + privsep_process = p->p_id; + + setproctitle("%s", p->p_title); + + if (setgroups(1, &pw->pw_gid) || + setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) || + setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid)) + fatal("proc_run: cannot drop privileges"); + + event_init(); + + signal_set(&ps->ps_evsigint, SIGINT, proc_sig_handler, p); + signal_set(&ps->ps_evsigterm, SIGTERM, proc_sig_handler, p); + signal_set(&ps->ps_evsigchld, SIGCHLD, proc_sig_handler, p); + signal_set(&ps->ps_evsighup, SIGHUP, proc_sig_handler, p); + signal_set(&ps->ps_evsigpipe, SIGPIPE, proc_sig_handler, p); + signal_set(&ps->ps_evsigusr1, SIGUSR1, proc_sig_handler, p); + + signal_add(&ps->ps_evsigint, NULL); + signal_add(&ps->ps_evsigterm, NULL); + signal_add(&ps->ps_evsigchld, NULL); + signal_add(&ps->ps_evsighup, NULL); + signal_add(&ps->ps_evsigpipe, NULL); + signal_add(&ps->ps_evsigusr1, NULL); + + proc_setup(ps, procs, nproc); + proc_accept(ps, PROC_PARENT_SOCK_FILENO, PROC_PARENT, 0); + if (p->p_id == PROC_CONTROL && ps->ps_instance == 0) { + TAILQ_INIT(&ctl_conns); + if (control_listen(&ps->ps_csock) == -1) + fatalx("%s: control_listen", __func__); + TAILQ_FOREACH(rcs, &ps->ps_rcsocks, cs_entry) + if (control_listen(rcs) == -1) + fatalx("%s: control_listen", __func__); + } + + DPRINTF("%s: %s %d/%d, pid %d", __func__, p->p_title, + ps->ps_instance + 1, ps->ps_instances[p->p_id], getpid()); + + if (run != NULL) + run(ps, p, arg); + + event_dispatch(); + + proc_shutdown(p); +} + +void +proc_dispatch(int fd, short event, void *arg) +{ + struct imsgev *iev = arg; + struct privsep_proc *p = iev->proc; + struct privsep *ps = p->p_ps; + struct imsgbuf *ibuf; + struct imsg imsg; + ssize_t n; + int verbose; + const char *title; + struct privsep_fd pf; + + title = ps->ps_title[privsep_process]; + ibuf = &iev->ibuf; + + if (event & EV_READ) { + if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN) + fatal("%s: imsg_read", __func__); + if (n == 0) { + /* this pipe is dead, so remove the event handler */ + event_del(&iev->ev); + event_loopexit(NULL); + return; + } + } + + if (event & EV_WRITE) { + if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN) + fatal("%s: msgbuf_write", __func__); + if (n == 0) { + /* this pipe is dead, so remove the event handler */ + event_del(&iev->ev); + event_loopexit(NULL); + return; + } + } + + for (;;) { + if ((n = imsg_get(ibuf, &imsg)) == -1) + fatal("%s: imsg_get", __func__); + if (n == 0) + break; + +#if DEBUG > 1 + log_debug("%s: %s %d got imsg %d peerid %d from %s %d", + __func__, title, ps->ps_instance + 1, + imsg.hdr.type, imsg.hdr.peerid, p->p_title, imsg.hdr.pid); +#endif + + /* + * Check the message with the program callback + */ + if ((p->p_cb)(fd, p, &imsg) == 0) { + /* Message was handled by the callback, continue */ + imsg_free(&imsg); + continue; + } + + /* + * Generic message handling + */ + switch (imsg.hdr.type) { + case IMSG_CTL_VERBOSE: + log_info("%s", __func__); + IMSG_SIZE_CHECK(&imsg, &verbose); + memcpy(&verbose, imsg.data, sizeof(verbose)); + log_setverbose(verbose); + break; + case IMSG_CTL_PROCFD: + IMSG_SIZE_CHECK(&imsg, &pf); + memcpy(&pf, imsg.data, sizeof(pf)); + proc_accept(ps, imsg.fd, pf.pf_procid, + pf.pf_instance); + break; + default: + log_warnx("%s: %s %d got invalid imsg %d peerid %d " + "from %s %d", + __func__, title, ps->ps_instance + 1, + imsg.hdr.type, imsg.hdr.peerid, + p->p_title, imsg.hdr.pid); + } + imsg_free(&imsg); + } + imsg_event_add(iev); +} + +int +proc_dispatch_null(int fd, struct privsep_proc *p, struct imsg *imsg) +{ + return (-1); +} + +/* + * imsg helper functions + */ + +void +imsg_event_add(struct imsgev *iev) +{ + if (iev->handler == NULL) { + imsg_flush(&iev->ibuf); + return; + } + + iev->events = EV_READ; + if (iev->ibuf.w.queued) + iev->events |= EV_WRITE; + + event_del(&iev->ev); + event_set(&iev->ev, iev->ibuf.fd, iev->events, iev->handler, iev->data); + event_add(&iev->ev, NULL); +} + +int +imsg_compose_event(struct imsgev *iev, uint16_t type, uint32_t peerid, + pid_t pid, int fd, void *data, uint16_t datalen) +{ + int ret; + + if ((ret = imsg_compose(&iev->ibuf, type, peerid, + pid, fd, data, datalen)) == -1) + return (ret); + imsg_event_add(iev); + return (ret); +} + +int +imsg_composev_event(struct imsgev *iev, uint16_t type, uint32_t peerid, + pid_t pid, int fd, const struct iovec *iov, int iovcnt) +{ + int ret; + + if ((ret = imsg_composev(&iev->ibuf, type, peerid, + pid, fd, iov, iovcnt)) == -1) + return (ret); + imsg_event_add(iev); + return (ret); +} + +void +proc_range(struct privsep *ps, enum privsep_procid id, int *n, int *m) +{ + if (*n == -1) { + /* Use a range of all target instances */ + *n = 0; + *m = ps->ps_instances[id]; + } else { + /* Use only a single slot of the specified peer process */ + *m = *n + 1; + } +} + +int +proc_compose_imsg(struct privsep *ps, enum privsep_procid id, int n, + uint16_t type, uint32_t peerid, int fd, void *data, uint16_t datalen) +{ + int m; + + proc_range(ps, id, &n, &m); + for (; n < m; n++) { + if (imsg_compose_event(&ps->ps_ievs[id][n], + type, peerid, ps->ps_instance + 1, fd, data, datalen) == -1) + return (-1); + } + + return (0); +} + +int +proc_compose(struct privsep *ps, enum privsep_procid id, + uint16_t type, void *data, uint16_t datalen) +{ + return (proc_compose_imsg(ps, id, -1, type, -1, -1, data, datalen)); +} + +int +proc_composev_imsg(struct privsep *ps, enum privsep_procid id, int n, + uint16_t type, uint32_t peerid, int fd, const struct iovec *iov, int iovcnt) +{ + int m; + + proc_range(ps, id, &n, &m); + for (; n < m; n++) + if (imsg_composev_event(&ps->ps_ievs[id][n], + type, peerid, ps->ps_instance + 1, fd, iov, iovcnt) == -1) + return (-1); + + return (0); +} + +int +proc_composev(struct privsep *ps, enum privsep_procid id, + uint16_t type, const struct iovec *iov, int iovcnt) +{ + return (proc_composev_imsg(ps, id, -1, type, -1, -1, iov, iovcnt)); +} + +int +proc_forward_imsg(struct privsep *ps, struct imsg *imsg, + enum privsep_procid id, int n) +{ + return (proc_compose_imsg(ps, id, n, imsg->hdr.type, + imsg->hdr.peerid, imsg->fd, imsg->data, IMSG_DATA_SIZE(imsg))); +} + +struct imsgbuf * +proc_ibuf(struct privsep *ps, enum privsep_procid id, int n) +{ + int m; + + proc_range(ps, id, &n, &m); + return (&ps->ps_ievs[id][n].ibuf); +} + +struct imsgev * +proc_iev(struct privsep *ps, enum privsep_procid id, int n) +{ + int m; + + proc_range(ps, id, &n, &m); + return (&ps->ps_ievs[id][n]); +} + +/* This function should only be called with care as it breaks async I/O */ +int +proc_flush_imsg(struct privsep *ps, enum privsep_procid id, int n) +{ + struct imsgbuf *ibuf; + int m, ret = 0; + + proc_range(ps, id, &n, &m); + for (; n < m; n++) { + if ((ibuf = proc_ibuf(ps, id, n)) == NULL) + return (-1); + do { + ret = imsg_flush(ibuf); + } while (ret == -1 && errno == EAGAIN); + if (ret == -1) + break; + imsg_event_add(&ps->ps_ievs[id][n]); + } + + return (ret); +} blob - 53d2f5cba52bd2a31abad4c9fdc074e0544e8c05 blob + e8b8b663c4ea05736d3d9ae6b53745fcb41199a9 --- thingsd/serial.c +++ thingsd/serial.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2019 Tracey Emery + * Copyright (c) 2016, 2019, 2020 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 @@ -21,53 +21,63 @@ #include #include +#include #include #include #include +#include "proc.h" #include "thingsd.h" -extern struct dthgs *pdthgs; - void -open_thgs(struct thgsd *pthgsd, bool reconn) +open_things(struct thingsd *env, bool reconn) { - struct thg *thg; - struct dthg *dthg; + struct thing *thing; + struct dead_thing *dead_thing; struct termios s_opts; int fd; int baudrate = 0, stop = 0; - evbuffercb sockrd = sock_rd; - evbuffercb sockwr = sock_wr; + evbuffercb socketrd = socket_rd; + evbuffercb socketwr = socket_wr; - TAILQ_FOREACH(thg, &pthgsd->thgs, entry) { - if (thg->exists) + TAILQ_FOREACH(thing, env->things, entry) { + if (thing->exists) continue; - if (thg->location != NULL) { - thg->type = DEV; + + if (strlen(thing->location) != 0) { + thing->type = DEV; + /* * Just a reminder to set the ownership of your serial * devices to _thingsd. Otherwise, a thing will not be * able to successfully open(2) the file descriptor. */ - fd = open(thg->location, O_RDWR | O_NONBLOCK | O_NOCTTY - | O_NDELAY); + fd = open(thing->location, O_RDWR | O_NONBLOCK | + O_NOCTTY | O_NDELAY); + if (fd == -1) { - log_warnx("failed to open %s", thg->location); + log_warnx("failed to open %s", thing->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); + + dead_thing = new_dead_thing(thing); + + env->exists = true; + env->dcount++; + thing->fd = -1; + thing->exists = false; + + TAILQ_INSERT_TAIL(env->dead_things-> + dead_things_list, dead_thing, entry); + return; } else { /* load current s_opts */ tcgetattr(fd, &s_opts); + /* set baud */ - switch (thg->baud) { + switch (thing->baud) { case 50: baudrate = B50; break; @@ -123,14 +133,17 @@ open_thgs(struct thgsd *pthgsd, bool reconn) 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) { + if (thing->data_bits != -1) { s_opts.c_cflag &= ~CSIZE; - switch(thg->data_bits) { + switch(thing->data_bits) { case 5: stop = CS5; break; @@ -146,71 +159,89 @@ open_thgs(struct thgsd *pthgsd, bool reconn) } s_opts.c_cflag |= stop; } + /* set parity */ - if (thg->parity != NULL) { + if (strlen(thing->parity) != 0) { s_opts.c_cflag &= ~PARENB; + /* enable parity checking */ - if (strcmp(thg->parity, "odd") == 0) { + if (strcmp(thing->parity, "odd") == 0) { s_opts.c_cflag |= PARENB; s_opts.c_cflag |= PARODD; s_opts.c_iflag |= (INPCK | ISTRIP); - } else if (strcmp(thg->parity, + } else if (strcmp(thing->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) + if (thing->stop_bits != -1) { + if (thing->stop_bits == 2) s_opts.c_cflag |= CSTOPB; else s_opts.c_cflag &= ~CSTOPB; } + /* set hardware control */ - if (thg->hw_ctl == false) { + if (thing->hw_ctl == false) { s_opts.c_cflag &= ~CRTSCTS; } else { s_opts.c_cflag |= CRTSCTS; } + /* set software control */ - if (thg->sw_ctl == false) { + if (thing->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') { + + if ((thing->fd = fd) == '\0') { log_warnx("serial device not opened"); if (reconn) return; - thg->exists = false; - add_reconn(thg); + thing->exists = false; + add_reconn(thing); return; } - thg->bev = bufferevent_new(thg->fd, sockrd, - sockwr, sock_err, pthgsd); - if (thg->bev == NULL) + + thing->bev = bufferevent_new(thing->fd, + socketrd, socketwr, socket_err, env); + + if (thing->bev == NULL) fatalx("ipaddr bev error"); - thg->evb = evbuffer_new(); - if (thg->evb == NULL) + + thing->evb = evbuffer_new(); + + if (thing->evb == NULL) fatalx("ipaddr evb error"); - bufferevent_enable(thg->bev, EV_READ|EV_WRITE); + + bufferevent_enable(thing->bev, EV_READ | + EV_WRITE); } + if (reconn) { - thg->exists = true; - log_info("reconnected: %s", thg->name); + thing->exists = true; + log_info("reconnected: %s", thing->name); } + } } } blob - /dev/null blob + 07d7c1ce586a14ed9fcca6d2471daea1d64f9f4f (mode 644) --- /dev/null +++ thingsd/proc.h @@ -0,0 +1,203 @@ +/* + * Copyright (c) 2010-2015 Reyk Floeter + * + * 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. + */ + +enum { + IMSG_NONE, + IMSG_CTL_OK, + IMSG_CTL_FAIL, + IMSG_CTL_VERBOSE, + IMSG_CTL_NOTIFY, + IMSG_CTL_RESET, + IMSG_CTL_PROCFD, + IMSG_PROC_MAX +}; + +/* imsg */ +struct imsgev { + struct imsgbuf ibuf; + void (*handler)(int, short, void *); + struct event ev; + struct privsep_proc *proc; + void *data; + short events; +}; + +#define IMSG_SIZE_CHECK(imsg, p) do { \ + if (IMSG_DATA_SIZE(imsg) < sizeof(*p)) \ + fatalx("bad length imsg received (%s)", #p); \ +} while (0) +#define IMSG_DATA_SIZE(imsg) ((imsg)->hdr.len - IMSG_HEADER_SIZE) + +/* control socket */ +struct control_sock { + const char *cs_name; + struct event cs_ev; + struct event cs_evt; + int cs_fd; + int cs_restricted; + void *cs_env; + + TAILQ_ENTRY(control_sock) cs_entry; +}; +TAILQ_HEAD(control_socks, control_sock); + +struct { + struct event ev; + int fd; +} control_state; + +struct ctl_conn { + TAILQ_ENTRY(ctl_conn) entry; + uint8_t flags; + unsigned int waiting; +#define CTL_CONN_NOTIFY 0x01 + struct imsgev iev; + struct sockpeercred peercred; + +}; +TAILQ_HEAD(ctl_connlist, ctl_conn); +extern struct ctl_connlist ctl_conns; + +/* privsep */ +enum privsep_procid { + PROC_PARENT = 0, + PROC_CONTROL, + PROC_THINGS, + PROC_MAX, +} privsep_process; + +#define CONFIG_RELOAD 0x00 +#define CONFIG_THINGS 0x01 +#define CONFIG_ALL 0xff + +struct privsep_pipes { + int *pp_pipes[PROC_MAX]; +}; + +struct privsep { + struct privsep_pipes *ps_pipes[PROC_MAX]; + struct privsep_pipes *ps_pp; + + struct imsgev *ps_ievs[PROC_MAX]; + const char *ps_title[PROC_MAX]; + uint8_t ps_what[PROC_MAX]; + + struct passwd *ps_pw; + int ps_noaction; + + struct control_sock ps_csock; + struct control_socks ps_rcsocks; + + unsigned int ps_instances[PROC_MAX]; + unsigned int ps_instance; + + /* Event and signal handlers */ + struct event ps_evsigint; + struct event ps_evsigterm; + struct event ps_evsigchld; + struct event ps_evsighup; + struct event ps_evsigpipe; + struct event ps_evsigusr1; + + void *ps_env; +}; + +struct privsep_proc { + const char *p_title; + enum privsep_procid p_id; + int (*p_cb)(int, struct privsep_proc *, + struct imsg *); + void (*p_init)(struct privsep *, + struct privsep_proc *); + void (*p_shutdown)(void); + const char *p_chroot; + struct passwd *p_pw; + struct privsep *p_ps; +}; + +struct privsep_fd { + enum privsep_procid pf_procid; + unsigned int pf_instance; +}; + +#if DEBUG +#define DPRINTF log_debug +#else +#define DPRINTF(x...) do {} while(0) +#endif + +#define PROC_PARENT_SOCK_FILENO 3 +#define PROC_MAX_INSTANCES 32 + +/* proc.c */ +void proc_init(struct privsep *, struct privsep_proc *, unsigned int, + int, char **, enum privsep_procid); +void proc_kill(struct privsep *); +void proc_connect(struct privsep *ps); +void proc_dispatch(int, short event, void *); +void proc_run(struct privsep *, struct privsep_proc *, + struct privsep_proc *, unsigned int, + void (*)(struct privsep *, struct privsep_proc *, void *), void *); +void imsg_event_add(struct imsgev *); +int imsg_compose_event(struct imsgev *, uint16_t, uint32_t, + pid_t, int, void *, uint16_t); +int imsg_composev_event(struct imsgev *, uint16_t, uint32_t, + pid_t, int, const struct iovec *, int); +int proc_compose_imsg(struct privsep *, enum privsep_procid, int, + uint16_t, uint32_t, int, void *, uint16_t); +int proc_compose(struct privsep *, enum privsep_procid, + uint16_t, void *data, uint16_t); +int proc_composev_imsg(struct privsep *, enum privsep_procid, int, + uint16_t, uint32_t, int, const struct iovec *, int); +int proc_composev(struct privsep *, enum privsep_procid, + uint16_t, const struct iovec *, int); +int proc_forward_imsg(struct privsep *, struct imsg *, + enum privsep_procid, int); +struct imsgbuf * + proc_ibuf(struct privsep *, enum privsep_procid, int); +struct imsgev * + proc_iev(struct privsep *, enum privsep_procid, int); +enum privsep_procid + proc_getid(struct privsep_proc *, unsigned int, const char *); +int proc_flush_imsg(struct privsep *, enum privsep_procid, int); + +/* control.c */ +void control(struct privsep *, struct privsep_proc *); +int control_init(struct privsep *, struct control_sock *); +int control_listen(struct control_sock *); +void control_cleanup(struct control_sock *); + +/* 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))); blob - 97618eb47412c18f85263cf25273ea6ef5735878 blob + 441381b4142211cab1b9091709c21b74e937ff07 --- thingsd/sockets.c +++ thingsd/sockets.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2019-2020 Tracey Emery + * Copyright (c) 2016, 2019, 2020 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 @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -29,152 +30,187 @@ #include #include +#include "proc.h" #include "thingsd.h" -extern struct dthgs *pdthgs; extern struct ctl_pkt *ctl_pkt; extern bool ctl_conn; void -create_socks(struct thgsd *pthgsd, bool reconn) +create_sockets(struct thingsd *env, bool reconn) { - struct thg *thg; - struct sock *sock = NULL, *tsock, *conn_sock = NULL; + struct thing *thing; + struct socket *sock = NULL, *tsock, *conn_socket = NULL; char *iface = NULL; int csock = 0, conn_csock = 0; bool fail = false; - evbuffercb sockrd = sock_rd; - evbuffercb sockwr = sock_wr; + evbuffercb socketrd = socket_rd; + evbuffercb socketwr = socket_wr; + size_t n; - TAILQ_FOREACH(thg, &pthgsd->thgs, entry) { + TAILQ_FOREACH(thing, env->things, entry) { if (reconn) { - if (thg->exists) + if (thing->exists) continue; - if (thg->type == TCP) + if (thing->type == TCP) goto recreate; else continue; } - sock = new_sock(thg->port); - if (thg->tls) - sock_tls_init(sock, thg); + + sock = new_socket(thing->port); + + if (thing->tls) + socket_tls_init(sock, thing); else sock->tls = false; - 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, + + sock->max_clients += thing->max_clients; + + n = strlcpy(sock->name, thing->name, sizeof(sock->name)); + if (n >= sizeof(sock->name)) + fatalx("%s: sock->name too long", __func__); + + if (strlen(thing->iface) != 0) + iface = get_ifaddrs(thing->iface); + + if (thing->type == DEV) { + if((csock = sock->fd = create_socket(thing->port, iface, TCP)) == -1) log_warnx("fd create socket failed"); - else if (thg->fd != -1) - thg->exists = true; + else if (thing->fd != -1) + thing->exists = true; else { - thg->exists = false; + thing->exists = false; } } - if (thg->udp != NULL) { + + if (strlen(thing->udp) != 0) { /* 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) + thing->type = UDP; + conn_socket = new_socket(thing->rcv_port); + + if ((csock = sock->fd = create_socket(thing->port, + iface, TCP)) == -1) log_warnx("udp create socket failed"); else - thg->exists = true; - if ((conn_csock = conn_sock->fd = - create_sock(thg->conn_port, iface, - thg->type)) == -1) + thing->exists = true; + + if ((conn_csock = conn_socket->fd = + create_socket(thing->rcv_port, iface, + thing->type)) == -1) log_warnx("udp create socket failed"); else - thg->exists = true; - thg->fd = conn_sock->fd; + thing->exists = true; + + thing->fd = conn_socket->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) { + if (strlen(thing->ipaddr) != 0) { + thing->type = TCP; + + if (thing->persist == 1) { + if ((thing->fd = + open_client_socket(thing->ipaddr, + thing->conn_port)) == -1) { log_warnx("ipaddr connection failed"); if (reconn) continue; - thg->exists = false; - add_reconn(thg); + thing->exists = false; + add_reconn(thing); } else - thg->exists = true; - if (thg->fd != -1) { - thg->bev = bufferevent_new(thg->fd, - sockrd, sockwr, sock_err, pthgsd); - if (thg->bev == NULL) + thing->exists = true; + + if (thing->fd != -1) { + thing->bev = bufferevent_new(thing->fd, + socketrd, socketwr, socket_err, + env); + + if (thing->bev == NULL) fatalx("ipaddr bev error"); - thg->evb = evbuffer_new(); - if (thg->evb == NULL) + + thing->evb = evbuffer_new(); + + if (thing->evb == NULL) fatalx("ipaddr evb error"); - bufferevent_enable(thg->bev, - EV_READ|EV_WRITE); + + bufferevent_enable(thing->bev, + EV_READ | EV_WRITE); } } else - thg->fd = -1; + thing->fd = -1; + if (reconn == false) { - if ((csock = sock->fd = create_sock(thg->port, - iface, TCP)) == -1) { + if ((csock = sock->fd = + create_socket(thing->port, iface, + TCP)) == -1) { log_warnx("tcp create socket failed"); - thg->exists = false; - add_reconn(thg); + thing->exists = false; + add_reconn(thing); } else { - if (thg->fd != -1) - thg->exists = true; + if (thing->fd != -1) + thing->exists = true; } } + } - if (reconn && thg->exists) { - log_info("reconnected: %s", thg->name); + if (reconn && thing->exists) { + log_info("reconnected: %s", thing->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) { + + TAILQ_FOREACH(tsock, env->sockets, entry) { + if (thing->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); + TAILQ_INSERT_TAIL(env->sockets, sock, entry); + + if (thing->type == UDP) + TAILQ_INSERT_TAIL(env->sockets, conn_socket, entry); + if (sock->fd > 0) { - event_set(sock->ev, sock->fd, EV_READ|EV_PERSIST, - clt_conn, pthgsd); + event_set(sock->ev, sock->fd, EV_READ | EV_PERSIST, + client_conn, env); 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"); + + if (conn_socket != NULL && conn_socket->fd > 0) { + event_set(conn_socket->ev, conn_socket->fd, + EV_READ | EV_PERSIST, udp_event, env); + + if (event_add(conn_socket->ev, NULL)) + fatalx("event add conn_socket"); } + } } int -create_sock(int iport, char *iface, int type) +create_socket(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; + int socket_fd, gai, o_val = 1, flags; snprintf(port, sizeof(port), "%d", iport); memset(&addr_hints, 0, sizeof(addr_hints)); @@ -182,7 +218,7 @@ create_sock(int iport, char *iface, int type) switch (type) { case UDP: addr_hints.ai_socktype = SOCK_DGRAM; - addr_hints.ai_flags = AI_PASSIVE|AI_ADDRCONFIG; + addr_hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG; addr_hints.ai_protocol = 0; break; case TCP: @@ -192,203 +228,302 @@ create_sock(int iport, char *iface, int type) break; } if ((gai = getaddrinfo(iface, port, &addr_hints, &addr_res)) != 0) - fatalx("getaddrinfo failed: %s", gai_strerror(gai)); + fatalx("getaddrinfo failed on %s: %s:%s", gai_strerror(gai), + iface, port); for (loop_res = addr_res; loop_res != NULL; loop_res = loop_res->ai_next) { - if ((sock_fd = socket(loop_res->ai_family, + if ((socket_fd = socket(loop_res->ai_family, loop_res->ai_socktype, loop_res->ai_protocol)) == -1) fatalx("unable to create socket"); - if (setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &o_val, + + if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &o_val, sizeof(int)) == -1) { freeaddrinfo(addr_res); fatalx("setsockopt error"); + } /* non-blocking */ - flags = fcntl(sock_fd, F_GETFL); + flags = fcntl(socket_fd, F_GETFL); flags |= O_NONBLOCK; - fcntl(sock_fd, F_SETFL, flags); - if (bind(sock_fd, loop_res->ai_addr, + + fcntl(socket_fd, F_SETFL, flags); + + if (bind(socket_fd, loop_res->ai_addr, loop_res->ai_addrlen) == -1) { - close(sock_fd); + close(socket_fd); log_warnx("%s%s", "bind address busy\n", " -checking existing sockets"); return -2; } + break; } + if (loop_res == NULL) { freeaddrinfo(addr_res); fatalx("can't bind to port"); } + freeaddrinfo(addr_res); + if (type == TCP) { - if (listen(sock_fd, SOMAXCONN) == -1) { + if (listen(socket_fd, SOMAXCONN) == -1) { fatal("unable to listen on socket"); return -1; } } - return sock_fd; + + return socket_fd; } int -open_clt_sock(char *ip_addr, int cport) +open_client_socket(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 failed: %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 = 0, *ifa; + struct ifaddrs *ifaps, *ifap; struct sockaddr *sa = NULL; char *addr = NULL; char hbuf[NI_MAXHOST]; - int count = 0; - if (getifaddrs(&ifap) == -1) + if (getifaddrs(&ifaps) == -1) fatalx("getifaddrs error"); - for (count = 0, ifa = ifap; ifa; ifa = ifa->ifa_next) { + + ifap = ifaps; + + 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, hbuf, sizeof(hbuf), NULL, 0, NI_NAMEREQD | NI_NUMERICHOST)) log_warnx("getnameinfo error"); + + free(addr); + + addr = NULL; addr = strdup(hbuf); + if (addr == NULL) - goto err; + fatalx("out of memory"); + if (strcmp(name, ifap->ifa_name) == 0) { - freeifaddrs(ifap); + freeifaddrs(ifaps); return addr; } + } + + ifap = ifap->ifa_next; + } -err: - freeifaddrs(ifap); + + freeifaddrs(ifaps); return NULL; } -struct sock * -new_sock(int port) +struct socket * +new_socket(int port) { - struct sock *sock; + struct socket *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 socket * +get_socket(struct thingsd *env, int val) { - struct sock *sock = NULL; + struct socket *sock = NULL; - TAILQ_FOREACH(sock, &pthgsd->socks, entry) { + TAILQ_FOREACH(sock, env->sockets, entry) { if (sock->fd == val || sock->port == val) return sock; } + return NULL; } void -sock_rd(struct bufferevent *bev, void *arg) +socket_rd(struct bufferevent *bev, void *arg) { - struct thgsd *pthgsd = (struct thgsd *)arg; - struct thg *thg = NULL, *tthg; - struct clt *clt; + struct thingsd *env = (struct thingsd *)arg; + struct thing *thing = NULL, *tthing; + struct client *client; size_t len; int fd = bev->ev_read.ev_fd; size_t n; - char *pkt; + char *pkt = NULL; - TAILQ_FOREACH(tthg, &pthgsd->thgs, entry) { - if (tthg->fd == fd) { - thg = tthg; - thg->evb = EVBUFFER_INPUT(bev); - len = EVBUFFER_LENGTH(thg->evb); + TAILQ_FOREACH(tthing, env->things, entry) { + if (tthing->fd == fd) { + thing = tthing; + thing->evb = EVBUFFER_INPUT(bev); + + len = EVBUFFER_LENGTH(thing->evb); + if ((pkt = calloc(len, sizeof(*pkt))) == NULL) return; - evbuffer_remove(thg->evb, pkt, len); - 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); + evbuffer_remove(thing->evb, pkt, len); + + TAILQ_FOREACH(client, env->clients, entry) { + for (n = 0; n < client->le; n++) { + if (strcmp(client->sub_names[n], + thing->name) == 0) + bufferevent_write(client->bev, + pkt, len); } } - send_ctl_pkt(thg->name, pkt, len); + + if (env->packet_client_count > 0) + send_to_packet_client(env, thing->name, pkt, + len); + free(pkt); + pkt = NULL; + } } + free(pkt); } void -sock_wr(struct bufferevent *bev, void *arg) +socket_wr(struct bufferevent *bev, void *arg) { } void -sock_err(struct bufferevent *bev, short error, void *arg) +socket_err(struct bufferevent *bev, short error, void *arg) { - struct thgsd *pthgsd = (struct thgsd *)arg; - struct thg *thg = NULL; + struct thingsd *env = (struct thingsd *)arg; + struct thing *thing = 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); + TAILQ_FOREACH(thing, env->things, entry) { + if (thing->fd == fd && thing->persist) { + bufferevent_free(thing->bev); + close(thing->fd); + thing->fd = -1; + thing->exists = false; + add_reconn(thing); log_warnx("thing error: %s disconnected", - thg->name); + thing->name); } } } } + +void +sockets_show_info(struct privsep *ps, struct imsg *imsg) +{ + char filter[THINGSD_MAXNAME]; + struct socket *socket, nsi; + size_t n; + + switch (imsg->hdr.type) { + case IMSG_GET_INFO_SOCKETS_REQUEST: + + memcpy(filter, imsg->data, sizeof(filter)); + + TAILQ_FOREACH(socket, thingsd_env->sockets, entry) { + if (filter[0] == '\0' || memcmp(filter, + socket->name, sizeof(filter)) == 0) { + + n = strlcpy(nsi.name, socket->name, + sizeof(nsi.name)); + if (n >= sizeof(nsi.name)) + fatalx("%s: nsi.name too long", + __func__); + + nsi.fd = socket->fd; + nsi.port = socket->port; + nsi.tls = socket->tls; + nsi.client_cnt = socket->client_cnt; + nsi.max_clients = socket->max_clients; + + if (proc_compose_imsg(ps, PROC_CONTROL, -1, + IMSG_GET_INFO_SOCKETS_DATA, + imsg->hdr.peerid, -1, &nsi, + sizeof(nsi)) == -1) + return; + + } + } + + if (proc_compose_imsg(ps, PROC_CONTROL, -1, + IMSG_GET_INFO_SOCKETS_END_DATA, imsg->hdr.peerid, + -1, &nsi, sizeof(nsi)) == -1) + return; + + break; + default: + log_debug("%s: error handling imsg", __func__); + break; + } +} blob - 7be727dae78c67ef2994810ec5ef9ae83d80ebab blob + a5ac19820cc9a642b5ee12c59f37f7448cd135a6 --- thingsd/things.c +++ thingsd/things.c @@ -1,5 +1,6 @@ /* - * Copyright (c) 2016, 2019 Tracey Emery + * Copyright (c) 2016, 2019, 2020 Tracey Emery + * Copyright (c) 2015 Mike Larkin * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above @@ -14,491 +15,541 @@ * 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 +#include +#include +#include +#include +#include #include #include -#include +#include #include +#include +#include "proc.h" #include "thingsd.h" -#include "things.h" -struct thgsd *pthgsd; -struct dthgs *pdthgs; -struct imsgev *iev_main; -struct ctl_pkt *ctl_pkt; +int things_dispatch_parent(int, struct privsep_proc *, struct imsg *); +void things_run(struct privsep *, struct privsep_proc *, void *); +struct thing compose_thing(struct thing *, enum imsg_type); + +static struct privsep_proc procs[] = { + { "parent", PROC_PARENT, things_dispatch_parent }, +}; + void -thgs_sighdlr(int sig, short event, void *bula) +things(struct privsep *ps, struct privsep_proc *p) { - struct dthgs *zdthgs = (struct dthgs *)bula; + proc_run(ps, p, procs, nitems(procs), things_run, NULL); +} +void +things_run(struct privsep *ps, struct privsep_proc *p, void *arg) +{ + if (config_init(ps->ps_env) == -1) + fatal("failed to initialize configuration"); + + signal_del(&ps->ps_evsigchld); + signal_set(&ps->ps_evsigchld, SIGCHLD, things_sighdlr, ps); + signal_add(&ps->ps_evsigchld, NULL); + + if (pledge("stdio recvfd", NULL) == -1) + fatal("pledge"); +} + +int +things_dispatch_parent(int fd, struct privsep_proc *p, struct imsg *imsg) +{ + struct privsep *ps = p->p_ps; + struct thing *thing, nti; + int res = 0, cmd = 0, verbose; + unsigned int mode; + size_t n; + + switch (imsg->hdr.type) { + case IMSG_ADD_THING: + IMSG_SIZE_CHECK(imsg, &nti); + + memcpy(&nti, imsg->data, sizeof(nti)); + + thing = calloc(1, sizeof(*thing)); + + thing->exists = nti.exists; + thing->hw_ctl = nti.hw_ctl; + thing->persist = nti.persist; + + n = strlcpy(thing->iface, nti.iface, sizeof(thing->iface)); + if (n >= sizeof(thing->iface)) + fatalx("%s: thing->iface too long", __func__); + + n = strlcpy(thing->ipaddr, nti.ipaddr, sizeof(thing->ipaddr)); + if (n >= sizeof(thing->ipaddr)) + fatalx("%s: thing->ipaddr too long", __func__); + + n = strlcpy(thing->parity, nti.parity, sizeof(thing->parity)); + if (n >= sizeof(thing->parity)) + fatalx("%s: thing->parity name too long", __func__); + + n = strlcpy(thing->name, nti.name, sizeof(thing->name)); + if (n >= sizeof(thing->name)) + fatalx("%s: thing->name too long", __func__); + + n = strlcpy(thing->password, nti.password, + sizeof(thing->password)); + if (n >= sizeof(thing->password)) + fatalx("%s: thing->password too long", __func__); + + n = strlcpy(thing->location, nti.location, + sizeof(thing->location)); + if (n >= sizeof(thing->location)) + fatalx("%s: thing->location too long", __func__); + + n = strlcpy(thing->udp, nti.udp, sizeof(thing->udp)); + if (n >= sizeof(thing->udp)) + fatalx("%s: thing->name too long", __func__); + + thing->fd = nti.fd; + thing->baud = nti.baud; + thing->conn_port = nti.conn_port; + thing->rcv_port = nti.rcv_port; + thing->data_bits = nti.data_bits; + thing->max_clients = nti.max_clients; + thing->port = nti.port; + thing->stop_bits = nti.stop_bits; + thing->type = nti.type; + thing->client_cnt = nti.client_cnt; + + thing->tls = nti.tls; + n = strlcpy(thing->tls_cert_file, nti.tls_cert_file, + sizeof(thing->tls_cert_file)); + if (n >= sizeof(thing->tls_cert_file)) + fatalx("%s: thing->tls_cert_file too long", __func__); + + n = strlcpy(thing->tls_key_file, nti.tls_key_file, + sizeof(thing->tls_key_file)); + if (n >= sizeof(thing->tls_key_file)) + fatalx("%s: thing->tls_key_file too long", __func__); + + n = strlcpy(thing->tls_ca_file, nti.tls_ca_file, + sizeof(thing->tls_ca_file)); + if (n >= sizeof(thing->tls_ca_file)) + fatalx("%s: thing->tls_ca_file too long", __func__); + + n = strlcpy(thing->tls_crl_file, nti.tls_crl_file, + sizeof(thing->tls_crl_file)); + if (n >= sizeof(thing->tls_crl_file)) + fatalx("%s: thing->tls_crl_file too long", __func__); + + n = strlcpy(thing->tls_ocsp_staple_file, + nti.tls_ocsp_staple_file, + sizeof(thing->tls_ocsp_staple_file)); + if (n >= sizeof(thing->tls_ocsp_staple_file)) + fatalx("%s: thing->tls_ocsp_staple_file too long", + __func__); + + TAILQ_INSERT_TAIL(thingsd_env->things, thing, entry); + + break; + case IMSG_CTL_RESET: + IMSG_SIZE_CHECK(imsg, &mode); + memcpy(&mode, imsg->data, sizeof(mode)); + + config_getreset(thingsd_env, imsg); + break; + case IMSG_CTL_VERBOSE: + IMSG_SIZE_CHECK(imsg, &verbose); + memcpy(&verbose, imsg->data, sizeof(verbose)); + log_setverbose(verbose); + break; + default: + return (-1); + } + + switch (cmd) { + case 0: + break; + case IMSG_GET_INFO_THINGS_END_DATA: + if (proc_compose_imsg(ps, PROC_PARENT, -1, cmd, + imsg->hdr.peerid, -1, &mode, sizeof(mode)) == -1) + return (-1); + break; + default: + if (proc_compose_imsg(ps, PROC_PARENT, -1, cmd, + imsg->hdr.peerid, -1, &res, sizeof(res)) == -1) + return (-1); + break; + } + + return (0); +} + +void +things_sighdlr(int sig, short event, void *arg) +{ switch (sig) { - case SIGINT: - case SIGTERM: - case SIGQUIT: - thgs_shutdown(zdthgs); default: fatalx("unexpected signal"); } } void -thgs_main(int debug, int verbose, char *thgs_sock) +things_reset(void) { - struct timeval eb_timeout; + struct thing *thing, *tthing; + struct socket *sock, *tsock; + struct client *client, *tclient; - log_init(debug, LOG_DAEMON); - log_setverbose(verbose); - - if ((pthgsd = calloc(1, sizeof(*pthgsd))) == NULL) - fatalx("no thgsd calloc"); - if ((pdthgs = calloc(1, sizeof(*pdthgs))) == NULL) - fatalx("no dthgs calloc"); - if ((ctl_pkt = calloc(1, sizeof(*ctl_pkt))) == NULL) - fatalx("no ctl_pkt calloc"); - if (parse_conf(PATH_CONF)) - fatalx("config parsing failed"); - - thgsd_process = PROC_THGS; - setproctitle("%s", log_procnames[thgsd_process]); - log_procinit(log_procnames[thgsd_process]); - - if ((pthgsd->pw = getpwnam(TH_USER)) != NULL) { - if(setuid(pthgsd->pw->pw_uid) != 0) - log_warn("unable to set user id of %s: %s", TH_USER, - strerror(errno)); + /* clean up clients */ + TAILQ_FOREACH_SAFE(client, thingsd_env->clients, entry, tclient) { + close(client->fd); + TAILQ_REMOVE(thingsd_env->clients, client, entry); } - ctl_pkt->exists = false; - ctl_pkt->pid = getppid(); - ctl_pkt->cpid = -1; - - pthgsd->thgs_eb = event_init(); - - open_thgs(pthgsd, false); - create_socks(pthgsd, false); - - pdthgs->run = 1; - - if (unveil("/dev", "rw") == -1) - errx(1, "unveil"); - if (pledge("stdio rpath wpath inet proc tty dns", NULL) == -1) - errx(1, "pledge"); - - signal_set(&pthgsd->thgs_evsigquit, SIGQUIT, thgs_sighdlr, pdthgs); - signal_set(&pthgsd->thgs_evsigterm, SIGTERM, thgs_sighdlr, pdthgs); - signal_set(&pthgsd->thgs_evsigint, SIGINT, thgs_sighdlr, pdthgs); - - signal_add(&pthgsd->thgs_evsigquit, NULL); - signal_add(&pthgsd->thgs_evsigterm, NULL); - signal_add(&pthgsd->thgs_evsigint, NULL); - signal(SIGPIPE, SIG_IGN); - signal(SIGHUP, SIG_IGN); - - /* Setup pipe and event handler to the parent process. */ - if ((iev_main = malloc(sizeof(struct imsgev))) == NULL) - fatal(NULL); - imsg_init(&iev_main->ibuf, PARENT_SOCK_FD); - iev_main->handler = thgs_dispatch_main; - iev_main->events = EV_READ; - event_set(&iev_main->ev, iev_main->ibuf.fd, iev_main->events, - iev_main->handler, iev_main); - event_add(&iev_main->ev, NULL); - - /* begin thing watchdog */ - eb_timeout.tv_sec = EB_TIMEOUT; - eb_timeout.tv_usec = 0; - - start_clt_chk(pthgsd); - while (pdthgs->run) { - if (pthgsd->exists) { - do_reconn(); + /* clean up sockets */ + TAILQ_FOREACH_SAFE(sock, thingsd_env->sockets, entry, tsock) { + if (sock->tls) { + tls_config_free(sock->tls_config); + tls_free(sock->tls_ctx); } - if (getppid() == 1) - break; - event_base_loopexit(pthgsd->thgs_eb, &eb_timeout); - event_base_dispatch(pthgsd->thgs_eb); + close(sock->fd); + TAILQ_REMOVE(thingsd_env->sockets, sock, entry); } - thgs_shutdown(pdthgs); -} -void -thgs_dispatch_main(int fd, short event, void *bula) -{ - struct clt *clt; - struct thg *thg; - struct imsg imsg; - struct imsgev *iev = bula; - struct imsgbuf *ibuf = &iev->ibuf; - enum thgs_list_type type; - int n, shut = 0, verbose; - bool tchk = true; - - if (event & EV_READ) { - if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN) - fatal("imsg_read error"); - if (n == 0) /* Connection closed. */ - shut = 1; + /* clean up things */ + TAILQ_FOREACH_SAFE(thing, thingsd_env->things, entry, tthing) { + close(thing->fd); + TAILQ_REMOVE(thingsd_env->things, thing, entry); } - if (event & EV_WRITE) { - if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN) - fatal("msgbuf_write"); - if (n == 0) /* Connection closed. */ - shut = 1; - } - for (;;) { - if ((n = imsg_get(ibuf, &imsg)) == -1) - fatal("imsg_get error"); - if (n == 0) /* No more messages. */ - break; - - switch (imsg.hdr.type) { - case IMSG_SHOW_PKTS: - TAILQ_FOREACH(thg, &pthgsd->thgs, entry) { - if (strncmp(thg->name, imsg.data, - IMSG_DATA_SIZE(imsg)) == 0) { - if ((ctl_pkt->name = - strndup(thg->name, - strlen(thg->name))) == NULL) - continue; - tchk = false; - ctl_pkt->cpid = imsg.hdr.pid; - ctl_pkt->exists = true; - log_debug("ctl request packets: %s", - thg->name); - break; - } - } - if (tchk) - thgs_imsg_compose_main(IMSG_CTL_END, - ctl_pkt->pid, NULL, 0); - break; - case IMSG_KILL_CLT: - TAILQ_FOREACH(clt, &pthgsd->clts, entry) { - if (imsg.data == NULL) - break; - if (strncmp(clt->name, imsg.data, BUFF) == 0) { - log_debug("Control killed client: %s", - (char *)imsg.data); - clt_del(pthgsd, clt); - break; - } - } - break; - case IMSG_THGS_LIST: - if (IMSG_DATA_SIZE(imsg) != sizeof(type)) - fatalx("%s: IMSG_THGS_STATUS wrong length: %lu", - __func__, IMSG_DATA_SIZE(imsg)); - memcpy(&type, imsg.data, sizeof(type)); - show_list(type, imsg.hdr.pid); - break; - case IMSG_THGS_LOG_VERBOSE: - memcpy(&verbose, imsg.data, sizeof(verbose)); - log_setverbose(verbose); - break; - case IMSG_CTL_END: - if (ctl_pkt->exists) { - ctl_pkt->exists = false; - ctl_pkt->cpid = -1; - free(ctl_pkt->name); - } - break; - default: - log_debug("%s: error handling imsg %d", __func__, - imsg.hdr.type); - break; - } - imsg_free(&imsg); - } - if (!shut) - imsg_event_add(iev); - else { - /* This pipe is dead. Remove its event handler. */ - event_del(&iev->ev); - event_loopexit(NULL); - pdthgs->run = 0; - } } void -thgs_shutdown(struct dthgs *zdthgs) +things_shutdown(void) { - struct thg *thg, *tthg; - struct sock *sock, *tsock; - struct clt *clt, *tclt; - struct dthg *dthg, *tdthg; + struct thing *thing, *tthing; + struct socket *sock, *tsock; + struct client *client, *tclient; + struct dead_thing *dead_thing, *dead_tthing; - zdthgs->run = 0; - - /* Close pipes. */ - msgbuf_write(&iev_main->ibuf.w); - msgbuf_clear(&iev_main->ibuf.w); - close(iev_main->ibuf.fd); - free(iev_main); - /* clean up things */ - TAILQ_FOREACH_SAFE(thg, &pthgsd->thgs, entry, tthg) { - close(thg->fd); - TAILQ_REMOVE(&pthgsd->thgs, thg, entry); - free(thg); + TAILQ_FOREACH_SAFE(thing, thingsd_env->things, entry, tthing) { + close(thing->fd); + TAILQ_REMOVE(thingsd_env->things, thing, entry); + free(thing); } - /* clean up dead things */ - TAILQ_FOREACH_SAFE(dthg, &pdthgs->zthgs, entry, tdthg) { - TAILQ_REMOVE(&pdthgs->zthgs, dthg, entry); - free(dthg); + + /* clean up dead things */ + TAILQ_FOREACH_SAFE(dead_thing, + thingsd_env->dead_things->dead_things_list, entry, dead_tthing) { + TAILQ_REMOVE(thingsd_env->dead_things->dead_things_list, + dead_thing, entry); + free(dead_thing); } + /* clean up sockets */ - TAILQ_FOREACH_SAFE(sock, &pthgsd->socks, entry, tsock) { + TAILQ_FOREACH_SAFE(sock, thingsd_env->sockets, entry, tsock) { if (sock->tls) { tls_config_free(sock->tls_config); tls_free(sock->tls_ctx); } close(sock->fd); free(sock->ev); - TAILQ_REMOVE(&pthgsd->socks, sock, entry); + TAILQ_REMOVE(thingsd_env->sockets, 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); + + /* clean up clients */ + TAILQ_FOREACH_SAFE(client, thingsd_env->clients, entry, tclient) { + close(client->fd); + free(client->sub_names); + TAILQ_REMOVE(thingsd_env->clients, client, entry); + free(client); } - log_debug("%s child exiting", getprogname()); - free(pdthgs); - free(pthgsd); - free(ctl_pkt); - exit(0); } -int -thgs_imsg_compose_main(int type, pid_t pid, void *data, uint16_t datalen) +void +things_echo_pkt(struct privsep *ps, struct imsg *imsg) { - return (imsg_compose_event(iev_main, type, 0, pid, -1, data, datalen)); + struct packet_client *packet_client; + + packet_client = calloc(1, sizeof(*packet_client)); + if (packet_client == NULL) + fatalx("no calloc packet_client"); + + thingsd_env->packet_client_count++; + + packet_client->ps = *ps; + packet_client->imsg = *imsg; + memcpy(packet_client->name, imsg->data, sizeof(packet_client->name)); + + log_debug("control packet echo request for %s", packet_client->name); + TAILQ_INSERT_TAIL(thingsd_env->packet_clients, packet_client, entry); } -struct dthg -*new_dthg(struct thg *pthg) +void +things_stop_pkt(struct privsep *ps, struct imsg *imsg) { - struct dthg *dthg; + struct packet_client *packet_client, *tpacket_client; + uint32_t fd; - if ((dthg = calloc(1, sizeof(*dthg))) == NULL) - fatalx("no calloc dthg"); - log_debug("%s: adding detached thing, %s", __func__, pthg->name); - dthg->name = pthg->name; - dthg->type = pthg->type; - dthg->dtime = time(NULL); - return dthg; + memcpy(&fd, imsg->data, sizeof(fd)); + + TAILQ_FOREACH_SAFE(packet_client, thingsd_env->packet_clients, entry, + tpacket_client) { + if (fd == packet_client->imsg.hdr.peerid) { + TAILQ_REMOVE(thingsd_env->packet_clients, + packet_client, entry); + log_debug("control packet echo request stopping for %s", + packet_client->name); + + free(packet_client); + + return; + } + } + + thingsd_env->packet_client_count--; } void -add_reconn(struct thg *pthg) +things_show_info(struct privsep *ps, struct imsg *imsg) { - struct dthg *dthg; + char filter[THINGSD_MAXNAME]; + struct thing *thing, nti; - dthg = new_dthg(pthg); - pthgsd->exists = true; - pthgsd->dcount++; - TAILQ_INSERT_TAIL(&pdthgs->zthgs, dthg, entry); + switch (imsg->hdr.type) { + case IMSG_GET_INFO_THINGS_REQUEST: + case IMSG_GET_INFO_THINGS_REQUEST_ROOT: + + memcpy(filter, imsg->data, sizeof(filter)); + + TAILQ_FOREACH(thing, thingsd_env->things, entry) { + if (filter[0] == '\0' || memcmp(filter, + thing->name, sizeof(filter)) == 0) { + nti = compose_thing(thing, imsg->hdr.type); + + if (proc_compose_imsg(ps, PROC_CONTROL, -1, + IMSG_GET_INFO_THINGS_DATA, + imsg->hdr.peerid, -1, &nti, + sizeof(nti)) == -1) + return; + + } + } + + if (proc_compose_imsg(ps, PROC_CONTROL, -1, + IMSG_GET_INFO_THINGS_END_DATA, imsg->hdr.peerid, + -1, &nti, sizeof(nti)) == -1) + return; + + break; + default: + log_debug("%s: error handling imsg", __func__); + break; + } } +struct thing +compose_thing(struct thing *thing, enum imsg_type type) +{ + struct thing nti; + char blank[9] = "********"; + size_t n; + + memset(&nti, 0, sizeof(nti)); + nti.exists = thing->exists; + nti.hw_ctl = thing->hw_ctl; + nti.persist = thing->persist; + + n = strlcpy(nti.iface, thing->iface, sizeof(nti.iface)); + if (n >= sizeof(nti.iface)) + fatalx("%s: nti.iface too long", __func__); + + n = strlcpy(nti.ipaddr, thing->ipaddr, sizeof(nti.ipaddr)); + if (n >= sizeof(nti.ipaddr)) + fatalx("%s: nti.ipaddr too long", __func__); + + n = strlcpy(nti.parity, thing->parity, sizeof(nti.parity)); + if (n >= sizeof(nti.parity)) + fatalx("%s: nti.parity too long", __func__); + + n = strlcpy(nti.name, thing->name, sizeof(nti.name)); + if (n >= sizeof(nti.name)) + fatalx("%s: nti.name too long", __func__); + + nti.password[0] = '\0'; + if (type == IMSG_GET_INFO_THINGS_REQUEST) + n = strlcpy(nti.password, blank, sizeof(nti.password)); + else + n = strlcpy(nti.password, thing->password, + sizeof(nti.password)); + if (n >= sizeof(nti.password)) + fatalx("%s: nti.password too long", __func__); + + n = strlcpy(nti.location, thing->location, sizeof(nti.location)); + if (n >= sizeof(nti.location)) + fatalx("%s: nti.location too long", __func__); + + n = strlcpy(nti.udp, thing->udp, sizeof(nti.udp)); + if (n >= sizeof(nti.udp)) + fatalx("%s: nti.udp too long", __func__); + + nti.fd = thing->fd; + nti.baud = thing->baud; + nti.conn_port = thing->conn_port; + nti.rcv_port = thing->rcv_port; + nti.data_bits = thing->data_bits; + nti.max_clients = thing->max_clients; + nti.port = thing->port; + nti.stop_bits = thing->stop_bits; + nti.type = thing->type; + nti.client_cnt = thing->client_cnt; + + nti.tls = thing->tls; + n = strlcpy(nti.tls_cert_file, thing->tls_cert_file, + sizeof(nti.tls_cert_file)); + if (n >= sizeof(nti.tls_cert_file)) + fatalx("%s: nti.tls_cert_file too long", __func__); + + n = strlcpy(nti.tls_key_file, thing->tls_key_file, + sizeof(nti.tls_key_file)); + if (n >= sizeof(nti.tls_key_file)) + fatalx("%s: nti.tls_key_file too long", __func__); + + n = strlcpy(nti.tls_ca_file, thing->tls_ca_file, + sizeof(nti.tls_ca_file)); + if (n >= sizeof(nti.tls_ca_file)) + fatalx("%s: nti.tls_ca_file too long", __func__); + + n = strlcpy(nti.tls_crl_file, thing->tls_crl_file, + sizeof(nti.tls_crl_file)); + if (n >= sizeof(nti.tls_crl_file)) + fatalx("%s: nti.tls_crl_file too long", __func__); + + n = strlcpy(nti.tls_ocsp_staple_file, thing->tls_ocsp_staple_file, + sizeof(nti.tls_ocsp_staple_file)); + if (n >= sizeof(nti.tls_ocsp_staple_file)) + fatalx("%s: nti.tls_ocsp_staple_file too long", __func__); + + return nti; +} + void +add_reconn(struct thing *thing) +{ + struct dead_thing *dead_thing; + + dead_thing = new_dead_thing(thing); + + thingsd_env->exists = true; + thingsd_env->dcount++; + + TAILQ_INSERT_TAIL(thingsd_env->dead_things->dead_things_list, + dead_thing, entry); + +} + +struct dead_thing +*new_dead_thing(struct thing *thing) +{ + struct dead_thing *dead_thing; + size_t n; + + dead_thing = calloc(1, sizeof(*dead_thing)); + if (dead_thing == NULL) + fatalx("no calloc dead_thing"); + + log_debug("%s: adding detached thing, %s", __func__, thing->name); + + n = strlcpy(dead_thing->name, thing->name, sizeof(dead_thing->name)); + if (n >= sizeof(dead_thing->name)) + fatalx("%s: dead_thing->name too long", __func__); + + dead_thing->type = thing->type; + dead_thing->dtime = time(NULL); + + return dead_thing; +} + +void do_reconn(void) { - struct dthg *dthg, *tdthg; - struct thg *thg; + struct dead_thing *dead_thing, *tdead_thing; + struct thing *thing; - 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) { + TAILQ_FOREACH_SAFE(dead_thing, + thingsd_env->dead_things->dead_things_list, entry, tdead_thing) { + if ((size_t)(time(NULL) - dead_thing->dtime) > + thingsd_env->conn_retry) { + dead_thing->dtime = time(NULL); + + log_debug("attempting to reconnect %s", + dead_thing->name); + + switch (dead_thing->type) { case DEV: - open_thgs(pthgsd, true); + open_things(thingsd_env, true); break; case TCP: - create_socks(pthgsd, true); + create_sockets(thingsd_env, 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); + + TAILQ_FOREACH_SAFE(dead_thing, + thingsd_env->dead_things->dead_things_list, entry, tdead_thing) { + TAILQ_FOREACH(thing, thingsd_env->things, entry) { + if (strcmp(thing->name, dead_thing->name) == 0 && + thing->exists) { + TAILQ_REMOVE(thingsd_env->dead_things-> + dead_things_list, + dead_thing, entry); + thingsd_env->dcount--; + + free(dead_thing); + return; } } } - if (pthgsd->dcount == 0) - pthgsd->exists = false; + + if (thingsd_env->dcount == 0) + thingsd_env->exists = false; } void -show_list(enum thgs_list_type type, pid_t pid) +send_to_packet_client(struct thingsd *env, char *name, char *pkt, int len) { - struct clt *clt; - struct thg *thg; - struct sock *sock; - struct clt_imsg *clt_imsg; - struct thg_imsg *thg_imsg; - struct sock_imsg *sock_imsg; + struct packet_client *packet_client; + int snm; - switch(type) { - case THGS_LIST_CLTS: - TAILQ_FOREACH(clt, &pthgsd->clts, entry) { - clt_imsg = compose_clts(clt); - thgs_imsg_compose_main(IMSG_LIST_CLTS, pid, clt_imsg, - sizeof(*clt_imsg)); - free(clt_imsg); - } - break; - case THGS_LIST_THGS_ROOT: - case THGS_LIST_THGS: - TAILQ_FOREACH(thg, &pthgsd->thgs, entry) { - thg_imsg = compose_thgs(thg, type); - thgs_imsg_compose_main(IMSG_LIST_THGS, pid, thg_imsg, - sizeof(*thg_imsg)); - free(thg_imsg); - } - break; - case THGS_LIST_SOCKS: - TAILQ_FOREACH(sock, &pthgsd->socks, entry) { - sock_imsg = compose_socks(sock); - thgs_imsg_compose_main(IMSG_LIST_SOCKS, pid, sock_imsg, - sizeof(*sock_imsg)); - free(sock_imsg); - } - break; - default: - fatalx("unknown resolver type %d", type); - break; - } - thgs_imsg_compose_main(IMSG_CTL_END, pid, NULL, 0); -} + TAILQ_FOREACH(packet_client, env->packet_clients, entry) { + if (strlen(packet_client->name) != 0) + if ((snm = strcmp(name, packet_client->name)) == 0) + if (proc_compose_imsg(&packet_client->ps, + PROC_CONTROL, -1, IMSG_SHOW_PACKETS_DATA, + packet_client->imsg.hdr.peerid, -1, + pkt, len) == -1) + return; -struct clt_imsg * -compose_clts(struct clt *pclt) -{ - struct clt_imsg *comp_clt; - if ((comp_clt = calloc(1, sizeof(*comp_clt))) == NULL) - fatalx("no com_clt calloc"); - - comp_clt->subscribed = pclt->subscribed; - - if (pclt->name != NULL) - strlcpy(comp_clt->name, pclt->name, BUFF); - - comp_clt->fd = pclt->fd; - comp_clt->port = pclt->port; - comp_clt->subs = pclt->subs; - comp_clt->tls = pclt->tls; - return(comp_clt); -}; - -struct thg_imsg * -compose_thgs(struct thg *pthg, int type) -{ - struct thg_imsg *comp_thg; - char *blank = "********"; - - if ((comp_thg = calloc(1, sizeof(*comp_thg))) == NULL) - fatalx("no com_thg calloc"); - - comp_thg->exists = pthg->exists; - comp_thg->hw_ctl = pthg->hw_ctl; - comp_thg->persist = pthg->persist; - comp_thg->sw_ctl = pthg->sw_ctl; - - if (pthg->iface != NULL) - strlcpy(comp_thg->iface, pthg->iface, BUFF); - if (pthg->ipaddr != NULL) - strlcpy(comp_thg->ipaddr, pthg->ipaddr, BUFF); - if (pthg->name != NULL) - strlcpy(comp_thg->name, pthg->name, BUFF); - if (pthg->parity != NULL) - strlcpy(comp_thg->parity, pthg->parity, BUFF); - if (pthg->password != NULL) { - switch (type) { - case THGS_LIST_THGS_ROOT: - strlcpy(comp_thg->password, pthg->password, BUFF); - break; - case THGS_LIST_THGS: - strlcpy(comp_thg->password, blank, BUFF); - break; - } } - if (pthg->location != NULL) - strlcpy(comp_thg->location, pthg->location, BUFF); - if (pthg->udp != NULL) - strlcpy(comp_thg->udp, pthg->udp, BUFF); - - comp_thg->fd = pthg->fd; - comp_thg->baud = pthg->baud; - comp_thg->conn_port = pthg->conn_port; - comp_thg->data_bits = pthg->data_bits; - comp_thg->max_clt = pthg->max_clt; - comp_thg->port = pthg->port; - comp_thg->stop_bits = pthg->stop_bits; - comp_thg->type = pthg->type; - comp_thg->clt_cnt = pthg->clt_cnt; - comp_thg->tls = pthg->tls; - - if (pthg->tls_cert_file != NULL) - strlcpy(comp_thg->tls_cert_file, pthg->tls_cert_file, BUFF); - if (pthg->tls_key_file != NULL) - strlcpy(comp_thg->tls_key_file, pthg->tls_key_file, BUFF); - if (pthg->tls_ca_file != NULL) - strlcpy(comp_thg->tls_ca_file, pthg->tls_ca_file, BUFF); - if (pthg->tls_crl_file != NULL) - strlcpy(comp_thg->tls_crl_file, pthg->tls_crl_file, BUFF); - if (pthg->tls_ocsp_staple_file != NULL) - strlcpy(comp_thg->tls_ocsp_staple_file, - pthg->tls_ocsp_staple_file, BUFF); - return(comp_thg); -}; - -struct sock_imsg * -compose_socks(struct sock *psock) -{ - struct sock_imsg *comp_sock; - - if ((comp_sock = calloc(1, sizeof(*comp_sock))) == NULL) - fatalx("no com_sock calloc"); - - if (psock->name != NULL) - strlcpy(comp_sock->name, psock->name, BUFF); - - comp_sock->fd = psock->fd; - comp_sock->port = psock->port; - comp_sock->clt_cnt = psock->clt_cnt; - comp_sock->max_clts = psock->max_clts; - comp_sock->tls = psock->tls; - return(comp_sock); -}; - -void -send_ctl_pkt(char *name, char *pkt, int len) -{ - int snm = -1; - - /* send pkt to control socket */ - if (ctl_pkt->exists) { - if (ctl_pkt->name != NULL) - if ((snm = strcmp(name, ctl_pkt->name)) == 0) - thgs_imsg_compose_main(IMSG_SHOW_PKTS, - ctl_pkt->pid, pkt, len); - } -} +} \ No newline at end of file blob - fea5e2b82e3c78632bffe9c78e0a4090db141221 (mode 644) blob + /dev/null --- thingsd/things.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - * 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 "thingsd.h" - -void thgs_sighdlr(int, short, void *); -void thgs_shutdown(struct dthgs *); -void thgs_dispatch_main(int, short, void *); -void do_reconn(void); -void show_list(enum thgs_list_type, pid_t); - -/* things.c */ -struct thgsd *pthgsd; -struct dthgs *pdthgs; -struct thg_imsg *compose_thgs(struct thg *, int); -struct clt_imsg *compose_clts(struct clt *); -struct sock_imsg *compose_socks(struct sock *); blob - b2317a04d56695900c0b6c3f87bf88d4ca4f959a blob + 4672c5eac1d4554526a05d9bf7dde89b891c3bf8 --- thingsd/thingsd.c +++ thingsd/thingsd.c @@ -1,5 +1,6 @@ /* - * Copyright (c) 2016, 2019 Tracey Emery + * Copyright (c) 2016, 2019, 2020 Tracey Emery + * Copyright (c) 2015 Reyk Floeter * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above @@ -14,327 +15,516 @@ * 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 +#include #include #include #include -#include -#include -#include #include #include +#include +#include +#include "proc.h" #include "thingsd.h" -#include "control.h" -__dead void usage(void); -int main(int, char *[]); -void thgsd_sighdlr(int, short, void *); -void thgsd_shutdown(void); -static pid_t start_child(int, char *, int, int, int); -static void main_dispatch_thgs(int, short, void *); +__dead void usage(void); -bool thgs_chld = false; -struct event evsigquit; -struct event evsigterm; -struct event evsigint; -struct event evsighup; +int main(int, char **); +int thingsd_configure(struct privsep *); +void thingsd_sighdlr(int sig, short event, void *arg); +void thingsd_shutdown(void); +int thingsd_control_run(void); +int thingsd_dispatch_control(int, struct privsep_proc *, struct imsg *); +int thingsd_dispatch_things(int, struct privsep_proc *, struct imsg *); +void thingsd_configure_things(struct privsep *); -pid_t thgs_pid; -static struct imsgev *iev_thgs; +void thingsd_show_info(struct privsep *, struct imsg *); -uint32_t v_opts; +struct thingsd *thingsd_env; -__dead void -usage(void) +static struct privsep_proc procs[] = { + { "control", PROC_CONTROL, thingsd_dispatch_control, control }, + { "things", PROC_THINGS, thingsd_dispatch_things, things, + things_shutdown }, +}; + +/* For the privileged process */ +static struct privsep_proc *proc_priv = &procs[0]; +static struct passwd proc_privpw; + +int +thingsd_dispatch_control(int fd, struct privsep_proc *p, struct imsg *imsg) { - fprintf(stderr, "usage: %s [-dv]\n", getprogname()); - exit(1); + struct privsep *ps = p->p_ps; + int res = 0, cmd = 0, verbose; + unsigned int v = 0; + char client_name[THINGSD_MAXNAME]; + struct client *client; + + switch (imsg->hdr.type) { + case IMSG_SHOW_PACKETS_END_DATA: + IMSG_SIZE_CHECK(imsg, &v); + if (imsg->data == NULL) + break; + things_stop_pkt(ps, imsg); + break; + case IMSG_SHOW_PACKETS_REQUEST: + IMSG_SIZE_CHECK(imsg, &v); + if (imsg->data == NULL) + break; + things_echo_pkt(ps, imsg); + break; + case IMSG_KILL_CLIENT: + IMSG_SIZE_CHECK(imsg, &v); + if (imsg->data == NULL) + break; + memcpy(client_name, imsg->data, sizeof(client_name)); + TAILQ_FOREACH(client, thingsd_env->clients, entry) { + if (strcmp(client->name, client_name) == 0) { + log_debug("Control killed client: %s", + client_name); + client_del(thingsd_env, client); + break; + } + } + break; + case IMSG_GET_INFO_CLIENTS_REQUEST: + clients_show_info(ps, imsg); + break; + case IMSG_GET_INFO_SOCKETS_REQUEST: + sockets_show_info(ps, imsg); + break; + case IMSG_GET_INFO_THINGS_REQUEST: + case IMSG_GET_INFO_THINGS_REQUEST_ROOT: + things_show_info(ps, imsg); + break; + case IMSG_GET_INFO_PARENT_REQUEST: + thingsd_show_info(ps, imsg); + break; + case IMSG_CTL_RESET: + IMSG_SIZE_CHECK(imsg, &v); + memcpy(&v, imsg->data, sizeof(v)); + thingsd_reload(v); + break; + case IMSG_CTL_VERBOSE: + IMSG_SIZE_CHECK(imsg, &verbose); + memcpy(&verbose, imsg->data, sizeof(verbose)); + log_setverbose(verbose); + + proc_forward_imsg(ps, imsg, PROC_THINGS, -1); + break; + default: + return (-1); + } + + switch (cmd) { + case 0: + break; + default: + if (proc_compose_imsg(ps, PROC_CONTROL, -1, cmd, + imsg->hdr.peerid, -1, &res, sizeof(res)) == -1) + return (-1); + break; + } + + return (0); } +int +thingsd_dispatch_things(int fd, struct privsep_proc *p, struct imsg *imsg) +{ + struct privsep *ps = p->p_ps; + + switch (imsg->hdr.type) { + case IMSG_ADD_THING: + proc_forward_imsg(ps, imsg, PROC_CONTROL, -1); + break; + default: + return (-1); + } + + return (0); +} + void -thgsd_sighdlr(int sig, short event, void *arg) +thingsd_sighdlr(int sig, short event, void *arg) { + if (privsep_process != PROC_PARENT) + return; + switch (sig) { - case SIGQUIT: - case SIGTERM: - case SIGINT: case SIGHUP: - thgsd_shutdown(); + log_info("%s: reload requested with SIGHUP", __func__); + + /* + * This is safe because libevent uses async signal handlers + * that run in the event loop and not in signal context. + */ + thingsd_reload(0); break; case SIGPIPE: - /* ignore */ + log_info("%s: ignoring SIGPIPE", __func__); break; + case SIGUSR1: + log_info("%s: ignoring SIGUSR1", __func__); + break; + case SIGTERM: + case SIGINT: + thingsd_shutdown(); + break; default: fatalx("unexpected signal"); } } +__dead void +usage(void) +{ + fprintf(stderr, "usage: %s [-dnv] [-D macro=value] [-f file]\n", + getprogname()); + exit(1); +} + int -main(int argc, char *argv[]) +main(int argc, char **argv) { + struct thingsd *env; + struct privsep *ps; + struct timeval eb_timeout; int ch; - char *thgs_sock, *saved_argv0; - int pipe_thgs[2], debug = 0; - int control_fd; + const char *conffile = THINGSD_CONF; + enum privsep_procid proc_id = PROC_PARENT; + int proc_instance = 0; + const char *errp, *title = NULL; + int argc0 = argc; - thgs_sock = THINGSD_SOCK; - /* log to stderr until daemonized */ log_init(1, LOG_DAEMON); - log_setverbose(1); - saved_argv0 = argv[0]; + if ((env = calloc(1, sizeof(*env))) == NULL) + fatal("calloc: env"); - if (saved_argv0 == NULL) - saved_argv0 = "thingsd"; + thingsd_env = env; - while ((ch = getopt(argc, argv, "dvC")) != -1) { + while ((ch = getopt(argc, argv, "D:P:I:df:vn")) != -1) { switch (ch) { - case 'C': - thgs_chld = true; + case 'D': + if (cmdline_symset(optarg) < 0) + log_warnx("could not parse macro definition %s", + optarg); break; case 'd': - debug = 1; + env->thingsd_debug = 2; break; + case 'f': + conffile = optarg; + break; case 'v': - if (v_opts & L_VERBOSE1) - v_opts |= L_VERBOSE2; - v_opts |= L_VERBOSE1; + env->thingsd_verbose++; break; + case 'n': + env->thingsd_noaction = 1; + break; + case 'P': + title = optarg; + proc_id = proc_getid(procs, nitems(procs), title); + if (proc_id == PROC_MAX) + fatalx("invalid process name"); + break; + case 'I': + proc_instance = strtonum(optarg, 0, + PROC_MAX_INSTANCES, &errp); + if (errp) + fatalx("invalid process instance"); + break; default: usage(); } } argc -= optind; - if (argc > 0) usage(); - if (thgs_chld) - thgs_main(debug, v_opts & (L_VERBOSE1 | L_VERBOSE2), thgs_sock); - if (geteuid()) - fatalx("need root privileges"); - if ((control_fd = control_init(thgs_sock)) == -1) - fatalx("thgs_sock failed"); - control_state.fd = control_fd; + if (env->thingsd_noaction && !env->thingsd_debug) + env->thingsd_debug = 1; - log_init(debug, LOG_DAEMON); - log_setverbose(v_opts & L_VERBOSE1); + /* check for root privileges */ + if (env->thingsd_noaction == 0) { + if (geteuid()) + fatalx("need root privileges"); + } - /* make parent daemon */ - thgsd_process = PROC_MAIN; - log_procinit(log_procnames[thgsd_process]); + ps = &env->thingsd_ps; + ps->ps_env = env; - if (!debug && daemon(1, 0) == -1) - fatalx("daemon"); + if (config_init(env) == -1) + fatal("failed to initialize configuration"); - log_info("%s started", getprogname()); + if ((ps->ps_pw = getpwnam(THINGSD_USER)) == NULL) + fatal("unknown user %s", THINGSD_USER); - if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, - PF_UNSPEC, pipe_thgs) == -1) - fatalx("thgs socketpair"); + env->thingsd_conffile = conffile; - thgs_pid = start_child(PROC_THGS, saved_argv0, pipe_thgs[1], debug, - v_opts & (L_VERBOSE1 | L_VERBOSE2)); + if (parse_config(env->thingsd_conffile) == -1) + exit(1); - event_init(); + /* First proc runs as root without pledge but in default chroot */ + proc_priv->p_pw = &proc_privpw; /* initialized to all 0 */ + proc_priv->p_chroot = ps->ps_pw->pw_dir; /* from THINGSD_USER */ - signal_set(&evsigquit, SIGQUIT, thgsd_sighdlr, NULL); - signal_set(&evsigterm, SIGTERM, thgsd_sighdlr, NULL); - signal_set(&evsigint, SIGINT, thgsd_sighdlr, NULL); - signal_set(&evsighup, SIGHUP, thgsd_sighdlr, NULL); + /* Configure the control socket */ + ps->ps_csock.cs_name = THINGSD_SOCKET; + TAILQ_INIT(&ps->ps_rcsocks); - signal_add(&evsigquit, NULL); - signal_add(&evsigterm, NULL); - signal_add(&evsigint, NULL); - signal_add(&evsighup, NULL); - signal(SIGPIPE, SIG_IGN); + log_init(env->thingsd_debug, LOG_DAEMON); + log_setverbose(env->thingsd_verbose); - /* setup thgs child pipe */ - if ((iev_thgs = malloc(sizeof(struct imsgev))) == NULL) - fatalx("iev_thgs malloc"); + if (env->thingsd_noaction) + ps->ps_noaction = 1; - imsg_init(&iev_thgs->ibuf, pipe_thgs[0]); - iev_thgs->handler = main_dispatch_thgs; + ps->ps_instances[PROC_THINGS] = env->prefork_things; + ps->ps_instance = proc_instance; + if (title != NULL) + ps->ps_title[proc_id] = title; - /* setup event handler */ - iev_thgs->events = EV_READ; - event_set(&iev_thgs->ev, pipe_thgs[0], iev_thgs->events, - iev_thgs->handler, iev_thgs); - event_add(&iev_thgs->ev, NULL); + /* only the parent returns */ + proc_init(ps, procs, nitems(procs), argc0, argv, proc_id); - if (getpwnam(TH_USER) == NULL) - log_info("running as root. %s user not found", TH_USER); - if (pledge("stdio unix recvfd", NULL) == -1) - fatal("pledge"); + log_procinit("parent"); + if (!env->thingsd_debug && daemon(0, 0) == -1) + fatal("can't daemonize"); - TAILQ_INIT(&ctl_conns); - control_listen(); + if (ps->ps_noaction == 0) + log_info("%s startup", getprogname()); - event_dispatch(); + env->things_eb = event_init(); - thgsd_shutdown(); - return EXIT_SUCCESS; + signal_set(&ps->ps_evsigint, SIGINT, thingsd_sighdlr, ps); + signal_set(&ps->ps_evsigterm, SIGTERM, thingsd_sighdlr, ps); + signal_set(&ps->ps_evsighup, SIGHUP, thingsd_sighdlr, ps); + signal_set(&ps->ps_evsigpipe, SIGPIPE, thingsd_sighdlr, ps); + signal_set(&ps->ps_evsigusr1, SIGUSR1, thingsd_sighdlr, ps); + + signal_add(&ps->ps_evsigint, NULL); + signal_add(&ps->ps_evsigterm, NULL); + signal_add(&ps->ps_evsighup, NULL); + signal_add(&ps->ps_evsigpipe, NULL); + signal_add(&ps->ps_evsigusr1, NULL); + + if (!env->thingsd_noaction) + proc_connect(ps); + + if (thingsd_configure(ps) == -1) + fatalx("configuration failed"); + + /* begin thing watchdog */ + eb_timeout.tv_sec = EB_TIMEOUT; + eb_timeout.tv_usec = 0; + + while (env->dead_things->run) { + if (env->exists) { + do_reconn(); + } + event_base_loopexit(env->things_eb, &eb_timeout); + event_base_dispatch(env->things_eb); + } + + log_debug("%s parent exiting", getprogname()); + + return (0); } +int +thingsd_configure(struct privsep *ps) +{ + if (unveil(THINGSD_CONF, "r") == -1) + err(1, "unveil"); + if (unveil("/dev", "rw") == -1) + err(1, "unveil"); + if (unveil(NULL, NULL) != 0) + err(1, "unveil"); + + if (pledge("stdio rpath wpath inet proc tty dns", NULL) == -1) + err(1, "pledge"); + + if (parse_config(thingsd_env->thingsd_conffile) == -1) { + proc_kill(&thingsd_env->thingsd_ps); + exit(1); + } + + if (thingsd_env->thingsd_noaction) { + fprintf(stderr, "configuration OK\n"); + proc_kill(&thingsd_env->thingsd_ps); + exit(0); + } + + thingsd_configure_things(ps); + + return (0); +} + void -thgsd_shutdown() +thingsd_reload(int reset) { - pid_t pid; - int status; + const char *filename = thingsd_env->thingsd_conffile; - /* close pipe */ - msgbuf_write(&iev_thgs->ibuf.w); - msgbuf_clear(&iev_thgs->ibuf.w); - close(iev_thgs->ibuf.fd); - free(iev_thgs); - log_debug("waiting for children to terminate"); - do { - pid = wait(&status); - if (pid == -1) { - if (errno != EINTR && errno != ECHILD) - fatal("wait"); - } else if (WIFSIGNALED(status)) - log_warnx("%s terminated; signal %d", "things", - WTERMSIG(status)); - } while (pid != -1 || (pid == -1 && errno == EINTR)); - log_info("%s terminated", getprogname()); + log_warnx("%s: reload config file %s", __func__, filename); + + things_reset(); + + /* Purge the existing configuration. */ + config_purge(thingsd_env, reset); + config_setreset(thingsd_env, reset); + + if (parse_config(thingsd_env->thingsd_conffile) == -1) { + log_warnx("%s: failed to reload config file %s", + __func__, filename); + } + + thingsd_configure_things(&thingsd_env->thingsd_ps); +} + +void +thingsd_shutdown(void) +{ + proc_kill(&thingsd_env->thingsd_ps); + free(thingsd_env); + + log_warnx("parent terminating"); exit(0); } -static pid_t -start_child(int p, char *argv0, int fd, int debug, int verbose) +void +thingsd_show_info(struct privsep *ps, struct imsg *imsg) { - int argc = 0, argvc = 10; - char *argv[argvc]; - pid_t pid; + struct thingsd_parent_info npi; - switch (pid = fork()) { - case -1: - fatal("cannot fork"); - case 0: + switch (imsg->hdr.type) { + case IMSG_GET_INFO_PARENT_REQUEST: + npi.verbose = log_getverbose(); + if (proc_compose_imsg(ps, PROC_CONTROL, -1, + IMSG_GET_INFO_PARENT_DATA, imsg->hdr.peerid, + -1, &npi, sizeof(npi)) == -1) + return; + if (proc_compose_imsg(ps, PROC_CONTROL, -1, + IMSG_GET_INFO_PARENT_END_DATA, imsg->hdr.peerid, + -1, &npi, sizeof(npi)) == -1) + return; break; default: - close(fd); - return (pid); - } - - if (fd != PARENT_SOCK_FD) { - if (dup2(fd, PARENT_SOCK_FD) == -1) - fatal("cannot setup imsg fd"); - } else if (fcntl(fd, F_SETFD, 0) == -1) - fatal("cannot setup imsg fd"); - - argv[argc++] = argv0; - switch (p) { - case PROC_MAIN: - fatalx("Can not start main process"); - case PROC_THGS: - argv[argc++] = "-C"; + log_debug("%s: error handling imsg", __func__); break; } - if (debug) - argv[argc++] = "-d"; - if (verbose & L_VERBOSE1) - argv[argc++] = "-v"; - if (verbose & L_VERBOSE2) - argv[argc++] = "-v"; - argv[argc++] = NULL; - - execvp(argv0, argv); - fatal("execvp"); } void -imsg_event_add(struct imsgev *iev) +thingsd_configure_things(struct privsep *ps) { - iev->events = EV_READ; - if (iev->ibuf.w.queued) - iev->events |= EV_WRITE; + struct thing *thing, nti; + size_t n; - event_del(&iev->ev); - event_set(&iev->ev, iev->ibuf.fd, iev->events, iev->handler, iev); - event_add(&iev->ev, NULL); -} + open_things(thingsd_env, false); + create_sockets(thingsd_env, false); -int -imsg_compose_event(struct imsgev *iev, uint16_t type, uint32_t peerid, - pid_t pid, int fd, void *data, uint16_t datalen) -{ - int ret; + start_client_chk(thingsd_env); - if ((ret = imsg_compose(&iev->ibuf, type, peerid, - pid, fd, data, datalen)) != -1) - imsg_event_add(iev); - return (ret); -} + /* Send configured things to things. */ + TAILQ_FOREACH(thing, thingsd_env->things, entry) { + memset(&nti, 0, sizeof(nti)); -static void -main_dispatch_thgs(int fd, short event, void *bula) -{ - struct imsgev *iev = bula; - struct imsgbuf *ibuf = &iev->ibuf; - struct imsg imsg; - ssize_t n; - int shut = 0; + nti.exists = thing->exists; + nti.hw_ctl = thing->hw_ctl; + nti.persist = thing->persist; - if (event & EV_READ) { - if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN) - fatal("imsg_read error"); - if (n == 0) /* connection closed */ - shut = 1; - } - if (event & EV_WRITE) { - if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN) - fatal("msgbuf_write"); - if (n == 0) - shut = 1; - } + n = strlcpy(nti.iface, thing->iface, sizeof(nti.iface)); + if (n >= sizeof(nti.iface)) + fatalx("%s: nti.iface too long", __func__); - for (;;) { - if ((n = imsg_get(ibuf, &imsg)) == -1) - fatal("imsg_get"); + n = strlcpy(nti.ipaddr, thing->ipaddr, sizeof(nti.ipaddr)); + if (n >= sizeof(nti.ipaddr)) + fatalx("%s: nti.ipaddr too long", __func__); - if (n == 0) - break; + n = strlcpy(nti.parity, thing->parity, sizeof(nti.parity)); + if (n >= sizeof(nti.parity)) + fatalx("%s: nti.parity name too long", __func__); - switch (imsg.hdr.type) { - case IMSG_SHOW_PKTS: - case IMSG_LIST_CLTS: - case IMSG_LIST_THGS: - case IMSG_LIST_SOCKS: - case IMSG_CTL_END: - control_imsg_relay(&imsg); - break; - default: - log_debug("%s: error handling imsg %d", __func__, - imsg.hdr.type); - break; - } - imsg_free(&imsg); + n = strlcpy(nti.name, thing->name, sizeof(nti.name)); + if (n >= sizeof(nti.name)) + fatalx("%s: nti.name too long", __func__); + + n = strlcpy(nti.password, thing->password, + sizeof(nti.password)); + if (n >= sizeof(nti.password)) + fatalx("%s: nti.password too long", __func__); + + n = strlcpy(nti.location, thing->location, + sizeof(nti.location)); + if (n >= sizeof(nti.location)) + fatalx("%s: nti.location too long", __func__); + + n = strlcpy(nti.udp, thing->udp, sizeof(nti.udp)); + if (n >= sizeof(nti.udp)) + fatalx("%s: nti.name too long", __func__); + + nti.fd = thing->fd; + nti.baud = thing->baud; + nti.conn_port = thing->conn_port; + nti.rcv_port = thing->rcv_port; + nti.data_bits = thing->data_bits; + nti.max_clients = thing->max_clients; + nti.port = thing->port; + nti.stop_bits = thing->stop_bits; + nti.type = thing->type; + nti.client_cnt = thing->client_cnt; + + nti.tls = thing->tls; + + n = strlcpy(nti.tls_cert_file, thing->tls_cert_file, + sizeof(nti.tls_cert_file)); + if (n >= sizeof(nti.tls_cert_file)) + fatalx("%s: nti.tls_cert_file too long", __func__); + + n = strlcpy(nti.tls_key_file, thing->tls_key_file, + sizeof(nti.tls_key_file)); + if (n >= sizeof(nti.tls_key_file)) + fatalx("%s: nti.tls_key_file too long", __func__); + + n = strlcpy(nti.tls_ca_file, thing->tls_ca_file, + sizeof(nti.tls_ca_file)); + if (n >= sizeof(nti.tls_ca_file)) + fatalx("%s: nti.tls_ca_file too long", __func__); + + n = strlcpy(nti.tls_crl_file, thing->tls_crl_file, + sizeof(nti.tls_crl_file)); + if (n >= sizeof(nti.tls_crl_file)) + fatalx("%s: nti.tls_crl_file too long", __func__); + + n = strlcpy(nti.tls_ocsp_staple_file, + thing->tls_ocsp_staple_file, + sizeof(nti.tls_ocsp_staple_file)); + if (n >= sizeof(nti.tls_ocsp_staple_file)) + fatalx("%s: nti.tls_ocsp_staple_file too long", + __func__); + + proc_compose(ps, PROC_THINGS, IMSG_ADD_THING, + &nti, sizeof(nti)); } - if (!shut) - imsg_event_add(iev); - else { - /* this pipe is dead, so remove the event handler */ - event_del(&iev->ev); - event_loopexit(NULL); - } } - -int -main_imsg_compose_thgs(int type, pid_t pid, void *data, uint16_t datalen) -{ - return (imsg_compose_event(iev_thgs, type, 0, pid, -1, data, datalen)); -} blob - c67f9adb065e65b1c9813d8decb7653e606f9811 blob + fc0cc60f0d8d2ea8c4015f86c780a25d52bf76d9 --- thingsd/thingsd.conf.5 +++ thingsd/thingsd.conf.5 @@ -50,23 +50,28 @@ must be quoted. .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 default port Ar number +Set the default port for things to communicate on. +This is a required setting. +.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 prefork Ar number +Run the specified number of things processes. +This increases the performance and prevents delays when connecting to a thing. +.Xr thingsd 8 +runs 3 things processes by default. .El .Sh THINGS things represent a serial, TCP/IP, or UDP listener thing for @@ -85,9 +90,6 @@ Specify a single interface to create a 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 @@ -95,12 +97,9 @@ 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 data Ar number +Set the data bits for a serial thing +.Ar location . .It Ic hardware Ar number Set to 1 to turn on hardware control for a serial thing .Ar location . @@ -165,6 +164,12 @@ Set to 1 to turn on software control for a serial thin .It Ic stop Ar number Set the stop bit for a serial thing .Ar location . +.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 tls Ar option Set the TLS configuration for a thing. These options are only used if TLS has been enabled via the listen directive. @@ -256,6 +261,11 @@ 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 @@ -266,6 +276,8 @@ ipaddr thing would communicate on a separate port. # Global Options # +prefork 5 + default port 50000 max clients 10 @@ -301,11 +313,6 @@ thing "udp_thing" { } } .Ed -.Sh FILES -.Bl -tag -width Ds -compact -.It Pa /etc/thingsd.conf -.Xr thingsd 8 configuration file. -.El .Sh SEE ALSO .Xr thingsctl 8 , .Xr thingsd 8 blob - 9008ae693769ce93c836f1a45ba52857e341bd00 blob + a8da26e3d21a2f780fb4d3113e8f2e8e30db4109 --- thingsd/thingsd.h +++ thingsd/thingsd.h @@ -1,5 +1,6 @@ /* - * Copyright (c) 2016, 2019 Tracey Emery + * Copyright (c) 2016, 2019, 2020 Tracey Emery + * Copyright (c) 2015 Mike Larkin * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above @@ -14,32 +15,25 @@ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ -#ifndef _THINGSD_H -#define _THINGSD_H - -#include -#include - -#include -#include +#include #include -#include -#include -#include -#include "log.h" +#ifdef THINGSD_DEBUG +#define dprintf(x...) do { log_debug(x); } while(0) +#else +#define dprintf(x...) +#endif /* THINGSD_DEBUG */ -#define PATH_CONF "/etc/thingsd.conf" -#define TH_USER "_thingsd" -#define THINGSD_SOCK "/var/run/thingsd.sock" -#define CONN_RTRY 30 -#define MIN_RTRY 10 -#define MAX_RTRY 600 +#define THINGSD_CONF "/etc/thingsd.conf" +#define THINGSD_SOCKET "/var/run/thingsd.sock" +#define THINGSD_USER "_thingsd" + +#define CONN_RETRY 30 +#define MIN_RETRY 10 +#define MAX_RETRY 600 #define DEFAULT_BAUD 9600 -#define CLT_SUB_TIME 5 -#define CLT_SUB_CHK 1 -#define BUFF 1024 -#define DTHG_CHK 2 +#define CLIENT_SUB_TIME 5 +#define CLIENT_SUB_CHK 1 #define EB_TIMEOUT 10 #define TLS_CONFIG_MAX 511 @@ -53,300 +47,279 @@ #define TLSFLAG_OPTIONAL 0x04 #define TLSFLAG_BITS "\10\01CA\02CRL\03OPTIONAL" -#define L_VERBOSE1 0x00000001 -#define L_VERBOSE2 0x00000002 +#define THINGSD_MAXTEXT 511 +#define THINGSD_MAXNAME 16 -#define PARENT_SOCK_FD (STDERR_FILENO + 1) +#define THINGS_NUMPROC 3 +#define PKT_BUFF 2048 + +enum imsg_type { + IMSG_GET_INFO_PARENT_REQUEST = IMSG_PROC_MAX, + IMSG_GET_INFO_PARENT_DATA, + IMSG_GET_INFO_PARENT_END_DATA, + + IMSG_GET_INFO_CONTROL_REQUEST, + IMSG_GET_INFO_CONTROL_DATA, + IMSG_GET_INFO_CONTROL_END_DATA, + + IMSG_GET_INFO_THINGS_REQUEST, + IMSG_GET_INFO_THINGS_REQUEST_ROOT, + IMSG_GET_INFO_THINGS_DATA, + IMSG_GET_INFO_THINGS_END_DATA, + + IMSG_GET_INFO_CLIENTS_REQUEST, + IMSG_GET_INFO_CLIENTS_DATA, + IMSG_GET_INFO_CLIENTS_END_DATA, + + IMSG_GET_INFO_SOCKETS_REQUEST, + IMSG_GET_INFO_SOCKETS_DATA, + IMSG_GET_INFO_SOCKETS_END_DATA, + + IMSG_SHOW_PACKETS_REQUEST, + IMSG_SHOW_PACKETS_DATA, + IMSG_SHOW_PACKETS_END_DATA, + + IMSG_ADD_THING, + IMSG_KILL_CLIENT, +}; + enum socktypes { TCP, UDP, DEV }; -struct dthgs { - TAILQ_HEAD(zthgs, dthg) zthgs; - volatile sig_atomic_t run; +struct thingsd_control_info { + int verbose; }; -struct dthg { - TAILQ_ENTRY(dthg) entry; - char *name; - int type; - time_t dtime; +struct thingsd_parent_info { + int verbose; + char text[THINGSD_MAXTEXT]; }; -struct thg_imsg { - bool exists; - bool hw_ctl; - bool persist; - bool sw_ctl; - char iface[BUFF]; - char ipaddr[BUFF]; - char name[BUFF]; - char parity[BUFF]; - char password[BUFF]; - char location[BUFF]; - char udp[BUFF]; +struct client { + TAILQ_ENTRY(client) entry; + struct event *ev; + struct evbuffer *evb; + struct bufferevent *bev; + struct socket *socket; + bool subscribed; + char name[THINGSD_MAXNAME]; + char *sub_names[THINGSD_MAXTEXT]; int fd; - int baud; - int conn_port; - int data_bits; - int max_clt; int port; - int stop_bits; - int type; - size_t clt_cnt; + time_t join_time; + size_t le; + size_t subs; bool tls; - char tls_cert_file[BUFF]; - char tls_key_file[BUFF]; - char tls_ca_file[BUFF]; - char tls_crl_file[BUFF]; - char tls_ocsp_staple_file[BUFF]; + struct tls *tls_ctx; }; +TAILQ_HEAD(clientlist, client); -struct thg { - TAILQ_ENTRY(thg) entry; +struct socket { + TAILQ_ENTRY(socket) entry; + struct event *ev; + char name[THINGSD_MAXNAME]; + int fd; + int port; + size_t client_cnt; + size_t max_clients; + + bool tls; + struct tls_config *tls_config; + struct tls *tls_ctx; +}; +TAILQ_HEAD(socketlist, socket); + +struct thing { + TAILQ_ENTRY(thing) 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; + + char iface[THINGSD_MAXTEXT]; + char ipaddr[THINGSD_MAXTEXT]; + char name[THINGSD_MAXNAME]; + char parity[THINGSD_MAXTEXT]; + char password[THINGSD_MAXTEXT]; + char location[THINGSD_MAXTEXT]; + char udp[THINGSD_MAXTEXT]; + int fd; int baud; int conn_port; + int rcv_port; int data_bits; - int max_clt; + int max_clients; int port; int stop_bits; int type; - size_t clt_cnt; + size_t client_cnt; + bool tls; uint8_t tls_flags; + uint8_t *tls_cert; size_t tls_cert_len; - char *tls_cert_file; + char tls_cert_file[THINGSD_MAXTEXT]; + uint8_t *tls_key; size_t tls_key_len; - char *tls_key_file; + char tls_key_file[THINGSD_MAXTEXT]; + uint8_t *tls_ca; size_t tls_ca_len; - char *tls_ca_file; + char tls_ca_file[THINGSD_MAXTEXT]; + uint8_t *tls_crl; size_t tls_crl_len; - char *tls_crl_file; + char tls_crl_file[THINGSD_MAXTEXT]; + uint8_t *tls_ocsp_staple; size_t tls_ocsp_staple_len; - char *tls_ocsp_staple_file; + char tls_ocsp_staple_file[THINGSD_MAXTEXT]; + char tls_ciphers[TLS_CONFIG_MAX]; char tls_dhe_params[TLS_CONFIG_MAX]; char tls_ecdhe_curves[TLS_CONFIG_MAX]; + uint32_t tls_protocols; }; +TAILQ_HEAD(thinglist, thing); -struct sock_imsg { - char name[BUFF]; - int fd; - int port; - size_t clt_cnt; - size_t max_clts; - - bool tls; +struct dead_thing { + TAILQ_ENTRY(dead_thing) entry; + char name[THINGSD_MAXTEXT]; + int type; + time_t dtime; }; +TAILQ_HEAD(deadthinglist, dead_thing); -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; - - bool tls; - struct tls_config *tls_config; - struct tls *tls_ctx; +struct dead_things { + struct deadthinglist *dead_things_list; + volatile sig_atomic_t run; }; -struct clt_imsg { - bool subscribed; - char name[BUFF]; +struct packet_client { + TAILQ_ENTRY(packet_client) entry; + struct privsep ps; + struct imsg imsg; int fd; - int port; - size_t subs; - - bool tls; + char name[THINGSD_MAXNAME]; }; +TAILQ_HEAD(packetclientlist, packet_client); -struct clt { - TAILQ_ENTRY(clt) entry; - struct event *ev; - 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 thingsd { + struct thinglist *things; + struct clientlist *clients; + struct socketlist *sockets; - bool tls; - struct tls *tls_ctx; -}; + struct privsep thingsd_ps; + const char *thingsd_conffile; -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 thingsd_debug; + int thingsd_verbose; + int thingsd_noaction; + + char iface[THINGSD_MAXTEXT]; + int max_clients; int port; - size_t clt_cnt; - size_t conn_rtry; - size_t max_sub; - void (*clt_fptr)(struct thgsd *); + size_t client_cnt; + size_t conn_retry; + size_t max_subs; + uint16_t prefork_things; + void (*client_fptr)(struct thingsd *); /* disconnected things parts */ + struct dead_things *dead_things; bool exists; int dcount; - /* thgs */ - struct event_base *thgs_eb; - struct event thgs_evsigquit; - struct event thgs_evsigterm; - struct event thgs_evsigint; + /* things */ + struct event_base *things_eb; + struct event things_evsigquit; + struct event things_evsigterm; + struct event things_evsigint; + + /* control packets */ + struct packetclientlist *packet_clients; + int packet_client_count; }; +extern struct thingsd *thingsd_env; + +/* events.c */ +void udp_event(int, short, void *); + +/* client.c */ +void client_conn(int, short, void *); +void client_add(struct thingsd *, struct client *); +void client_del(struct thingsd *, struct client *); +void client_rd(struct bufferevent *, void *); +void client_wr(struct bufferevent *, void *); +void client_err(struct bufferevent *, short, void *); +void start_client_chk(struct thingsd *); +void *client_chk(void *); +void client_do_chk(struct thingsd *); +void client_wr_things(struct client *, struct thing *, size_t); +void client_tls_readcb(int, short, void *); +void client_tls_writecb(int, short, void *); +void clients_show_info(struct privsep *, struct imsg *); + +/* serial.c */ +void open_things(struct thingsd *, bool); + +/* sockets.c */ +struct socket *new_socket(int); +struct socket *get_socket(struct thingsd *, int); +char *get_ifaddrs(char *); +void create_sockets(struct thingsd *, bool); +void socket_rd(struct bufferevent *, void *); +void socket_wr(struct bufferevent *, void *); +void socket_err(struct bufferevent *, short, void *); +int create_socket(int, char *, int); +int open_client_socket(char *, int); +void sockets_show_info(struct privsep *, struct imsg *); + /* thingsd.c */ -int main_imsg_compose_thgs(int, pid_t, void *, - uint16_t); +void thingsd_reload(int); -/* control.c */ -#define IMSG_DATA_SIZE(imsg) ((imsg).hdr.len - IMSG_HEADER_SIZE) - -enum { - PROC_MAIN, - PROC_THGS, -} thgsd_process; - -static const char * const log_procnames[] = { - "main", - "things", -}; - -enum thgs_list_type { - THGS_LIST_CLTS, - THGS_LIST_THGS, - THGS_LIST_THGS_ROOT, - THGS_LIST_SOCKS, -}; - -struct imsgev { - struct imsgbuf ibuf; - void (*handler)(int, short, void *); - struct event ev; - short events; -}; - -struct ctl_pkt { - pid_t pid; - pid_t cpid; - char *name; - bool exists; -}; - -int control_init(char *); -int control_listen(void); -void control_accept(int, short, void *); -void control_dispatch_imsg(int, short, void *); -int control_imsg_relay(struct imsg *); - -TAILQ_HEAD(ctl_conns, ctl_conn) ctl_conns; - -enum imsg_type { - IMSG_NONE, - IMSG_CTL_END, - IMSG_THGS_LOG_VERBOSE, - IMSG_THGS_LIST, - IMSG_LIST_CLTS, - IMSG_LIST_THGS, - IMSG_LIST_SOCKS, - IMSG_KILL_CLT, - IMSG_SHOW_PKTS, -}; - -void imsg_event_add(struct imsgev *); -int imsg_compose_event(struct imsgev *, uint16_t, - uint32_t, pid_t, int, void *, uint16_t); - /* things.c */ -void thgs_main(int, int, char*); -void add_reconn(struct thg *); -struct dthg *new_dthg(struct thg *); -int thgs_imsg_compose_main(int, pid_t, void *, - uint16_t); -void send_ctl_pkt(char *, char *, int); +struct dead_thing *new_dead_thing(struct thing *); +void things(struct privsep *, struct privsep_proc *); +void things_reset(void); +void things_shutdown(void); +void add_reconn(struct thing *); +void do_reconn(void); +void things_sighdlr(int, short, void *); +void things_show_info(struct privsep *, struct imsg *); +void things_echo_pkt(struct privsep *, struct imsg *); +void things_stop_pkt(struct privsep *, struct imsg *); +void send_to_packet_client(struct thingsd *, char *, char *, int); +/* control.c */ +int config_init(struct thingsd *); +void config_purge(struct thingsd *, unsigned int); +int config_setreset(struct thingsd *, unsigned int); +int config_getreset(struct thingsd *, struct imsg *); + /* parse.y */ -struct thg *new_thg(char *); -int parse_conf(const char *); -int parse_buf(struct clt *, u_char *, int); +int parse_config(const char *); +int parse_buf(struct client *, u_char *, int); +int cmdline_symset(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); - -/* events.c */ -void udp_evt(int, short, void *); - -/* client.c */ -void clt_conn(int, short, void *); -void clt_add(struct thgsd *, struct clt *); -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); -void clt_tls_readcb(int, short, void *); -void clt_tls_writecb(int, short, void *); - /* tls.c */ -int tls_load_keypair(struct thg *); -int tls_load_ca(struct thg *); -int tls_load_crl(struct thg *); -int tls_load_ocsp(struct thg *); -int sock_tls_init(struct sock *, struct thg *); -void sock_tls_handshake(int, short, void *); -#endif /* _THINGSD_H */ +int tls_load_keypair(struct thing *); +int tls_load_ca(struct thing *); +int tls_load_crl(struct thing *); +int tls_load_ocsp(struct thing *); +int socket_tls_init(struct socket *, struct thing *); +void socket_tls_handshake(int, short, void *); blob - 01c0d50d1ffab875f9bd8151221102b3773eb7dd blob + 4c9d1b6da7a5e7a4ea1439f0bcf242d8a244282c --- thingsd/tls.c +++ thingsd/tls.c @@ -16,207 +16,269 @@ * 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 #include +#include "proc.h" #include "thingsd.h" int -tls_load_keypair(struct thg *pthg) +tls_load_keypair(struct thing *thing) { - if (pthg->tls == false) + if (thing->tls == false) return (0); - if ((pthg->tls_cert = tls_load_file(pthg->tls_cert_file, - &pthg->tls_cert_len, NULL)) == NULL) + + if ((thing->tls_cert = tls_load_file(thing->tls_cert_file, + &thing->tls_cert_len, NULL)) == NULL) return (-1); - log_debug("%s: using certificate %s", __func__, pthg->tls_cert_file); + + log_debug("%s: using certificate %s", __func__, thing->tls_cert_file); + /* XXX allow to specify password for encrypted key */ - if ((pthg->tls_key = tls_load_file(pthg->tls_key_file, - &pthg->tls_key_len, NULL)) == NULL) + if ((thing->tls_key = tls_load_file(thing->tls_key_file, + &thing->tls_key_len, NULL)) == NULL) return (-1); - log_debug("%s: using private key %s", __func__, pthg->tls_key_file); + + log_debug("%s: using private key %s", __func__, thing->tls_key_file); + return (0); } int -tls_load_ca(struct thg *pthg) +tls_load_ca(struct thing *thing) { - if ((pthg->tls_flags & TLSFLAG_CA) == 0 || pthg->tls_ca_file == NULL) + if ((thing->tls_flags & TLSFLAG_CA) == 0 || + strlen(thing->tls_ca_file) == 0) return (0); - if ((pthg->tls_ca = tls_load_file(pthg->tls_ca_file, &pthg->tls_ca_len, - NULL)) == NULL) + + if ((thing->tls_ca = tls_load_file(thing->tls_ca_file, + &thing->tls_ca_len, NULL)) == NULL) return (-1); - log_debug("%s: using ca cert(s) from %s", __func__, pthg->tls_ca_file); + + log_debug("%s: using ca cert(s) from %s", __func__, thing->tls_ca_file); + return (0); } int -tls_load_ocsp(struct thg *pthg) +tls_load_ocsp(struct thing *thing) { - if (pthg->tls == false) + if (thing->tls == false) return (0); - if (pthg->tls_ocsp_staple_file == NULL) + + if (strlen(thing->tls_ocsp_staple_file) == 0) return (0); - if ((pthg->tls_ocsp_staple = tls_load_file( - pthg->tls_ocsp_staple_file, - &pthg->tls_ocsp_staple_len, NULL)) == NULL) { + + if ((thing->tls_ocsp_staple = tls_load_file( + thing->tls_ocsp_staple_file, + &thing->tls_ocsp_staple_len, NULL)) == NULL) { log_warnx("%s: Failed to load ocsp staple from %s", __func__, - pthg->tls_ocsp_staple_file); + thing->tls_ocsp_staple_file); return (-1); } - if (pthg->tls_ocsp_staple_len == 0) { + + if (thing->tls_ocsp_staple_len == 0) { log_warnx("%s: ignoring 0 length ocsp staple from %s", __func__, - pthg->tls_ocsp_staple_file); + thing->tls_ocsp_staple_file); return (0); } + log_debug("%s: using ocsp staple from %s", __func__, - pthg->tls_ocsp_staple_file); + thing->tls_ocsp_staple_file); + return (0); } int -tls_load_crl(struct thg *pthg) +tls_load_crl(struct thing *thing) { - if ((pthg->tls_flags & TLSFLAG_CA) == 0 || pthg->tls_crl_file == NULL) + if ((thing->tls_flags & TLSFLAG_CA) == 0 || + strlen(thing->tls_crl_file) == 0) return (0); - if ((pthg->tls_crl = tls_load_file(pthg->tls_crl_file, - &pthg->tls_crl_len, NULL)) == NULL) + + if ((thing->tls_crl = tls_load_file(thing->tls_crl_file, + &thing->tls_crl_len, NULL)) == NULL) return (-1); - log_debug("%s: using crl(s) from %s", __func__, pthg->tls_crl_file); + + log_debug("%s: using crl(s) from %s", __func__, thing->tls_crl_file); + return (0); } int -sock_tls_init(struct sock *psock, struct thg *pthg) +socket_tls_init(struct socket *socket, struct thing *thing) { - if (pthg->tls == false) + if (thing->tls == false) return 0; - if (pthg->tls_cert == NULL) - /* soft fail if cert is not there yet */ - return (0); - log_debug("%s: setting up tls for %s", __func__, pthg->name); + + if (thing->tls_cert == NULL) + /* + * hard fail if cert is not there yet + * we don't check again + */ + return (-1); + + log_debug("%s: setting up tls for %s", __func__, thing->name); + if (tls_init() != 0) { log_warnx("%s: failed to initialise tls", __func__); return (-1); } - if ((psock->tls_config = tls_config_new()) == NULL) { + + if ((socket->tls_config = tls_config_new()) == NULL) { log_warnx("%s: failed to get tls config", __func__); return (-1); } - if ((psock->tls_ctx = tls_server()) == NULL) { + + if ((socket->tls_ctx = tls_server()) == NULL) { log_warnx("%s: failed to get tls server", __func__); return (-1); } - if (tls_config_set_protocols(psock->tls_config, - pthg->tls_protocols) != 0) { + + if (tls_config_set_protocols(socket->tls_config, + thing->tls_protocols) != 0) { log_warnx("%s: failed to set tls protocols: %s", __func__, - tls_config_error(psock->tls_config)); + tls_config_error(socket->tls_config)); return (-1); } - if (tls_config_set_ciphers(psock->tls_config, pthg->tls_ciphers) != 0) { + + if (tls_config_set_ciphers(socket->tls_config, + thing->tls_ciphers) != 0) { log_warnx("%s: failed to set tls ciphers: %s", __func__, - tls_config_error(psock->tls_config)); + tls_config_error(socket->tls_config)); return (-1); } - if (tls_config_set_dheparams(psock->tls_config, - pthg->tls_dhe_params) != 0) { + + if (tls_config_set_dheparams(socket->tls_config, + thing->tls_dhe_params) != 0) { log_warnx("%s: failed to set tls dhe params: %s", __func__, - tls_config_error(psock->tls_config)); + tls_config_error(socket->tls_config)); return (-1); } - if (tls_config_set_ecdhecurves(psock->tls_config, - pthg->tls_ecdhe_curves) != 0) { + + if (tls_config_set_ecdhecurves(socket->tls_config, + thing->tls_ecdhe_curves) != 0) { log_warnx("%s: failed to set tls ecdhe curves: %s", __func__, - tls_config_error(psock->tls_config)); + tls_config_error(socket->tls_config)); return (-1); } - if (tls_config_set_keypair_ocsp_mem(psock->tls_config, pthg->tls_cert, - pthg->tls_cert_len, pthg->tls_key, pthg->tls_key_len, - pthg->tls_ocsp_staple, pthg->tls_ocsp_staple_len) != 0) { + + if (tls_config_set_keypair_ocsp_mem(socket->tls_config, thing->tls_cert, + thing->tls_cert_len, thing->tls_key, thing->tls_key_len, + thing->tls_ocsp_staple, thing->tls_ocsp_staple_len) != 0) { log_warnx("%s: failed to set tls certificate/key: %s", __func__, - tls_config_error(psock->tls_config)); + tls_config_error(socket->tls_config)); return (-1); } - if (pthg->tls_ca != NULL) { - if (tls_config_set_ca_mem(psock->tls_config, pthg->tls_ca, - pthg->tls_ca_len) != 0) { + + if (thing->tls_ca != NULL) { + if (tls_config_set_ca_mem(socket->tls_config, thing->tls_ca, + thing->tls_ca_len) != 0) { log_warnx("%s: failed to add ca cert(s)", __func__); return (-1); } - if (tls_config_set_crl_mem(psock->tls_config, pthg->tls_crl, - pthg->tls_crl_len) != 0) { + + if (tls_config_set_crl_mem(socket->tls_config, thing->tls_crl, + thing->tls_crl_len) != 0) { log_warnx("%s: failed to add crl(s)", __func__); return (-1); } - if (pthg->tls_flags & TLSFLAG_OPTIONAL) - tls_config_verify_client_optional(psock->tls_config); + + if (thing->tls_flags & TLSFLAG_OPTIONAL) + tls_config_verify_client_optional(socket->tls_config); else - tls_config_verify_client(psock->tls_config); + tls_config_verify_client(socket->tls_config); } - log_debug("%s: adding keypair for server %s", __func__, pthg->name); - if (tls_config_add_keypair_ocsp_mem(psock->tls_config, pthg->tls_cert, - pthg->tls_cert_len, pthg->tls_key, pthg->tls_key_len, - pthg->tls_ocsp_staple, pthg->tls_ocsp_staple_len) != 0) { + + log_debug("%s: adding keypair for server %s", __func__, thing->name); + + if (tls_config_add_keypair_ocsp_mem(socket->tls_config, thing->tls_cert, + thing->tls_cert_len, thing->tls_key, thing->tls_key_len, + thing->tls_ocsp_staple, thing->tls_ocsp_staple_len) != 0) { log_warnx("%s: failed to add tls keypair", __func__); return (-1); } - if (tls_configure(psock->tls_ctx, psock->tls_config) != 0) { + + if (tls_configure(socket->tls_ctx, socket->tls_config) != 0) { log_warnx("%s: failed to configure tls - %s", __func__, - tls_error(psock->tls_ctx)); + tls_error(socket->tls_ctx)); return (-1); } + /* We're now done with the public/private key & ca/crl... */ - tls_config_clear_keys(psock->tls_config); - psock->tls = true; - freezero(pthg->tls_cert, pthg->tls_cert_len); - freezero(pthg->tls_key, pthg->tls_key_len); - free(pthg->tls_ca); - free(pthg->tls_crl); - pthg->tls_ca = NULL; - pthg->tls_cert = NULL; - pthg->tls_crl = NULL; - pthg->tls_key = NULL; - pthg->tls_ca_len = 0; - pthg->tls_cert_len = 0; - pthg->tls_crl_len = 0; - pthg->tls_key_len = 0; + tls_config_clear_keys(socket->tls_config); + + socket->tls = true; + + freezero(thing->tls_cert, thing->tls_cert_len); + freezero(thing->tls_key, thing->tls_key_len); + free(thing->tls_ca); + free(thing->tls_crl); + + thing->tls_ca = NULL; + thing->tls_cert = NULL; + thing->tls_crl = NULL; + thing->tls_key = NULL; + + thing->tls_ca_len = 0; + thing->tls_cert_len = 0; + thing->tls_crl_len = 0; + thing->tls_key_len = 0; + return 0; } void -sock_tls_handshake(int fd, short event, void *arg) +socket_tls_handshake(int fd, short event, void *arg) { - struct thgsd *pthgsd = (struct thgsd *)arg; - struct clt *clt = NULL, *tclt; + struct thingsd *thingsd = (struct thingsd *)arg; + struct client *client = NULL, *tclient; ssize_t ret = 0; - TAILQ_FOREACH(tclt, &pthgsd->clts, entry) { - if (tclt->fd == fd) { - clt = tclt; + TAILQ_FOREACH(tclient, thingsd->clients, entry) { + if (tclient->fd == fd) { + client = tclient; break; } } - ret = tls_handshake(clt->tls_ctx); + + ret = tls_handshake(client->tls_ctx); + if (ret == 0) { - event_del(clt->ev); + event_del(client->ev); log_debug("%s: tls handshake success", __func__); - clt_add(pthgsd, clt); + /* client_add(thingsd, client); */ } else if (ret == TLS_WANT_POLLIN) { - event_del(clt->ev); - event_set(clt->ev, clt->fd, EV_READ|EV_PERSIST, - sock_tls_handshake, pthgsd); - if (event_add(clt->ev, NULL)) - log_debug("%s: event add clt", __func__); + event_del(client->ev); + event_set(client->ev, client->fd, EV_READ|EV_PERSIST, + socket_tls_handshake, thingsd); + if (event_add(client->ev, NULL)) + log_debug("%s: event add client", __func__); } else if (ret == TLS_WANT_POLLOUT) { - event_del(clt->ev); - event_set(clt->ev, clt->fd, EV_WRITE|EV_PERSIST, - sock_tls_handshake, pthgsd); - if (event_add(clt->ev, NULL)) - log_debug("%s: event add clt", __func__); + event_del(client->ev); + event_set(client->ev, client->fd, EV_WRITE|EV_PERSIST, + socket_tls_handshake, thingsd); + if (event_add(client->ev, NULL)) + log_debug("%s: event add client", __func__); } else { - event_del(clt->ev); + event_del(client->ev); log_debug("%s: tls handshake failed - %s", __func__, - tls_error(clt->tls_ctx)); + tls_error(client->tls_ctx)); } }