75a32f4bed29d728e64463315f0c2668c591aaab
[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 "replace.h"
35 #include "system/filesys.h"
36 #include "system/wait.h"
37
38 #ifdef HAVE_PTY_H
39 #include <pty.h>
40 #endif
41 #ifdef HAVE_UTIL_H
42 #include <util.h>
43 #endif
44 #ifdef HAVE_BSD_LIBUTIL_H
45 #include <bsd/libutil.h>
46 #elif defined HAVE_LIBUTIL_H
47 #include <libutil.h>
48 #endif
49
50 #ifdef  STREAMSPTY
51 #include <stropts.h>
52 #endif /* STREAMPTY */
53
54 #include <popt.h>
55 #include <err.h>
56
57 struct command {
58         enum { CMD_EXPECT = 0, CMD_SEND, CMD_PASSWORD } type;
59         unsigned int lineno;
60         char *str;
61         struct command *next;
62 };
63
64 /*
65  *
66  */
67
68 static struct command *commands, **next = &commands;
69
70 static sig_atomic_t alarmset = 0;
71
72 static int opt_timeout = 10;
73 static int opt_verbose;
74
75 static int master;
76 static int slave;
77 static char line[256] = { 0 };
78
79 static void caught_signal(int signo)
80 {
81         alarmset = signo;
82 }
83
84
85 static void open_pty(void)
86 {
87 #ifdef _AIX
88         printf("implement open_pty\n");
89         exit(77);
90 #endif
91 #if defined(HAVE_OPENPTY) || defined(__linux) || defined(__osf__) /* XXX */
92         if(openpty(&master, &slave, line, 0, 0) == 0)
93                 return;
94 #endif /* HAVE_OPENPTY .... */
95 #ifdef STREAMSPTY
96         {
97                 char *clone[] = {
98                         "/dev/ptc",
99                         "/dev/ptmx",
100                         "/dev/ptm",
101                         "/dev/ptym/clone",
102                         NULL
103                 };
104                 char **q;
105
106                 for(q = clone; *q; q++){
107                         master = open(*q, O_RDWR);
108                         if(master >= 0){
109 #ifdef HAVE_GRANTPT
110                                 grantpt(master);
111 #endif
112 #ifdef HAVE_UNLOCKPT
113                                 unlockpt(master);
114 #endif
115                                 strlcpy(line, ptsname(master), sizeof(line));
116                                 slave = open(line, O_RDWR);
117                                 if (slave < 0)
118                                         errx(1, "failed to open slave when using %s", *q);
119                                 ioctl(slave, I_PUSH, "ptem");
120                                 ioctl(slave, I_PUSH, "ldterm");
121
122                                 return;
123                         }
124                 }
125         }
126 #endif /* STREAMSPTY */
127
128         /* more cases, like open /dev/ptmx, etc */
129
130         exit(77);
131 }
132
133 /*
134  *
135  */
136
137 static char *iscmd(const char *buf, const char *s)
138 {
139         size_t len = strlen(s);
140
141         if (strncmp(buf, s, len) != 0) {
142                 return NULL;
143         }
144
145         return strdup(buf + len);
146 }
147
148 /*******************************************************************
149 A write wrapper that will deal with EINTR.
150 ********************************************************************/
151
152 static ssize_t sys_write(int fd, const void *buf, size_t count)
153 {
154         ssize_t ret;
155
156         do {
157                 ret = write(fd, buf, count);
158 #if defined(EWOULDBLOCK)
159         } while (ret == -1 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK));
160 #else
161         } while (ret == -1 && (errno == EINTR || errno == EAGAIN));
162 #endif
163         return ret;
164 }
165
166 static void parse_configuration(const char *fn)
167 {
168         struct command *c;
169         char s[1024];
170         char *str;
171         unsigned int lineno = 0;
172         FILE *cmd;
173
174         cmd = fopen(fn, "r");
175         if (cmd == NULL)
176                 err(1, "open: %s", fn);
177
178         while (fgets(s, sizeof(s),  cmd) != NULL) {
179
180                 s[strcspn(s, "#\n")] = '\0';
181                 lineno++;
182
183                 c = calloc(1, sizeof(*c));
184                 if (c == NULL)
185                         errx(1, "malloc");
186
187                 c->lineno = lineno;
188                 (*next) = c;
189                 next = &(c->next);
190
191                 if ((str = iscmd(s, "expect ")) != NULL) {
192                         c->type = CMD_EXPECT;
193                         c->str = str;
194                 } else if ((str = iscmd(s, "send ")) != NULL) {
195                         c->type = CMD_SEND;
196                         c->str = str;
197                 } else if ((str = iscmd(s, "password ")) != NULL) {
198                         c->type = CMD_PASSWORD;
199                         c->str = str;
200                 } else
201                         errx(1, "Invalid command on line %d: %s", lineno, s);
202         }
203
204         fclose(cmd);
205 }
206
207 /* A wrapper to close als file descriptors above the given fd */
208 static int sys_closefrom(int fd)
209 {
210         int num = getdtablesize();
211
212         if (num < 0) {
213                 num = 1024;
214         }
215
216         for (; fd <= num; fd++) {
217                 close(fd);
218         }
219
220         return 0;
221 }
222
223
224 /*
225  *
226  */
227
228 static int eval_parent(pid_t pid)
229 {
230         struct command *c;
231         char in;
232         size_t len = 0;
233         ssize_t sret;
234
235         for (c = commands; c != NULL; c = c->next) {
236                 switch(c->type) {
237                 case CMD_EXPECT:
238                         if (opt_verbose) {
239                                 printf("[expecting %s]\n", c->str);
240                         }
241                         len = 0;
242                         alarm(opt_timeout);
243                         while((sret = read(master, &in, sizeof(in))) > 0) {
244                                 alarm(opt_timeout);
245                                 printf("%c", in);
246                                 if (c->str[len] != in) {
247                                         len = 0;
248                                         continue;
249                                 }
250                                 len++;
251                                 if (c->str[len] == '\0') {
252                                         break;
253                                 }
254                         }
255                         alarm(0);
256                         if (alarmset == SIGALRM) {
257                                 errx(1, "timeout waiting for %s (line %u)",
258                                                 c->str, c->lineno);
259                         } else if (alarmset) {
260                                 errx(1, "got a signal %d waiting for %s (line %u)",
261                                                 (int)alarmset, c->str, c->lineno);
262                         }
263
264                         if (sret <= 0) {
265                                 errx(1, "end command while waiting for %s (line %u)",
266                                                 c->str, c->lineno);
267                         }
268                         break;
269                 case CMD_SEND:
270                 case CMD_PASSWORD: {
271                         size_t i = 0;
272                         const char *msg = (c->type == CMD_PASSWORD) ? "****" : c->str;
273
274                         if (opt_verbose) {
275                                 printf("[send %s]\n", msg);
276                         }
277
278                         len = strlen(c->str);
279
280                         while (i < len) {
281                                 if (c->str[i] == '\\' && i < len - 1) {
282                                         char ctrl;
283                                         i++;
284                                         switch(c->str[i]) {
285                                         case 'n':
286                                                 ctrl = '\n';
287                                                 break;
288                                         case 'r':
289                                                 ctrl = '\r';
290                                                 break;
291                                         case 't':
292                                                 ctrl = '\t';
293                                                 break;
294                                         default:
295                                                 errx(1,
296                                                      "unknown control char %c (line %u)",
297                                                      c->str[i],
298                                                      c->lineno);
299                                         }
300                                         if (sys_write(master, &ctrl, 1) != 1) {
301                                                 errx(1, "command refused input (line %u)", c->lineno);
302                                         }
303                                 } else {
304                                         if (sys_write(master, &c->str[i], 1) != 1) {
305                                                 errx(1, "command refused input (line %u)", c->lineno);
306                                         }
307                                 }
308                                 i++;
309                         }
310                         break;
311                 }
312                 default:
313                         abort();
314                 }
315         }
316
317         while(read(master, &in, sizeof(in)) > 0) {
318                 printf("%c", in);
319         }
320
321         if (opt_verbose) {
322                 printf("[end of program]\n");
323         }
324
325         /*
326          * Fetch status from child
327          */
328         {
329                 int ret, status;
330
331                 ret = waitpid(pid, &status, 0);
332                 if (ret == -1) {
333                         err(1, "waitpid");
334                 }
335
336                 if (WIFEXITED(status) && WEXITSTATUS(status)) {
337                         return WEXITSTATUS(status);
338                 } else if (WIFSIGNALED(status)) {
339                         printf("killed by signal: %d\n", WTERMSIG(status));
340                         return 1;
341                 }
342         }
343
344         return 0;
345 }
346
347 /*
348  *
349  */
350 struct poptOption long_options[] = {
351         POPT_AUTOHELP
352         {"timeout", 't', POPT_ARG_INT,  &opt_timeout, 't'},
353         {"verbose", 'v', POPT_ARG_NONE, &opt_verbose, 'v'},
354         POPT_TABLEEND
355 };
356
357 int main(int argc, const char **argv)
358 {
359         int optidx = 0;
360         pid_t pid;
361         poptContext pc;
362         const char *instruction_file;
363         const char **args;
364         const char *program;
365         char * const *program_args;
366
367         pc = poptGetContext("texpect",
368                             argc,
369                             argv,
370                             long_options,
371                             POPT_CONTEXT_POSIXMEHARDER);
372
373         if (argc == 1) {
374                 poptPrintHelp(pc, stderr, 0);
375                 return 1;
376         }
377
378         while ((optidx = poptGetNextOpt(pc)) != -1) {
379                 ;;
380         }
381
382         instruction_file = poptGetArg(pc);
383         args = poptGetArgs(pc);
384         program_args = (char * const *)discard_const_p(char *, args);
385         program = program_args[0];
386
387         if (opt_verbose) {
388                 int i;
389
390                 printf("Using instruction_file: %s\n", instruction_file);
391                 printf("Executing '%s' ", program);
392                 for (i = 0; program_args && program_args[i] != NULL; i++) {
393                         printf("'%s' ", program_args[i]);
394                 }
395                 printf("\n");
396         }
397
398         parse_configuration(instruction_file);
399
400         open_pty();
401
402         pid = fork();
403         switch (pid) {
404                 case -1:
405                         err(1, "Failed to fork");
406                 case 0:
407
408                         if(setsid()<0)
409                                 err(1, "setsid");
410
411                         dup2(slave, STDIN_FILENO);
412                         dup2(slave, STDOUT_FILENO);
413                         dup2(slave, STDERR_FILENO);
414
415                         sys_closefrom(STDERR_FILENO + 1);
416
417                         /* texpect <expect_instructions> <progname> [<args>] */
418                         execvp(program, program_args);
419                         err(1, "Failed to exec: %s", program);
420                 default:
421                         close(slave);
422                         {
423                                 struct sigaction sa;
424
425                                 sa.sa_handler = caught_signal;
426                                 sa.sa_flags = 0;
427                                 sigemptyset (&sa.sa_mask);
428
429                                 sigaction(SIGALRM, &sa, NULL);
430                         }
431
432                         return eval_parent(pid);
433         }
434 }