Remove __P macros from src/usr.bin and src/usr.sbin.
[dragonfly.git] / usr.sbin / inetd / builtins.c
1 /*-
2  * Copyright (c) 1983, 1991, 1993, 1994
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  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD: src/usr.sbin/inetd/builtins.c,v 1.19.2.7 2002/07/22 14:05:56 fanf Exp $
27  * $DragonFly: src/usr.sbin/inetd/builtins.c,v 1.3 2003/11/03 19:31:37 eirikn Exp $
28  *
29  */
30
31 #include <sys/filio.h>
32 #include <sys/ioccom.h>
33 #include <sys/param.h>
34 #include <sys/stat.h>
35 #include <sys/socket.h>
36 #include <sys/sysctl.h>
37 #include <sys/ucred.h>
38 #include <sys/uio.h>
39 #include <sys/utsname.h>
40
41 #include <ctype.h>
42 #include <err.h>
43 #include <errno.h>
44 #include <fcntl.h>
45 #include <limits.h>
46 #include <pwd.h>
47 #include <signal.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <sysexits.h>
51 #include <syslog.h>
52 #include <unistd.h>
53
54 #include "inetd.h"
55
56 void            chargen_dg(int, struct servtab *);
57 void            chargen_stream(int, struct servtab *);
58 void            daytime_dg(int, struct servtab *);
59 void            daytime_stream(int, struct servtab *);
60 void            discard_dg(int, struct servtab *);
61 void            discard_stream(int, struct servtab *);
62 void            echo_dg(int, struct servtab *);
63 void            echo_stream(int, struct servtab *);
64 static int      getline(int, char *, int);
65 void            iderror(int, int, int, const char *);
66 void            ident_stream(int, struct servtab *);
67 void            initring(void);
68 unsigned long   machtime(void);
69 void            machtime_dg(int, struct servtab *);
70 void            machtime_stream(int, struct servtab *);
71
72 char ring[128];
73 char *endring;
74
75
76 struct biltin biltins[] = {
77         /* Echo received data */
78         { "echo",       SOCK_STREAM,    1, -1,  echo_stream },
79         { "echo",       SOCK_DGRAM,     0, 1,   echo_dg },
80
81         /* Internet /dev/null */
82         { "discard",    SOCK_STREAM,    1, -1,  discard_stream },
83         { "discard",    SOCK_DGRAM,     0, 1,   discard_dg },
84
85         /* Return 32 bit time since 1900 */
86         { "time",       SOCK_STREAM,    0, -1,  machtime_stream },
87         { "time",       SOCK_DGRAM,     0, 1,   machtime_dg },
88
89         /* Return human-readable time */
90         { "daytime",    SOCK_STREAM,    0, -1,  daytime_stream },
91         { "daytime",    SOCK_DGRAM,     0, 1,   daytime_dg },
92
93         /* Familiar character generator */
94         { "chargen",    SOCK_STREAM,    1, -1,  chargen_stream },
95         { "chargen",    SOCK_DGRAM,     0, 1,   chargen_dg },
96
97         { "tcpmux",     SOCK_STREAM,    1, -1,  (bi_fn_t *)tcpmux },
98
99         { "auth",       SOCK_STREAM,    1, -1,  ident_stream },
100
101         { NULL,         0,              0, 0,   NULL }
102 };
103
104 /*
105  * RFC864 Character Generator Protocol. Generates character data without
106  * any regard for input.
107  */
108
109 void
110 initring()
111 {
112         int i;
113
114         endring = ring;
115
116         for (i = 0; i <= 128; ++i)
117                 if (isprint(i))
118                         *endring++ = i;
119 }
120
121 /* ARGSUSED */
122 void
123 chargen_dg(s, sep)              /* Character generator */
124         int s;
125         struct servtab *sep;
126 {
127         struct sockaddr_storage ss;
128         static char *rs;
129         int len;
130         socklen_t size;
131         char text[LINESIZ+2];
132
133         if (endring == 0) {
134                 initring();
135                 rs = ring;
136         }
137
138         size = sizeof(ss);
139         if (recvfrom(s, text, sizeof(text), 0,
140                      (struct sockaddr *)&ss, &size) < 0)
141                 return;
142
143         if (check_loop((struct sockaddr *)&ss, sep))
144                 return;
145
146         if ((len = endring - rs) >= LINESIZ)
147                 memmove(text, rs, LINESIZ);
148         else {
149                 memmove(text, rs, len);
150                 memmove(text + len, ring, LINESIZ - len);
151         }
152         if (++rs == endring)
153                 rs = ring;
154         text[LINESIZ] = '\r';
155         text[LINESIZ + 1] = '\n';
156         (void) sendto(s, text, sizeof(text), 0, (struct sockaddr *)&ss, size);
157 }
158
159 /* ARGSUSED */
160 void
161 chargen_stream(s, sep)          /* Character generator */
162         int s;
163         struct servtab *sep;
164 {
165         int len;
166         char *rs, text[LINESIZ+2];
167
168         inetd_setproctitle(sep->se_service, s);
169
170         if (!endring) {
171                 initring();
172                 rs = ring;
173         }
174
175         text[LINESIZ] = '\r';
176         text[LINESIZ + 1] = '\n';
177         for (rs = ring;;) {
178                 if ((len = endring - rs) >= LINESIZ)
179                         memmove(text, rs, LINESIZ);
180                 else {
181                         memmove(text, rs, len);
182                         memmove(text + len, ring, LINESIZ - len);
183                 }
184                 if (++rs == endring)
185                         rs = ring;
186                 if (write(s, text, sizeof(text)) != sizeof(text))
187                         break;
188         }
189         exit(0);
190 }
191
192 /*
193  * RFC867 Daytime Protocol. Sends the current date and time as an ascii
194  * character string without any regard for input.
195  */
196
197 /* ARGSUSED */
198 void
199 daytime_dg(s, sep)              /* Return human-readable time of day */
200         int s;
201         struct servtab *sep;
202 {
203         char buffer[256];
204         time_t now;
205         struct sockaddr_storage ss;
206         socklen_t size;
207
208         now = time((time_t *) 0);
209
210         size = sizeof(ss);
211         if (recvfrom(s, buffer, sizeof(buffer), 0,
212                      (struct sockaddr *)&ss, &size) < 0)
213                 return;
214
215         if (check_loop((struct sockaddr *)&ss, sep))
216                 return;
217
218         (void) sprintf(buffer, "%.24s\r\n", ctime(&now));
219         (void) sendto(s, buffer, strlen(buffer), 0,
220                       (struct sockaddr *)&ss, size);
221 }
222
223 /* ARGSUSED */
224 void
225 daytime_stream(s, sep)          /* Return human-readable time of day */
226         int s;
227         struct servtab *sep __unused;
228 {
229         char buffer[256];
230         time_t now;
231
232         now = time((time_t *) 0);
233
234         (void) sprintf(buffer, "%.24s\r\n", ctime(&now));
235         (void) send(s, buffer, strlen(buffer), MSG_EOF);
236 }
237
238 /*
239  * RFC863 Discard Protocol. Any data received is thrown away and no response
240  * is sent.
241  */
242
243 /* ARGSUSED */
244 void
245 discard_dg(s, sep)              /* Discard service -- ignore data */
246         int s;
247         struct servtab *sep __unused;
248 {
249         char buffer[BUFSIZE];
250
251         (void) read(s, buffer, sizeof(buffer));
252 }
253
254 /* ARGSUSED */
255 void
256 discard_stream(s, sep)          /* Discard service -- ignore data */
257         int s;
258         struct servtab *sep;
259 {
260         int ret;
261         char buffer[BUFSIZE];
262
263         inetd_setproctitle(sep->se_service, s);
264         while (1) {
265                 while ((ret = read(s, buffer, sizeof(buffer))) > 0)
266                         ;
267                 if (ret == 0 || errno != EINTR)
268                         break;
269         }
270         exit(0);
271 }
272
273 /*
274  * RFC862 Echo Protocol. Any data received is sent back to the sender as
275  * received.
276  */
277
278 /* ARGSUSED */
279 void
280 echo_dg(s, sep)                 /* Echo service -- echo data back */
281         int s;
282         struct servtab *sep;
283 {
284         char buffer[65536]; /* Should be sizeof(max datagram). */
285         int i;
286         socklen_t size;
287         struct sockaddr_storage ss;
288
289         size = sizeof(ss);
290         if ((i = recvfrom(s, buffer, sizeof(buffer), 0,
291                           (struct sockaddr *)&ss, &size)) < 0)
292                 return;
293
294         if (check_loop((struct sockaddr *)&ss, sep))
295                 return;
296
297         (void) sendto(s, buffer, i, 0, (struct sockaddr *)&ss, size);
298 }
299
300 /* ARGSUSED */
301 void
302 echo_stream(s, sep)             /* Echo service -- echo data back */
303         int s;
304         struct servtab *sep;
305 {
306         char buffer[BUFSIZE];
307         int i;
308
309         inetd_setproctitle(sep->se_service, s);
310         while ((i = read(s, buffer, sizeof(buffer))) > 0 &&
311             write(s, buffer, i) > 0)
312                 ;
313         exit(0);
314 }
315
316 /*
317  * RFC1413 Identification Protocol. Given a TCP port number pair, return a
318  * character string which identifies the owner of that connection on the
319  * server's system. Extended to allow for ~/.fakeid support and ~/.noident
320  * support.
321  */
322
323 /* RFC 1413 says the following are the only errors you can return. */
324 #define ID_INVALID      "INVALID-PORT"  /* Port number improperly specified. */
325 #define ID_NOUSER       "NO-USER"       /* Port not in use/not identifable. */
326 #define ID_HIDDEN       "HIDDEN-USER"   /* Hiden at user's request. */
327 #define ID_UNKNOWN      "UNKNOWN-ERROR" /* Everything else. */
328
329 /* ARGSUSED */
330 void
331 iderror(lport, fport, s, er)    /* Generic ident_stream error-sending func */
332         int lport, fport, s;
333         const char *er;
334 {
335         char *p;
336
337         asprintf(&p, "%d , %d : ERROR : %s\r\n", lport, fport, er);
338         if (p == NULL) {
339                 syslog(LOG_ERR, "asprintf: %m");
340                 exit(EX_OSERR);
341         }
342         send(s, p, strlen(p), MSG_EOF);
343         free(p);
344
345         exit(0);
346 }
347
348 /* ARGSUSED */
349 void
350 ident_stream(s, sep)            /* Ident service (AKA "auth") */
351         int s;
352         struct servtab *sep;
353 {
354         struct utsname un;
355         struct stat sb;
356         struct sockaddr_in sin4[2];
357 #ifdef INET6
358         struct sockaddr_in6 sin6[2];
359 #endif
360         struct sockaddr_storage ss[2];
361         struct ucred uc;
362         struct timeval tv = {
363                 10,
364                 0
365         }, to;
366         struct passwd *pw = NULL;
367         fd_set fdset;
368         char buf[BUFSIZE], *p, **av, *osname = NULL, e;
369         char idbuf[MAXLOGNAME] = ""; /* Big enough to hold uid in decimal. */
370         socklen_t socklen;
371         ssize_t ssize;
372         size_t size, bufsiz;
373         int c, fflag = 0, nflag = 0, rflag = 0, argc = 0;
374         int gflag = 0, iflag = 0, Fflag = 0, getcredfail = 0, onreadlen;
375         u_short lport, fport;
376
377         inetd_setproctitle(sep->se_service, s);
378         /*
379          * Reset getopt() since we are a fork() but not an exec() from
380          * a parent which used getopt() already.
381          */
382         optind = 1;
383         optreset = 1;
384         /*
385          * Take the internal argument vector and count it out to make an
386          * argument count for getopt. This can be used for any internal
387          * service to read arguments and use getopt() easily.
388          */
389         for (av = sep->se_argv; *av; av++)
390                 argc++;
391         if (argc) {
392                 int sec, usec;
393                 size_t i;
394                 u_int32_t rnd32;
395
396                 while ((c = getopt(argc, sep->se_argv, "d:fFgino:rt:")) != -1)
397                         switch (c) {
398                         case 'd':
399                                 if (!gflag)
400                                         strlcpy(idbuf, optarg, sizeof(idbuf));
401                                 break;
402                         case 'f':
403                                 fflag = 1;
404                                 break;
405                         case 'F':
406                                 fflag = 1;
407                                 Fflag=1;
408                                 break;
409                         case 'g':
410                                 gflag = 1;
411                                 rnd32 = 0;      /* Shush, compiler. */
412                                 /*
413                                  * The number of bits in "rnd32" divided
414                                  * by the number of bits needed per iteration
415                                  * gives a more optimal way to reload the
416                                  * random number only when necessary.
417                                  *
418                                  * 32 bits from arc4random corresponds to
419                                  * about 6 base-36 digits, so we reseed evey 6.
420                                  */
421                                 for (i = 0; i < sizeof(idbuf) - 1; i++) {
422                                         static const char *const base36 =
423                                             "0123456789"
424                                             "abcdefghijklmnopqrstuvwxyz";
425                                         if (i % 6 == 0)
426                                                 rnd32 = arc4random();
427                                         idbuf[i] = base36[rnd32 % 36];
428                                         rnd32 /= 36;
429                                 }
430                                 idbuf[i] = '\0';
431                                 break;
432                         case 'i':
433                                 iflag = 1;
434                                 break;
435                         case 'n':
436                                 nflag = 1;
437                                 break;
438                         case 'o':
439                                 osname = optarg;
440                                 break;
441                         case 'r':
442                                 rflag = 1;
443                                 break;
444                         case 't':
445                                 switch (sscanf(optarg, "%d.%d", &sec, &usec)) {
446                                 case 2:
447                                         tv.tv_usec = usec;
448                                         /* FALLTHROUGH */
449                                 case 1:
450                                         tv.tv_sec = sec;
451                                         break;
452                                 default:
453                                         if (debug)
454                                                 warnx("bad -t argument");
455                                         break;
456                                 }
457                                 break;
458                         default:
459                                 break;
460                         }
461         }
462         if (osname == NULL) {
463                 if (uname(&un) == -1)
464                         iderror(0, 0, s, ID_UNKNOWN);
465                 osname = un.sysname;
466         }
467
468         /*
469          * We're going to prepare for and execute reception of a
470          * packet of data from the user. The data is in the format
471          * "local_port , foreign_port\r\n" (with local being the
472          * server's port and foreign being the client's.)
473          */
474         gettimeofday(&to, NULL);
475         to.tv_sec += tv.tv_sec;
476         to.tv_usec += tv.tv_usec;
477         if (to.tv_usec >= 1000000) {
478                 to.tv_usec -= 1000000;
479                 to.tv_sec++;
480         }
481
482         size = 0;
483         bufsiz = sizeof(buf) - 1;
484         FD_ZERO(&fdset);
485         while (bufsiz > 0) {
486                 gettimeofday(&tv, NULL);
487                 tv.tv_sec = to.tv_sec - tv.tv_sec;
488                 tv.tv_usec = to.tv_usec - tv.tv_usec;
489                 if (tv.tv_usec < 0) {
490                         tv.tv_usec += 1000000;
491                         tv.tv_sec--;
492                 }
493                 if (tv.tv_sec < 0)
494                         break;
495                 FD_SET(s, &fdset);
496                 if (select(s + 1, &fdset, NULL, NULL, &tv) == -1)
497                         iderror(0, 0, s, ID_UNKNOWN);
498                 if (ioctl(s, FIONREAD, &onreadlen) == -1)
499                         iderror(0, 0, s, ID_UNKNOWN);
500                 if ((size_t)onreadlen > bufsiz)
501                         onreadlen = bufsiz;
502                 ssize = read(s, &buf[size], (size_t)onreadlen);
503                 if (ssize == -1)
504                         iderror(0, 0, s, ID_UNKNOWN);
505                 else if (ssize == 0)
506                         break;
507                 bufsiz -= ssize;
508                 size += ssize;
509                 if (memchr(&buf[size - ssize], '\n', ssize) != NULL)
510                         break;
511         }
512         buf[size] = '\0';
513         /* Read two characters, and check for a delimiting character */
514         if (sscanf(buf, "%hu , %hu%c", &lport, &fport, &e) != 3 || isdigit(e))
515                 iderror(0, 0, s, ID_INVALID);
516
517         /* Send garbage? */
518         if (gflag)
519                 goto printit;
520
521         /*
522          * If not "real" (-r), send a HIDDEN-USER error for everything.
523          * If -d is used to set a fallback username, this is used to
524          * override it, and the fallback is returned instead.
525          */
526         if (!rflag) {
527                 if (*idbuf == '\0')
528                         iderror(lport, fport, s, ID_HIDDEN);
529                 goto printit;
530         }
531
532         /*
533          * We take the input and construct an array of two sockaddr_ins
534          * which contain the local address information and foreign
535          * address information, respectively, used to look up the
536          * credentials for the socket (which are returned by the
537          * sysctl "net.inet.tcp.getcred" when we call it.)
538          */
539         socklen = sizeof(ss[0]);
540         if (getsockname(s, (struct sockaddr *)&ss[0], &socklen) == -1)
541                 iderror(lport, fport, s, ID_UNKNOWN);
542         socklen = sizeof(ss[1]);
543         if (getpeername(s, (struct sockaddr *)&ss[1], &socklen) == -1)
544                 iderror(lport, fport, s, ID_UNKNOWN);
545         if (ss[0].ss_family != ss[1].ss_family)
546                 iderror(lport, fport, s, ID_UNKNOWN);
547         size = sizeof(uc);
548         switch (ss[0].ss_family) {
549         case AF_INET:
550                 sin4[0] = *(struct sockaddr_in *)&ss[0];
551                 sin4[0].sin_port = htons(lport);
552                 sin4[1] = *(struct sockaddr_in *)&ss[1];
553                 sin4[1].sin_port = htons(fport);
554                 if (sysctlbyname("net.inet.tcp.getcred", &uc, &size, sin4,
555                                  sizeof(sin4)) == -1)
556                         getcredfail = errno;
557                 break;
558 #ifdef INET6
559         case AF_INET6:
560                 sin6[0] = *(struct sockaddr_in6 *)&ss[0];
561                 sin6[0].sin6_port = htons(lport);
562                 sin6[1] = *(struct sockaddr_in6 *)&ss[1];
563                 sin6[1].sin6_port = htons(fport);
564                 if (sysctlbyname("net.inet6.tcp6.getcred", &uc, &size, sin6,
565                                  sizeof(sin6)) == -1)
566                         getcredfail = errno;
567                 break;
568 #endif
569         default: /* should not reach here */
570                 getcredfail = EAFNOSUPPORT;
571                 break;
572         }
573         if (getcredfail != 0) {
574                 if (*idbuf == '\0')
575                         iderror(lport, fport, s,
576                             getcredfail == ENOENT ? ID_NOUSER : ID_UNKNOWN);
577                 goto printit;
578         }
579
580         /* Look up the pw to get the username and home directory*/
581         errno = 0;
582         pw = getpwuid(uc.cr_uid);
583         if (pw == NULL)
584                 iderror(lport, fport, s, errno == 0 ? ID_NOUSER : ID_UNKNOWN);
585
586         if (iflag)
587                 snprintf(idbuf, sizeof(idbuf), "%u", (unsigned)pw->pw_uid);
588         else
589                 strlcpy(idbuf, pw->pw_name, sizeof(idbuf));
590
591         /*
592          * If enabled, we check for a file named ".noident" in the user's
593          * home directory. If found, we return HIDDEN-USER.
594          */
595         if (nflag) {
596                 if (asprintf(&p, "%s/.noident", pw->pw_dir) == -1)
597                         iderror(lport, fport, s, ID_UNKNOWN);
598                 if (lstat(p, &sb) == 0) {
599                         free(p);
600                         iderror(lport, fport, s, ID_HIDDEN);
601                 }
602                 free(p);
603         }
604
605         /*
606          * Here, if enabled, we read a user's ".fakeid" file in their
607          * home directory. It consists of a line containing the name
608          * they want.
609          */
610         if (fflag) {
611                 int fakeid_fd;
612
613                 /*
614                  * Here we set ourself to effectively be the user, so we don't
615                  * open any files we have no permission to open, especially
616                  * symbolic links to sensitive root-owned files or devices.
617                  */
618                 if (initgroups(pw->pw_name, pw->pw_gid) == -1)
619                         iderror(lport, fport, s, ID_UNKNOWN);
620                 if (seteuid(pw->pw_uid) == -1)
621                         iderror(lport, fport, s, ID_UNKNOWN);
622                 /*
623                  * We can't stat() here since that would be a race
624                  * condition.
625                  * Therefore, we open the file we have permissions to open
626                  * and if it's not a regular file, we close it and end up
627                  * returning the user's real username.
628                  */
629                 if (asprintf(&p, "%s/.fakeid", pw->pw_dir) == -1)
630                         iderror(lport, fport, s, ID_UNKNOWN);
631                 fakeid_fd = open(p, O_RDONLY | O_NONBLOCK);
632                 free(p);
633                 if (fakeid_fd == -1 || fstat(fakeid_fd, &sb) == -1 ||
634                     !S_ISREG(sb.st_mode))
635                         goto fakeid_fail;
636
637                 if ((ssize = read(fakeid_fd, buf, sizeof(buf) - 1)) < 0)
638                         goto fakeid_fail;
639                 buf[ssize] = '\0';
640
641                 /*
642                  * Usually, the file will have the desired identity
643                  * in the form "identity\n". Allow for leading white
644                  * space and trailing white space/end of line.
645                  */
646                 p = buf;
647                 p += strspn(p, " \t");
648                 p[strcspn(p, " \t\r\n")] = '\0';
649                 if (strlen(p) > MAXLOGNAME - 1) /* Too long (including nul)? */
650                         p[MAXLOGNAME - 1] = '\0';
651
652                 /*
653                  * If the name is a zero-length string or matches it
654                  * the id or name of another user (unless permitted by -F)
655                  * then it is invalid.
656                  */
657                 if (*p == '\0')
658                         goto fakeid_fail;
659                 if (!Fflag) {
660                         if (iflag) {
661                                 if (p[strspn(p, "0123456789")] == '\0' &&
662                                     getpwuid(atoi(p)) != NULL)
663                                         goto fakeid_fail;
664                         } else {
665                                 if (getpwnam(p) != NULL)
666                                         goto fakeid_fail;
667                         }
668                 }
669
670                 strlcpy(idbuf, p, sizeof(idbuf));
671
672 fakeid_fail:
673                 if (fakeid_fd != -1)
674                         close(fakeid_fd);
675         }
676
677 printit:
678         /* Finally, we make and send the reply. */
679         if (asprintf(&p, "%d , %d : USERID : %s : %s\r\n", lport, fport, osname,
680             idbuf) == -1) {
681                 syslog(LOG_ERR, "asprintf: %m");
682                 exit(EX_OSERR);
683         }
684         send(s, p, strlen(p), MSG_EOF);
685         free(p);
686         
687         exit(0);
688 }
689
690 /*
691  * RFC738 Time Server.
692  * Return a machine readable date and time, in the form of the
693  * number of seconds since midnight, Jan 1, 1900.  Since gettimeofday
694  * returns the number of seconds since midnight, Jan 1, 1970,
695  * we must add 2208988800 seconds to this figure to make up for
696  * some seventy years Bell Labs was asleep.
697  */
698
699 unsigned long
700 machtime()
701 {
702         struct timeval tv;
703
704         if (gettimeofday(&tv, (struct timezone *)NULL) < 0) {
705                 if (debug)
706                         warnx("unable to get time of day");
707                 return (0L);
708         }
709 #define OFFSET ((u_long)25567 * 24*60*60)
710         return (htonl((long)(tv.tv_sec + OFFSET)));
711 #undef OFFSET
712 }
713
714 /* ARGSUSED */
715 void
716 machtime_dg(s, sep)
717         int s;
718         struct servtab *sep;
719 {
720         unsigned long result;
721         struct sockaddr_storage ss;
722         socklen_t size;
723
724         size = sizeof(ss);
725         if (recvfrom(s, (char *)&result, sizeof(result), 0,
726                      (struct sockaddr *)&ss, &size) < 0)
727                 return;
728
729         if (check_loop((struct sockaddr *)&ss, sep))
730                 return;
731
732         result = machtime();
733         (void) sendto(s, (char *) &result, sizeof(result), 0,
734                       (struct sockaddr *)&ss, size);
735 }
736
737 /* ARGSUSED */
738 void
739 machtime_stream(s, sep)
740         int s;
741         struct servtab *sep __unused;
742 {
743         unsigned long result;
744
745         result = machtime();
746         (void) send(s, (char *) &result, sizeof(result), MSG_EOF);
747 }
748
749 /*
750  * RFC1078 TCP Port Service Multiplexer (TCPMUX). Service connections to
751  * services based on the service name sent.
752  *
753  *  Based on TCPMUX.C by Mark K. Lottor November 1988
754  *  sri-nic::ps:<mkl>tcpmux.c
755  */
756
757 #define MAX_SERV_LEN    (256+2)         /* 2 bytes for \r\n */
758 #define strwrite(fd, buf)       (void) write(fd, buf, sizeof(buf)-1)
759
760 static int              /* # of characters upto \r,\n or \0 */
761 getline(fd, buf, len)
762         int fd;
763         char *buf;
764         int len;
765 {
766         int count = 0, n;
767         struct sigaction sa;
768
769         sa.sa_flags = 0;
770         sigemptyset(&sa.sa_mask);
771         sa.sa_handler = SIG_DFL;
772         sigaction(SIGALRM, &sa, (struct sigaction *)0);
773         do {
774                 alarm(10);
775                 n = read(fd, buf, len-count);
776                 alarm(0);
777                 if (n == 0)
778                         return (count);
779                 if (n < 0)
780                         return (-1);
781                 while (--n >= 0) {
782                         if (*buf == '\r' || *buf == '\n' || *buf == '\0')
783                                 return (count);
784                         count++;
785                         buf++;
786                 }
787         } while (count < len);
788         return (count);
789 }
790
791 struct servtab *
792 tcpmux(s)
793         int s;
794 {
795         struct servtab *sep;
796         char service[MAX_SERV_LEN+1];
797         int len;
798
799         /* Get requested service name */
800         if ((len = getline(s, service, MAX_SERV_LEN)) < 0) {
801                 strwrite(s, "-Error reading service name\r\n");
802                 return (NULL);
803         }
804         service[len] = '\0';
805
806         if (debug)
807                 warnx("tcpmux: someone wants %s", service);
808
809         /*
810          * Help is a required command, and lists available services,
811          * one per line.
812          */
813         if (!strcasecmp(service, "help")) {
814                 for (sep = servtab; sep; sep = sep->se_next) {
815                         if (!ISMUX(sep))
816                                 continue;
817                         (void)write(s,sep->se_service,strlen(sep->se_service));
818                         strwrite(s, "\r\n");
819                 }
820                 return (NULL);
821         }
822
823         /* Try matching a service in inetd.conf with the request */
824         for (sep = servtab; sep; sep = sep->se_next) {
825                 if (!ISMUX(sep))
826                         continue;
827                 if (!strcasecmp(service, sep->se_service)) {
828                         if (ISMUXPLUS(sep)) {
829                                 strwrite(s, "+Go\r\n");
830                         }
831                         return (sep);
832                 }
833         }
834         strwrite(s, "-Service not available\r\n");
835         return (NULL);
836 }