xref: /openbmc/qemu/chardev/char-pty.c (revision 13b5ae94)
1 /*
2  * QEMU System Emulator
3  *
4  * Copyright (c) 2003-2008 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 
25 #include "qemu/osdep.h"
26 #include "qapi/error.h"
27 #include "chardev/char.h"
28 #include "io/channel-file.h"
29 #include "qemu/sockets.h"
30 #include "qemu/error-report.h"
31 #include "qemu/module.h"
32 #include "qemu/qemu-print.h"
33 
34 #include "chardev/char-io.h"
35 #include "qom/object.h"
36 
37 struct PtyChardev {
38     Chardev parent;
39     QIOChannel *ioc;
40     int read_bytes;
41 
42     int connected;
43     GSource *timer_src;
44 };
45 typedef struct PtyChardev PtyChardev;
46 
47 DECLARE_INSTANCE_CHECKER(PtyChardev, PTY_CHARDEV,
48                          TYPE_CHARDEV_PTY)
49 
50 static void pty_chr_state(Chardev *chr, int connected);
51 
52 static void pty_chr_timer_cancel(PtyChardev *s)
53 {
54     if (s->timer_src) {
55         g_source_destroy(s->timer_src);
56         g_source_unref(s->timer_src);
57         s->timer_src = NULL;
58     }
59 }
60 
61 static gboolean pty_chr_timer(gpointer opaque)
62 {
63     struct Chardev *chr = CHARDEV(opaque);
64     PtyChardev *s = PTY_CHARDEV(opaque);
65 
66     pty_chr_timer_cancel(s);
67     if (!s->connected) {
68         /* Next poll ... */
69         qemu_chr_be_update_read_handlers(chr, chr->gcontext);
70     }
71     return FALSE;
72 }
73 
74 static void pty_chr_rearm_timer(Chardev *chr, int ms)
75 {
76     PtyChardev *s = PTY_CHARDEV(chr);
77     char *name;
78 
79     pty_chr_timer_cancel(s);
80     name = g_strdup_printf("pty-timer-%s", chr->label);
81     s->timer_src = qemu_chr_timeout_add_ms(chr, ms, pty_chr_timer, chr);
82     g_source_set_name(s->timer_src, name);
83     g_free(name);
84 }
85 
86 static void pty_chr_update_read_handler(Chardev *chr)
87 {
88     PtyChardev *s = PTY_CHARDEV(chr);
89     GPollFD pfd;
90     int rc;
91     QIOChannelFile *fioc = QIO_CHANNEL_FILE(s->ioc);
92 
93     pfd.fd = fioc->fd;
94     pfd.events = G_IO_OUT;
95     pfd.revents = 0;
96     rc = RETRY_ON_EINTR(g_poll(&pfd, 1, 0));
97     assert(rc >= 0);
98 
99     if (pfd.revents & G_IO_HUP) {
100         pty_chr_state(chr, 0);
101     } else {
102         pty_chr_state(chr, 1);
103     }
104 }
105 
106 static int char_pty_chr_write(Chardev *chr, const uint8_t *buf, int len)
107 {
108     PtyChardev *s = PTY_CHARDEV(chr);
109     GPollFD pfd;
110     int rc;
111 
112     if (s->connected) {
113         return io_channel_send(s->ioc, buf, len);
114     }
115 
116     /*
117      * The other side might already be re-connected, but the timer might
118      * not have fired yet. So let's check here whether we can write again:
119      */
120     pfd.fd = QIO_CHANNEL_FILE(s->ioc)->fd;
121     pfd.events = G_IO_OUT;
122     pfd.revents = 0;
123     rc = RETRY_ON_EINTR(g_poll(&pfd, 1, 0));
124     g_assert(rc >= 0);
125     if (!(pfd.revents & G_IO_HUP) && (pfd.revents & G_IO_OUT)) {
126         io_channel_send(s->ioc, buf, len);
127     }
128 
129     return len;
130 }
131 
132 static GSource *pty_chr_add_watch(Chardev *chr, GIOCondition cond)
133 {
134     PtyChardev *s = PTY_CHARDEV(chr);
135     if (!s->connected) {
136         return NULL;
137     }
138     return qio_channel_create_watch(s->ioc, cond);
139 }
140 
141 static int pty_chr_read_poll(void *opaque)
142 {
143     Chardev *chr = CHARDEV(opaque);
144     PtyChardev *s = PTY_CHARDEV(opaque);
145 
146     s->read_bytes = qemu_chr_be_can_write(chr);
147     return s->read_bytes;
148 }
149 
150 static gboolean pty_chr_read(QIOChannel *chan, GIOCondition cond, void *opaque)
151 {
152     Chardev *chr = CHARDEV(opaque);
153     PtyChardev *s = PTY_CHARDEV(opaque);
154     gsize len;
155     uint8_t buf[CHR_READ_BUF_LEN];
156     ssize_t ret;
157 
158     len = sizeof(buf);
159     if (len > s->read_bytes) {
160         len = s->read_bytes;
161     }
162     if (len == 0) {
163         return TRUE;
164     }
165     ret = qio_channel_read(s->ioc, (char *)buf, len, NULL);
166     if (ret <= 0) {
167         pty_chr_state(chr, 0);
168         return FALSE;
169     } else {
170         pty_chr_state(chr, 1);
171         qemu_chr_be_write(chr, buf, ret);
172     }
173     return TRUE;
174 }
175 
176 static void pty_chr_state(Chardev *chr, int connected)
177 {
178     PtyChardev *s = PTY_CHARDEV(chr);
179 
180     if (!connected) {
181         remove_fd_in_watch(chr);
182         s->connected = 0;
183         /* (re-)connect poll interval for idle guests: once per second.
184          * We check more frequently in case the guests sends data to
185          * the virtual device linked to our pty. */
186         pty_chr_rearm_timer(chr, 1000);
187     } else {
188         pty_chr_timer_cancel(s);
189         if (!s->connected) {
190             s->connected = 1;
191             qemu_chr_be_event(chr, CHR_EVENT_OPENED);
192         }
193         if (!chr->gsource) {
194             chr->gsource = io_add_watch_poll(chr, s->ioc,
195                                                pty_chr_read_poll,
196                                                pty_chr_read,
197                                                chr, chr->gcontext);
198         }
199     }
200 }
201 
202 static void char_pty_finalize(Object *obj)
203 {
204     Chardev *chr = CHARDEV(obj);
205     PtyChardev *s = PTY_CHARDEV(obj);
206 
207     pty_chr_state(chr, 0);
208     object_unref(OBJECT(s->ioc));
209     pty_chr_timer_cancel(s);
210     qemu_chr_be_event(chr, CHR_EVENT_CLOSED);
211 }
212 
213 #if defined HAVE_PTY_H
214 # include <pty.h>
215 #elif defined CONFIG_BSD
216 # include <termios.h>
217 # if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
218 #  include <libutil.h>
219 # else
220 #  include <util.h>
221 # endif
222 #elif defined CONFIG_SOLARIS
223 # include <termios.h>
224 # include <stropts.h>
225 #else
226 # include <termios.h>
227 #endif
228 
229 #ifdef __sun__
230 
231 #if !defined(HAVE_OPENPTY)
232 /* Once illumos has openpty(), this is going to be removed. */
233 static int openpty(int *amaster, int *aslave, char *name,
234                    struct termios *termp, struct winsize *winp)
235 {
236     const char *slave;
237     int mfd = -1, sfd = -1;
238 
239     *amaster = *aslave = -1;
240 
241     mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
242     if (mfd < 0) {
243         goto err;
244     }
245 
246     if (grantpt(mfd) == -1 || unlockpt(mfd) == -1) {
247         goto err;
248     }
249 
250     if ((slave = ptsname(mfd)) == NULL) {
251         goto err;
252     }
253 
254     if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1) {
255         goto err;
256     }
257 
258     if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
259         (termp != NULL && tcgetattr(sfd, termp) < 0)) {
260         goto err;
261     }
262 
263     *amaster = mfd;
264     *aslave = sfd;
265 
266     if (winp) {
267         ioctl(sfd, TIOCSWINSZ, winp);
268     }
269 
270     return 0;
271 
272 err:
273     if (sfd != -1) {
274         close(sfd);
275     }
276     close(mfd);
277     return -1;
278 }
279 #endif
280 
281 static void cfmakeraw (struct termios *termios_p)
282 {
283     termios_p->c_iflag &=
284         ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
285     termios_p->c_oflag &= ~OPOST;
286     termios_p->c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
287     termios_p->c_cflag &= ~(CSIZE | PARENB);
288     termios_p->c_cflag |= CS8;
289 
290     termios_p->c_cc[VMIN] = 0;
291     termios_p->c_cc[VTIME] = 0;
292 }
293 #endif
294 
295 /* like openpty() but also makes it raw; return master fd */
296 static int qemu_openpty_raw(int *aslave, char *pty_name)
297 {
298     int amaster;
299     struct termios tty;
300 #if defined(__OpenBSD__) || defined(__DragonFly__)
301     char pty_buf[PATH_MAX];
302 #define q_ptsname(x) pty_buf
303 #else
304     char *pty_buf = NULL;
305 #define q_ptsname(x) ptsname(x)
306 #endif
307 
308     if (openpty(&amaster, aslave, pty_buf, NULL, NULL) < 0) {
309         return -1;
310     }
311 
312     /* Set raw attributes on the pty. */
313     tcgetattr(*aslave, &tty);
314     cfmakeraw(&tty);
315     tcsetattr(*aslave, TCSAFLUSH, &tty);
316 
317     if (pty_name) {
318         strcpy(pty_name, q_ptsname(amaster));
319     }
320 
321     return amaster;
322 }
323 
324 static void char_pty_open(Chardev *chr,
325                           ChardevBackend *backend,
326                           bool *be_opened,
327                           Error **errp)
328 {
329     PtyChardev *s;
330     int master_fd, slave_fd;
331     char pty_name[PATH_MAX];
332     char *name;
333 
334     master_fd = qemu_openpty_raw(&slave_fd, pty_name);
335     if (master_fd < 0) {
336         error_setg_errno(errp, errno, "Failed to create PTY");
337         return;
338     }
339 
340     close(slave_fd);
341     if (!g_unix_set_fd_nonblocking(master_fd, true, NULL)) {
342         error_setg_errno(errp, errno, "Failed to set FD nonblocking");
343         return;
344     }
345 
346     chr->filename = g_strdup_printf("pty:%s", pty_name);
347     qemu_printf("char device redirected to %s (label %s)\n",
348                 pty_name, chr->label);
349 
350     s = PTY_CHARDEV(chr);
351     s->ioc = QIO_CHANNEL(qio_channel_file_new_fd(master_fd));
352     name = g_strdup_printf("chardev-pty-%s", chr->label);
353     qio_channel_set_name(s->ioc, name);
354     g_free(name);
355     s->timer_src = NULL;
356     *be_opened = false;
357 }
358 
359 static void char_pty_class_init(ObjectClass *oc, void *data)
360 {
361     ChardevClass *cc = CHARDEV_CLASS(oc);
362 
363     cc->open = char_pty_open;
364     cc->chr_write = char_pty_chr_write;
365     cc->chr_update_read_handler = pty_chr_update_read_handler;
366     cc->chr_add_watch = pty_chr_add_watch;
367 }
368 
369 static const TypeInfo char_pty_type_info = {
370     .name = TYPE_CHARDEV_PTY,
371     .parent = TYPE_CHARDEV,
372     .instance_size = sizeof(PtyChardev),
373     .instance_finalize = char_pty_finalize,
374     .class_init = char_pty_class_init,
375 };
376 
377 static void register_types(void)
378 {
379     type_register_static(&char_pty_type_info);
380 }
381 
382 type_init(register_types);
383