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#ifdef HAVE_UNISTD_H
45#include <unistd.h>
46#endif
47#ifdef HAVE_PTY_H
48#include <pty.h>
49#endif
50#ifdef HAVE_UTIL_H
51#include <util.h>
52#endif
53#ifdef HAVE_LIBUTIL_H
54#include <libutil.h>
55#endif
56
57#ifdef	STREAMSPTY
58#include <stropts.h>
59#endif /* STREAMPTY */
60
61#include "roken.h"
62#include <getarg.h>
63
64struct command {
65    enum { CMD_EXPECT = 0, CMD_SEND, CMD_PASSWORD } type;
66    unsigned int lineno;
67    char *str;
68    struct command *next;
69};
70
71/*
72 *
73 */
74
75static struct command *commands, **next = &commands;
76
77static sig_atomic_t alarmset = 0;
78
79static int timeout = 10;
80static int verbose;
81static int help_flag;
82static int version_flag;
83
84static int master;
85static int slave;
86static char line[256] = { 0 };
87
88static void
89caught_signal(int signo)
90{
91    alarmset = signo;
92}
93
94
95static void
96open_pty(void)
97{
98#ifdef _AIX
99    printf("implement open_pty\n");
100    exit(77);
101#endif
102#if defined(HAVE_OPENPTY) || defined(__linux) || defined(__osf__) /* XXX */
103    if(openpty(&master, &slave, line, 0, 0) == 0)
104	return;
105#endif /* HAVE_OPENPTY .... */
106#ifdef STREAMSPTY
107    {
108	char *clone[] = {
109	    "/dev/ptc",
110	    "/dev/ptmx",
111	    "/dev/ptm",
112	    "/dev/ptym/clone",
113	    NULL
114	};
115	char **q;
116
117	for(q = clone; *q; q++){
118	    master = open(*q, O_RDWR);
119	    if(master >= 0){
120#ifdef HAVE_GRANTPT
121		grantpt(master);
122#endif
123#ifdef HAVE_UNLOCKPT
124		unlockpt(master);
125#endif
126		strlcpy(line, ptsname(master), sizeof(line));
127		slave = open(line, O_RDWR);
128		if (slave < 0)
129		    errx(1, "failed to open slave when using %s", *q);
130		ioctl(slave, I_PUSH, "ptem");
131		ioctl(slave, I_PUSH, "ldterm");
132
133		return;
134	    }
135	}
136    }
137#endif /* STREAMSPTY */
138
139    /* more cases, like open /dev/ptmx, etc */
140
141    exit(77);
142}
143
144/*
145 *
146 */
147
148static char *
149iscmd(const char *buf, const char *s)
150{
151    size_t len = strlen(s);
152    if (strncmp(buf, s, len) != 0)
153	return NULL;
154    return estrdup(buf + len);
155}
156
157static void
158parse_configuration(const char *fn)
159{
160    struct command *c;
161    char s[1024];
162    char *str;
163    unsigned int lineno = 0;
164    FILE *cmd;
165
166    cmd = fopen(fn, "r");
167    if (cmd == NULL)
168	err(1, "open: %s", fn);
169
170    while (fgets(s, sizeof(s),  cmd) != NULL) {
171
172	s[strcspn(s, "#\n")] = '\0';
173	lineno++;
174
175	c = calloc(1, sizeof(*c));
176	if (c == NULL)
177	    errx(1, "malloc");
178
179	c->lineno = lineno;
180	(*next) = c;
181	next = &(c->next);
182
183	if ((str = iscmd(s, "expect ")) != NULL) {
184	    c->type = CMD_EXPECT;
185	    c->str = str;
186	} else if ((str = iscmd(s, "send ")) != NULL) {
187	    c->type = CMD_SEND;
188	    c->str = str;
189	} else if ((str = iscmd(s, "password ")) != NULL) {
190	    c->type = CMD_PASSWORD;
191	    c->str = str;
192	} else
193	    errx(1, "Invalid command on line %d: %s", lineno, s);
194    }
195
196    fclose(cmd);
197}
198
199
200/*
201 *
202 */
203
204static int
205eval_parent(pid_t pid)
206{
207    struct command *c;
208    char in;
209    size_t len = 0;
210    ssize_t sret;
211
212    for (c = commands; c != NULL; c = c->next) {
213	switch(c->type) {
214	case CMD_EXPECT:
215	    if (verbose)
216		printf("[expecting %s]", c->str);
217	    len = 0;
218	    alarm(timeout);
219	    while((sret = read(master, &in, sizeof(in))) > 0) {
220		alarm(timeout);
221		printf("%c", in);
222		if (c->str[len] != in) {
223		    len = 0;
224		    continue;
225		}
226		len++;
227		if (c->str[len] == '\0')
228		    break;
229	    }
230	    alarm(0);
231	    if (alarmset == SIGALRM)
232		errx(1, "timeout waiting for %s (line %u)",
233		     c->str, c->lineno);
234	    else if (alarmset)
235		errx(1, "got a signal %d waiting for %s (line %u)",
236		     alarmset, c->str, c->lineno);
237	    if (sret <= 0)
238		errx(1, "end command while waiting for %s (line %u)",
239		     c->str, c->lineno);
240	    break;
241	case CMD_SEND:
242	case CMD_PASSWORD: {
243	    size_t i = 0;
244	    const char *msg = (c->type == CMD_PASSWORD) ? "****" : c->str;
245
246	    if (verbose)
247		printf("[send %s]", msg);
248
249	    len = strlen(c->str);
250
251	    while (i < len) {
252		if (c->str[i] == '\\' && i < len - 1) {
253		    char ctrl;
254		    i++;
255		    switch(c->str[i]) {
256		    case 'n': ctrl = '\n'; break;
257		    case 'r': ctrl = '\r'; break;
258		    case 't': ctrl = '\t'; break;
259		    default:
260			errx(1, "unknown control char %c (line %u)",
261			     c->str[i], c->lineno);
262		    }
263		    if (net_write(master, &ctrl, 1) != 1)
264			errx(1, "command refused input (line %u)", c->lineno);
265		} else {
266		    if (net_write(master, &c->str[i], 1) != 1)
267			errx(1, "command refused input (line %u)", c->lineno);
268		}
269		i++;
270	    }
271	    break;
272	}
273	default:
274	    abort();
275	}
276    }
277    while(read(master, &in, sizeof(in)) > 0)
278	printf("%c", in);
279
280    if (verbose)
281	printf("[end of program]\n");
282
283    /*
284     * Fetch status from child
285     */
286    {
287	int ret, status;
288
289	ret = waitpid(pid, &status, 0);
290	if (ret == -1)
291	    err(1, "waitpid");
292	if (WIFEXITED(status) && WEXITSTATUS(status))
293	    return WEXITSTATUS(status);
294	else if (WIFSIGNALED(status)) {
295	    printf("killed by signal: %d\n", WTERMSIG(status));
296	    return 1;
297	}
298    }
299    return 0;
300}
301
302/*
303 *
304 */
305
306static struct getargs args[] = {
307    { "timeout", 	't', arg_integer, &timeout, "timout", "seconds" },
308    { "verbose", 	'v', arg_counter, &verbose, "verbose debugging" },
309    { "version",	0, arg_flag,	&version_flag, "print version" },
310    { "help",		0, arg_flag,	&help_flag, NULL }
311};
312
313static void
314usage(int ret)
315{
316    arg_printusage (args, sizeof(args)/sizeof(*args), NULL, "infile command..");
317    exit (ret);
318}
319
320int
321main(int argc, char **argv)
322{
323    int optidx = 0;
324    pid_t pid;
325
326    setprogname(argv[0]);
327
328    if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
329	usage(1);
330
331    if (help_flag)
332	usage (0);
333
334    if (version_flag) {
335	fprintf (stderr, "%s from %s-%s\n", getprogname(), PACKAGE, VERSION);
336	return 0;
337    }
338
339    argv += optidx;
340    argc -= optidx;
341
342    if (argc < 2)
343	usage(1);
344
345    parse_configuration(argv[0]);
346
347    argv += 1;
348
349    open_pty();
350
351    pid = fork();
352    switch (pid) {
353    case -1:
354	err(1, "Failed to fork");
355    case 0:
356
357	if(setsid()<0)
358	    err(1, "setsid");
359
360	dup2(slave, STDIN_FILENO);
361	dup2(slave, STDOUT_FILENO);
362	dup2(slave, STDERR_FILENO);
363	closefrom(STDERR_FILENO + 1);
364
365	execvp(argv[0], argv); /* add NULL to end of array ? */
366	err(1, "Failed to exec: %s", argv[0]);
367    default:
368	close(slave);
369	{
370	    struct sigaction sa;
371
372	    sa.sa_handler = caught_signal;
373	    sa.sa_flags = 0;
374	    sigemptyset (&sa.sa_mask);
375
376	    sigaction(SIGALRM, &sa, NULL);
377	}
378
379	return eval_parent(pid);
380    }
381}
382