1 /* $OpenBSD: misc.c,v 1.86 2011/09/05 05:59:08 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>
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)
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 copy->pw_gecos = xstrdup(pw->pw_gecos);
211 copy->pw_uid = pw->pw_uid;
212 copy->pw_gid = pw->pw_gid;
213 #ifdef HAVE_PW_EXPIRE_IN_PASSWD
214 copy->pw_expire = pw->pw_expire;
216 #ifdef HAVE_PW_CHANGE_IN_PASSWD
217 copy->pw_change = pw->pw_change;
219 #ifdef HAVE_PW_CLASS_IN_PASSWD
220 copy->pw_class = xstrdup(pw->pw_class);
222 copy->pw_dir = xstrdup(pw->pw_dir);
223 copy->pw_shell = xstrdup(pw->pw_shell);
228 * Convert ASCII string to TCP/IP port number.
229 * Port must be >=0 and <=65535.
230 * Return -1 if invalid.
233 a2port(const char *s)
238 port = strtonum(s, 0, 65535, &errstr);
245 a2tun(const char *s, int *remote)
247 const char *errstr = NULL;
251 if (remote != NULL) {
252 *remote = SSH_TUNID_ANY;
254 if ((ep = strchr(sp, ':')) == NULL) {
256 return (a2tun(s, NULL));
259 *remote = a2tun(ep, NULL);
260 tun = a2tun(sp, NULL);
262 return (*remote == SSH_TUNID_ERR ? *remote : tun);
265 if (strcasecmp(s, "any") == 0)
266 return (SSH_TUNID_ANY);
268 tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
270 return (SSH_TUNID_ERR);
276 #define MINUTES (SECONDS * 60)
277 #define HOURS (MINUTES * 60)
278 #define DAYS (HOURS * 24)
279 #define WEEKS (DAYS * 7)
282 * Convert a time string into seconds; format is
286 * Valid time qualifiers are:
300 * Return -1 if time string is invalid.
303 convtime(const char *s)
313 if (p == NULL || *p == '\0')
317 secs = strtol(p, &endp, 10);
319 (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
359 * Returns a standardized host+port identifier string.
360 * Caller must free returned string.
363 put_host_port(const char *host, u_short port)
367 if (port == 0 || port == SSH_DEFAULT_PORT)
368 return(xstrdup(host));
369 if (asprintf(&hoststr, "[%s]:%d", host, (int)port) < 0)
370 fatal("put_host_port: asprintf: %s", strerror(errno));
371 debug3("put_host_port: %s", hoststr);
376 * Search for next delimiter between hostnames/addresses and ports.
377 * Argument may be modified (for termination).
378 * Returns *cp if parsing succeeds.
379 * *cp is set to the start of the next delimiter, if one was found.
380 * If this is the last field, *cp is set to NULL.
387 if (cp == NULL || *cp == NULL)
392 if ((s = strchr(s, ']')) == NULL)
396 } else if ((s = strpbrk(s, ":/")) == NULL)
397 s = *cp + strlen(*cp); /* skip to end (see first case below) */
401 *cp = NULL; /* no more fields*/
406 *s = '\0'; /* terminate */
418 cleanhostname(char *host)
420 if (*host == '[' && host[strlen(host) - 1] == ']') {
421 host[strlen(host) - 1] = '\0';
432 if (*cp == ':') /* Leading colon is part of file name. */
438 if (*cp == '@' && *(cp+1) == '[')
440 if (*cp == ']' && *(cp+1) == ':' && flag)
442 if (*cp == ':' && !flag)
450 /* function to assist building execv() arguments */
452 addargs(arglist *args, char *fmt, ...)
460 r = vasprintf(&cp, fmt, ap);
463 fatal("addargs: argument too long");
465 nalloc = args->nalloc;
466 if (args->list == NULL) {
469 } else if (args->num+2 >= nalloc)
472 args->list = xrealloc(args->list, nalloc, sizeof(char *));
473 args->nalloc = nalloc;
474 args->list[args->num++] = cp;
475 args->list[args->num] = NULL;
479 replacearg(arglist *args, u_int which, char *fmt, ...)
486 r = vasprintf(&cp, fmt, ap);
489 fatal("replacearg: argument too long");
491 if (which >= args->num)
492 fatal("replacearg: tried to replace invalid arg %d >= %d",
494 xfree(args->list[which]);
495 args->list[which] = cp;
499 freeargs(arglist *args)
503 if (args->list != NULL) {
504 for (i = 0; i < args->num; i++)
505 xfree(args->list[i]);
507 args->nalloc = args->num = 0;
513 * Expands tildes in the file name. Returns data allocated by xmalloc.
514 * Warning: this calls getpw*.
517 tilde_expand_filename(const char *filename, uid_t uid)
520 char user[128], ret[MAXPATHLEN];
524 if (*filename != '~')
525 return (xstrdup(filename));
528 path = strchr(filename, '/');
529 if (path != NULL && path > filename) { /* ~user/path */
530 slash = path - filename;
531 if (slash > sizeof(user) - 1)
532 fatal("tilde_expand_filename: ~username too long");
533 memcpy(user, filename, slash);
535 if ((pw = getpwnam(user)) == NULL)
536 fatal("tilde_expand_filename: No such user %s", user);
537 } else if ((pw = getpwuid(uid)) == NULL) /* ~/path */
538 fatal("tilde_expand_filename: No such uid %ld", (long)uid);
540 if (strlcpy(ret, pw->pw_dir, sizeof(ret)) >= sizeof(ret))
541 fatal("tilde_expand_filename: Path too long");
543 /* Make sure directory has a trailing '/' */
544 len = strlen(pw->pw_dir);
545 if ((len == 0 || pw->pw_dir[len - 1] != '/') &&
546 strlcat(ret, "/", sizeof(ret)) >= sizeof(ret))
547 fatal("tilde_expand_filename: Path too long");
549 /* Skip leading '/' from specified path */
552 if (strlcat(ret, filename, sizeof(ret)) >= sizeof(ret))
553 fatal("tilde_expand_filename: Path too long");
555 return (xstrdup(ret));
559 * Expand a string with a set of %[char] escapes. A number of escapes may be
560 * specified as (char *escape_chars, char *replacement) pairs. The list must
561 * be terminated by a NULL escape_char. Returns replaced string in memory
562 * allocated by xmalloc.
565 percent_expand(const char *string, ...)
567 #define EXPAND_MAX_KEYS 16
568 u_int num_keys, i, j;
572 } keys[EXPAND_MAX_KEYS];
577 va_start(ap, string);
578 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
579 keys[num_keys].key = va_arg(ap, char *);
580 if (keys[num_keys].key == NULL)
582 keys[num_keys].repl = va_arg(ap, char *);
583 if (keys[num_keys].repl == NULL)
584 fatal("%s: NULL replacement", __func__);
586 if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
587 fatal("%s: too many keys", __func__);
592 for (i = 0; *string != '\0'; string++) {
593 if (*string != '%') {
596 if (i >= sizeof(buf))
597 fatal("%s: string too long", __func__);
605 for (j = 0; j < num_keys; j++) {
606 if (strchr(keys[j].key, *string) != NULL) {
607 i = strlcat(buf, keys[j].repl, sizeof(buf));
608 if (i >= sizeof(buf))
609 fatal("%s: string too long", __func__);
614 fatal("%s: unknown key %%%c", __func__, *string);
616 return (xstrdup(buf));
617 #undef EXPAND_MAX_KEYS
621 * Read an entire line from a public key file into a static buffer, discarding
622 * lines that exceed the buffer size. Returns 0 on success, -1 on failure.
625 read_keyfile_line(FILE *f, const char *filename, char *buf, size_t bufsz,
628 while (fgets(buf, bufsz, f) != NULL) {
632 if (buf[strlen(buf) - 1] == '\n' || feof(f)) {
635 debug("%s: %s line %lu exceeds size limit", __func__,
637 /* discard remainder of line */
638 while (fgetc(f) != '\n' && !feof(f))
646 tun_open(int tun, int mode)
648 #if defined(CUSTOM_SYS_TUN_OPEN)
649 return (sys_tun_open(tun, mode));
650 #elif defined(SSH_TUN_OPENBSD)
655 /* Open the tunnel device */
656 if (tun <= SSH_TUNID_MAX) {
657 snprintf(name, sizeof(name), "/dev/tun%d", tun);
658 fd = open(name, O_RDWR);
659 } else if (tun == SSH_TUNID_ANY) {
660 for (tun = 100; tun >= 0; tun--) {
661 snprintf(name, sizeof(name), "/dev/tun%d", tun);
662 if ((fd = open(name, O_RDWR)) >= 0)
666 debug("%s: invalid tunnel %u", __func__, tun);
671 debug("%s: %s open failed: %s", __func__, name, strerror(errno));
675 debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
677 /* Set the tunnel device operation mode */
678 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "tun%d", tun);
679 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
682 if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1)
685 /* Set interface mode */
686 ifr.ifr_flags &= ~IFF_UP;
687 if (mode == SSH_TUNMODE_ETHERNET)
688 ifr.ifr_flags |= IFF_LINK0;
690 ifr.ifr_flags &= ~IFF_LINK0;
691 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1)
694 /* Bring interface up */
695 ifr.ifr_flags |= IFF_UP;
696 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1)
707 debug("%s: failed to set %s mode %d: %s", __func__, name,
708 mode, strerror(errno));
711 error("Tunnel interfaces are not supported on this platform");
721 if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
722 fprintf(stderr, "Couldn't open /dev/null: %s\n",
726 while (++dupfd <= 2) {
727 /* Only clobber closed fds */
728 if (fcntl(dupfd, F_GETFL, 0) >= 0)
730 if (dup2(nullfd, dupfd) == -1) {
731 fprintf(stderr, "dup2: %s\n", strerror(errno));
740 tohex(const void *vp, size_t l)
742 const u_char *p = (const u_char *)vp;
747 return xstrdup("tohex: length > 65536");
751 for (i = 0; i < l; i++) {
752 snprintf(b, sizeof(b), "%02x", p[i]);
759 get_u64(const void *vp)
761 const u_char *p = (const u_char *)vp;
764 v = (u_int64_t)p[0] << 56;
765 v |= (u_int64_t)p[1] << 48;
766 v |= (u_int64_t)p[2] << 40;
767 v |= (u_int64_t)p[3] << 32;
768 v |= (u_int64_t)p[4] << 24;
769 v |= (u_int64_t)p[5] << 16;
770 v |= (u_int64_t)p[6] << 8;
771 v |= (u_int64_t)p[7];
777 get_u32(const void *vp)
779 const u_char *p = (const u_char *)vp;
782 v = (u_int32_t)p[0] << 24;
783 v |= (u_int32_t)p[1] << 16;
784 v |= (u_int32_t)p[2] << 8;
785 v |= (u_int32_t)p[3];
791 get_u16(const void *vp)
793 const u_char *p = (const u_char *)vp;
796 v = (u_int16_t)p[0] << 8;
797 v |= (u_int16_t)p[1];
803 put_u64(void *vp, u_int64_t v)
805 u_char *p = (u_char *)vp;
807 p[0] = (u_char)(v >> 56) & 0xff;
808 p[1] = (u_char)(v >> 48) & 0xff;
809 p[2] = (u_char)(v >> 40) & 0xff;
810 p[3] = (u_char)(v >> 32) & 0xff;
811 p[4] = (u_char)(v >> 24) & 0xff;
812 p[5] = (u_char)(v >> 16) & 0xff;
813 p[6] = (u_char)(v >> 8) & 0xff;
814 p[7] = (u_char)v & 0xff;
818 put_u32(void *vp, u_int32_t v)
820 u_char *p = (u_char *)vp;
822 p[0] = (u_char)(v >> 24) & 0xff;
823 p[1] = (u_char)(v >> 16) & 0xff;
824 p[2] = (u_char)(v >> 8) & 0xff;
825 p[3] = (u_char)v & 0xff;
830 put_u16(void *vp, u_int16_t v)
832 u_char *p = (u_char *)vp;
834 p[0] = (u_char)(v >> 8) & 0xff;
835 p[1] = (u_char)v & 0xff;
839 ms_subtract_diff(struct timeval *start, int *ms)
841 struct timeval diff, finish;
843 gettimeofday(&finish, NULL);
844 timersub(&finish, start, &diff);
845 *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
849 ms_to_timeval(struct timeval *tv, int ms)
853 tv->tv_sec = ms / 1000;
854 tv->tv_usec = (ms % 1000) * 1000;
858 bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
862 bw->thresh = bw->rate;
864 timerclear(&bw->bwstart);
865 timerclear(&bw->bwend);
868 /* Callback from read/write loop to insert bandwidth-limiting delays */
870 bandwidth_limit(struct bwlimit *bw, size_t read_len)
873 struct timespec ts, rm;
875 if (!timerisset(&bw->bwstart)) {
876 gettimeofday(&bw->bwstart, NULL);
880 bw->lamt += read_len;
881 if (bw->lamt < bw->thresh)
884 gettimeofday(&bw->bwend, NULL);
885 timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
886 if (!timerisset(&bw->bwend))
890 waitlen = (double)1000000L * bw->lamt / bw->rate;
892 bw->bwstart.tv_sec = waitlen / 1000000L;
893 bw->bwstart.tv_usec = waitlen % 1000000L;
895 if (timercmp(&bw->bwstart, &bw->bwend, >)) {
896 timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
898 /* Adjust the wait time */
899 if (bw->bwend.tv_sec) {
901 if (bw->thresh < bw->buflen / 4)
902 bw->thresh = bw->buflen / 4;
903 } else if (bw->bwend.tv_usec < 10000) {
905 if (bw->thresh > bw->buflen * 8)
906 bw->thresh = bw->buflen * 8;
909 TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
910 while (nanosleep(&ts, &rm) == -1) {
918 gettimeofday(&bw->bwstart, NULL);
921 /* Make a template filename for mk[sd]temp() */
923 mktemp_proto(char *s, size_t len)
928 if ((tmpdir = getenv("TMPDIR")) != NULL) {
929 r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
930 if (r > 0 && (size_t)r < len)
933 r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
934 if (r < 0 || (size_t)r >= len)
935 fatal("%s: template string too short", __func__);
938 static const struct {
942 { "af11", IPTOS_DSCP_AF11 },
943 { "af12", IPTOS_DSCP_AF12 },
944 { "af13", IPTOS_DSCP_AF13 },
945 { "af21", IPTOS_DSCP_AF21 },
946 { "af22", IPTOS_DSCP_AF22 },
947 { "af23", IPTOS_DSCP_AF23 },
948 { "af31", IPTOS_DSCP_AF31 },
949 { "af32", IPTOS_DSCP_AF32 },
950 { "af33", IPTOS_DSCP_AF33 },
951 { "af41", IPTOS_DSCP_AF41 },
952 { "af42", IPTOS_DSCP_AF42 },
953 { "af43", IPTOS_DSCP_AF43 },
954 { "cs0", IPTOS_DSCP_CS0 },
955 { "cs1", IPTOS_DSCP_CS1 },
956 { "cs2", IPTOS_DSCP_CS2 },
957 { "cs3", IPTOS_DSCP_CS3 },
958 { "cs4", IPTOS_DSCP_CS4 },
959 { "cs5", IPTOS_DSCP_CS5 },
960 { "cs6", IPTOS_DSCP_CS6 },
961 { "cs7", IPTOS_DSCP_CS7 },
962 { "ef", IPTOS_DSCP_EF },
963 { "lowdelay", IPTOS_LOWDELAY },
964 { "throughput", IPTOS_THROUGHPUT },
965 { "reliability", IPTOS_RELIABILITY },
970 parse_ipqos(const char *cp)
978 for (i = 0; ipqos[i].name != NULL; i++) {
979 if (strcasecmp(cp, ipqos[i].name) == 0)
980 return ipqos[i].value;
982 /* Try parsing as an integer */
983 val = strtol(cp, &ep, 0);
984 if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
993 static char iptos_str[sizeof "0xff"];
995 for (i = 0; ipqos[i].name != NULL; i++) {
996 if (ipqos[i].value == iptos)
997 return ipqos[i].name;
999 snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1003 sock_set_v6only(int s)
1008 debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
1009 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
1010 error("setsockopt IPV6_V6ONLY: %s", strerror(errno));
1015 sock_get_rcvbuf(int *size, int rcvbuf)
1018 socklen_t socksizelen = sizeof(socksize);
1021 * Create a socket but do not connect it. We use it
1022 * only to get the rcv socket size.
1024 sock = socket(AF_INET6, SOCK_STREAM, 0);
1026 sock = socket(AF_INET, SOCK_STREAM, 0);
1031 * If the tcp_rcv_buf option is set and passed in, attempt to set the
1032 * buffer size to its value.
1035 setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *)&rcvbuf,
1038 if (getsockopt(sock, SOL_SOCKET, SO_RCVBUF,
1039 &socksize, &socksizelen) == 0)