]> rtime.felk.cvut.cz Git - sojka/sterm.git/blob - sterm.c
Teach shell completions about the -t option
[sojka/sterm.git] / sterm.c
1 /*
2  * Simple serial terminal
3  *
4  * Copyright 2014, 2015, 2016, 2017, 2019, 2020 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 #define _DEFAULT_SOURCE
34 #define _GNU_SOURCE
35 #include <sys/ioctl.h>
36 #include <sys/types.h>
37 #include <unistd.h>
38 #include <fcntl.h>
39 #include <termios.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <getopt.h>
43 #include <poll.h>
44 #include <stdbool.h>
45 #include <stdint.h>
46 #include <string.h>
47 #include <signal.h>
48 #ifdef HAVE_LOCKDEV
49 #include <lockdev.h>
50 #endif
51 #include <sys/file.h>
52 #include <time.h>
53 #include <errno.h>
54
55 #define STRINGIFY(val) #val
56 #define TOSTRING(val) STRINGIFY(val)
57 #define CHECK(cmd) ({ int ret = (cmd); if (ret == -1) { perror(#cmd " line " TOSTRING(__LINE__)); exit(1); }; ret; })
58 #define CHECKPTR(cmd) ({ void *ptr = (cmd); if (ptr == (void*)-1) { perror(#cmd " line " TOSTRING(__LINE__)); exit(1); }; ptr; })
59 #define CHECKNULL(cmd) ({ void *ptr = (cmd); if (ptr == NULL) { perror(#cmd " line " TOSTRING(__LINE__)); exit(1); }; ptr; })
60
61 #define VERBOSE(format, ...) do { if (verbose) fprintf(stderr, "sterm: " format, ##__VA_ARGS__); } while (0)
62
63 #define MAX(X, Y) (((X) > (Y)) ? (X) : (Y))
64
65 bool verbose = false;
66 bool exit_on_escape = true;
67
68 struct termios stdin_tio_backup;
69 char *dev = NULL;
70
71 void rm_file(int status, void *arg)
72 {
73         char *fn = arg;
74         if (fn[0])
75                 unlink(fn);
76         fn[0] = 0;
77 }
78
79 void restore_stdin_term()
80 {
81         tcsetattr(0, TCSANOW, &stdin_tio_backup);
82 }
83
84 #ifdef HAVE_LOCKDEV
85 void unlock()
86 {
87         dev_unlock(dev, getpid());
88 }
89 #endif
90
91 void sighandler(int arg)
92 {
93         exit(0); /* Invoke exit handlers */
94 }
95
96 int dtr_rts_arg(const char option, const char *optarg)
97 {
98         int val = -1;
99
100         if (optarg) {
101                 char *end;
102                 val = strtol(optarg, &end, 10);
103                 if (end == optarg) {
104                         /* Not a number */
105                         switch (optarg[0]) {
106                         case '+': val = +1; break;
107                         case '-': val = -1; break;
108                         default:
109                                 fprintf(stderr, "Unknown -%c argument: %s\n", option, optarg);
110                                 exit(1);
111                         }
112                 }
113         }
114         return val;
115 }
116
117 // See DSR and CPR at
118 // https://en.wikipedia.org/wiki/ANSI_escape_code#Terminal_output_sequences
119 bool is_cpr_control_seq(char c)
120 {
121         static enum state { CSI_ESC, CSI_BRACKET, PAR_N, PAR_M, FIN_R } state;
122
123         switch (state) {
124         case CSI_ESC:      state = (c == 0x1b) ? CSI_BRACKET : CSI_ESC; break;
125         case CSI_BRACKET:  state = (c == '[')  ? PAR_N : CSI_ESC; break;
126         case PAR_N:        state = (c == ';')  ? PAR_M : (c >= '0' && c <= '9' ? PAR_N : CSI_ESC); break;
127         case PAR_M:        state = (c == 'R')  ? FIN_R : (c >= '0' && c <= '9' ? PAR_M : CSI_ESC); break;
128         case FIN_R: break;
129         }
130         if (state == FIN_R) {
131                 state = CSI_ESC;
132                 return true;
133
134         } else
135                 return state != CSI_ESC;
136 }
137
138 void exit_on_escapeseq(const char *buf, int len)
139 {
140         static const char escseq[] = "\r~.";
141         static const char *state = escseq+1;
142         int i;
143         for (i = 0; i < len; i++) {
144                 if (is_cpr_control_seq(buf[i]))
145                         continue;
146                 if (buf[i] == *state) {
147                         state++;
148                         if (*state == 0)
149                                 exit(0);
150                 } else {
151                         state = escseq;
152                         if (buf[i] == *state)
153                                 state++;
154                 }
155         }
156 }
157
158 void usage(const char* argv0)
159 {
160         fprintf(stderr, "Usage: %s [options] <device>\n", argv0);
161         fprintf(stderr,
162                 "Options:\n"
163                 "  -b <duration> send break signal\n"
164                 "  -c        enter command mode\n"
165                 "  -d[PULSE] make pulse on DTR\n"
166                 "  -e        ignore '~.' escape sequence\n"
167                 "  -n        do not switch stdin TTY to raw mode\n"
168                 "  -r[PULSE] make pulse on RTS\n"
169                 "  -s <baudrate>\n"
170                 "  -t <ms>   minimum delay between two transmitted characters\n"
171                 "  -v        verbose mode\n"
172                 "\n"
173                 "PULSE is a number specifying the pulse. Absolute value defines the\n"
174                 "length of the pulse in milliseconds, sign determines the polarity of\n"
175                 "the pulse. Alternatively, PULSE can be either '+' or '-', which\n"
176                 "corresponds to +1 or -1.\n"
177                 );
178 }
179
180 void pulse(int fd, int dtr, int rts)
181 {
182         int status, ms = 0;
183         /* tio.c_cflag &= ~HUPCL; */ /* Don't lower DTR/RTS on close */
184
185         CHECK(ioctl(fd, TIOCMGET, &status));
186         if (dtr > 0) { status &= ~TIOCM_DTR; ms = +dtr; }
187         if (dtr < 0) { status |=  TIOCM_DTR; ms = -dtr; }
188         if (rts > 0) { status &= ~TIOCM_RTS; ms = +rts; }
189         if (rts < 0) { status |=  TIOCM_RTS; ms = -rts; }
190         CHECK(ioctl(fd, TIOCMSET, &status));
191
192         usleep(ms*1000);
193
194         if (dtr < 0) { status &= ~TIOCM_DTR; }
195         if (dtr > 0) { status |=  TIOCM_DTR; }
196         if (rts < 0) { status &= ~TIOCM_RTS; }
197         if (rts > 0) { status |=  TIOCM_RTS; }
198         CHECK(ioctl(fd, TIOCMSET, &status));
199 }
200
201 void handle_commands(int fd)
202 {
203         char command[100];
204         bool go = false;
205
206         while (!go) {
207                 char *p1 = NULL;
208                 int num;
209                 if (fgets(command, sizeof(command), stdin) == NULL) {
210                         if (!feof(stdin))
211                             perror("Command read");
212                         exit(1);
213                 }
214                 if (sscanf(command, "dtr %ms", &p1) == 1)
215                         pulse(fd, dtr_rts_arg('d', p1), 0);
216                 else if (sscanf(command, "rts %ms", &p1) == 1)
217                         pulse(fd, 0, dtr_rts_arg('r', p1));
218                 else if (sscanf(command, "break %d", &num) == 1)
219                         CHECK(tcsendbreak(fd, num));
220                 else if (strcmp(command, "go\n") == 0)
221                         break;
222                 else if (strcmp(command, "exit\n") == 0)
223                         exit(0);
224                 else {
225                         fprintf(stderr, "Unknown command: %s\n", command);
226                         exit(1);
227                 }
228
229                 free(p1);
230         }
231 }
232
233 static int64_t now_us()
234 {
235         struct timespec ts;
236         CHECK(clock_gettime(CLOCK_MONOTONIC, &ts));
237         return ts.tv_sec * 1000000 + ts.tv_nsec / 1000;
238 }
239
240 int main(int argc, char *argv[])
241 {
242         int fd;
243         int opt;
244         speed_t speed = 0;
245         int dtr = 0, rts = 0;
246         struct termios tio;
247         bool stdin_tty;
248         bool raw = true;
249         bool cmd = false;
250         int break_dur = -1;
251         int tx_delay_ms = 0;
252
253         if ((stdin_tty = isatty(0))) {
254                 CHECK(tcgetattr(0, &stdin_tio_backup));
255                 atexit(restore_stdin_term);
256         }
257
258         while ((opt = getopt(argc, argv, "b:cnd::er::s:vt:")) != -1) {
259                 switch (opt) {
260                 case 'b': break_dur = atoi(optarg); break;
261                 case 'c': cmd = true; break;
262                 case 'd': dtr = dtr_rts_arg(opt, optarg); break;
263                 case 'e': exit_on_escape = false; break;
264                 case 'n': raw = false; break;
265                 case 'r': rts = dtr_rts_arg(opt, optarg); break;
266                 case 's': {
267                         int s = atoi(optarg);
268                         switch (s) {
269 #define S(s) case s: speed = B##s; break;
270                                 S(0);
271                                 S(50);
272                                 S(75);
273                                 S(110);
274                                 S(134);
275                                 S(150);
276                                 S(200);
277                                 S(300);
278                                 S(600);
279                                 S(1200);
280                                 S(1800);
281                                 S(2400);
282                                 S(4800);
283                                 S(9600);
284                                 S(19200);
285                                 S(38400);
286                                 S(57600);
287                                 S(115200);
288                                 S(230400);
289                                 S(460800);
290                                 S(500000);
291                                 S(576000);
292                                 S(921600);
293                                 S(1000000);
294                                 S(1152000);
295                                 S(1500000);
296                                 S(2000000);
297                                 S(2500000);
298                                 S(3000000);
299                                 S(3500000);
300                                 S(4000000);
301 #undef S
302                         default:
303                                 fprintf(stderr, "Unknown baud rate %d\n", s);
304                                 exit(1);
305                         }
306                         break;
307                 }
308                 case 't':
309                         tx_delay_ms = atoi(optarg);
310                         break;
311                 case 'v':
312                         verbose = true;
313                         break;
314                 default: /* '?' */
315                         usage(argv[0]);
316                         exit(1);
317                 }
318         }
319
320         if (optind < argc)
321                 dev = argv[optind];
322
323         if (!dev) {
324                 fprintf(stderr, "No device specified\n");
325                 usage(argv[0]);
326                 exit(1);
327         }
328
329         signal(SIGINT, sighandler);
330         signal(SIGTERM, sighandler);
331         signal(SIGHUP, sighandler);
332
333 #ifdef HAVE_LOCKDEV
334         pid_t pid = dev_lock(dev);
335         if (pid > 0) {
336                 fprintf(stderr, "%s is used by PID %d\n", dev, pid);
337                 exit(1);
338         } else if (pid < 0) {
339                 char *msg;
340                 asprintf(&msg, "dev_lock('%s')", dev); /* No free() because we exit() immediately */
341                 if (errno)
342                         perror(msg);
343                 else
344                         fprintf(stderr, "%s: Error\n", msg);
345                 exit(1);
346         }
347         atexit(unlock);
348 #endif
349
350         /* O_NONBLOCK is needed to not wait for the CDC signal. See tty_ioctl(4). */
351         if ((fd = open(dev, O_RDWR|O_NOCTTY|O_NONBLOCK)) < 0) {
352                 perror(dev);
353                 exit(1);
354         }
355         /* Cancel the efect of O_NONBLOCK flag. */
356         int n = fcntl(fd, F_GETFL, 0);
357         fcntl(fd, F_SETFL, n & ~O_NDELAY);
358
359         flock(fd, LOCK_EX);
360
361         if (isatty(fd)) {
362                 CHECK(ioctl(fd, TIOCEXCL, NULL));
363
364                 CHECK(tcgetattr(fd, &tio));
365
366                 cfmakeraw(&tio);
367
368                 if (speed) {
369                         CHECK(cfsetospeed(&tio, speed));
370                         CHECK(cfsetispeed(&tio, speed));
371                 }
372
373                 if (dtr || rts)
374                         pulse(fd, dtr, rts);
375
376                 if (break_dur != -1)
377                         CHECK(tcsendbreak(fd, break_dur));
378
379                  /* Disable flow control */
380                 tio.c_cflag &= ~(CRTSCTS);
381                 tio.c_iflag &= ~(IXON|IXOFF);
382
383                 CHECK(tcsetattr(fd, TCSANOW, &tio));
384         } else if (speed || dtr || rts) {
385                 fprintf(stderr, "Cannot set speed, DTR or RTS on non-terminal %s\n", dev);
386                 exit(1);
387         }
388
389         VERBOSE("Connected.\r\n");
390
391         if (cmd)
392                 handle_commands(fd);
393
394
395         enum { STDIN, DEV };
396         struct pollfd fds[2] = {
397                 [STDIN] = { .fd = STDIN_FILENO,  .events = POLLIN },
398                 [DEV]   = { .fd = fd,            .events = POLLIN },
399         };
400
401         if (stdin_tty) {
402                 tio = stdin_tio_backup;
403                 if (raw)
404                         cfmakeraw(&tio);
405                 CHECK(tcsetattr(0, TCSANOW, &tio));
406         }
407
408         if (exit_on_escape)
409                 VERBOSE("Use '<Enter>~.' sequence to exit.\r\n");
410
411         char buf2dev[4096];
412         int buf_len = 0, buf_idx = 0;
413         int64_t last_tx_us = 0;
414         while (1) {
415                 int timeout = (tx_delay_ms == 0 || buf_len == 0)
416                         ? -1
417                         : MAX(0, tx_delay_ms - (now_us() - last_tx_us) / 1000);
418
419                 CHECK(poll(fds, 2, timeout));
420                 if (fds[STDIN].revents & POLLIN && buf_len == 0) {
421                         buf_len = CHECK(read(STDIN_FILENO, buf2dev, sizeof(buf2dev)));
422                         if (buf_len == 0) {
423                                 VERBOSE("EOF on stdin\r\n");
424                                 break;
425                         }
426                         buf_idx = 0;
427                         if (exit_on_escape)
428                                 exit_on_escapeseq(buf2dev, buf_len);
429                 }
430                 if (buf_len > 0) {
431                         int wlen = 0;
432                         bool short_write = false;
433                         if (tx_delay_ms == 0) {
434                                 wlen = CHECK(write(fd, buf2dev, buf_len));
435                                 short_write = wlen != buf_len;
436
437                         } else {
438                                 int64_t now = now_us();
439                                 if (now - last_tx_us >= tx_delay_ms * 1000) {
440                                         wlen = CHECK(write(fd, &buf2dev[buf_idx], 1));
441                                         short_write = wlen != 1;
442                                         last_tx_us = now;
443                                 }
444                         }
445                         if (short_write) {
446                                 fprintf(stderr, "Not all data written to %s (%d/%d)\n", dev, buf_len, wlen);
447                                 exit(1);
448                         }
449                         buf_idx += wlen;
450                         if (buf_idx >= buf_len)
451                                 buf_len = 0;
452                 }
453                 if (fds[STDIN].revents & POLLHUP) {
454                         VERBOSE("HUP on stdin\r\n");
455                         break;
456                 }
457                 if (fds[DEV].revents & POLLIN) {
458                         char buf[1024];
459                         int rlen, wlen;
460                         rlen = CHECK(read(fd, buf, sizeof(buf)));
461                         if (rlen == 0) {
462                                 VERBOSE("EOF on %s\r\n", dev);
463                                 break;
464                         }
465                         wlen = CHECK(write(STDOUT_FILENO, buf, rlen));
466                         if (rlen != wlen) {
467                                 fprintf(stderr, "Not all data written to stdout (%d/%d)\n", wlen, rlen);
468                                 exit(1);
469                         }
470                 }
471         }
472         return 0;
473 }