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