1 /* $OpenBSD: misc.c,v 1.92 2013/10/14 23:28:23 djm Exp $ */
4 * Copyright (c) 2000 Markus Friedl. All rights reserved.
5 * Copyright (c) 2005,2006 Damien Miller. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 #include <sys/types.h>
32 #include <sys/ioctl.h>
33 #include <sys/socket.h>
34 #include <sys/param.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, 0);
89 error("fcntl(%d, F_GETFL, 0): %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, 0);
113 error("fcntl(%d, F_GETFL, 0): %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)
454 /* function to assist building execv() arguments */
456 addargs(arglist *args, char *fmt, ...)
464 r = vasprintf(&cp, fmt, ap);
467 fatal("addargs: argument too long");
469 nalloc = args->nalloc;
470 if (args->list == NULL) {
473 } else if (args->num+2 >= nalloc)
476 args->list = xrealloc(args->list, nalloc, sizeof(char *));
477 args->nalloc = nalloc;
478 args->list[args->num++] = cp;
479 args->list[args->num] = NULL;
483 replacearg(arglist *args, u_int which, char *fmt, ...)
490 r = vasprintf(&cp, fmt, ap);
493 fatal("replacearg: argument too long");
495 if (which >= args->num)
496 fatal("replacearg: tried to replace invalid arg %d >= %d",
498 free(args->list[which]);
499 args->list[which] = cp;
503 freeargs(arglist *args)
507 if (args->list != NULL) {
508 for (i = 0; i < args->num; i++)
511 args->nalloc = args->num = 0;
517 * Expands tildes in the file name. Returns data allocated by xmalloc.
518 * Warning: this calls getpw*.
521 tilde_expand_filename(const char *filename, uid_t uid)
523 const char *path, *sep;
524 char user[128], *ret;
528 if (*filename != '~')
529 return (xstrdup(filename));
532 path = strchr(filename, '/');
533 if (path != NULL && path > filename) { /* ~user/path */
534 slash = path - filename;
535 if (slash > sizeof(user) - 1)
536 fatal("tilde_expand_filename: ~username too long");
537 memcpy(user, filename, slash);
539 if ((pw = getpwnam(user)) == NULL)
540 fatal("tilde_expand_filename: No such user %s", user);
541 } else if ((pw = getpwuid(uid)) == NULL) /* ~/path */
542 fatal("tilde_expand_filename: No such uid %ld", (long)uid);
544 /* Make sure directory has a trailing '/' */
545 len = strlen(pw->pw_dir);
546 if (len == 0 || pw->pw_dir[len - 1] != '/')
551 /* Skip leading '/' from specified path */
555 if (xasprintf(&ret, "%s%s%s", pw->pw_dir, sep, filename) >= MAXPATHLEN)
556 fatal("tilde_expand_filename: Path too long");
562 * Expand a string with a set of %[char] escapes. A number of escapes may be
563 * specified as (char *escape_chars, char *replacement) pairs. The list must
564 * be terminated by a NULL escape_char. Returns replaced string in memory
565 * allocated by xmalloc.
568 percent_expand(const char *string, ...)
570 #define EXPAND_MAX_KEYS 16
571 u_int num_keys, i, j;
575 } keys[EXPAND_MAX_KEYS];
580 va_start(ap, string);
581 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
582 keys[num_keys].key = va_arg(ap, char *);
583 if (keys[num_keys].key == NULL)
585 keys[num_keys].repl = va_arg(ap, char *);
586 if (keys[num_keys].repl == NULL)
587 fatal("%s: NULL replacement", __func__);
589 if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
590 fatal("%s: too many keys", __func__);
595 for (i = 0; *string != '\0'; string++) {
596 if (*string != '%') {
599 if (i >= sizeof(buf))
600 fatal("%s: string too long", __func__);
608 for (j = 0; j < num_keys; j++) {
609 if (strchr(keys[j].key, *string) != NULL) {
610 i = strlcat(buf, keys[j].repl, sizeof(buf));
611 if (i >= sizeof(buf))
612 fatal("%s: string too long", __func__);
617 fatal("%s: unknown key %%%c", __func__, *string);
619 return (xstrdup(buf));
620 #undef EXPAND_MAX_KEYS
624 * Read an entire line from a public key file into a static buffer, discarding
625 * lines that exceed the buffer size. Returns 0 on success, -1 on failure.
628 read_keyfile_line(FILE *f, const char *filename, char *buf, size_t bufsz,
631 while (fgets(buf, bufsz, f) != NULL) {
635 if (buf[strlen(buf) - 1] == '\n' || feof(f)) {
638 debug("%s: %s line %lu exceeds size limit", __func__,
640 /* discard remainder of line */
641 while (fgetc(f) != '\n' && !feof(f))
649 tun_open(int tun, int mode)
651 #if defined(CUSTOM_SYS_TUN_OPEN)
652 return (sys_tun_open(tun, mode));
653 #elif defined(SSH_TUN_OPENBSD)
658 /* Open the tunnel device */
659 if (tun <= SSH_TUNID_MAX) {
660 snprintf(name, sizeof(name), "/dev/tun%d", tun);
661 fd = open(name, O_RDWR);
662 } else if (tun == SSH_TUNID_ANY) {
663 for (tun = 100; tun >= 0; tun--) {
664 snprintf(name, sizeof(name), "/dev/tun%d", tun);
665 if ((fd = open(name, O_RDWR)) >= 0)
669 debug("%s: invalid tunnel %u", __func__, tun);
674 debug("%s: %s open failed: %s", __func__, name, strerror(errno));
678 debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
680 /* Set the tunnel device operation mode */
681 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "tun%d", tun);
682 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
685 if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1)
688 /* Set interface mode */
689 ifr.ifr_flags &= ~IFF_UP;
690 if (mode == SSH_TUNMODE_ETHERNET)
691 ifr.ifr_flags |= IFF_LINK0;
693 ifr.ifr_flags &= ~IFF_LINK0;
694 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1)
697 /* Bring interface up */
698 ifr.ifr_flags |= IFF_UP;
699 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1)
710 debug("%s: failed to set %s mode %d: %s", __func__, name,
711 mode, strerror(errno));
714 error("Tunnel interfaces are not supported on this platform");
724 if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
725 fprintf(stderr, "Couldn't open /dev/null: %s\n",
729 while (++dupfd <= 2) {
730 /* Only clobber closed fds */
731 if (fcntl(dupfd, F_GETFL, 0) >= 0)
733 if (dup2(nullfd, dupfd) == -1) {
734 fprintf(stderr, "dup2: %s\n", strerror(errno));
743 tohex(const void *vp, size_t l)
745 const u_char *p = (const u_char *)vp;
750 return xstrdup("tohex: length > 65536");
754 for (i = 0; i < l; i++) {
755 snprintf(b, sizeof(b), "%02x", p[i]);
762 get_u64(const void *vp)
764 const u_char *p = (const u_char *)vp;
767 v = (u_int64_t)p[0] << 56;
768 v |= (u_int64_t)p[1] << 48;
769 v |= (u_int64_t)p[2] << 40;
770 v |= (u_int64_t)p[3] << 32;
771 v |= (u_int64_t)p[4] << 24;
772 v |= (u_int64_t)p[5] << 16;
773 v |= (u_int64_t)p[6] << 8;
774 v |= (u_int64_t)p[7];
780 get_u32(const void *vp)
782 const u_char *p = (const u_char *)vp;
785 v = (u_int32_t)p[0] << 24;
786 v |= (u_int32_t)p[1] << 16;
787 v |= (u_int32_t)p[2] << 8;
788 v |= (u_int32_t)p[3];
794 get_u16(const void *vp)
796 const u_char *p = (const u_char *)vp;
799 v = (u_int16_t)p[0] << 8;
800 v |= (u_int16_t)p[1];
806 put_u64(void *vp, u_int64_t v)
808 u_char *p = (u_char *)vp;
810 p[0] = (u_char)(v >> 56) & 0xff;
811 p[1] = (u_char)(v >> 48) & 0xff;
812 p[2] = (u_char)(v >> 40) & 0xff;
813 p[3] = (u_char)(v >> 32) & 0xff;
814 p[4] = (u_char)(v >> 24) & 0xff;
815 p[5] = (u_char)(v >> 16) & 0xff;
816 p[6] = (u_char)(v >> 8) & 0xff;
817 p[7] = (u_char)v & 0xff;
821 put_u32(void *vp, u_int32_t v)
823 u_char *p = (u_char *)vp;
825 p[0] = (u_char)(v >> 24) & 0xff;
826 p[1] = (u_char)(v >> 16) & 0xff;
827 p[2] = (u_char)(v >> 8) & 0xff;
828 p[3] = (u_char)v & 0xff;
833 put_u16(void *vp, u_int16_t v)
835 u_char *p = (u_char *)vp;
837 p[0] = (u_char)(v >> 8) & 0xff;
838 p[1] = (u_char)v & 0xff;
842 ms_subtract_diff(struct timeval *start, int *ms)
844 struct timeval diff, finish;
846 gettimeofday(&finish, NULL);
847 timersub(&finish, start, &diff);
848 *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
852 ms_to_timeval(struct timeval *tv, int ms)
856 tv->tv_sec = ms / 1000;
857 tv->tv_usec = (ms % 1000) * 1000;
863 #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
865 static int gettime_failed = 0;
867 if (!gettime_failed) {
868 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
870 debug3("clock_gettime: %s", strerror(errno));
879 bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
883 bw->thresh = bw->rate;
885 timerclear(&bw->bwstart);
886 timerclear(&bw->bwend);
889 /* Callback from read/write loop to insert bandwidth-limiting delays */
891 bandwidth_limit(struct bwlimit *bw, size_t read_len)
894 struct timespec ts, rm;
896 if (!timerisset(&bw->bwstart)) {
897 gettimeofday(&bw->bwstart, NULL);
901 bw->lamt += read_len;
902 if (bw->lamt < bw->thresh)
905 gettimeofday(&bw->bwend, NULL);
906 timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
907 if (!timerisset(&bw->bwend))
911 waitlen = (double)1000000L * bw->lamt / bw->rate;
913 bw->bwstart.tv_sec = waitlen / 1000000L;
914 bw->bwstart.tv_usec = waitlen % 1000000L;
916 if (timercmp(&bw->bwstart, &bw->bwend, >)) {
917 timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
919 /* Adjust the wait time */
920 if (bw->bwend.tv_sec) {
922 if (bw->thresh < bw->buflen / 4)
923 bw->thresh = bw->buflen / 4;
924 } else if (bw->bwend.tv_usec < 10000) {
926 if (bw->thresh > bw->buflen * 8)
927 bw->thresh = bw->buflen * 8;
930 TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
931 while (nanosleep(&ts, &rm) == -1) {
939 gettimeofday(&bw->bwstart, NULL);
942 /* Make a template filename for mk[sd]temp() */
944 mktemp_proto(char *s, size_t len)
949 if ((tmpdir = getenv("TMPDIR")) != NULL) {
950 r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
951 if (r > 0 && (size_t)r < len)
954 r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
955 if (r < 0 || (size_t)r >= len)
956 fatal("%s: template string too short", __func__);
959 static const struct {
963 { "af11", IPTOS_DSCP_AF11 },
964 { "af12", IPTOS_DSCP_AF12 },
965 { "af13", IPTOS_DSCP_AF13 },
966 { "af21", IPTOS_DSCP_AF21 },
967 { "af22", IPTOS_DSCP_AF22 },
968 { "af23", IPTOS_DSCP_AF23 },
969 { "af31", IPTOS_DSCP_AF31 },
970 { "af32", IPTOS_DSCP_AF32 },
971 { "af33", IPTOS_DSCP_AF33 },
972 { "af41", IPTOS_DSCP_AF41 },
973 { "af42", IPTOS_DSCP_AF42 },
974 { "af43", IPTOS_DSCP_AF43 },
975 { "cs0", IPTOS_DSCP_CS0 },
976 { "cs1", IPTOS_DSCP_CS1 },
977 { "cs2", IPTOS_DSCP_CS2 },
978 { "cs3", IPTOS_DSCP_CS3 },
979 { "cs4", IPTOS_DSCP_CS4 },
980 { "cs5", IPTOS_DSCP_CS5 },
981 { "cs6", IPTOS_DSCP_CS6 },
982 { "cs7", IPTOS_DSCP_CS7 },
983 { "ef", IPTOS_DSCP_EF },
984 { "lowdelay", IPTOS_LOWDELAY },
985 { "throughput", IPTOS_THROUGHPUT },
986 { "reliability", IPTOS_RELIABILITY },
991 parse_ipqos(const char *cp)
999 for (i = 0; ipqos[i].name != NULL; i++) {
1000 if (strcasecmp(cp, ipqos[i].name) == 0)
1001 return ipqos[i].value;
1003 /* Try parsing as an integer */
1004 val = strtol(cp, &ep, 0);
1005 if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1011 iptos2str(int iptos)
1014 static char iptos_str[sizeof "0xff"];
1016 for (i = 0; ipqos[i].name != NULL; i++) {
1017 if (ipqos[i].value == iptos)
1018 return ipqos[i].name;
1020 snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1028 *s = tolower((u_char)*s);
1031 sock_set_v6only(int s)
1036 debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
1037 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
1038 error("setsockopt IPV6_V6ONLY: %s", strerror(errno));
1043 sock_get_rcvbuf(int *size, int rcvbuf)
1046 socklen_t socksizelen = sizeof(socksize);
1049 * Create a socket but do not connect it. We use it
1050 * only to get the rcv socket size.
1052 sock = socket(AF_INET6, SOCK_STREAM, 0);
1054 sock = socket(AF_INET, SOCK_STREAM, 0);
1059 * If the tcp_rcv_buf option is set and passed in, attempt to set the
1060 * buffer size to its value.
1063 setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *)&rcvbuf,
1066 if (getsockopt(sock, SOL_SOCKET, SO_RCVBUF,
1067 &socksize, &socksizelen) == 0)