]> rtime.felk.cvut.cz Git - sojka/sterm.git/blob - sterm.c
Print more descriptive error message
[sojka/sterm.git] / sterm.c
1 /*
2  * Simple serial terminal
3  *
4  * Copyright 2014, 2015, 2016, 2017 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 <string.h>
46 #include <signal.h>
47 #include <lockdev.h>
48 #include <errno.h>
49
50 #define STRINGIFY(val) #val
51 #define TOSTRING(val) STRINGIFY(val)
52 #define CHECK(cmd) ({ int ret = (cmd); if (ret == -1) { perror(#cmd " line " TOSTRING(__LINE__)); exit(1); }; ret; })
53 #define CHECKPTR(cmd) ({ void *ptr = (cmd); if (ptr == (void*)-1) { perror(#cmd " line " TOSTRING(__LINE__)); exit(1); }; ptr; })
54 #define CHECKNULL(cmd) ({ void *ptr = (cmd); if (ptr == NULL) { perror(#cmd " line " TOSTRING(__LINE__)); exit(1); }; ptr; })
55
56 #define VERBOSE(format, ...) do { if (verbose) fprintf(stderr, "sterm: " format, ##__VA_ARGS__); } while (0)
57
58 bool verbose = false;
59 bool exit_on_escape = true;
60
61 struct termios stdin_tio_backup;
62 char *dev = NULL;
63
64 void rm_file(int status, void *arg)
65 {
66         char *fn = arg;
67         if (fn[0])
68                 unlink(fn);
69         fn[0] = 0;
70 }
71
72 void restore_stdin_term()
73 {
74         tcsetattr(0, TCSANOW, &stdin_tio_backup);
75 }
76
77 void unlock()
78 {
79         dev_unlock(dev, getpid());
80 }
81
82 void sighandler(int arg)
83 {
84         exit(0); /* Invoke exit handlers */
85 }
86
87 int dtr_rts_arg(const char option, const char *optarg)
88 {
89         int val = -1;
90
91         if (optarg) {
92                 char *end;
93                 val = strtol(optarg, &end, 10);
94                 if (end == optarg) {
95                         /* Not a number */
96                         switch (optarg[0]) {
97                         case '+': val = +1; break;
98                         case '-': val = -1; break;
99                         default:
100                                 fprintf(stderr, "Unknown -%c argument: %s\n", option, optarg);
101                                 exit(1);
102                         }
103                 }
104         }
105         return val;
106 }
107
108 void exit_on_escapeseq(const char *buf, int len)
109 {
110         static const char escseq[] = "\r~.";
111         static const char *state = escseq+1;
112         int i;
113         for (i = 0; i < len; i++) {
114                 if (buf[i] == *state) {
115                         state++;
116                         if (*state == 0)
117                                 exit(0);
118                 } else {
119                         state = escseq;
120                         if (buf[i] == *state)
121                                 state++;
122                 }
123         }
124 }
125
126 void usage(const char* argv0)
127 {
128         fprintf(stderr, "Usage: %s [options] <device>\n", argv0);
129         fprintf(stderr,
130                 "Options:\n"
131                 "  -c        enter command mode\n"
132                 "  -d[PULSE] make pulse on DTR\n"
133                 "  -e        ignore '~.' escape sequence\n"
134                 "  -n        do not switch the device to raw mode\n"
135                 "  -r[PULSE] make pulse on RTS\n"
136                 "  -s <baudrate>\n"
137                 "  -v        verbose mode\n"
138                 "\n"
139                 "PULSE is a number specifying the pulse. Absolute value defines the\n"
140                 "length of the pulse in milliseconds, sign determines the polarity of\n"
141                 "the pulse. Alternatively, PULSE can be either '+' or '-', which\n"
142                 "corresponds to +1 or -1.\n"
143                 );
144 }
145
146 void pulse(int fd, int dtr, int rts)
147 {
148         int status, ms = 0;
149         /* tio.c_cflag &= ~HUPCL; */ /* Don't lower DTR/RTS on close */
150
151         CHECK(ioctl(fd, TIOCMGET, &status));
152         if (dtr > 0) { status &= ~TIOCM_DTR; ms = +dtr; }
153         if (dtr < 0) { status |=  TIOCM_DTR; ms = -dtr; }
154         if (rts > 0) { status &= ~TIOCM_RTS; ms = +rts; }
155         if (rts < 0) { status |=  TIOCM_RTS; ms = -rts; }
156         CHECK(ioctl(fd, TIOCMSET, &status));
157
158         usleep(ms*1000);
159
160         if (dtr < 0) { status &= ~TIOCM_DTR; }
161         if (dtr > 0) { status |=  TIOCM_DTR; }
162         if (rts < 0) { status &= ~TIOCM_RTS; }
163         if (rts > 0) { status |=  TIOCM_RTS; }
164         CHECK(ioctl(fd, TIOCMSET, &status));
165 }
166
167 void handle_commands(int fd)
168 {
169         char command[100];
170         bool go = false;
171
172         while (!go) {
173                 char *p1 = NULL;
174                 if (fgets(command, sizeof(command), stdin) == NULL) {
175                         if (!feof(stdin))
176                             perror("Command read");
177                         exit(1);
178                 }
179                 if (sscanf(command, "dtr %ms", &p1) == 1)
180                         pulse(fd, dtr_rts_arg('d', p1), 0);
181                 else if (sscanf(command, "rts %ms", &p1) == 1)
182                         pulse(fd, 0, dtr_rts_arg('r', p1));
183                 else if (strcmp(command, "go\n") == 0)
184                         break;
185                 else {
186                         fprintf(stderr, "Unknown command: %s\n", command);
187                         exit(1);
188                 }
189
190                 free(p1);
191         }
192 }
193
194 int main(int argc, char *argv[])
195 {
196         int fd;
197         int opt;
198         speed_t speed = 0;
199         int dtr = 0, rts = 0;
200         struct termios tio;
201         bool stdin_tty;
202         bool raw = true;
203         bool cmd = false;
204
205         if ((stdin_tty = isatty(0))) {
206                 CHECK(tcgetattr(0, &stdin_tio_backup));
207                 atexit(restore_stdin_term);
208         }
209
210         while ((opt = getopt(argc, argv, "cnd::er::s:v")) != -1) {
211                 switch (opt) {
212                 case 'c': cmd = true; break;
213                 case 'd': dtr = dtr_rts_arg(opt, optarg); break;
214                 case 'e': exit_on_escape = false; break;
215                 case 'n': raw = false; break;
216                 case 'r': rts = dtr_rts_arg(opt, optarg); break;
217                 case 's': {
218                         int s = atoi(optarg);
219                         switch (s) {
220 #define S(s) case s: speed = B##s; break;
221                                 S(0);
222                                 S(50);
223                                 S(75);
224                                 S(110);
225                                 S(134);
226                                 S(150);
227                                 S(200);
228                                 S(300);
229                                 S(600);
230                                 S(1200);
231                                 S(1800);
232                                 S(2400);
233                                 S(4800);
234                                 S(9600);
235                                 S(19200);
236                                 S(38400);
237                                 S(57600);
238                                 S(115200);
239                                 S(230400);
240 #undef S
241                         default:
242                                 fprintf(stderr, "Unknown baud rate %d\n", s);
243                                 exit(1);
244                         }
245                         break;
246                 }
247                 case 'v':
248                         verbose = true;
249                         break;
250                 default: /* '?' */
251                         usage(argv[0]);
252                         exit(1);
253                 }
254         }
255
256         if (optind < argc)
257                 dev = argv[optind];
258
259         if (!dev) {
260                 fprintf(stderr, "No device specified\n");
261                 usage(argv[0]);
262                 exit(1);
263         }
264
265         signal(SIGINT, sighandler);
266         signal(SIGTERM, sighandler);
267         signal(SIGHUP, sighandler);
268
269         pid_t pid = dev_lock(dev);
270         if (pid > 0) {
271                 fprintf(stderr, "%s is used by PID %d\n", dev, pid);
272                 exit(1);
273         } else if (pid < 0) {
274                 char *msg;
275                 asprintf(&msg, "dev_lock('%s')", dev); /* No free() because we exit() immediately */
276                 if (errno)
277                         perror(msg);
278                 else
279                         fprintf(stderr, "%s: Error\n", msg);
280                 exit(1);
281         }
282         atexit(unlock);
283
284         /* O_NONBLOCK is needed to not wait for the CDC signal. See tty_ioctl(4). */
285         if ((fd = open(dev, O_RDWR|O_NOCTTY|O_NONBLOCK)) < 0) {
286                 perror(dev);
287                 exit(1);
288         }
289         /* Cancel the efect of O_NONBLOCK flag. */
290         int n = fcntl(fd, F_GETFL, 0);
291         fcntl(fd, F_SETFL, n & ~O_NDELAY);
292
293         if (isatty(fd)) {
294                 CHECK(ioctl(fd, TIOCEXCL, NULL));
295
296                 CHECK(tcgetattr(fd, &tio));
297
298                 cfmakeraw(&tio);
299
300                 if (speed) {
301                         CHECK(cfsetospeed(&tio, speed));
302                         CHECK(cfsetispeed(&tio, speed));
303                 }
304
305                 if (dtr || rts)
306                         pulse(fd, dtr, rts);
307
308                  /* Disable flow control */
309                 tio.c_cflag &= ~(CRTSCTS);
310                 tio.c_iflag &= ~(IXON|IXOFF);
311
312                 CHECK(tcsetattr(fd, TCSANOW, &tio));
313         } else if (speed || dtr || rts) {
314                 fprintf(stderr, "Cannot set speed, DTR or RTS on non-terminal %s\n", dev);
315                 exit(1);
316         }
317
318         VERBOSE("Connected.\r\n");
319
320         if (cmd)
321                 handle_commands(fd);
322
323         struct pollfd fds[2] = {
324                 { .fd = 0,  .events = POLLIN },
325                 { .fd = fd, .events = POLLIN },
326         };
327         char buf[4096];
328
329         if (stdin_tty) {
330                 tio = stdin_tio_backup;
331                 if (raw)
332                         cfmakeraw(&tio);
333                 CHECK(tcsetattr(0, TCSANOW, &tio));
334         }
335
336         if (exit_on_escape)
337                 VERBOSE("Use '<Enter>~.' sequence to exit.\r\n");
338
339         while (1) {
340                 int r1, r2;
341                 CHECK(poll(fds, 2, -1));
342                 if (fds[0].revents & POLLIN) {
343                         r1 = CHECK(read(0, buf, sizeof(buf)));
344                         if (r1 == 0) {
345                                 VERBOSE("EOF on stdin\r\n");
346                                 break;
347                         }
348                         if (exit_on_escape)
349                                 exit_on_escapeseq(buf, r1);
350                         r2 = CHECK(write(fd, buf, r1));
351                         if (r1 != r2) {
352                                 fprintf(stderr, "Not all data written to %s (%d/%d)\n", dev, r1, r2);
353                                 exit(1);
354                         }
355                 }
356                 if (fds[1].revents & POLLIN) {
357                         r1 = CHECK(read(fd, buf, sizeof(buf)));
358                         if (r1 == 0) {
359                                 VERBOSE("EOF on %s\r\n", dev);
360                                 break;
361                         }
362                         r2 = CHECK(write(1, buf, r1));
363                         if (r1 != r2) {
364                                 fprintf(stderr, "Not all data written to stdout (%d/%d)\n", r1, r2);
365                                 exit(1);
366                         }
367                 }
368         }
369         return 0;
370 }