]> rtime.felk.cvut.cz Git - can-utils.git/blob - canlogserver.c
Updated help text for commandline options.
[can-utils.git] / canlogserver.c
1 /*
2  *  $Id$
3  */
4
5 /*
6  * canlogserver.c
7  *
8  * Copyright (c) 2002-2007 Volkswagen Group Electronic Research
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. Neither the name of Volkswagen nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * Alternatively, provided that this notice is retained in full, this
24  * software may be distributed under the terms of the GNU General
25  * Public License ("GPL") version 2, in which case the provisions of the
26  * GPL apply INSTEAD OF those given above.
27  *
28  * The provided data structures and external interfaces from this code
29  * are not restricted to be used by modules with a GPL compatible license.
30  *
31  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
32  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
35  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
37  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
41  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
42  * DAMAGE.
43  *
44  * Send feedback to <socketcan-users@lists.berlios.de>
45  *
46  */
47
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <unistd.h>
51 #include <string.h>
52 #include <signal.h>
53 #include <ctype.h>
54 #include <libgen.h>
55 #include <time.h>
56
57 #include <sys/time.h>
58 #include <sys/types.h>
59 #include <sys/socket.h>
60 #include <sys/ioctl.h>
61 #include <sys/uio.h>
62 #include <net/if.h>
63 #include <netinet/in.h>
64
65 #include <linux/can.h>
66 #include <linux/can/raw.h>
67 #include <signal.h>
68 #include <wait.h>
69 #include <errno.h>
70
71 #include "lib.h"
72
73 #define MAXDEV 6 /* change sscanf()'s manually if changed here */
74 #define ANYDEV "any"
75 #define ANL "\r\n" /* newline in ASC mode */
76
77 #define DEFPORT 28700
78
79 static char devname[MAXDEV][IFNAMSIZ+1];
80 static int  dindex[MAXDEV];
81 static int  max_devname_len;
82
83 extern int optind, opterr, optopt;
84
85 static volatile int running = 1;
86
87 void print_usage(char *prg)
88 {
89     fprintf(stderr, "\nUsage: %s [options] <CAN interface>+\n", prg);
90     fprintf(stderr, "  (use CTRL-C to terminate %s)\n\n", prg);
91     fprintf(stderr, "Options: -m <mask>   (ID filter mask.  Default 0x00000000) *\n");
92     fprintf(stderr, "         -v <value>  (ID filter value. Default 0x00000000) *\n");
93     fprintf(stderr, "         -i <0|1>    (invert the specified ID filter) *\n");
94     fprintf(stderr, "         -e <emask>  (mask for error frames)\n");
95     fprintf(stderr, "         -p <port>   (listen on port <port>. Default: %d)\n", DEFPORT);
96     fprintf(stderr, "\n");
97     fprintf(stderr, "* The CAN ID filter matches, when ...\n");
98     fprintf(stderr, "       <received_can_id> & mask == value & mask\n");
99     fprintf(stderr, "\n");
100     fprintf(stderr, "When using more than one CAN interface the options\n");
101     fprintf(stderr, "m/v/i/e have comma seperated values e.g. '-m 0,7FF,0'\n");
102     fprintf(stderr, "\nUse interface name '%s' to receive from all CAN interfaces.\n\n", ANYDEV);
103 }
104
105 int idx2dindex(int ifidx, int socket)
106 {
107     int i;
108     struct ifreq ifr;
109
110     for (i=0; i<MAXDEV; i++) {
111         if (dindex[i] == ifidx)
112             return i;
113     }
114
115     /* create new interface index cache entry */
116
117     /* remove index cache zombies first */
118     for (i=0; i < MAXDEV; i++) {
119         if (dindex[i]) {
120             ifr.ifr_ifindex = dindex[i];
121             if (ioctl(socket, SIOCGIFNAME, &ifr) < 0)
122                 dindex[i] = 0;
123         }
124     }
125
126     for (i=0; i < MAXDEV; i++)
127         if (!dindex[i]) /* free entry */
128             break;
129
130     if (i == MAXDEV) {
131         printf("Interface index cache only supports %d interfaces.\n", MAXDEV);
132         exit(1);
133     }
134
135     dindex[i] = ifidx;
136
137     ifr.ifr_ifindex = ifidx;
138     if (ioctl(socket, SIOCGIFNAME, &ifr) < 0)
139         perror("SIOCGIFNAME");
140
141     if (max_devname_len < strlen(ifr.ifr_name))
142         max_devname_len = strlen(ifr.ifr_name);
143
144     strcpy(devname[i], ifr.ifr_name);
145
146 #ifdef DEBUG
147     printf("new index %d (%s)\n", i, devname[i]);
148 #endif
149
150     return i;
151 }
152
153 /* 
154  * This is a Signalhandler. When we get a signal, that a child
155  * terminated, we wait for it, so the zombie will disappear.
156  */
157 void childdied(int i)
158 {
159     wait(NULL);
160 }
161
162 /*
163  * This is a Signalhandler for a cought SIGTERM
164  */
165 void shutdown_gra(int i)
166 {
167     exit(0);
168 }
169
170
171 int main(int argc, char **argv)
172 {
173     struct sigaction signalaction;
174     sigset_t sigset;
175     fd_set rdfs;
176     int s[MAXDEV];
177     int socki, accsocket;
178     canid_t mask[MAXDEV] = {0};
179     canid_t value[MAXDEV] = {0};
180     int inv_filter[MAXDEV] = {0};
181     can_err_mask_t err_mask[MAXDEV] = {0};
182     int opt, ret;
183     int currmax = 1; /* we assume at least one can bus ;-) */
184     struct sockaddr_can addr;
185     struct can_filter rfilter;
186     struct can_frame frame;
187     int nbytes, i, j;
188     struct ifreq ifr;
189     struct timeval tv, last_tv;
190     int port = DEFPORT;
191     struct sockaddr_in inaddr;
192     struct sockaddr_in clientaddr;
193     socklen_t sin_size = sizeof(clientaddr);
194     char temp[128];
195
196     sigemptyset(&sigset);
197     signalaction.sa_handler = &childdied;
198     signalaction.sa_mask = sigset;
199     signalaction.sa_flags = 0;
200     sigaction(SIGCHLD, &signalaction, NULL);  /* install signal for dying child */
201     signalaction.sa_handler = &shutdown_gra;
202     signalaction.sa_mask = sigset;
203     signalaction.sa_flags = 0;
204     sigaction(SIGTERM, &signalaction, NULL); /* install Signal for termination */
205     sigaction(SIGINT, &signalaction, NULL); /* install Signal for termination */
206
207
208     last_tv.tv_sec  = 0;
209     last_tv.tv_usec = 0;
210
211     while ((opt = getopt(argc, argv, "m:v:i:e:p:")) != -1) {
212
213         switch (opt) {
214         case 'm':
215             i = sscanf(optarg, "%x,%x,%x,%x,%x,%x",
216                        &mask[0], &mask[1], &mask[2],
217                        &mask[3], &mask[4], &mask[5]);
218             if (i > currmax)
219                 currmax = i;
220             break;
221
222         case 'v':
223             i = sscanf(optarg, "%x,%x,%x,%x,%x,%x",
224                        &value[0], &value[1], &value[2],
225                        &value[3], &value[4], &value[5]);
226             if (i > currmax)
227                 currmax = i;
228             break;
229
230         case 'i':
231             i = sscanf(optarg, "%d,%d,%d,%d,%d,%d",
232                        &inv_filter[0], &inv_filter[1], &inv_filter[2],
233                        &inv_filter[3], &inv_filter[4], &inv_filter[5]);
234             if (i > currmax)
235                 currmax = i;
236             break;
237
238         case 'e':
239             i = sscanf(optarg, "%x,%x,%x,%x,%x,%x",
240                        &err_mask[0], &err_mask[1], &err_mask[2],
241                        &err_mask[3], &err_mask[4], &err_mask[5]);
242             if (i > currmax)
243                 currmax = i;
244             break;
245         case 'p':
246             port = atoi(optarg);
247             break;
248         default:
249             fprintf(stderr, "Unknown option %c\n", opt);
250             print_usage(basename(argv[0]));
251             exit(1);
252             break;
253         }
254     }
255
256     if (optind == argc) {
257         print_usage(basename(argv[0]));
258         exit(0);
259     }
260
261     /* count in options higher than device count ? */
262     if (optind + currmax > argc) {
263         printf("low count of CAN devices!\n");
264         return 1;
265     }
266
267     currmax = argc - optind; /* find real number of CAN devices */
268
269     if (currmax > MAXDEV) {
270         printf("More than %d CAN devices!\n", MAXDEV);
271         return 1;
272     }
273
274
275     socki = socket(PF_INET, SOCK_STREAM, 0);
276     if (socki < 0) {
277         perror("socket");
278         exit(1);
279     }
280
281     inaddr.sin_family = AF_INET;
282     inaddr.sin_addr.s_addr = htonl(INADDR_ANY);
283     inaddr.sin_port = htons(port);
284
285     while(bind(socki, (struct sockaddr*)&inaddr, sizeof(inaddr)) < 0) {
286         printf(".");fflush(NULL);
287         usleep(100000);
288     }
289
290     if (listen(socki, 3) != 0) {
291         perror("listen");
292         exit(1);
293     }
294
295     while(1) {
296         accsocket = accept(socki, (struct sockaddr*)&clientaddr, &sin_size);
297         if (accsocket > 0) {
298             //printf("accepted\n");
299             if (!fork())
300                 break;
301             else
302                 close(accsocket);
303         }
304         else if (errno != EINTR) {
305             perror("accept");
306             exit(1);
307         }
308     }
309   
310     for (i=0; i<currmax; i++) {
311
312 #ifdef DEBUG
313         printf("open %d '%s' m%08X v%08X i%d e%d.\n",
314                i, argv[optind+i], mask[i], value[i],
315                inv_filter[i], err_mask[i]);
316 #endif
317
318         if ((s[i] = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
319             perror("socket");
320             return 1;
321         }
322
323         if (mask[i] || value[i]) {
324
325             printf("CAN ID filter[%d] for %s set to "
326                    "mask = %08X, value = %08X %s\n",
327                    i, argv[optind+i], mask[i], value[i],
328                    (inv_filter[i]) ? "(inv_filter)" : "");
329
330             rfilter.can_id   = value[i];
331             rfilter.can_mask = mask[i];
332             if (inv_filter[i])
333                 rfilter.can_id |= CAN_INV_FILTER;
334
335             setsockopt(s[i], SOL_CAN_RAW, CAN_RAW_FILTER,
336                        &rfilter, sizeof(rfilter));
337         }
338
339         if (err_mask[i])
340             setsockopt(s[i], SOL_CAN_RAW, CAN_RAW_ERR_FILTER,
341                        &err_mask[i], sizeof(err_mask[i]));
342
343         j = strlen(argv[optind+i]);
344
345         if (!(j < IFNAMSIZ)) {
346             printf("name of CAN device '%s' is too long!\n", argv[optind+i]);
347             return 1;
348         }
349
350         if (j > max_devname_len)
351             max_devname_len = j; /* for nice printing */
352
353         addr.can_family = AF_CAN;
354
355         if (strcmp(ANYDEV, argv[optind+i])) {
356             strcpy(ifr.ifr_name, argv[optind+i]);
357             if (ioctl(s[i], SIOCGIFINDEX, &ifr) < 0) {
358                 perror("SIOCGIFINDEX");
359                 exit(1);
360             }
361             addr.can_ifindex = ifr.ifr_ifindex;
362         }
363         else
364             addr.can_ifindex = 0; /* any can interface */
365
366         if (bind(s[i], (struct sockaddr *)&addr, sizeof(addr)) < 0) {
367             perror("bindcan");
368             return 1;
369         }
370     }
371
372     while (running) {
373
374         FD_ZERO(&rdfs);
375         for (i=0; i<currmax; i++)
376             FD_SET(s[i], &rdfs);
377
378         if ((ret = select(s[currmax-1]+1, &rdfs, NULL, NULL, NULL)) < 0) {
379             //perror("select");
380             running = 0;
381             continue;
382         }
383
384         for (i=0; i<currmax; i++) {  /* check all CAN RAW sockets */
385
386             if (FD_ISSET(s[i], &rdfs)) {
387
388                 socklen_t len = sizeof(addr);
389                 int idx;
390
391                 if ((nbytes = recvfrom(s[i], &frame,
392                                        sizeof(struct can_frame), 0,
393                                        (struct sockaddr*)&addr, &len)) < 0) {
394                     perror("read");
395                     return 1;
396                 }
397
398                 if (nbytes < sizeof(struct can_frame)) {
399                     fprintf(stderr, "read: incomplete CAN frame\n");
400                     return 1;
401                 }
402
403                 if (ioctl(s[i], SIOCGSTAMP, &tv) < 0)
404                     perror("SIOCGSTAMP");
405
406
407                 idx = idx2dindex(addr.can_ifindex, s[i]);
408
409                 sprintf(temp, "(%ld.%06ld) %*s ",
410                         tv.tv_sec, tv.tv_usec, max_devname_len, devname[idx]);
411                 sprint_canframe(temp+strlen(temp), &frame, 0); 
412                 strcat(temp, "\n");
413
414                 if (write(accsocket, temp, strlen(temp)) < 0) {
415                     perror("writeaccsock");
416                     return 1;
417                 }
418                     
419                 /* printf("%s\n",temp2); */
420
421 #if 0
422                 /* print CAN frame in log file style to stdout */
423                 printf("(%ld.%06ld) ", tv.tv_sec, tv.tv_usec);
424                 printf("%*s ", max_devname_len, devname[idx]);
425                 fprint_canframe(stdout, &frame, "\n", 0);
426 #endif
427             }
428
429         }
430     }
431
432     for (i=0; i<currmax; i++)
433         close(s[i]);
434
435     close(accsocket);
436     return 0;
437 }