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