2 * slcand.c - userspace daemon for serial line CAN interface driver SLCAN
4 * Copyright (c) 2009 Robert Haddon <robert.haddon@verari.com>
5 * Copyright (c) 2009 Verari Systems Inc.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 * This code is derived from an example daemon code from
23 * http://en.wikipedia.org/wiki/Daemon_(computer_software)#Sample_Program_in_C_on_Linux
24 * (accessed 2009-05-05)
26 * So it is additionally licensed under the GNU Free Documentation License:
28 * Permission is granted to copy, distribute and/or modify this document
29 * under the terms of the GNU Free Documentation License, Version 1.2
30 * or any later version published by the Free Software Foundation;
31 * with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
32 * A copy of the license is included in the section entitled "GNU
33 * Free Documentation License".
35 * Send feedback to <linux-can@vger.kernel.org>
43 #include <sys/types.h>
50 #include <sys/ioctl.h>
54 /* default slcan line discipline since Kernel 2.6.25 */
55 #define LDISC_N_SLCAN 17
57 /* Change this to whatever your daemon is called */
58 #define DAEMON_NAME "slcand"
60 /* Change this to the user under which to run */
61 #define RUN_AS_USER "root"
63 /* The length of ttypath buffer */
64 #define TTYPATH_LENGTH 64
66 /* The length of pidfile name buffer */
67 #define PIDFILE_LENGTH 64
69 #define EXIT_SUCCESS 0
70 #define EXIT_FAILURE 1
72 void print_usage(char *prg)
74 fprintf(stderr, "\nUsage: %s [options] <tty> [canif-name]\n\n", prg);
75 fprintf(stderr, "Options: -o (send open command 'O\\r')\n");
76 fprintf(stderr, " -c (send close command 'C\\r')\n");
77 fprintf(stderr, " -f (read status flags with 'F\\r' to reset error states)\n");
78 fprintf(stderr, " -s <speed> (set CAN speed 0..8)\n");
79 fprintf(stderr, " -S <speed> (set UART speed in baud)\n");
80 fprintf(stderr, " -b <btr> (set bit time register value)\n");
81 fprintf(stderr, " -F (stay in foreground; no daemonize)\n");
82 fprintf(stderr, " -h (show this help page)\n");
83 fprintf(stderr, "\nExamples:\n");
84 fprintf(stderr, "slcand -o -c -f -s6 ttyslcan0\n");
85 fprintf(stderr, "slcand -o -c -f -s6 ttyslcan0 can0\n");
86 fprintf(stderr, "\n");
90 static int slcand_running;
92 static char ttypath[TTYPATH_LENGTH];
93 static char pidfile[PIDFILE_LENGTH];
95 static void child_handler(int signum)
105 syslog(LOG_NOTICE, "received signal %i on %s", signum, ttypath);
106 exit_code = EXIT_FAILURE;
111 syslog(LOG_NOTICE, "received signal %i on %s", signum, ttypath);
112 exit_code = EXIT_SUCCESS;
118 static int look_up_uart_speed(long int s)
175 static pid_t daemonize(const char *lockfile, char *tty, char *name)
177 pid_t pid, sid, parent;
181 char const *pidprefix = "/var/run/";
182 char const *pidsuffix = ".pid";
184 snprintf(pidfile, PIDFILE_LENGTH, "%s%s-%s%s", pidprefix, DAEMON_NAME, tty, pidsuffix);
186 /* already a daemon */
190 /* Create the lock file as the current user */
191 if (lockfile && lockfile[0]) {
193 lfp = open(lockfile, O_RDWR | O_CREAT, 0640);
196 syslog(LOG_ERR, "unable to create lock file %s, code=%d (%s)",
197 lockfile, errno, strerror(errno));
202 /* Drop user if there is one, and we were run as root */
203 if (getuid() == 0 || geteuid() == 0) {
204 struct passwd *pw = getpwnam(RUN_AS_USER);
208 /* syslog(LOG_NOTICE, "setting user to " RUN_AS_USER); */
213 /* Trap signals that we expect to receive */
214 signal(SIGINT, child_handler);
215 signal(SIGTERM, child_handler);
216 signal(SIGCHLD, child_handler);
217 signal(SIGUSR1, child_handler);
218 signal(SIGALRM, child_handler);
220 /* Fork off the parent process */
223 syslog(LOG_ERR, "unable to fork daemon, code=%d (%s)",
224 errno, strerror(errno));
228 /* If we got a good PID, then we can exit the parent process. */
230 /* Wait for confirmation from the child via SIGTERM or SIGCHLD, or
231 for five seconds to elapse (SIGALRM). pause() should not return. */
237 /* At this point we are executing as the child process */
240 /* Cancel certain signals */
241 signal(SIGCHLD, SIG_DFL); /* A child process dies */
242 signal(SIGTSTP, SIG_IGN); /* Various TTY signals */
243 signal(SIGTTOU, SIG_IGN);
244 signal(SIGTTIN, SIG_IGN);
245 signal(SIGHUP, SIG_IGN); /* Ignore hangup signal */
246 signal(SIGINT, child_handler);
247 signal(SIGTERM, child_handler);
249 /* Change the file mode mask */
252 /* Create a new SID for the child process */
255 syslog(LOG_ERR, "unable to create a new session, code %d (%s)",
256 errno, strerror(errno));
260 pFile = fopen(pidfile, "w");
262 syslog(LOG_ERR, "unable to create pid file %s, code=%d (%s)",
263 pidfile, errno, strerror(errno));
266 fprintf(pFile, "%d\n", sid);
269 /* Change the current working directory. This prevents the current
270 directory from being locked; hence not being able to remove it. */
271 if (chdir("/") < 0) {
272 syslog(LOG_ERR, "unable to change directory to %s, code %d (%s)",
273 "/", errno, strerror(errno));
277 /* Redirect standard files to /dev/null */
278 dummyFile = freopen("/dev/null", "r", stdin);
279 dummyFile = freopen("/dev/null", "w", stdout);
280 dummyFile = freopen("/dev/null", "w", stderr);
282 /* Tell the parent process that we are A-okay */
283 /* kill(parent, SIGUSR1); */
287 int main(int argc, char *argv[])
290 char const *devprefix = "/dev/";
292 char buf[IFNAMSIZ+1];
300 int send_read_status_flags = 0;
302 char *uart_speed_str = NULL;
303 long int uart_speed = 0;
305 int run_as_daemon = 1;
306 pid_t parent_pid = 0;
308 int ldisc = LDISC_N_SLCAN;
313 while ((opt = getopt(argc, argv, "ocfs:S:b:?hF")) != -1) {
322 send_read_status_flags = 1;
326 if (strlen(speed) > 1)
327 print_usage(argv[0]);
330 uart_speed_str = optarg;
332 uart_speed = strtol(uart_speed_str, NULL, 10);
334 print_usage(argv[0]);
335 if (look_up_uart_speed(uart_speed) == -1) {
336 fprintf(stderr, "Unsupported UART speed (%lu)\n", uart_speed);
343 print_usage(argv[0]);
351 print_usage(argv[0]);
356 /* Initialize the logging interface */
357 openlog(DAEMON_NAME, LOG_PID, LOG_LOCAL5);
359 /* Parse serial device name and optional can interface name */
362 print_usage(argv[0]);
364 name = argv[optind + 1];
366 /* Prepare the tty device name string */
367 pch = strstr(tty, devprefix);
369 print_usage(argv[0]);
371 snprintf(ttypath, TTYPATH_LENGTH, "%s%s", devprefix, tty);
372 syslog(LOG_INFO, "starting on TTY device %s", ttypath);
376 parent_pid = daemonize("/var/lock/" DAEMON_NAME, tty, name);
378 /* Trap signals that we expect to receive */
379 signal(SIGINT, child_handler);
380 signal(SIGTERM, child_handler);
386 /* Now we are a daemon -- do the work for which we were paid */
387 fd = open(ttypath, O_RDWR | O_NONBLOCK | O_NOCTTY);
389 syslog(LOG_NOTICE, "failed to open TTY device %s\n", ttypath);
394 /* Configure baud rate */
395 memset(&tios, 0, sizeof(struct termios));
396 if (tcgetattr(fd, &tios) < 0) {
397 syslog(LOG_NOTICE, "failed to get attributes for TTY device %s: %s\n", ttypath, strerror(errno));
401 /* Get old values for later restore */
402 old_ispeed = cfgetispeed(&tios);
403 old_ospeed = cfgetospeed(&tios);
406 cfsetispeed(&tios, look_up_uart_speed(uart_speed));
407 cfsetospeed(&tios, look_up_uart_speed(uart_speed));
410 if (tcsetattr(fd, TCSADRAIN, &tios) < 0)
411 syslog(LOG_NOTICE, "Cannot set attributes for device \"%s\": %s!\n", ttypath, strerror(errno));
414 sprintf(buf, "C\rS%s\r", speed);
415 write(fd, buf, strlen(buf));
419 sprintf(buf, "C\rs%s\r", btr);
420 write(fd, buf, strlen(buf));
423 if (send_read_status_flags) {
425 write(fd, buf, strlen(buf));
430 write(fd, buf, strlen(buf));
433 /* set slcan like discipline on given tty */
434 if (ioctl(fd, TIOCSETD, &ldisc) < 0) {
435 perror("ioctl TIOCSETD");
439 /* retrieve the name of the created CAN netdevice */
440 if (ioctl(fd, SIOCGIFNAME, buf) < 0) {
441 perror("ioctl SIOCGIFNAME");
445 syslog(LOG_NOTICE, "attached TTY %s to netdevice %s\n", ttypath, buf);
447 /* try to rename the created netdevice */
450 int s = socket(PF_INET, SOCK_DGRAM, 0);
453 perror("socket for interface rename");
455 strncpy(ifr.ifr_name, buf, IFNAMSIZ);
456 strncpy(ifr.ifr_newname, name, IFNAMSIZ);
458 if (ioctl(s, SIOCSIFNAME, &ifr) < 0) {
459 syslog(LOG_NOTICE, "netdevice %s rename to %s failed\n", buf, name);
460 perror("ioctl SIOCSIFNAME rename");
463 syslog(LOG_NOTICE, "netdevice %s renamed to %s\n", buf, name);
469 kill(parent_pid, SIGUSR1);
472 while (slcand_running)
473 sleep(1); /* wait 1 second */
475 /* Reset line discipline */
476 syslog(LOG_INFO, "stopping on TTY device %s", ttypath);
478 if (ioctl(fd, TIOCSETD, &ldisc) < 0) {
479 perror("ioctl TIOCSETD");
485 write(fd, buf, strlen(buf));
488 /* Reset old rates */
489 cfsetispeed(&tios, old_ispeed);
490 cfsetospeed(&tios, old_ospeed);
493 if (tcsetattr(fd, TCSADRAIN, &tios) < 0)
494 syslog(LOG_NOTICE, "Cannot set attributes for device \"%s\": %s!\n", ttypath, strerror(errno));
501 syslog(LOG_NOTICE, "terminated on %s", ttypath);