25ca9750440cad393bb187f6deb4a1cb8a6398b6
[dragonfly.git] / lib / libcompat / 4.3 / rexec.c
1 /*
2  * Copyright (c) 1980, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University 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 REGENTS 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 REGENTS 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  * $FreeBSD: src/lib/libcompat/4.3/rexec.c,v 1.5.8.3 2000/11/22 13:36:00 ben Exp $
34  *
35  * @(#)rexec.c  8.1 (Berkeley) 6/4/93
36  */
37
38 #include <sys/types.h>
39 #include <sys/uio.h>
40 #include <sys/socket.h>
41 #include <sys/param.h>
42 #include <sys/stat.h>
43
44 #include <netinet/in.h>
45
46 #include <stdio.h>
47 #include <unistd.h>
48 #include <string.h>
49 #include <netdb.h>
50 #include <errno.h>
51 #include <ctype.h>
52 #include <err.h>
53 #include <stdlib.h>
54
55 #define SA_LEN(addr)            ((addr)->sa_len)
56 #define __set_errno(val)        errno = (val)
57
58 int     rexecoptions;
59 char    *getpass(), *getlogin();
60
61 /*
62  * Options and other state info.
63  */
64 struct macel {
65         char mac_name[9];       /* macro name */
66         char *mac_start;        /* start of macro in macbuf */
67         char *mac_end;          /* end of macro in macbuf */
68 };
69
70 int macnum;                     /* number of defined macros */
71 struct macel macros[16];
72 char macbuf[4096];
73
74 static  FILE *cfile;
75
76 #define DEFAULT 1
77 #define LOGIN   2
78 #define PASSWD  3
79 #define ACCOUNT 4
80 #define MACDEF  5
81 #define ID      10
82 #define MACH    11
83
84 static char tokval[100];
85
86 static struct toktab {
87         char *tokstr;
88         int tval;
89 } toktab[]= {
90         { "default",    DEFAULT },
91         { "login",      LOGIN },
92         { "password",   PASSWD },
93         { "passwd",     PASSWD },
94         { "account",    ACCOUNT },
95         { "machine",    MACH },
96         { "macdef",     MACDEF },
97         { NULL,         0 }
98 };
99
100 static int
101 token(void)
102 {
103         char *cp;
104         int c;
105         struct toktab *t;
106
107         if (feof(cfile) || ferror(cfile))
108                 return (0);
109         while ((c = getc(cfile)) != EOF &&
110             (c == '\n' || c == '\t' || c == ' ' || c == ','))
111                 continue;
112         if (c == EOF)
113                 return (0);
114         cp = tokval;
115         if (c == '"') {
116                 while ((c = getc(cfile)) != EOF && c != '"') {
117                         if (c == '\\')
118                                 c = getc(cfile);
119                         *cp++ = c;
120                 }
121         } else {
122                 *cp++ = c;
123                 while ((c = getc(cfile)) != EOF
124                     && c != '\n' && c != '\t' && c != ' ' && c != ',') {
125                         if (c == '\\')
126                                 c = getc(cfile);
127                         *cp++ = c;
128                 }
129         }
130         *cp = 0;
131         if (tokval[0] == 0)
132                 return (0);
133         for (t = toktab; t->tokstr; t++)
134                 if (!strcmp(t->tokstr, tokval))
135                         return (t->tval);
136         return (ID);
137 }
138
139 static int
140 ruserpass(char *host, const char **aname, const char **apass, char **aacct)
141 {
142         char *hdir, buf[BUFSIZ], *tmp;
143         char myname[MAXHOSTNAMELEN], *mydomain;
144         int t, i, c, usedefault = 0;
145         struct stat stb;
146
147         hdir = getenv("HOME");
148         if (hdir == NULL)
149                 hdir = ".";
150         if (strlen(hdir) + 8 > sizeof(buf))
151                 return (0);
152         (void) sprintf(buf, "%s/.netrc", hdir);
153         cfile = fopen(buf, "r");
154         if (cfile == NULL) {
155                 if (errno != ENOENT)
156                         warn("%s", buf);
157                 return (0);
158         }
159         if (gethostname(myname, sizeof(myname)) < 0)
160                 myname[0] = '\0';
161         if ((mydomain = strchr(myname, '.')) == NULL)
162                 mydomain = "";
163 next:
164         while ((t = token())) switch(t) {
165
166         case DEFAULT:
167                 usedefault = 1;
168                 /* FALL THROUGH */
169
170         case MACH:
171                 if (!usedefault) {
172                         if (token() != ID)
173                                 continue;
174                         /*
175                          * Allow match either for user's input host name
176                          * or official hostname.  Also allow match of
177                          * incompletely-specified host in local domain.
178                          */
179                         if (strcasecmp(host, tokval) == 0)
180                                 goto match;
181                         if ((tmp = strchr(host, '.')) != NULL &&
182                             strcasecmp(tmp, mydomain) == 0 &&
183                             strncasecmp(host, tokval, tmp - host) == 0 &&
184                             tokval[tmp - host] == '\0')
185                                 goto match;
186                         continue;
187                 }
188         match:
189                 while ((t = token()) && t != MACH && t != DEFAULT) switch(t) {
190
191                 case LOGIN:
192                         if (token()) {
193                                 if (*aname == NULL) {
194                                         char *tmp;
195                                         tmp = malloc(strlen(tokval) + 1);
196                                         strcpy(tmp, tokval);
197                                         *aname = tmp;
198                                 } else {
199                                         if (strcmp(*aname, tokval))
200                                                 goto next;
201                                 }
202                         }
203                         break;
204                 case PASSWD:
205                         if ((*aname == NULL || strcmp(*aname, "anonymous")) &&
206                             fstat(fileno(cfile), &stb) >= 0 &&
207                             (stb.st_mode & 077) != 0) {
208         warnx("Error: .netrc file is readable by others.");
209         warnx("Remove password or make file unreadable by others.");
210                                 goto bad;
211                         }
212                         if (token() && *apass == NULL) {
213                                 char *tmp;
214                                 tmp = malloc(strlen(tokval) + 1);
215                                 strcpy(tmp, tokval);
216                                 *apass = tmp;
217                         }
218                         break;
219                 case ACCOUNT:
220                         if (fstat(fileno(cfile), &stb) >= 0
221                             && (stb.st_mode & 077) != 0) {
222         warnx("Error: .netrc file is readable by others.");
223         warnx("Remove account or make file unreadable by others.");
224                                 goto bad;
225                         }
226                         if (token() && *aacct == NULL) {
227                                 *aacct = malloc((unsigned) strlen(tokval) + 1);
228                                 (void) strcpy(*aacct, tokval);
229                         }
230                         break;
231                 case MACDEF:
232                         while ((c=getc(cfile)) != EOF &&
233                                                 (c == ' ' || c == '\t'))
234                                 ;
235                         if (c == EOF || c == '\n') {
236                                 printf("Missing macdef name argument.\n");
237                                 goto bad;
238                         }
239                         if (macnum == 16) {
240                                 printf("Limit of 16 macros have already been defined\n");
241                                 goto bad;
242                         }
243                         tmp = macros[macnum].mac_name;
244                         *tmp++ = c;
245                         for (i=0; i < 8 && (c=getc(cfile)) != EOF &&
246                             !isspace(c); ++i) {
247                                 *tmp++ = c;
248                         }
249                         if (c == EOF) {
250                                 printf("Macro definition missing null line terminator.\n");
251                                 goto bad;
252                         }
253                         *tmp = '\0';
254                         if (c != '\n') {
255                                 while ((c=getc(cfile)) != EOF && c != '\n');
256                         }
257                         if (c == EOF) {
258                                 printf("Macro definition missing null line terminator.\n");
259                                 goto bad;
260                         }
261                         if (macnum == 0) {
262                                 macros[macnum].mac_start = macbuf;
263                         }
264                         else {
265                                 macros[macnum].mac_start = macros[macnum-1].mac_end + 1;
266                         }
267                         tmp = macros[macnum].mac_start;
268                         while (tmp != macbuf + 4096) {
269                                 if ((c=getc(cfile)) == EOF) {
270                                 printf("Macro definition missing null line terminator.\n");
271                                         goto bad;
272                                 }
273                                 *tmp = c;
274                                 if (*tmp == '\n') {
275                                         if (*(tmp-1) == '\0') {
276                                            macros[macnum++].mac_end = tmp - 1;
277                                            break;
278                                         }
279                                         *tmp = '\0';
280                                 }
281                                 tmp++;
282                         }
283                         if (tmp == macbuf + 4096) {
284                                 printf("4K macro buffer exceeded\n");
285                                 goto bad;
286                         }
287                         break;
288                 default:
289                         warnx("Unknown .netrc keyword %s", tokval);
290                         break;
291                 }
292                 goto done;
293         }
294 done:
295         (void) fclose(cfile);
296         return (0);
297 bad:
298         (void) fclose(cfile);
299         return (-1);
300 }
301
302 int
303 rexec_af(char **ahost, int rport, const char *name, const char *pass,
304     const char *cmd, int *fd2p, sa_family_t *af)
305 {
306         struct sockaddr_storage sa2, from;
307         struct addrinfo hints, *res0;
308         const char *orig_name = name;
309         const char *orig_pass = pass;
310         static char *ahostbuf;
311         u_short port = 0;
312         int s, timo = 1, s3;
313         char c;
314         int gai;
315         char servbuff[NI_MAXSERV];
316
317         snprintf(servbuff, sizeof(servbuff), "%d", ntohs(rport));
318         servbuff[sizeof(servbuff) - 1] = '\0';
319
320         memset(&hints, '\0', sizeof(hints));
321         if (af)
322                 hints.ai_family = *af;
323         hints.ai_socktype = SOCK_STREAM;
324         hints.ai_flags = AI_CANONNAME;
325         gai = getaddrinfo(*ahost, servbuff, &hints, &res0);
326         if (gai){
327                 /* XXX: set errno? */
328                 return -1;
329         }
330
331         if (res0->ai_canonname){
332                 free (ahostbuf);
333                 ahostbuf = strdup (res0->ai_canonname);
334                 if (ahostbuf == NULL) {
335                         perror ("rexec: strdup");
336                         return (-1);
337                 }
338                 *ahost = ahostbuf;
339         } else {
340                 *ahost = NULL;
341                 __set_errno (ENOENT);
342                 return -1;
343         }
344         ruserpass(res0->ai_canonname, &name, &pass, 0);
345 retry:
346         s = socket(res0->ai_family, res0->ai_socktype, 0);
347         if (s < 0) {
348                 perror("rexec: socket");
349                 return (-1);
350         }
351         if (connect(s, res0->ai_addr, res0->ai_addrlen) < 0) {
352                 if (errno == ECONNREFUSED && timo <= 16) {
353                         (void) close(s);
354                         sleep(timo);
355                         timo *= 2;
356                         goto retry;
357                 }
358                 perror(res0->ai_canonname);
359                 return (-1);
360         }
361         if (fd2p == NULL) {
362                 (void) write(s, "", 1);
363                 port = 0;
364         } else {
365                 char num[32];
366                 int s2;
367                 socklen_t sa2len;
368
369                 s2 = socket(res0->ai_family, res0->ai_socktype, 0);
370                 if (s2 < 0) {
371                         (void) close(s);
372                         return (-1);
373                 }
374                 listen(s2, 1);
375                 sa2len = sizeof (sa2);
376                 if (getsockname(s2, (struct sockaddr *)&sa2, &sa2len) < 0) {
377                         perror("getsockname");
378                         (void) close(s2);
379                         goto bad;
380                 } else if (sa2len != SA_LEN((struct sockaddr *)&sa2)) {
381                         __set_errno(EINVAL);
382                         (void) close(s2);
383                         goto bad;
384                 }
385                 port = 0;
386                 if (!getnameinfo((struct sockaddr *)&sa2, sa2len,
387                                  NULL, 0, servbuff, sizeof(servbuff),
388                                  NI_NUMERICSERV))
389                         port = atoi(servbuff);
390                 (void) sprintf(num, "%u", port);
391                 (void) write(s, num, strlen(num)+1);
392                 { socklen_t len = sizeof (from);
393                   s3 = accept(s2, (struct sockaddr *)&from,
394                                                   &len);
395                   close(s2);
396                   if (s3 < 0) {
397                         perror("accept");
398                         port = 0;
399                         goto bad;
400                   }
401                 }
402                 *fd2p = s3;
403         }
404
405         (void) write(s, name, strlen(name) + 1);
406         /* should public key encypt the password here */
407         (void) write(s, pass, strlen(pass) + 1);
408         (void) write(s, cmd, strlen(cmd) + 1);
409
410         /* We don't need the memory allocated for the name and the password
411            in ruserpass anymore.  */
412         if (name != orig_name)
413           free ((char *) name);
414         if (pass != orig_pass)
415           free ((char *) pass);
416
417         if (read(s, &c, 1) != 1) {
418                 perror(*ahost);
419                 goto bad;
420         }
421         if (c != 0) {
422                 while (read(s, &c, 1) == 1) {
423                         (void) write(2, &c, 1);
424                         if (c == '\n')
425                                 break;
426                 }
427                 goto bad;
428         }
429         freeaddrinfo(res0);
430         return (s);
431 bad:
432         if (port)
433                 (void) close(*fd2p);
434         (void) close(s);
435         freeaddrinfo(res0);
436         return (-1);
437 }
438
439
440 int
441 rexec(char **ahost, int rport, const char *name, const char *pass, char *cmd, int *fd2p)
442 {
443         struct sockaddr_in sin, sin2, from;
444         struct hostent *hp;
445         u_short port;
446         int s, timo = 1, s3;
447         char c;
448         char *acct = NULL;
449
450         hp = gethostbyname(*ahost);
451         if (hp == NULL) {
452                 herror(*ahost);
453                 return (-1);
454         }
455         *ahost = hp->h_name;
456         ruserpass(hp->h_name, &name, &pass, &acct);
457         if (acct != NULL)
458                 free(acct);
459 retry:
460         s = socket(AF_INET, SOCK_STREAM, 0);
461         if (s < 0) {
462                 perror("rexec: socket");
463                 return (-1);
464         }
465         sin.sin_family = hp->h_addrtype;
466         sin.sin_port = rport;
467         bcopy(hp->h_addr, (caddr_t)&sin.sin_addr, hp->h_length);
468         if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
469                 if (errno == ECONNREFUSED && timo <= 16) {
470                         (void) close(s);
471                         sleep(timo);
472                         timo *= 2;
473                         goto retry;
474                 }
475                 perror(hp->h_name);
476                 return (-1);
477         }
478         if (fd2p == NULL) {
479                 (void) write(s, "", 1);
480                 port = 0;
481         } else {
482                 char num[8];
483                 int s2, sin2len;
484
485                 s2 = socket(AF_INET, SOCK_STREAM, 0);
486                 if (s2 < 0) {
487                         (void) close(s);
488                         return (-1);
489                 }
490                 listen(s2, 1);
491                 sin2len = sizeof (sin2);
492                 if (getsockname(s2, (struct sockaddr *)&sin2, &sin2len) < 0 ||
493                   sin2len != sizeof (sin2)) {
494                         perror("getsockname");
495                         (void) close(s2);
496                         goto bad;
497                 }
498                 port = ntohs((u_short)sin2.sin_port);
499                 (void) sprintf(num, "%u", port);
500                 (void) write(s, num, strlen(num)+1);
501                 { int len = sizeof (from);
502                   s3 = accept(s2, (struct sockaddr *)&from, &len);
503                   close(s2);
504                   if (s3 < 0) {
505                         perror("accept");
506                         port = 0;
507                         goto bad;
508                   }
509                 }
510                 *fd2p = s3;
511         }
512         (void) write(s, name, strlen(name) + 1);
513         /* should public key encypt the password here */
514         (void) write(s, pass, strlen(pass) + 1);
515         (void) write(s, cmd, strlen(cmd) + 1);
516         if (read(s, &c, 1) != 1) {
517                 perror(*ahost);
518                 goto bad;
519         }
520         if (c != 0) {
521                 while (read(s, &c, 1) == 1) {
522                         (void) write(2, &c, 1);
523                         if (c == '\n')
524                                 break;
525                 }
526                 goto bad;
527         }
528         return (s);
529 bad:
530         if (port)
531                 (void) close(*fd2p);
532         (void) close(s);
533         return (-1);
534 }