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