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"
49 static void debug_buffer (FILE *, const char *);
54 mexp_h *h = malloc (sizeof *h);
58 /* Initialize the fields to default values. */
65 h->len = h->alloc = 0;
68 h->user1 = h->user2 = h->user3 = NULL;
74 clear_buffer (mexp_h *h)
78 h->alloc = h->len = 0;
83 mexp_close (mexp_h *h)
92 if (waitpid (h->pid, &status, 0) == -1)
102 mexp_spawnlf (unsigned flags, const char *file, const char *arg, ...)
104 char **argv, **new_argv;
109 argv = malloc (sizeof (char *));
112 argv[0] = (char *) arg;
114 va_start (args, arg);
115 for (i = 1; arg != NULL; ++i) {
116 arg = va_arg (args, const char *);
117 new_argv = realloc (argv, sizeof (char *) * (i+1));
118 if (new_argv == NULL) {
124 argv[i] = (char *) arg;
127 h = mexp_spawnvf (flags, file, argv);
134 mexp_spawnvf (unsigned flags, const char *file, char **argv)
142 fd = posix_openpt (O_RDWR|O_NOCTTY);
146 if (grantpt (fd) == -1)
149 if (unlockpt (fd) == -1)
152 /* Get the slave pty name now, but don't open it in the parent. */
153 if (ptsname_r (fd, slave, sizeof slave) != 0)
156 /* Create the handle last before we fork. */
157 h = create_handle ();
165 if (pid == 0) { /* Child. */
168 if (!(flags & MEXP_SPAWN_KEEP_SIGNALS)) {
172 /* Remove all signal handlers. See the justification here:
173 * https://www.redhat.com/archives/libvir-list/2008-August/msg00303.html
174 * We don't mask signal handlers yet, so this isn't completely
175 * race-free, but better than not doing it at all.
177 memset (&sa, 0, sizeof sa);
178 sa.sa_handler = SIG_DFL;
180 sigemptyset (&sa.sa_mask);
181 for (i = 1; i < NSIG; ++i)
182 sigaction (i, &sa, NULL);
187 /* Open the slave side of the pty. We must do this in the child
188 * after setsid so it becomes our controlling tty.
190 slave_fd = open (slave, O_RDWR);
194 if (!(flags & MEXP_SPAWN_COOKED_MODE)) {
195 struct termios termios;
198 tcgetattr (slave_fd, &termios);
199 cfmakeraw (&termios);
200 tcsetattr (slave_fd, TCSANOW, &termios);
203 /* Set up stdin, stdout, stderr to point to the pty. */
209 /* Close the master side of the pty - do this late to avoid a
210 * kernel bug, see sshpass source code.
214 if (!(flags & MEXP_SPAWN_KEEP_FDS)) {
217 /* Close all other file descriptors. This ensures that we don't
218 * hold open (eg) pipes from the parent process.
220 max_fd = sysconf (_SC_OPEN_MAX);
224 max_fd = 65536; /* bound the amount of work we do here */
225 for (i = 3; i < max_fd; ++i)
229 /* Run the subprocess. */
232 _exit (EXIT_FAILURE);
246 waitpid (pid, NULL, 0);
254 mexp_expect (mexp_h *h, const mexp_regexp *regexps, int *ovector, int ovecsize)
256 time_t start_t, now_t;
258 struct pollfd pfds[1];
264 if (h->next_match == -1) {
265 /* Fully clear the buffer, then read. */
268 /* See the comment in the manual about h->next_match. We have
269 * some data remaining in the buffer, so begin by matching that.
271 memmove (&h->buffer[0], &h->buffer[h->next_match], h->len - h->next_match);
272 h->len -= h->next_match;
273 h->buffer[h->len] = '\0';
279 /* If we've got a timeout then work out how many seconds are left.
280 * Timeout == 0 is not particularly well-defined, but it probably
281 * means "return immediately if there's no data to be read".
283 if (h->timeout >= 0) {
285 timeout = h->timeout - ((now_t - start_t) * 1000);
293 pfds[0].events = POLLIN;
295 r = poll (pfds, 1, timeout);
297 fprintf (h->debug_fp, "DEBUG: poll returned %d\n", r);
304 /* Otherwise we expect there is something to read from the file
307 if (h->alloc - h->len <= h->read_size) {
309 /* +1 here allows us to store \0 after the data read */
310 new_buffer = realloc (h->buffer, h->alloc + h->read_size + 1);
311 if (new_buffer == NULL)
313 h->buffer = new_buffer;
314 h->alloc += h->read_size;
316 rs = read (h->fd, h->buffer + h->len, h->read_size);
318 fprintf (h->debug_fp, "DEBUG: read returned %zd\n", rs);
320 /* Annoyingly on Linux (I'm fairly sure this is a bug) if the
321 * writer closes the connection, the entire pty is destroyed,
322 * and read returns -1 / EIO. Handle that special case here.
331 /* We read something. */
333 h->buffer[h->len] = '\0';
335 fprintf (h->debug_fp, "DEBUG: read %zd bytes from pty\n", rs);
336 fprintf (h->debug_fp, "DEBUG: buffer content: ");
337 debug_buffer (h->debug_fp, h->buffer);
338 fprintf (h->debug_fp, "\n");
342 /* See if there is a full or partial match against any regexp. */
345 int can_clear_buffer = 1;
347 assert (h->buffer != NULL);
349 for (i = 0; regexps[i].r > 0; ++i) {
350 const int options = regexps[i].options | PCRE_PARTIAL_SOFT;
352 r = pcre_exec (regexps[i].re, regexps[i].extra,
353 h->buffer, (int)h->len, 0,
360 if (ovector != NULL && ovecsize >= 1 && ovector[1] >= 0)
361 h->next_match = ovector[1];
365 fprintf (h->debug_fp, "DEBUG: next_match at buffer offset %zu\n",
370 else if (r == PCRE_ERROR_NOMATCH) {
371 /* No match at all. */
375 else if (r == PCRE_ERROR_PARTIAL) {
376 /* Partial match. Keep the buffer and keep reading. */
377 can_clear_buffer = 0;
381 /* An actual PCRE error. */
382 return MEXP_PCRE_ERROR;
386 /* If none of the regular expressions matched (not partially)
387 * then we can clear the buffer. This is an optimization.
389 if (can_clear_buffer)
396 static int mexp_vprintf (mexp_h *h, int password, const char *fs, va_list args)
397 __attribute__((format(printf,3,0)));
400 mexp_vprintf (mexp_h *h, int password, const char *fs, va_list args)
408 len = vasprintf (&msg, fs, args);
415 fprintf (h->debug_fp, "DEBUG: writing: ");
416 debug_buffer (h->debug_fp, msg);
417 fprintf (h->debug_fp, "\n");
420 fprintf (h->debug_fp, "DEBUG: writing the password\n");
426 r = write (h->fd, p, n);
440 mexp_printf (mexp_h *h, const char *fs, ...)
446 r = mexp_vprintf (h, 0, fs, args);
452 mexp_printf_password (mexp_h *h, const char *fs, ...)
458 r = mexp_vprintf (h, 1, fs, args);
464 mexp_send_interrupt (mexp_h *h)
466 return write (h->fd, "\003", 1);
469 /* Print escaped buffer to fp. */
471 debug_buffer (FILE *fp, const char *buf)
478 case '\0': fputs ("\\0", fp); break;
479 case '\a': fputs ("\\a", fp); break;
480 case '\b': fputs ("\\b", fp); break;
481 case '\f': fputs ("\\f", fp); break;
482 case '\n': fputs ("\\n", fp); break;
483 case '\r': fputs ("\\r", fp); break;
484 case '\t': fputs ("\\t", fp); break;
485 case '\v': fputs ("\\v", fp); break;
487 fprintf (fp, "\\x%x", (unsigned char) *buf);