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