1 /* $OpenBSD: misc.c,v 1.96 2015/01/16 06:40:12 deraadt 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/un.h>
33
34 #include <limits.h>
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 *
chop(char * s)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
set_nonblock(int fd)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
unset_nonblock(int fd)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 *
ssh_gai_strerror(int gaierr)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
set_nodelay(int fd)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 *
strdelim(char ** s)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 *
pwcopy(struct passwd * pw)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 = pw->pw_passwd ? xstrdup(pw->pw_passwd) : NULL;
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
a2port(const char * s)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
a2tun(const char * s,int * remote)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
convtime(const char * s)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 *
put_host_port(const char * host,u_short port)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 *
hpdelim(char ** cp)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 *
cleanhostname(char * host)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 *
colon(char * cp)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
addargs(arglist * args,char * fmt,...)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
replacearg(arglist * args,u_int which,char * fmt,...)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
freeargs(arglist * args)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 *
tilde_expand_filename(const char * filename,uid_t uid)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) >= PATH_MAX)
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 *
percent_expand(const char * string,...)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
read_keyfile_line(FILE * f,const char * filename,char * buf,size_t bufsz,u_long * lineno)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
tun_open(int tun,int mode)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
sanitise_stdfd(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 *
tohex(const void * vp,size_t l)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
get_u64(const void * vp)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
get_u32(const void * vp)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_int32_t
get_u32_le(const void * vp)793 get_u32_le(const void *vp)
794 {
795 const u_char *p = (const u_char *)vp;
796 u_int32_t v;
797
798 v = (u_int32_t)p[0];
799 v |= (u_int32_t)p[1] << 8;
800 v |= (u_int32_t)p[2] << 16;
801 v |= (u_int32_t)p[3] << 24;
802
803 return (v);
804 }
805
806 u_int16_t
get_u16(const void * vp)807 get_u16(const void *vp)
808 {
809 const u_char *p = (const u_char *)vp;
810 u_int16_t v;
811
812 v = (u_int16_t)p[0] << 8;
813 v |= (u_int16_t)p[1];
814
815 return (v);
816 }
817
818 void
put_u64(void * vp,u_int64_t v)819 put_u64(void *vp, u_int64_t v)
820 {
821 u_char *p = (u_char *)vp;
822
823 p[0] = (u_char)(v >> 56) & 0xff;
824 p[1] = (u_char)(v >> 48) & 0xff;
825 p[2] = (u_char)(v >> 40) & 0xff;
826 p[3] = (u_char)(v >> 32) & 0xff;
827 p[4] = (u_char)(v >> 24) & 0xff;
828 p[5] = (u_char)(v >> 16) & 0xff;
829 p[6] = (u_char)(v >> 8) & 0xff;
830 p[7] = (u_char)v & 0xff;
831 }
832
833 void
put_u32(void * vp,u_int32_t v)834 put_u32(void *vp, u_int32_t v)
835 {
836 u_char *p = (u_char *)vp;
837
838 p[0] = (u_char)(v >> 24) & 0xff;
839 p[1] = (u_char)(v >> 16) & 0xff;
840 p[2] = (u_char)(v >> 8) & 0xff;
841 p[3] = (u_char)v & 0xff;
842 }
843
844 void
put_u32_le(void * vp,u_int32_t v)845 put_u32_le(void *vp, u_int32_t v)
846 {
847 u_char *p = (u_char *)vp;
848
849 p[0] = (u_char)v & 0xff;
850 p[1] = (u_char)(v >> 8) & 0xff;
851 p[2] = (u_char)(v >> 16) & 0xff;
852 p[3] = (u_char)(v >> 24) & 0xff;
853 }
854
855 void
put_u16(void * vp,u_int16_t v)856 put_u16(void *vp, u_int16_t v)
857 {
858 u_char *p = (u_char *)vp;
859
860 p[0] = (u_char)(v >> 8) & 0xff;
861 p[1] = (u_char)v & 0xff;
862 }
863
864 void
ms_subtract_diff(struct timeval * start,int * ms)865 ms_subtract_diff(struct timeval *start, int *ms)
866 {
867 struct timeval diff, finish;
868
869 gettimeofday(&finish, NULL);
870 timersub(&finish, start, &diff);
871 *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
872 }
873
874 void
ms_to_timeval(struct timeval * tv,int ms)875 ms_to_timeval(struct timeval *tv, int ms)
876 {
877 if (ms < 0)
878 ms = 0;
879 tv->tv_sec = ms / 1000;
880 tv->tv_usec = (ms % 1000) * 1000;
881 }
882
883 time_t
monotime(void)884 monotime(void)
885 {
886 #if defined(HAVE_CLOCK_GETTIME) && \
887 (defined(CLOCK_MONOTONIC) || defined(CLOCK_BOOTTIME))
888 struct timespec ts;
889 static int gettime_failed = 0;
890
891 if (!gettime_failed) {
892 #if defined(CLOCK_BOOTTIME)
893 if (clock_gettime(CLOCK_BOOTTIME, &ts) == 0)
894 return (ts.tv_sec);
895 #endif
896 #if defined(CLOCK_MONOTONIC)
897 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
898 return (ts.tv_sec);
899 #endif
900 debug3("clock_gettime: %s", strerror(errno));
901 gettime_failed = 1;
902 }
903 #endif /* HAVE_CLOCK_GETTIME && (CLOCK_MONOTONIC || CLOCK_BOOTTIME */
904
905 return time(NULL);
906 }
907
908 void
bandwidth_limit_init(struct bwlimit * bw,u_int64_t kbps,size_t buflen)909 bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
910 {
911 bw->buflen = buflen;
912 bw->rate = kbps;
913 bw->thresh = bw->rate;
914 bw->lamt = 0;
915 timerclear(&bw->bwstart);
916 timerclear(&bw->bwend);
917 }
918
919 /* Callback from read/write loop to insert bandwidth-limiting delays */
920 void
bandwidth_limit(struct bwlimit * bw,size_t read_len)921 bandwidth_limit(struct bwlimit *bw, size_t read_len)
922 {
923 u_int64_t waitlen;
924 struct timespec ts, rm;
925
926 if (!timerisset(&bw->bwstart)) {
927 gettimeofday(&bw->bwstart, NULL);
928 return;
929 }
930
931 bw->lamt += read_len;
932 if (bw->lamt < bw->thresh)
933 return;
934
935 gettimeofday(&bw->bwend, NULL);
936 timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
937 if (!timerisset(&bw->bwend))
938 return;
939
940 bw->lamt *= 8;
941 waitlen = (double)1000000L * bw->lamt / bw->rate;
942
943 bw->bwstart.tv_sec = waitlen / 1000000L;
944 bw->bwstart.tv_usec = waitlen % 1000000L;
945
946 if (timercmp(&bw->bwstart, &bw->bwend, >)) {
947 timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
948
949 /* Adjust the wait time */
950 if (bw->bwend.tv_sec) {
951 bw->thresh /= 2;
952 if (bw->thresh < bw->buflen / 4)
953 bw->thresh = bw->buflen / 4;
954 } else if (bw->bwend.tv_usec < 10000) {
955 bw->thresh *= 2;
956 if (bw->thresh > bw->buflen * 8)
957 bw->thresh = bw->buflen * 8;
958 }
959
960 TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
961 while (nanosleep(&ts, &rm) == -1) {
962 if (errno != EINTR)
963 break;
964 ts = rm;
965 }
966 }
967
968 bw->lamt = 0;
969 gettimeofday(&bw->bwstart, NULL);
970 }
971
972 /* Make a template filename for mk[sd]temp() */
973 void
mktemp_proto(char * s,size_t len)974 mktemp_proto(char *s, size_t len)
975 {
976 const char *tmpdir;
977 int r;
978
979 if ((tmpdir = getenv("TMPDIR")) != NULL) {
980 r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
981 if (r > 0 && (size_t)r < len)
982 return;
983 }
984 r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
985 if (r < 0 || (size_t)r >= len)
986 fatal("%s: template string too short", __func__);
987 }
988
989 static const struct {
990 const char *name;
991 int value;
992 } ipqos[] = {
993 { "af11", IPTOS_DSCP_AF11 },
994 { "af12", IPTOS_DSCP_AF12 },
995 { "af13", IPTOS_DSCP_AF13 },
996 { "af21", IPTOS_DSCP_AF21 },
997 { "af22", IPTOS_DSCP_AF22 },
998 { "af23", IPTOS_DSCP_AF23 },
999 { "af31", IPTOS_DSCP_AF31 },
1000 { "af32", IPTOS_DSCP_AF32 },
1001 { "af33", IPTOS_DSCP_AF33 },
1002 { "af41", IPTOS_DSCP_AF41 },
1003 { "af42", IPTOS_DSCP_AF42 },
1004 { "af43", IPTOS_DSCP_AF43 },
1005 { "cs0", IPTOS_DSCP_CS0 },
1006 { "cs1", IPTOS_DSCP_CS1 },
1007 { "cs2", IPTOS_DSCP_CS2 },
1008 { "cs3", IPTOS_DSCP_CS3 },
1009 { "cs4", IPTOS_DSCP_CS4 },
1010 { "cs5", IPTOS_DSCP_CS5 },
1011 { "cs6", IPTOS_DSCP_CS6 },
1012 { "cs7", IPTOS_DSCP_CS7 },
1013 { "ef", IPTOS_DSCP_EF },
1014 { "lowdelay", IPTOS_LOWDELAY },
1015 { "throughput", IPTOS_THROUGHPUT },
1016 { "reliability", IPTOS_RELIABILITY },
1017 { NULL, -1 }
1018 };
1019
1020 int
parse_ipqos(const char * cp)1021 parse_ipqos(const char *cp)
1022 {
1023 u_int i;
1024 char *ep;
1025 long val;
1026
1027 if (cp == NULL)
1028 return -1;
1029 for (i = 0; ipqos[i].name != NULL; i++) {
1030 if (strcasecmp(cp, ipqos[i].name) == 0)
1031 return ipqos[i].value;
1032 }
1033 /* Try parsing as an integer */
1034 val = strtol(cp, &ep, 0);
1035 if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1036 return -1;
1037 return val;
1038 }
1039
1040 const char *
iptos2str(int iptos)1041 iptos2str(int iptos)
1042 {
1043 int i;
1044 static char iptos_str[sizeof "0xff"];
1045
1046 for (i = 0; ipqos[i].name != NULL; i++) {
1047 if (ipqos[i].value == iptos)
1048 return ipqos[i].name;
1049 }
1050 snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1051 return iptos_str;
1052 }
1053
1054 void
lowercase(char * s)1055 lowercase(char *s)
1056 {
1057 for (; *s; s++)
1058 *s = tolower((u_char)*s);
1059 }
1060
1061 int
unix_listener(const char * path,int backlog,int unlink_first)1062 unix_listener(const char *path, int backlog, int unlink_first)
1063 {
1064 struct sockaddr_un sunaddr;
1065 int saved_errno, sock;
1066
1067 memset(&sunaddr, 0, sizeof(sunaddr));
1068 sunaddr.sun_family = AF_UNIX;
1069 if (strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1070 error("%s: \"%s\" too long for Unix domain socket", __func__,
1071 path);
1072 errno = ENAMETOOLONG;
1073 return -1;
1074 }
1075
1076 sock = socket(PF_UNIX, SOCK_STREAM, 0);
1077 if (sock < 0) {
1078 saved_errno = errno;
1079 error("socket: %.100s", strerror(errno));
1080 errno = saved_errno;
1081 return -1;
1082 }
1083 if (unlink_first == 1) {
1084 if (unlink(path) != 0 && errno != ENOENT)
1085 error("unlink(%s): %.100s", path, strerror(errno));
1086 }
1087 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0) {
1088 saved_errno = errno;
1089 error("bind: %.100s", strerror(errno));
1090 close(sock);
1091 error("%s: cannot bind to path: %s", __func__, path);
1092 errno = saved_errno;
1093 return -1;
1094 }
1095 if (listen(sock, backlog) < 0) {
1096 saved_errno = errno;
1097 error("listen: %.100s", strerror(errno));
1098 close(sock);
1099 unlink(path);
1100 error("%s: cannot listen on path: %s", __func__, path);
1101 errno = saved_errno;
1102 return -1;
1103 }
1104 return sock;
1105 }
1106
1107 void
sock_set_v6only(int s)1108 sock_set_v6only(int s)
1109 {
1110 #ifdef IPV6_V6ONLY
1111 int on = 1;
1112
1113 debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
1114 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
1115 error("setsockopt IPV6_V6ONLY: %s", strerror(errno));
1116 #endif
1117 }
1118