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 /* Characters considered as quotations. */
126 /* return next token in configuration line */
138 if ((q=strchr(QUOTES, (int) *old)) && *q)
140 /* find next quote character, point old to start of quoted
142 for (p = ++old;*p && *p!=*q; p++)
145 /* find start of next token */
146 *s = (*p) ? p + strspn(p + 1, WHITESPACE) + 1 : NULL;
148 /* terminate 'old' token */
153 *s = strpbrk(*s, WHITESPACE "=");
157 /* Allow only one '=' to be skipped */
162 *s += strspn(*s + 1, WHITESPACE) + 1;
163 if (*s[0] == '=' && !wspace)
164 *s += strspn(*s + 1, WHITESPACE) + 1;
170 pwcopy(struct passwd *pw)
172 struct passwd *copy = xmalloc(sizeof(*copy));
174 memset(copy, 0, sizeof(*copy));
175 copy->pw_name = xstrdup(pw->pw_name);
176 copy->pw_passwd = xstrdup(pw->pw_passwd);
177 copy->pw_gecos = xstrdup(pw->pw_gecos);
178 copy->pw_uid = pw->pw_uid;
179 copy->pw_gid = pw->pw_gid;
180 #ifdef HAVE_PW_EXPIRE_IN_PASSWD
181 copy->pw_expire = pw->pw_expire;
183 #ifdef HAVE_PW_CHANGE_IN_PASSWD
184 copy->pw_change = pw->pw_change;
186 #ifdef HAVE_PW_CLASS_IN_PASSWD
187 copy->pw_class = xstrdup(pw->pw_class);
189 copy->pw_dir = xstrdup(pw->pw_dir);
190 copy->pw_shell = xstrdup(pw->pw_shell);
195 * Convert ASCII string to TCP/IP port number.
196 * Port must be >0 and <=65535.
197 * Return 0 if invalid.
200 a2port(const char *s)
206 port = strtol(s, &endp, 0);
207 if (s == endp || *endp != '\0' ||
208 (errno == ERANGE && (port == LONG_MIN || port == LONG_MAX)) ||
209 port <= 0 || port > 65535)
216 #define MINUTES (SECONDS * 60)
217 #define HOURS (MINUTES * 60)
218 #define DAYS (HOURS * 24)
219 #define WEEKS (DAYS * 7)
222 * Convert a time string into seconds; format is
226 * Valid time qualifiers are:
240 * Return -1 if time string is invalid.
243 convtime(const char *s)
253 if (p == NULL || *p == '\0')
257 secs = strtol(p, &endp, 10);
259 (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
298 * Search for next delimiter between hostnames/addresses and ports.
299 * Argument may be modified (for termination).
300 * Returns *cp if parsing succeeds.
301 * *cp is set to the start of the next delimiter, if one was found.
302 * If this is the last field, *cp is set to NULL.
309 if (cp == NULL || *cp == NULL)
314 if ((s = strchr(s, ']')) == NULL)
318 } else if ((s = strpbrk(s, ":/")) == NULL)
319 s = *cp + strlen(*cp); /* skip to end (see first case below) */
323 *cp = NULL; /* no more fields*/
328 *s = '\0'; /* terminate */
340 cleanhostname(char *host)
342 if (*host == '[' && host[strlen(host) - 1] == ']') {
343 host[strlen(host) - 1] = '\0';
354 if (*cp == ':') /* Leading colon is part of file name. */
360 if (*cp == '@' && *(cp+1) == '[')
362 if (*cp == ']' && *(cp+1) == ':' && flag)
364 if (*cp == ':' && !flag)
372 /* function to assist building execv() arguments */
374 addargs(arglist *args, char *fmt, ...)
381 vsnprintf(buf, sizeof(buf), fmt, ap);
384 nalloc = args->nalloc;
385 if (args->list == NULL) {
388 } else if (args->num+2 >= nalloc)
391 args->list = xrealloc(args->list, nalloc * sizeof(char *));
392 args->nalloc = nalloc;
393 args->list[args->num++] = xstrdup(buf);
394 args->list[args->num] = NULL;
398 * Expands tildes in the file name. Returns data allocated by xmalloc.
399 * Warning: this calls getpw*.
402 tilde_expand_filename(const char *filename, uid_t uid)
405 char user[128], ret[MAXPATHLEN];
409 if (*filename != '~')
410 return (xstrdup(filename));
413 path = strchr(filename, '/');
414 if (path != NULL && path > filename) { /* ~user/path */
415 slash = path - filename;
416 if (slash > sizeof(user) - 1)
417 fatal("tilde_expand_filename: ~username too long");
418 memcpy(user, filename, slash);
420 if ((pw = getpwnam(user)) == NULL)
421 fatal("tilde_expand_filename: No such user %s", user);
422 } else if ((pw = getpwuid(uid)) == NULL) /* ~/path */
423 fatal("tilde_expand_filename: No such uid %d", uid);
425 if (strlcpy(ret, pw->pw_dir, sizeof(ret)) >= sizeof(ret))
426 fatal("tilde_expand_filename: Path too long");
428 /* Make sure directory has a trailing '/' */
429 len = strlen(pw->pw_dir);
430 if ((len == 0 || pw->pw_dir[len - 1] != '/') &&
431 strlcat(ret, "/", sizeof(ret)) >= sizeof(ret))
432 fatal("tilde_expand_filename: Path too long");
434 /* Skip leading '/' from specified path */
437 if (strlcat(ret, filename, sizeof(ret)) >= sizeof(ret))
438 fatal("tilde_expand_filename: Path too long");
440 return (xstrdup(ret));
444 * Expand a string with a set of %[char] escapes. A number of escapes may be
445 * specified as (char *escape_chars, char *replacement) pairs. The list must
446 * be terminated by a NULL escape_char. Returns replaced string in memory
447 * allocated by xmalloc.
450 percent_expand(const char *string, ...)
452 #define EXPAND_MAX_KEYS 16
456 } keys[EXPAND_MAX_KEYS];
457 u_int num_keys, i, j;
462 va_start(ap, string);
463 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
464 keys[num_keys].key = va_arg(ap, char *);
465 if (keys[num_keys].key == NULL)
467 keys[num_keys].repl = va_arg(ap, char *);
468 if (keys[num_keys].repl == NULL)
469 fatal("percent_expand: NULL replacement");
473 if (num_keys >= EXPAND_MAX_KEYS)
474 fatal("percent_expand: too many keys");
478 for (i = 0; *string != '\0'; string++) {
479 if (*string != '%') {
482 if (i >= sizeof(buf))
483 fatal("percent_expand: string too long");
490 for (j = 0; j < num_keys; j++) {
491 if (strchr(keys[j].key, *string) != NULL) {
492 i = strlcat(buf, keys[j].repl, sizeof(buf));
493 if (i >= sizeof(buf))
494 fatal("percent_expand: string too long");
499 fatal("percent_expand: unknown key %%%c", *string);
501 return (xstrdup(buf));
502 #undef EXPAND_MAX_KEYS
506 * Read an entire line from a public key file into a static buffer, discarding
507 * lines that exceed the buffer size. Returns 0 on success, -1 on failure.
510 read_keyfile_line(FILE *f, const char *filename, char *buf, size_t bufsz,
513 while (fgets(buf, bufsz, f) != NULL) {
515 if (buf[strlen(buf) - 1] == '\n' || feof(f)) {
518 debug("%s: %s line %lu exceeds size limit", __func__,
520 /* discard remainder of line */
521 while (fgetc(f) != '\n' && !feof(f))
529 tohex(const u_char *d, u_int l)
537 for (i = 0; i < l; i++) {
538 snprintf(b, sizeof(b), "%02x", d[i]);