1 /* $OpenBSD: misc.c,v 1.109 2017/03/14 00:55:37 dtucker Exp $ */
3 * Copyright (c) 2000 Markus Friedl. All rights reserved.
4 * Copyright (c) 2005,2006 Damien Miller. All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 #include <sys/types.h>
30 #include <sys/ioctl.h>
31 #include <sys/socket.h>
32 #include <sys/sysctl.h>
44 #include <netinet/in.h>
45 #include <netinet/in_systm.h>
46 #include <netinet/ip.h>
47 #include <netinet/tcp.h>
57 #ifdef SSH_TUN_OPENBSD
66 /* remove newline at end of string */
72 if (*t == '\n' || *t == '\r') {
82 /* set/unset filedescriptor to non-blocking */
88 val = fcntl(fd, F_GETFL);
90 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
93 if (val & O_NONBLOCK) {
94 debug3("fd %d is O_NONBLOCK", fd);
97 debug2("fd %d setting O_NONBLOCK", fd);
99 if (fcntl(fd, F_SETFL, val) == -1) {
100 debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
108 unset_nonblock(int fd)
112 val = fcntl(fd, F_GETFL);
114 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
117 if (!(val & O_NONBLOCK)) {
118 debug3("fd %d is not O_NONBLOCK", fd);
121 debug("fd %d clearing O_NONBLOCK", fd);
123 if (fcntl(fd, F_SETFL, val) == -1) {
124 debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
125 fd, strerror(errno));
132 ssh_gai_strerror(int gaierr)
134 if (gaierr == EAI_SYSTEM && errno != 0)
135 return strerror(errno);
136 return gai_strerror(gaierr);
139 /* disable nagle on socket */
147 if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
148 debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
152 debug2("fd %d is TCP_NODELAY", fd);
156 debug2("fd %d setting TCP_NODELAY", fd);
157 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
158 error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
161 /* Characters considered whitespace in strsep calls. */
162 #define WHITESPACE " \t\r\n"
165 /* return next token in configuration line */
177 *s = strpbrk(*s, WHITESPACE QUOTE "=");
182 memmove(*s, *s + 1, strlen(*s)); /* move nul too */
183 /* Find matching quote */
184 if ((*s = strpbrk(*s, QUOTE)) == NULL) {
185 return (NULL); /* no matching quote */
188 *s += strspn(*s + 1, WHITESPACE) + 1;
193 /* Allow only one '=' to be skipped */
198 /* Skip any extra whitespace after first token */
199 *s += strspn(*s + 1, WHITESPACE) + 1;
200 if (*s[0] == '=' && !wspace)
201 *s += strspn(*s + 1, WHITESPACE) + 1;
207 pwcopy(struct passwd *pw)
209 struct passwd *copy = xcalloc(1, sizeof(*copy));
211 copy->pw_name = xstrdup(pw->pw_name);
212 copy->pw_passwd = xstrdup(pw->pw_passwd);
213 #ifdef HAVE_STRUCT_PASSWD_PW_GECOS
214 copy->pw_gecos = xstrdup(pw->pw_gecos);
216 copy->pw_uid = pw->pw_uid;
217 copy->pw_gid = pw->pw_gid;
218 #ifdef HAVE_STRUCT_PASSWD_PW_EXPIRE
219 copy->pw_expire = pw->pw_expire;
221 #ifdef HAVE_STRUCT_PASSWD_PW_CHANGE
222 copy->pw_change = pw->pw_change;
224 #ifdef HAVE_STRUCT_PASSWD_PW_CLASS
225 copy->pw_class = xstrdup(pw->pw_class);
227 copy->pw_dir = xstrdup(pw->pw_dir);
228 copy->pw_shell = xstrdup(pw->pw_shell);
233 * Convert ASCII string to TCP/IP port number.
234 * Port must be >=0 and <=65535.
235 * Return -1 if invalid.
238 a2port(const char *s)
243 port = strtonum(s, 0, 65535, &errstr);
250 a2tun(const char *s, int *remote)
252 const char *errstr = NULL;
256 if (remote != NULL) {
257 *remote = SSH_TUNID_ANY;
259 if ((ep = strchr(sp, ':')) == NULL) {
261 return (a2tun(s, NULL));
264 *remote = a2tun(ep, NULL);
265 tun = a2tun(sp, NULL);
267 return (*remote == SSH_TUNID_ERR ? *remote : tun);
270 if (strcasecmp(s, "any") == 0)
271 return (SSH_TUNID_ANY);
273 tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
275 return (SSH_TUNID_ERR);
281 #define MINUTES (SECONDS * 60)
282 #define HOURS (MINUTES * 60)
283 #define DAYS (HOURS * 24)
284 #define WEEKS (DAYS * 7)
287 * Convert a time string into seconds; format is
291 * Valid time qualifiers are:
305 * Return -1 if time string is invalid.
308 convtime(const char *s)
310 long total, secs, multiplier = 1;
318 if (p == NULL || *p == '\0')
322 secs = strtol(p, &endp, 10);
324 (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
337 multiplier = MINUTES;
354 if (secs >= LONG_MAX / multiplier)
357 if (total >= LONG_MAX - secs)
369 * Returns a standardized host+port identifier string.
370 * Caller must free returned string.
373 put_host_port(const char *host, u_short port)
377 if (port == 0 || port == SSH_DEFAULT_PORT)
378 return(xstrdup(host));
379 if (asprintf(&hoststr, "[%s]:%d", host, (int)port) < 0)
380 fatal("put_host_port: asprintf: %s", strerror(errno));
381 debug3("put_host_port: %s", hoststr);
386 * Search for next delimiter between hostnames/addresses and ports.
387 * Argument may be modified (for termination).
388 * Returns *cp if parsing succeeds.
389 * *cp is set to the start of the next delimiter, if one was found.
390 * If this is the last field, *cp is set to NULL.
397 if (cp == NULL || *cp == NULL)
402 if ((s = strchr(s, ']')) == NULL)
406 } else if ((s = strpbrk(s, ":/")) == NULL)
407 s = *cp + strlen(*cp); /* skip to end (see first case below) */
411 *cp = NULL; /* no more fields*/
416 *s = '\0'; /* terminate */
428 cleanhostname(char *host)
430 if (*host == '[' && host[strlen(host) - 1] == ']') {
431 host[strlen(host) - 1] = '\0';
442 if (*cp == ':') /* Leading colon is part of file name. */
448 if (*cp == '@' && *(cp+1) == '[')
450 if (*cp == ']' && *(cp+1) == ':' && flag)
452 if (*cp == ':' && !flag)
461 * Parse a [user@]host[:port] string.
462 * Caller must free returned user and host.
463 * Any of the pointer return arguments may be NULL (useful for syntax checking).
464 * If user was not specified then *userp will be set to NULL.
465 * If port was not specified then *portp will be -1.
466 * Returns 0 on success, -1 on failure.
469 parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
471 char *sdup, *cp, *tmp;
472 char *user = NULL, *host = NULL;
473 int port = -1, ret = -1;
482 if ((sdup = tmp = strdup(s)) == NULL)
484 /* Extract optional username */
485 if ((cp = strchr(tmp, '@')) != NULL) {
489 if ((user = strdup(tmp)) == NULL)
493 /* Extract mandatory hostname */
494 if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
496 host = xstrdup(cleanhostname(cp));
497 /* Convert and verify optional port */
498 if (tmp != NULL && *tmp != '\0') {
499 if ((port = a2port(tmp)) <= 0)
521 /* function to assist building execv() arguments */
523 addargs(arglist *args, char *fmt, ...)
531 r = vasprintf(&cp, fmt, ap);
534 fatal("addargs: argument too long");
536 nalloc = args->nalloc;
537 if (args->list == NULL) {
540 } else if (args->num+2 >= nalloc)
543 args->list = xreallocarray(args->list, nalloc, sizeof(char *));
544 args->nalloc = nalloc;
545 args->list[args->num++] = cp;
546 args->list[args->num] = NULL;
550 replacearg(arglist *args, u_int which, char *fmt, ...)
557 r = vasprintf(&cp, fmt, ap);
560 fatal("replacearg: argument too long");
562 if (which >= args->num)
563 fatal("replacearg: tried to replace invalid arg %d >= %d",
565 free(args->list[which]);
566 args->list[which] = cp;
570 freeargs(arglist *args)
574 if (args->list != NULL) {
575 for (i = 0; i < args->num; i++)
578 args->nalloc = args->num = 0;
584 * Expands tildes in the file name. Returns data allocated by xmalloc.
585 * Warning: this calls getpw*.
588 tilde_expand_filename(const char *filename, uid_t uid)
590 const char *path, *sep;
591 char user[128], *ret;
595 if (*filename != '~')
596 return (xstrdup(filename));
599 path = strchr(filename, '/');
600 if (path != NULL && path > filename) { /* ~user/path */
601 slash = path - filename;
602 if (slash > sizeof(user) - 1)
603 fatal("tilde_expand_filename: ~username too long");
604 memcpy(user, filename, slash);
606 if ((pw = getpwnam(user)) == NULL)
607 fatal("tilde_expand_filename: No such user %s", user);
608 } else if ((pw = getpwuid(uid)) == NULL) /* ~/path */
609 fatal("tilde_expand_filename: No such uid %ld", (long)uid);
611 /* Make sure directory has a trailing '/' */
612 len = strlen(pw->pw_dir);
613 if (len == 0 || pw->pw_dir[len - 1] != '/')
618 /* Skip leading '/' from specified path */
622 if (xasprintf(&ret, "%s%s%s", pw->pw_dir, sep, filename) >= PATH_MAX)
623 fatal("tilde_expand_filename: Path too long");
629 * Expand a string with a set of %[char] escapes. A number of escapes may be
630 * specified as (char *escape_chars, char *replacement) pairs. The list must
631 * be terminated by a NULL escape_char. Returns replaced string in memory
632 * allocated by xmalloc.
635 percent_expand(const char *string, ...)
637 #define EXPAND_MAX_KEYS 16
638 u_int num_keys, i, j;
642 } keys[EXPAND_MAX_KEYS];
647 va_start(ap, string);
648 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
649 keys[num_keys].key = va_arg(ap, char *);
650 if (keys[num_keys].key == NULL)
652 keys[num_keys].repl = va_arg(ap, char *);
653 if (keys[num_keys].repl == NULL)
654 fatal("%s: NULL replacement", __func__);
656 if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
657 fatal("%s: too many keys", __func__);
662 for (i = 0; *string != '\0'; string++) {
663 if (*string != '%') {
666 if (i >= sizeof(buf))
667 fatal("%s: string too long", __func__);
676 fatal("%s: invalid format", __func__);
677 for (j = 0; j < num_keys; j++) {
678 if (strchr(keys[j].key, *string) != NULL) {
679 i = strlcat(buf, keys[j].repl, sizeof(buf));
680 if (i >= sizeof(buf))
681 fatal("%s: string too long", __func__);
686 fatal("%s: unknown key %%%c", __func__, *string);
688 return (xstrdup(buf));
689 #undef EXPAND_MAX_KEYS
693 * Read an entire line from a public key file into a static buffer, discarding
694 * lines that exceed the buffer size. Returns 0 on success, -1 on failure.
697 read_keyfile_line(FILE *f, const char *filename, char *buf, size_t bufsz,
700 while (fgets(buf, bufsz, f) != NULL) {
704 if (buf[strlen(buf) - 1] == '\n' || feof(f)) {
707 debug("%s: %s line %lu exceeds size limit", __func__,
709 /* discard remainder of line */
710 while (fgetc(f) != '\n' && !feof(f))
718 tun_open(int tun, int mode)
720 #if defined(CUSTOM_SYS_TUN_OPEN)
721 return (sys_tun_open(tun, mode));
722 #elif defined(SSH_TUN_OPENBSD)
726 const char *tunbase = "tun";
728 if (mode == SSH_TUNMODE_ETHERNET)
731 /* Open the tunnel device */
732 if (tun <= SSH_TUNID_MAX) {
733 snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
734 fd = open(name, O_RDWR);
735 } else if (tun == SSH_TUNID_ANY) {
736 for (tun = 100; tun >= 0; tun--) {
737 snprintf(name, sizeof(name), "/dev/%s%d",
739 if ((fd = open(name, O_RDWR)) >= 0)
743 debug("%s: invalid tunnel %u", __func__, tun);
748 debug("%s: %s open: %s", __func__, name, strerror(errno));
752 debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
754 /* Bring interface up if it is not already */
755 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
756 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
759 if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
760 debug("%s: get interface %s flags: %s", __func__,
761 ifr.ifr_name, strerror(errno));
765 if (!(ifr.ifr_flags & IFF_UP)) {
766 ifr.ifr_flags |= IFF_UP;
767 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
768 debug("%s: activate interface %s: %s", __func__,
769 ifr.ifr_name, strerror(errno));
784 error("Tunnel interfaces are not supported on this platform");
794 if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
795 fprintf(stderr, "Couldn't open /dev/null: %s\n",
799 while (++dupfd <= STDERR_FILENO) {
800 /* Only populate closed fds. */
801 if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
802 if (dup2(nullfd, dupfd) == -1) {
803 fprintf(stderr, "dup2: %s\n", strerror(errno));
808 if (nullfd > STDERR_FILENO)
813 tohex(const void *vp, size_t l)
815 const u_char *p = (const u_char *)vp;
820 return xstrdup("tohex: length > 65536");
824 for (i = 0; i < l; i++) {
825 snprintf(b, sizeof(b), "%02x", p[i]);
832 get_u64(const void *vp)
834 const u_char *p = (const u_char *)vp;
837 v = (u_int64_t)p[0] << 56;
838 v |= (u_int64_t)p[1] << 48;
839 v |= (u_int64_t)p[2] << 40;
840 v |= (u_int64_t)p[3] << 32;
841 v |= (u_int64_t)p[4] << 24;
842 v |= (u_int64_t)p[5] << 16;
843 v |= (u_int64_t)p[6] << 8;
844 v |= (u_int64_t)p[7];
850 get_u32(const void *vp)
852 const u_char *p = (const u_char *)vp;
855 v = (u_int32_t)p[0] << 24;
856 v |= (u_int32_t)p[1] << 16;
857 v |= (u_int32_t)p[2] << 8;
858 v |= (u_int32_t)p[3];
864 get_u32_le(const void *vp)
866 const u_char *p = (const u_char *)vp;
870 v |= (u_int32_t)p[1] << 8;
871 v |= (u_int32_t)p[2] << 16;
872 v |= (u_int32_t)p[3] << 24;
878 get_u16(const void *vp)
880 const u_char *p = (const u_char *)vp;
883 v = (u_int16_t)p[0] << 8;
884 v |= (u_int16_t)p[1];
890 put_u64(void *vp, u_int64_t v)
892 u_char *p = (u_char *)vp;
894 p[0] = (u_char)(v >> 56) & 0xff;
895 p[1] = (u_char)(v >> 48) & 0xff;
896 p[2] = (u_char)(v >> 40) & 0xff;
897 p[3] = (u_char)(v >> 32) & 0xff;
898 p[4] = (u_char)(v >> 24) & 0xff;
899 p[5] = (u_char)(v >> 16) & 0xff;
900 p[6] = (u_char)(v >> 8) & 0xff;
901 p[7] = (u_char)v & 0xff;
905 put_u32(void *vp, u_int32_t v)
907 u_char *p = (u_char *)vp;
909 p[0] = (u_char)(v >> 24) & 0xff;
910 p[1] = (u_char)(v >> 16) & 0xff;
911 p[2] = (u_char)(v >> 8) & 0xff;
912 p[3] = (u_char)v & 0xff;
916 put_u32_le(void *vp, u_int32_t v)
918 u_char *p = (u_char *)vp;
920 p[0] = (u_char)v & 0xff;
921 p[1] = (u_char)(v >> 8) & 0xff;
922 p[2] = (u_char)(v >> 16) & 0xff;
923 p[3] = (u_char)(v >> 24) & 0xff;
927 put_u16(void *vp, u_int16_t v)
929 u_char *p = (u_char *)vp;
931 p[0] = (u_char)(v >> 8) & 0xff;
932 p[1] = (u_char)v & 0xff;
936 ms_subtract_diff(struct timeval *start, int *ms)
938 struct timeval diff, finish;
940 gettimeofday(&finish, NULL);
941 timersub(&finish, start, &diff);
942 *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
946 ms_to_timeval(struct timeval *tv, int ms)
950 tv->tv_sec = ms / 1000;
951 tv->tv_usec = (ms % 1000) * 1000;
957 #if defined(HAVE_CLOCK_GETTIME) && \
958 (defined(CLOCK_MONOTONIC) || defined(CLOCK_BOOTTIME))
960 static int gettime_failed = 0;
962 if (!gettime_failed) {
963 #if defined(CLOCK_BOOTTIME)
964 if (clock_gettime(CLOCK_BOOTTIME, &ts) == 0)
967 #if defined(CLOCK_MONOTONIC)
968 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
971 debug3("clock_gettime: %s", strerror(errno));
974 #endif /* HAVE_CLOCK_GETTIME && (CLOCK_MONOTONIC || CLOCK_BOOTTIME */
980 monotime_double(void)
982 #if defined(HAVE_CLOCK_GETTIME) && \
983 (defined(CLOCK_MONOTONIC) || defined(CLOCK_BOOTTIME))
985 static int gettime_failed = 0;
987 if (!gettime_failed) {
988 #if defined(CLOCK_BOOTTIME)
989 if (clock_gettime(CLOCK_BOOTTIME, &ts) == 0)
990 return (ts.tv_sec + (double)ts.tv_nsec / 1000000000);
992 #if defined(CLOCK_MONOTONIC)
993 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
994 return (ts.tv_sec + (double)ts.tv_nsec / 1000000000);
996 debug3("clock_gettime: %s", strerror(errno));
999 #endif /* HAVE_CLOCK_GETTIME && (CLOCK_MONOTONIC || CLOCK_BOOTTIME */
1001 return (double)time(NULL);
1005 bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
1007 bw->buflen = buflen;
1009 bw->thresh = bw->rate;
1011 timerclear(&bw->bwstart);
1012 timerclear(&bw->bwend);
1015 /* Callback from read/write loop to insert bandwidth-limiting delays */
1017 bandwidth_limit(struct bwlimit *bw, size_t read_len)
1020 struct timespec ts, rm;
1022 if (!timerisset(&bw->bwstart)) {
1023 gettimeofday(&bw->bwstart, NULL);
1027 bw->lamt += read_len;
1028 if (bw->lamt < bw->thresh)
1031 gettimeofday(&bw->bwend, NULL);
1032 timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
1033 if (!timerisset(&bw->bwend))
1037 waitlen = (double)1000000L * bw->lamt / bw->rate;
1039 bw->bwstart.tv_sec = waitlen / 1000000L;
1040 bw->bwstart.tv_usec = waitlen % 1000000L;
1042 if (timercmp(&bw->bwstart, &bw->bwend, >)) {
1043 timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
1045 /* Adjust the wait time */
1046 if (bw->bwend.tv_sec) {
1048 if (bw->thresh < bw->buflen / 4)
1049 bw->thresh = bw->buflen / 4;
1050 } else if (bw->bwend.tv_usec < 10000) {
1052 if (bw->thresh > bw->buflen * 8)
1053 bw->thresh = bw->buflen * 8;
1056 TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
1057 while (nanosleep(&ts, &rm) == -1) {
1065 gettimeofday(&bw->bwstart, NULL);
1068 /* Make a template filename for mk[sd]temp() */
1070 mktemp_proto(char *s, size_t len)
1075 if ((tmpdir = getenv("TMPDIR")) != NULL) {
1076 r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1077 if (r > 0 && (size_t)r < len)
1080 r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1081 if (r < 0 || (size_t)r >= len)
1082 fatal("%s: template string too short", __func__);
1085 static const struct {
1089 { "af11", IPTOS_DSCP_AF11 },
1090 { "af12", IPTOS_DSCP_AF12 },
1091 { "af13", IPTOS_DSCP_AF13 },
1092 { "af21", IPTOS_DSCP_AF21 },
1093 { "af22", IPTOS_DSCP_AF22 },
1094 { "af23", IPTOS_DSCP_AF23 },
1095 { "af31", IPTOS_DSCP_AF31 },
1096 { "af32", IPTOS_DSCP_AF32 },
1097 { "af33", IPTOS_DSCP_AF33 },
1098 { "af41", IPTOS_DSCP_AF41 },
1099 { "af42", IPTOS_DSCP_AF42 },
1100 { "af43", IPTOS_DSCP_AF43 },
1101 { "cs0", IPTOS_DSCP_CS0 },
1102 { "cs1", IPTOS_DSCP_CS1 },
1103 { "cs2", IPTOS_DSCP_CS2 },
1104 { "cs3", IPTOS_DSCP_CS3 },
1105 { "cs4", IPTOS_DSCP_CS4 },
1106 { "cs5", IPTOS_DSCP_CS5 },
1107 { "cs6", IPTOS_DSCP_CS6 },
1108 { "cs7", IPTOS_DSCP_CS7 },
1109 { "ef", IPTOS_DSCP_EF },
1110 { "lowdelay", IPTOS_LOWDELAY },
1111 { "throughput", IPTOS_THROUGHPUT },
1112 { "reliability", IPTOS_RELIABILITY },
1117 parse_ipqos(const char *cp)
1125 for (i = 0; ipqos[i].name != NULL; i++) {
1126 if (strcasecmp(cp, ipqos[i].name) == 0)
1127 return ipqos[i].value;
1129 /* Try parsing as an integer */
1130 val = strtol(cp, &ep, 0);
1131 if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1137 iptos2str(int iptos)
1140 static char iptos_str[sizeof "0xff"];
1142 for (i = 0; ipqos[i].name != NULL; i++) {
1143 if (ipqos[i].value == iptos)
1144 return ipqos[i].name;
1146 snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1154 *s = tolower((u_char)*s);
1158 unix_listener(const char *path, int backlog, int unlink_first)
1160 struct sockaddr_un sunaddr;
1161 int saved_errno, sock;
1163 memset(&sunaddr, 0, sizeof(sunaddr));
1164 sunaddr.sun_family = AF_UNIX;
1165 if (strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1166 error("%s: \"%s\" too long for Unix domain socket", __func__,
1168 errno = ENAMETOOLONG;
1172 sock = socket(PF_UNIX, SOCK_STREAM, 0);
1174 saved_errno = errno;
1175 error("socket: %.100s", strerror(errno));
1176 errno = saved_errno;
1179 if (unlink_first == 1) {
1180 if (unlink(path) != 0 && errno != ENOENT)
1181 error("unlink(%s): %.100s", path, strerror(errno));
1183 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0) {
1184 saved_errno = errno;
1185 error("bind: %.100s", strerror(errno));
1187 error("%s: cannot bind to path: %s", __func__, path);
1188 errno = saved_errno;
1191 if (listen(sock, backlog) < 0) {
1192 saved_errno = errno;
1193 error("listen: %.100s", strerror(errno));
1196 error("%s: cannot listen on path: %s", __func__, path);
1197 errno = saved_errno;
1204 sock_set_v6only(int s)
1206 #if defined(IPV6_V6ONLY) && !defined(__OpenBSD__)
1209 debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
1210 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
1211 error("setsockopt IPV6_V6ONLY: %s", strerror(errno));
1216 * Compares two strings that maybe be NULL. Returns non-zero if strings
1217 * are both NULL or are identical, returns zero otherwise.
1220 strcmp_maybe_null(const char *a, const char *b)
1222 if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1224 if (a != NULL && strcmp(a, b) != 0)
1230 * Compare two forwards, returning non-zero if they are identical or
1234 forward_equals(const struct Forward *a, const struct Forward *b)
1236 if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
1238 if (a->listen_port != b->listen_port)
1240 if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
1242 if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
1244 if (a->connect_port != b->connect_port)
1246 if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
1248 /* allocated_port and handle are not checked */
1253 ipport_reserved(void)
1257 size_t len = sizeof(old);
1259 ret = sysctlbyname("net.inet.ip.portrange.reservedhigh",
1260 &old, &len, NULL, 0);
1264 return (IPPORT_RESERVED);
1267 /* returns 1 if bind to specified port by specified user is permitted */
1269 bind_permitted(int port, uid_t uid)
1272 if (port < ipport_reserved() && uid != 0)
1277 /* returns 1 if process is already daemonized, 0 otherwise */
1283 if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
1285 return 0; /* have controlling terminal */
1288 return 0; /* parent is not init */
1289 if (getsid(0) != getpid())
1290 return 0; /* not session leader */
1291 debug3("already daemonized");