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