]> rtime.felk.cvut.cz Git - can-benchmark.git/blob - utils/sterm.c
Add scape sequence and an option to ignore it
[can-benchmark.git] / utils / sterm.c
1 /*
2  * Simple serial terminal
3  *
4  * Copyright 2014 Michal Sojka <sojkam1@fel.cvut.cz>
5  *
6  * This program is free software: you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License as
8  * published by the Free Software Foundation, either version 3 of the
9  * License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program. If not, see
18  * <http://www.gnu.org/licenses/>.
19  */
20
21 /*
22  * This is a minimalist terminal program like minicom or cu. The only
23  * thing it does is creating a bidirectional connection between
24  * stdin/stdout and a device (e.g. serial terminal). It can also set
25  * serial line baudrate and manipulate DTR/RTS modem lines.
26  *
27  * The -d and -r option create short pulse on DTR/RTS. The lines are
28  * always raised when the device is opened and those options lower the
29  * lines immediately after opening.
30  */
31
32 #define _BSD_SOURCE
33 #include <sys/ioctl.h>
34 #include <unistd.h>
35 #include <fcntl.h>
36 #include <termios.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <getopt.h>
40 #include <poll.h>
41 #include <stdbool.h>
42 #include <string.h>
43 #include <signal.h>
44
45 #define STRINGIFY(val) #val
46 #define TOSTRING(val) STRINGIFY(val)
47 #define CHECK(cmd) ({ int ret = (cmd); if (ret == -1) { perror(#cmd " line " TOSTRING(__LINE__)); exit(1); }; ret; })
48 #define CHECKPTR(cmd) ({ void *ptr = (cmd); if (ptr == (void*)-1) { perror(#cmd " line " TOSTRING(__LINE__)); exit(1); }; ptr; })
49
50 #define VERBOSE(format, ...) do { if (verbose) fprintf(stderr, format, ##__VA_ARGS__); } while (0)
51
52 bool verbose = false;
53 bool exit_on_escape = true;
54
55 char template[] = "/var/lock/TMPXXXXXX";
56 char lockfile[100];
57 struct termios stdin_tio_backup;
58
59 void rm_file(int status, void *arg)
60 {
61         char *fn = arg;
62         if (fn[0])
63                 unlink(fn);
64         fn[0] = 0;
65 }
66
67 void restore_stdin_term()
68 {
69         tcsetattr(0, TCSANOW, &stdin_tio_backup);
70 }
71
72 void sighandler(int arg)
73 {
74         exit(0); /* Invoke exit handlers */
75 }
76
77 int dtr_rts_arg(const char option)
78 {
79         int val = -1;
80
81         if (optarg) {
82                 switch (optarg[0]) {
83                 case '+': val = +1; break;
84                 case '-': val = -1; break;
85                 default:
86                         fprintf(stderr, "Unknown -%c argument: %s", option, optarg);
87                         exit(1);
88                 }
89         }
90         return val;
91 }
92
93 void exit_on_escapeseq(const char *buf, int len)
94 {
95         static const char escseq[] = "\r~.";
96         static const char *state = escseq+1;
97         int i;
98
99         for (i = 0; i < len; i++) {
100                 if (buf[i] == *state) {
101                         state++;
102                         if (*state == 0)
103                                 exit(0);
104                 } else
105                         state = escseq;
106         }
107 }
108
109
110 int main(int argc, char *argv[])
111 {
112         int fd;
113         char *dev = NULL;
114         int opt;
115         speed_t speed = 0;
116         int dtr = 0, rts = 0;
117         struct termios tio;
118         bool stdin_tty;
119         bool raw = true;
120
121         if ((stdin_tty = isatty(0))) {
122                 CHECK(tcgetattr(0, &stdin_tio_backup));
123                 atexit(restore_stdin_term);
124         }
125
126         while ((opt = getopt(argc, argv, "nd::er::s:v")) != -1) {
127                 switch (opt) {
128                 case 'd': dtr = dtr_rts_arg(opt); break;
129                 case 'e': exit_on_escape = false; break;
130                 case 'n': raw = false; break;
131                 case 'r': rts = dtr_rts_arg(opt); break;
132                 case 's': {
133                         int s = atoi(optarg);
134                         switch (s) {
135 #define S(s) case s: speed = B##s; break;
136                                 S(0);
137                                 S(50);
138                                 S(75);
139                                 S(110);
140                                 S(134);
141                                 S(150);
142                                 S(200);
143                                 S(300);
144                                 S(600);
145                                 S(1200);
146                                 S(1800);
147                                 S(2400);
148                                 S(4800);
149                                 S(9600);
150                                 S(19200);
151                                 S(38400);
152                                 S(57600);
153                                 S(115200);
154                                 S(230400);
155 #undef S
156                         default:
157                                 fprintf(stderr, "Unknown baud rate %d\n", s);
158                                 exit(1);
159                         }
160                         break;
161                 }
162                 case 'v':
163                         verbose = true;
164                         break;
165                 default: /* '?' */
166                         fprintf(stderr, "Usage: %s [-s baudrate] [-v] <device>\n", argv[0]);
167                         exit(1);
168                 }
169         }
170
171         if (optind < argc)
172                 dev = argv[optind];
173
174         if (!dev) {
175                 fprintf(stderr, "No device specified\n");
176                 exit(1);
177         }
178
179         signal(SIGINT, sighandler);
180         signal(SIGTERM, sighandler);
181         signal(SIGHUP, sighandler);
182
183         if (strncmp(dev, "/dev/", 5) == 0 &&
184             strrchr(dev, '/') == dev + 4 &&
185             dev[5] != 0)
186         { /* Create lock file (to be inter-operable with other programs) */
187                 /* This is racy, but what we can do - see also comments in uucp / cu */
188                 int tmp = CHECK(mkstemp(template));
189                 on_exit(rm_file, template);
190                 char pid[20];
191                 snprintf(pid, sizeof(pid), "%u", getpid());
192                 CHECK(write(tmp, pid, strlen(pid)));
193                 close(tmp);
194                 snprintf(lockfile, sizeof(lockfile), "/var/lock/LCK..%s", dev + 5);
195         retry:
196                 if (link(template, lockfile) == -1) {
197                         tmp = CHECK(open(lockfile, O_RDONLY));
198                         CHECK(read(tmp, pid, sizeof(pid)));
199                         close(tmp);
200                         int p = atoi(pid);
201                         char proc[50];
202                         snprintf(proc, sizeof(proc), "/proc/%d", p);
203                         if (access(proc, F_OK) == 0) {
204                                 fprintf(stderr, "%s is used by PID %d\n", dev, p);
205                                 exit(1);
206                         }
207                         fprintf(stderr, "Stale lock file %s (PID %d) - removing it!\n", lockfile, p);
208                         CHECK(unlink(lockfile));
209                         goto retry;
210                 }
211                 rm_file(0, template);
212                 on_exit(rm_file, lockfile);
213         }
214
215         if ((fd = open(dev, O_RDWR)) < 0) {
216                 perror(dev);
217                 exit(1);
218         }
219
220         if (isatty(fd)) {
221                 CHECK(ioctl(fd, TIOCEXCL, NULL));
222
223                 CHECK(tcgetattr(fd, &tio));
224
225                 cfmakeraw(&tio);
226
227                 if (speed) {
228                         CHECK(cfsetospeed(&tio, speed));
229                         CHECK(cfsetispeed(&tio, speed));
230                 }
231
232                 if (dtr || rts) {
233                         int status;
234                         /* tio.c_cflag &= ~HUPCL; */ /* Don't lower DTR/RTS on close */
235
236                         CHECK(ioctl(fd, TIOCMGET, &status));
237                         if (dtr == -1) status &= ~TIOCM_DTR;
238                         if (dtr == +1) status |=  TIOCM_DTR;
239                         if (rts == -1) status &= ~TIOCM_RTS;
240                         if (rts == +1) status |=  TIOCM_RTS;
241                         CHECK(ioctl(fd, TIOCMSET, &status));
242                 }
243
244                 CHECK(tcsetattr(fd, TCSANOW, &tio));
245         } else if (speed || dtr || rts) {
246                 fprintf(stderr, "Cannot set speed, DTR or RTS on non-terminal %s\n", dev);
247                 exit(1);
248         }
249
250         struct pollfd fds[2] = {
251                 { .fd = 0,  .events = POLLIN },
252                 { .fd = fd, .events = POLLIN },
253         };
254         char buf[4096];
255
256         if (stdin_tty) {
257                 tio = stdin_tio_backup;
258                 if (raw)
259                         cfmakeraw(&tio);
260                 CHECK(tcsetattr(0, TCSANOW, &tio));
261         }
262
263         VERBOSE("Connected.\n");
264         while (1) {
265                 int r1, r2;
266                 CHECK(poll(fds, 2, -1));
267                 if (fds[0].revents & POLLIN) {
268                         r1 = CHECK(read(0, buf, sizeof(buf)));
269                         if (r1 == 0) {
270                                 VERBOSE("EOF on stdin\n");
271                                 break;
272                         }
273                         if (exit_on_escape)
274                                 exit_on_escapeseq(buf, r1);
275                         r2 = CHECK(write(fd, buf, r1));
276                         if (r1 != r2) {
277                                 fprintf(stderr, "Not all data written to %s (%d/%d)\n", dev, r1, r2);
278                                 exit(1);
279                         }
280                 }
281                 if (fds[1].revents & POLLIN) {
282                         r1 = CHECK(read(fd, buf, sizeof(buf)));
283                         if (r1 == 0) {
284                                 VERBOSE("EOF on %s\n", dev);
285                                 break;
286                         }
287                         r2 = CHECK(write(1, buf, r1));
288                         if (r1 != r2) {
289                                 fprintf(stderr, "Not all data written to stdout (%d/%d)\n", r1, r2);
290                                 exit(1);
291                         }
292                 }
293         }
294         return 0;
295 }