]> rtime.felk.cvut.cz Git - sojka/sterm.git/blob - sterm.c
Debian release
[sojka/sterm.git] / 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 <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                 switch (optarg[0]) {
89                 case '+': val = +1; break;
90                 case '-': val = -1; break;
91                 default:
92                         fprintf(stderr, "Unknown -%c argument: %s", option, optarg);
93                         exit(1);
94                 }
95         }
96         return val;
97 }
98
99 void exit_on_escapeseq(const char *buf, int len)
100 {
101         static const char escseq[] = "\r~.";
102         static const char *state = escseq+1;
103         int i;
104
105         for (i = 0; i < len; i++) {
106                 if (buf[i] == *state) {
107                         state++;
108                         if (*state == 0)
109                                 exit(0);
110                 } else
111                         state = escseq;
112         }
113 }
114
115 void usage(const char* argv0)
116 {
117         fprintf(stderr, "Usage: %s [options] <device>\n", argv0);
118         fprintf(stderr, "Options:\n");
119         fprintf(stderr, "  -d [+|-] create short positive/negative pulse on DTR\n");
120         fprintf(stderr, "  -e       ignore '~.' escape sequence\n");
121         fprintf(stderr, "  -n       do not switch the device to raw mode\n");
122         fprintf(stderr, "  -r [+|-] create short positive/negative pulse on RTS\n");
123         fprintf(stderr, "  -s <baudrate>\n");
124         fprintf(stderr, "  -v       verbose\n");
125 }
126
127 int main(int argc, char *argv[])
128 {
129         int fd;
130         int opt;
131         speed_t speed = 0;
132         int dtr = 0, rts = 0;
133         struct termios tio;
134         bool stdin_tty;
135         bool raw = true;
136
137         if ((stdin_tty = isatty(0))) {
138                 CHECK(tcgetattr(0, &stdin_tio_backup));
139                 atexit(restore_stdin_term);
140         }
141
142         while ((opt = getopt(argc, argv, "nd::er::s:v")) != -1) {
143                 switch (opt) {
144                 case 'd': dtr = dtr_rts_arg(opt); break;
145                 case 'e': exit_on_escape = false; break;
146                 case 'n': raw = false; break;
147                 case 'r': rts = dtr_rts_arg(opt); break;
148                 case 's': {
149                         int s = atoi(optarg);
150                         switch (s) {
151 #define S(s) case s: speed = B##s; break;
152                                 S(0);
153                                 S(50);
154                                 S(75);
155                                 S(110);
156                                 S(134);
157                                 S(150);
158                                 S(200);
159                                 S(300);
160                                 S(600);
161                                 S(1200);
162                                 S(1800);
163                                 S(2400);
164                                 S(4800);
165                                 S(9600);
166                                 S(19200);
167                                 S(38400);
168                                 S(57600);
169                                 S(115200);
170                                 S(230400);
171 #undef S
172                         default:
173                                 fprintf(stderr, "Unknown baud rate %d\n", s);
174                                 exit(1);
175                         }
176                         break;
177                 }
178                 case 'v':
179                         verbose = true;
180                         break;
181                 default: /* '?' */
182                         usage(argv[0]);
183                         exit(1);
184                 }
185         }
186
187         if (optind < argc)
188                 dev = argv[optind];
189
190         if (!dev) {
191                 fprintf(stderr, "No device specified\n");
192                 usage(argv[0]);
193                 exit(1);
194         }
195
196         signal(SIGINT, sighandler);
197         signal(SIGTERM, sighandler);
198         signal(SIGHUP, sighandler);
199
200         pid_t pid = dev_lock(dev);
201         if (pid > 0) {
202                 fprintf(stderr, "%s is used by PID %d\n", dev, pid);
203                 exit(1);
204         } else if (pid < 0) {
205                 perror("dev_lock()");
206                 exit(1);
207         }
208         atexit(unlock);
209
210         if ((fd = open(dev, O_RDWR)) < 0) {
211                 perror(dev);
212                 exit(1);
213         }
214
215         if (isatty(fd)) {
216                 CHECK(ioctl(fd, TIOCEXCL, NULL));
217
218                 CHECK(tcgetattr(fd, &tio));
219
220                 cfmakeraw(&tio);
221
222                 if (speed) {
223                         CHECK(cfsetospeed(&tio, speed));
224                         CHECK(cfsetispeed(&tio, speed));
225                 }
226
227                 if (dtr || rts) {
228                         int status;
229                         /* tio.c_cflag &= ~HUPCL; */ /* Don't lower DTR/RTS on close */
230
231                         CHECK(ioctl(fd, TIOCMGET, &status));
232                         if (dtr == -1) status &= ~TIOCM_DTR;
233                         if (dtr == +1) status |=  TIOCM_DTR;
234                         if (rts == -1) status &= ~TIOCM_RTS;
235                         if (rts == +1) status |=  TIOCM_RTS;
236                         CHECK(ioctl(fd, TIOCMSET, &status));
237                 }
238
239                 CHECK(tcsetattr(fd, TCSANOW, &tio));
240         } else if (speed || dtr || rts) {
241                 fprintf(stderr, "Cannot set speed, DTR or RTS on non-terminal %s\n", dev);
242                 exit(1);
243         }
244
245         struct pollfd fds[2] = {
246                 { .fd = 0,  .events = POLLIN },
247                 { .fd = fd, .events = POLLIN },
248         };
249         char buf[4096];
250
251         if (stdin_tty) {
252                 tio = stdin_tio_backup;
253                 if (raw)
254                         cfmakeraw(&tio);
255                 CHECK(tcsetattr(0, TCSANOW, &tio));
256         }
257
258         VERBOSE("Connected.\r\n");
259         if (exit_on_escape)
260                 VERBOSE("Use '<Enter>~.' sequence to exit.\r\n");
261
262         while (1) {
263                 int r1, r2;
264                 CHECK(poll(fds, 2, -1));
265                 if (fds[0].revents & POLLIN) {
266                         r1 = CHECK(read(0, buf, sizeof(buf)));
267                         if (r1 == 0) {
268                                 VERBOSE("EOF on stdin\r\n");
269                                 break;
270                         }
271                         if (exit_on_escape)
272                                 exit_on_escapeseq(buf, r1);
273                         r2 = CHECK(write(fd, buf, r1));
274                         if (r1 != r2) {
275                                 fprintf(stderr, "Not all data written to %s (%d/%d)\n", dev, r1, r2);
276                                 exit(1);
277                         }
278                 }
279                 if (fds[1].revents & POLLIN) {
280                         r1 = CHECK(read(fd, buf, sizeof(buf)));
281                         if (r1 == 0) {
282                                 VERBOSE("EOF on %s\r\n", dev);
283                                 break;
284                         }
285                         r2 = CHECK(write(1, buf, r1));
286                         if (r1 != r2) {
287                                 fprintf(stderr, "Not all data written to stdout (%d/%d)\n", r1, r2);
288                                 exit(1);
289                         }
290                 }
291         }
292         return 0;
293 }