- (dtucker) OpenBSD CVS Sync
[openssh-git.git] / misc.c
blob1c57ce0acb7551a3c65cd1cba4535b93536284a1
1 /* $OpenBSD: misc.c,v 1.84 2010/11/21 01:01:13 djm Exp $ */
2 /*
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
8 * are met:
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.
27 #include "includes.h"
29 #include <sys/types.h>
30 #include <sys/ioctl.h>
31 #include <sys/socket.h>
32 #include <sys/param.h>
34 #include <stdarg.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <unistd.h>
40 #include <netinet/in.h>
41 #include <netinet/in_systm.h>
42 #include <netinet/ip.h>
43 #include <netinet/tcp.h>
45 #include <errno.h>
46 #include <fcntl.h>
47 #include <netdb.h>
48 #ifdef HAVE_PATHS_H
49 # include <paths.h>
50 #include <pwd.h>
51 #endif
52 #ifdef SSH_TUN_OPENBSD
53 #include <net/if.h>
54 #endif
56 #include "xmalloc.h"
57 #include "misc.h"
58 #include "log.h"
59 #include "ssh.h"
61 /* remove newline at end of string */
62 char *
63 chop(char *s)
65 char *t = s;
66 while (*t) {
67 if (*t == '\n' || *t == '\r') {
68 *t = '\0';
69 return s;
71 t++;
73 return s;
77 /* set/unset filedescriptor to non-blocking */
78 int
79 set_nonblock(int fd)
81 int val;
83 val = fcntl(fd, F_GETFL, 0);
84 if (val < 0) {
85 error("fcntl(%d, F_GETFL, 0): %s", fd, strerror(errno));
86 return (-1);
88 if (val & O_NONBLOCK) {
89 debug3("fd %d is O_NONBLOCK", fd);
90 return (0);
92 debug2("fd %d setting O_NONBLOCK", fd);
93 val |= O_NONBLOCK;
94 if (fcntl(fd, F_SETFL, val) == -1) {
95 debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
96 strerror(errno));
97 return (-1);
99 return (0);
103 unset_nonblock(int fd)
105 int val;
107 val = fcntl(fd, F_GETFL, 0);
108 if (val < 0) {
109 error("fcntl(%d, F_GETFL, 0): %s", fd, strerror(errno));
110 return (-1);
112 if (!(val & O_NONBLOCK)) {
113 debug3("fd %d is not O_NONBLOCK", fd);
114 return (0);
116 debug("fd %d clearing O_NONBLOCK", fd);
117 val &= ~O_NONBLOCK;
118 if (fcntl(fd, F_SETFL, val) == -1) {
119 debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
120 fd, strerror(errno));
121 return (-1);
123 return (0);
126 const char *
127 ssh_gai_strerror(int gaierr)
129 if (gaierr == EAI_SYSTEM)
130 return strerror(errno);
131 return gai_strerror(gaierr);
134 /* disable nagle on socket */
135 void
136 set_nodelay(int fd)
138 int opt;
139 socklen_t optlen;
141 optlen = sizeof opt;
142 if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
143 debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
144 return;
146 if (opt == 1) {
147 debug2("fd %d is TCP_NODELAY", fd);
148 return;
150 opt = 1;
151 debug2("fd %d setting TCP_NODELAY", fd);
152 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
153 error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
156 /* Characters considered whitespace in strsep calls. */
157 #define WHITESPACE " \t\r\n"
158 #define QUOTE "\""
160 /* return next token in configuration line */
161 char *
162 strdelim(char **s)
164 char *old;
165 int wspace = 0;
167 if (*s == NULL)
168 return NULL;
170 old = *s;
172 *s = strpbrk(*s, WHITESPACE QUOTE "=");
173 if (*s == NULL)
174 return (old);
176 if (*s[0] == '\"') {
177 memmove(*s, *s + 1, strlen(*s)); /* move nul too */
178 /* Find matching quote */
179 if ((*s = strpbrk(*s, QUOTE)) == NULL) {
180 return (NULL); /* no matching quote */
181 } else {
182 *s[0] = '\0';
183 *s += strspn(*s + 1, WHITESPACE) + 1;
184 return (old);
188 /* Allow only one '=' to be skipped */
189 if (*s[0] == '=')
190 wspace = 1;
191 *s[0] = '\0';
193 /* Skip any extra whitespace after first token */
194 *s += strspn(*s + 1, WHITESPACE) + 1;
195 if (*s[0] == '=' && !wspace)
196 *s += strspn(*s + 1, WHITESPACE) + 1;
198 return (old);
201 struct passwd *
202 pwcopy(struct passwd *pw)
204 struct passwd *copy = xcalloc(1, sizeof(*copy));
206 copy->pw_name = xstrdup(pw->pw_name);
207 copy->pw_passwd = xstrdup(pw->pw_passwd);
208 copy->pw_gecos = xstrdup(pw->pw_gecos);
209 copy->pw_uid = pw->pw_uid;
210 copy->pw_gid = pw->pw_gid;
211 #ifdef HAVE_PW_EXPIRE_IN_PASSWD
212 copy->pw_expire = pw->pw_expire;
213 #endif
214 #ifdef HAVE_PW_CHANGE_IN_PASSWD
215 copy->pw_change = pw->pw_change;
216 #endif
217 #ifdef HAVE_PW_CLASS_IN_PASSWD
218 copy->pw_class = xstrdup(pw->pw_class);
219 #endif
220 copy->pw_dir = xstrdup(pw->pw_dir);
221 copy->pw_shell = xstrdup(pw->pw_shell);
222 return copy;
226 * Convert ASCII string to TCP/IP port number.
227 * Port must be >=0 and <=65535.
228 * Return -1 if invalid.
231 a2port(const char *s)
233 long long port;
234 const char *errstr;
236 port = strtonum(s, 0, 65535, &errstr);
237 if (errstr != NULL)
238 return -1;
239 return (int)port;
243 a2tun(const char *s, int *remote)
245 const char *errstr = NULL;
246 char *sp, *ep;
247 int tun;
249 if (remote != NULL) {
250 *remote = SSH_TUNID_ANY;
251 sp = xstrdup(s);
252 if ((ep = strchr(sp, ':')) == NULL) {
253 xfree(sp);
254 return (a2tun(s, NULL));
256 ep[0] = '\0'; ep++;
257 *remote = a2tun(ep, NULL);
258 tun = a2tun(sp, NULL);
259 xfree(sp);
260 return (*remote == SSH_TUNID_ERR ? *remote : tun);
263 if (strcasecmp(s, "any") == 0)
264 return (SSH_TUNID_ANY);
266 tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
267 if (errstr != NULL)
268 return (SSH_TUNID_ERR);
270 return (tun);
273 #define SECONDS 1
274 #define MINUTES (SECONDS * 60)
275 #define HOURS (MINUTES * 60)
276 #define DAYS (HOURS * 24)
277 #define WEEKS (DAYS * 7)
280 * Convert a time string into seconds; format is
281 * a sequence of:
282 * time[qualifier]
284 * Valid time qualifiers are:
285 * <none> seconds
286 * s|S seconds
287 * m|M minutes
288 * h|H hours
289 * d|D days
290 * w|W weeks
292 * Examples:
293 * 90m 90 minutes
294 * 1h30m 90 minutes
295 * 2d 2 days
296 * 1w 1 week
298 * Return -1 if time string is invalid.
300 long
301 convtime(const char *s)
303 long total, secs;
304 const char *p;
305 char *endp;
307 errno = 0;
308 total = 0;
309 p = s;
311 if (p == NULL || *p == '\0')
312 return -1;
314 while (*p) {
315 secs = strtol(p, &endp, 10);
316 if (p == endp ||
317 (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
318 secs < 0)
319 return -1;
321 switch (*endp++) {
322 case '\0':
323 endp--;
324 break;
325 case 's':
326 case 'S':
327 break;
328 case 'm':
329 case 'M':
330 secs *= MINUTES;
331 break;
332 case 'h':
333 case 'H':
334 secs *= HOURS;
335 break;
336 case 'd':
337 case 'D':
338 secs *= DAYS;
339 break;
340 case 'w':
341 case 'W':
342 secs *= WEEKS;
343 break;
344 default:
345 return -1;
347 total += secs;
348 if (total < 0)
349 return -1;
350 p = endp;
353 return total;
357 * Returns a standardized host+port identifier string.
358 * Caller must free returned string.
360 char *
361 put_host_port(const char *host, u_short port)
363 char *hoststr;
365 if (port == 0 || port == SSH_DEFAULT_PORT)
366 return(xstrdup(host));
367 if (asprintf(&hoststr, "[%s]:%d", host, (int)port) < 0)
368 fatal("put_host_port: asprintf: %s", strerror(errno));
369 debug3("put_host_port: %s", hoststr);
370 return hoststr;
374 * Search for next delimiter between hostnames/addresses and ports.
375 * Argument may be modified (for termination).
376 * Returns *cp if parsing succeeds.
377 * *cp is set to the start of the next delimiter, if one was found.
378 * If this is the last field, *cp is set to NULL.
380 char *
381 hpdelim(char **cp)
383 char *s, *old;
385 if (cp == NULL || *cp == NULL)
386 return NULL;
388 old = s = *cp;
389 if (*s == '[') {
390 if ((s = strchr(s, ']')) == NULL)
391 return NULL;
392 else
393 s++;
394 } else if ((s = strpbrk(s, ":/")) == NULL)
395 s = *cp + strlen(*cp); /* skip to end (see first case below) */
397 switch (*s) {
398 case '\0':
399 *cp = NULL; /* no more fields*/
400 break;
402 case ':':
403 case '/':
404 *s = '\0'; /* terminate */
405 *cp = s + 1;
406 break;
408 default:
409 return NULL;
412 return old;
415 char *
416 cleanhostname(char *host)
418 if (*host == '[' && host[strlen(host) - 1] == ']') {
419 host[strlen(host) - 1] = '\0';
420 return (host + 1);
421 } else
422 return host;
425 char *
426 colon(char *cp)
428 int flag = 0;
430 if (*cp == ':') /* Leading colon is part of file name. */
431 return NULL;
432 if (*cp == '[')
433 flag = 1;
435 for (; *cp; ++cp) {
436 if (*cp == '@' && *(cp+1) == '[')
437 flag = 1;
438 if (*cp == ']' && *(cp+1) == ':' && flag)
439 return (cp+1);
440 if (*cp == ':' && !flag)
441 return (cp);
442 if (*cp == '/')
443 return NULL;
445 return NULL;
448 /* function to assist building execv() arguments */
449 void
450 addargs(arglist *args, char *fmt, ...)
452 va_list ap;
453 char *cp;
454 u_int nalloc;
455 int r;
457 va_start(ap, fmt);
458 r = vasprintf(&cp, fmt, ap);
459 va_end(ap);
460 if (r == -1)
461 fatal("addargs: argument too long");
463 nalloc = args->nalloc;
464 if (args->list == NULL) {
465 nalloc = 32;
466 args->num = 0;
467 } else if (args->num+2 >= nalloc)
468 nalloc *= 2;
470 args->list = xrealloc(args->list, nalloc, sizeof(char *));
471 args->nalloc = nalloc;
472 args->list[args->num++] = cp;
473 args->list[args->num] = NULL;
476 void
477 replacearg(arglist *args, u_int which, char *fmt, ...)
479 va_list ap;
480 char *cp;
481 int r;
483 va_start(ap, fmt);
484 r = vasprintf(&cp, fmt, ap);
485 va_end(ap);
486 if (r == -1)
487 fatal("replacearg: argument too long");
489 if (which >= args->num)
490 fatal("replacearg: tried to replace invalid arg %d >= %d",
491 which, args->num);
492 xfree(args->list[which]);
493 args->list[which] = cp;
496 void
497 freeargs(arglist *args)
499 u_int i;
501 if (args->list != NULL) {
502 for (i = 0; i < args->num; i++)
503 xfree(args->list[i]);
504 xfree(args->list);
505 args->nalloc = args->num = 0;
506 args->list = NULL;
511 * Expands tildes in the file name. Returns data allocated by xmalloc.
512 * Warning: this calls getpw*.
514 char *
515 tilde_expand_filename(const char *filename, uid_t uid)
517 const char *path;
518 char user[128], ret[MAXPATHLEN];
519 struct passwd *pw;
520 u_int len, slash;
522 if (*filename != '~')
523 return (xstrdup(filename));
524 filename++;
526 path = strchr(filename, '/');
527 if (path != NULL && path > filename) { /* ~user/path */
528 slash = path - filename;
529 if (slash > sizeof(user) - 1)
530 fatal("tilde_expand_filename: ~username too long");
531 memcpy(user, filename, slash);
532 user[slash] = '\0';
533 if ((pw = getpwnam(user)) == NULL)
534 fatal("tilde_expand_filename: No such user %s", user);
535 } else if ((pw = getpwuid(uid)) == NULL) /* ~/path */
536 fatal("tilde_expand_filename: No such uid %ld", (long)uid);
538 if (strlcpy(ret, pw->pw_dir, sizeof(ret)) >= sizeof(ret))
539 fatal("tilde_expand_filename: Path too long");
541 /* Make sure directory has a trailing '/' */
542 len = strlen(pw->pw_dir);
543 if ((len == 0 || pw->pw_dir[len - 1] != '/') &&
544 strlcat(ret, "/", sizeof(ret)) >= sizeof(ret))
545 fatal("tilde_expand_filename: Path too long");
547 /* Skip leading '/' from specified path */
548 if (path != NULL)
549 filename = path + 1;
550 if (strlcat(ret, filename, sizeof(ret)) >= sizeof(ret))
551 fatal("tilde_expand_filename: Path too long");
553 return (xstrdup(ret));
557 * Expand a string with a set of %[char] escapes. A number of escapes may be
558 * specified as (char *escape_chars, char *replacement) pairs. The list must
559 * be terminated by a NULL escape_char. Returns replaced string in memory
560 * allocated by xmalloc.
562 char *
563 percent_expand(const char *string, ...)
565 #define EXPAND_MAX_KEYS 16
566 u_int num_keys, i, j;
567 struct {
568 const char *key;
569 const char *repl;
570 } keys[EXPAND_MAX_KEYS];
571 char buf[4096];
572 va_list ap;
574 /* Gather keys */
575 va_start(ap, string);
576 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
577 keys[num_keys].key = va_arg(ap, char *);
578 if (keys[num_keys].key == NULL)
579 break;
580 keys[num_keys].repl = va_arg(ap, char *);
581 if (keys[num_keys].repl == NULL)
582 fatal("%s: NULL replacement", __func__);
584 if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
585 fatal("%s: too many keys", __func__);
586 va_end(ap);
588 /* Expand string */
589 *buf = '\0';
590 for (i = 0; *string != '\0'; string++) {
591 if (*string != '%') {
592 append:
593 buf[i++] = *string;
594 if (i >= sizeof(buf))
595 fatal("%s: string too long", __func__);
596 buf[i] = '\0';
597 continue;
599 string++;
600 /* %% case */
601 if (*string == '%')
602 goto append;
603 for (j = 0; j < num_keys; j++) {
604 if (strchr(keys[j].key, *string) != NULL) {
605 i = strlcat(buf, keys[j].repl, sizeof(buf));
606 if (i >= sizeof(buf))
607 fatal("%s: string too long", __func__);
608 break;
611 if (j >= num_keys)
612 fatal("%s: unknown key %%%c", __func__, *string);
614 return (xstrdup(buf));
615 #undef EXPAND_MAX_KEYS
619 * Read an entire line from a public key file into a static buffer, discarding
620 * lines that exceed the buffer size. Returns 0 on success, -1 on failure.
623 read_keyfile_line(FILE *f, const char *filename, char *buf, size_t bufsz,
624 u_long *lineno)
626 while (fgets(buf, bufsz, f) != NULL) {
627 if (buf[0] == '\0')
628 continue;
629 (*lineno)++;
630 if (buf[strlen(buf) - 1] == '\n' || feof(f)) {
631 return 0;
632 } else {
633 debug("%s: %s line %lu exceeds size limit", __func__,
634 filename, *lineno);
635 /* discard remainder of line */
636 while (fgetc(f) != '\n' && !feof(f))
637 ; /* nothing */
640 return -1;
644 tun_open(int tun, int mode)
646 #if defined(CUSTOM_SYS_TUN_OPEN)
647 return (sys_tun_open(tun, mode));
648 #elif defined(SSH_TUN_OPENBSD)
649 struct ifreq ifr;
650 char name[100];
651 int fd = -1, sock;
653 /* Open the tunnel device */
654 if (tun <= SSH_TUNID_MAX) {
655 snprintf(name, sizeof(name), "/dev/tun%d", tun);
656 fd = open(name, O_RDWR);
657 } else if (tun == SSH_TUNID_ANY) {
658 for (tun = 100; tun >= 0; tun--) {
659 snprintf(name, sizeof(name), "/dev/tun%d", tun);
660 if ((fd = open(name, O_RDWR)) >= 0)
661 break;
663 } else {
664 debug("%s: invalid tunnel %u", __func__, tun);
665 return (-1);
668 if (fd < 0) {
669 debug("%s: %s open failed: %s", __func__, name, strerror(errno));
670 return (-1);
673 debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
675 /* Set the tunnel device operation mode */
676 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "tun%d", tun);
677 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
678 goto failed;
680 if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1)
681 goto failed;
683 /* Set interface mode */
684 ifr.ifr_flags &= ~IFF_UP;
685 if (mode == SSH_TUNMODE_ETHERNET)
686 ifr.ifr_flags |= IFF_LINK0;
687 else
688 ifr.ifr_flags &= ~IFF_LINK0;
689 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1)
690 goto failed;
692 /* Bring interface up */
693 ifr.ifr_flags |= IFF_UP;
694 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1)
695 goto failed;
697 close(sock);
698 return (fd);
700 failed:
701 if (fd >= 0)
702 close(fd);
703 if (sock >= 0)
704 close(sock);
705 debug("%s: failed to set %s mode %d: %s", __func__, name,
706 mode, strerror(errno));
707 return (-1);
708 #else
709 error("Tunnel interfaces are not supported on this platform");
710 return (-1);
711 #endif
714 void
715 sanitise_stdfd(void)
717 int nullfd, dupfd;
719 if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
720 fprintf(stderr, "Couldn't open /dev/null: %s\n",
721 strerror(errno));
722 exit(1);
724 while (++dupfd <= 2) {
725 /* Only clobber closed fds */
726 if (fcntl(dupfd, F_GETFL, 0) >= 0)
727 continue;
728 if (dup2(nullfd, dupfd) == -1) {
729 fprintf(stderr, "dup2: %s\n", strerror(errno));
730 exit(1);
733 if (nullfd > 2)
734 close(nullfd);
737 char *
738 tohex(const void *vp, size_t l)
740 const u_char *p = (const u_char *)vp;
741 char b[3], *r;
742 size_t i, hl;
744 if (l > 65536)
745 return xstrdup("tohex: length > 65536");
747 hl = l * 2 + 1;
748 r = xcalloc(1, hl);
749 for (i = 0; i < l; i++) {
750 snprintf(b, sizeof(b), "%02x", p[i]);
751 strlcat(r, b, hl);
753 return (r);
756 u_int64_t
757 get_u64(const void *vp)
759 const u_char *p = (const u_char *)vp;
760 u_int64_t v;
762 v = (u_int64_t)p[0] << 56;
763 v |= (u_int64_t)p[1] << 48;
764 v |= (u_int64_t)p[2] << 40;
765 v |= (u_int64_t)p[3] << 32;
766 v |= (u_int64_t)p[4] << 24;
767 v |= (u_int64_t)p[5] << 16;
768 v |= (u_int64_t)p[6] << 8;
769 v |= (u_int64_t)p[7];
771 return (v);
774 u_int32_t
775 get_u32(const void *vp)
777 const u_char *p = (const u_char *)vp;
778 u_int32_t v;
780 v = (u_int32_t)p[0] << 24;
781 v |= (u_int32_t)p[1] << 16;
782 v |= (u_int32_t)p[2] << 8;
783 v |= (u_int32_t)p[3];
785 return (v);
788 u_int16_t
789 get_u16(const void *vp)
791 const u_char *p = (const u_char *)vp;
792 u_int16_t v;
794 v = (u_int16_t)p[0] << 8;
795 v |= (u_int16_t)p[1];
797 return (v);
800 void
801 put_u64(void *vp, u_int64_t v)
803 u_char *p = (u_char *)vp;
805 p[0] = (u_char)(v >> 56) & 0xff;
806 p[1] = (u_char)(v >> 48) & 0xff;
807 p[2] = (u_char)(v >> 40) & 0xff;
808 p[3] = (u_char)(v >> 32) & 0xff;
809 p[4] = (u_char)(v >> 24) & 0xff;
810 p[5] = (u_char)(v >> 16) & 0xff;
811 p[6] = (u_char)(v >> 8) & 0xff;
812 p[7] = (u_char)v & 0xff;
815 void
816 put_u32(void *vp, u_int32_t v)
818 u_char *p = (u_char *)vp;
820 p[0] = (u_char)(v >> 24) & 0xff;
821 p[1] = (u_char)(v >> 16) & 0xff;
822 p[2] = (u_char)(v >> 8) & 0xff;
823 p[3] = (u_char)v & 0xff;
827 void
828 put_u16(void *vp, u_int16_t v)
830 u_char *p = (u_char *)vp;
832 p[0] = (u_char)(v >> 8) & 0xff;
833 p[1] = (u_char)v & 0xff;
836 void
837 ms_subtract_diff(struct timeval *start, int *ms)
839 struct timeval diff, finish;
841 gettimeofday(&finish, NULL);
842 timersub(&finish, start, &diff);
843 *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
846 void
847 ms_to_timeval(struct timeval *tv, int ms)
849 if (ms < 0)
850 ms = 0;
851 tv->tv_sec = ms / 1000;
852 tv->tv_usec = (ms % 1000) * 1000;
855 void
856 bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
858 bw->buflen = buflen;
859 bw->rate = kbps;
860 bw->thresh = bw->rate;
861 bw->lamt = 0;
862 timerclear(&bw->bwstart);
863 timerclear(&bw->bwend);
866 /* Callback from read/write loop to insert bandwidth-limiting delays */
867 void
868 bandwidth_limit(struct bwlimit *bw, size_t read_len)
870 u_int64_t waitlen;
871 struct timespec ts, rm;
873 if (!timerisset(&bw->bwstart)) {
874 gettimeofday(&bw->bwstart, NULL);
875 return;
878 bw->lamt += read_len;
879 if (bw->lamt < bw->thresh)
880 return;
882 gettimeofday(&bw->bwend, NULL);
883 timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
884 if (!timerisset(&bw->bwend))
885 return;
887 bw->lamt *= 8;
888 waitlen = (double)1000000L * bw->lamt / bw->rate;
890 bw->bwstart.tv_sec = waitlen / 1000000L;
891 bw->bwstart.tv_usec = waitlen % 1000000L;
893 if (timercmp(&bw->bwstart, &bw->bwend, >)) {
894 timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
896 /* Adjust the wait time */
897 if (bw->bwend.tv_sec) {
898 bw->thresh /= 2;
899 if (bw->thresh < bw->buflen / 4)
900 bw->thresh = bw->buflen / 4;
901 } else if (bw->bwend.tv_usec < 10000) {
902 bw->thresh *= 2;
903 if (bw->thresh > bw->buflen * 8)
904 bw->thresh = bw->buflen * 8;
907 TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
908 while (nanosleep(&ts, &rm) == -1) {
909 if (errno != EINTR)
910 break;
911 ts = rm;
915 bw->lamt = 0;
916 gettimeofday(&bw->bwstart, NULL);
919 /* Make a template filename for mk[sd]temp() */
920 void
921 mktemp_proto(char *s, size_t len)
923 const char *tmpdir;
924 int r;
926 if ((tmpdir = getenv("TMPDIR")) != NULL) {
927 r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
928 if (r > 0 && (size_t)r < len)
929 return;
931 r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
932 if (r < 0 || (size_t)r >= len)
933 fatal("%s: template string too short", __func__);
936 static const struct {
937 const char *name;
938 int value;
939 } ipqos[] = {
940 { "af11", IPTOS_DSCP_AF11 },
941 { "af12", IPTOS_DSCP_AF12 },
942 { "af13", IPTOS_DSCP_AF13 },
943 { "af14", IPTOS_DSCP_AF21 },
944 { "af22", IPTOS_DSCP_AF22 },
945 { "af23", IPTOS_DSCP_AF23 },
946 { "af31", IPTOS_DSCP_AF31 },
947 { "af32", IPTOS_DSCP_AF32 },
948 { "af33", IPTOS_DSCP_AF33 },
949 { "af41", IPTOS_DSCP_AF41 },
950 { "af42", IPTOS_DSCP_AF42 },
951 { "af43", IPTOS_DSCP_AF43 },
952 { "cs0", IPTOS_DSCP_CS0 },
953 { "cs1", IPTOS_DSCP_CS1 },
954 { "cs2", IPTOS_DSCP_CS2 },
955 { "cs3", IPTOS_DSCP_CS3 },
956 { "cs4", IPTOS_DSCP_CS4 },
957 { "cs5", IPTOS_DSCP_CS5 },
958 { "cs6", IPTOS_DSCP_CS6 },
959 { "cs7", IPTOS_DSCP_CS7 },
960 { "ef", IPTOS_DSCP_EF },
961 { "lowdelay", IPTOS_LOWDELAY },
962 { "throughput", IPTOS_THROUGHPUT },
963 { "reliability", IPTOS_RELIABILITY },
964 { NULL, -1 }
968 parse_ipqos(const char *cp)
970 u_int i;
971 char *ep;
972 long val;
974 if (cp == NULL)
975 return -1;
976 for (i = 0; ipqos[i].name != NULL; i++) {
977 if (strcasecmp(cp, ipqos[i].name) == 0)
978 return ipqos[i].value;
980 /* Try parsing as an integer */
981 val = strtol(cp, &ep, 0);
982 if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
983 return -1;
984 return val;
987 void
988 sock_set_v6only(int s)
990 #ifdef IPV6_V6ONLY
991 int on = 1;
993 debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
994 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
995 error("setsockopt IPV6_V6ONLY: %s", strerror(errno));
996 #endif