1/*	$NetBSD: rkpty.c,v 1.2 2017/01/28 21:31:50 christos Exp $	*/
2
3/*
4 * Copyright (c) 2008 Kungliga Tekniska H��gskolan
5 * (Royal Institute of Technology, Stockholm, Sweden).
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 *
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions and the following disclaimer.
14 *
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 *
19 * 3. Neither the name of the Institute nor the names of its contributors
20 *    may be used to endorse or promote products derived from this software
21 *    without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 */
35
36#include "config.h"
37
38#ifndef HAVE_SYS_TYPES_H
39#include <sys/types.h>
40#endif
41#ifdef HAVE_SYS_WAIT_H
42#include <sys/wait.h>
43#endif
44#include <stdio.h>
45#include <stdlib.h>
46#ifdef HAVE_UNISTD_H
47#include <unistd.h>
48#endif
49#ifdef HAVE_PTY_H
50#include <pty.h>
51#endif
52#ifdef HAVE_UTIL_H
53#include <util.h>
54#endif
55#ifdef HAVE_LIBUTIL_H
56#include <libutil.h>
57#endif
58
59#ifdef	STREAMSPTY
60#include <stropts.h>
61#endif /* STREAMPTY */
62
63#include <krb5/roken.h>
64#include <krb5/getarg.h>
65
66struct command {
67    enum { CMD_EXPECT = 0, CMD_SEND, CMD_PASSWORD } type;
68    unsigned int lineno;
69    char *str;
70    struct command *next;
71};
72
73/*
74 *
75 */
76
77static struct command *commands, **next = &commands;
78
79static sig_atomic_t alarmset = 0;
80
81static int timeout = 10;
82static int verbose;
83static int help_flag;
84static int version_flag;
85
86static int master;
87static int slave;
88static char line[256] = { 0 };
89
90static void
91caught_signal(int signo)
92{
93    alarmset = signo;
94}
95
96
97static void
98open_pty(void)
99{
100#ifdef _AIX
101    printf("implement open_pty\n");
102    exit(77);
103#endif
104#if defined(HAVE_OPENPTY) || defined(__osf__) /* XXX */
105    if(openpty(&master, &slave, line, 0, 0) == 0)
106	return;
107#endif /* HAVE_OPENPTY .... */
108#ifdef STREAMSPTY
109    {
110	char *clone[] = {
111	    "/dev/ptc",
112	    "/dev/ptmx",
113	    "/dev/ptm",
114	    "/dev/ptym/clone",
115	    NULL
116	};
117	char **q;
118
119	for(q = clone; *q; q++){
120	    master = open(*q, O_RDWR);
121	    if(master >= 0){
122#ifdef HAVE_GRANTPT
123		grantpt(master);
124#endif
125#ifdef HAVE_UNLOCKPT
126		unlockpt(master);
127#endif
128		strlcpy(line, ptsname(master), sizeof(line));
129		slave = open(line, O_RDWR);
130		if (slave < 0)
131		    errx(1, "failed to open slave when using %s", *q);
132		ioctl(slave, I_PUSH, "ptem");
133		ioctl(slave, I_PUSH, "ldterm");
134
135		return;
136	    }
137	}
138    }
139#endif /* STREAMSPTY */
140
141    /* more cases, like open /dev/ptmx, etc */
142
143    exit(77);
144}
145
146/*
147 *
148 */
149
150static char *
151iscmd(const char *buf, const char *s)
152{
153    size_t len = strlen(s);
154    if (strncmp(buf, s, len) != 0)
155	return NULL;
156    return estrdup(buf + len);
157}
158
159static void
160parse_configuration(const char *fn)
161{
162    struct command *c;
163    char s[1024];
164    char *str;
165    unsigned int lineno = 0;
166    FILE *cmd;
167
168    cmd = fopen(fn, "r");
169    if (cmd == NULL)
170	err(1, "open: %s", fn);
171
172    while (fgets(s, sizeof(s),  cmd) != NULL) {
173
174	s[strcspn(s, "#\n")] = '\0';
175	lineno++;
176
177	c = calloc(1, sizeof(*c));
178	if (c == NULL)
179	    errx(1, "malloc");
180
181	c->lineno = lineno;
182	(*next) = c;
183	next = &(c->next);
184
185	if ((str = iscmd(s, "expect ")) != NULL) {
186	    c->type = CMD_EXPECT;
187	    c->str = str;
188	} else if ((str = iscmd(s, "send ")) != NULL) {
189	    c->type = CMD_SEND;
190	    c->str = str;
191	} else if ((str = iscmd(s, "password ")) != NULL) {
192	    c->type = CMD_PASSWORD;
193	    c->str = str;
194	} else
195	    errx(1, "Invalid command on line %d: %s", lineno, s);
196    }
197
198    fclose(cmd);
199}
200
201
202/*
203 *
204 */
205
206static int
207eval_parent(pid_t pid)
208{
209    struct command *c;
210    char in;
211    size_t len = 0;
212    ssize_t sret;
213
214    for (c = commands; c != NULL; c = c->next) {
215	switch(c->type) {
216	case CMD_EXPECT:
217	    if (verbose)
218		printf("[expecting %s]", c->str);
219	    len = 0;
220	    alarm(timeout);
221	    while((sret = read(master, &in, sizeof(in))) > 0) {
222		alarm(timeout);
223		printf("%c", in);
224		if (c->str[len] != in) {
225		    len = 0;
226		    continue;
227		}
228		len++;
229		if (c->str[len] == '\0')
230		    break;
231	    }
232	    alarm(0);
233	    if (alarmset == SIGALRM)
234		errx(1, "timeout waiting for %s (line %u)",
235		     c->str, c->lineno);
236	    else if (alarmset)
237		errx(1, "got a signal %d waiting for %s (line %u)",
238		     (int)alarmset, c->str, c->lineno);
239	    if (sret <= 0)
240		errx(1, "end command while waiting for %s (line %u)",
241		     c->str, c->lineno);
242	    break;
243	case CMD_SEND:
244	case CMD_PASSWORD: {
245	    size_t i = 0;
246	    const char *msg = (c->type == CMD_PASSWORD) ? "****" : c->str;
247
248	    if (verbose)
249		printf("[send %s]", msg);
250
251	    len = strlen(c->str);
252
253	    while (i < len) {
254		if (c->str[i] == '\\' && i < len - 1) {
255		    char ctrl;
256		    i++;
257		    switch(c->str[i]) {
258		    case 'n': ctrl = '\n'; break;
259		    case 'r': ctrl = '\r'; break;
260		    case 't': ctrl = '\t'; break;
261		    default:
262			errx(1, "unknown control char %c (line %u)",
263			     c->str[i], c->lineno);
264		    }
265		    if (net_write(master, &ctrl, 1) != 1)
266			errx(1, "command refused input (line %u)", c->lineno);
267		} else {
268		    if (net_write(master, &c->str[i], 1) != 1)
269			errx(1, "command refused input (line %u)", c->lineno);
270		}
271		i++;
272	    }
273	    break;
274	}
275	default:
276	    abort();
277	}
278    }
279    while(read(master, &in, sizeof(in)) > 0)
280	printf("%c", in);
281
282    if (verbose)
283	printf("[end of program]\n");
284
285    /*
286     * Fetch status from child
287     */
288    {
289	int ret, status;
290
291	ret = waitpid(pid, &status, 0);
292	if (ret == -1)
293	    err(1, "waitpid");
294	if (WIFEXITED(status) && WEXITSTATUS(status))
295	    return WEXITSTATUS(status);
296	else if (WIFSIGNALED(status)) {
297	    printf("killed by signal: %d\n", WTERMSIG(status));
298	    return 1;
299	}
300    }
301    return 0;
302}
303
304/*
305 *
306 */
307
308static struct getargs args[] = {
309    { "timeout", 	't', arg_integer, &timeout, "timout", "seconds" },
310    { "verbose", 	'v', arg_counter, &verbose, "verbose debugging", NULL },
311    { "version",	0, arg_flag,	&version_flag, "print version", NULL },
312    { "help",		0, arg_flag,	&help_flag, NULL, NULL }
313};
314
315static void
316usage(int ret)
317{
318    arg_printusage (args, sizeof(args)/sizeof(*args), NULL, "infile command..");
319    exit (ret);
320}
321
322int
323main(int argc, char **argv)
324{
325    int optidx = 0;
326    pid_t pid;
327
328    setprogname(argv[0]);
329
330    if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &optidx))
331	usage(1);
332
333    if (help_flag)
334	usage (0);
335
336    if (version_flag) {
337	fprintf (stderr, "%s from %s-%s\n", getprogname(), PACKAGE, VERSION);
338	return 0;
339    }
340
341    argv += optidx;
342    argc -= optidx;
343
344    if (argc < 2)
345	usage(1);
346
347    parse_configuration(argv[0]);
348
349    argv += 1;
350
351    open_pty();
352
353    pid = fork();
354    switch (pid) {
355    case -1:
356	err(1, "Failed to fork");
357    case 0:
358
359	if(setsid()<0)
360	    err(1, "setsid");
361
362	dup2(slave, STDIN_FILENO);
363	dup2(slave, STDOUT_FILENO);
364	dup2(slave, STDERR_FILENO);
365	closefrom(STDERR_FILENO + 1);
366
367	execvp(argv[0], argv); /* add NULL to end of array ? */
368	err(1, "Failed to exec: %s", argv[0]);
369    default:
370	close(slave);
371	{
372	    struct sigaction sa;
373
374	    sa.sa_handler = caught_signal;
375	    sa.sa_flags = 0;
376	    sigemptyset (&sa.sa_mask);
377
378	    sigaction(SIGALRM, &sa, NULL);
379	}
380
381	return eval_parent(pid);
382    }
383}
384