update version
[openssh.git] / misc.c
1 /* $OpenBSD: misc.c,v 1.85 2011/03/29 18:54:17 stevesk 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 void
228 pwfree(struct passwd *pw)
229 {
230         xfree(pw->pw_name);
231         xfree(pw->pw_passwd);
232         xfree(pw->pw_gecos);
233 #ifdef HAVE_PW_CLASS_IN_PASSWD
234         xfree(pw->pw_class);
235 #endif
236         xfree(pw->pw_dir);
237         xfree(pw->pw_shell);
238         xfree(pw);
239 }
240
241 /*
242  * Convert ASCII string to TCP/IP port number.
243  * Port must be >=0 and <=65535.
244  * Return -1 if invalid.
245  */
246 int
247 a2port(const char *s)
248 {
249         long long port;
250         const char *errstr;
251
252         port = strtonum(s, 0, 65535, &errstr);
253         if (errstr != NULL)
254                 return -1;
255         return (int)port;
256 }
257
258 int
259 a2tun(const char *s, int *remote)
260 {
261         const char *errstr = NULL;
262         char *sp, *ep;
263         int tun;
264
265         if (remote != NULL) {
266                 *remote = SSH_TUNID_ANY;
267                 sp = xstrdup(s);
268                 if ((ep = strchr(sp, ':')) == NULL) {
269                         xfree(sp);
270                         return (a2tun(s, NULL));
271                 }
272                 ep[0] = '\0'; ep++;
273                 *remote = a2tun(ep, NULL);
274                 tun = a2tun(sp, NULL);
275                 xfree(sp);
276                 return (*remote == SSH_TUNID_ERR ? *remote : tun);
277         }
278
279         if (strcasecmp(s, "any") == 0)
280                 return (SSH_TUNID_ANY);
281
282         tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
283         if (errstr != NULL)
284                 return (SSH_TUNID_ERR);
285
286         return (tun);
287 }
288
289 #define SECONDS         1
290 #define MINUTES         (SECONDS * 60)
291 #define HOURS           (MINUTES * 60)
292 #define DAYS            (HOURS * 24)
293 #define WEEKS           (DAYS * 7)
294
295 /*
296  * Convert a time string into seconds; format is
297  * a sequence of:
298  *      time[qualifier]
299  *
300  * Valid time qualifiers are:
301  *      <none>  seconds
302  *      s|S     seconds
303  *      m|M     minutes
304  *      h|H     hours
305  *      d|D     days
306  *      w|W     weeks
307  *
308  * Examples:
309  *      90m     90 minutes
310  *      1h30m   90 minutes
311  *      2d      2 days
312  *      1w      1 week
313  *
314  * Return -1 if time string is invalid.
315  */
316 long
317 convtime(const char *s)
318 {
319         long total, secs;
320         const char *p;
321         char *endp;
322
323         errno = 0;
324         total = 0;
325         p = s;
326
327         if (p == NULL || *p == '\0')
328                 return -1;
329
330         while (*p) {
331                 secs = strtol(p, &endp, 10);
332                 if (p == endp ||
333                     (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
334                     secs < 0)
335                         return -1;
336
337                 switch (*endp++) {
338                 case '\0':
339                         endp--;
340                         break;
341                 case 's':
342                 case 'S':
343                         break;
344                 case 'm':
345                 case 'M':
346                         secs *= MINUTES;
347                         break;
348                 case 'h':
349                 case 'H':
350                         secs *= HOURS;
351                         break;
352                 case 'd':
353                 case 'D':
354                         secs *= DAYS;
355                         break;
356                 case 'w':
357                 case 'W':
358                         secs *= WEEKS;
359                         break;
360                 default:
361                         return -1;
362                 }
363                 total += secs;
364                 if (total < 0)
365                         return -1;
366                 p = endp;
367         }
368
369         return total;
370 }
371
372 /*
373  * Returns a standardized host+port identifier string.
374  * Caller must free returned string.
375  */
376 char *
377 put_host_port(const char *host, u_short port)
378 {
379         char *hoststr;
380
381         if (port == 0 || port == SSH_DEFAULT_PORT)
382                 return(xstrdup(host));
383         if (asprintf(&hoststr, "[%s]:%d", host, (int)port) < 0)
384                 fatal("put_host_port: asprintf: %s", strerror(errno));
385         debug3("put_host_port: %s", hoststr);
386         return hoststr;
387 }
388
389 /*
390  * Search for next delimiter between hostnames/addresses and ports.
391  * Argument may be modified (for termination).
392  * Returns *cp if parsing succeeds.
393  * *cp is set to the start of the next delimiter, if one was found.
394  * If this is the last field, *cp is set to NULL.
395  */
396 char *
397 hpdelim(char **cp)
398 {
399         char *s, *old;
400
401         if (cp == NULL || *cp == NULL)
402                 return NULL;
403
404         old = s = *cp;
405         if (*s == '[') {
406                 if ((s = strchr(s, ']')) == NULL)
407                         return NULL;
408                 else
409                         s++;
410         } else if ((s = strpbrk(s, ":/")) == NULL)
411                 s = *cp + strlen(*cp); /* skip to end (see first case below) */
412
413         switch (*s) {
414         case '\0':
415                 *cp = NULL;     /* no more fields*/
416                 break;
417
418         case ':':
419         case '/':
420                 *s = '\0';      /* terminate */
421                 *cp = s + 1;
422                 break;
423
424         default:
425                 return NULL;
426         }
427
428         return old;
429 }
430
431 char *
432 cleanhostname(char *host)
433 {
434         if (*host == '[' && host[strlen(host) - 1] == ']') {
435                 host[strlen(host) - 1] = '\0';
436                 return (host + 1);
437         } else
438                 return host;
439 }
440
441 char *
442 colon(char *cp)
443 {
444         int flag = 0;
445
446         if (*cp == ':')         /* Leading colon is part of file name. */
447                 return NULL;
448         if (*cp == '[')
449                 flag = 1;
450
451         for (; *cp; ++cp) {
452                 if (*cp == '@' && *(cp+1) == '[')
453                         flag = 1;
454                 if (*cp == ']' && *(cp+1) == ':' && flag)
455                         return (cp+1);
456                 if (*cp == ':' && !flag)
457                         return (cp);
458                 if (*cp == '/')
459                         return NULL;
460         }
461         return NULL;
462 }
463
464 /* function to assist building execv() arguments */
465 void
466 addargs(arglist *args, char *fmt, ...)
467 {
468         va_list ap;
469         char *cp;
470         u_int nalloc;
471         int r;
472
473         va_start(ap, fmt);
474         r = vasprintf(&cp, fmt, ap);
475         va_end(ap);
476         if (r == -1)
477                 fatal("addargs: argument too long");
478
479         nalloc = args->nalloc;
480         if (args->list == NULL) {
481                 nalloc = 32;
482                 args->num = 0;
483         } else if (args->num+2 >= nalloc)
484                 nalloc *= 2;
485
486         args->list = xrealloc(args->list, nalloc, sizeof(char *));
487         args->nalloc = nalloc;
488         args->list[args->num++] = cp;
489         args->list[args->num] = NULL;
490 }
491
492 void
493 replacearg(arglist *args, u_int which, char *fmt, ...)
494 {
495         va_list ap;
496         char *cp;
497         int r;
498
499         va_start(ap, fmt);
500         r = vasprintf(&cp, fmt, ap);
501         va_end(ap);
502         if (r == -1)
503                 fatal("replacearg: argument too long");
504
505         if (which >= args->num)
506                 fatal("replacearg: tried to replace invalid arg %d >= %d",
507                     which, args->num);
508         xfree(args->list[which]);
509         args->list[which] = cp;
510 }
511
512 void
513 freeargs(arglist *args)
514 {
515         u_int i;
516
517         if (args->list != NULL) {
518                 for (i = 0; i < args->num; i++)
519                         xfree(args->list[i]);
520                 xfree(args->list);
521                 args->nalloc = args->num = 0;
522                 args->list = NULL;
523         }
524 }
525
526 /*
527  * Expands tildes in the file name.  Returns data allocated by xmalloc.
528  * Warning: this calls getpw*.
529  */
530 char *
531 tilde_expand_filename(const char *filename, uid_t uid)
532 {
533         const char *path;
534         char user[128], ret[MAXPATHLEN];
535         struct passwd *pw;
536         u_int len, slash;
537
538         if (*filename != '~')
539                 return (xstrdup(filename));
540         filename++;
541
542         path = strchr(filename, '/');
543         if (path != NULL && path > filename) {          /* ~user/path */
544                 slash = path - filename;
545                 if (slash > sizeof(user) - 1)
546                         fatal("tilde_expand_filename: ~username too long");
547                 memcpy(user, filename, slash);
548                 user[slash] = '\0';
549                 if ((pw = getpwnam(user)) == NULL)
550                         fatal("tilde_expand_filename: No such user %s", user);
551         } else if ((pw = getpwuid(uid)) == NULL)        /* ~/path */
552                 fatal("tilde_expand_filename: No such uid %ld", (long)uid);
553
554         if (strlcpy(ret, pw->pw_dir, sizeof(ret)) >= sizeof(ret))
555                 fatal("tilde_expand_filename: Path too long");
556
557         /* Make sure directory has a trailing '/' */
558         len = strlen(pw->pw_dir);
559         if ((len == 0 || pw->pw_dir[len - 1] != '/') &&
560             strlcat(ret, "/", sizeof(ret)) >= sizeof(ret))
561                 fatal("tilde_expand_filename: Path too long");
562
563         /* Skip leading '/' from specified path */
564         if (path != NULL)
565                 filename = path + 1;
566         if (strlcat(ret, filename, sizeof(ret)) >= sizeof(ret))
567                 fatal("tilde_expand_filename: Path too long");
568
569         return (xstrdup(ret));
570 }
571
572 /*
573  * Expand a string with a set of %[char] escapes. A number of escapes may be
574  * specified as (char *escape_chars, char *replacement) pairs. The list must
575  * be terminated by a NULL escape_char. Returns replaced string in memory
576  * allocated by xmalloc.
577  */
578 char *
579 percent_expand(const char *string, ...)
580 {
581 #define EXPAND_MAX_KEYS 16
582         u_int num_keys, i, j;
583         struct {
584                 const char *key;
585                 const char *repl;
586         } keys[EXPAND_MAX_KEYS];
587         char buf[4096];
588         va_list ap;
589
590         /* Gather keys */
591         va_start(ap, string);
592         for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
593                 keys[num_keys].key = va_arg(ap, char *);
594                 if (keys[num_keys].key == NULL)
595                         break;
596                 keys[num_keys].repl = va_arg(ap, char *);
597                 if (keys[num_keys].repl == NULL)
598                         fatal("%s: NULL replacement", __func__);
599         }
600         if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
601                 fatal("%s: too many keys", __func__);
602         va_end(ap);
603
604         /* Expand string */
605         *buf = '\0';
606         for (i = 0; *string != '\0'; string++) {
607                 if (*string != '%') {
608  append:
609                         buf[i++] = *string;
610                         if (i >= sizeof(buf))
611                                 fatal("%s: string too long", __func__);
612                         buf[i] = '\0';
613                         continue;
614                 }
615                 string++;
616                 /* %% case */
617                 if (*string == '%')
618                         goto append;
619                 for (j = 0; j < num_keys; j++) {
620                         if (strchr(keys[j].key, *string) != NULL) {
621                                 i = strlcat(buf, keys[j].repl, sizeof(buf));
622                                 if (i >= sizeof(buf))
623                                         fatal("%s: string too long", __func__);
624                                 break;
625                         }
626                 }
627                 if (j >= num_keys)
628                         fatal("%s: unknown key %%%c", __func__, *string);
629         }
630         return (xstrdup(buf));
631 #undef EXPAND_MAX_KEYS
632 }
633
634 /*
635  * Read an entire line from a public key file into a static buffer, discarding
636  * lines that exceed the buffer size.  Returns 0 on success, -1 on failure.
637  */
638 int
639 read_keyfile_line(FILE *f, const char *filename, char *buf, size_t bufsz,
640    u_long *lineno)
641 {
642         while (fgets(buf, bufsz, f) != NULL) {
643                 if (buf[0] == '\0')
644                         continue;
645                 (*lineno)++;
646                 if (buf[strlen(buf) - 1] == '\n' || feof(f)) {
647                         return 0;
648                 } else {
649                         debug("%s: %s line %lu exceeds size limit", __func__,
650                             filename, *lineno);
651                         /* discard remainder of line */
652                         while (fgetc(f) != '\n' && !feof(f))
653                                 ;       /* nothing */
654                 }
655         }
656         return -1;
657 }
658
659 int
660 secure_permissions(struct stat *st, uid_t uid)
661 {
662         if (st->st_uid != 0 && st->st_uid != uid)
663                 return 0;
664         if ((st->st_mode & 002) != 0)
665                 return 0;
666         if ((st->st_mode & 020) != 0) {
667                 /* If the file is group-writable, the group in question must
668                  * have exactly one member, namely the file's owner.
669                  * (Zero-member groups are typically used by setgid
670                  * binaries, and are unlikely to be suitable.)
671                  */
672                 struct passwd *pw;
673                 struct group *gr;
674                 int members = 0;
675
676                 gr = getgrgid(st->st_gid);
677                 if (!gr)
678                         return 0;
679
680                 /* Check primary group memberships. */
681                 while ((pw = getpwent()) != NULL) {
682                         if (pw->pw_gid == gr->gr_gid) {
683                                 ++members;
684                                 if (pw->pw_uid != uid)
685                                         return 0;
686                         }
687                 }
688                 endpwent();
689
690                 pw = getpwuid(st->st_uid);
691                 if (!pw)
692                         return 0;
693
694                 /* Check supplementary group memberships. */
695                 if (gr->gr_mem[0]) {
696                         ++members;
697                         if (strcmp(pw->pw_name, gr->gr_mem[0]) ||
698                             gr->gr_mem[1])
699                                 return 0;
700                 }
701
702                 if (!members)
703                         return 0;
704         }
705         return 1;
706 }
707
708 int
709 tun_open(int tun, int mode)
710 {
711 #if defined(CUSTOM_SYS_TUN_OPEN)
712         return (sys_tun_open(tun, mode));
713 #elif defined(SSH_TUN_OPENBSD)
714         struct ifreq ifr;
715         char name[100];
716         int fd = -1, sock;
717
718         /* Open the tunnel device */
719         if (tun <= SSH_TUNID_MAX) {
720                 snprintf(name, sizeof(name), "/dev/tun%d", tun);
721                 fd = open(name, O_RDWR);
722         } else if (tun == SSH_TUNID_ANY) {
723                 for (tun = 100; tun >= 0; tun--) {
724                         snprintf(name, sizeof(name), "/dev/tun%d", tun);
725                         if ((fd = open(name, O_RDWR)) >= 0)
726                                 break;
727                 }
728         } else {
729                 debug("%s: invalid tunnel %u", __func__, tun);
730                 return (-1);
731         }
732
733         if (fd < 0) {
734                 debug("%s: %s open failed: %s", __func__, name, strerror(errno));
735                 return (-1);
736         }
737
738         debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
739
740         /* Set the tunnel device operation mode */
741         snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "tun%d", tun);
742         if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
743                 goto failed;
744
745         if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1)
746                 goto failed;
747
748         /* Set interface mode */
749         ifr.ifr_flags &= ~IFF_UP;
750         if (mode == SSH_TUNMODE_ETHERNET)
751                 ifr.ifr_flags |= IFF_LINK0;
752         else
753                 ifr.ifr_flags &= ~IFF_LINK0;
754         if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1)
755                 goto failed;
756
757         /* Bring interface up */
758         ifr.ifr_flags |= IFF_UP;
759         if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1)
760                 goto failed;
761
762         close(sock);
763         return (fd);
764
765  failed:
766         if (fd >= 0)
767                 close(fd);
768         if (sock >= 0)
769                 close(sock);
770         debug("%s: failed to set %s mode %d: %s", __func__, name,
771             mode, strerror(errno));
772         return (-1);
773 #else
774         error("Tunnel interfaces are not supported on this platform");
775         return (-1);
776 #endif
777 }
778
779 void
780 sanitise_stdfd(void)
781 {
782         int nullfd, dupfd;
783
784         if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
785                 fprintf(stderr, "Couldn't open /dev/null: %s\n",
786                     strerror(errno));
787                 exit(1);
788         }
789         while (++dupfd <= 2) {
790                 /* Only clobber closed fds */
791                 if (fcntl(dupfd, F_GETFL, 0) >= 0)
792                         continue;
793                 if (dup2(nullfd, dupfd) == -1) {
794                         fprintf(stderr, "dup2: %s\n", strerror(errno));
795                         exit(1);
796                 }
797         }
798         if (nullfd > 2)
799                 close(nullfd);
800 }
801
802 char *
803 tohex(const void *vp, size_t l)
804 {
805         const u_char *p = (const u_char *)vp;
806         char b[3], *r;
807         size_t i, hl;
808
809         if (l > 65536)
810                 return xstrdup("tohex: length > 65536");
811
812         hl = l * 2 + 1;
813         r = xcalloc(1, hl);
814         for (i = 0; i < l; i++) {
815                 snprintf(b, sizeof(b), "%02x", p[i]);
816                 strlcat(r, b, hl);
817         }
818         return (r);
819 }
820
821 u_int64_t
822 get_u64(const void *vp)
823 {
824         const u_char *p = (const u_char *)vp;
825         u_int64_t v;
826
827         v  = (u_int64_t)p[0] << 56;
828         v |= (u_int64_t)p[1] << 48;
829         v |= (u_int64_t)p[2] << 40;
830         v |= (u_int64_t)p[3] << 32;
831         v |= (u_int64_t)p[4] << 24;
832         v |= (u_int64_t)p[5] << 16;
833         v |= (u_int64_t)p[6] << 8;
834         v |= (u_int64_t)p[7];
835
836         return (v);
837 }
838
839 u_int32_t
840 get_u32(const void *vp)
841 {
842         const u_char *p = (const u_char *)vp;
843         u_int32_t v;
844
845         v  = (u_int32_t)p[0] << 24;
846         v |= (u_int32_t)p[1] << 16;
847         v |= (u_int32_t)p[2] << 8;
848         v |= (u_int32_t)p[3];
849
850         return (v);
851 }
852
853 u_int16_t
854 get_u16(const void *vp)
855 {
856         const u_char *p = (const u_char *)vp;
857         u_int16_t v;
858
859         v  = (u_int16_t)p[0] << 8;
860         v |= (u_int16_t)p[1];
861
862         return (v);
863 }
864
865 void
866 put_u64(void *vp, u_int64_t v)
867 {
868         u_char *p = (u_char *)vp;
869
870         p[0] = (u_char)(v >> 56) & 0xff;
871         p[1] = (u_char)(v >> 48) & 0xff;
872         p[2] = (u_char)(v >> 40) & 0xff;
873         p[3] = (u_char)(v >> 32) & 0xff;
874         p[4] = (u_char)(v >> 24) & 0xff;
875         p[5] = (u_char)(v >> 16) & 0xff;
876         p[6] = (u_char)(v >> 8) & 0xff;
877         p[7] = (u_char)v & 0xff;
878 }
879
880 void
881 put_u32(void *vp, u_int32_t v)
882 {
883         u_char *p = (u_char *)vp;
884
885         p[0] = (u_char)(v >> 24) & 0xff;
886         p[1] = (u_char)(v >> 16) & 0xff;
887         p[2] = (u_char)(v >> 8) & 0xff;
888         p[3] = (u_char)v & 0xff;
889 }
890
891
892 void
893 put_u16(void *vp, u_int16_t v)
894 {
895         u_char *p = (u_char *)vp;
896
897         p[0] = (u_char)(v >> 8) & 0xff;
898         p[1] = (u_char)v & 0xff;
899 }
900
901 void
902 ms_subtract_diff(struct timeval *start, int *ms)
903 {
904         struct timeval diff, finish;
905
906         gettimeofday(&finish, NULL);
907         timersub(&finish, start, &diff);        
908         *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
909 }
910
911 void
912 ms_to_timeval(struct timeval *tv, int ms)
913 {
914         if (ms < 0)
915                 ms = 0;
916         tv->tv_sec = ms / 1000;
917         tv->tv_usec = (ms % 1000) * 1000;
918 }
919
920 void
921 bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
922 {
923         bw->buflen = buflen;
924         bw->rate = kbps;
925         bw->thresh = bw->rate;
926         bw->lamt = 0;
927         timerclear(&bw->bwstart);
928         timerclear(&bw->bwend);
929 }       
930
931 /* Callback from read/write loop to insert bandwidth-limiting delays */
932 void
933 bandwidth_limit(struct bwlimit *bw, size_t read_len)
934 {
935         u_int64_t waitlen;
936         struct timespec ts, rm;
937
938         if (!timerisset(&bw->bwstart)) {
939                 gettimeofday(&bw->bwstart, NULL);
940                 return;
941         }
942
943         bw->lamt += read_len;
944         if (bw->lamt < bw->thresh)
945                 return;
946
947         gettimeofday(&bw->bwend, NULL);
948         timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
949         if (!timerisset(&bw->bwend))
950                 return;
951
952         bw->lamt *= 8;
953         waitlen = (double)1000000L * bw->lamt / bw->rate;
954
955         bw->bwstart.tv_sec = waitlen / 1000000L;
956         bw->bwstart.tv_usec = waitlen % 1000000L;
957
958         if (timercmp(&bw->bwstart, &bw->bwend, >)) {
959                 timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
960
961                 /* Adjust the wait time */
962                 if (bw->bwend.tv_sec) {
963                         bw->thresh /= 2;
964                         if (bw->thresh < bw->buflen / 4)
965                                 bw->thresh = bw->buflen / 4;
966                 } else if (bw->bwend.tv_usec < 10000) {
967                         bw->thresh *= 2;
968                         if (bw->thresh > bw->buflen * 8)
969                                 bw->thresh = bw->buflen * 8;
970                 }
971
972                 TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
973                 while (nanosleep(&ts, &rm) == -1) {
974                         if (errno != EINTR)
975                                 break;
976                         ts = rm;
977                 }
978         }
979
980         bw->lamt = 0;
981         gettimeofday(&bw->bwstart, NULL);
982 }
983
984 /* Make a template filename for mk[sd]temp() */
985 void
986 mktemp_proto(char *s, size_t len)
987 {
988         const char *tmpdir;
989         int r;
990
991         if ((tmpdir = getenv("TMPDIR")) != NULL) {
992                 r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
993                 if (r > 0 && (size_t)r < len)
994                         return;
995         }
996         r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
997         if (r < 0 || (size_t)r >= len)
998                 fatal("%s: template string too short", __func__);
999 }
1000
1001 static const struct {
1002         const char *name;
1003         int value;
1004 } ipqos[] = {
1005         { "af11", IPTOS_DSCP_AF11 },
1006         { "af12", IPTOS_DSCP_AF12 },
1007         { "af13", IPTOS_DSCP_AF13 },
1008         { "af14", IPTOS_DSCP_AF21 },
1009         { "af22", IPTOS_DSCP_AF22 },
1010         { "af23", IPTOS_DSCP_AF23 },
1011         { "af31", IPTOS_DSCP_AF31 },
1012         { "af32", IPTOS_DSCP_AF32 },
1013         { "af33", IPTOS_DSCP_AF33 },
1014         { "af41", IPTOS_DSCP_AF41 },
1015         { "af42", IPTOS_DSCP_AF42 },
1016         { "af43", IPTOS_DSCP_AF43 },
1017         { "cs0", IPTOS_DSCP_CS0 },
1018         { "cs1", IPTOS_DSCP_CS1 },
1019         { "cs2", IPTOS_DSCP_CS2 },
1020         { "cs3", IPTOS_DSCP_CS3 },
1021         { "cs4", IPTOS_DSCP_CS4 },
1022         { "cs5", IPTOS_DSCP_CS5 },
1023         { "cs6", IPTOS_DSCP_CS6 },
1024         { "cs7", IPTOS_DSCP_CS7 },
1025         { "ef", IPTOS_DSCP_EF },
1026         { "lowdelay", IPTOS_LOWDELAY },
1027         { "throughput", IPTOS_THROUGHPUT },
1028         { "reliability", IPTOS_RELIABILITY },
1029         { NULL, -1 }
1030 };
1031
1032 int
1033 parse_ipqos(const char *cp)
1034 {
1035         u_int i;
1036         char *ep;
1037         long val;
1038
1039         if (cp == NULL)
1040                 return -1;
1041         for (i = 0; ipqos[i].name != NULL; i++) {
1042                 if (strcasecmp(cp, ipqos[i].name) == 0)
1043                         return ipqos[i].value;
1044         }
1045         /* Try parsing as an integer */
1046         val = strtol(cp, &ep, 0);
1047         if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1048                 return -1;
1049         return val;
1050 }
1051
1052 const char *
1053 iptos2str(int iptos)
1054 {
1055         int i;
1056         static char iptos_str[sizeof "0xff"];
1057
1058         for (i = 0; ipqos[i].name != NULL; i++) {
1059                 if (ipqos[i].value == iptos)
1060                         return ipqos[i].name;
1061         }
1062         snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1063         return iptos_str;
1064 }
1065 void
1066 sock_set_v6only(int s)
1067 {
1068 #ifdef IPV6_V6ONLY
1069         int on = 1;
1070
1071         debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
1072         if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
1073                 error("setsockopt IPV6_V6ONLY: %s", strerror(errno));
1074 #endif
1075 }