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