2 * Copyright (C) 2014 Red Hat Inc.
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
34 #include <sys/types.h>
40 /* RHEL 6 pcre did not define PCRE_PARTIAL_SOFT. However PCRE_PARTIAL
41 * is a synonym so use that.
43 #ifndef PCRE_PARTIAL_SOFT
44 #define PCRE_PARTIAL_SOFT PCRE_PARTIAL
47 #include "miniexpect.h"
52 static void debug_buffer (FILE *, const char *);
58 mexp_h *h = malloc (sizeof *h);
62 /* Initialize the fields to default values. */
69 h->len = h->alloc = 0;
71 h->user1 = h->user2 = h->user3 = NULL;
77 clear_buffer (mexp_h *h)
81 h->alloc = h->len = 0;
86 mexp_close (mexp_h *h)
95 if (waitpid (h->pid, &status, 0) == -1)
105 mexp_spawnlf (unsigned flags, const char *file, const char *arg, ...)
107 char **argv, **new_argv;
112 argv = malloc (sizeof (char *));
115 argv[0] = (char *) arg;
117 va_start (args, arg);
118 for (i = 1; arg != NULL; ++i) {
119 arg = va_arg (args, const char *);
120 new_argv = realloc (argv, sizeof (char *) * (i+1));
121 if (new_argv == NULL) {
127 argv[i] = (char *) arg;
130 h = mexp_spawnvf (flags, file, argv);
137 mexp_spawnvf (unsigned flags, const char *file, char **argv)
145 fd = posix_openpt (O_RDWR|O_NOCTTY);
149 if (grantpt (fd) == -1)
152 if (unlockpt (fd) == -1)
155 /* Get the slave pty name now, but don't open it in the parent. */
156 if (ptsname_r (fd, slave, sizeof slave) != 0)
159 /* Create the handle last before we fork. */
160 h = create_handle ();
168 if (pid == 0) { /* Child. */
171 if (!(flags & MEXP_SPAWN_KEEP_SIGNALS)) {
175 /* Remove all signal handlers. See the justification here:
176 * https://www.redhat.com/archives/libvir-list/2008-August/msg00303.html
177 * We don't mask signal handlers yet, so this isn't completely
178 * race-free, but better than not doing it at all.
180 memset (&sa, 0, sizeof sa);
181 sa.sa_handler = SIG_DFL;
183 sigemptyset (&sa.sa_mask);
184 for (i = 1; i < NSIG; ++i)
185 sigaction (i, &sa, NULL);
190 /* Open the slave side of the pty. We must do this in the child
191 * after setsid so it becomes our controlling tty.
193 slave_fd = open (slave, O_RDWR);
197 if (!(flags & MEXP_SPAWN_COOKED_MODE)) {
198 struct termios termios;
201 tcgetattr (slave_fd, &termios);
202 cfmakeraw (&termios);
203 tcsetattr (slave_fd, TCSANOW, &termios);
206 /* Set up stdin, stdout, stderr to point to the pty. */
212 /* Close the master side of the pty - do this late to avoid a
213 * kernel bug, see sshpass source code.
217 if (!(flags & MEXP_SPAWN_KEEP_FDS)) {
220 /* Close all other file descriptors. This ensures that we don't
221 * hold open (eg) pipes from the parent process.
223 max_fd = sysconf (_SC_OPEN_MAX);
227 max_fd = 65536; /* bound the amount of work we do here */
228 for (i = 3; i < max_fd; ++i)
232 /* Run the subprocess. */
235 _exit (EXIT_FAILURE);
249 waitpid (pid, NULL, 0);
257 mexp_expect (mexp_h *h, const mexp_regexp *regexps, int *ovector, int ovecsize)
259 time_t start_t, now_t;
261 struct pollfd pfds[1];
267 if (h->next_match == -1) {
268 /* Fully clear the buffer, then read. */
271 /* See the comment in the manual about h->next_match. We have
272 * some data remaining in the buffer, so begin by matching that.
274 memmove (&h->buffer[0], &h->buffer[h->next_match], h->len - h->next_match);
275 h->len -= h->next_match;
276 h->buffer[h->len] = '\0';
282 /* If we've got a timeout then work out how many seconds are left.
283 * Timeout == 0 is not particularly well-defined, but it probably
284 * means "return immediately if there's no data to be read".
286 if (h->timeout >= 0) {
288 timeout = h->timeout - ((now_t - start_t) * 1000);
296 pfds[0].events = POLLIN;
298 r = poll (pfds, 1, timeout);
300 fprintf (stderr, "DEBUG: poll returned %d\n", r);
308 /* Otherwise we expect there is something to read from the file
311 if (h->alloc - h->len <= h->read_size) {
313 /* +1 here allows us to store \0 after the data read */
314 new_buffer = realloc (h->buffer, h->alloc + h->read_size + 1);
315 if (new_buffer == NULL)
317 h->buffer = new_buffer;
318 h->alloc += h->read_size;
320 rs = read (h->fd, h->buffer + h->len, h->read_size);
322 fprintf (stderr, "DEBUG: read returned %zd\n", rs);
325 /* Annoyingly on Linux (I'm fairly sure this is a bug) if the
326 * writer closes the connection, the entire pty is destroyed,
327 * and read returns -1 / EIO. Handle that special case here.
336 /* We read something. */
338 h->buffer[h->len] = '\0';
340 fprintf (stderr, "DEBUG: read %zd bytes from pty\n", rs);
341 fprintf (stderr, "DEBUG: buffer content: ");
342 debug_buffer (stderr, h->buffer);
343 fprintf (stderr, "\n");
347 /* See if there is a full or partial match against any regexp. */
350 int can_clear_buffer = 1;
352 assert (h->buffer != NULL);
354 for (i = 0; regexps[i].r > 0; ++i) {
355 const int options = regexps[i].options | PCRE_PARTIAL_SOFT;
357 r = pcre_exec (regexps[i].re, regexps[i].extra,
358 h->buffer, (int)h->len, 0,
365 if (ovector != NULL && ovecsize >= 1 && ovector[1] >= 0)
366 h->next_match = ovector[1];
372 else if (r == PCRE_ERROR_NOMATCH) {
373 /* No match at all. */
377 else if (r == PCRE_ERROR_PARTIAL) {
378 /* Partial match. Keep the buffer and keep reading. */
379 can_clear_buffer = 0;
383 /* An actual PCRE error. */
384 return MEXP_PCRE_ERROR;
388 /* If none of the regular expressions matched (not partially)
389 * then we can clear the buffer. This is an optimization.
391 if (can_clear_buffer)
399 mexp_printf (mexp_h *h, const char *fs, ...)
409 len = vasprintf (&msg, fs, args);
416 fprintf (stderr, "DEBUG: writing: ");
417 debug_buffer (stderr, msg);
418 fprintf (stderr, "\n");
424 r = write (h->fd, p, n);
438 mexp_send_interrupt (mexp_h *h)
440 return write (h->fd, "\003", 1);
444 /* Print escaped buffer to fp. */
446 debug_buffer (FILE *fp, const char *buf)
453 case '\0': fputs ("\\0", fp); break;
454 case '\a': fputs ("\\a", fp); break;
455 case '\b': fputs ("\\b", fp); break;
456 case '\f': fputs ("\\f", fp); break;
457 case '\n': fputs ("\\n", fp); break;
458 case '\r': fputs ("\\r", fp); break;
459 case '\t': fputs ("\\t", fp); break;
460 case '\v': fputs ("\\v", fp); break;
462 fprintf (fp, "\\x%x", (unsigned char) *buf);