2 /* $OpenBSD: misc.c,v 1.71 2009/02/21 19:32:04 tobias Exp $ */
4 * Copyright (c) 2000 Markus Friedl. All rights reserved.
5 * Copyright (c) 2005,2006 Damien Miller. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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.
29 __RCSID("$NetBSD: misc.c,v 1.23 2009/02/16 20:53:54 christos Exp $");
30 #include <sys/types.h>
31 #include <sys/ioctl.h>
32 #include <sys/socket.h>
33 #include <sys/param.h>
36 #include <net/if_tun.h>
37 #include <netinet/in.h>
38 #include <netinet/tcp.h>
56 /* remove newline at end of string */
62 if (*t
== '\n' || *t
== '\r') {
72 /* set/unset filedescriptor to non-blocking */
78 val
= fcntl(fd
, F_GETFL
, 0);
80 error("fcntl(%d, F_GETFL, 0): %s", fd
, strerror(errno
));
83 if (val
& O_NONBLOCK
) {
84 debug3("fd %d is O_NONBLOCK", fd
);
87 debug2("fd %d setting O_NONBLOCK", fd
);
89 if (fcntl(fd
, F_SETFL
, val
) == -1) {
90 debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd
,
98 unset_nonblock(int fd
)
102 val
= fcntl(fd
, F_GETFL
, 0);
104 error("fcntl(%d, F_GETFL, 0): %s", fd
, strerror(errno
));
107 if (!(val
& O_NONBLOCK
)) {
108 debug3("fd %d is not O_NONBLOCK", fd
);
111 debug("fd %d clearing O_NONBLOCK", fd
);
113 if (fcntl(fd
, F_SETFL
, val
) == -1) {
114 debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
115 fd
, strerror(errno
));
122 ssh_gai_strerror(int gaierr
)
124 if (gaierr
== EAI_SYSTEM
)
125 return strerror(errno
);
126 return gai_strerror(gaierr
);
129 /* disable nagle on socket */
137 if (getsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, &opt
, &optlen
) == -1) {
138 debug("getsockopt TCP_NODELAY: %.100s", strerror(errno
));
142 debug2("fd %d is TCP_NODELAY", fd
);
146 debug2("fd %d setting TCP_NODELAY", fd
);
147 if (setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, &opt
, sizeof opt
) == -1)
148 error("setsockopt TCP_NODELAY: %.100s", strerror(errno
));
151 /* Characters considered whitespace in strsep calls. */
152 #define WHITESPACE " \t\r\n"
155 /* return next token in configuration line */
167 *s
= strpbrk(*s
, WHITESPACE QUOTE
"=");
172 memmove(*s
, *s
+ 1, strlen(*s
)); /* move nul too */
173 /* Find matching quote */
174 if ((*s
= strpbrk(*s
, QUOTE
)) == NULL
) {
175 return (NULL
); /* no matching quote */
182 /* Allow only one '=' to be skipped */
187 /* Skip any extra whitespace after first token */
188 *s
+= strspn(*s
+ 1, WHITESPACE
) + 1;
189 if (*s
[0] == '=' && !wspace
)
190 *s
+= strspn(*s
+ 1, WHITESPACE
) + 1;
196 pwcopy(struct passwd
*pw
)
198 struct passwd
*copy
= xcalloc(1, sizeof(*copy
));
200 copy
->pw_name
= xstrdup(pw
->pw_name
);
201 copy
->pw_passwd
= xstrdup(pw
->pw_passwd
);
202 copy
->pw_gecos
= xstrdup(pw
->pw_gecos
);
203 copy
->pw_uid
= pw
->pw_uid
;
204 copy
->pw_gid
= pw
->pw_gid
;
205 copy
->pw_expire
= pw
->pw_expire
;
206 copy
->pw_change
= pw
->pw_change
;
207 copy
->pw_class
= xstrdup(pw
->pw_class
);
208 copy
->pw_dir
= xstrdup(pw
->pw_dir
);
209 copy
->pw_shell
= xstrdup(pw
->pw_shell
);
214 * Convert ASCII string to TCP/IP port number.
215 * Port must be >=0 and <=65535.
216 * Return -1 if invalid.
219 a2port(const char *s
)
224 port
= strtonum(s
, 0, 65535, &errstr
);
231 a2tun(const char *s
, int *remote
)
233 const char *errstr
= NULL
;
237 if (remote
!= NULL
) {
238 *remote
= SSH_TUNID_ANY
;
240 if ((ep
= strchr(sp
, ':')) == NULL
) {
242 return (a2tun(s
, NULL
));
245 *remote
= a2tun(ep
, NULL
);
246 tun
= a2tun(sp
, NULL
);
248 return (*remote
== SSH_TUNID_ERR
? *remote
: tun
);
251 if (strcasecmp(s
, "any") == 0)
252 return (SSH_TUNID_ANY
);
254 tun
= strtonum(s
, 0, SSH_TUNID_MAX
, &errstr
);
256 return (SSH_TUNID_ERR
);
262 #define MINUTES (SECONDS * 60)
263 #define HOURS (MINUTES * 60)
264 #define DAYS (HOURS * 24)
265 #define WEEKS (DAYS * 7)
268 * Convert a time string into seconds; format is
272 * Valid time qualifiers are:
286 * Return -1 if time string is invalid.
289 convtime(const char *s
)
299 if (p
== NULL
|| *p
== '\0')
303 secs
= strtol(p
, &endp
, 10);
305 (errno
== ERANGE
&& (secs
== LONG_MIN
|| secs
== LONG_MAX
)) ||
345 * Returns a standardized host+port identifier string.
346 * Caller must free returned string.
349 put_host_port(const char *host
, u_short port
)
353 if (port
== 0 || port
== SSH_DEFAULT_PORT
)
354 return(xstrdup(host
));
355 if (asprintf(&hoststr
, "[%s]:%d", host
, (int)port
) < 0)
356 fatal("put_host_port: asprintf: %s", strerror(errno
));
357 debug3("put_host_port: %s", hoststr
);
362 * Search for next delimiter between hostnames/addresses and ports.
363 * Argument may be modified (for termination).
364 * Returns *cp if parsing succeeds.
365 * *cp is set to the start of the next delimiter, if one was found.
366 * If this is the last field, *cp is set to NULL.
373 if (cp
== NULL
|| *cp
== NULL
)
378 if ((s
= strchr(s
, ']')) == NULL
)
382 } else if ((s
= strpbrk(s
, ":/")) == NULL
)
383 s
= *cp
+ strlen(*cp
); /* skip to end (see first case below) */
387 *cp
= NULL
; /* no more fields*/
392 *s
= '\0'; /* terminate */
404 cleanhostname(char *host
)
406 if (*host
== '[' && host
[strlen(host
) - 1] == ']') {
407 host
[strlen(host
) - 1] = '\0';
418 if (*cp
== ':') /* Leading colon is part of file name. */
424 if (*cp
== '@' && *(cp
+1) == '[')
426 if (*cp
== ']' && *(cp
+1) == ':' && flag
)
428 if (*cp
== ':' && !flag
)
436 /* function to assist building execv() arguments */
438 addargs(arglist
*args
, char *fmt
, ...)
446 r
= vasprintf(&cp
, fmt
, ap
);
449 fatal("addargs: argument too long");
451 nalloc
= args
->nalloc
;
452 if (args
->list
== NULL
) {
455 } else if (args
->num
+2 >= nalloc
)
458 args
->list
= xrealloc(args
->list
, nalloc
, sizeof(char *));
459 args
->nalloc
= nalloc
;
460 args
->list
[args
->num
++] = cp
;
461 args
->list
[args
->num
] = NULL
;
465 replacearg(arglist
*args
, u_int which
, char *fmt
, ...)
472 r
= vasprintf(&cp
, fmt
, ap
);
475 fatal("replacearg: argument too long");
477 if (which
>= args
->num
)
478 fatal("replacearg: tried to replace invalid arg %d >= %d",
480 xfree(args
->list
[which
]);
481 args
->list
[which
] = cp
;
485 freeargs(arglist
*args
)
489 if (args
->list
!= NULL
) {
490 for (i
= 0; i
< args
->num
; i
++)
491 xfree(args
->list
[i
]);
493 args
->nalloc
= args
->num
= 0;
499 * Expands tildes in the file name. Returns data allocated by xmalloc.
500 * Warning: this calls getpw*.
503 tilde_expand_filename(const char *filename
, uid_t uid
)
505 const char *path
, *homedir
;
506 char user
[128], ret
[MAXPATHLEN
];
510 if (*filename
!= '~')
511 return (xstrdup(filename
));
514 path
= strchr(filename
, '/');
515 if (path
!= NULL
&& path
> filename
) { /* ~user/path */
516 slash
= path
- filename
;
517 if (slash
> sizeof(user
) - 1)
518 fatal("tilde_expand_filename: ~username too long");
519 memcpy(user
, filename
, slash
);
521 if ((pw
= getpwnam(user
)) == NULL
)
522 fatal("tilde_expand_filename: No such user %s", user
);
523 homedir
= pw
->pw_dir
;
525 if ((pw
= getpwuid(uid
)) == NULL
) /* ~/path */
526 fatal("tilde_expand_filename: No such uid %ld",
528 homedir
= pw
->pw_dir
;
531 if (strlcpy(ret
, homedir
, sizeof(ret
)) >= sizeof(ret
))
532 fatal("tilde_expand_filename: Path too long");
534 /* Make sure directory has a trailing '/' */
535 len
= strlen(homedir
);
536 if ((len
== 0 || homedir
[len
- 1] != '/') &&
537 strlcat(ret
, "/", sizeof(ret
)) >= sizeof(ret
))
538 fatal("tilde_expand_filename: Path too long");
540 /* Skip leading '/' from specified path */
543 if (strlcat(ret
, filename
, sizeof(ret
)) >= sizeof(ret
))
544 fatal("tilde_expand_filename: Path too long");
546 return (xstrdup(ret
));
550 * Expand a string with a set of %[char] escapes. A number of escapes may be
551 * specified as (char *escape_chars, char *replacement) pairs. The list must
552 * be terminated by a NULL escape_char. Returns replaced string in memory
553 * allocated by xmalloc.
556 percent_expand(const char *string
, ...)
558 #define EXPAND_MAX_KEYS 16
562 } keys
[EXPAND_MAX_KEYS
];
563 u_int num_keys
, i
, j
;
568 va_start(ap
, string
);
569 for (num_keys
= 0; num_keys
< EXPAND_MAX_KEYS
; num_keys
++) {
570 keys
[num_keys
].key
= va_arg(ap
, char *);
571 if (keys
[num_keys
].key
== NULL
)
573 keys
[num_keys
].repl
= va_arg(ap
, char *);
574 if (keys
[num_keys
].repl
== NULL
)
575 fatal("percent_expand: NULL replacement");
579 if (num_keys
>= EXPAND_MAX_KEYS
)
580 fatal("percent_expand: too many keys");
584 for (i
= 0; *string
!= '\0'; string
++) {
585 if (*string
!= '%') {
588 if (i
>= sizeof(buf
))
589 fatal("percent_expand: string too long");
596 for (j
= 0; j
< num_keys
; j
++) {
597 if (strchr(keys
[j
].key
, *string
) != NULL
) {
598 i
= strlcat(buf
, keys
[j
].repl
, sizeof(buf
));
599 if (i
>= sizeof(buf
))
600 fatal("percent_expand: string too long");
605 fatal("percent_expand: unknown key %%%c", *string
);
607 return (xstrdup(buf
));
608 #undef EXPAND_MAX_KEYS
612 * Read an entire line from a public key file into a static buffer, discarding
613 * lines that exceed the buffer size. Returns 0 on success, -1 on failure.
616 read_keyfile_line(FILE *f
, const char *filename
, char *buf
, size_t bufsz
,
619 while (fgets(buf
, bufsz
, f
) != NULL
) {
623 if (buf
[strlen(buf
) - 1] == '\n' || feof(f
)) {
626 debug("%s: %s line %lu exceeds size limit", __func__
,
628 /* discard remainder of line */
629 while (fgetc(f
) != '\n' && !feof(f
))
637 tun_open(int tun
, int mode
)
640 int fd
= -1, sock
, flag
;
641 const char *tunbase
= mode
== SSH_TUNMODE_ETHERNET
? "tap" : "tun";
643 /* Open the tunnel device */
644 if (tun
<= SSH_TUNID_MAX
) {
645 snprintf(ifr
.ifr_name
, sizeof(ifr
.ifr_name
),
646 "/dev/%s%d", tunbase
, tun
);
647 fd
= open(ifr
.ifr_name
, O_RDWR
);
648 } else if (tun
== SSH_TUNID_ANY
) {
649 for (tun
= 100; tun
>= 0; tun
--) {
650 snprintf(ifr
.ifr_name
, sizeof(ifr
.ifr_name
),
651 "/dev/%s%d", tunbase
, tun
);
652 if ((fd
= open(ifr
.ifr_name
, O_RDWR
)) >= 0)
656 debug("%s: invalid tunnel %u", __func__
, tun
);
661 debug("%s: %s open failed: %s", __func__
, ifr
.ifr_name
,
667 /* Turn on tunnel headers */
669 if (mode
!= SSH_TUNMODE_ETHERNET
&&
670 ioctl(fd
, TUNSIFHEAD
, &flag
) == -1) {
671 debug("%s: ioctl(%d, TUNSIFHEAD, 1): %s", __func__
, fd
,
677 debug("%s: %s mode %d fd %d", __func__
, ifr
.ifr_name
, mode
, fd
);
678 /* Set the tunnel device operation mode */
679 if ((sock
= socket(PF_UNIX
, SOCK_STREAM
, 0)) == -1)
682 if (ioctl(sock
, SIOCGIFFLAGS
, &ifr
) == -1)
686 /* Set interface mode */
687 ifr
.ifr_flags
&= ~IFF_UP
;
688 if (mode
== SSH_TUNMODE_ETHERNET
)
689 ifr
.ifr_flags
|= IFF_LINK0
;
691 ifr
.ifr_flags
&= ~IFF_LINK0
;
692 if (ioctl(sock
, SIOCSIFFLAGS
, &ifr
) == -1)
696 /* Bring interface up */
697 ifr
.ifr_flags
|= IFF_UP
;
698 if (ioctl(sock
, SIOCSIFFLAGS
, &ifr
) == -1)
709 debug("%s: failed to set %s mode %d: %s", __func__
, ifr
.ifr_name
,
710 mode
, strerror(errno
));
719 if ((nullfd
= dupfd
= open(_PATH_DEVNULL
, O_RDWR
)) == -1) {
720 fprintf(stderr
, "Couldn't open /dev/null: %s\n",
724 while (++dupfd
<= 2) {
725 /* Only clobber closed fds */
726 if (fcntl(dupfd
, F_GETFL
, 0) >= 0)
728 if (dup2(nullfd
, dupfd
) == -1) {
729 fprintf(stderr
, "dup2: %s\n", strerror(errno
));
738 tohex(const void *vp
, size_t l
)
740 const u_char
*p
= (const u_char
*)vp
;
745 return xstrdup("tohex: length > 65536");
749 for (i
= 0; i
< l
; i
++) {
750 snprintf(b
, sizeof(b
), "%02x", p
[i
]);
757 get_u64(const void *vp
)
759 const u_char
*p
= (const u_char
*)vp
;
762 v
= (u_int64_t
)p
[0] << 56;
763 v
|= (u_int64_t
)p
[1] << 48;
764 v
|= (u_int64_t
)p
[2] << 40;
765 v
|= (u_int64_t
)p
[3] << 32;
766 v
|= (u_int64_t
)p
[4] << 24;
767 v
|= (u_int64_t
)p
[5] << 16;
768 v
|= (u_int64_t
)p
[6] << 8;
769 v
|= (u_int64_t
)p
[7];
775 get_u32(const void *vp
)
777 const u_char
*p
= (const u_char
*)vp
;
780 v
= (u_int32_t
)p
[0] << 24;
781 v
|= (u_int32_t
)p
[1] << 16;
782 v
|= (u_int32_t
)p
[2] << 8;
783 v
|= (u_int32_t
)p
[3];
789 get_u16(const void *vp
)
791 const u_char
*p
= (const u_char
*)vp
;
794 v
= (u_int16_t
)p
[0] << 8;
795 v
|= (u_int16_t
)p
[1];
801 put_u64(void *vp
, u_int64_t v
)
803 u_char
*p
= (u_char
*)vp
;
805 p
[0] = (u_char
)(v
>> 56) & 0xff;
806 p
[1] = (u_char
)(v
>> 48) & 0xff;
807 p
[2] = (u_char
)(v
>> 40) & 0xff;
808 p
[3] = (u_char
)(v
>> 32) & 0xff;
809 p
[4] = (u_char
)(v
>> 24) & 0xff;
810 p
[5] = (u_char
)(v
>> 16) & 0xff;
811 p
[6] = (u_char
)(v
>> 8) & 0xff;
812 p
[7] = (u_char
)v
& 0xff;
816 put_u32(void *vp
, u_int32_t v
)
818 u_char
*p
= (u_char
*)vp
;
820 p
[0] = (u_char
)(v
>> 24) & 0xff;
821 p
[1] = (u_char
)(v
>> 16) & 0xff;
822 p
[2] = (u_char
)(v
>> 8) & 0xff;
823 p
[3] = (u_char
)v
& 0xff;
828 put_u16(void *vp
, u_int16_t v
)
830 u_char
*p
= (u_char
*)vp
;
832 p
[0] = (u_char
)(v
>> 8) & 0xff;
833 p
[1] = (u_char
)v
& 0xff;
837 ms_subtract_diff(struct timeval
*start
, int *ms
)
839 struct timeval diff
, finish
;
841 gettimeofday(&finish
, NULL
);
842 timersub(&finish
, start
, &diff
);
843 *ms
-= (diff
.tv_sec
* 1000) + (diff
.tv_usec
/ 1000);
847 ms_to_timeval(struct timeval
*tv
, int ms
)
851 tv
->tv_sec
= ms
/ 1000;
852 tv
->tv_usec
= (ms
% 1000) * 1000;