]> rtime.felk.cvut.cz Git - sojka/can-utils.git/blob - slcand.c
gitignore: added tarballs
[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 /* The length of ttypath buffer */
67 #define TTYPATH_LENGTH  64
68
69 /* The length of pidfile name buffer */
70 #define PIDFILE_LENGTH  64
71
72 #define EXIT_SUCCESS 0
73 #define EXIT_FAILURE 1
74
75 void print_usage(char *prg)
76 {
77         fprintf(stderr, "\nUsage: %s tty [name]\n\n", prg);
78         fprintf(stderr, "Example:\n");
79         fprintf(stderr, "%s ttyUSB1\n", prg);
80         fprintf(stderr, "%s ttyS0 can0\n", prg);
81         fprintf(stderr, "\n");
82         exit(EXIT_FAILURE);
83 }
84
85 static void child_handler (int signum)
86 {
87         switch (signum)
88         {
89         case SIGALRM:
90                 exit (EXIT_FAILURE);
91                 break;
92         case SIGUSR1:
93                 exit (EXIT_SUCCESS);
94                 break;
95         case SIGCHLD:
96                 exit (EXIT_FAILURE);
97                 break;
98         }
99 }
100
101 static void daemonize (const char *lockfile, char *tty, char *name)
102 {
103         pid_t pid, sid, parent;
104         int lfp = -1;
105         FILE * pFile;
106         char const *pidprefix = "/var/run/";
107         char const *pidsuffix = ".pid";
108         char pidfile[PIDFILE_LENGTH];
109
110         snprintf(pidfile, PIDFILE_LENGTH, "%s%s-%s%s", pidprefix, DAEMON_NAME, tty, pidsuffix);
111
112         /* already a daemon */
113         if (getppid () == 1)
114                 return;
115
116         /* Create the lock file as the current user */
117         if (lockfile && lockfile[0])
118         {
119                 lfp = open (lockfile, O_RDWR | O_CREAT, 0640);
120                 if (lfp < 0)
121                 {
122                         syslog (LOG_ERR, "unable to create lock file %s, code=%d (%s)",
123                                 lockfile, errno, strerror (errno));
124                         exit (EXIT_FAILURE);
125                 }
126         }
127
128         /* Drop user if there is one, and we were run as root */
129         if (getuid () == 0 || geteuid () == 0)
130         {
131                 struct passwd *pw = getpwnam (RUN_AS_USER);
132                 if (pw)
133                 {
134                         //syslog (LOG_NOTICE, "setting user to " RUN_AS_USER);
135                         setuid (pw->pw_uid);
136                 }
137         }
138
139         /* Trap signals that we expect to receive */
140         signal (SIGCHLD, child_handler);
141         signal (SIGUSR1, child_handler);
142         signal (SIGALRM, child_handler);
143
144         /* Fork off the parent process */
145         pid = fork ();
146         if (pid < 0)
147         {
148                 syslog (LOG_ERR, "unable to fork daemon, code=%d (%s)",
149                         errno, strerror (errno));
150                 exit (EXIT_FAILURE);
151         }
152         /* If we got a good PID, then we can exit the parent process. */
153         if (pid > 0)
154         {
155
156                 /* Wait for confirmation from the child via SIGTERM or SIGCHLD, or
157                    for two seconds to elapse (SIGALRM).  pause() should not return. */
158                 alarm (2);
159                 pause ();
160
161                 exit (EXIT_FAILURE);
162         }
163
164         /* At this point we are executing as the child process */
165         parent = getppid ();
166
167         /* Cancel certain signals */
168         signal (SIGCHLD, SIG_DFL);      /* A child process dies */
169         signal (SIGTSTP, SIG_IGN);      /* Various TTY signals */
170         signal (SIGTTOU, SIG_IGN);
171         signal (SIGTTIN, SIG_IGN);
172         signal (SIGHUP, SIG_IGN);       /* Ignore hangup signal */
173         signal (SIGTERM, SIG_DFL);      /* Die on SIGTERM */
174
175         /* Change the file mode mask */
176         umask (0);
177
178         /* Create a new SID for the child process */
179         sid = setsid ();
180         if (sid < 0)
181         {
182                 syslog (LOG_ERR, "unable to create a new session, code %d (%s)",
183                         errno, strerror (errno));
184                 exit (EXIT_FAILURE);
185         }
186
187         pFile = fopen (pidfile,"w");
188         if (pFile < 0)
189         {
190                 syslog (LOG_ERR, "unable to create pid file %s, code=%d (%s)",
191                         pidfile, errno, strerror (errno));
192                 exit (EXIT_FAILURE);
193         }
194         fprintf (pFile, "%d\n", sid);
195         fclose (pFile);
196
197         /* Change the current working directory.  This prevents the current
198            directory from being locked; hence not being able to remove it. */
199         if ((chdir ("/")) < 0)
200         {
201                 syslog (LOG_ERR, "unable to change directory to %s, code %d (%s)",
202                         "/", errno, strerror (errno));
203                 exit (EXIT_FAILURE);
204         }
205
206         /* Redirect standard files to /dev/null */
207         freopen ("/dev/null", "r", stdin);
208         freopen ("/dev/null", "w", stdout);
209         freopen ("/dev/null", "w", stderr);
210
211         /* Tell the parent process that we are A-okay */
212         kill (parent, SIGUSR1);
213 }
214
215 int main (int argc, char *argv[])
216 {
217         char *tty = NULL;
218         char ttypath[TTYPATH_LENGTH];
219         char const *devprefix = "/dev/";
220         char *name = NULL;
221         char buf[IFNAMSIZ+1];
222
223         /* Initialize the logging interface */
224         openlog (DAEMON_NAME, LOG_PID, LOG_LOCAL5);
225
226         /* See how we're called */
227         if (argc == 2) {
228                 tty = argv[1];
229         } else if (argc == 3) {
230                 tty = argv[1];
231                 name = argv[2];
232                 if (strlen(name) > IFNAMSIZ-1)
233                         print_usage(argv[0]);
234         } else {
235                 print_usage(argv[0]);
236         }
237
238         /* Prepare the tty device name string */
239         char * pch;
240         pch = strstr (tty, devprefix);
241         if (pch == tty) {
242                 print_usage(argv[0]);
243         }
244
245         snprintf (ttypath, TTYPATH_LENGTH, "%s%s", devprefix, tty);
246         syslog (LOG_INFO, "starting on TTY device %s", ttypath);
247
248         /* Daemonize */
249         daemonize ("/var/lock/" DAEMON_NAME, tty, name);
250
251         /* Now we are a daemon -- do the work for which we were paid */
252         int fd;
253         int ldisc = LDISC_N_SLCAN;
254
255         if ((fd = open (ttypath, O_WRONLY | O_NOCTTY )) < 0) {
256             syslog (LOG_NOTICE, "failed to open TTY device %s\n", ttypath);
257                 perror(ttypath);
258                 exit(1);
259         }
260
261         /* set slcan like discipline on given tty */
262         if (ioctl (fd, TIOCSETD, &ldisc) < 0) {
263                 perror("ioctl TIOCSETD");
264                 exit(1);
265         }
266         
267         /* retrieve the name of the created CAN netdevice */
268         if (ioctl (fd, SIOCGIFNAME, buf) < 0) {
269                 perror("ioctl SIOCGIFNAME");
270                 exit(1);
271         }
272
273         syslog (LOG_NOTICE, "attached TTY %s to netdevice %s\n", ttypath, buf);
274         
275         /* try to rename the created netdevice */
276         if (name) {
277                 struct ifreq ifr;
278                 int s = socket(PF_INET, SOCK_DGRAM, 0);
279                 if (s < 0)
280                         perror("socket for interface rename");
281                 else {
282                         strncpy (ifr.ifr_name, buf, IFNAMSIZ);
283                         strncpy (ifr.ifr_newname, name, IFNAMSIZ);
284
285                         if (ioctl(s, SIOCSIFNAME, &ifr) < 0) {
286                                 syslog (LOG_NOTICE, "netdevice %s rename to %s failed\n", buf, name);
287                                 perror("ioctl SIOCSIFNAME rename");
288                 exit(1);
289                         } else
290                                 syslog (LOG_NOTICE, "netdevice %s renamed to %s\n", buf, name);
291
292                         close(s);
293                 }       
294         }
295
296         /* The Big Loop */
297         while (1) {
298                 sleep(60); /* wait 60 seconds */
299         }
300
301         /* Finish up */
302         syslog (LOG_NOTICE, "terminated on %s", ttypath);
303         closelog ();
304         return 0;
305 }