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