Initial commit on github.

This commit is contained in:
Roland Jax
2013-11-14 21:15:14 +01:00
parent 36fc9f23c2
commit 916ec20456
37 changed files with 8561 additions and 2 deletions
+9
View File
@@ -0,0 +1,9 @@
bin_PROGRAMS = ebusd
ebusd_SOURCES = ebusd.c ebusd.h utils.c utils.h
ebusd_LDADD = $(top_srcdir)/lib/libebus.a $(top_srcdir)/lib/liblog.a
ebusd_CFLAGS = -I$(top_srcdir)/lib
distclean-local:
-rm -f Makefile.in
+742
View File
@@ -0,0 +1,742 @@
/*
* Copyright (C) Roland Jax 2012-2013 <roland.jax@liwest.at>
*
* This file is part of ebusd.
*
* ebusd is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ebusd is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ebusd. If not, see http://www.gnu.org/licenses/.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <getopt.h>
#include <unistd.h>
#include <sys/stat.h>
#include <ctype.h>
#include <syslog.h>
#include <termios.h>
#include <errno.h>
#include "log.h"
#include "utils.h"
#include "ebus-decode.h"
#include "ebus-cmd.h"
#include "ebus-bus.h"
#include "ebusd.h"
/* global variables */
const char *progname;
static int pidfile_locked = NO;
static int msg_queue_on = NO;
static int pidfd = UNSET; /* pidfile file descriptor */
static int serialfd = UNSET; /* serial file descriptor */
static int socketfd = UNSET; /* socket file descriptor */
static char address[3];
static char cfgdir[CFG_LINELEN];
static char cfgfile[CFG_LINELEN];
static char device[CFG_LINELEN];
static char extension[10];
static int foreground = UNSET;
static char loglevel[CFG_LINELEN];
static char logfile[CFG_LINELEN];
static char pidfile[CFG_LINELEN];
static int port = UNSET;
static int rawdump = UNSET;
static char rawfile[CFG_LINELEN];
static int showraw = UNSET;
static int settings = UNSET;
static int localhost = UNSET;
static int get_retry = UNSET;
static int skip_ack = UNSET;
static int max_wait = UNSET;
static int send_retry = UNSET;
static int print_size = UNSET;
static char options[] = "a:c:C:d:e:fl:L:P:p:rR:sStvh";
static struct option opts[] = {
{"address", required_argument, NULL, 'a'},
{"cfgfdir", required_argument, NULL, 'c'},
{"cfgfile", required_argument, NULL, 'C'},
{"device", required_argument, NULL, 'd'},
{"extension", required_argument, NULL, 'e'},
{"foreground", no_argument, NULL, 'f'},
{"loglevel", required_argument, NULL, 'l'},
{"logfile", required_argument, NULL, 'L'},
{"pidfile", required_argument, NULL, 'P'},
{"port", required_argument, NULL, 'p'},
{"rawdump", no_argument, NULL, 'r'},
{"rawfile", required_argument, NULL, 'R'},
{"showraw", no_argument, NULL, 's'},
{"settings", no_argument, NULL, 'S'},
{"localhost", no_argument, NULL, 't'},
{"version", no_argument, NULL, 'v'},
{"help", no_argument, NULL, 'h'},
{NULL, no_argument, NULL, 0 },
};
static struct config cfg[] = {
{"address", STR, &address, "\tbus address (" NUMSTR(EBUS_QQ) ")"},
{"cfgdir", STR, &cfgdir, "\tconfiguration directory of command files (" DAEMON_CFGDIR ")"},
{"cfgfile", STR, &cfgfile, "\tdaemon configuration file (" DAEMON_CFGFILE ")"},
{"device", STR, &device, "\tserial device (" SERIAL_DEVICE ")"},
{"extension", STR, &extension, "extension of command files (" DAEMON_EXTENSION ")"},
{"foreground", BOL, &foreground, "run in foreground"},
{"loglevel", STR, &loglevel, "\tlog level (INF | " LOGTXT ")"},
{"logfile", STR, &logfile, "\tlog file (" DAEMON_LOGFILE ")"},
{"pidfile", STR, &pidfile, "\tpid file (" DAEMON_PIDFILE ")"},
{"port", NUM, &port, "\tport (" NUMSTR(SOCKET_PORT) ")"},
{"rawdump", BOL, &rawdump, "\tdump raw ebus data to file"},
{"rawfile", STR, &rawfile, "\traw file (" DAEMON_RAWFILE ")"},
{"showraw", BOL, &showraw, "\tprint raw data"},
{"settings", BOL, &settings, "\tprint daemon settings"},
{"localhost", BOL, &localhost, "allow only connection from localhost"},
{"get_retry", NUM, &get_retry, NULL},
{"skip_ack", NUM, &skip_ack, NULL},
{"max_wait", NUM, &max_wait, NULL},
{"send_retry", NUM, &send_retry, NULL},
{"print_size", NUM, &print_size, NULL},
{"version", STR, NULL, "\tprint version information"},
{"help", STR, NULL, "\tprint this message"}
};
const int cfglen = sizeof(cfg) / sizeof(cfg[0]);
void
usage(void)
{
fprintf(stdout, "\nUsage: %s [OPTIONS]\n", progname);
int i, skip;
skip = 0;
for (i = 0; i < cfglen; i++) {
if (cfg[i].info != NULL) {
fprintf(stdout, " -%c --%s\t%s\n",
opts[i - skip].val,
opts[i - skip].name,
cfg[i].info);
} else {
skip++;
}
}
fprintf(stdout, "\n");
}
void
cmdline(int *argc, char ***argv)
{
for (;;) {
int i;
i = getopt_long(*argc, *argv, options, opts, NULL);
if (i == -1)
break;
switch (i) {
case 'a':
if (strlen(optarg) > 2)
strncpy(address, &optarg[strlen(optarg) - 2 ], 2);
else
strncpy(address, optarg, strlen(optarg));
break;
case 'c':
strncpy(cfgdir, optarg, strlen(optarg));
break;
case 'C':
strncpy(cfgfile, optarg, strlen(optarg));
break;
case 'd':
strncpy(device, optarg, strlen(optarg));
break;
case 'e':
strncpy(extension, optarg, strlen(optarg));
break;
case 'f':
foreground = YES;
break;
case 'l':
strncpy(loglevel, optarg, strlen(optarg));
break;
case 'L':
strncpy(logfile, optarg, strlen(optarg));
break;
case 'P':
strncpy(pidfile, optarg, strlen(optarg));
break;
case 'p':
if (isdigit(*optarg))
port = atoi(optarg);
break;
case 'r':
rawdump = YES;
break;
case 'R':
strncpy(rawfile, optarg, strlen(optarg));
rawdump = YES;
break;
case 's':
showraw = YES;
break;
case 'S':
settings = YES;
break;
case 't':
localhost = YES;
break;
case 'v':
fprintf(stdout, DAEMON_NAME " " DAEMON_VERSION "\n");
exit(EXIT_SUCCESS);
case 'h':
default:
usage();
exit(EXIT_FAILURE);
break;
}
}
}
void
set_unset(void)
{
if (*address == '\0')
strncpy(address , &NUMSTR(EBUS_QQ)[2], 2);
if (*cfgdir == '\0')
strncpy(cfgdir , DAEMON_CFGDIR, strlen(DAEMON_CFGDIR));
if (*device == '\0')
strncpy(device , SERIAL_DEVICE, strlen(SERIAL_DEVICE));
if (*extension == '\0') {
strncpy(extension , DAEMON_EXTENSION, strlen(DAEMON_EXTENSION));
}
if (foreground == UNSET)
foreground = NO;
if (*loglevel == '\0')
strncpy(loglevel , DAEMON_LOGLEVEL, strlen(DAEMON_LOGLEVEL));
if (*logfile == '\0')
strncpy(logfile , DAEMON_LOGFILE, strlen(DAEMON_LOGFILE));
if (*pidfile == '\0')
strncpy(pidfile , DAEMON_PIDFILE, strlen(DAEMON_PIDFILE));
if (port == UNSET)
port = SOCKET_PORT;
if (rawdump == UNSET)
rawdump = NO;
if (*rawfile == '\0')
strncpy(rawfile , DAEMON_RAWFILE, strlen(DAEMON_RAWFILE));
if (showraw == UNSET)
showraw = NO;
if (settings == UNSET)
settings = NO;
if (localhost == UNSET)
localhost = NO;
if (get_retry == UNSET)
get_retry = EBUS_GET_RETRY;
/* set max */
if (get_retry > EBUS_GET_RETRY_MAX)
get_retry = EBUS_GET_RETRY_MAX;
if (skip_ack == UNSET)
skip_ack = EBUS_SKIP_ACK;
if (max_wait == UNSET)
max_wait = EBUS_MAX_WAIT;
if (send_retry == UNSET)
send_retry = EBUS_SEND_RETRY;
/* set max */
if (send_retry > EBUS_SEND_RETRY_MAX)
send_retry = EBUS_SEND_RETRY_MAX;
if (print_size == UNSET)
print_size = EBUS_PRINT_SIZE;
}
void
signal_handler(int sig) {
switch(sig) {
case SIGHUP:
log_print(L_ALL, "SIGHUP received");
syslog(LOG_INFO, "SIGHUP received");
break;
case SIGINT:
log_print(L_ALL, "SIGINT received - logfile reopen");
syslog(LOG_INFO, "SIGINT received - logfile reopen");
log_open(logfile, foreground);
break;
case SIGTERM:
log_print(L_ALL, "daemon exiting");
syslog(LOG_INFO, "daemon exiting");
cleanup(EXIT_SUCCESS);
break;
default:
log_print(L_ALL, "unknown signal %s", strsignal(sig));
syslog(LOG_INFO, "unknown signal %s", strsignal(sig));
break;
}
}
void
daemonize(void)
{
pid_t pid;
/* fork off the parent process */
pid = fork();
if (pid < 0) {
err_if(1);
cleanup(EXIT_FAILURE);
}
/* If we got a good PID, then we can exit the parent process */
if (pid > 0) {
/* printf("Child process created: %d\n", pid); */
exit(EXIT_SUCCESS);
}
/* At this point we are executing as the child process */
/* Set file permissions 750 */
umask(027);
/* Create a new SID for the child process and */
/* detach the process from the parent (normally a shell) */
if (setsid() < 0) {
err_if(1);
cleanup(EXIT_FAILURE);
}
/* Change the current working directory. This prevents the current
directory from being locked; hence not being able to remove it. */
if (chdir(DAEMON_WORKDIR) < 0) {
/* Log any failure here */
err_if(1);
cleanup(EXIT_FAILURE);
}
/* Route I/O connections */
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
/* write pidfile and try to lock it */
if (pid_file_open(pidfile, &pidfd) == -1) {
log_print(L_ERR, "can't open pidfile: %s\n", pidfile);
cleanup(EXIT_FAILURE);
} else {
pidfile_locked = YES;
log_print(L_INF, "%s created.", pidfile);
}
/* Cancel certain signals */
signal(SIGCHLD, SIG_DFL); /* A child process dies */
signal(SIGTSTP, SIG_IGN); /* Various TTY signals */
signal(SIGTTOU, SIG_IGN); /* Ignore TTY background writes */
signal(SIGTTIN, SIG_IGN); /* Ignore TTY background reads */
/* Trap signals that we expect to receive */
signal(SIGHUP, signal_handler);
signal(SIGINT, signal_handler);
signal(SIGTERM, signal_handler);
}
void
cleanup(int state)
{
/* free msg queue */
if (msg_queue_on == YES) {
msg_queue_free();
log_print(L_INF, "msg queue freeed");
}
/* close listing tcp socket */
if (socketfd > 0) {
if (sock_close(socketfd) == -1)
log_print(L_ERR, "can't close port: %d", port);
else
log_print(L_INF, "port %d closed", port);
}
/* close serial device */
if (serialfd > 0) {
if (eb_serial_close() == -1)
log_print(L_ERR, "can't close device: %s", device);
else
log_print(L_INF, "%s closed", device);
}
/* close rawfile */
if (rawdump == YES) {
if (eb_raw_file_close() == -1)
log_print(L_ERR, "can't close rawfile: %s\n", rawfile);
else
log_print(L_INF, "%s closed", rawfile);
}
/* free mem for ebus commands */
eb_cmd_dir_free();
if (foreground == NO) {
/* delete PID file */
if (pidfile_locked)
if (pid_file_close(pidfile, pidfd) == -1)
log_print(L_INF, "%s deleted", pidfile);
/* Reset all signal handlers to default */
signal(SIGCHLD, SIG_DFL);
signal(SIGTSTP, SIG_DFL);
signal(SIGTTOU, SIG_DFL);
signal(SIGTTIN, SIG_DFL);
signal(SIGHUP, SIG_DFL);
signal(SIGINT, SIG_DFL);
signal(SIGTERM, SIG_DFL);
/* print end message */
log_print(L_ALL, DAEMON_NAME " " DAEMON_VERSION " stopped");
syslog(LOG_INFO, DAEMON_NAME " " DAEMON_VERSION " stopped");
}
/* close logging system */
log_close();
exit(state);
}
void
main_loop(void)
{
int maxfd, sfd_closed, timeout_reached;
fd_set listenfds;
struct timeval timeout;
sfd_closed = NO;
timeout_reached = NO;
FD_ZERO(&listenfds);
FD_SET(serialfd, &listenfds);
FD_SET(socketfd, &listenfds);
maxfd = socketfd;
/* serialfd should be always lower then socketfd */
if (serialfd > socketfd) {
log_print(L_ERR, "serialfd %d > %d socketfd", serialfd, socketfd);
cleanup(EXIT_FAILURE);
}
for (;;) {
fd_set readfds;
int readfd;
int ret;
/* set select timeout 10 secs */
timeout.tv_sec = 10;
timeout.tv_usec = 0;
/* set readfds to inital listenfds */
readfds = listenfds;
/* check if the usb device is working */
if (eb_serial_valid() < 0 || timeout_reached == YES) {
timeout_reached = NO;
if (serialfd > 0 && sfd_closed == NO) {
log_print(L_ERR, "serial device is invalid");
sfd_closed = YES;
/* close listing tcp socket */
if (socketfd > 0) {
if (sock_close(socketfd) == -1)
log_print(L_ERR, "can't close port: %d", port);
else
log_print(L_INF, "port %d closed", port);
}
/* close serial device */
if (eb_serial_close() == -1)
log_print(L_ERR, "can't close device: %s", device);
else
log_print(L_INF, "%s closed", device);
}
/* need sleep to prevent high cpu consumption */
sleep(1);
/* open serial device */
if (eb_serial_open(device, &serialfd) == 0) {
log_print(L_INF, "%s opened", device);
sfd_closed = NO;
}
/* open listing tcp socket */
if (sfd_closed == NO && sock_open(&socketfd, port, localhost) == 0)
log_print(L_INF, "port %d opened", port);
continue;
}
ret = select(maxfd + 1, &readfds, NULL, NULL, &timeout);
/* timeout after 10 secs means that ebus is probably
disconnected or USB device is dead */
if (ret == 0) {
log_print(L_WAR, "select timeout (%d) reached", timeout.tv_sec);
timeout_reached = YES;
continue;
/* ignore signals */
} else if ((ret < 0) && (errno == EINTR)) {
/* log_print(L_NOT, "get signal at select: %s", strerror(errno)); */
continue;
/* on other errors */
} else if (ret < 0) {
err_if(1);
cleanup(EXIT_FAILURE);
}
/* new data from serial port? */
if (FD_ISSET(serialfd, &readfds)) {
/* get cycle message from bus */
ret = eb_cyc_data_recv();
/* send msg to bus - only when cyc buf is empty */
if (ret == 0 && msg_queue_entries() > 0) {
char tcpbuf[SOCKET_BUFSIZE];
char data[MSG_QUEUE_MSG_SIZE];
int tcpbuflen, id, clientfd;
memset(tcpbuf, '\0', sizeof(tcpbuf));
tcpbuflen = sizeof(tcpbuf);
memset(data, '\0', sizeof(data));
/* get next entry from msg queue */
msg_queue_msg_del(&id, data, &clientfd);
/* just do it */
eb_execute(id, data, tcpbuf, &tcpbuflen);
/* send answer */
sock_client_write(clientfd, tcpbuf, tcpbuflen);
}
}
/* new incoming connection at TCP port arrived? */
if (FD_ISSET(socketfd, &readfds)) {
/* get new TCP client fd*/
ret = sock_client_accept(socketfd, &readfd);
if (readfd >= 0) {
/* add new TCP client fd to listenfds */
FD_SET(readfd, &listenfds);
(readfd > maxfd) ? (maxfd = readfd) : (1);
}
}
/* run through connected sockets for new data */
for (readfd = socketfd + 1; readfd <= maxfd; ++readfd) {
/* check all connected clients */
if (FD_ISSET(readfd, &readfds)) {
char tcpbuf[SOCKET_BUFSIZE];
char data[MSG_QUEUE_MSG_SIZE];
int tcpbuflen;
memset(tcpbuf, '\0', sizeof(tcpbuf));
tcpbuflen = sizeof(tcpbuf);
memset(data, '\0', sizeof(data));
/* get message from client */
ret = sock_client_read(readfd, tcpbuf, &tcpbuflen);
/* remove dead TCP client */
if (ret < 0) {
FD_CLR(readfd, &listenfds);
continue;
}
/* handle different commands */
if (strncasecmp("shutdown", tcpbuf, 8) == 0)
cleanup(EXIT_SUCCESS);
if (strncasecmp("loglevel", tcpbuf, 8) == 0) {
strncpy(loglevel, tcpbuf, strlen(tcpbuf));
log_level(loglevel);
continue;
}
/* search ebus command */
if (tcpbuflen > 0)
ret = eb_cmd_search_com(tcpbuf, data);
else
ret = -1;
/* command not found */
if (ret < 0) {
memset(tcpbuf, '\0', sizeof(tcpbuf));
strcpy(tcpbuf, "command not found\n");
tcpbuflen = strlen(tcpbuf);
/* send answer */
sock_client_write(readfd, tcpbuf, tcpbuflen);
} else {
msg_queue_msg_add(ret, data, readfd);
}
}
}
}
}
int
main(int argc, char *argv[])
{
int tmp;
/* set progname */
progname = (const char *)strrchr(argv[0], '/');
progname = progname ? (progname + 1) : argv[0];
/* read command line */
cmdline(&argc, &argv);
/* set default cfgfile */
if (*cfgfile == '\0')
strncpy(cfgfile , DAEMON_CFGFILE, strlen(DAEMON_CFGFILE));
/* read config file */
if (cfg_file_read(cfgfile, cfg, cfglen) == -1)
fprintf(stderr, "can't open cfgfile: %s ==> " \
"build in settings will be used\n", cfgfile);
/* set unset configuration */
set_unset();
/* print configuration */
if (settings == YES)
cfg_print(cfg, cfglen);
/* set ebus configuration */
eb_set_rawdump(rawdump);
eb_set_showraw(showraw);
tmp = (eb_htoi(&address[0])) * 16 + (eb_htoi(&address[1]));
eb_set_qq((unsigned char) tmp);
eb_set_get_retry(get_retry);
eb_set_skip_ack(skip_ack);
eb_set_max_wait(max_wait);
eb_set_send_retry(send_retry);
eb_set_print_size(print_size);
/* open log */
log_level(loglevel);
log_open(logfile, foreground);
/* to be daemon */
if (foreground == NO) {
log_print(L_ALL, DAEMON_NAME " " DAEMON_VERSION " started");
syslog(LOG_INFO, DAEMON_NAME " " DAEMON_VERSION " started");
daemonize();
}
/* read ebus command configuration files */
if (eb_cmd_dir_read(cfgdir, extension) == -1)
log_print(L_WAR, "error during read command file");
/* open raw file */
if (rawdump == YES) {
if (eb_raw_file_open(rawfile) == -1) {
log_print(L_ALL, "can't open rawfile: %s", rawfile);
cleanup(EXIT_FAILURE);
} else {
log_print(L_INF, "%s opened", rawfile);
}
}
/* open serial device */
if (eb_serial_open(device, &serialfd) == -1) {
log_print(L_ALL, "can't open device: %s", device);
cleanup(EXIT_FAILURE);
} else {
log_print(L_INF, "%s opened", device);
}
/* open listing tcp socket */
if (sock_open(&socketfd, port, localhost) == -1) {
log_print(L_ALL, "can't open port: %d", port);
cleanup(EXIT_FAILURE);
} else {
log_print(L_INF, "port %d opened", port);
}
/* init msg queue */
if (msg_queue_init() == -1) {
log_print(L_ALL, "can't initialize msg queue");
cleanup(EXIT_FAILURE);
} else {
msg_queue_on = YES;
log_print(L_INF, "msg queue initialized");
}
/* enter main loop */
main_loop();
cleanup(EXIT_SUCCESS);
return 0;
}
+54
View File
@@ -0,0 +1,54 @@
/*
* Copyright (C) Roland Jax 2012-2013 <roland.jax@liwest.at>
*
* This file is part of ebusd.
*
* ebusd is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ebusd is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ebusd. If not, see http://www.gnu.org/licenses/.
*/
#ifndef MAIN_H_
#define MAIN_H_
#define DAEMON_NAME "ebusd"
#define DAEMON_VERSION "0.1"
#define DAEMON_WORKDIR "/tmp/"
#define DAEMON_CFGDIR "/etc/ebusd"
#define DAEMON_CFGFILE DAEMON_CFGDIR"/ebusd.conf"
#define DAEMON_EXTENSION "csv"
#define DAEMON_FOREGROUND NO
#define DAEMON_LOGLEVEL "INF"
#define DAEMON_LOGFILE "/var/log/ebusd.log"
#define DAEMON_NOSYN NO
#define DAEMON_PIDFILE "/var/run/ebusd.pid"
#define DAEMON_RAWFILE "/tmp/ebusd.bin"
#define DAEMON_RAWDUMP NO
void usage(void);
void cmdline(int *argc, char ***argv);
void set_unset(void);
void signal_handler(int sig);
void daemonize(void);
void cleanup(int state);
void main_loop(void);
#endif /* MAIN_H_ */
+414
View File
@@ -0,0 +1,414 @@
/*
* Copyright (C) Roland Jax 2012-2013 <roland.jax@liwest.at>
*
* This file is part of ebusd.
*
* ebusd is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ebusd is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ebusd. If not, see http://www.gnu.org/licenses/.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <netdb.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "log.h"
#include "ebus-bus.h"
#include "utils.h"
struct msg_queue *dummy;
static int msg_entries;
int
msg_queue_entries(void)
{
return msg_entries;
}
int
msg_queue_init(void)
{
dummy = (struct msg_queue *) malloc(sizeof(struct msg_queue));
if (dummy != NULL) {
dummy->id = -1;
memset(dummy->data, '\0', sizeof(dummy->data));
dummy->clientfd = -1;
dummy->prev = NULL;
msg_entries = 0;
return 0;
}
return -1;
}
void
msg_queue_free(void)
{
while (dummy->prev != NULL)
msg_queue_get();
free(dummy);
msg_entries = 0;
}
void
msg_queue_put(struct msg_queue *new)
{
struct msg_queue *tmp;
/* first element */
if (dummy->prev == NULL) {
dummy->prev = new;
new->prev = NULL;
} else {
tmp = dummy;
/* get last element */
while (tmp->prev != NULL)
tmp = tmp->prev;
tmp->prev = new;
new->prev = NULL;
}
}
void
msg_queue_get(void)
{
struct msg_queue *tmp;
/* delete element */
if (dummy->prev != NULL) {
tmp = dummy->prev;
dummy->prev = tmp->prev;
free(tmp);
} else {
log_print(L_ERR, "msg queue empty - should never seen");
}
}
void
msg_queue_msg_add(int id, char *data, int clientfd)
{
struct msg_queue *new;
new = (struct msg_queue *) malloc(sizeof(struct msg_queue));
if (new != NULL) {
new->id = id;
memset(new->data, '\0', sizeof(new->data));
strncpy(new->data, data, strlen(data));
new->clientfd = clientfd;
new->prev = NULL;
msg_queue_put(new);
msg_entries++;
log_print(L_DBG, "add: id: %d clientfd: %d ==> entries: %d",
new->id, new->clientfd, msg_entries);
}
}
void
msg_queue_msg_del(int *id, char *data, int *clientfd)
{
if (dummy->prev != NULL) {
*id = dummy->prev->id;
memset(data, '\0', sizeof(data));
strncpy(data, dummy->prev->data, strlen(dummy->prev->data));
*clientfd = dummy->prev->clientfd;
msg_queue_get();
msg_entries--;
log_print(L_DBG, "del: id: %d clientfd: %d ==> entries: %d",
*id, *clientfd, msg_entries);
} else {
log_print(L_NOT, "msg queue empty");
}
}
void
cfg_print(struct config *cfg, int len)
{
int i;
fprintf(stdout, "\n");
for (i = 0; i < len; i++) {
if (cfg[i].key != NULL && cfg[i].tgt != NULL) {
fprintf(stdout, "%s = ", cfg[i].key);
switch (cfg[i].type) {
case STR:
fprintf(stdout, "%s\n", (char *) cfg[i].tgt);
break;
case BOL:
if (*(int *) cfg[i].tgt == NO)
fprintf(stdout, "NO\n");
else if (*(int *) cfg[i].tgt == YES)
fprintf(stdout, "YES\n");
else
fprintf(stdout, "UNSET\n");
break;
case NUM:
fprintf(stdout, "%d\n", *(int *) cfg[i].tgt);
break;
default:
break;
}
}
}
fprintf(stdout, "\n");
}
int
cfg_file_set_param(char *par, struct config *cfg, int len)
{
int i;
for (i = 0; i < len; i++) {
if (strncasecmp(par, cfg[i].key, strlen(cfg[i].key)) == 0 &&
strlen(par) == strlen(cfg[i].key)) {
par = strtok(NULL, "\t =\n\r");
switch (cfg[i].type) {
case STR:
if (strlen(cfg[i].tgt) == 0)
strncpy(cfg[i].tgt , par, strlen(par));
break;
case BOL:
if (*(int *) cfg[i].tgt == UNSET) {
if (strncasecmp(par, "NO", 2) == 0)
*(int *) cfg[i].tgt = NO;
else if (strncasecmp(par, "YES", 3) == 0)
*(int *) cfg[i].tgt = YES;
else
*(int *) cfg[i].tgt = UNSET;
}
break;
case NUM:
if (*(int *) cfg[i].tgt == UNSET)
*(int *) cfg[i].tgt = atoi(par);
break;
default:
break;
}
return 1;
}
}
return 0;
}
int
cfg_file_read(const char *file, struct config *cfg, int len)
{
int ret;
char line[CFG_LINELEN];
char *par, *tmp;
FILE *fp = NULL;
/* open config file */
fp = fopen(file, "r");
/* try local configuration file */
if (fp == NULL) {
fprintf(stdout, "configuration file %s not found.\n", file);
tmp = strrchr(file, '/');
tmp++;
/* open config file */
fp = fopen(tmp, "r");
err_ret_if(fp == NULL, -1);
fprintf(stdout, "local configuration file %s used.\n", tmp);
}
/* read each line and set parameter */
while (fgets(line, CFG_LINELEN, fp) != NULL ) {
par = strtok(line, "\t =\n\r") ;
if (par != NULL && par[0] != '#')
ret = cfg_file_set_param(par, cfg, len);
}
/* close config file */
ret = fclose(fp);
err_ret_if(ret == EOF, -1);
return 0;
}
int
pid_file_open(const char *file, int *fd)
{
int ret;
char pid[10];
*fd = open(file, O_RDWR|O_CREAT, 0600);
err_ret_if(*fd < 0, -1);
ret = lockf(*fd, F_TLOCK, 0);
err_ret_if(ret < 0, -1);
sprintf(pid, "%d\n", getpid());
ret = write(*fd, pid, strlen(pid));
err_ret_if(ret < 0, -1);
return 0;
}
int
pid_file_close(const char *file, int fd)
{
int ret;
ret = close(fd);
err_ret_if(ret < 0, -1);
ret = unlink(file);
err_ret_if(ret < 0, -1);
return 0;
}
int
sock_open(int *fd, int port, int localhost)
{
int ret, opt;
struct sockaddr_in sock;
*fd = socket(PF_INET, SOCK_STREAM, 0);
err_ret_if(fd < 0, -1);
/* todo: verify if this realy work */
/* prevent "Error Address already in use" error message */
opt = 1;
ret = setsockopt(*fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(int));
err_ret_if(ret < 0, -1);
memset((char *) &sock, 0, sizeof(sock));
sock.sin_family = AF_INET;
if (localhost == YES)
sock.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
else
sock.sin_addr.s_addr = htonl(INADDR_ANY);
sock.sin_port = htons(port);
ret = bind(*fd, (struct sockaddr *) &sock, sizeof(sock));
err_ret_if(ret < 0, -1);
ret = listen(*fd, 5);
err_ret_if(ret < 0, -1);
return 0;
}
int
sock_close(int fd)
{
int ret;
ret = close(fd);
err_ret_if(ret < 0, -1);
return 0;
}
int
sock_client_accept(int listenfd, int *datafd)
{
struct sockaddr_in sock;
socklen_t socklen;
socklen = sizeof(sock);
*datafd = accept(listenfd, (struct sockaddr *) &sock, &socklen);
err_ret_if(*datafd < 0, -1);
log_print(L_DBG, "client [%d] from %s connected.",
*datafd, inet_ntoa(sock.sin_addr));
return 0;
}
int
sock_client_read(int fd, char *buf, int *buflen)
{
*buflen = read(fd, buf, *buflen);
err_ret_if(*buflen < 0, -1);
if (strncasecmp("quit", buf , 4) == 0 || *buflen <= 0) {
/* close tcp connection */
log_print(L_DBG, "client [%d] disconnected.", fd);
sock_close(fd);
return -1;
}
if (strchr(buf, '\n') != NULL) {
buf[strcspn(buf, "\n")] = '\0';
*buflen -= 1;
}
log_print(L_NET, ">>> client [%d] %s", fd, buf);
return 0;
}
int
sock_client_write(int fd, char *buf, int buflen)
{
int ret;
/* add <cr> to each line */
buf[buflen] = '\r';
buflen++;
ret = write(fd, buf, buflen);
err_ret_if(ret < 0, -1);
buf[strcspn(buf,"\n")] = '\0';
log_print(L_NET, "<<< client [%d] %s", fd, buf);
return 0;
}
+70
View File
@@ -0,0 +1,70 @@
/*
* Copyright (C) Roland Jax 2012-2013 <roland.jax@liwest.at>
*
* This file is part of ebusd.
*
* ebusd is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ebusd is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with ebusd. If not, see http://www.gnu.org/licenses/.
*/
#ifndef UTILS_H_
#define UTILS_H_
#define NUMSTR2(s) #s
#define NUMSTR(s) NUMSTR2(s)
#define CFG_LINELEN 256
#define SOCKET_PORT 8888
#define SOCKET_BUFSIZE 1024
#define MSG_QUEUE_MSG_SIZE 256
enum enum_config {STR, BOL, NUM};
struct config {
char *key;
int type;
void *tgt;
char *info;
};
struct msg_queue {
int id;
char data[MSG_QUEUE_MSG_SIZE + 1];
int clientfd;
struct msg_queue *prev;
};
int msg_queue_entries(void);
int msg_queue_init(void);
void msg_queue_free(void);
void msg_queue_put(struct msg_queue *msg);
void msg_queue_get(void);
void msg_queue_msg_add(int id, char *data, int clientfd);
void msg_queue_msg_del(int *id, char *data, int *clientfd);
void cfg_print(struct config *cfg, int len);
int cfg_file_set_param(char *param, struct config *cfg, int len);
int cfg_file_read(const char *file, struct config *cfg, int len);
int pid_file_open(const char *file, int *fd);
int pid_file_close(const char *file, int fd);
int sock_open(int *fd, int port, int localhost);
int sock_close(int fd);
int sock_client_accept(int listenfd, int *datafd);
int sock_client_read(int fd, char *buf, int *buflen);
int sock_client_write(int fd, char *buf, int buflen);
#endif /* UTILS_H_ */