lib/texpect: add texpect binary based on heimdals rkpty.
[vlendec/samba-autobuild/.git] / lib / texpect / texpect.c
1 /*
2  * Copyright (c) 2008 Kungliga Tekniska Högskolan
3  * (Royal Institute of Technology, Stockholm, Sweden).
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * 3. Neither the name of the Institute nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 #include "config.h"
35
36 #ifndef HAVE_SYS_TYPES_H
37 #include <sys/types.h>
38 #endif
39 #ifdef HAVE_SYS_WAIT_H
40 #include <sys/wait.h>
41 #endif
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #ifdef HAVE_UNISTD_H
46 #include <unistd.h>
47 #endif
48 #ifdef HAVE_PTY_H
49 #include <pty.h>
50 #endif
51 #ifdef HAVE_UTIL_H
52 #include <util.h>
53 #endif
54 #ifdef HAVE_LIBUTIL_H
55 #include <libutil.h>
56 #endif
57
58 #ifdef  STREAMSPTY
59 #include <stropts.h>
60 #endif /* STREAMPTY */
61
62 #include <popt.h>
63 #include <errno.h>
64 #include <err.h>
65
66 struct command {
67         enum { CMD_EXPECT = 0, CMD_SEND, CMD_PASSWORD } type;
68         unsigned int lineno;
69         char *str;
70         struct command *next;
71 };
72
73 /*
74  *
75  */
76
77 static struct command *commands, **next = &commands;
78
79 static sig_atomic_t alarmset = 0;
80
81 static int opt_timeout = 10;
82 static int opt_verbose;
83
84 static int master;
85 static int slave;
86 static char line[256] = { 0 };
87
88 static void caught_signal(int signo)
89 {
90         alarmset = signo;
91 }
92
93
94 static void open_pty(void)
95 {
96 #ifdef _AIX
97         printf("implement open_pty\n");
98         exit(77);
99 #endif
100 #if defined(HAVE_OPENPTY) || defined(__linux) || defined(__osf__) /* XXX */
101         if(openpty(&master, &slave, line, 0, 0) == 0)
102                 return;
103 #endif /* HAVE_OPENPTY .... */
104 #ifdef STREAMSPTY
105         {
106                 char *clone[] = {
107                         "/dev/ptc",
108                         "/dev/ptmx",
109                         "/dev/ptm",
110                         "/dev/ptym/clone",
111                         NULL
112                 };
113                 char **q;
114
115                 for(q = clone; *q; q++){
116                         master = open(*q, O_RDWR);
117                         if(master >= 0){
118 #ifdef HAVE_GRANTPT
119                                 grantpt(master);
120 #endif
121 #ifdef HAVE_UNLOCKPT
122                                 unlockpt(master);
123 #endif
124                                 strlcpy(line, ptsname(master), sizeof(line));
125                                 slave = open(line, O_RDWR);
126                                 if (slave < 0)
127                                         errx(1, "failed to open slave when using %s", *q);
128                                 ioctl(slave, I_PUSH, "ptem");
129                                 ioctl(slave, I_PUSH, "ldterm");
130
131                                 return;
132                         }
133                 }
134         }
135 #endif /* STREAMSPTY */
136
137         /* more cases, like open /dev/ptmx, etc */
138
139         exit(77);
140 }
141
142 /*
143  *
144  */
145
146 static char *iscmd(const char *buf, const char *s)
147 {
148         size_t len = strlen(s);
149
150         if (strncmp(buf, s, len) != 0) {
151                 return NULL;
152         }
153
154         return strdup(buf + len);
155 }
156
157 /*******************************************************************
158 A write wrapper that will deal with EINTR.
159 ********************************************************************/
160
161 static ssize_t sys_write(int fd, const void *buf, size_t count)
162 {
163         ssize_t ret;
164
165         do {
166                 ret = write(fd, buf, count);
167 #if defined(EWOULDBLOCK)
168         } while (ret == -1 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK));
169 #else
170         } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
171 #endif
172         return ret;
173 }
174
175 static void parse_configuration(const char *fn)
176 {
177         struct command *c;
178         char s[1024];
179         char *str;
180         unsigned int lineno = 0;
181         FILE *cmd;
182
183         cmd = fopen(fn, "r");
184         if (cmd == NULL)
185                 err(1, "open: %s", fn);
186
187         while (fgets(s, sizeof(s),  cmd) != NULL) {
188
189                 s[strcspn(s, "#\n")] = '\0';
190                 lineno++;
191
192                 c = calloc(1, sizeof(*c));
193                 if (c == NULL)
194                         errx(1, "malloc");
195
196                 c->lineno = lineno;
197                 (*next) = c;
198                 next = &(c->next);
199
200                 if ((str = iscmd(s, "expect ")) != NULL) {
201                         c->type = CMD_EXPECT;
202                         c->str = str;
203                 } else if ((str = iscmd(s, "send ")) != NULL) {
204                         c->type = CMD_SEND;
205                         c->str = str;
206                 } else if ((str = iscmd(s, "password ")) != NULL) {
207                         c->type = CMD_PASSWORD;
208                         c->str = str;
209                 } else
210                         errx(1, "Invalid command on line %d: %s", lineno, s);
211         }
212
213         fclose(cmd);
214 }
215
216 /* A wrapper to close als file descriptors above the given fd */
217 static int sys_closefrom(int fd)
218 {
219         int num = getdtablesize();
220
221         if (num < 0) {
222                 num = 1024;
223         }
224
225         for (; fd <= num; fd++) {
226                 close(fd);
227         }
228
229         return 0;
230 }
231
232
233 /*
234  *
235  */
236
237 static int eval_parent(pid_t pid)
238 {
239         struct command *c;
240         char in;
241         size_t len = 0;
242         ssize_t sret;
243
244         for (c = commands; c != NULL; c = c->next) {
245                 switch(c->type) {
246                 case CMD_EXPECT:
247                         if (opt_verbose) {
248                                 printf("[expecting %s]\n", c->str);
249                         }
250                         len = 0;
251                         alarm(opt_timeout);
252                         while((sret = read(master, &in, sizeof(in))) > 0) {
253                                 alarm(opt_timeout);
254                                 printf("%c", in);
255                                 if (c->str[len] != in) {
256                                         len = 0;
257                                         continue;
258                                 }
259                                 len++;
260                                 if (c->str[len] == '\0') {
261                                         break;
262                                 }
263                         }
264                         alarm(0);
265                         if (alarmset == SIGALRM) {
266                                 errx(1, "timeout waiting for %s (line %u)",
267                                                 c->str, c->lineno);
268                         } else if (alarmset) {
269                                 errx(1, "got a signal %d waiting for %s (line %u)",
270                                                 (int)alarmset, c->str, c->lineno);
271                         }
272
273                         if (sret <= 0) {
274                                 errx(1, "end command while waiting for %s (line %u)",
275                                                 c->str, c->lineno);
276                         }
277                         break;
278                 case CMD_SEND:
279                 case CMD_PASSWORD: {
280                         size_t i = 0;
281                         const char *msg = (c->type == CMD_PASSWORD) ? "****" : c->str;
282
283                         if (opt_verbose) {
284                                 printf("[send %s]\n", msg);
285                         }
286
287                         len = strlen(c->str);
288
289                         while (i < len) {
290                                 if (c->str[i] == '\\' && i < len - 1) {
291                                         char ctrl;
292                                         i++;
293                                         switch(c->str[i]) {
294                                         case 'n':
295                                                 ctrl = '\n';
296                                                 break;
297                                         case 'r':
298                                                 ctrl = '\r';
299                                                 break;
300                                         case 't':
301                                                 ctrl = '\t';
302                                                 break;
303                                         default:
304                                                 errx(1,
305                                                      "unknown control char %c (line %u)",
306                                                      c->str[i],
307                                                      c->lineno);
308                                         }
309                                         if (sys_write(master, &ctrl, 1) != 1) {
310                                                 errx(1, "command refused input (line %u)", c->lineno);
311                                         }
312                                 } else {
313                                         if (sys_write(master, &c->str[i], 1) != 1) {
314                                                 errx(1, "command refused input (line %u)", c->lineno);
315                                         }
316                                 }
317                                 i++;
318                         }
319                         break;
320                 }
321                 default:
322                         abort();
323                 }
324         }
325
326         while(read(master, &in, sizeof(in)) > 0) {
327                 printf("%c", in);
328         }
329
330         if (opt_verbose) {
331                 printf("[end of program]\n");
332         }
333
334         /*
335          * Fetch status from child
336          */
337         {
338                 int ret, status;
339
340                 ret = waitpid(pid, &status, 0);
341                 if (ret == -1) {
342                         err(1, "waitpid");
343                 }
344
345                 if (WIFEXITED(status) && WEXITSTATUS(status)) {
346                         return WEXITSTATUS(status);
347                 } else if (WIFSIGNALED(status)) {
348                         printf("killed by signal: %d\n", WTERMSIG(status));
349                         return 1;
350                 }
351         }
352
353         return 0;
354 }
355
356 /*
357  *
358  */
359 struct poptOption long_options[] = {
360         POPT_AUTOHELP
361         {"timeout", 't', POPT_ARG_INT,  &opt_timeout, 't'},
362         {"verbose", 'v', POPT_ARG_NONE, &opt_verbose, 'v'},
363         POPT_TABLEEND
364 };
365
366 int main(int argc, const char **argv)
367 {
368         int optidx = 0;
369         pid_t pid;
370         poptContext pc;
371         const char *instruction_file;
372         const char *program;
373         char* const *program_args;
374
375         pc = poptGetContext("texpect",
376                             argc,
377                             argv,
378                             long_options,
379                             POPT_CONTEXT_POSIXMEHARDER);
380
381         if (argc == 1) {
382                 poptPrintHelp(pc, stderr, 0);
383                 return 1;
384         }
385
386         while ((optidx = poptGetNextOpt(pc)) != -1) {
387                 ;;
388         }
389
390         instruction_file = poptGetArg(pc);
391         program_args = poptGetArgs(pc);
392         program = program_args[0];
393
394         if (opt_verbose) {
395                 int i;
396
397                 printf("Using instruction_file: %s\n", instruction_file);
398                 printf("Executing '%s' ", program);
399                 for (i = 0; program_args && program_args[i] != NULL; i++) {
400                         printf("'%s' ", program_args[i]);
401                 }
402                 printf("\n");
403         }
404
405         parse_configuration(instruction_file);
406
407         open_pty();
408
409         pid = fork();
410         switch (pid) {
411                 case -1:
412                         err(1, "Failed to fork");
413                 case 0:
414
415                         if(setsid()<0)
416                                 err(1, "setsid");
417
418                         dup2(slave, STDIN_FILENO);
419                         dup2(slave, STDOUT_FILENO);
420                         dup2(slave, STDERR_FILENO);
421
422                         sys_closefrom(STDERR_FILENO + 1);
423
424                         /* texpect <expect_instructions> <progname> [<args>] */
425                         execvp(program, program_args);
426                         err(1, "Failed to exec: %s", program);
427                 default:
428                         close(slave);
429                         {
430                                 struct sigaction sa;
431
432                                 sa.sa_handler = caught_signal;
433                                 sa.sa_flags = 0;
434                                 sigemptyset (&sa.sa_mask);
435
436                                 sigaction(SIGALRM, &sa, NULL);
437                         }
438
439                         return eval_parent(pid);
440         }
441 }