1 /* $OpenBSD: misc.c,v 1.92 2013/10/14 23:28:23 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>
32 #include <sys/param.h>
41 #include <netinet/in.h>
42 #include <netinet/in_systm.h>
43 #include <netinet/ip.h>
44 #include <netinet/tcp.h>
54 #ifdef SSH_TUN_OPENBSD
63 /* remove newline at end of string */
69 if (*t == '\n' || *t == '\r') {
79 /* set/unset filedescriptor to non-blocking */
85 val = fcntl(fd, F_GETFL, 0);
87 error("fcntl(%d, F_GETFL, 0): %s", fd, strerror(errno));
90 if (val & O_NONBLOCK) {
91 debug3("fd %d is O_NONBLOCK", fd);
94 debug2("fd %d setting O_NONBLOCK", fd);
96 if (fcntl(fd, F_SETFL, val) == -1) {
97 debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
105 unset_nonblock(int fd)
109 val = fcntl(fd, F_GETFL, 0);
111 error("fcntl(%d, F_GETFL, 0): %s", fd, strerror(errno));
114 if (!(val & O_NONBLOCK)) {
115 debug3("fd %d is not O_NONBLOCK", fd);
118 debug("fd %d clearing O_NONBLOCK", fd);
120 if (fcntl(fd, F_SETFL, val) == -1) {
121 debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
122 fd, strerror(errno));
129 ssh_gai_strerror(int gaierr)
131 if (gaierr == EAI_SYSTEM && errno != 0)
132 return strerror(errno);
133 return gai_strerror(gaierr);
136 /* disable nagle on socket */
144 if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
145 debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
149 debug2("fd %d is TCP_NODELAY", fd);
153 debug2("fd %d setting TCP_NODELAY", fd);
154 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
155 error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
158 /* Characters considered whitespace in strsep calls. */
159 #define WHITESPACE " \t\r\n"
162 /* return next token in configuration line */
174 *s = strpbrk(*s, WHITESPACE QUOTE "=");
179 memmove(*s, *s + 1, strlen(*s)); /* move nul too */
180 /* Find matching quote */
181 if ((*s = strpbrk(*s, QUOTE)) == NULL) {
182 return (NULL); /* no matching quote */
185 *s += strspn(*s + 1, WHITESPACE) + 1;
190 /* Allow only one '=' to be skipped */
195 /* Skip any extra whitespace after first token */
196 *s += strspn(*s + 1, WHITESPACE) + 1;
197 if (*s[0] == '=' && !wspace)
198 *s += strspn(*s + 1, WHITESPACE) + 1;
204 pwcopy(struct passwd *pw)
206 struct passwd *copy = xcalloc(1, sizeof(*copy));
208 copy->pw_name = xstrdup(pw->pw_name);
209 copy->pw_passwd = xstrdup(pw->pw_passwd);
210 #ifdef HAVE_STRUCT_PASSWD_PW_GECOS
211 copy->pw_gecos = xstrdup(pw->pw_gecos);
213 copy->pw_uid = pw->pw_uid;
214 copy->pw_gid = pw->pw_gid;
215 #ifdef HAVE_STRUCT_PASSWD_PW_EXPIRE
216 copy->pw_expire = pw->pw_expire;
218 #ifdef HAVE_STRUCT_PASSWD_PW_CHANGE
219 copy->pw_change = pw->pw_change;
221 #ifdef HAVE_STRUCT_PASSWD_PW_CLASS
222 copy->pw_class = xstrdup(pw->pw_class);
224 copy->pw_dir = xstrdup(pw->pw_dir);
225 copy->pw_shell = xstrdup(pw->pw_shell);
230 * Convert ASCII string to TCP/IP port number.
231 * Port must be >=0 and <=65535.
232 * Return -1 if invalid.
235 a2port(const char *s)
240 port = strtonum(s, 0, 65535, &errstr);
247 a2tun(const char *s, int *remote)
249 const char *errstr = NULL;
253 if (remote != NULL) {
254 *remote = SSH_TUNID_ANY;
256 if ((ep = strchr(sp, ':')) == NULL) {
258 return (a2tun(s, NULL));
261 *remote = a2tun(ep, NULL);
262 tun = a2tun(sp, NULL);
264 return (*remote == SSH_TUNID_ERR ? *remote : tun);
267 if (strcasecmp(s, "any") == 0)
268 return (SSH_TUNID_ANY);
270 tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
272 return (SSH_TUNID_ERR);
278 #define MINUTES (SECONDS * 60)
279 #define HOURS (MINUTES * 60)
280 #define DAYS (HOURS * 24)
281 #define WEEKS (DAYS * 7)
284 * Convert a time string into seconds; format is
288 * Valid time qualifiers are:
302 * Return -1 if time string is invalid.
305 convtime(const char *s)
315 if (p == NULL || *p == '\0')
319 secs = strtol(p, &endp, 10);
321 (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
361 * Returns a standardized host+port identifier string.
362 * Caller must free returned string.
365 put_host_port(const char *host, u_short port)
369 if (port == 0 || port == SSH_DEFAULT_PORT)
370 return(xstrdup(host));
371 if (asprintf(&hoststr, "[%s]:%d", host, (int)port) < 0)
372 fatal("put_host_port: asprintf: %s", strerror(errno));
373 debug3("put_host_port: %s", hoststr);
378 * Search for next delimiter between hostnames/addresses and ports.
379 * Argument may be modified (for termination).
380 * Returns *cp if parsing succeeds.
381 * *cp is set to the start of the next delimiter, if one was found.
382 * If this is the last field, *cp is set to NULL.
389 if (cp == NULL || *cp == NULL)
394 if ((s = strchr(s, ']')) == NULL)
398 } else if ((s = strpbrk(s, ":/")) == NULL)
399 s = *cp + strlen(*cp); /* skip to end (see first case below) */
403 *cp = NULL; /* no more fields*/
408 *s = '\0'; /* terminate */
420 cleanhostname(char *host)
422 if (*host == '[' && host[strlen(host) - 1] == ']') {
423 host[strlen(host) - 1] = '\0';
434 if (*cp == ':') /* Leading colon is part of file name. */
440 if (*cp == '@' && *(cp+1) == '[')
442 if (*cp == ']' && *(cp+1) == ':' && flag)
444 if (*cp == ':' && !flag)
452 /* function to assist building execv() arguments */
454 addargs(arglist *args, char *fmt, ...)
462 r = vasprintf(&cp, fmt, ap);
465 fatal("addargs: argument too long");
467 nalloc = args->nalloc;
468 if (args->list == NULL) {
471 } else if (args->num+2 >= nalloc)
474 args->list = xrealloc(args->list, nalloc, sizeof(char *));
475 args->nalloc = nalloc;
476 args->list[args->num++] = cp;
477 args->list[args->num] = NULL;
481 replacearg(arglist *args, u_int which, char *fmt, ...)
488 r = vasprintf(&cp, fmt, ap);
491 fatal("replacearg: argument too long");
493 if (which >= args->num)
494 fatal("replacearg: tried to replace invalid arg %d >= %d",
496 free(args->list[which]);
497 args->list[which] = cp;
501 freeargs(arglist *args)
505 if (args->list != NULL) {
506 for (i = 0; i < args->num; i++)
509 args->nalloc = args->num = 0;
515 * Expands tildes in the file name. Returns data allocated by xmalloc.
516 * Warning: this calls getpw*.
519 tilde_expand_filename(const char *filename, uid_t uid)
521 const char *path, *sep;
522 char user[128], *ret;
526 if (*filename != '~')
527 return (xstrdup(filename));
530 path = strchr(filename, '/');
531 if (path != NULL && path > filename) { /* ~user/path */
532 slash = path - filename;
533 if (slash > sizeof(user) - 1)
534 fatal("tilde_expand_filename: ~username too long");
535 memcpy(user, filename, slash);
537 if ((pw = getpwnam(user)) == NULL)
538 fatal("tilde_expand_filename: No such user %s", user);
539 } else if ((pw = getpwuid(uid)) == NULL) /* ~/path */
540 fatal("tilde_expand_filename: No such uid %ld", (long)uid);
542 /* Make sure directory has a trailing '/' */
543 len = strlen(pw->pw_dir);
544 if (len == 0 || pw->pw_dir[len - 1] != '/')
549 /* Skip leading '/' from specified path */
553 if (xasprintf(&ret, "%s%s%s", pw->pw_dir, sep, filename) >= MAXPATHLEN)
554 fatal("tilde_expand_filename: Path too long");
560 * Expand a string with a set of %[char] escapes. A number of escapes may be
561 * specified as (char *escape_chars, char *replacement) pairs. The list must
562 * be terminated by a NULL escape_char. Returns replaced string in memory
563 * allocated by xmalloc.
566 percent_expand(const char *string, ...)
568 #define EXPAND_MAX_KEYS 16
569 u_int num_keys, i, j;
573 } keys[EXPAND_MAX_KEYS];
578 va_start(ap, string);
579 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
580 keys[num_keys].key = va_arg(ap, char *);
581 if (keys[num_keys].key == NULL)
583 keys[num_keys].repl = va_arg(ap, char *);
584 if (keys[num_keys].repl == NULL)
585 fatal("%s: NULL replacement", __func__);
587 if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
588 fatal("%s: too many keys", __func__);
593 for (i = 0; *string != '\0'; string++) {
594 if (*string != '%') {
597 if (i >= sizeof(buf))
598 fatal("%s: string too long", __func__);
606 for (j = 0; j < num_keys; j++) {
607 if (strchr(keys[j].key, *string) != NULL) {
608 i = strlcat(buf, keys[j].repl, sizeof(buf));
609 if (i >= sizeof(buf))
610 fatal("%s: string too long", __func__);
615 fatal("%s: unknown key %%%c", __func__, *string);
617 return (xstrdup(buf));
618 #undef EXPAND_MAX_KEYS
622 * Read an entire line from a public key file into a static buffer, discarding
623 * lines that exceed the buffer size. Returns 0 on success, -1 on failure.
626 read_keyfile_line(FILE *f, const char *filename, char *buf, size_t bufsz,
629 while (fgets(buf, bufsz, f) != NULL) {
633 if (buf[strlen(buf) - 1] == '\n' || feof(f)) {
636 debug("%s: %s line %lu exceeds size limit", __func__,
638 /* discard remainder of line */
639 while (fgetc(f) != '\n' && !feof(f))
647 tun_open(int tun, int mode)
649 #if defined(CUSTOM_SYS_TUN_OPEN)
650 return (sys_tun_open(tun, mode));
651 #elif defined(SSH_TUN_OPENBSD)
656 /* Open the tunnel device */
657 if (tun <= SSH_TUNID_MAX) {
658 snprintf(name, sizeof(name), "/dev/tun%d", tun);
659 fd = open(name, O_RDWR);
660 } else if (tun == SSH_TUNID_ANY) {
661 for (tun = 100; tun >= 0; tun--) {
662 snprintf(name, sizeof(name), "/dev/tun%d", tun);
663 if ((fd = open(name, O_RDWR)) >= 0)
667 debug("%s: invalid tunnel %u", __func__, tun);
672 debug("%s: %s open failed: %s", __func__, name, strerror(errno));
676 debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
678 /* Set the tunnel device operation mode */
679 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "tun%d", tun);
680 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
683 if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1)
686 /* Set interface mode */
687 ifr.ifr_flags &= ~IFF_UP;
688 if (mode == SSH_TUNMODE_ETHERNET)
689 ifr.ifr_flags |= IFF_LINK0;
691 ifr.ifr_flags &= ~IFF_LINK0;
692 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1)
695 /* Bring interface up */
696 ifr.ifr_flags |= IFF_UP;
697 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1)
708 debug("%s: failed to set %s mode %d: %s", __func__, name,
709 mode, strerror(errno));
712 error("Tunnel interfaces are not supported on this platform");
722 if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
723 fprintf(stderr, "Couldn't open /dev/null: %s\n",
727 while (++dupfd <= 2) {
728 /* Only clobber closed fds */
729 if (fcntl(dupfd, F_GETFL, 0) >= 0)
731 if (dup2(nullfd, dupfd) == -1) {
732 fprintf(stderr, "dup2: %s\n", strerror(errno));
741 tohex(const void *vp, size_t l)
743 const u_char *p = (const u_char *)vp;
748 return xstrdup("tohex: length > 65536");
752 for (i = 0; i < l; i++) {
753 snprintf(b, sizeof(b), "%02x", p[i]);
760 get_u64(const void *vp)
762 const u_char *p = (const u_char *)vp;
765 v = (u_int64_t)p[0] << 56;
766 v |= (u_int64_t)p[1] << 48;
767 v |= (u_int64_t)p[2] << 40;
768 v |= (u_int64_t)p[3] << 32;
769 v |= (u_int64_t)p[4] << 24;
770 v |= (u_int64_t)p[5] << 16;
771 v |= (u_int64_t)p[6] << 8;
772 v |= (u_int64_t)p[7];
778 get_u32(const void *vp)
780 const u_char *p = (const u_char *)vp;
783 v = (u_int32_t)p[0] << 24;
784 v |= (u_int32_t)p[1] << 16;
785 v |= (u_int32_t)p[2] << 8;
786 v |= (u_int32_t)p[3];
792 get_u16(const void *vp)
794 const u_char *p = (const u_char *)vp;
797 v = (u_int16_t)p[0] << 8;
798 v |= (u_int16_t)p[1];
804 put_u64(void *vp, u_int64_t v)
806 u_char *p = (u_char *)vp;
808 p[0] = (u_char)(v >> 56) & 0xff;
809 p[1] = (u_char)(v >> 48) & 0xff;
810 p[2] = (u_char)(v >> 40) & 0xff;
811 p[3] = (u_char)(v >> 32) & 0xff;
812 p[4] = (u_char)(v >> 24) & 0xff;
813 p[5] = (u_char)(v >> 16) & 0xff;
814 p[6] = (u_char)(v >> 8) & 0xff;
815 p[7] = (u_char)v & 0xff;
819 put_u32(void *vp, u_int32_t v)
821 u_char *p = (u_char *)vp;
823 p[0] = (u_char)(v >> 24) & 0xff;
824 p[1] = (u_char)(v >> 16) & 0xff;
825 p[2] = (u_char)(v >> 8) & 0xff;
826 p[3] = (u_char)v & 0xff;
831 put_u16(void *vp, u_int16_t v)
833 u_char *p = (u_char *)vp;
835 p[0] = (u_char)(v >> 8) & 0xff;
836 p[1] = (u_char)v & 0xff;
840 ms_subtract_diff(struct timeval *start, int *ms)
842 struct timeval diff, finish;
844 gettimeofday(&finish, NULL);
845 timersub(&finish, start, &diff);
846 *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
850 ms_to_timeval(struct timeval *tv, int ms)
854 tv->tv_sec = ms / 1000;
855 tv->tv_usec = (ms % 1000) * 1000;
861 #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
863 static int gettime_failed = 0;
865 if (!gettime_failed) {
866 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
868 debug3("clock_gettime: %s", strerror(errno));
877 bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
881 bw->thresh = bw->rate;
883 timerclear(&bw->bwstart);
884 timerclear(&bw->bwend);
887 /* Callback from read/write loop to insert bandwidth-limiting delays */
889 bandwidth_limit(struct bwlimit *bw, size_t read_len)
892 struct timespec ts, rm;
894 if (!timerisset(&bw->bwstart)) {
895 gettimeofday(&bw->bwstart, NULL);
899 bw->lamt += read_len;
900 if (bw->lamt < bw->thresh)
903 gettimeofday(&bw->bwend, NULL);
904 timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
905 if (!timerisset(&bw->bwend))
909 waitlen = (double)1000000L * bw->lamt / bw->rate;
911 bw->bwstart.tv_sec = waitlen / 1000000L;
912 bw->bwstart.tv_usec = waitlen % 1000000L;
914 if (timercmp(&bw->bwstart, &bw->bwend, >)) {
915 timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
917 /* Adjust the wait time */
918 if (bw->bwend.tv_sec) {
920 if (bw->thresh < bw->buflen / 4)
921 bw->thresh = bw->buflen / 4;
922 } else if (bw->bwend.tv_usec < 10000) {
924 if (bw->thresh > bw->buflen * 8)
925 bw->thresh = bw->buflen * 8;
928 TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
929 while (nanosleep(&ts, &rm) == -1) {
937 gettimeofday(&bw->bwstart, NULL);
940 /* Make a template filename for mk[sd]temp() */
942 mktemp_proto(char *s, size_t len)
947 if ((tmpdir = getenv("TMPDIR")) != NULL) {
948 r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
949 if (r > 0 && (size_t)r < len)
952 r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
953 if (r < 0 || (size_t)r >= len)
954 fatal("%s: template string too short", __func__);
957 static const struct {
961 { "af11", IPTOS_DSCP_AF11 },
962 { "af12", IPTOS_DSCP_AF12 },
963 { "af13", IPTOS_DSCP_AF13 },
964 { "af21", IPTOS_DSCP_AF21 },
965 { "af22", IPTOS_DSCP_AF22 },
966 { "af23", IPTOS_DSCP_AF23 },
967 { "af31", IPTOS_DSCP_AF31 },
968 { "af32", IPTOS_DSCP_AF32 },
969 { "af33", IPTOS_DSCP_AF33 },
970 { "af41", IPTOS_DSCP_AF41 },
971 { "af42", IPTOS_DSCP_AF42 },
972 { "af43", IPTOS_DSCP_AF43 },
973 { "cs0", IPTOS_DSCP_CS0 },
974 { "cs1", IPTOS_DSCP_CS1 },
975 { "cs2", IPTOS_DSCP_CS2 },
976 { "cs3", IPTOS_DSCP_CS3 },
977 { "cs4", IPTOS_DSCP_CS4 },
978 { "cs5", IPTOS_DSCP_CS5 },
979 { "cs6", IPTOS_DSCP_CS6 },
980 { "cs7", IPTOS_DSCP_CS7 },
981 { "ef", IPTOS_DSCP_EF },
982 { "lowdelay", IPTOS_LOWDELAY },
983 { "throughput", IPTOS_THROUGHPUT },
984 { "reliability", IPTOS_RELIABILITY },
989 parse_ipqos(const char *cp)
997 for (i = 0; ipqos[i].name != NULL; i++) {
998 if (strcasecmp(cp, ipqos[i].name) == 0)
999 return ipqos[i].value;
1001 /* Try parsing as an integer */
1002 val = strtol(cp, &ep, 0);
1003 if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1009 iptos2str(int iptos)
1012 static char iptos_str[sizeof "0xff"];
1014 for (i = 0; ipqos[i].name != NULL; i++) {
1015 if (ipqos[i].value == iptos)
1016 return ipqos[i].name;
1018 snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1026 *s = tolower((u_char)*s);
1029 sock_set_v6only(int s)
1034 debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
1035 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
1036 error("setsockopt IPV6_V6ONLY: %s", strerror(errno));