]> rtime.felk.cvut.cz Git - sojka/can-utils.git/blob - slcand.c
cangen: Added '-n <count>' commandline option analogue to candump tool.
[sojka/can-utils.git] / slcand.c
1 /*
2  *  $Id$
3  */
4
5 /*
6  * slcand.c - userspace daemon for serial line CAN interface driver SLCAN
7  *
8  * Copyright (c) 2009 Robert Haddon <robert.haddon@verari.com>
9  * Copyright (c) 2009 Verari Systems Inc.
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
24  *
25  * This code is derived from an example daemon code from
26  *
27  * http://en.wikipedia.org/wiki/Daemon_(computer_software)#Sample_Program_in_C_on_Linux
28  * (accessed 2009-05-05)
29  *
30  * So it is additionally licensed under the GNU Free Documentation License:
31  *
32  * Permission is granted to copy, distribute and/or modify this document
33  * under the terms of the GNU Free Documentation License, Version 1.2
34  * or any later version published by the Free Software Foundation;
35  * with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
36  * A copy of the license is included in the section entitled "GNU
37  * Free Documentation License".
38  *
39  * Send feedback to <socketcan-users@lists.berlios.de>
40  *
41  */
42
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <unistd.h>
47 #include <sys/types.h>
48 #include <sys/stat.h>
49 #include <fcntl.h>
50 #include <syslog.h>
51 #include <errno.h>
52 #include <pwd.h>
53 #include <signal.h>
54 #include <sys/ioctl.h>
55 #include <net/if.h>
56
57 /* default slcan line discipline since Kernel 2.6.25 */
58 #define LDISC_N_SLCAN 17
59
60 /* Change this to whatever your daemon is called */
61 #define DAEMON_NAME "slcand"
62
63 /* Change this to the user under which to run */
64 #define RUN_AS_USER "root"
65
66 #define EXIT_SUCCESS 0
67 #define EXIT_FAILURE 1
68
69 void print_usage(char *prg)
70 {
71         fprintf(stderr, "\nUsage: %s tty [name]\n\n", prg);
72         fprintf(stderr, "Example:\n");
73         fprintf(stderr, "%s ttyUSB1\n", prg);
74         fprintf(stderr, "%s ttyS0 can0\n", prg);
75         fprintf(stderr, "\n");
76         exit(EXIT_FAILURE);
77 }
78
79 static void child_handler (int signum)
80 {
81         switch (signum)
82         {
83         case SIGALRM:
84                 exit (EXIT_FAILURE);
85                 break;
86         case SIGUSR1:
87                 exit (EXIT_SUCCESS);
88                 break;
89         case SIGCHLD:
90                 exit (EXIT_FAILURE);
91                 break;
92         }
93 }
94
95 static void daemonize (const char *lockfile, char *tty, char *name)
96 {
97         pid_t pid, sid, parent;
98         int lfp = -1;
99         FILE * pFile;
100         char const *pidprefix = "/var/run/";
101         char const *pidsuffix = ".pid";
102         char *pidfile;
103         pidfile = malloc((strlen(pidprefix) +strlen(DAEMON_NAME) + strlen(tty) + strlen(pidsuffix) + 1) * sizeof(char));
104         sprintf(pidfile, "%s%s-%s%s", pidprefix, DAEMON_NAME, tty, pidsuffix);
105
106         /* already a daemon */
107         if (getppid () == 1)
108                 return;
109
110         /* Create the lock file as the current user */
111         if (lockfile && lockfile[0])
112         {
113                 lfp = open (lockfile, O_RDWR | O_CREAT, 0640);
114                 if (lfp < 0)
115                 {
116                         syslog (LOG_ERR, "unable to create lock file %s, code=%d (%s)",
117                                 lockfile, errno, strerror (errno));
118                         exit (EXIT_FAILURE);
119                 }
120         }
121
122         /* Drop user if there is one, and we were run as root */
123         if (getuid () == 0 || geteuid () == 0)
124         {
125                 struct passwd *pw = getpwnam (RUN_AS_USER);
126                 if (pw)
127                 {
128                         //syslog (LOG_NOTICE, "setting user to " RUN_AS_USER);
129                         setuid (pw->pw_uid);
130                 }
131         }
132
133         /* Trap signals that we expect to receive */
134         signal (SIGCHLD, child_handler);
135         signal (SIGUSR1, child_handler);
136         signal (SIGALRM, child_handler);
137
138         /* Fork off the parent process */
139         pid = fork ();
140         if (pid < 0)
141         {
142                 syslog (LOG_ERR, "unable to fork daemon, code=%d (%s)",
143                         errno, strerror (errno));
144                 exit (EXIT_FAILURE);
145         }
146         /* If we got a good PID, then we can exit the parent process. */
147         if (pid > 0)
148         {
149
150                 /* Wait for confirmation from the child via SIGTERM or SIGCHLD, or
151                    for two seconds to elapse (SIGALRM).  pause() should not return. */
152                 alarm (2);
153                 pause ();
154
155                 exit (EXIT_FAILURE);
156         }
157
158         /* At this point we are executing as the child process */
159         parent = getppid ();
160
161         /* Cancel certain signals */
162         signal (SIGCHLD, SIG_DFL);      /* A child process dies */
163         signal (SIGTSTP, SIG_IGN);      /* Various TTY signals */
164         signal (SIGTTOU, SIG_IGN);
165         signal (SIGTTIN, SIG_IGN);
166         signal (SIGHUP, SIG_IGN);       /* Ignore hangup signal */
167         signal (SIGTERM, SIG_DFL);      /* Die on SIGTERM */
168
169         /* Change the file mode mask */
170         umask (0);
171
172         /* Create a new SID for the child process */
173         sid = setsid ();
174         if (sid < 0)
175         {
176                 syslog (LOG_ERR, "unable to create a new session, code %d (%s)",
177                         errno, strerror (errno));
178                 exit (EXIT_FAILURE);
179         }
180
181         pFile = fopen (pidfile,"w");
182         if (pFile < 0)
183         {
184                 syslog (LOG_ERR, "unable to create pid file %s, code=%d (%s)",
185                         pidfile, errno, strerror (errno));
186                 exit (EXIT_FAILURE);
187         }
188         fprintf (pFile, "%d\n", sid);
189         fclose (pFile);
190
191         /* Change the current working directory.  This prevents the current
192            directory from being locked; hence not being able to remove it. */
193         if ((chdir ("/")) < 0)
194         {
195                 syslog (LOG_ERR, "unable to change directory to %s, code %d (%s)",
196                         "/", errno, strerror (errno));
197                 exit (EXIT_FAILURE);
198         }
199
200         /* Redirect standard files to /dev/null */
201         freopen ("/dev/null", "r", stdin);
202         freopen ("/dev/null", "w", stdout);
203         freopen ("/dev/null", "w", stderr);
204
205         /* Tell the parent process that we are A-okay */
206         kill (parent, SIGUSR1);
207 }
208
209 int main (int argc, char *argv[])
210 {
211         char *tty = NULL;
212         char *ttypath;
213         char const *devprefix = "/dev/";
214         char *name = NULL;
215         char buf[IFNAMSIZ+1];
216
217         /* Initialize the logging interface */
218         openlog (DAEMON_NAME, LOG_PID, LOG_LOCAL5);
219
220         /* See how we're called */
221         if (argc == 2) {
222                 tty = argv[1];
223         } else if (argc == 3) {
224                 tty = argv[1];
225                 name = argv[2];
226                 if (strlen(name) > IFNAMSIZ-1)
227                         print_usage(argv[0]);
228         } else {
229                 print_usage(argv[0]);
230         }
231
232         /* Prepare the tty device name string */
233         char * pch;
234         pch = strstr (tty, devprefix);
235         if (pch == tty) {
236                 print_usage(argv[0]);
237         }
238         ttypath = malloc((strlen(devprefix) + strlen(tty)) * sizeof(char));
239         sprintf (ttypath, "%s%s", devprefix, tty);
240         syslog (LOG_INFO, "starting on TTY device %s", ttypath);
241
242         /* Daemonize */
243         daemonize ("/var/lock/" DAEMON_NAME, tty, name);
244
245         /* Now we are a daemon -- do the work for which we were paid */
246         int fd;
247         int ldisc = LDISC_N_SLCAN;
248
249         if ((fd = open (ttypath, O_WRONLY | O_NOCTTY )) < 0) {
250             syslog (LOG_NOTICE, "failed to open TTY device %s\n", ttypath);
251                 perror(ttypath);
252                 exit(1);
253         }
254
255         /* set slcan like discipline on given tty */
256         if (ioctl (fd, TIOCSETD, &ldisc) < 0) {
257                 perror("ioctl TIOCSETD");
258                 exit(1);
259         }
260         
261         /* retrieve the name of the created CAN netdevice */
262         if (ioctl (fd, SIOCGIFNAME, buf) < 0) {
263                 perror("ioctl SIOCGIFNAME");
264                 exit(1);
265         }
266
267         syslog (LOG_NOTICE, "attached TTY %s to netdevice %s\n", ttypath, buf);
268         
269         /* try to rename the created netdevice */
270         if (name) {
271                 struct ifreq ifr;
272                 int s = socket(PF_INET, SOCK_DGRAM, 0);
273                 if (s < 0)
274                         perror("socket for interface rename");
275                 else {
276                         strncpy (ifr.ifr_name, buf, IFNAMSIZ);
277                         strncpy (ifr.ifr_newname, name, IFNAMSIZ);
278
279                         if (ioctl(s, SIOCSIFNAME, &ifr) < 0) {
280                                 syslog (LOG_NOTICE, "netdevice %s rename to %s failed\n", buf, name);
281                                 perror("ioctl SIOCSIFNAME rename");
282                 exit(1);
283                         } else
284                                 syslog (LOG_NOTICE, "netdevice %s renamed to %s\n", buf, name);
285
286                         close(s);
287                 }       
288         }
289
290         /* The Big Loop */
291         while (1) {
292                 sleep(60); /* wait 60 seconds */
293         }
294
295         /* Finish up */
296         syslog (LOG_NOTICE, "terminated on %s", ttypath);
297         closelog ();
298         return 0;
299 }