17 #include <asm/termbits.h>
18 #include <asm/ioctls.h>
19 #else /* needed for termios2, which is itself needed for non-standard bauds */
29 #if defined(CCDTR_IFLOW) && defined(CDSR_OFLOW)
30 #define CDTRDSR (CDTR_IFLOW | CDSR_OFLOW)
32 #define IXONXOFF (IXON | IXOFF)
37 int offset
; /* can only be a 1 or a -1 */
54 /* including here to access CRLFOpt */
57 static int gettermattr(int dv
, void *strct
);
58 static int settermattr(int dv
, const void *strct
);
59 static void settermspd(unsigned int lispeed
, unsigned int lospeed
, const void *strct
);
60 static int openport();
61 static unsigned int strtoui(const char *str
, const char *msg
, unsigned int min
);
62 static int troptions(CRLFOpt
*options
, const char *str
);
63 static int setroptions();
64 static inline unsigned int lsbmask(unsigned int n
);
65 static inline int termchck(const void *term
);
66 static void interchck();
68 static void *writeport(void *unused
);
69 static void *readport(void *unused
);
70 static void getcmd(int escape
);
71 static inline void replacechar(char *buff
, ssize_t size
, const Args
*args
);
72 static inline ssize_t
addchar(char *buff
, ssize_t size
, int *scratch
, const Sizes
*msizes
, const Args
*args
);
73 static inline ssize_t
rmchar(char *buff
, ssize_t sread
, int *scratch
, const Args
*args
);
74 static void sighandl(int signo
);
75 static void die(int code
, const char *msg
, ...);
78 static struct termios2 cntrl
, origterm
= { 0 }, newterm
= { 0 };
80 static struct termios cntrl
, origterm
= { 0 }, newterm
= { 0 };
83 static Args bsargs
= {DEL
, DEL
, 0};
84 static Args nocrargs
= {CR
, 0, 0};
85 static Args nolfargs
= {LF
, '\0', 0}; /* null-terminator is for use inside `getcmd()` */
86 static Args lfincrargs
= {CR
, LF
, 1};
87 static Args crinlfargs
= {LF
, CR
, -1};
88 static const unsigned int uintmax
= ~(unsigned int)0; /* unsigned -1 to return on error */
89 static struct timespec wts
;
90 static char *writebuff
= NULL
;
91 static char *readbuff
= NULL
;
92 static int *scratchr
= NULL
;
93 static int *scratchw
= NULL
;
95 static int interactive
= 0;
98 gettermattr(int dv
, void *strct
)
101 struct termios2
*optst
= (struct termios2
*)strct
;
102 return ioctl(dv
, TCGETS2
, optst
);
104 struct termios
*optst
= (struct termios
*)strct
;
105 return tcgetattr(dv
, optst
);
110 settermattr(int dv
, const void *strct
)
113 struct termios2
*optst
= (struct termios2
*)strct
;
114 return ioctl(dv
, TCSETS2
, optst
);
116 struct termios
*optst
= (struct termios
*)strct
;
117 return tcsetattr(dv
, TCSANOW
, optst
);
122 settermspd(unsigned int lispeed
, unsigned int lospeed
, const void *strct
)
125 struct termios2
*optst
= (struct termios2
*)strct
;
127 optst
->c_cflag
&= ~CBAUD
;
128 optst
->c_cflag
|= BOTHER
;
129 optst
->c_ispeed
= ispeed
;
130 optst
->c_ospeed
= ospeed
;
132 struct termios
*optst
= (struct termios
*)strct
;
133 cfsetispeed(optst
, ispeed
);
134 cfsetospeed(optst
, ospeed
);
142 struct flock fl
= { 0 };
144 if (verbose
) fprintf(stderr
, "opening \"%s\"\n", line
);
146 fd
= open(line
, (O_RDWR
| O_NOCTTY
| O_NDELAY
));
148 perror("error opening device");
152 if (verbose
) fprintf(stderr
, "checking if \"%s\" is a TTY\n", line
);
155 die(2, "device \"%s\" is not a TTY\n", line
);
157 flags
= fcntl(fd
, F_GETFL
, 0);
158 /* opened to check with non-blocking mode, now set to blocking */
159 flags
&= ~(O_NONBLOCK
| O_NDELAY
);
161 if (fcntl(fd
, F_SETFL
, flags
) == -1) {
163 die(1, "exiting now\n");
166 if (gettermattr(fd
, &cntrl
) == -1)
167 die(1, "failed to get device attributes\n");
170 fl
.l_whence
= SEEK_SET
;
175 if (fcntl(fd
, F_SETLK
, &fl
) == -1) {
177 die(1, "failed to lock the device, exiting now\n");
181 if (verbose
) fprintf(stderr
, "setting baudrate [RX:%u | TX:%u]\n", ispeed
, ospeed
);
183 settermspd(ispeed
, ospeed
, &cntrl
);
184 if (settermattr(fd
, &cntrl
) == -1)
185 die(2,"failed to set baudrate [RX:%u | TX:%u]\n", ispeed
, ospeed
);
188 cntrl
.c_iflag
&= ~(ISTRIP
| BRKINT
);
189 cntrl
.c_cflag
&= ~(PARENB
| PARODD
);
191 if (verbose
) fprintf(stderr
, "setting parity [even: %d, odd: %d]\n", parity
& 1, (parity
& 2) >> 1);
194 cntrl
.c_cflag
|= PARENB
;
196 cntrl
.c_cflag
|= PARENB
| PARODD
;
198 if (settermattr(fd
, &cntrl
) == -1)
199 die(2, "failed to set parity [even: %d, odd: %d]\n", parity
& 1, (parity
& 2) >> 1);
202 /* it's so ugly and beautiful at the same time */
203 int t
= (((hard
& 1) << 1) & (hard
& 2)) >> 1;
204 fprintf(stderr
, "setting flow control [XON/XOFF: %d, RTS/CTS: %d, DTR/DSR: %d, DCD: %d]\n",\
205 soft
, t
^ ((hard
& 1) << 1) >> 1, t
^ (hard
& 2) >> 1, t
);
208 cntrl
.c_cflag
|= CLOCAL
;
209 cntrl
.c_iflag
&= ~IXONXOFF
;
212 cntrl
.c_iflag
|= IXONXOFF
;
215 cntrl
.c_cflag
|= CRTSCTS
;
216 } else if (hard
== 2) {
218 fprintf(stderr
, "DTR/DSR flow control is not supported on this platform\n"
219 "enabling this option does nothing!\n");
221 cntrl
.c_lflag
|= CDTRDSR
;
223 } else if (hard
== 3) {
224 cntrl
.c_cflag
&= ~CLOCAL
;
226 cntrl
.c_lflag
|= CCAR_OFLOW
;
230 if (settermattr(fd
, &cntrl
) == -1)
231 die(2, "failed to set flow control\n");
233 cntrl
.c_iflag
&= ~(ICRNL
| INLCR
);
234 cntrl
.c_oflag
&= ~(OCRNL
| ONLRET
| ONLCR
);
237 die(2, "failed to set cr-lf translation options\n");
239 if (verbose
) fprintf(stderr
, "setting data bits [%c]\n", datab
);
252 cntrl
.c_cflag
&= ~CSIZE
;
255 if (settermattr(fd
, &cntrl
) == -1)
256 die(2, "failed to set data bits [%c]\n", datab
);
258 if (verbose
) fprintf(stderr
, "setting stop bits [%d]\n", stopb
+1);
261 cntrl
.c_cflag
|= CSTOPB
;
263 cntrl
.c_cflag
&= ~CSTOPB
;
265 if (settermattr(fd
, &cntrl
) == -1)
266 die(1, "failed to set stop bits [%d]\n", stopb
+1);
268 cntrl
.c_cc
[VMIN
] = 1;
269 cntrl
.c_cc
[VTIME
] = 0;
272 ioctl(fd
, TCFLSH
, TCIOFLUSH
);
274 tcflush(fd
, TCIOFLUSH
);
280 strtoui(const char *str
, const char *msg
, unsigned int min
)
285 t
= strtol(str
, &endptr
, 10);
286 if (errno
!= 0 || *endptr
!= '\0' || t
< min
|| t
> uintmax
) {
287 fprintf(stderr
, msg
, str
);
291 * conversion like this results in 'undefined behavior' according to C spec,
292 * but almost all compilers will just truncate the value so it's OK
294 return (unsigned int)t
;
295 /* termios's `speed_t` is a typedef for `unsigned int` */
299 troptions(CRLFOpt
*options
, const char *str
)
303 if (!strcmp(str
, "lf-in-cr")) {
304 options
->lfincr
^= 1; return 0;
305 } else if (!strcmp(str
, "lf-to-cr")) {
306 options
->lftocr
^= 1; return 0;
312 if (!strcmp(str
, "cr-in-lf")) {
313 options
->crinlf
^= 1; return 0;
314 } else if (!strcmp(str
, "cr-to-lf")) {
315 options
->crtolf
^= 1; return 0;
321 if (!strcmp(str
, "no-lf")) {
322 options
->nolf
^= 1; return 0;
323 } else if (!strcmp(str
, "no-cr")) {
324 options
->nocr
^= 1; return 0;
331 fprintf(stderr
, "invalid translation option: %s\n", str
);
339 cntrl
.c_iflag
^= (ICRNL
& lsbmask(itropts
.crtolf
));
340 cntrl
.c_iflag
^= (INLCR
& lsbmask(itropts
.lftocr
));
341 cntrl
.c_oflag
^= (OCRNL
& lsbmask(tropts
.crtolf
));
342 cntrl
.c_oflag
^= (ONLRET
& lsbmask(tropts
.lftocr
));
343 cntrl
.c_oflag
^= (ONLCR
& lsbmask(tropts
.crinlf
));
345 return settermattr(fd
, &cntrl
);
349 lsbmask(unsigned int n
)
351 /* if n == 1, n fills with all 1s, 0 stays the same */
352 for (int i
= (sizeof(int) * CHAR_BIT
); i
> 0; i
--)
358 termchck(const void *term
)
361 struct termios2
*iterm
= (struct termios2
*)term
;
362 #define TERMIOS_STRUCT termios2
364 struct termios
*iterm
= (struct termios
*)term
;
365 #define TERMIOS_STRUCT termios
367 for (size_t i
= 0; i
< sizeof(struct TERMIOS_STRUCT
); i
++)
368 if (((char*)iterm
)[i
] != 0)
375 writeport(void *unused
)
380 ts
.tv_sec
= swritedelay
;
381 ts
.tv_nsec
= nswritedelay
;
383 wts
.tv_nsec
= chardelay
;
384 msizes
.sizesm
= scratchwsz
;
385 msizes
.sizebm
= wbuffsz
;
387 writebuff
= malloc(wbuffsz
* sizeof(char));
388 scratchw
= malloc(scratchwsz
* sizeof(int));
390 if (writebuff
== NULL
)
391 die(1, "buffer allocation failed\n");
392 if (scratchw
== NULL
)
393 die(1, "scratch buffer allocation failed\n");
398 ssize_t inln
= read(STDIN_FILENO
, writebuff
, wbuffsz
- 1);
404 if (writebuff
[0] == escapechar
) {
411 if (bsargs
.find
!= bsargs
.input
)
412 replacechar(writebuff
, inln
, &bsargs
);
414 inln
= rmchar(writebuff
, inln
, scratchw
, &nocrargs
);
416 inln
= rmchar(writebuff
, inln
, scratchw
, &nolfargs
);
418 inln
= addchar(writebuff
, inln
, scratchw
, &msizes
, &lfincrargs
);
421 for (int i
= 0; i
<= inln
; i
++) {
422 write(fd
, &writebuff
[i
], 1);
423 nanosleep(&wts
, NULL
);
426 write(fd
, writebuff
, 1);
429 nanosleep(&ts
, NULL
);
435 readport(void *unused
)
439 ts
.tv_sec
= sreaddelay
;
440 ts
.tv_nsec
= nsreaddelay
;
441 msizes
.sizesm
= scratchrsz
;
442 msizes
.sizebm
= rbuffsz
;
444 readbuff
= malloc(rbuffsz
* sizeof(char));
445 scratchr
= malloc(scratchrsz
* sizeof(int));
447 if (readbuff
== NULL
)
448 die(1, "buffer allocation failed\n");
449 if (scratchr
== NULL
)
450 die(1, "scratch buffer allocation failed\n");
454 /* disable stdout buffering */
455 setvbuf(stdout
, NULL
, _IONBF
, 0);
458 ssize_t outln
= read(fd
, readbuff
, rbuffsz
- 1);
461 outln
= rmchar(readbuff
, outln
, scratchr
, &nocrargs
);
463 outln
= rmchar(readbuff
, outln
, scratchr
, &nolfargs
);
465 outln
= addchar(readbuff
, outln
, scratchr
, &msizes
, &crinlfargs
);
467 outln
= addchar(readbuff
, outln
, scratchr
, &msizes
, &lfincrargs
);
469 write(STDOUT_FILENO
, readbuff
, outln
);
471 nanosleep(&ts
, NULL
);
473 if (isatty(STDIN_FILENO
))
474 settermattr(STDIN_FILENO
, &origterm
);
478 inline void __attribute__((hot
))
479 replacechar(char *buff
, ssize_t size
, const Args
*args
)
481 for (int i
= 0; i
< size
; i
++)
482 if (buff
[i
] == args
->find
)
483 buff
[i
] = args
->input
;
486 inline ssize_t
__attribute__((hot
))
487 addchar(char *buff
, ssize_t size
, int *scratch
, const Sizes
*sizes
, const Args
*args
)
491 /* turns negative numbers into 1, positive into 0 */
492 to
= ((args
->offset
>> ((sizeof(int) * CHAR_BIT
) - 1)) & 1);
494 for (int i
= 0; i
< size
; i
++) {
495 if (buff
[i
] == args
->find
) {
499 if (c
>= sizes
->sizesm
)
504 if (size
== 1 && c
== 1 && scratch
[0] == 0) {
505 buff
[to
^ 1] = args
->input
;
506 buff
[to
] = args
->find
;
509 if ((size
+ c
) > sizes
->sizebm
)
510 c
= sizes
->sizebm
- size
;
512 for (int i
= c
- 1; i
>= 0; i
--) {
514 memmove(&buff
[t
] + 1, &buff
[t
], (size
+ c
) - t
);
515 buff
[t
+ (to
^ 1)] = args
->input
;
517 printf("%s\n", buff
);
521 inline ssize_t
__attribute__((hot
))
522 rmchar(char *buff
, ssize_t size
, int *scratch
, const Args
*args
)
525 for (int i
= 0; i
< size
; i
++) {
526 if (buff
[i
] == args
->find
) {
533 if (size
== 1 && c
== 1 && scratch
[0] == 0)
536 for (int i
= c
; i
>= 0; i
--) {
538 memmove(&buff
[t
], &buff
[t
] + 1, (size
+ c
) - t
);
547 if (gettermattr(STDIN_FILENO
, &origterm
) < 0 )
548 die(1, "failed to get terminal attributes\n");
553 newterm
.c_lflag
&= ~ECHO
;
555 newterm
.c_lflag
&= ~ICANON
;
558 newterm
.c_iflag
|= IXONXOFF
;
560 newterm
.c_iflag
|= INLCR
;
561 newterm
.c_cc
[VMIN
] = minchars
;
562 newterm
.c_cc
[VTIME
] = 0;
563 newterm
.c_cc
[VINTR
] = newterm
.c_cc
[VSUSP
]\
564 = newterm
.c_cc
[VQUIT
] = newterm
.c_cc
[VLNEXT
]\
565 = newterm
.c_cc
[VDISCARD
] = _POSIX_VDISABLE
;
568 newterm
.c_cc
[VDSUSP
] = _POSIX_VDISABLE
;
576 bsargs
.find
= origterm
.c_cc
[VERASE
];
578 if (settermattr(STDOUT_FILENO
, &newterm
) < 0)
579 die(1, "failed to set terminal attributes\n");
587 if ((!half
|| !canonical
) && interactive
) {
588 newterm
.c_lflag
|= ECHO
;
589 newterm
.c_lflag
|= ICANON
;
590 if (settermattr(STDIN_FILENO
, &newterm
) < 0)
591 fprintf(stderr
, "failed to enable echo and/or canonical mode\n");
604 msizes
.sizesm
= scratchwsz
;
605 msizes
.sizebm
= wbuffsz
;
607 if (isatty(STDIN_FILENO
) && isatty(STDOUT_FILENO
))
613 cmdchar
= writebuff
[0];
615 cmdchar
= writebuff
[1];
618 case EOT
: /* FALLTHROUGH */
631 newterm
.c_lflag
&= ~ECHO
;
633 newterm
.c_lflag
|= ECHO
;
635 if (settermattr(STDOUT_FILENO
, &newterm
) < 0)
636 die(1, "failed to set terminal attributes\n");
640 newterm
.c_lflag
&= ~ICANON
;
642 newterm
.c_lflag
|= ICANON
;
644 if (settermattr(STDOUT_FILENO
, &newterm
) < 0)
645 die(1, "failed to set terminal attributes\n");
649 if (fgets(ttr
, sizeof(ttr
), stdin
) != NULL
) {
650 replacechar(ttr
, 63, &nolfargs
);
652 int wfd
= open(ttr
, O_RDONLY
);
654 perror("error opening file");
657 while ((frln
= read(wfd
, writebuff
, wbuffsz
- 1)) > 0) {
658 for (int i
= 0; i
<= frln
; i
++) {
660 frln
= rmchar(writebuff
, frln
, scratchw
, &nocrargs
);
662 frln
= rmchar(writebuff
, frln
, scratchw
, &nolfargs
);
664 frln
= addchar(writebuff
, frln
, scratchw
, &msizes
, &lfincrargs
);
666 write(fd
, &writebuff
[i
], 1);
667 nanosleep(&wts
, NULL
);
674 if (fgets(ttr
, sizeof(ttr
), stdin
) != NULL
) {
675 replacechar(ttr
, 63, &nolfargs
);
676 tspd
= strtoui(ttr
, "invalid speed\n", 0);
677 if (tspd
!= uintmax
) {
678 ospeed
= ispeed
= tspd
;
679 settermspd(ispeed
, ospeed
, &cntrl
);
680 if (settermattr(fd
, &cntrl
) != 0)
681 fprintf(stderr
, "failed to set baudrate "
682 "[RX:%u | TX:%u]\n", ispeed
, ospeed
);
688 if (fgets(ttr
, sizeof(ttr
), stdin
) != NULL
) {
689 replacechar(ttr
, 63, &nolfargs
);
690 chardelay
= strtoui(ttr
, "invalid delay\n", 0);
691 if (chardelay
!= uintmax
) {
693 wts
.tv_nsec
= chardelay
;
699 fprintf(stderr
, "additional output translation option: ");
700 if (fgets(ttr
, sizeof(ttr
), stdin
) != NULL
) {
701 replacechar(ttr
, 63, &nolfargs
);
702 if(troptions(&tropts
, ttr
))
705 fprintf(stderr
, "could not set new options\n");
710 printf("additional input translation option: ");
711 if (fgets(ttr
, sizeof(ttr
), stdin
) != NULL
) {
712 replacechar(ttr
, 63, &nolfargs
);
713 if (troptions(&itropts
, ttr
))
716 fprintf(stderr
, "could not set new options\n");
719 if (!half
&& interactive
)
720 newterm
.c_lflag
&= ~ECHO
;
721 if (!canonical
&& interactive
)
722 newterm
.c_lflag
&= ~ICANON
;
723 if (settermattr(STDIN_FILENO
, &newterm
) == -1)
724 fprintf(stderr
, "failed to restore echo and/or canonical mode\n");
729 ts
.tv_sec
= spulsedelay
;
730 ts
.tv_nsec
= nspulsedelay
;
732 if (ioctl(fd
, TIOCMGET
, &st
) != 0) {
733 fprintf(stderr
, "failed to get port status\n");
737 if (ioctl(fd
, TIOCMSET
, &st
) != 0) {
738 fprintf(stderr
, "failed to set DTR [assertion]\n");
741 nanosleep(&ts
, NULL
);
744 if (ioctl(fd
, TIOCMSET
, &st
) != 0)
745 fprintf(stderr
, "failed to set DTR [negation]\n");
747 case BS
: /* FALLTHROUGH */
752 fprintf(stderr
, "not a valid command [%c]\n", cmdchar
);
761 die(128 + signo
, "\nrecieved signal [%d], exiting\n", signo
);
765 die(int code
, const char *msg
, ...)
780 if (termchck(&newterm
))
781 settermattr(STDIN_FILENO
, &origterm
);
784 vfprintf(stderr
, msg
, fpa
);
791 main(int argc
, char **argv
)
794 /* glibc's `asprintf()` won't set the string to NULL on failure automatically */
795 for (int i
= 1; i
< argc
; i
++ ) {
796 if (argv
[i
][0] == '-' && argv
[i
][1] >= '0' && argv
[i
][1] <= '9') {
797 asprintf(&t
, "-s%s", argv
[i
] + 1);
799 fprintf(stderr
, "cannot convert -# to -s#\n");
806 static struct option longopt
[] = {
807 {"line", required_argument
, NULL
, 'l'},
808 {"speed", required_argument
, NULL
, 's'},
809 {"rx-speed", required_argument
, NULL
, 'i'},
810 {"echo", no_argument
, NULL
, 'h'},
811 {"canonical", no_argument
, NULL
, 'c'},
812 {"odd", no_argument
, NULL
, 'o'},
813 {"even", no_argument
, NULL
, 'e'},
814 {"hardware-rts-cts", no_argument
, NULL
, 'R'},
815 {"hardware-dtr-dsr", no_argument
, NULL
, 'r'},
816 {"software", no_argument
, NULL
, 'X'},
817 {"data", required_argument
, NULL
, 'D'},
818 {"delay", required_argument
, NULL
, 'd'},
819 {"min-chars", required_argument
, NULL
, 'm'},
820 {"stop-bits", no_argument
, NULL
, 'S'},
821 {"backspace", no_argument
, NULL
, 'b'},
822 {"translation", required_argument
, NULL
, 't'},
823 {"input-translation", required_argument
, NULL
, 'T'},
824 {"verbose", no_argument
, NULL
, 'v'},
829 int oind
, rxspdset
, devset
, c
;
830 oind
= rxspdset
= devset
= 0;
831 while ((c
= getopt_long(argc
, argv
, "bcd:D:ehi:l:m:oRrs:t:T:vX", longopt
, &oind
)) != -1) {
836 backspace
^= 1; break;
838 canonical
^= 1; break;
848 t
= strtol(optarg
, &endptr
, 10);
849 if (errno
!= 0 || *endptr
!= '\0' || t
< 0) {
850 fprintf(stderr
, "invalid character delay\n");
857 if (strlen(optarg
) != 1 || !(optarg
[0] >= '5' && optarg
[0] <= '8')) {
858 fprintf(stderr
, "invalid number of data bits: %s\n", optarg
);
871 tui
= strtoui(optarg
, "invalid rx speed: %s\n", 1);
878 tui
= strtoui(optarg
, "invalid speed: %s\n", 1);
887 fprintf(stderr
, "cannot specify multiple devices\n");
890 if (strlen(optarg
) > 10) {
891 fprintf(stderr
, "device name too long\n");
894 if (strchr(optarg
, '/')) {
895 strcpy(line
, optarg
);
898 sprintf(line
, "/dev/%s", optarg
);
903 tui
= strtoui(optarg
, "invalid number of characters: %s\n", 1);
909 if (troptions(&tropts
, optarg
))
913 if (troptions(&itropts
, optarg
))
920 die(2, "usage: %s [--line|-l line] [--speed|-s #|-#] [--rx-speed|-i #]\n"
921 " [--data-bits|-D #] [--stop-bits|-S]"
922 " [--even|-e] [--odd|-o]\n"
923 " [--hardware-rts-cts|-R]"
924 " [--hardware-dtr-dsr|-r] [--software|-X]\n"
925 " [--delay|-d #] [--min-chars|-m #]"
926 " [--canonical|-c] [--echo|-h]\n"
927 " [--translation|-t option]"
928 " [--input-translation|-T option]\n"
929 " [--verbose|-v] [--backspace|-b]\n",
935 * not the best practice, but in order for this `free()`
936 * to not get executed ust needs to be killed,
937 * which means the OS *should* free the memory
944 if (isatty(STDIN_FILENO
) && isatty(STDOUT_FILENO
))
947 signal(SIGHUP
, sighandl
);
948 signal(SIGINT
, sighandl
);
949 signal(SIGQUIT
, sighandl
);
950 signal(SIGTERM
, sighandl
);
951 signal(SIGCHLD
, SIG_DFL
);
955 pthread_t readthread
, writethread
;
956 pthread_create(&writethread
, NULL
, writeport
, NULL
);
957 pthread_create(&readthread
, NULL
, readport
, NULL
);
958 pthread_join(writethread
, NULL
);
959 pthread_join(readthread
, NULL
);