12 #include <sys/ioctl.h>
15 #include <asm/termbits.h>
16 #include <asm/ioctls.h>
17 #else /* needed for termios2, which is itself needed for non-standard bauds */
28 #if defined(CCDTR_IFLOW) && defined(CDSR_OFLOW)
29 #define CDTRDSR (CDTR_IFLOW | CDSR_OFLOW)
31 #define IXONXOFF (IXON | IXOFF)
36 int offset
; /* can only be a 1 or a -1 */
44 static int gettermattr(int dv
, void *strct
);
45 static int settermattr(int dv
, const void *strct
);
46 static void settermspd(unsigned int lispeed
, unsigned int lospeed
, const void *strct
);
47 static int openport();
48 static unsigned int strtoui(const char *str
, const char *msg
, unsigned int min
);
49 static int troptions(CRLFOpt
*options
, const char *str
);
50 static int setroptions();
51 static inline unsigned int lsbmask(unsigned int n
);
52 static inline int termchck(const void *term
);
53 static void interchck();
55 static void *writeport(void *unused
);
56 static void *readport(void *unused
);
57 static void getcmd(int escape
);
58 static inline void replacechar(char *buff
, ssize_t size
, const Args
*args
);
59 static inline ssize_t
addchar(char *buff
, ssize_t size
, int *scratch
, const Sizes
*msizes
, const Args
*args
);
60 static inline ssize_t
rmchar(char *buff
, ssize_t sread
, int *scratch
, const Args
*args
);
61 static void sighandl(int signo
);
62 static void die(int code
, const char *msg
, ...);
65 static struct termios2 cntrl
, origterm
= {0}, newterm
= {0};
67 static struct termios cntrl
, origterm
= {0}, newterm
= {0};
70 static Args bsargs
= {DEL
, DEL
, 0};
71 static Args nocrargs
= {CR
, 0, 0};
72 static Args nolfargs
= {LF
, '\0', 0}; /* null-terminator is for use inside `getcmd()` */
73 static Args lfincrargs
= {CR
, LF
, 1};
74 static Args crinlfargs
= {LF
, CR
, -1};
75 static const unsigned int uintmax
= ~(unsigned int)0; /* unsigned -1 to return on error */
76 static struct timespec wts
;
77 static char *writebuff
= NULL
;
78 static char *readbuff
= NULL
;
79 static int *scratchr
= NULL
;
80 static int *scratchw
= NULL
;
82 static int interactive
= 0;
85 gettermattr(int dv
, void *strct
)
88 struct termios2
*optst
= (struct termios2
*)strct
;
89 return ioctl(dv
, TCGETS2
, optst
);
91 struct termios
*optst
= (struct termios
*)strct
;
92 return tcgetattr(dv
, optst
);
97 settermattr(int dv
, const void *strct
)
100 struct termios2
*optst
= (struct termios2
*)strct
;
101 return ioctl(dv
, TCSETS2
, optst
);
103 struct termios
*optst
= (struct termios
*)strct
;
104 return tcsetattr(dv
, TCSANOW
, optst
);
109 settermspd(unsigned int lispeed
, unsigned int lospeed
, const void *strct
)
112 struct termios2
*optst
= (struct termios2
*)strct
;
114 optst
->c_cflag
&= ~CBAUD
;
115 optst
->c_cflag
|= BOTHER
;
116 optst
->c_ispeed
= ispeed
;
117 optst
->c_ospeed
= ospeed
;
119 struct termios
*optst
= (struct termios
*)strct
;
120 cfsetispeed(optst
, ispeed
);
121 cfsetospeed(optst
, ospeed
);
128 if (verbose
) fprintf(stderr
, "opening \"%s\"\n", line
);
130 fd
= open(line
, O_RDWR
| O_NOCTTY
| O_NDELAY
);
132 perror("error opening device");
136 if (verbose
) fprintf(stderr
, "checking if \"%s\" is a TTY\n", line
);
139 die(2, "device \"%s\" is not a TTY\n", line
);
142 flags
= fcntl(fd
, F_GETFL
, 0);
143 /* opened to check with non-blocking mode, now set to blocking */
144 flags
&= ~(O_NONBLOCK
| O_NDELAY
);
145 if (fcntl(fd
, F_SETFL
, flags
) == -1)
146 die(1, "failed to set the device to blocking mode\n");
148 if (gettermattr(fd
, &cntrl
) == -1)
149 die(1, "failed to get device attributes\n");
151 if (verbose
) fprintf(stderr
, "setting baudrate [RX:%u | TX:%u]\n", ispeed
, ospeed
);
153 settermspd(ispeed
, ospeed
, &cntrl
);
154 if (settermattr(fd
, &cntrl
) == -1)
155 die(2,"failed to set baudrate [RX:%u | TX:%u]\n", ispeed
, ospeed
);
158 cntrl
.c_iflag
&= ~(ISTRIP
| BRKINT
);
159 cntrl
.c_cflag
&= ~(PARENB
| PARODD
);
161 if (verbose
) fprintf(stderr
, "setting parity [even: %d, odd: %d]\n", parity
& 1, (parity
& 2) >> 1);
164 cntrl
.c_cflag
|= PARENB
;
166 cntrl
.c_cflag
|= PARENB
| PARODD
;
168 if (settermattr(fd
, &cntrl
) == -1)
169 die(2, "failed to set parity [even: %d, odd: %d]\n", parity
& 1, (parity
& 2) >> 1);
172 /* it's so ugly and beautiful at the same time */
173 int t
= (((hard
& 1) << 1) & (hard
& 2)) >> 1;
174 fprintf(stderr
, "setting flow control [XON/XOFF: %d, RTS/CTS: %d, DTR/DSR: %d, DCD: %d]\n",\
175 soft
, t
^ ((hard
& 1) << 1) >> 1, t
^ (hard
& 2) >> 1, t
);
178 cntrl
.c_cflag
|= CLOCAL
;
179 cntrl
.c_iflag
&= ~IXONXOFF
;
182 cntrl
.c_iflag
|= IXONXOFF
;
185 cntrl
.c_cflag
|= CRTSCTS
;
186 } else if (hard
== 2) {
188 fprintf(stderr
, "DTR/DSR flow control is not supported on this platform\n"
189 "enabling this option does nothing!\n");
191 cntrl
.c_lflag
|= CDTRDSR
;
193 } else if (hard
== 3) {
194 cntrl
.c_cflag
&= ~CLOCAL
;
196 cntrl
.c_lflag
|= CCAR_OFLOW
;
200 if (settermattr(fd
, &cntrl
) == -1)
201 die(2, "failed to set flow control\n");
203 cntrl
.c_iflag
&= ~(ICRNL
| INLCR
);
204 cntrl
.c_oflag
&= ~(OCRNL
| ONLRET
| ONLCR
);
207 die(2, "failed to set cr-lf translation options\n");
209 if (verbose
) fprintf(stderr
, "setting data bits [%c]\n", datab
);
222 cntrl
.c_cflag
&= ~CSIZE
;
225 if (settermattr(fd
, &cntrl
) == -1)
226 die(2, "failed to set data bits [%c]\n", datab
);
228 if (verbose
) fprintf(stderr
, "setting stop bits [%d]\n", stopb
+1);
231 cntrl
.c_cflag
|= CSTOPB
;
233 cntrl
.c_cflag
&= ~CSTOPB
;
235 if (settermattr(fd
, &cntrl
) == -1)
236 die(1, "failed to set stop bits [%d]\n", stopb
+1);
239 ioctl(fd
, TCFLSH
, TCIOFLUSH
);
241 tcflush(fd
, TCIOFLUSH
);
247 strtoui(const char *str
, const char *msg
, unsigned int min
)
252 t
= strtol(str
, &endptr
, 10);
253 if (errno
!= 0 || *endptr
!= '\0' || t
< min
) {
254 fprintf(stderr
, msg
, str
);
258 * conversion like this results in 'undefined behavior' according to C spec,
259 * but almost all compilers will just truncate the value so it's OK
261 return (unsigned int)t
;
262 /* termios's `speed_t` is a typedef for `unsigned int` */
266 troptions(CRLFOpt
*options
, const char *str
)
270 if (strcmp(str
, "lf-in-cr") == 0) {
271 options
->lfincr
= !options
->lfincr
; return 0;
272 } else if (strcmp(str
, "lf-to-cr") == 0) {
273 options
->lftocr
= !options
->lftocr
; return 0;
279 if (strcmp(str
, "cr-in-lf") == 0) {
280 options
->crinlf
= !options
->crinlf
; return 0;
281 } else if (strcmp(str
, "cr-to-lf") == 0) {
282 options
->crtolf
= !options
->crtolf
; return 0;
288 if (strcmp(str
, "no-lf") == 0) {
289 options
->nolf
= !options
->nolf
; return 0;
290 } else if (strcmp(str
, "no-cr") == 0) {
291 options
->nocr
= !options
->nocr
; return 0;
298 fprintf(stderr
, "invalid translation option: %s\n", str
);
306 cntrl
.c_iflag
^= (ICRNL
& lsbmask(itropts
.crtolf
));
307 cntrl
.c_iflag
^= (INLCR
& lsbmask(itropts
.lftocr
));
308 cntrl
.c_oflag
^= (OCRNL
& lsbmask(tropts
.crtolf
));
309 cntrl
.c_oflag
^= (ONLRET
& lsbmask(tropts
.lftocr
));
310 cntrl
.c_oflag
^= (ONLCR
& lsbmask(tropts
.crinlf
));
312 return settermattr(fd
, &cntrl
);
316 lsbmask(unsigned int n
)
318 /* if n == 1, n fills with all 1s, 0 stays the same */
319 for (int i
= (sizeof(int) * CHAR_BIT
); i
> 0; i
--)
325 termchck(const void *term
)
328 struct termios2
*iterm
= (struct termios2
*)term
;
329 #define TERMIOS_STRUCT termios2
331 struct termios
*iterm
= (struct termios
*)term
;
332 #define TERMIOS_STRUCT termios
334 for (size_t i
= 0; i
< sizeof(struct TERMIOS_STRUCT
); i
++)
335 if (((char*)iterm
)[i
] != 0)
342 writeport(void *unused
)
346 ts
.tv_sec
= swritedelay
;
347 ts
.tv_nsec
= nswritedelay
;
349 wts
.tv_nsec
= chardelay
;
350 msizes
.sizesm
= scratchwsz
;
351 msizes
.sizebm
= wbuffsz
;
353 writebuff
= malloc(wbuffsz
* sizeof(char));
354 scratchw
= malloc(scratchwsz
* sizeof(int));
356 if (writebuff
== NULL
)
357 die(1, "buffer allocation failed\n");
358 if (scratchw
== NULL
)
359 die(1, "scratch buffer allocation failed\n");
364 ssize_t inln
= read(STDIN_FILENO
, writebuff
, wbuffsz
- 1);
370 if (writebuff
[0] == escapechar
) {
377 if (bsargs
.find
!= bsargs
.input
)
378 replacechar(writebuff
, inln
, &bsargs
);
380 inln
= rmchar(writebuff
, inln
, scratchw
, &nocrargs
);
382 inln
= rmchar(writebuff
, inln
, scratchw
, &nolfargs
);
384 inln
= addchar(writebuff
, inln
, scratchw
, &msizes
, &lfincrargs
);
387 for (int i
= 0; i
<= inln
; i
++) {
388 write(fd
, &writebuff
[i
], 1);
389 nanosleep(&wts
, NULL
);
392 write(fd
, writebuff
, 1);
395 nanosleep(&ts
, NULL
);
401 readport(void *unused
)
405 ts
.tv_sec
= sreaddelay
;
406 ts
.tv_nsec
= nsreaddelay
;
407 msizes
.sizesm
= scratchrsz
;
408 msizes
.sizebm
= rbuffsz
;
410 readbuff
= malloc(rbuffsz
* sizeof(char));
411 scratchr
= malloc(scratchrsz
* sizeof(int));
413 if (readbuff
== NULL
)
414 die(1, "buffer allocation failed\n");
415 if (scratchr
== NULL
)
416 die(1, "scratch buffer allocation failed\n");
420 /* disable stdout buffering */
421 setvbuf(stdout
, NULL
, _IONBF
, 0);
424 ssize_t outln
= read(fd
, readbuff
, rbuffsz
- 1);
427 outln
= rmchar(readbuff
, outln
, scratchr
, &nocrargs
);
429 outln
= rmchar(readbuff
, outln
, scratchr
, &nolfargs
);
431 outln
= addchar(readbuff
, outln
, scratchr
, &msizes
, &crinlfargs
);
433 outln
= addchar(readbuff
, outln
, scratchr
, &msizes
, &lfincrargs
);
435 write(STDOUT_FILENO
, readbuff
, outln
);
437 nanosleep(&ts
, NULL
);
439 if (isatty(STDIN_FILENO
))
440 settermattr(STDIN_FILENO
, &origterm
);
444 inline void __attribute__((hot
))
445 replacechar(char *buff
, ssize_t size
, const Args
*args
)
447 for (int i
= 0; i
< size
; i
++)
448 if (buff
[i
] == args
->find
)
449 buff
[i
] = args
->input
;
452 inline ssize_t
__attribute__((hot
))
453 addchar(char *buff
, ssize_t size
, int *scratch
, const Sizes
*sizes
, const Args
*args
)
457 /* turns negative numbers into 1, positive into 0 */
458 to
= ((args
->offset
>> ((sizeof(int) * CHAR_BIT
) - 1)) & 1);
460 for (int i
= 0; i
< size
; i
++) {
461 if (buff
[i
] == args
->find
) {
465 if (c
>= sizes
->sizesm
)
470 if (size
== 1 && c
== 1 && scratch
[0] == 0) {
471 buff
[to
^ 1] = args
->input
;
472 buff
[to
] = args
->find
;
475 if ((size
+ c
) > sizes
->sizebm
)
476 c
= sizes
->sizebm
- size
;
478 for (int i
= c
- 1; i
>= 0; i
--) {
480 memmove(&buff
[t
] + 1, &buff
[t
], (size
+ c
) - t
);
481 buff
[t
+ (to
^ 1)] = args
->input
;
483 printf("%s\n", buff
);
487 inline ssize_t
__attribute__((hot
))
488 rmchar(char *buff
, ssize_t size
, int *scratch
, const Args
*args
)
491 for (int i
= 0; i
< size
; i
++) {
492 if (buff
[i
] == args
->find
) {
499 if (size
== 1 && c
== 1 && scratch
[0] == 0)
502 for (int i
= c
; i
>= 0; i
--) {
504 memmove(&buff
[t
], &buff
[t
] + 1, (size
+ c
) - t
);
513 if (gettermattr(STDIN_FILENO
, &origterm
) < 0 )
514 die(1, "failed to get terminal attributes\n");
519 newterm
.c_lflag
&= ~ECHO
;
521 newterm
.c_lflag
&= ~ICANON
;
524 newterm
.c_iflag
|= IXONXOFF
;
526 newterm
.c_iflag
|= INLCR
;
527 newterm
.c_cc
[VMIN
] = minchars
;
528 newterm
.c_cc
[VINTR
] = _POSIX_VDISABLE
;
529 newterm
.c_cc
[VSUSP
] = _POSIX_VDISABLE
;
530 newterm
.c_cc
[VQUIT
] = _POSIX_VDISABLE
;
537 bsargs
.find
= origterm
.c_cc
[VERASE
];
539 if (settermattr(STDOUT_FILENO
, &newterm
) < 0)
540 die(1, "failed to set terminal attributes\n");
548 if ((!half
|| !canonical
) && interactive
) {
549 newterm
.c_lflag
|= ECHO
;
550 newterm
.c_lflag
|= ICANON
;
551 if (settermattr(STDIN_FILENO
, &newterm
) < 0)
552 fprintf(stderr
, "failed to enable echo and/or canonical mode\n");
561 msizes
.sizesm
= scratchwsz
;
562 msizes
.sizebm
= wbuffsz
;
568 if (isatty(STDIN_FILENO
) && isatty(STDOUT_FILENO
))
574 cmdchar
= writebuff
[0];
576 cmdchar
= writebuff
[1];
591 newterm
.c_lflag
&= ~ECHO
;
593 newterm
.c_lflag
|= ECHO
;
595 if (settermattr(STDOUT_FILENO
, &newterm
) < 0)
596 die(1, "failed to set terminal attributes\n");
600 newterm
.c_lflag
&= ~ICANON
;
602 newterm
.c_lflag
|= ICANON
;
604 if (settermattr(STDOUT_FILENO
, &newterm
) < 0)
605 die(1, "failed to set terminal attributes\n");
609 if (fgets(ttr
, sizeof(ttr
), stdin
) != NULL
) {
610 replacechar(ttr
, 63, &nolfargs
);
612 int wfd
= open(ttr
, O_RDONLY
);
614 perror("error opening file");
617 while ((frln
= read(wfd
, writebuff
, wbuffsz
- 1)) > 0) {
618 for (int i
= 0; i
<= frln
; i
++) {
620 frln
= rmchar(writebuff
, frln
, scratchw
, &nocrargs
);
622 frln
= rmchar(writebuff
, frln
, scratchw
, &nolfargs
);
624 frln
= addchar(writebuff
, frln
, scratchw
, &msizes
, &lfincrargs
);
626 write(fd
, &writebuff
[i
], 1);
627 nanosleep(&wts
, NULL
);
634 if (fgets(ttr
, sizeof(ttr
), stdin
) != NULL
) {
635 replacechar(ttr
, 63, &nolfargs
);
636 tspd
= strtoui(ttr
, "invalid speed\n", 0);
637 if (tspd
!= uintmax
) {
638 ospeed
= ispeed
= tspd
;
639 settermspd(ispeed
, ospeed
, &cntrl
);
640 if (settermattr(fd
, &cntrl
) != 0)
641 fprintf(stderr
, "failed to set baudrate "
642 "[RX:%u | TX:%u]\n", ispeed
, ospeed
);
648 if (fgets(ttr
, sizeof(ttr
), stdin
) != NULL
) {
649 replacechar(ttr
, 63, &nolfargs
);
650 chardelay
= strtoui(ttr
, "invalid delay\n", 0);
651 if (chardelay
!= uintmax
) {
653 wts
.tv_nsec
= chardelay
;
659 fprintf(stderr
, "additional output translation option: ");
660 if (fgets(ttr
, sizeof(ttr
), stdin
) != NULL
) {
661 replacechar(ttr
, 63, &nolfargs
);
662 if(troptions(&tropts
, ttr
))
665 fprintf(stderr
, "could not set new options\n");
670 printf("additional input translation option: ");
671 if (fgets(ttr
, sizeof(ttr
), stdin
) != NULL
) {
672 replacechar(ttr
, 63, &nolfargs
);
673 if (troptions(&itropts
, ttr
))
676 fprintf(stderr
, "could not set new options\n");
679 if (!half
&& interactive
)
680 newterm
.c_lflag
&= ~ECHO
;
681 if (!canonical
&& interactive
)
682 newterm
.c_lflag
&= ~ICANON
;
683 if (settermattr(STDIN_FILENO
, &newterm
) == -1)
684 fprintf(stderr
, "failed to restore echo and/or canonical mode\n");
689 ts
.tv_sec
= spulsedelay
;
690 ts
.tv_nsec
= nspulsedelay
;
692 if (ioctl(fd
, TIOCMGET
, &st
) != 0) {
693 fprintf(stderr
, "failed to get port status\n");
697 if (ioctl(fd
, TIOCMSET
, &st
) != 0) {
698 fprintf(stderr
, "failed to set DTR [assertion]\n");
701 nanosleep(&ts
, NULL
);
704 if (ioctl(fd
, TIOCMSET
, &st
) != 0)
705 fprintf(stderr
, "failed to set DTR [negation]\n");
707 case BS
: /* FALLTHROUGH */
712 fprintf(stderr
, "not a valid command [%c]\n", cmdchar
);
721 die(128 + signo
, "\nrecieved signal [%d], exiting\n", signo
);
725 die(int code
, const char *msg
, ...)
740 if (termchck(&newterm
))
741 settermattr(STDIN_FILENO
, &origterm
);
744 vfprintf(stderr
, msg
, fpa
);
751 main(int argc
, char **argv
)
754 /* glibc's `asprintf()` won't set the string to NULL on failure automatically */
755 for (int i
= 1; i
< argc
; i
++ ) {
756 if (argv
[i
][0] == '-' && argv
[i
][1] >= '0' && argv
[i
][1] <= '9') {
757 asprintf(&t
, "-s%s", argv
[i
] + 1);
759 fprintf(stderr
, "cannot convert -# to -s#\n");
766 static struct option longopt
[] = {
767 {"line", required_argument
, NULL
, 'l'},
768 {"speed", required_argument
, NULL
, 's'},
769 {"rx-speed", required_argument
, NULL
, 'i'},
770 {"echo", no_argument
, NULL
, 'h'},
771 {"canonical", no_argument
, NULL
, 'c'},
772 {"odd", no_argument
, NULL
, 'o'},
773 {"even", no_argument
, NULL
, 'e'},
774 {"hardware-rts-cts", no_argument
, NULL
, 'R'},
775 {"hardware-dtr-dsr", no_argument
, NULL
, 'r'},
776 {"software", no_argument
, NULL
, 'X'},
777 {"data", required_argument
, NULL
, 'D'},
778 {"delay", required_argument
, NULL
, 'd'},
779 {"min-chars", required_argument
, NULL
, 'm'},
780 {"stop-bits", no_argument
, NULL
, 'S'},
781 {"backspace", no_argument
, NULL
, 'b'},
782 {"translation", required_argument
, NULL
, 't'},
783 {"input-translation", required_argument
, NULL
, 'T'},
784 {"verbose", no_argument
, NULL
, 'v'},
789 int oind
, rxspdset
, devset
, c
;
790 oind
= rxspdset
= devset
= 0;
791 while ((c
= getopt_long(argc
, argv
, "bcd:D:ehi:l:m:oRrs:t:T:vX", longopt
, &oind
)) != -1) {
796 backspace
^= 1; break;
798 canonical
^= 1; break;
808 t
= strtol(optarg
, &endptr
, 10);
809 if (errno
!= 0 || *endptr
!= '\0' || t
< 0) {
810 fprintf(stderr
, "invalid character delay\n");
817 if (strlen(optarg
) != 1 || !(optarg
[0] >= '5' && optarg
[0] <= '8')) {
818 fprintf(stderr
, "invalid number of data bits: %s\n", optarg
);
831 tui
= strtoui(optarg
, "invalid rx speed: %s\n", 1);
838 tui
= strtoui(optarg
, "invalid speed: %s\n", 1);
847 fprintf(stderr
, "cannot specify multiple devices\n");
850 if (strlen(optarg
) > 10) {
851 fprintf(stderr
, "device name too long\n");
854 if (strchr(optarg
, '/')) {
855 strcpy(line
, optarg
);
858 sprintf(line
, "/dev/%s", optarg
);
863 tui
= strtoui(optarg
, "invalid number of characters: %s\n", 1);
869 if (troptions(&tropts
, optarg
))
873 if (troptions(&itropts
, optarg
))
880 die(2, "usage: %s [--line|-l line] [--speed|-s #|-#] [--rx-speed|-i #]\n"
881 " [--data-bits|-D #] [--stop-bits|-S]"
882 " [--even|-e] [--odd|-o]\n"
883 " [--hardware-rts-cts|-R]"
884 " [--hardware-dtr-dsr|-r] [--software|-X]\n"
885 " [--delay|-d #] [--min-chars|-m #]"
886 " [--canonical|-c] [--echo|-h]\n"
887 " [--translation|-t tropt]"
888 " [--input-translation|-T tropt]\n"
889 " [--verbose|-v] [--backspace|-b]\n",
895 * not the best practice, but in order for this `free()`
896 * to not get executed ust needs to be killed,
897 * which means the OS *should* free the memory
904 if (isatty(STDIN_FILENO
) && isatty(STDOUT_FILENO
))
907 signal(SIGHUP
, sighandl
);
908 signal(SIGINT
, sighandl
);
909 signal(SIGQUIT
, sighandl
);
910 signal(SIGTERM
, sighandl
);
914 pthread_t readthread
, writethread
;
915 pthread_create(&writethread
, NULL
, writeport
, NULL
);
916 pthread_create(&readthread
, NULL
, readport
, NULL
);
917 pthread_join(writethread
, NULL
);
918 pthread_join(readthread
, NULL
);