]> rtime.felk.cvut.cz Git - sojka/can-utils.git/blob - canplayer.c
Added commandline option '-r' to set the per-socket receive buffer size.
[sojka/can-utils.git] / canplayer.c
1 /*
2  *  $Id$
3  */
4
5 /*
6  * canplayer.c - replay a compact CAN frame logfile to CAN devices
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 <string.h>
50 #include <time.h>
51 #include <libgen.h>
52 #include <stdlib.h>
53 #include <unistd.h>
54
55 #include <net/if.h>
56 #include <sys/ioctl.h>
57 #include <sys/time.h>
58 #include <linux/can.h>
59 #include <linux/can/raw.h>
60
61 #include "lib.h"
62
63 #define DEFAULT_GAP     1       /* ms */
64 #define DEFAULT_LOOPS   1       /* only one replay */
65 #define CHANNELS        20      /* anyone using more than 20 CAN interfaces at a time? */
66 #define BUFSZ           400     /* for one line in the logfile */
67
68 struct assignment {
69         char txif[IFNAMSIZ];
70         int  txifidx;
71         char rxif[IFNAMSIZ];
72 };
73 static struct assignment asgn[CHANNELS];
74
75 extern int optind, opterr, optopt;
76
77 void print_usage(char *prg)
78 {
79         fprintf(stderr, "\nUsage: %s <options> [interface assignment]*\n\n", prg);
80         fprintf(stderr, "Options:              -I <infile>  (default stdin)\n");
81         fprintf(stderr, "                      -l <num>     "
82                 "(process input file <num> times)\n"
83                 "                                   "
84                 "(Use 'i' for infinite loop - default: %d)\n", DEFAULT_LOOPS);
85         fprintf(stderr, "                      -t           (ignore timestamps: "
86                 "send frames immediately)\n");
87         fprintf(stderr, "                      -g <ms>      (gap in milli "
88                 "seconds - default: %d ms)\n", DEFAULT_GAP);
89         fprintf(stderr, "                      -s <s>      (skip gaps in "
90                 "timestamps > 's' seconds)\n");
91         fprintf(stderr, "                      -x           (disable local "
92                 "loopback of sent CAN frames)\n");
93         fprintf(stderr, "                      -v           (verbose: print "
94                 "sent CAN frames)\n\n");
95         fprintf(stderr, "Interface assignment:  0..n assignments like "
96                 "<write-if>=<log-if>\n");
97         fprintf(stderr, "e.g. vcan2=can0 ( send frames received from can0 on "
98                 "vcan2 )\n");
99         fprintf(stderr, "No assignments => send frames to the interface(s) they "
100                 "had been received from.\n\n");
101         fprintf(stderr, "Lines in the logfile not beginning with '(' (start of "
102                 "timestamp) are ignored.\n\n");
103 }
104
105 /* copied from /usr/src/linux/include/linux/time.h ...
106  * lhs < rhs:  return <0
107  * lhs == rhs: return 0
108  * lhs > rhs:  return >0
109  */
110 static inline int timeval_compare(struct timeval *lhs, struct timeval *rhs)
111 {
112         if (lhs->tv_sec < rhs->tv_sec)
113                 return -1;
114         if (lhs->tv_sec > rhs->tv_sec)
115                 return 1;
116         return lhs->tv_usec - rhs->tv_usec;
117 }
118
119 static inline void create_diff_tv(struct timeval *today, struct timeval *diff,
120                                   struct timeval *log) {
121
122         /* create diff_tv so that log_tv + diff_tv = today_tv */
123         diff->tv_sec  = today->tv_sec  - log->tv_sec;
124         diff->tv_usec = today->tv_usec - log->tv_usec;
125 }
126
127 static inline int frames_to_send(struct timeval *today, struct timeval *diff,
128                                  struct timeval *log)
129 {
130         /* return value <0 when log + diff < today */
131
132         struct timeval cmp;
133
134         cmp.tv_sec  = log->tv_sec  + diff->tv_sec;
135         cmp.tv_usec = log->tv_usec + diff->tv_usec;
136
137         if (cmp.tv_usec > 1000000) {
138                 cmp.tv_usec -= 1000000;
139                 cmp.tv_sec++;
140         }
141
142         if (cmp.tv_usec < 0) {
143                 cmp.tv_usec += 1000000;
144                 cmp.tv_sec--;
145         }
146
147         return timeval_compare(&cmp, today);
148 }
149
150 int get_txidx(char *logif_name) {
151
152         int i;
153
154         for (i=0; i<CHANNELS; i++) {
155                 if (asgn[i].rxif[0] == 0) /* end of table content */
156                         break;
157                 if (strcmp(asgn[i].rxif, logif_name) == 0) /* found device name */
158                         break;
159         }
160
161         if ((i == CHANNELS) || (asgn[i].rxif[0] == 0))
162                 return 0; /* not found */
163
164         return asgn[i].txifidx; /* return interface index */
165 }
166
167 char *get_txname(char *logif_name) {
168
169         int i;
170
171         for (i=0; i<CHANNELS; i++) {
172                 if (asgn[i].rxif[0] == 0) /* end of table content */
173                         break;
174                 if (strcmp(asgn[i].rxif, logif_name) == 0) /* found device name */
175                         break;
176         }
177
178         if ((i == CHANNELS) || (asgn[i].rxif[0] == 0))
179                 return 0; /* not found */
180
181         return asgn[i].txif; /* return interface name */
182 }
183
184 int add_assignment(char *mode, int socket, char *txname, char *rxname,
185                    int verbose) {
186
187         struct ifreq ifr;
188         int i;
189
190         /* find free entry */
191         for (i=0; i<CHANNELS; i++) {
192                 if (asgn[i].txif[0] == 0)
193                         break;
194         }
195
196         if (i == CHANNELS) {
197                 fprintf(stderr, "Assignment table exceeded!\n");
198                 return 1;
199         }
200
201         if (strlen(txname) >= IFNAMSIZ) {
202                 fprintf(stderr, "write-if interface name '%s' too long!", txname);
203                 return 1;
204         }
205         strcpy(asgn[i].txif, txname);
206
207         if (strlen(rxname) >= IFNAMSIZ) {
208                 fprintf(stderr, "log-if interface name '%s' too long!", rxname);
209                 return 1;
210         }
211         strcpy(asgn[i].rxif, rxname);
212
213         strcpy(ifr.ifr_name, txname);
214         if (ioctl(socket, SIOCGIFINDEX, &ifr) < 0) {
215                 perror("SIOCGIFINDEX");
216                 fprintf(stderr, "write-if interface name '%s' is wrong!\n", txname);
217                 return 1;
218         }
219         asgn[i].txifidx = ifr.ifr_ifindex;
220
221         if (verbose > 1) /* use -v -v to see this */
222                 printf("added %s assignment: log-if=%s write-if=%s write-if-idx=%d\n",
223                        mode, asgn[i].rxif, asgn[i].txif, asgn[i].txifidx);
224
225         return 0;
226 }
227
228 int main(int argc, char **argv)
229 {
230         static char buf[BUFSZ], device[BUFSZ], ascframe[BUFSZ];
231         struct sockaddr_can addr;
232         static struct can_frame frame;
233         static struct timeval today_tv, log_tv, last_log_tv, diff_tv;
234         struct timespec sleep_ts;
235         int s; /* CAN_RAW socket */
236         FILE *infile = stdin;
237         unsigned long gap = DEFAULT_GAP; 
238         int use_timestamps = 1;
239         static int verbose, opt, delay_loops, skipgap;
240         static int loopback_disable = 0;
241         static int infinite_loops = 0;
242         static int loops = DEFAULT_LOOPS;
243         int assignments; /* assignments defined on the commandline */
244         int txidx;       /* sendto() interface index */
245         int eof, nbytes, i, j;
246         char *fret;
247
248         while ((opt = getopt(argc, argv, "I:l:tg:s:xv?")) != -1) {
249                 switch (opt) {
250                 case 'I':
251                         infile = fopen(optarg, "r");
252                         if (!infile) {
253                                 perror("infile");
254                                 return 1;
255                         }
256                         break;
257
258                 case 'l':
259                         if (optarg[0] == 'i')
260                                 infinite_loops = 1;
261                         else
262                                 if (!(loops = atoi(optarg))) {
263                                         fprintf(stderr, "Invalid argument for option -l !\n");
264                                         return 1;
265                                 }
266                         break;
267
268                 case 't':
269                         use_timestamps = 0;
270                         break;
271
272                 case 'g':
273                         gap = strtoul(optarg, NULL, 10);
274                         break;
275
276                 case 's':
277                         skipgap = strtoul(optarg, NULL, 10);
278                         if (skipgap < 1) {
279                                 fprintf(stderr, "Invalid argument for option -s !\n");
280                                 return 1;
281                         }
282                         break;
283
284                 case 'x':
285                         loopback_disable = 1;
286                         break;
287
288                 case 'v':
289                         verbose++;
290                         break;
291
292                 case '?':
293                 default:
294                         print_usage(basename(argv[0]));
295                         return 1;
296                         break;
297                 }
298         }
299
300         assignments = argc - optind; /* find real number of user assignments */
301
302         if (infile == stdin) { /* no jokes with stdin */
303                 infinite_loops = 0;
304                 loops = 1;
305         }
306
307         if (verbose > 1) /* use -v -v to see this */
308                 if (infinite_loops)
309                         printf("infinite_loops\n");
310                 else
311                         printf("%d loops\n", loops);
312
313         sleep_ts.tv_sec  =  gap / 1000;
314         sleep_ts.tv_nsec = (gap % 1000) * 1000000;
315
316         /* open socket */
317         if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
318                 perror("socket");
319                 return 1;
320         }
321
322         addr.can_family  = AF_CAN;
323         addr.can_ifindex = 0;
324
325         /* disable unneeded default receive filter on this RAW socket */
326         setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);
327
328         if (loopback_disable) {
329                 int loopback = 0;
330
331                 setsockopt(s, SOL_CAN_RAW, CAN_RAW_LOOPBACK,
332                            &loopback, sizeof(loopback));
333         }
334
335         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
336                 perror("bind");
337                 return 1;
338         }
339
340         if (assignments) {
341                 /* add & check user assginments from commandline */
342                 for (i=0; i<assignments; i++) {
343                         if (strlen(argv[optind+i]) >= BUFSZ) {
344                                 fprintf(stderr, "Assignment too long!\n");
345                                 print_usage(basename(argv[0]));
346                                 return 1;
347                         }
348                         strcpy(buf, argv[optind+i]);
349                         for (j=0; j<BUFSZ; j++) { /* find '=' in assignment */
350                                 if (buf[j] == '=')
351                                         break;
352                         }
353                         if ((j == BUFSZ) || (buf[j] != '=')) {
354                                 fprintf(stderr, "'=' missing in assignment!\n");
355                                 print_usage(basename(argv[0]));
356                                 return 1;
357                         }
358                         buf[j] = 0; /* cut string in two pieces */
359                         if (add_assignment("user", s, &buf[0], &buf[j+1], verbose))
360                                 return 1;
361                 }
362         }
363
364         while (infinite_loops || loops--) {
365
366                 if (infile != stdin)
367                         rewind(infile); /* for each loop */
368
369                 if (verbose > 1) /* use -v -v to see this */
370                         printf (">>>>>>>>> start reading file. remaining loops = %d\n", loops);
371
372                 /* read first non-comment frame from logfile */
373                 while ((fret = fgets(buf, BUFSZ-1, infile)) != NULL && buf[0] != '(') {
374                         if (strlen(buf) >= BUFSZ-2) {
375                                 fprintf(stderr, "comment line too long for input buffer\n");
376                                 return 1;
377                         }
378                 }
379
380                 if (!fret)
381                         goto out; /* nothing to read */
382
383                 eof = 0;
384
385                 if (sscanf(buf, "(%ld.%ld) %s %s", &log_tv.tv_sec, &log_tv.tv_usec,
386                            device, ascframe) != 4) {
387                         fprintf(stderr, "incorrect line format in logfile\n");
388                         return 1;
389                 }
390
391                 if (use_timestamps) { /* throttle sending due to logfile timestamps */
392
393                         gettimeofday(&today_tv, NULL);
394                         create_diff_tv(&today_tv, &diff_tv, &log_tv);
395                         last_log_tv = log_tv;
396                 }
397
398                 while (!eof) {
399
400                         while ((!use_timestamps) ||
401                                (frames_to_send(&today_tv, &diff_tv, &log_tv) < 0)) {
402
403                                 /* log_tv/device/ascframe are valid here */
404
405                                 if (strlen(device) >= IFNAMSIZ) {
406                                         fprintf(stderr, "log interface name '%s' too long!", device);
407                                         return 1;
408                                 }
409
410                                 txidx = get_txidx(device); /* get ifindex for sending the frame */
411  
412                                 if ((!txidx) && (!assignments)) {
413                                         /* ifindex not found and no user assignments */
414                                         /* => assign this device automatically       */
415                                         if (add_assignment("auto", s, device, device, verbose))
416                                                 return 1;
417                                         txidx = get_txidx(device);
418                                 }
419
420                                 if (txidx) { /* only send to valid CAN devices */
421
422                                         if (parse_canframe(ascframe, &frame)) {
423                                                 fprintf(stderr, "wrong CAN frame format: '%s'!", ascframe);
424                                                 return 1;
425                                         }
426
427                                         addr.can_family  = AF_CAN;
428                                         addr.can_ifindex = txidx; /* send via this interface */
429  
430                                         nbytes = sendto(s, &frame, sizeof(struct can_frame), 0,
431                                                         (struct sockaddr*)&addr, sizeof(addr));
432
433                                         if (nbytes != sizeof(struct can_frame)) {
434                                                 perror("sendto");
435                                                 return 1;
436                                         }
437
438                                         if (verbose) {
439                                                 printf("%s (%s) ", get_txname(device), device);
440                                                 fprint_long_canframe(stdout, &frame, "\n", 1);
441                                         }
442                                 }
443
444                                 /* read next non-comment frame from logfile */
445                                 while ((fret = fgets(buf, BUFSZ-1, infile)) != NULL && buf[0] != '(') {
446                                         if (strlen(buf) >= BUFSZ-2) {
447                                                 fprintf(stderr, "comment line too long for input buffer\n");
448                                                 return 1;
449                                         }
450                                 }
451
452                                 if (!fret) {
453                                         eof = 1; /* this file is completely processed */
454                                         break;
455                                 }
456
457                                 if (sscanf(buf, "(%ld.%ld) %s %s", &log_tv.tv_sec, &log_tv.tv_usec,
458                                            device, ascframe) != 4) {
459                                         fprintf(stderr, "incorrect line format in logfile\n");
460                                         return 1;
461                                 }
462
463                                 if (use_timestamps) {
464                                         gettimeofday(&today_tv, NULL);
465
466                                         /* test for logfile timestamps jumping backwards OR      */
467                                         /* if the user likes to skip long gaps in the timestamps */
468                                         if ((last_log_tv.tv_sec > log_tv.tv_sec) ||
469                                             (skipgap && abs(last_log_tv.tv_sec - log_tv.tv_sec) > skipgap))
470                                                 create_diff_tv(&today_tv, &diff_tv, &log_tv);
471
472                                         last_log_tv = log_tv;
473                                 }
474
475                         } /* while frames_to_send ... */
476
477                         if (nanosleep(&sleep_ts, NULL))
478                                 return 1;
479
480                         delay_loops++; /* private statistics */
481                         gettimeofday(&today_tv, NULL);
482
483                 } /* while (!eof) */
484
485         } /* while (infinite_loops || loops--) */
486
487 out:
488
489         close(s);
490         fclose(infile);
491
492         if (verbose > 1) /* use -v -v to see this */
493                 printf("%d delay_loops\n", delay_loops);
494
495         return 0;
496 }