1 /* $OpenBSD: misc.c,v 1.107 2016/11/30 00:28:31 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)
318 if (p == NULL || *p == '\0')
322 secs = strtol(p, &endp, 10);
324 (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
364 * Returns a standardized host+port identifier string.
365 * Caller must free returned string.
368 put_host_port(const char *host, u_short port)
372 if (port == 0 || port == SSH_DEFAULT_PORT)
373 return(xstrdup(host));
374 if (asprintf(&hoststr, "[%s]:%d", host, (int)port) < 0)
375 fatal("put_host_port: asprintf: %s", strerror(errno));
376 debug3("put_host_port: %s", hoststr);
381 * Search for next delimiter between hostnames/addresses and ports.
382 * Argument may be modified (for termination).
383 * Returns *cp if parsing succeeds.
384 * *cp is set to the start of the next delimiter, if one was found.
385 * If this is the last field, *cp is set to NULL.
392 if (cp == NULL || *cp == NULL)
397 if ((s = strchr(s, ']')) == NULL)
401 } else if ((s = strpbrk(s, ":/")) == NULL)
402 s = *cp + strlen(*cp); /* skip to end (see first case below) */
406 *cp = NULL; /* no more fields*/
411 *s = '\0'; /* terminate */
423 cleanhostname(char *host)
425 if (*host == '[' && host[strlen(host) - 1] == ']') {
426 host[strlen(host) - 1] = '\0';
437 if (*cp == ':') /* Leading colon is part of file name. */
443 if (*cp == '@' && *(cp+1) == '[')
445 if (*cp == ']' && *(cp+1) == ':' && flag)
447 if (*cp == ':' && !flag)
456 * Parse a [user@]host[:port] string.
457 * Caller must free returned user and host.
458 * Any of the pointer return arguments may be NULL (useful for syntax checking).
459 * If user was not specified then *userp will be set to NULL.
460 * If port was not specified then *portp will be -1.
461 * Returns 0 on success, -1 on failure.
464 parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
466 char *sdup, *cp, *tmp;
467 char *user = NULL, *host = NULL;
468 int port = -1, ret = -1;
477 if ((sdup = tmp = strdup(s)) == NULL)
479 /* Extract optional username */
480 if ((cp = strchr(tmp, '@')) != NULL) {
484 if ((user = strdup(tmp)) == NULL)
488 /* Extract mandatory hostname */
489 if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
491 host = xstrdup(cleanhostname(cp));
492 /* Convert and verify optional port */
493 if (tmp != NULL && *tmp != '\0') {
494 if ((port = a2port(tmp)) <= 0)
516 /* function to assist building execv() arguments */
518 addargs(arglist *args, char *fmt, ...)
526 r = vasprintf(&cp, fmt, ap);
529 fatal("addargs: argument too long");
531 nalloc = args->nalloc;
532 if (args->list == NULL) {
535 } else if (args->num+2 >= nalloc)
538 args->list = xreallocarray(args->list, nalloc, sizeof(char *));
539 args->nalloc = nalloc;
540 args->list[args->num++] = cp;
541 args->list[args->num] = NULL;
545 replacearg(arglist *args, u_int which, char *fmt, ...)
552 r = vasprintf(&cp, fmt, ap);
555 fatal("replacearg: argument too long");
557 if (which >= args->num)
558 fatal("replacearg: tried to replace invalid arg %d >= %d",
560 free(args->list[which]);
561 args->list[which] = cp;
565 freeargs(arglist *args)
569 if (args->list != NULL) {
570 for (i = 0; i < args->num; i++)
573 args->nalloc = args->num = 0;
579 * Expands tildes in the file name. Returns data allocated by xmalloc.
580 * Warning: this calls getpw*.
583 tilde_expand_filename(const char *filename, uid_t uid)
585 const char *path, *sep;
586 char user[128], *ret;
590 if (*filename != '~')
591 return (xstrdup(filename));
594 path = strchr(filename, '/');
595 if (path != NULL && path > filename) { /* ~user/path */
596 slash = path - filename;
597 if (slash > sizeof(user) - 1)
598 fatal("tilde_expand_filename: ~username too long");
599 memcpy(user, filename, slash);
601 if ((pw = getpwnam(user)) == NULL)
602 fatal("tilde_expand_filename: No such user %s", user);
603 } else if ((pw = getpwuid(uid)) == NULL) /* ~/path */
604 fatal("tilde_expand_filename: No such uid %ld", (long)uid);
606 /* Make sure directory has a trailing '/' */
607 len = strlen(pw->pw_dir);
608 if (len == 0 || pw->pw_dir[len - 1] != '/')
613 /* Skip leading '/' from specified path */
617 if (xasprintf(&ret, "%s%s%s", pw->pw_dir, sep, filename) >= PATH_MAX)
618 fatal("tilde_expand_filename: Path too long");
624 * Expand a string with a set of %[char] escapes. A number of escapes may be
625 * specified as (char *escape_chars, char *replacement) pairs. The list must
626 * be terminated by a NULL escape_char. Returns replaced string in memory
627 * allocated by xmalloc.
630 percent_expand(const char *string, ...)
632 #define EXPAND_MAX_KEYS 16
633 u_int num_keys, i, j;
637 } keys[EXPAND_MAX_KEYS];
642 va_start(ap, string);
643 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
644 keys[num_keys].key = va_arg(ap, char *);
645 if (keys[num_keys].key == NULL)
647 keys[num_keys].repl = va_arg(ap, char *);
648 if (keys[num_keys].repl == NULL)
649 fatal("%s: NULL replacement", __func__);
651 if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
652 fatal("%s: too many keys", __func__);
657 for (i = 0; *string != '\0'; string++) {
658 if (*string != '%') {
661 if (i >= sizeof(buf))
662 fatal("%s: string too long", __func__);
671 fatal("%s: invalid format", __func__);
672 for (j = 0; j < num_keys; j++) {
673 if (strchr(keys[j].key, *string) != NULL) {
674 i = strlcat(buf, keys[j].repl, sizeof(buf));
675 if (i >= sizeof(buf))
676 fatal("%s: string too long", __func__);
681 fatal("%s: unknown key %%%c", __func__, *string);
683 return (xstrdup(buf));
684 #undef EXPAND_MAX_KEYS
688 * Read an entire line from a public key file into a static buffer, discarding
689 * lines that exceed the buffer size. Returns 0 on success, -1 on failure.
692 read_keyfile_line(FILE *f, const char *filename, char *buf, size_t bufsz,
695 while (fgets(buf, bufsz, f) != NULL) {
699 if (buf[strlen(buf) - 1] == '\n' || feof(f)) {
702 debug("%s: %s line %lu exceeds size limit", __func__,
704 /* discard remainder of line */
705 while (fgetc(f) != '\n' && !feof(f))
713 tun_open(int tun, int mode)
715 #if defined(CUSTOM_SYS_TUN_OPEN)
716 return (sys_tun_open(tun, mode));
717 #elif defined(SSH_TUN_OPENBSD)
721 const char *tunbase = "tun";
723 if (mode == SSH_TUNMODE_ETHERNET)
726 /* Open the tunnel device */
727 if (tun <= SSH_TUNID_MAX) {
728 snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
729 fd = open(name, O_RDWR);
730 } else if (tun == SSH_TUNID_ANY) {
731 for (tun = 100; tun >= 0; tun--) {
732 snprintf(name, sizeof(name), "/dev/%s%d",
734 if ((fd = open(name, O_RDWR)) >= 0)
738 debug("%s: invalid tunnel %u", __func__, tun);
743 debug("%s: %s open: %s", __func__, name, strerror(errno));
747 debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
749 /* Bring interface up if it is not already */
750 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
751 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
754 if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
755 debug("%s: get interface %s flags: %s", __func__,
756 ifr.ifr_name, strerror(errno));
760 if (!(ifr.ifr_flags & IFF_UP)) {
761 ifr.ifr_flags |= IFF_UP;
762 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
763 debug("%s: activate interface %s: %s", __func__,
764 ifr.ifr_name, strerror(errno));
779 error("Tunnel interfaces are not supported on this platform");
789 if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
790 fprintf(stderr, "Couldn't open /dev/null: %s\n",
794 while (++dupfd <= STDERR_FILENO) {
795 /* Only populate closed fds. */
796 if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
797 if (dup2(nullfd, dupfd) == -1) {
798 fprintf(stderr, "dup2: %s\n", strerror(errno));
803 if (nullfd > STDERR_FILENO)
808 tohex(const void *vp, size_t l)
810 const u_char *p = (const u_char *)vp;
815 return xstrdup("tohex: length > 65536");
819 for (i = 0; i < l; i++) {
820 snprintf(b, sizeof(b), "%02x", p[i]);
827 get_u64(const void *vp)
829 const u_char *p = (const u_char *)vp;
832 v = (u_int64_t)p[0] << 56;
833 v |= (u_int64_t)p[1] << 48;
834 v |= (u_int64_t)p[2] << 40;
835 v |= (u_int64_t)p[3] << 32;
836 v |= (u_int64_t)p[4] << 24;
837 v |= (u_int64_t)p[5] << 16;
838 v |= (u_int64_t)p[6] << 8;
839 v |= (u_int64_t)p[7];
845 get_u32(const void *vp)
847 const u_char *p = (const u_char *)vp;
850 v = (u_int32_t)p[0] << 24;
851 v |= (u_int32_t)p[1] << 16;
852 v |= (u_int32_t)p[2] << 8;
853 v |= (u_int32_t)p[3];
859 get_u32_le(const void *vp)
861 const u_char *p = (const u_char *)vp;
865 v |= (u_int32_t)p[1] << 8;
866 v |= (u_int32_t)p[2] << 16;
867 v |= (u_int32_t)p[3] << 24;
873 get_u16(const void *vp)
875 const u_char *p = (const u_char *)vp;
878 v = (u_int16_t)p[0] << 8;
879 v |= (u_int16_t)p[1];
885 put_u64(void *vp, u_int64_t v)
887 u_char *p = (u_char *)vp;
889 p[0] = (u_char)(v >> 56) & 0xff;
890 p[1] = (u_char)(v >> 48) & 0xff;
891 p[2] = (u_char)(v >> 40) & 0xff;
892 p[3] = (u_char)(v >> 32) & 0xff;
893 p[4] = (u_char)(v >> 24) & 0xff;
894 p[5] = (u_char)(v >> 16) & 0xff;
895 p[6] = (u_char)(v >> 8) & 0xff;
896 p[7] = (u_char)v & 0xff;
900 put_u32(void *vp, u_int32_t v)
902 u_char *p = (u_char *)vp;
904 p[0] = (u_char)(v >> 24) & 0xff;
905 p[1] = (u_char)(v >> 16) & 0xff;
906 p[2] = (u_char)(v >> 8) & 0xff;
907 p[3] = (u_char)v & 0xff;
911 put_u32_le(void *vp, u_int32_t v)
913 u_char *p = (u_char *)vp;
915 p[0] = (u_char)v & 0xff;
916 p[1] = (u_char)(v >> 8) & 0xff;
917 p[2] = (u_char)(v >> 16) & 0xff;
918 p[3] = (u_char)(v >> 24) & 0xff;
922 put_u16(void *vp, u_int16_t v)
924 u_char *p = (u_char *)vp;
926 p[0] = (u_char)(v >> 8) & 0xff;
927 p[1] = (u_char)v & 0xff;
931 ms_subtract_diff(struct timeval *start, int *ms)
933 struct timeval diff, finish;
935 gettimeofday(&finish, NULL);
936 timersub(&finish, start, &diff);
937 *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
941 ms_to_timeval(struct timeval *tv, int ms)
945 tv->tv_sec = ms / 1000;
946 tv->tv_usec = (ms % 1000) * 1000;
952 #if defined(HAVE_CLOCK_GETTIME) && \
953 (defined(CLOCK_MONOTONIC) || defined(CLOCK_BOOTTIME))
955 static int gettime_failed = 0;
957 if (!gettime_failed) {
958 #if defined(CLOCK_BOOTTIME)
959 if (clock_gettime(CLOCK_BOOTTIME, &ts) == 0)
962 #if defined(CLOCK_MONOTONIC)
963 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
966 debug3("clock_gettime: %s", strerror(errno));
969 #endif /* HAVE_CLOCK_GETTIME && (CLOCK_MONOTONIC || CLOCK_BOOTTIME */
975 monotime_double(void)
977 #if defined(HAVE_CLOCK_GETTIME) && \
978 (defined(CLOCK_MONOTONIC) || defined(CLOCK_BOOTTIME))
980 static int gettime_failed = 0;
982 if (!gettime_failed) {
983 #if defined(CLOCK_BOOTTIME)
984 if (clock_gettime(CLOCK_BOOTTIME, &ts) == 0)
985 return (ts.tv_sec + (double)ts.tv_nsec / 1000000000);
987 #if defined(CLOCK_MONOTONIC)
988 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
989 return (ts.tv_sec + (double)ts.tv_nsec / 1000000000);
991 debug3("clock_gettime: %s", strerror(errno));
994 #endif /* HAVE_CLOCK_GETTIME && (CLOCK_MONOTONIC || CLOCK_BOOTTIME */
996 return (double)time(NULL);
1000 bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
1002 bw->buflen = buflen;
1004 bw->thresh = bw->rate;
1006 timerclear(&bw->bwstart);
1007 timerclear(&bw->bwend);
1010 /* Callback from read/write loop to insert bandwidth-limiting delays */
1012 bandwidth_limit(struct bwlimit *bw, size_t read_len)
1015 struct timespec ts, rm;
1017 if (!timerisset(&bw->bwstart)) {
1018 gettimeofday(&bw->bwstart, NULL);
1022 bw->lamt += read_len;
1023 if (bw->lamt < bw->thresh)
1026 gettimeofday(&bw->bwend, NULL);
1027 timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
1028 if (!timerisset(&bw->bwend))
1032 waitlen = (double)1000000L * bw->lamt / bw->rate;
1034 bw->bwstart.tv_sec = waitlen / 1000000L;
1035 bw->bwstart.tv_usec = waitlen % 1000000L;
1037 if (timercmp(&bw->bwstart, &bw->bwend, >)) {
1038 timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
1040 /* Adjust the wait time */
1041 if (bw->bwend.tv_sec) {
1043 if (bw->thresh < bw->buflen / 4)
1044 bw->thresh = bw->buflen / 4;
1045 } else if (bw->bwend.tv_usec < 10000) {
1047 if (bw->thresh > bw->buflen * 8)
1048 bw->thresh = bw->buflen * 8;
1051 TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
1052 while (nanosleep(&ts, &rm) == -1) {
1060 gettimeofday(&bw->bwstart, NULL);
1063 /* Make a template filename for mk[sd]temp() */
1065 mktemp_proto(char *s, size_t len)
1070 if ((tmpdir = getenv("TMPDIR")) != NULL) {
1071 r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1072 if (r > 0 && (size_t)r < len)
1075 r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1076 if (r < 0 || (size_t)r >= len)
1077 fatal("%s: template string too short", __func__);
1080 static const struct {
1084 { "af11", IPTOS_DSCP_AF11 },
1085 { "af12", IPTOS_DSCP_AF12 },
1086 { "af13", IPTOS_DSCP_AF13 },
1087 { "af21", IPTOS_DSCP_AF21 },
1088 { "af22", IPTOS_DSCP_AF22 },
1089 { "af23", IPTOS_DSCP_AF23 },
1090 { "af31", IPTOS_DSCP_AF31 },
1091 { "af32", IPTOS_DSCP_AF32 },
1092 { "af33", IPTOS_DSCP_AF33 },
1093 { "af41", IPTOS_DSCP_AF41 },
1094 { "af42", IPTOS_DSCP_AF42 },
1095 { "af43", IPTOS_DSCP_AF43 },
1096 { "cs0", IPTOS_DSCP_CS0 },
1097 { "cs1", IPTOS_DSCP_CS1 },
1098 { "cs2", IPTOS_DSCP_CS2 },
1099 { "cs3", IPTOS_DSCP_CS3 },
1100 { "cs4", IPTOS_DSCP_CS4 },
1101 { "cs5", IPTOS_DSCP_CS5 },
1102 { "cs6", IPTOS_DSCP_CS6 },
1103 { "cs7", IPTOS_DSCP_CS7 },
1104 { "ef", IPTOS_DSCP_EF },
1105 { "lowdelay", IPTOS_LOWDELAY },
1106 { "throughput", IPTOS_THROUGHPUT },
1107 { "reliability", IPTOS_RELIABILITY },
1112 parse_ipqos(const char *cp)
1120 for (i = 0; ipqos[i].name != NULL; i++) {
1121 if (strcasecmp(cp, ipqos[i].name) == 0)
1122 return ipqos[i].value;
1124 /* Try parsing as an integer */
1125 val = strtol(cp, &ep, 0);
1126 if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1132 iptos2str(int iptos)
1135 static char iptos_str[sizeof "0xff"];
1137 for (i = 0; ipqos[i].name != NULL; i++) {
1138 if (ipqos[i].value == iptos)
1139 return ipqos[i].name;
1141 snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1149 *s = tolower((u_char)*s);
1153 unix_listener(const char *path, int backlog, int unlink_first)
1155 struct sockaddr_un sunaddr;
1156 int saved_errno, sock;
1158 memset(&sunaddr, 0, sizeof(sunaddr));
1159 sunaddr.sun_family = AF_UNIX;
1160 if (strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1161 error("%s: \"%s\" too long for Unix domain socket", __func__,
1163 errno = ENAMETOOLONG;
1167 sock = socket(PF_UNIX, SOCK_STREAM, 0);
1169 saved_errno = errno;
1170 error("socket: %.100s", strerror(errno));
1171 errno = saved_errno;
1174 if (unlink_first == 1) {
1175 if (unlink(path) != 0 && errno != ENOENT)
1176 error("unlink(%s): %.100s", path, strerror(errno));
1178 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0) {
1179 saved_errno = errno;
1180 error("bind: %.100s", strerror(errno));
1182 error("%s: cannot bind to path: %s", __func__, path);
1183 errno = saved_errno;
1186 if (listen(sock, backlog) < 0) {
1187 saved_errno = errno;
1188 error("listen: %.100s", strerror(errno));
1191 error("%s: cannot listen on path: %s", __func__, path);
1192 errno = saved_errno;
1199 sock_set_v6only(int s)
1201 #if defined(IPV6_V6ONLY) && !defined(__OpenBSD__)
1204 debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
1205 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
1206 error("setsockopt IPV6_V6ONLY: %s", strerror(errno));
1211 * Compares two strings that maybe be NULL. Returns non-zero if strings
1212 * are both NULL or are identical, returns zero otherwise.
1215 strcmp_maybe_null(const char *a, const char *b)
1217 if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1219 if (a != NULL && strcmp(a, b) != 0)
1225 * Compare two forwards, returning non-zero if they are identical or
1229 forward_equals(const struct Forward *a, const struct Forward *b)
1231 if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
1233 if (a->listen_port != b->listen_port)
1235 if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
1237 if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
1239 if (a->connect_port != b->connect_port)
1241 if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
1243 /* allocated_port and handle are not checked */
1248 ipport_reserved(void)
1252 size_t len = sizeof(old);
1254 ret = sysctlbyname("net.inet.ip.portrange.reservedhigh",
1255 &old, &len, NULL, 0);
1259 return (IPPORT_RESERVED);
1262 /* returns 1 if bind to specified port by specified user is permitted */
1264 bind_permitted(int port, uid_t uid)
1267 if (port < ipport_reserved() && uid != 0)
1272 /* returns 1 if process is already daemonized, 0 otherwise */
1278 if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
1280 return 0; /* have controlling terminal */
1283 return 0; /* parent is not init */
1284 if (getsid(0) != getpid())
1285 return 0; /* not session leader */
1286 debug3("already daemonized");