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.
30 #include <sys/types.h>
31 #include <sys/ioctl.h>
32 #include <sys/socket.h>
33 #include <sys/param.h>
42 #include <netinet/in.h>
43 #include <netinet/in_systm.h>
44 #include <netinet/ip.h>
45 #include <netinet/tcp.h>
55 #ifdef SSH_TUN_OPENBSD
64 /* remove newline at end of string */
70 if (*t == '\n' || *t == '\r') {
80 /* set/unset filedescriptor to non-blocking */
86 val = fcntl(fd, F_GETFL, 0);
88 error("fcntl(%d, F_GETFL, 0): %s", fd, strerror(errno));
91 if (val & O_NONBLOCK) {
92 debug3("fd %d is O_NONBLOCK", fd);
95 debug2("fd %d setting O_NONBLOCK", fd);
97 if (fcntl(fd, F_SETFL, val) == -1) {
98 debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
106 unset_nonblock(int fd)
110 val = fcntl(fd, F_GETFL, 0);
112 error("fcntl(%d, F_GETFL, 0): %s", fd, strerror(errno));
115 if (!(val & O_NONBLOCK)) {
116 debug3("fd %d is not O_NONBLOCK", fd);
119 debug("fd %d clearing O_NONBLOCK", fd);
121 if (fcntl(fd, F_SETFL, val) == -1) {
122 debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
123 fd, strerror(errno));
130 ssh_gai_strerror(int gaierr)
132 if (gaierr == EAI_SYSTEM && errno != 0)
133 return strerror(errno);
134 return gai_strerror(gaierr);
137 /* disable nagle on socket */
145 if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
146 debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
150 debug2("fd %d is TCP_NODELAY", fd);
154 debug2("fd %d setting TCP_NODELAY", fd);
155 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
156 error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
159 /* Characters considered whitespace in strsep calls. */
160 #define WHITESPACE " \t\r\n"
163 /* return next token in configuration line */
175 *s = strpbrk(*s, WHITESPACE QUOTE "=");
180 memmove(*s, *s + 1, strlen(*s)); /* move nul too */
181 /* Find matching quote */
182 if ((*s = strpbrk(*s, QUOTE)) == NULL) {
183 return (NULL); /* no matching quote */
186 *s += strspn(*s + 1, WHITESPACE) + 1;
191 /* Allow only one '=' to be skipped */
196 /* Skip any extra whitespace after first token */
197 *s += strspn(*s + 1, WHITESPACE) + 1;
198 if (*s[0] == '=' && !wspace)
199 *s += strspn(*s + 1, WHITESPACE) + 1;
205 pwcopy(struct passwd *pw)
207 struct passwd *copy = xcalloc(1, sizeof(*copy));
209 copy->pw_name = xstrdup(pw->pw_name);
210 copy->pw_passwd = xstrdup(pw->pw_passwd);
211 #ifdef HAVE_STRUCT_PASSWD_PW_GECOS
212 copy->pw_gecos = xstrdup(pw->pw_gecos);
214 copy->pw_uid = pw->pw_uid;
215 copy->pw_gid = pw->pw_gid;
216 #ifdef HAVE_STRUCT_PASSWD_PW_EXPIRE
217 copy->pw_expire = pw->pw_expire;
219 #ifdef HAVE_STRUCT_PASSWD_PW_CHANGE
220 copy->pw_change = pw->pw_change;
222 #ifdef HAVE_STRUCT_PASSWD_PW_CLASS
223 copy->pw_class = xstrdup(pw->pw_class);
225 copy->pw_dir = xstrdup(pw->pw_dir);
226 copy->pw_shell = xstrdup(pw->pw_shell);
231 * Convert ASCII string to TCP/IP port number.
232 * Port must be >=0 and <=65535.
233 * Return -1 if invalid.
236 a2port(const char *s)
241 port = strtonum(s, 0, 65535, &errstr);
248 a2tun(const char *s, int *remote)
250 const char *errstr = NULL;
254 if (remote != NULL) {
255 *remote = SSH_TUNID_ANY;
257 if ((ep = strchr(sp, ':')) == NULL) {
259 return (a2tun(s, NULL));
262 *remote = a2tun(ep, NULL);
263 tun = a2tun(sp, NULL);
265 return (*remote == SSH_TUNID_ERR ? *remote : tun);
268 if (strcasecmp(s, "any") == 0)
269 return (SSH_TUNID_ANY);
271 tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
273 return (SSH_TUNID_ERR);
279 #define MINUTES (SECONDS * 60)
280 #define HOURS (MINUTES * 60)
281 #define DAYS (HOURS * 24)
282 #define WEEKS (DAYS * 7)
285 * Convert a time string into seconds; format is
289 * Valid time qualifiers are:
303 * Return -1 if time string is invalid.
306 convtime(const char *s)
316 if (p == NULL || *p == '\0')
320 secs = strtol(p, &endp, 10);
322 (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
362 * Returns a standardized host+port identifier string.
363 * Caller must free returned string.
366 put_host_port(const char *host, u_short port)
370 if (port == 0 || port == SSH_DEFAULT_PORT)
371 return(xstrdup(host));
372 if (asprintf(&hoststr, "[%s]:%d", host, (int)port) < 0)
373 fatal("put_host_port: asprintf: %s", strerror(errno));
374 debug3("put_host_port: %s", hoststr);
379 * Search for next delimiter between hostnames/addresses and ports.
380 * Argument may be modified (for termination).
381 * Returns *cp if parsing succeeds.
382 * *cp is set to the start of the next delimiter, if one was found.
383 * If this is the last field, *cp is set to NULL.
390 if (cp == NULL || *cp == NULL)
395 if ((s = strchr(s, ']')) == NULL)
399 } else if ((s = strpbrk(s, ":/")) == NULL)
400 s = *cp + strlen(*cp); /* skip to end (see first case below) */
404 *cp = NULL; /* no more fields*/
409 *s = '\0'; /* terminate */
421 cleanhostname(char *host)
423 if (*host == '[' && host[strlen(host) - 1] == ']') {
424 host[strlen(host) - 1] = '\0';
435 if (*cp == ':') /* Leading colon is part of file name. */
441 if (*cp == '@' && *(cp+1) == '[')
443 if (*cp == ']' && *(cp+1) == ':' && flag)
445 if (*cp == ':' && !flag)
453 /* function to assist building execv() arguments */
455 addargs(arglist *args, char *fmt, ...)
463 r = vasprintf(&cp, fmt, ap);
466 fatal("addargs: argument too long");
468 nalloc = args->nalloc;
469 if (args->list == NULL) {
472 } else if (args->num+2 >= nalloc)
475 args->list = xrealloc(args->list, nalloc, sizeof(char *));
476 args->nalloc = nalloc;
477 args->list[args->num++] = cp;
478 args->list[args->num] = NULL;
482 replacearg(arglist *args, u_int which, char *fmt, ...)
489 r = vasprintf(&cp, fmt, ap);
492 fatal("replacearg: argument too long");
494 if (which >= args->num)
495 fatal("replacearg: tried to replace invalid arg %d >= %d",
497 free(args->list[which]);
498 args->list[which] = cp;
502 freeargs(arglist *args)
506 if (args->list != NULL) {
507 for (i = 0; i < args->num; i++)
510 args->nalloc = args->num = 0;
516 * Expands tildes in the file name. Returns data allocated by xmalloc.
517 * Warning: this calls getpw*.
520 tilde_expand_filename(const char *filename, uid_t uid)
522 const char *path, *sep;
523 char user[128], *ret;
527 if (*filename != '~')
528 return (xstrdup(filename));
531 path = strchr(filename, '/');
532 if (path != NULL && path > filename) { /* ~user/path */
533 slash = path - filename;
534 if (slash > sizeof(user) - 1)
535 fatal("tilde_expand_filename: ~username too long");
536 memcpy(user, filename, slash);
538 if ((pw = getpwnam(user)) == NULL)
539 fatal("tilde_expand_filename: No such user %s", user);
540 } else if ((pw = getpwuid(uid)) == NULL) /* ~/path */
541 fatal("tilde_expand_filename: No such uid %ld", (long)uid);
543 /* Make sure directory has a trailing '/' */
544 len = strlen(pw->pw_dir);
545 if (len == 0 || pw->pw_dir[len - 1] != '/')
550 /* Skip leading '/' from specified path */
554 if (xasprintf(&ret, "%s%s%s", pw->pw_dir, sep, filename) >= MAXPATHLEN)
555 fatal("tilde_expand_filename: Path too long");
561 * Expand a string with a set of %[char] escapes. A number of escapes may be
562 * specified as (char *escape_chars, char *replacement) pairs. The list must
563 * be terminated by a NULL escape_char. Returns replaced string in memory
564 * allocated by xmalloc.
567 percent_expand(const char *string, ...)
569 #define EXPAND_MAX_KEYS 16
570 u_int num_keys, i, j;
574 } keys[EXPAND_MAX_KEYS];
579 va_start(ap, string);
580 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
581 keys[num_keys].key = va_arg(ap, char *);
582 if (keys[num_keys].key == NULL)
584 keys[num_keys].repl = va_arg(ap, char *);
585 if (keys[num_keys].repl == NULL)
586 fatal("%s: NULL replacement", __func__);
588 if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
589 fatal("%s: too many keys", __func__);
594 for (i = 0; *string != '\0'; string++) {
595 if (*string != '%') {
598 if (i >= sizeof(buf))
599 fatal("%s: string too long", __func__);
607 for (j = 0; j < num_keys; j++) {
608 if (strchr(keys[j].key, *string) != NULL) {
609 i = strlcat(buf, keys[j].repl, sizeof(buf));
610 if (i >= sizeof(buf))
611 fatal("%s: string too long", __func__);
616 fatal("%s: unknown key %%%c", __func__, *string);
618 return (xstrdup(buf));
619 #undef EXPAND_MAX_KEYS
623 * Read an entire line from a public key file into a static buffer, discarding
624 * lines that exceed the buffer size. Returns 0 on success, -1 on failure.
627 read_keyfile_line(FILE *f, const char *filename, char *buf, size_t bufsz,
630 while (fgets(buf, bufsz, f) != NULL) {
634 if (buf[strlen(buf) - 1] == '\n' || feof(f)) {
637 debug("%s: %s line %lu exceeds size limit", __func__,
639 /* discard remainder of line */
640 while (fgetc(f) != '\n' && !feof(f))
648 tun_open(int tun, int mode)
650 #if defined(CUSTOM_SYS_TUN_OPEN)
651 return (sys_tun_open(tun, mode));
652 #elif defined(SSH_TUN_OPENBSD)
657 /* Open the tunnel device */
658 if (tun <= SSH_TUNID_MAX) {
659 snprintf(name, sizeof(name), "/dev/tun%d", tun);
660 fd = open(name, O_RDWR);
661 } else if (tun == SSH_TUNID_ANY) {
662 for (tun = 100; tun >= 0; tun--) {
663 snprintf(name, sizeof(name), "/dev/tun%d", tun);
664 if ((fd = open(name, O_RDWR)) >= 0)
668 debug("%s: invalid tunnel %u", __func__, tun);
673 debug("%s: %s open failed: %s", __func__, name, strerror(errno));
677 debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
679 /* Set the tunnel device operation mode */
680 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "tun%d", tun);
681 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
684 if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1)
687 /* Set interface mode */
688 ifr.ifr_flags &= ~IFF_UP;
689 if (mode == SSH_TUNMODE_ETHERNET)
690 ifr.ifr_flags |= IFF_LINK0;
692 ifr.ifr_flags &= ~IFF_LINK0;
693 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1)
696 /* Bring interface up */
697 ifr.ifr_flags |= IFF_UP;
698 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1)
709 debug("%s: failed to set %s mode %d: %s", __func__, name,
710 mode, strerror(errno));
713 error("Tunnel interfaces are not supported on this platform");
723 if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
724 fprintf(stderr, "Couldn't open /dev/null: %s\n",
728 while (++dupfd <= 2) {
729 /* Only clobber closed fds */
730 if (fcntl(dupfd, F_GETFL, 0) >= 0)
732 if (dup2(nullfd, dupfd) == -1) {
733 fprintf(stderr, "dup2: %s\n", strerror(errno));
742 tohex(const void *vp, size_t l)
744 const u_char *p = (const u_char *)vp;
749 return xstrdup("tohex: length > 65536");
753 for (i = 0; i < l; i++) {
754 snprintf(b, sizeof(b), "%02x", p[i]);
761 get_u64(const void *vp)
763 const u_char *p = (const u_char *)vp;
766 v = (u_int64_t)p[0] << 56;
767 v |= (u_int64_t)p[1] << 48;
768 v |= (u_int64_t)p[2] << 40;
769 v |= (u_int64_t)p[3] << 32;
770 v |= (u_int64_t)p[4] << 24;
771 v |= (u_int64_t)p[5] << 16;
772 v |= (u_int64_t)p[6] << 8;
773 v |= (u_int64_t)p[7];
779 get_u32(const void *vp)
781 const u_char *p = (const u_char *)vp;
784 v = (u_int32_t)p[0] << 24;
785 v |= (u_int32_t)p[1] << 16;
786 v |= (u_int32_t)p[2] << 8;
787 v |= (u_int32_t)p[3];
793 get_u16(const void *vp)
795 const u_char *p = (const u_char *)vp;
798 v = (u_int16_t)p[0] << 8;
799 v |= (u_int16_t)p[1];
805 put_u64(void *vp, u_int64_t v)
807 u_char *p = (u_char *)vp;
809 p[0] = (u_char)(v >> 56) & 0xff;
810 p[1] = (u_char)(v >> 48) & 0xff;
811 p[2] = (u_char)(v >> 40) & 0xff;
812 p[3] = (u_char)(v >> 32) & 0xff;
813 p[4] = (u_char)(v >> 24) & 0xff;
814 p[5] = (u_char)(v >> 16) & 0xff;
815 p[6] = (u_char)(v >> 8) & 0xff;
816 p[7] = (u_char)v & 0xff;
820 put_u32(void *vp, u_int32_t v)
822 u_char *p = (u_char *)vp;
824 p[0] = (u_char)(v >> 24) & 0xff;
825 p[1] = (u_char)(v >> 16) & 0xff;
826 p[2] = (u_char)(v >> 8) & 0xff;
827 p[3] = (u_char)v & 0xff;
832 put_u16(void *vp, u_int16_t v)
834 u_char *p = (u_char *)vp;
836 p[0] = (u_char)(v >> 8) & 0xff;
837 p[1] = (u_char)v & 0xff;
841 ms_subtract_diff(struct timeval *start, int *ms)
843 struct timeval diff, finish;
845 gettimeofday(&finish, NULL);
846 timersub(&finish, start, &diff);
847 *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
851 ms_to_timeval(struct timeval *tv, int ms)
855 tv->tv_sec = ms / 1000;
856 tv->tv_usec = (ms % 1000) * 1000;
862 #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
864 static int gettime_failed = 0;
866 if (!gettime_failed) {
867 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
869 debug3("clock_gettime: %s", strerror(errno));
878 bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
882 bw->thresh = bw->rate;
884 timerclear(&bw->bwstart);
885 timerclear(&bw->bwend);
888 /* Callback from read/write loop to insert bandwidth-limiting delays */
890 bandwidth_limit(struct bwlimit *bw, size_t read_len)
893 struct timespec ts, rm;
895 if (!timerisset(&bw->bwstart)) {
896 gettimeofday(&bw->bwstart, NULL);
900 bw->lamt += read_len;
901 if (bw->lamt < bw->thresh)
904 gettimeofday(&bw->bwend, NULL);
905 timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
906 if (!timerisset(&bw->bwend))
910 waitlen = (double)1000000L * bw->lamt / bw->rate;
912 bw->bwstart.tv_sec = waitlen / 1000000L;
913 bw->bwstart.tv_usec = waitlen % 1000000L;
915 if (timercmp(&bw->bwstart, &bw->bwend, >)) {
916 timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
918 /* Adjust the wait time */
919 if (bw->bwend.tv_sec) {
921 if (bw->thresh < bw->buflen / 4)
922 bw->thresh = bw->buflen / 4;
923 } else if (bw->bwend.tv_usec < 10000) {
925 if (bw->thresh > bw->buflen * 8)
926 bw->thresh = bw->buflen * 8;
929 TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
930 while (nanosleep(&ts, &rm) == -1) {
938 gettimeofday(&bw->bwstart, NULL);
941 /* Make a template filename for mk[sd]temp() */
943 mktemp_proto(char *s, size_t len)
948 if ((tmpdir = getenv("TMPDIR")) != NULL) {
949 r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
950 if (r > 0 && (size_t)r < len)
953 r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
954 if (r < 0 || (size_t)r >= len)
955 fatal("%s: template string too short", __func__);
958 static const struct {
962 { "af11", IPTOS_DSCP_AF11 },
963 { "af12", IPTOS_DSCP_AF12 },
964 { "af13", IPTOS_DSCP_AF13 },
965 { "af21", IPTOS_DSCP_AF21 },
966 { "af22", IPTOS_DSCP_AF22 },
967 { "af23", IPTOS_DSCP_AF23 },
968 { "af31", IPTOS_DSCP_AF31 },
969 { "af32", IPTOS_DSCP_AF32 },
970 { "af33", IPTOS_DSCP_AF33 },
971 { "af41", IPTOS_DSCP_AF41 },
972 { "af42", IPTOS_DSCP_AF42 },
973 { "af43", IPTOS_DSCP_AF43 },
974 { "cs0", IPTOS_DSCP_CS0 },
975 { "cs1", IPTOS_DSCP_CS1 },
976 { "cs2", IPTOS_DSCP_CS2 },
977 { "cs3", IPTOS_DSCP_CS3 },
978 { "cs4", IPTOS_DSCP_CS4 },
979 { "cs5", IPTOS_DSCP_CS5 },
980 { "cs6", IPTOS_DSCP_CS6 },
981 { "cs7", IPTOS_DSCP_CS7 },
982 { "ef", IPTOS_DSCP_EF },
983 { "lowdelay", IPTOS_LOWDELAY },
984 { "throughput", IPTOS_THROUGHPUT },
985 { "reliability", IPTOS_RELIABILITY },
990 parse_ipqos(const char *cp)
998 for (i = 0; ipqos[i].name != NULL; i++) {
999 if (strcasecmp(cp, ipqos[i].name) == 0)
1000 return ipqos[i].value;
1002 /* Try parsing as an integer */
1003 val = strtol(cp, &ep, 0);
1004 if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1010 iptos2str(int iptos)
1013 static char iptos_str[sizeof "0xff"];
1015 for (i = 0; ipqos[i].name != NULL; i++) {
1016 if (ipqos[i].value == iptos)
1017 return ipqos[i].name;
1019 snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1027 *s = tolower((u_char)*s);
1030 sock_set_v6only(int s)
1035 debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
1036 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
1037 error("setsockopt IPV6_V6ONLY: %s", strerror(errno));
1042 sock_get_rcvbuf(int *size, int rcvbuf)
1045 socklen_t socksizelen = sizeof(socksize);
1048 * Create a socket but do not connect it. We use it
1049 * only to get the rcv socket size.
1051 sock = socket(AF_INET6, SOCK_STREAM, 0);
1053 sock = socket(AF_INET, SOCK_STREAM, 0);
1058 * If the tcp_rcv_buf option is set and passed in, attempt to set the
1059 * buffer size to its value.
1062 setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *)&rcvbuf,
1065 if (getsockopt(sock, SOL_SOCKET, SO_RCVBUF,
1066 &socksize, &socksizelen) == 0)