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