]> rtime.felk.cvut.cz Git - can-utils.git/blob - slcanpty.c
candump: Enable HW timestamping before using it
[can-utils.git] / slcanpty.c
1 /*
2  * slcanpty.c -  creates a pty for applications using the slcan ASCII protocol
3  * and converts the ASCII data to a CAN network interface (and vice versa)
4  *
5  * Copyright (c)2009 Oliver Hartkopp
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  *
21  * Send feedback to <linux-can@vger.kernel.org>
22  *
23  */
24
25 /* To get ptsname grantpt and unlockpt definitions from stdlib.h */
26 #define _GNU_SOURCE
27
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <unistd.h>
32 #include <fcntl.h>
33 #include <termios.h>
34
35 #include <net/if.h>
36 #include <sys/socket.h>
37 #include <sys/ioctl.h>
38 #include <sys/stat.h>
39 #include <sys/types.h>
40
41 #include <linux/can.h>
42 #include <linux/can/raw.h>
43
44 /* maximum rx buffer len: extended CAN frame with timestamp */
45 #define SLC_MTU (sizeof("T1111222281122334455667788EA5F\r")+1)
46 #define DEVICE_NAME_PTMX "/dev/ptmx"
47
48 #define DEBUG
49
50 static int asc2nibble(char c)
51 {
52
53         if ((c >= '0') && (c <= '9'))
54                 return c - '0';
55
56         if ((c >= 'A') && (c <= 'F'))
57                 return c - 'A' + 10;
58
59         if ((c >= 'a') && (c <= 'f'))
60                 return c - 'a' + 10;
61
62         return 16; /* error */
63 }
64
65 /* read data from pty, send CAN frames to CAN socket and answer commands */
66 int pty2can(int pty, int socket, struct can_filter *fi,
67             int *is_open, int *tstamp)
68 {
69         int nbytes;
70         char cmd;
71         static char buf[200];
72         char replybuf[10]; /* for answers to received commands */
73         int ptr;
74         struct can_frame frame;
75         int tmp, i;
76         static int rxoffset = 0; /* points to the end of an received incomplete SLCAN message */
77
78         nbytes = read(pty, &buf[rxoffset], sizeof(buf)-rxoffset-1);
79         if (nbytes <= 0) {
80                 /* nbytes == 0 : no error but pty decriptor has been closed */
81                 if (nbytes < 0)
82                         perror("read pty");
83
84                 return 1;
85         }
86
87         /* reset incomplete message offset */
88         nbytes += rxoffset;
89         rxoffset = 0;
90
91 rx_restart:
92         /* remove trailing '\r' characters to be robust against some apps */
93         while (buf[0] == '\r' && nbytes > 0) {
94                 for (tmp = 0; tmp < nbytes; tmp++)
95                         buf[tmp] = buf[tmp+1];
96                 nbytes--;
97         }
98
99         if (!nbytes)
100                 return 0;
101
102         /* check if we can detect a complete SLCAN message including '\r' */
103         for (tmp = 0; tmp < nbytes; tmp++) {
104                 if (buf[tmp] == '\r')
105                         break;
106         }
107
108         /* no '\r' found in the message buffer? */
109         if (tmp == nbytes) {
110                 /* save incomplete message */
111                 rxoffset = nbytes;
112
113                 /* leave here and read from pty again */
114                 return 0;
115         }
116
117         cmd = buf[0];
118         buf[nbytes] = 0;
119
120 #ifdef DEBUG
121         for (tmp = 0; tmp < nbytes; tmp++)
122                 if (buf[tmp] == '\r')
123                         putchar('@');
124                 else
125                         putchar(buf[tmp]);
126         printf("\n");
127 #endif
128
129         /* check for filter configuration commands */
130         if (cmd == 'm' || cmd == 'M') {
131                 buf[9] = 0; /* terminate filter string */
132                 ptr = 9;
133 #if 0
134                 /* the filter is no SocketCAN filter :-( */
135
136                 /* TODO: behave like a SJA1000 controller specific filter */
137
138                 if (cmd == 'm') {
139                         fi->can_id = strtoul(buf+1,NULL,16);
140                         fi->can_id &= CAN_EFF_MASK;
141                 } else {
142                         fi->can_mask = strtoul(buf+1,NULL,16);
143                         fi->can_mask &= CAN_EFF_MASK;
144                 }
145
146                 if (*is_open)
147                         setsockopt(socket, SOL_CAN_RAW,
148                                    CAN_RAW_FILTER, fi,
149                                    sizeof(struct can_filter));
150 #endif
151                 goto rx_out_ack;
152         }
153
154
155         /* check for timestamp on/off command */
156         if (cmd == 'Z') {
157                 *tstamp = buf[1] & 0x01;
158                 ptr = 2;
159                 goto rx_out_ack;
160         }
161
162         /* check for 'O'pen command */
163         if (cmd == 'O') {
164                 setsockopt(socket, SOL_CAN_RAW,
165                            CAN_RAW_FILTER, fi,
166                            sizeof(struct can_filter));
167                 ptr = 1;
168                 *is_open = 1;
169                 goto rx_out_ack;
170         }
171
172         /* check for 'C'lose command */
173         if (cmd == 'C') {
174                 setsockopt(socket, SOL_CAN_RAW, CAN_RAW_FILTER,
175                            NULL, 0);
176                 ptr = 1;
177                 *is_open = 0;
178                 goto rx_out_ack;
179         }
180
181         /* check for 'V'ersion command */
182         if (cmd == 'V') {
183                 sprintf(replybuf, "V1013\r");
184                 tmp = strlen(replybuf);
185                 ptr = 1;
186                 goto rx_out;
187         }
188         /* check for 'v'ersion command */
189         if (cmd == 'v') {
190                 sprintf(replybuf, "v1014\r");
191                 tmp = strlen(replybuf);
192                 ptr = 1;
193                 goto rx_out;
194         }
195
196         /* check for serial 'N'umber command */
197         if (cmd == 'N') {
198                 sprintf(replybuf, "N4242\r");
199                 tmp = strlen(replybuf);
200                 ptr = 1;
201                 goto rx_out;
202         }
203
204         /* check for read status 'F'lags */
205         if (cmd == 'F') {
206                 sprintf(replybuf, "F00\r");
207                 tmp = strlen(replybuf);
208                 ptr = 1;
209                 goto rx_out;
210         }
211
212         /* correctly answer unsupported commands */
213         if (cmd == 'U') {
214                 ptr = 2;
215                 goto rx_out_ack;
216         }
217         if (cmd == 'S') {
218                 ptr = 2;
219                 goto rx_out_ack;
220         }
221         if (cmd == 's') {
222                 ptr = 5;
223                 goto rx_out_ack;
224         }
225         if (cmd == 'P' || cmd == 'A') {
226                 ptr = 1;
227                 goto rx_out_nack;
228         }
229         if (cmd == 'X') {
230                 ptr = 2;
231                 if (buf[1] & 0x01)
232                         goto rx_out_ack;
233                 else
234                         goto rx_out_nack;
235         }
236
237         /* catch unknown commands */
238         if ((cmd != 't') && (cmd != 'T') &&
239             (cmd != 'r') && (cmd != 'R')) {
240                 ptr = nbytes-1;
241                 goto rx_out_nack;
242         }
243
244         if (cmd & 0x20) /* tiny chars 'r' 't' => SFF */
245                 ptr = 4; /* dlc position tiiid */
246         else
247                 ptr = 9; /* dlc position Tiiiiiiiid */
248
249         *(unsigned long long *) (&frame.data) = 0ULL; /* clear data[] */
250
251         if ((cmd | 0x20) == 'r' && buf[ptr] != '0') {
252
253                 /* 
254                  * RTR frame without dlc information!
255                  * This is against the SLCAN spec but sent
256                  * by a commercial CAN tool ... so we are
257                  * robust against this protocol violation.
258                  */
259
260                 frame.can_dlc = buf[ptr]; /* save following byte */
261
262                 buf[ptr] = 0; /* terminate can_id string */
263
264                 frame.can_id = strtoul(buf+1, NULL, 16);
265                 frame.can_id |= CAN_RTR_FLAG;
266
267                 if (!(cmd & 0x20)) /* NO tiny chars => EFF */
268                         frame.can_id |= CAN_EFF_FLAG;
269
270                 buf[ptr]  = frame.can_dlc; /* restore following byte */
271                 frame.can_dlc = 0;
272                 ptr--; /* we have no dlc component in the violation case */
273
274         } else {
275
276                 if (!(buf[ptr] >= '0' && buf[ptr] < '9'))
277                         goto rx_out_nack;
278
279                 frame.can_dlc = buf[ptr] - '0'; /* get dlc from ASCII val */
280
281                 buf[ptr] = 0; /* terminate can_id string */
282
283                 frame.can_id = strtoul(buf+1, NULL, 16);
284
285                 if (!(cmd & 0x20)) /* NO tiny chars => EFF */
286                         frame.can_id |= CAN_EFF_FLAG;
287
288                 if ((cmd | 0x20) == 'r') /* RTR frame */
289                         frame.can_id |= CAN_RTR_FLAG;
290
291                 for (i = 0, ptr++; i < frame.can_dlc; i++) {
292
293                         tmp = asc2nibble(buf[ptr++]);
294                         if (tmp > 0x0F)
295                                 goto rx_out_nack;
296                         frame.data[i] = (tmp << 4);
297                         tmp = asc2nibble(buf[ptr++]);
298                         if (tmp > 0x0F)
299                                 goto rx_out_nack;
300                         frame.data[i] |= tmp;
301                 }
302                 /* point to last real data */
303                 if (frame.can_dlc)
304                         ptr--;
305         }
306
307         tmp = write(socket, &frame, sizeof(frame));
308         if (tmp != sizeof(frame)) {
309                 perror("write socket");
310                 return 1;
311         }
312
313 rx_out_ack:
314         replybuf[0] = '\r';
315         tmp = 1;
316         goto rx_out;
317 rx_out_nack:
318         replybuf[0] = '\a';
319         tmp = 1;
320 rx_out:
321         tmp = write(pty, replybuf, tmp);
322         if (tmp < 0) {
323                 perror("write pty replybuf");
324                 return 1;
325         }
326
327         /* check if there is another command in this buffer */
328         if (nbytes > ptr+1) {
329                 for (tmp = 0, ptr++; ptr+tmp < nbytes; tmp++)
330                         buf[tmp] = buf[ptr+tmp];
331                 nbytes = tmp;
332                 goto rx_restart;
333         }
334
335         return 0;
336 }
337
338 /* read CAN frames from CAN interface and write it to the pty */
339 int can2pty(int pty, int socket, int *tstamp)
340 {
341         int nbytes;
342         char cmd;
343         char buf[SLC_MTU];
344         int ptr;
345         struct can_frame frame;
346         int i;
347
348         nbytes = read(socket, &frame, sizeof(frame));
349         if (nbytes != sizeof(frame)) {
350                 perror("read socket");
351                 return 1;
352         }
353
354         /* convert to slcan ASCII frame */
355         if (frame.can_id & CAN_RTR_FLAG)
356                 cmd = 'R'; /* becomes 'r' in SFF format */
357         else
358                 cmd = 'T'; /* becomes 't' in SFF format */
359
360         if (frame.can_id & CAN_EFF_FLAG)
361                 sprintf(buf, "%c%08X%d", cmd,
362                         frame.can_id & CAN_EFF_MASK,
363                         frame.can_dlc);
364         else
365                 sprintf(buf, "%c%03X%d", cmd | 0x20,
366                         frame.can_id & CAN_SFF_MASK,
367                         frame.can_dlc);
368
369         ptr = strlen(buf);
370
371         for (i = 0; i < frame.can_dlc; i++)
372                 sprintf(&buf[ptr + 2*i], "%02X",
373                         frame.data[i]);
374
375         if (*tstamp) {
376                 struct timeval tv;
377
378                 if (ioctl(socket, SIOCGSTAMP, &tv) < 0)
379                         perror("SIOCGSTAMP");
380
381                 sprintf(&buf[ptr + 2*frame.can_dlc], "%04lX",
382                         (tv.tv_sec%60)*1000 + tv.tv_usec/1000);
383         }
384
385         strcat(buf, "\r"); /* add terminating character */
386         nbytes = write(pty, buf, strlen(buf));
387         if (nbytes < 0) {
388                 perror("write pty");
389                 return 1;
390         }
391         fflush(NULL);
392
393         return 0;
394 }
395
396 int check_select_stdin(void)
397 {
398         fd_set rdfs;
399         struct timeval timeout;
400         int ret;
401
402         FD_ZERO(&rdfs);
403         FD_SET(0, &rdfs);
404         timeout.tv_sec = 0;
405         timeout.tv_usec = 0;
406
407         ret = select(1, &rdfs, NULL, NULL, &timeout);
408
409         if (ret < 0)
410                 return 0; /* not selectable */
411
412         if (ret > 0 && getchar() == EOF)
413                 return 0; /* EOF, eg. /dev/null */
414
415         return 1;
416 }
417
418 int main(int argc, char **argv)
419 {
420         fd_set rdfs;
421         int p; /* pty master file */ 
422         int s; /* can raw socket */ 
423         struct sockaddr_can addr;
424         struct termios topts;
425         int select_stdin = 0;
426         int running = 1;
427         int tstamp = 0;
428         int is_open = 0;
429         struct can_filter fi;
430
431         /* check command line options */
432         if (argc != 3) {
433                 fprintf(stderr, "\n");
434                 fprintf(stderr, "%s creates a pty for applications using"
435                         " the slcan ASCII protocol and\n", argv[0]);
436                 fprintf(stderr, "converts the ASCII data to a CAN network"
437                         " interface (and vice versa)\n\n");
438                 fprintf(stderr, "Usage: %s <pty> <can interface>\n", argv[0]);
439                 fprintf(stderr, "e.g. '%s /dev/ptyc0 can0' creates"
440                         " /dev/ttyc0 for the slcan application\n", argv[0]);
441                 fprintf(stderr, "e.g. for pseudo-terminal '%s %s can0' creates"
442                         " /dev/pts/N\n", argv[0], DEVICE_NAME_PTMX);
443                 fprintf(stderr, "\n");
444                 return 1;
445         }
446
447         select_stdin = check_select_stdin();
448
449         /* open pty */
450         p = open(argv[1], O_RDWR);
451         if (p < 0) {
452                 perror("open pty");
453                 return 1;
454         }
455
456         if (tcgetattr(p, &topts)) {
457                 perror("tcgetattr");
458                 return 1;
459         }
460
461         /* disable local echo which would cause double frames */
462         topts.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK |
463                            ECHONL | ECHOPRT | ECHOKE);
464         topts.c_iflag &= ~(ICRNL);
465         topts.c_iflag |= INLCR;
466         tcsetattr(p, TCSANOW, &topts);
467
468         /* Support for the Unix 98 pseudo-terminal interface /dev/ptmx /dev/pts/N */
469         if  (strcmp(argv[1], DEVICE_NAME_PTMX) == 0) {
470
471                 char *name_pts = NULL;  /* slave pseudo-terminal device name */
472
473                 if (grantpt(p) < 0) {
474                         perror("grantpt");
475                         return 1;
476                 }
477
478                 if (unlockpt(p) < 0) {
479                         perror("unlockpt");
480                         return 1;
481                 }
482
483                 name_pts = ptsname(p);
484                 if (name_pts == NULL) {
485                         perror("ptsname");
486                         return 1;
487                 }
488                 printf("open: %s: slave pseudo-terminal is %s\n", argv[1], name_pts);
489         }
490
491         /* open socket */
492         s = socket(PF_CAN, SOCK_RAW, CAN_RAW);
493         if (s < 0) {
494                 perror("socket");
495                 return 1;
496         }
497
498         addr.can_family = AF_CAN;
499         addr.can_ifindex = if_nametoindex(argv[2]);
500
501         /* disable reception of CAN frames until we are opened by 'O' */
502         setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);
503
504         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
505                 perror("bind");
506                 return 1;
507         }
508
509         /* open filter by default */
510         fi.can_id   = 0;
511         fi.can_mask = 0;
512
513         while (running) {
514
515                 FD_ZERO(&rdfs);
516
517                 if (select_stdin)
518                         FD_SET(0, &rdfs);
519
520                 FD_SET(p, &rdfs);
521                 FD_SET(s, &rdfs);
522
523                 if (select(s+1, &rdfs, NULL, NULL, NULL) < 0) {
524                         perror("select");
525                         return 1;
526                 }
527
528                 if (FD_ISSET(0, &rdfs)) {
529                         running = 0;
530                         continue;
531                 }
532
533                 if (FD_ISSET(p, &rdfs))
534                         if (pty2can(p, s, &fi, &is_open, &tstamp)) {
535                         running = 0;
536                         continue;
537                 }
538
539                 if (FD_ISSET(s, &rdfs))
540                         if (can2pty(p, s, &tstamp)) {
541                         running = 0;
542                         continue;
543                 }
544         }
545
546         close(p);
547         close(s);
548
549         return 0;
550 }