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