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