]> rtime.felk.cvut.cz Git - can-utils.git/blob - slcand.c
can-calc-bit-timing: fix MCP251x bit rate calculation
[can-utils.git] / slcand.c
1 /*
2  * slcand.c - userspace daemon for serial line CAN interface driver SLCAN
3  *
4  * Copyright (c) 2009 Robert Haddon <robert.haddon@verari.com>
5  * Copyright (c) 2009 Verari Systems Inc.
6  *
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.
11  *
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.
16  *
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
20  *
21  * This code is derived from an example daemon code from
22  *
23  * http://en.wikipedia.org/wiki/Daemon_(computer_software)#Sample_Program_in_C_on_Linux
24  * (accessed 2009-05-05)
25  *
26  * So it is additionally licensed under the GNU Free Documentation License:
27  *
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".
34  *
35  * Send feedback to <linux-can@vger.kernel.org>
36  *
37  */
38
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <unistd.h>
43 #include <sys/types.h>
44 #include <sys/stat.h>
45 #include <fcntl.h>
46 #include <syslog.h>
47 #include <errno.h>
48 #include <pwd.h>
49 #include <signal.h>
50 #include <sys/ioctl.h>
51 #include <net/if.h>
52 #include <termios.h>
53
54 /* default slcan line discipline since Kernel 2.6.25 */
55 #define LDISC_N_SLCAN 17
56
57 /* Change this to whatever your daemon is called */
58 #define DAEMON_NAME "slcand"
59
60 /* Change this to the user under which to run */
61 #define RUN_AS_USER "root"
62
63 /* The length of ttypath buffer */
64 #define TTYPATH_LENGTH  64
65
66 /* The length of pidfile name buffer */
67 #define PIDFILE_LENGTH  64
68
69 #define EXIT_SUCCESS 0
70 #define EXIT_FAILURE 1
71
72 void print_usage(char *prg)
73 {
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");
87         exit(EXIT_FAILURE);
88 }
89
90 static int slcand_running;
91 static int exit_code;
92 static char ttypath[TTYPATH_LENGTH];
93 static char pidfile[PIDFILE_LENGTH];
94
95 static void child_handler(int signum)
96 {
97         switch (signum) {
98
99         case SIGUSR1:
100                 /* exit parent */
101                 exit(EXIT_SUCCESS);
102                 break;
103         case SIGALRM:
104         case SIGCHLD:
105                 syslog(LOG_NOTICE, "received signal %i on %s", signum, ttypath);
106                 exit_code = EXIT_FAILURE;
107                 slcand_running = 0;
108                 break;
109         case SIGINT:
110         case SIGTERM:
111                 syslog(LOG_NOTICE, "received signal %i on %s", signum, ttypath);
112                 exit_code = EXIT_SUCCESS;
113                 slcand_running = 0;
114                 break;
115         }
116 }
117
118 static int look_up_uart_speed(long int s)
119 {
120         switch (s) {
121
122         case 9600:
123                 return B9600;
124         case 19200:
125                 return B19200;
126         case 38400:
127                 return B38400;
128         case 57600:
129                 return B57600;
130         case 115200:
131                 return B115200;
132         case 230400:
133                 return B230400;
134         case 460800:
135                 return B460800;
136         case 500000:
137                 return B500000;
138         case 576000:
139                 return B576000;
140         case 921600:
141                 return B921600;
142         case 1000000:
143                 return B1000000;
144         case 1152000:
145                 return B1152000;
146         case 1500000:
147                 return B1500000;
148         case 2000000:
149                 return B2000000;
150 #ifdef B2500000
151         case 2500000:
152                 return B2500000;
153 #endif
154 #ifdef B3000000
155         case 3000000:
156                 return B3000000;
157 #endif
158 #ifdef B3500000
159         case 3500000:
160                 return B3500000;
161 #endif
162 #ifdef B3710000
163         case 3710000
164                 return B3710000;
165 #endif
166 #ifdef B4000000
167         case 4000000:
168                 return B4000000;
169 #endif
170         default:
171                 return -1;
172         }
173 }
174
175 static pid_t daemonize(const char *lockfile, char *tty, char *name)
176 {
177         pid_t pid, sid, parent;
178         int lfp = -1;
179         FILE *pFile;
180         char const *pidprefix = "/var/run/";
181         char const *pidsuffix = ".pid";
182
183         snprintf(pidfile, PIDFILE_LENGTH, "%s%s-%s%s", pidprefix, DAEMON_NAME, tty, pidsuffix);
184
185         /* already a daemon */
186         if (getppid() == 1)
187                 return 0;
188
189         /* Create the lock file as the current user */
190         if (lockfile && lockfile[0]) {
191
192                 lfp = open(lockfile, O_RDWR | O_CREAT, 0640);
193                 if (lfp < 0)
194                 {
195                         syslog(LOG_ERR, "unable to create lock file %s, code=%d (%s)",
196                                lockfile, errno, strerror(errno));
197                         exit(EXIT_FAILURE);
198                 }
199         }
200
201         /* Drop user if there is one, and we were run as root */
202         if (getuid() == 0 || geteuid() == 0) {
203                 struct passwd *pw = getpwnam(RUN_AS_USER);
204
205                 if (pw)
206                 {
207                         /* syslog(LOG_NOTICE, "setting user to " RUN_AS_USER); */
208                         setuid(pw->pw_uid);
209                 }
210         }
211
212         /* Trap signals that we expect to receive */
213         signal(SIGINT, child_handler);
214         signal(SIGTERM, child_handler);
215         signal(SIGCHLD, child_handler);
216         signal(SIGUSR1, child_handler);
217         signal(SIGALRM, child_handler);
218
219         /* Fork off the parent process */
220         pid = fork();
221         if (pid < 0) {
222                 syslog(LOG_ERR, "unable to fork daemon, code=%d (%s)",
223                        errno, strerror(errno));
224                 exit(EXIT_FAILURE);
225         }
226
227         /* If we got a good PID, then we can exit the parent process. */
228         if (pid > 0) {
229                 /* Wait for confirmation from the child via SIGTERM or SIGCHLD, or
230                    for five seconds to elapse (SIGALRM).  pause() should not return. */
231                 alarm(5);
232                 pause();
233                 exit(EXIT_FAILURE);
234         }
235
236         /* At this point we are executing as the child process */
237         parent = getppid();
238
239         /* Cancel certain signals */
240         signal(SIGCHLD, SIG_DFL);       /* A child process dies */
241         signal(SIGTSTP, SIG_IGN);       /* Various TTY signals */
242         signal(SIGTTOU, SIG_IGN);
243         signal(SIGTTIN, SIG_IGN);
244         signal(SIGHUP, SIG_IGN);        /* Ignore hangup signal */
245         signal(SIGINT, child_handler);
246         signal(SIGTERM, child_handler);
247
248         /* Change the file mode mask */
249         umask(0);
250
251         /* Create a new SID for the child process */
252         sid = setsid();
253         if (sid < 0) {
254                 syslog(LOG_ERR, "unable to create a new session, code %d (%s)",
255                        errno, strerror(errno));
256                 exit(EXIT_FAILURE);
257         }
258
259         pFile = fopen(pidfile, "w");
260         if (NULL == pFile) {
261                 syslog(LOG_ERR, "unable to create pid file %s, code=%d (%s)",
262                        pidfile, errno, strerror(errno));
263                 exit(EXIT_FAILURE);
264         }
265         fprintf(pFile, "%d\n", sid);
266         fclose(pFile);
267
268         /* Change the current working directory.  This prevents the current
269            directory from being locked; hence not being able to remove it. */
270         if (chdir("/") < 0) {
271                 syslog(LOG_ERR, "unable to change directory to %s, code %d (%s)",
272                        "/", errno, strerror(errno));
273                 exit(EXIT_FAILURE);
274         }
275
276         /* Redirect standard files to /dev/null */
277         pFile = freopen("/dev/null", "r", stdin);
278         pFile = freopen("/dev/null", "w", stdout);
279         pFile = freopen("/dev/null", "w", stderr);
280
281         /* Tell the parent process that we are A-okay */
282         /* kill(parent, SIGUSR1); */
283         return parent;
284 }
285
286 int main(int argc, char *argv[])
287 {
288         char *tty = NULL;
289         char const *devprefix = "/dev/";
290         char *name = NULL;
291         char buf[IFNAMSIZ+1];
292         struct termios tios;
293         speed_t old_ispeed;
294         speed_t old_ospeed;
295
296         int opt;
297         int send_open = 0;
298         int send_close = 0;
299         int send_read_status_flags = 0;
300         char *speed = NULL;
301         char *uart_speed_str = NULL;
302         long int uart_speed = 0;
303         char *btr = NULL;
304         int run_as_daemon = 1;
305         pid_t parent_pid = 0;
306         char *pch;
307         int ldisc = LDISC_N_SLCAN;
308         int fd;
309
310         ttypath[0] = '\0';
311
312         while ((opt = getopt(argc, argv, "ocfs:S:b:?hF")) != -1) {
313                 switch (opt) {
314                 case 'o':
315                         send_open = 1;
316                         break;
317                 case 'c':
318                         send_close = 1;
319                         break;
320                 case 'f':
321                         send_read_status_flags = 1;
322                         break;
323                 case 's':
324                         speed = optarg;
325                         if (strlen(speed) > 1)
326                                 print_usage(argv[0]);
327                         break;
328                 case 'S':
329                         uart_speed_str = optarg;
330                         errno = 0;
331                         uart_speed = strtol(uart_speed_str, NULL, 10);
332                         if (errno)
333                                 print_usage(argv[0]);
334                         if (look_up_uart_speed(uart_speed) == -1) {
335                                 fprintf(stderr, "Unsupported UART speed (%lu)\n", uart_speed);
336                                 exit(EXIT_FAILURE);
337                         }
338                         break;
339                 case 'b':
340                         btr = optarg;
341                         if (strlen(btr) > 6)
342                                 print_usage(argv[0]);
343                         break;
344                 case 'F':
345                         run_as_daemon = 0;
346                         break;
347                 case 'h':
348                 case '?':
349                 default:
350                         print_usage(argv[0]);
351                         break;
352                 }
353         }
354
355         /* Initialize the logging interface */
356         openlog(DAEMON_NAME, LOG_PID, LOG_LOCAL5);
357
358         /* Parse serial device name and optional can interface name */
359         tty = argv[optind];
360         if (NULL == tty)
361                 print_usage(argv[0]);
362
363         name = argv[optind + 1];
364
365         /* Prepare the tty device name string */
366         pch = strstr(tty, devprefix);
367         if (pch == tty)
368                 print_usage(argv[0]);
369
370         snprintf(ttypath, TTYPATH_LENGTH, "%s%s", devprefix, tty);
371         syslog(LOG_INFO, "starting on TTY device %s", ttypath);
372
373         /* Daemonize */
374         if (run_as_daemon)
375                 parent_pid = daemonize("/var/lock/" DAEMON_NAME, tty, name);
376         else {
377                 /* Trap signals that we expect to receive */
378                 signal(SIGINT, child_handler);
379                 signal(SIGTERM, child_handler);
380         }
381
382         /* */
383         slcand_running = 1;
384
385         /* Now we are a daemon -- do the work for which we were paid */
386         fd = open(ttypath, O_RDWR | O_NONBLOCK | O_NOCTTY);
387         if (fd < 0) {
388                 syslog(LOG_NOTICE, "failed to open TTY device %s\n", ttypath);
389                 perror(ttypath);
390                 exit(EXIT_FAILURE);
391         }
392
393         /* Configure baud rate */
394         memset(&tios, 0, sizeof(struct termios));
395         if (tcgetattr(fd, &tios) < 0) {
396                 syslog(LOG_NOTICE, "failed to get attributes for TTY device %s: %s\n", ttypath, strerror(errno));
397                 exit(EXIT_FAILURE);
398         }
399
400         /* Get old values for later restore */
401         old_ispeed = cfgetispeed(&tios);
402         old_ospeed = cfgetospeed(&tios);
403
404         /* Baud Rate */
405         cfsetispeed(&tios, look_up_uart_speed(uart_speed));
406         cfsetospeed(&tios, look_up_uart_speed(uart_speed));
407
408         /* apply changes */
409         if (tcsetattr(fd, TCSADRAIN, &tios) < 0)
410                 syslog(LOG_NOTICE, "Cannot set attributes for device \"%s\": %s!\n", ttypath, strerror(errno));
411
412         if (speed) {
413                 sprintf(buf, "C\rS%s\r", speed);
414                 write(fd, buf, strlen(buf));
415         }
416
417         if (btr) {
418                 sprintf(buf, "C\rs%s\r", btr);
419                 write(fd, buf, strlen(buf));
420         }
421
422         if (send_read_status_flags) {
423                 sprintf(buf, "F\r");
424                 write(fd, buf, strlen(buf));
425         }
426
427         if (send_open) {
428                 sprintf(buf, "O\r");
429                 write(fd, buf, strlen(buf));
430         }
431
432         /* set slcan like discipline on given tty */
433         if (ioctl(fd, TIOCSETD, &ldisc) < 0) {
434                 perror("ioctl TIOCSETD");
435                 exit(1);
436         }
437         
438         /* retrieve the name of the created CAN netdevice */
439         if (ioctl(fd, SIOCGIFNAME, buf) < 0) {
440                 perror("ioctl SIOCGIFNAME");
441                 exit(1);
442         }
443
444         syslog(LOG_NOTICE, "attached TTY %s to netdevice %s\n", ttypath, buf);
445         
446         /* try to rename the created netdevice */
447         if (name) {
448                 struct ifreq ifr;
449                 int s = socket(PF_INET, SOCK_DGRAM, 0);
450
451                 if (s < 0)
452                         perror("socket for interface rename");
453                 else {
454                         strncpy(ifr.ifr_name, buf, IFNAMSIZ);
455                         strncpy(ifr.ifr_newname, name, IFNAMSIZ);
456
457                         if (ioctl(s, SIOCSIFNAME, &ifr) < 0) {
458                                 syslog(LOG_NOTICE, "netdevice %s rename to %s failed\n", buf, name);
459                                 perror("ioctl SIOCSIFNAME rename");
460                                 exit(1);
461                         } else
462                                 syslog(LOG_NOTICE, "netdevice %s renamed to %s\n", buf, name);
463
464                         close(s);
465                 }       
466         }
467         if (parent_pid > 0)
468                 kill(parent_pid, SIGUSR1);
469
470         /* The Big Loop */
471         while (slcand_running)
472                 sleep(1); /* wait 1 second */
473
474         /* Reset line discipline */
475         syslog(LOG_INFO, "stopping on TTY device %s", ttypath);
476         ldisc = N_TTY;
477         if (ioctl(fd, TIOCSETD, &ldisc) < 0) {
478                 perror("ioctl TIOCSETD");
479                 exit(EXIT_FAILURE);
480         }
481
482         if (send_close) {
483                 sprintf(buf, "C\r");
484                 write(fd, buf, strlen(buf));
485         }
486
487         /* Reset old rates */
488         cfsetispeed(&tios, old_ispeed);
489         cfsetospeed(&tios, old_ospeed);
490
491         /* apply changes */
492         if (tcsetattr(fd, TCSADRAIN, &tios) < 0)
493                 syslog(LOG_NOTICE, "Cannot set attributes for device \"%s\": %s!\n", ttypath, strerror(errno));
494
495         /* Remove pidfile */
496         if (run_as_daemon)
497                 unlink(pidfile);
498
499         /* Finish up */
500         syslog(LOG_NOTICE, "terminated on %s", ttypath);
501         closelog();
502         return exit_code;
503 }