2 * Copyright (c) 2000 Markus Friedl. All rights reserved.
3 * Copyright (c) 2005 Damien Miller. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 RCSID("$OpenBSD: misc.c,v 1.34 2005/07/08 09:26:18 dtucker Exp $");
33 /* remove newline at end of string */
39 if (*t == '\n' || *t == '\r') {
49 /* set/unset filedescriptor to non-blocking */
55 val = fcntl(fd, F_GETFL, 0);
57 error("fcntl(%d, F_GETFL, 0): %s", fd, strerror(errno));
60 if (val & O_NONBLOCK) {
61 debug3("fd %d is O_NONBLOCK", fd);
64 debug2("fd %d setting O_NONBLOCK", fd);
66 if (fcntl(fd, F_SETFL, val) == -1) {
67 debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
75 unset_nonblock(int fd)
79 val = fcntl(fd, F_GETFL, 0);
81 error("fcntl(%d, F_GETFL, 0): %s", fd, strerror(errno));
84 if (!(val & O_NONBLOCK)) {
85 debug3("fd %d is not O_NONBLOCK", fd);
88 debug("fd %d clearing O_NONBLOCK", fd);
90 if (fcntl(fd, F_SETFL, val) == -1) {
91 debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
98 /* disable nagle on socket */
106 if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
107 debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
111 debug2("fd %d is TCP_NODELAY", fd);
115 debug2("fd %d setting TCP_NODELAY", fd);
116 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
117 error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
120 /* Characters considered whitespace in strsep calls. */
121 #define WHITESPACE " \t\r\n"
123 /* return next token in configuration line */
135 *s = strpbrk(*s, WHITESPACE "=");
139 /* Allow only one '=' to be skipped */
144 *s += strspn(*s + 1, WHITESPACE) + 1;
145 if (*s[0] == '=' && !wspace)
146 *s += strspn(*s + 1, WHITESPACE) + 1;
152 pwcopy(struct passwd *pw)
154 struct passwd *copy = xmalloc(sizeof(*copy));
156 memset(copy, 0, sizeof(*copy));
157 copy->pw_name = xstrdup(pw->pw_name);
158 copy->pw_passwd = xstrdup(pw->pw_passwd);
159 copy->pw_gecos = xstrdup(pw->pw_gecos);
160 copy->pw_uid = pw->pw_uid;
161 copy->pw_gid = pw->pw_gid;
162 #ifdef HAVE_PW_EXPIRE_IN_PASSWD
163 copy->pw_expire = pw->pw_expire;
165 #ifdef HAVE_PW_CHANGE_IN_PASSWD
166 copy->pw_change = pw->pw_change;
168 #ifdef HAVE_PW_CLASS_IN_PASSWD
169 copy->pw_class = xstrdup(pw->pw_class);
171 copy->pw_dir = xstrdup(pw->pw_dir);
172 copy->pw_shell = xstrdup(pw->pw_shell);
177 * Convert ASCII string to TCP/IP port number.
178 * Port must be >0 and <=65535.
179 * Return 0 if invalid.
182 a2port(const char *s)
188 port = strtol(s, &endp, 0);
189 if (s == endp || *endp != '\0' ||
190 (errno == ERANGE && (port == LONG_MIN || port == LONG_MAX)) ||
191 port <= 0 || port > 65535)
198 #define MINUTES (SECONDS * 60)
199 #define HOURS (MINUTES * 60)
200 #define DAYS (HOURS * 24)
201 #define WEEKS (DAYS * 7)
204 * Convert a time string into seconds; format is
208 * Valid time qualifiers are:
222 * Return -1 if time string is invalid.
225 convtime(const char *s)
235 if (p == NULL || *p == '\0')
239 secs = strtol(p, &endp, 10);
241 (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
280 * Search for next delimiter between hostnames/addresses and ports.
281 * Argument may be modified (for termination).
282 * Returns *cp if parsing succeeds.
283 * *cp is set to the start of the next delimiter, if one was found.
284 * If this is the last field, *cp is set to NULL.
291 if (cp == NULL || *cp == NULL)
296 if ((s = strchr(s, ']')) == NULL)
300 } else if ((s = strpbrk(s, ":/")) == NULL)
301 s = *cp + strlen(*cp); /* skip to end (see first case below) */
305 *cp = NULL; /* no more fields*/
310 *s = '\0'; /* terminate */
322 cleanhostname(char *host)
324 if (*host == '[' && host[strlen(host) - 1] == ']') {
325 host[strlen(host) - 1] = '\0';
336 if (*cp == ':') /* Leading colon is part of file name. */
342 if (*cp == '@' && *(cp+1) == '[')
344 if (*cp == ']' && *(cp+1) == ':' && flag)
346 if (*cp == ':' && !flag)
354 /* function to assist building execv() arguments */
356 addargs(arglist *args, char *fmt, ...)
363 vsnprintf(buf, sizeof(buf), fmt, ap);
366 nalloc = args->nalloc;
367 if (args->list == NULL) {
370 } else if (args->num+2 >= nalloc)
373 args->list = xrealloc(args->list, nalloc * sizeof(char *));
374 args->nalloc = nalloc;
375 args->list[args->num++] = xstrdup(buf);
376 args->list[args->num] = NULL;
380 * Expands tildes in the file name. Returns data allocated by xmalloc.
381 * Warning: this calls getpw*.
384 tilde_expand_filename(const char *filename, uid_t uid)
387 char user[128], ret[MAXPATHLEN];
391 if (*filename != '~')
392 return (xstrdup(filename));
395 path = strchr(filename, '/');
396 if (path != NULL && path > filename) { /* ~user/path */
397 slash = path - filename;
398 if (slash > sizeof(user) - 1)
399 fatal("tilde_expand_filename: ~username too long");
400 memcpy(user, filename, slash);
402 if ((pw = getpwnam(user)) == NULL)
403 fatal("tilde_expand_filename: No such user %s", user);
404 } else if ((pw = getpwuid(uid)) == NULL) /* ~/path */
405 fatal("tilde_expand_filename: No such uid %d", uid);
407 if (strlcpy(ret, pw->pw_dir, sizeof(ret)) >= sizeof(ret))
408 fatal("tilde_expand_filename: Path too long");
410 /* Make sure directory has a trailing '/' */
411 len = strlen(pw->pw_dir);
412 if ((len == 0 || pw->pw_dir[len - 1] != '/') &&
413 strlcat(ret, "/", sizeof(ret)) >= sizeof(ret))
414 fatal("tilde_expand_filename: Path too long");
416 /* Skip leading '/' from specified path */
419 if (strlcat(ret, filename, sizeof(ret)) >= sizeof(ret))
420 fatal("tilde_expand_filename: Path too long");
422 return (xstrdup(ret));
426 * Expand a string with a set of %[char] escapes. A number of escapes may be
427 * specified as (char *escape_chars, char *replacement) pairs. The list must
428 * be terminated by a NULL escape_char. Returns replaced string in memory
429 * allocated by xmalloc.
432 percent_expand(const char *string, ...)
434 #define EXPAND_MAX_KEYS 16
438 } keys[EXPAND_MAX_KEYS];
439 u_int num_keys, i, j;
444 va_start(ap, string);
445 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
446 keys[num_keys].key = va_arg(ap, char *);
447 if (keys[num_keys].key == NULL)
449 keys[num_keys].repl = va_arg(ap, char *);
450 if (keys[num_keys].repl == NULL)
451 fatal("percent_expand: NULL replacement");
455 if (num_keys >= EXPAND_MAX_KEYS)
456 fatal("percent_expand: too many keys");
460 for (i = 0; *string != '\0'; string++) {
461 if (*string != '%') {
464 if (i >= sizeof(buf))
465 fatal("percent_expand: string too long");
472 for (j = 0; j < num_keys; j++) {
473 if (strchr(keys[j].key, *string) != NULL) {
474 i = strlcat(buf, keys[j].repl, sizeof(buf));
475 if (i >= sizeof(buf))
476 fatal("percent_expand: string too long");
481 fatal("percent_expand: unknown key %%%c", *string);
483 return (xstrdup(buf));
484 #undef EXPAND_MAX_KEYS
488 * Read an entire line from a public key file into a static buffer, discarding
489 * lines that exceed the buffer size. Returns 0 on success, -1 on failure.
492 read_keyfile_line(FILE *f, const char *filename, char *buf, size_t bufsz,
495 while (fgets(buf, bufsz, f) != NULL) {
497 if (buf[strlen(buf) - 1] == '\n' || feof(f)) {
500 debug("%s: %s line %lu exceeds size limit", __func__,
502 /* discard remainder of line */
503 while (fgetc(f) != '\n' && !feof(f))
511 tohex(const u_char *d, u_int l)
519 for (i = 0; i < l; i++) {
520 snprintf(b, sizeof(b), "%02x", d[i]);