1 /* $OpenBSD: misc.c,v 1.105 2016/07/15 00:24:30 djm 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>
43 #include <netinet/in.h>
44 #include <netinet/in_systm.h>
45 #include <netinet/ip.h>
46 #include <netinet/tcp.h>
56 #ifdef SSH_TUN_OPENBSD
65 /* remove newline at end of string */
71 if (*t == '\n' || *t == '\r') {
81 /* set/unset filedescriptor to non-blocking */
87 val = fcntl(fd, F_GETFL);
89 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
92 if (val & O_NONBLOCK) {
93 debug3("fd %d is O_NONBLOCK", fd);
96 debug2("fd %d setting O_NONBLOCK", fd);
98 if (fcntl(fd, F_SETFL, val) == -1) {
99 debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
107 unset_nonblock(int fd)
111 val = fcntl(fd, F_GETFL);
113 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
116 if (!(val & O_NONBLOCK)) {
117 debug3("fd %d is not O_NONBLOCK", fd);
120 debug("fd %d clearing O_NONBLOCK", fd);
122 if (fcntl(fd, F_SETFL, val) == -1) {
123 debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
124 fd, strerror(errno));
131 ssh_gai_strerror(int gaierr)
133 if (gaierr == EAI_SYSTEM && errno != 0)
134 return strerror(errno);
135 return gai_strerror(gaierr);
138 /* disable nagle on socket */
146 if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
147 debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
151 debug2("fd %d is TCP_NODELAY", fd);
155 debug2("fd %d setting TCP_NODELAY", fd);
156 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
157 error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
160 /* Characters considered whitespace in strsep calls. */
161 #define WHITESPACE " \t\r\n"
164 /* return next token in configuration line */
176 *s = strpbrk(*s, WHITESPACE QUOTE "=");
181 memmove(*s, *s + 1, strlen(*s)); /* move nul too */
182 /* Find matching quote */
183 if ((*s = strpbrk(*s, QUOTE)) == NULL) {
184 return (NULL); /* no matching quote */
187 *s += strspn(*s + 1, WHITESPACE) + 1;
192 /* Allow only one '=' to be skipped */
197 /* Skip any extra whitespace after first token */
198 *s += strspn(*s + 1, WHITESPACE) + 1;
199 if (*s[0] == '=' && !wspace)
200 *s += strspn(*s + 1, WHITESPACE) + 1;
206 pwcopy(struct passwd *pw)
208 struct passwd *copy = xcalloc(1, sizeof(*copy));
210 copy->pw_name = xstrdup(pw->pw_name);
211 copy->pw_passwd = xstrdup(pw->pw_passwd);
212 #ifdef HAVE_STRUCT_PASSWD_PW_GECOS
213 copy->pw_gecos = xstrdup(pw->pw_gecos);
215 copy->pw_uid = pw->pw_uid;
216 copy->pw_gid = pw->pw_gid;
217 #ifdef HAVE_STRUCT_PASSWD_PW_EXPIRE
218 copy->pw_expire = pw->pw_expire;
220 #ifdef HAVE_STRUCT_PASSWD_PW_CHANGE
221 copy->pw_change = pw->pw_change;
223 #ifdef HAVE_STRUCT_PASSWD_PW_CLASS
224 copy->pw_class = xstrdup(pw->pw_class);
226 copy->pw_dir = xstrdup(pw->pw_dir);
227 copy->pw_shell = xstrdup(pw->pw_shell);
232 * Convert ASCII string to TCP/IP port number.
233 * Port must be >=0 and <=65535.
234 * Return -1 if invalid.
237 a2port(const char *s)
242 port = strtonum(s, 0, 65535, &errstr);
249 a2tun(const char *s, int *remote)
251 const char *errstr = NULL;
255 if (remote != NULL) {
256 *remote = SSH_TUNID_ANY;
258 if ((ep = strchr(sp, ':')) == NULL) {
260 return (a2tun(s, NULL));
263 *remote = a2tun(ep, NULL);
264 tun = a2tun(sp, NULL);
266 return (*remote == SSH_TUNID_ERR ? *remote : tun);
269 if (strcasecmp(s, "any") == 0)
270 return (SSH_TUNID_ANY);
272 tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
274 return (SSH_TUNID_ERR);
280 #define MINUTES (SECONDS * 60)
281 #define HOURS (MINUTES * 60)
282 #define DAYS (HOURS * 24)
283 #define WEEKS (DAYS * 7)
286 * Convert a time string into seconds; format is
290 * Valid time qualifiers are:
304 * Return -1 if time string is invalid.
307 convtime(const char *s)
317 if (p == NULL || *p == '\0')
321 secs = strtol(p, &endp, 10);
323 (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
363 * Returns a standardized host+port identifier string.
364 * Caller must free returned string.
367 put_host_port(const char *host, u_short port)
371 if (port == 0 || port == SSH_DEFAULT_PORT)
372 return(xstrdup(host));
373 if (asprintf(&hoststr, "[%s]:%d", host, (int)port) < 0)
374 fatal("put_host_port: asprintf: %s", strerror(errno));
375 debug3("put_host_port: %s", hoststr);
380 * Search for next delimiter between hostnames/addresses and ports.
381 * Argument may be modified (for termination).
382 * Returns *cp if parsing succeeds.
383 * *cp is set to the start of the next delimiter, if one was found.
384 * If this is the last field, *cp is set to NULL.
391 if (cp == NULL || *cp == NULL)
396 if ((s = strchr(s, ']')) == NULL)
400 } else if ((s = strpbrk(s, ":/")) == NULL)
401 s = *cp + strlen(*cp); /* skip to end (see first case below) */
405 *cp = NULL; /* no more fields*/
410 *s = '\0'; /* terminate */
422 cleanhostname(char *host)
424 if (*host == '[' && host[strlen(host) - 1] == ']') {
425 host[strlen(host) - 1] = '\0';
436 if (*cp == ':') /* Leading colon is part of file name. */
442 if (*cp == '@' && *(cp+1) == '[')
444 if (*cp == ']' && *(cp+1) == ':' && flag)
446 if (*cp == ':' && !flag)
455 * Parse a [user@]host[:port] string.
456 * Caller must free returned user and host.
457 * Any of the pointer return arguments may be NULL (useful for syntax checking).
458 * If user was not specified then *userp will be set to NULL.
459 * If port was not specified then *portp will be -1.
460 * Returns 0 on success, -1 on failure.
463 parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
465 char *sdup, *cp, *tmp;
466 char *user = NULL, *host = NULL;
467 int port = -1, ret = -1;
476 if ((sdup = tmp = strdup(s)) == NULL)
478 /* Extract optional username */
479 if ((cp = strchr(tmp, '@')) != NULL) {
483 if ((user = strdup(tmp)) == NULL)
487 /* Extract mandatory hostname */
488 if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
490 host = xstrdup(cleanhostname(cp));
491 /* Convert and verify optional port */
492 if (tmp != NULL && *tmp != '\0') {
493 if ((port = a2port(tmp)) <= 0)
515 /* function to assist building execv() arguments */
517 addargs(arglist *args, char *fmt, ...)
525 r = vasprintf(&cp, fmt, ap);
528 fatal("addargs: argument too long");
530 nalloc = args->nalloc;
531 if (args->list == NULL) {
534 } else if (args->num+2 >= nalloc)
537 args->list = xreallocarray(args->list, nalloc, sizeof(char *));
538 args->nalloc = nalloc;
539 args->list[args->num++] = cp;
540 args->list[args->num] = NULL;
544 replacearg(arglist *args, u_int which, char *fmt, ...)
551 r = vasprintf(&cp, fmt, ap);
554 fatal("replacearg: argument too long");
556 if (which >= args->num)
557 fatal("replacearg: tried to replace invalid arg %d >= %d",
559 free(args->list[which]);
560 args->list[which] = cp;
564 freeargs(arglist *args)
568 if (args->list != NULL) {
569 for (i = 0; i < args->num; i++)
572 args->nalloc = args->num = 0;
578 * Expands tildes in the file name. Returns data allocated by xmalloc.
579 * Warning: this calls getpw*.
582 tilde_expand_filename(const char *filename, uid_t uid)
584 const char *path, *sep;
585 char user[128], *ret;
589 if (*filename != '~')
590 return (xstrdup(filename));
593 path = strchr(filename, '/');
594 if (path != NULL && path > filename) { /* ~user/path */
595 slash = path - filename;
596 if (slash > sizeof(user) - 1)
597 fatal("tilde_expand_filename: ~username too long");
598 memcpy(user, filename, slash);
600 if ((pw = getpwnam(user)) == NULL)
601 fatal("tilde_expand_filename: No such user %s", user);
602 } else if ((pw = getpwuid(uid)) == NULL) /* ~/path */
603 fatal("tilde_expand_filename: No such uid %ld", (long)uid);
605 /* Make sure directory has a trailing '/' */
606 len = strlen(pw->pw_dir);
607 if (len == 0 || pw->pw_dir[len - 1] != '/')
612 /* Skip leading '/' from specified path */
616 if (xasprintf(&ret, "%s%s%s", pw->pw_dir, sep, filename) >= PATH_MAX)
617 fatal("tilde_expand_filename: Path too long");
623 * Expand a string with a set of %[char] escapes. A number of escapes may be
624 * specified as (char *escape_chars, char *replacement) pairs. The list must
625 * be terminated by a NULL escape_char. Returns replaced string in memory
626 * allocated by xmalloc.
629 percent_expand(const char *string, ...)
631 #define EXPAND_MAX_KEYS 16
632 u_int num_keys, i, j;
636 } keys[EXPAND_MAX_KEYS];
641 va_start(ap, string);
642 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
643 keys[num_keys].key = va_arg(ap, char *);
644 if (keys[num_keys].key == NULL)
646 keys[num_keys].repl = va_arg(ap, char *);
647 if (keys[num_keys].repl == NULL)
648 fatal("%s: NULL replacement", __func__);
650 if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
651 fatal("%s: too many keys", __func__);
656 for (i = 0; *string != '\0'; string++) {
657 if (*string != '%') {
660 if (i >= sizeof(buf))
661 fatal("%s: string too long", __func__);
670 fatal("%s: invalid format", __func__);
671 for (j = 0; j < num_keys; j++) {
672 if (strchr(keys[j].key, *string) != NULL) {
673 i = strlcat(buf, keys[j].repl, sizeof(buf));
674 if (i >= sizeof(buf))
675 fatal("%s: string too long", __func__);
680 fatal("%s: unknown key %%%c", __func__, *string);
682 return (xstrdup(buf));
683 #undef EXPAND_MAX_KEYS
687 * Read an entire line from a public key file into a static buffer, discarding
688 * lines that exceed the buffer size. Returns 0 on success, -1 on failure.
691 read_keyfile_line(FILE *f, const char *filename, char *buf, size_t bufsz,
694 while (fgets(buf, bufsz, f) != NULL) {
698 if (buf[strlen(buf) - 1] == '\n' || feof(f)) {
701 debug("%s: %s line %lu exceeds size limit", __func__,
703 /* discard remainder of line */
704 while (fgetc(f) != '\n' && !feof(f))
712 tun_open(int tun, int mode)
714 #if defined(CUSTOM_SYS_TUN_OPEN)
715 return (sys_tun_open(tun, mode));
716 #elif defined(SSH_TUN_OPENBSD)
720 const char *tunbase = "tun";
722 if (mode == SSH_TUNMODE_ETHERNET)
725 /* Open the tunnel device */
726 if (tun <= SSH_TUNID_MAX) {
727 snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
728 fd = open(name, O_RDWR);
729 } else if (tun == SSH_TUNID_ANY) {
730 for (tun = 100; tun >= 0; tun--) {
731 snprintf(name, sizeof(name), "/dev/%s%d",
733 if ((fd = open(name, O_RDWR)) >= 0)
737 debug("%s: invalid tunnel %u", __func__, tun);
742 debug("%s: %s open: %s", __func__, name, strerror(errno));
746 debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
748 /* Bring interface up if it is not already */
749 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
750 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
753 if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
754 debug("%s: get interface %s flags: %s", __func__,
755 ifr.ifr_name, strerror(errno));
759 if (!(ifr.ifr_flags & IFF_UP)) {
760 ifr.ifr_flags |= IFF_UP;
761 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
762 debug("%s: activate interface %s: %s", __func__,
763 ifr.ifr_name, strerror(errno));
778 error("Tunnel interfaces are not supported on this platform");
788 if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
789 fprintf(stderr, "Couldn't open /dev/null: %s\n",
793 while (++dupfd <= STDERR_FILENO) {
794 /* Only populate closed fds. */
795 if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
796 if (dup2(nullfd, dupfd) == -1) {
797 fprintf(stderr, "dup2: %s\n", strerror(errno));
802 if (nullfd > STDERR_FILENO)
807 tohex(const void *vp, size_t l)
809 const u_char *p = (const u_char *)vp;
814 return xstrdup("tohex: length > 65536");
818 for (i = 0; i < l; i++) {
819 snprintf(b, sizeof(b), "%02x", p[i]);
826 get_u64(const void *vp)
828 const u_char *p = (const u_char *)vp;
831 v = (u_int64_t)p[0] << 56;
832 v |= (u_int64_t)p[1] << 48;
833 v |= (u_int64_t)p[2] << 40;
834 v |= (u_int64_t)p[3] << 32;
835 v |= (u_int64_t)p[4] << 24;
836 v |= (u_int64_t)p[5] << 16;
837 v |= (u_int64_t)p[6] << 8;
838 v |= (u_int64_t)p[7];
844 get_u32(const void *vp)
846 const u_char *p = (const u_char *)vp;
849 v = (u_int32_t)p[0] << 24;
850 v |= (u_int32_t)p[1] << 16;
851 v |= (u_int32_t)p[2] << 8;
852 v |= (u_int32_t)p[3];
858 get_u32_le(const void *vp)
860 const u_char *p = (const u_char *)vp;
864 v |= (u_int32_t)p[1] << 8;
865 v |= (u_int32_t)p[2] << 16;
866 v |= (u_int32_t)p[3] << 24;
872 get_u16(const void *vp)
874 const u_char *p = (const u_char *)vp;
877 v = (u_int16_t)p[0] << 8;
878 v |= (u_int16_t)p[1];
884 put_u64(void *vp, u_int64_t v)
886 u_char *p = (u_char *)vp;
888 p[0] = (u_char)(v >> 56) & 0xff;
889 p[1] = (u_char)(v >> 48) & 0xff;
890 p[2] = (u_char)(v >> 40) & 0xff;
891 p[3] = (u_char)(v >> 32) & 0xff;
892 p[4] = (u_char)(v >> 24) & 0xff;
893 p[5] = (u_char)(v >> 16) & 0xff;
894 p[6] = (u_char)(v >> 8) & 0xff;
895 p[7] = (u_char)v & 0xff;
899 put_u32(void *vp, u_int32_t v)
901 u_char *p = (u_char *)vp;
903 p[0] = (u_char)(v >> 24) & 0xff;
904 p[1] = (u_char)(v >> 16) & 0xff;
905 p[2] = (u_char)(v >> 8) & 0xff;
906 p[3] = (u_char)v & 0xff;
910 put_u32_le(void *vp, u_int32_t v)
912 u_char *p = (u_char *)vp;
914 p[0] = (u_char)v & 0xff;
915 p[1] = (u_char)(v >> 8) & 0xff;
916 p[2] = (u_char)(v >> 16) & 0xff;
917 p[3] = (u_char)(v >> 24) & 0xff;
921 put_u16(void *vp, u_int16_t v)
923 u_char *p = (u_char *)vp;
925 p[0] = (u_char)(v >> 8) & 0xff;
926 p[1] = (u_char)v & 0xff;
930 ms_subtract_diff(struct timeval *start, int *ms)
932 struct timeval diff, finish;
934 gettimeofday(&finish, NULL);
935 timersub(&finish, start, &diff);
936 *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
940 ms_to_timeval(struct timeval *tv, int ms)
944 tv->tv_sec = ms / 1000;
945 tv->tv_usec = (ms % 1000) * 1000;
951 #if defined(HAVE_CLOCK_GETTIME) && \
952 (defined(CLOCK_MONOTONIC) || defined(CLOCK_BOOTTIME))
954 static int gettime_failed = 0;
956 if (!gettime_failed) {
957 #if defined(CLOCK_BOOTTIME)
958 if (clock_gettime(CLOCK_BOOTTIME, &ts) == 0)
961 #if defined(CLOCK_MONOTONIC)
962 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
965 debug3("clock_gettime: %s", strerror(errno));
968 #endif /* HAVE_CLOCK_GETTIME && (CLOCK_MONOTONIC || CLOCK_BOOTTIME */
974 monotime_double(void)
976 #if defined(HAVE_CLOCK_GETTIME) && \
977 (defined(CLOCK_MONOTONIC) || defined(CLOCK_BOOTTIME))
979 static int gettime_failed = 0;
981 if (!gettime_failed) {
982 #if defined(CLOCK_BOOTTIME)
983 if (clock_gettime(CLOCK_BOOTTIME, &ts) == 0)
984 return (ts.tv_sec + (double)ts.tv_nsec / 1000000000);
986 #if defined(CLOCK_MONOTONIC)
987 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
988 return (ts.tv_sec + (double)ts.tv_nsec / 1000000000);
990 debug3("clock_gettime: %s", strerror(errno));
993 #endif /* HAVE_CLOCK_GETTIME && (CLOCK_MONOTONIC || CLOCK_BOOTTIME */
995 return (double)time(NULL);
999 bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
1001 bw->buflen = buflen;
1003 bw->thresh = bw->rate;
1005 timerclear(&bw->bwstart);
1006 timerclear(&bw->bwend);
1009 /* Callback from read/write loop to insert bandwidth-limiting delays */
1011 bandwidth_limit(struct bwlimit *bw, size_t read_len)
1014 struct timespec ts, rm;
1016 if (!timerisset(&bw->bwstart)) {
1017 gettimeofday(&bw->bwstart, NULL);
1021 bw->lamt += read_len;
1022 if (bw->lamt < bw->thresh)
1025 gettimeofday(&bw->bwend, NULL);
1026 timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
1027 if (!timerisset(&bw->bwend))
1031 waitlen = (double)1000000L * bw->lamt / bw->rate;
1033 bw->bwstart.tv_sec = waitlen / 1000000L;
1034 bw->bwstart.tv_usec = waitlen % 1000000L;
1036 if (timercmp(&bw->bwstart, &bw->bwend, >)) {
1037 timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
1039 /* Adjust the wait time */
1040 if (bw->bwend.tv_sec) {
1042 if (bw->thresh < bw->buflen / 4)
1043 bw->thresh = bw->buflen / 4;
1044 } else if (bw->bwend.tv_usec < 10000) {
1046 if (bw->thresh > bw->buflen * 8)
1047 bw->thresh = bw->buflen * 8;
1050 TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
1051 while (nanosleep(&ts, &rm) == -1) {
1059 gettimeofday(&bw->bwstart, NULL);
1062 /* Make a template filename for mk[sd]temp() */
1064 mktemp_proto(char *s, size_t len)
1069 if ((tmpdir = getenv("TMPDIR")) != NULL) {
1070 r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1071 if (r > 0 && (size_t)r < len)
1074 r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1075 if (r < 0 || (size_t)r >= len)
1076 fatal("%s: template string too short", __func__);
1079 static const struct {
1083 { "af11", IPTOS_DSCP_AF11 },
1084 { "af12", IPTOS_DSCP_AF12 },
1085 { "af13", IPTOS_DSCP_AF13 },
1086 { "af21", IPTOS_DSCP_AF21 },
1087 { "af22", IPTOS_DSCP_AF22 },
1088 { "af23", IPTOS_DSCP_AF23 },
1089 { "af31", IPTOS_DSCP_AF31 },
1090 { "af32", IPTOS_DSCP_AF32 },
1091 { "af33", IPTOS_DSCP_AF33 },
1092 { "af41", IPTOS_DSCP_AF41 },
1093 { "af42", IPTOS_DSCP_AF42 },
1094 { "af43", IPTOS_DSCP_AF43 },
1095 { "cs0", IPTOS_DSCP_CS0 },
1096 { "cs1", IPTOS_DSCP_CS1 },
1097 { "cs2", IPTOS_DSCP_CS2 },
1098 { "cs3", IPTOS_DSCP_CS3 },
1099 { "cs4", IPTOS_DSCP_CS4 },
1100 { "cs5", IPTOS_DSCP_CS5 },
1101 { "cs6", IPTOS_DSCP_CS6 },
1102 { "cs7", IPTOS_DSCP_CS7 },
1103 { "ef", IPTOS_DSCP_EF },
1104 { "lowdelay", IPTOS_LOWDELAY },
1105 { "throughput", IPTOS_THROUGHPUT },
1106 { "reliability", IPTOS_RELIABILITY },
1111 parse_ipqos(const char *cp)
1119 for (i = 0; ipqos[i].name != NULL; i++) {
1120 if (strcasecmp(cp, ipqos[i].name) == 0)
1121 return ipqos[i].value;
1123 /* Try parsing as an integer */
1124 val = strtol(cp, &ep, 0);
1125 if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1131 iptos2str(int iptos)
1134 static char iptos_str[sizeof "0xff"];
1136 for (i = 0; ipqos[i].name != NULL; i++) {
1137 if (ipqos[i].value == iptos)
1138 return ipqos[i].name;
1140 snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1148 *s = tolower((u_char)*s);
1152 unix_listener(const char *path, int backlog, int unlink_first)
1154 struct sockaddr_un sunaddr;
1155 int saved_errno, sock;
1157 memset(&sunaddr, 0, sizeof(sunaddr));
1158 sunaddr.sun_family = AF_UNIX;
1159 if (strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1160 error("%s: \"%s\" too long for Unix domain socket", __func__,
1162 errno = ENAMETOOLONG;
1166 sock = socket(PF_UNIX, SOCK_STREAM, 0);
1168 saved_errno = errno;
1169 error("socket: %.100s", strerror(errno));
1170 errno = saved_errno;
1173 if (unlink_first == 1) {
1174 if (unlink(path) != 0 && errno != ENOENT)
1175 error("unlink(%s): %.100s", path, strerror(errno));
1177 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0) {
1178 saved_errno = errno;
1179 error("bind: %.100s", strerror(errno));
1181 error("%s: cannot bind to path: %s", __func__, path);
1182 errno = saved_errno;
1185 if (listen(sock, backlog) < 0) {
1186 saved_errno = errno;
1187 error("listen: %.100s", strerror(errno));
1190 error("%s: cannot listen on path: %s", __func__, path);
1191 errno = saved_errno;
1198 sock_set_v6only(int s)
1200 #if defined(IPV6_V6ONLY) && !defined(__OpenBSD__)
1203 debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
1204 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
1205 error("setsockopt IPV6_V6ONLY: %s", strerror(errno));
1210 * Compares two strings that maybe be NULL. Returns non-zero if strings
1211 * are both NULL or are identical, returns zero otherwise.
1214 strcmp_maybe_null(const char *a, const char *b)
1216 if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1218 if (a != NULL && strcmp(a, b) != 0)
1224 * Compare two forwards, returning non-zero if they are identical or
1228 forward_equals(const struct Forward *a, const struct Forward *b)
1230 if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
1232 if (a->listen_port != b->listen_port)
1234 if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
1236 if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
1238 if (a->connect_port != b->connect_port)
1240 if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
1242 /* allocated_port and handle are not checked */