Annotation of src/usr.bin/ssh/misc.c, Revision 1.82
1.82 ! matthew 1: /* $OpenBSD: misc.c,v 1.81 2010/09/22 22:58:51 djm Exp $ */
1.1 markus 2: /*
3: * Copyright (c) 2000 Markus Friedl. All rights reserved.
1.52 djm 4: * Copyright (c) 2005,2006 Damien Miller. All rights reserved.
1.1 markus 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:
1.64 deraadt 27: #include <sys/types.h>
1.45 stevesk 28: #include <sys/ioctl.h>
1.53 stevesk 29: #include <sys/socket.h>
1.61 stevesk 30: #include <sys/param.h>
1.38 stevesk 31:
32: #include <net/if.h>
1.53 stevesk 33: #include <netinet/in.h>
1.44 stevesk 34: #include <netinet/tcp.h>
1.43 stevesk 35:
1.58 stevesk 36: #include <errno.h>
1.55 stevesk 37: #include <fcntl.h>
1.66 dtucker 38: #include <netdb.h>
1.43 stevesk 39: #include <paths.h>
1.54 stevesk 40: #include <pwd.h>
1.57 stevesk 41: #include <stdarg.h>
1.63 stevesk 42: #include <stdio.h>
1.62 stevesk 43: #include <stdlib.h>
1.60 stevesk 44: #include <string.h>
1.59 stevesk 45: #include <unistd.h>
1.1 markus 46:
1.64 deraadt 47: #include "xmalloc.h"
1.1 markus 48: #include "misc.h"
49: #include "log.h"
1.56 dtucker 50: #include "ssh.h"
1.1 markus 51:
1.12 markus 52: /* remove newline at end of string */
1.1 markus 53: char *
54: chop(char *s)
55: {
56: char *t = s;
57: while (*t) {
1.13 deraadt 58: if (*t == '\n' || *t == '\r') {
1.1 markus 59: *t = '\0';
60: return s;
61: }
62: t++;
63: }
64: return s;
65:
66: }
67:
1.12 markus 68: /* set/unset filedescriptor to non-blocking */
1.24 djm 69: int
1.1 markus 70: set_nonblock(int fd)
71: {
72: int val;
1.8 markus 73:
1.1 markus 74: val = fcntl(fd, F_GETFL, 0);
75: if (val < 0) {
76: error("fcntl(%d, F_GETFL, 0): %s", fd, strerror(errno));
1.24 djm 77: return (-1);
1.1 markus 78: }
79: if (val & O_NONBLOCK) {
1.24 djm 80: debug3("fd %d is O_NONBLOCK", fd);
81: return (0);
1.1 markus 82: }
1.21 markus 83: debug2("fd %d setting O_NONBLOCK", fd);
1.1 markus 84: val |= O_NONBLOCK;
1.24 djm 85: if (fcntl(fd, F_SETFL, val) == -1) {
86: debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
87: strerror(errno));
88: return (-1);
89: }
90: return (0);
1.8 markus 91: }
92:
1.24 djm 93: int
1.8 markus 94: unset_nonblock(int fd)
95: {
96: int val;
97:
98: val = fcntl(fd, F_GETFL, 0);
99: if (val < 0) {
100: error("fcntl(%d, F_GETFL, 0): %s", fd, strerror(errno));
1.24 djm 101: return (-1);
1.8 markus 102: }
103: if (!(val & O_NONBLOCK)) {
1.24 djm 104: debug3("fd %d is not O_NONBLOCK", fd);
105: return (0);
1.8 markus 106: }
1.10 markus 107: debug("fd %d clearing O_NONBLOCK", fd);
1.8 markus 108: val &= ~O_NONBLOCK;
1.24 djm 109: if (fcntl(fd, F_SETFL, val) == -1) {
110: debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
1.18 markus 111: fd, strerror(errno));
1.24 djm 112: return (-1);
113: }
114: return (0);
1.66 dtucker 115: }
116:
117: const char *
118: ssh_gai_strerror(int gaierr)
119: {
1.67 dtucker 120: if (gaierr == EAI_SYSTEM)
121: return strerror(errno);
122: return gai_strerror(gaierr);
1.15 stevesk 123: }
124:
125: /* disable nagle on socket */
126: void
127: set_nodelay(int fd)
128: {
1.17 stevesk 129: int opt;
130: socklen_t optlen;
1.15 stevesk 131:
1.16 stevesk 132: optlen = sizeof opt;
133: if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
1.23 markus 134: debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
1.16 stevesk 135: return;
136: }
137: if (opt == 1) {
138: debug2("fd %d is TCP_NODELAY", fd);
139: return;
140: }
141: opt = 1;
1.20 markus 142: debug2("fd %d setting TCP_NODELAY", fd);
1.16 stevesk 143: if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
1.15 stevesk 144: error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
1.72 reyk 145: }
146:
1.1 markus 147: /* Characters considered whitespace in strsep calls. */
148: #define WHITESPACE " \t\r\n"
1.46 dtucker 149: #define QUOTE "\""
1.1 markus 150:
1.12 markus 151: /* return next token in configuration line */
1.1 markus 152: char *
153: strdelim(char **s)
154: {
155: char *old;
156: int wspace = 0;
157:
158: if (*s == NULL)
159: return NULL;
160:
161: old = *s;
162:
1.46 dtucker 163: *s = strpbrk(*s, WHITESPACE QUOTE "=");
1.1 markus 164: if (*s == NULL)
165: return (old);
166:
1.46 dtucker 167: if (*s[0] == '\"') {
168: memmove(*s, *s + 1, strlen(*s)); /* move nul too */
169: /* Find matching quote */
170: if ((*s = strpbrk(*s, QUOTE)) == NULL) {
171: return (NULL); /* no matching quote */
172: } else {
173: *s[0] = '\0';
1.77 djm 174: *s += strspn(*s + 1, WHITESPACE) + 1;
1.46 dtucker 175: return (old);
176: }
177: }
178:
1.1 markus 179: /* Allow only one '=' to be skipped */
180: if (*s[0] == '=')
181: wspace = 1;
182: *s[0] = '\0';
183:
1.46 dtucker 184: /* Skip any extra whitespace after first token */
1.1 markus 185: *s += strspn(*s + 1, WHITESPACE) + 1;
186: if (*s[0] == '=' && !wspace)
187: *s += strspn(*s + 1, WHITESPACE) + 1;
188:
189: return (old);
1.2 markus 190: }
191:
192: struct passwd *
193: pwcopy(struct passwd *pw)
194: {
1.49 djm 195: struct passwd *copy = xcalloc(1, sizeof(*copy));
1.4 deraadt 196:
1.2 markus 197: copy->pw_name = xstrdup(pw->pw_name);
198: copy->pw_passwd = xstrdup(pw->pw_passwd);
1.4 deraadt 199: copy->pw_gecos = xstrdup(pw->pw_gecos);
1.2 markus 200: copy->pw_uid = pw->pw_uid;
201: copy->pw_gid = pw->pw_gid;
1.11 markus 202: copy->pw_expire = pw->pw_expire;
203: copy->pw_change = pw->pw_change;
1.2 markus 204: copy->pw_class = xstrdup(pw->pw_class);
205: copy->pw_dir = xstrdup(pw->pw_dir);
206: copy->pw_shell = xstrdup(pw->pw_shell);
207: return copy;
1.5 stevesk 208: }
209:
1.12 markus 210: /*
211: * Convert ASCII string to TCP/IP port number.
1.70 djm 212: * Port must be >=0 and <=65535.
213: * Return -1 if invalid.
1.12 markus 214: */
215: int
216: a2port(const char *s)
1.5 stevesk 217: {
1.70 djm 218: long long port;
219: const char *errstr;
1.5 stevesk 220:
1.70 djm 221: port = strtonum(s, 0, 65535, &errstr);
222: if (errstr != NULL)
223: return -1;
224: return (int)port;
1.9 stevesk 225: }
226:
1.36 reyk 227: int
228: a2tun(const char *s, int *remote)
229: {
230: const char *errstr = NULL;
231: char *sp, *ep;
232: int tun;
233:
234: if (remote != NULL) {
1.37 reyk 235: *remote = SSH_TUNID_ANY;
1.36 reyk 236: sp = xstrdup(s);
237: if ((ep = strchr(sp, ':')) == NULL) {
238: xfree(sp);
239: return (a2tun(s, NULL));
240: }
241: ep[0] = '\0'; ep++;
242: *remote = a2tun(ep, NULL);
243: tun = a2tun(sp, NULL);
244: xfree(sp);
1.37 reyk 245: return (*remote == SSH_TUNID_ERR ? *remote : tun);
1.36 reyk 246: }
247:
248: if (strcasecmp(s, "any") == 0)
1.37 reyk 249: return (SSH_TUNID_ANY);
1.36 reyk 250:
1.37 reyk 251: tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
252: if (errstr != NULL)
253: return (SSH_TUNID_ERR);
1.36 reyk 254:
255: return (tun);
256: }
257:
1.9 stevesk 258: #define SECONDS 1
259: #define MINUTES (SECONDS * 60)
260: #define HOURS (MINUTES * 60)
261: #define DAYS (HOURS * 24)
262: #define WEEKS (DAYS * 7)
263:
1.12 markus 264: /*
265: * Convert a time string into seconds; format is
266: * a sequence of:
267: * time[qualifier]
268: *
269: * Valid time qualifiers are:
270: * <none> seconds
271: * s|S seconds
272: * m|M minutes
273: * h|H hours
274: * d|D days
275: * w|W weeks
276: *
277: * Examples:
278: * 90m 90 minutes
279: * 1h30m 90 minutes
280: * 2d 2 days
281: * 1w 1 week
282: *
283: * Return -1 if time string is invalid.
284: */
285: long
286: convtime(const char *s)
1.9 stevesk 287: {
288: long total, secs;
289: const char *p;
290: char *endp;
291:
292: errno = 0;
293: total = 0;
294: p = s;
295:
296: if (p == NULL || *p == '\0')
297: return -1;
298:
299: while (*p) {
300: secs = strtol(p, &endp, 10);
301: if (p == endp ||
302: (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
303: secs < 0)
304: return -1;
305:
306: switch (*endp++) {
307: case '\0':
308: endp--;
1.48 deraadt 309: break;
1.9 stevesk 310: case 's':
311: case 'S':
312: break;
313: case 'm':
314: case 'M':
315: secs *= MINUTES;
316: break;
317: case 'h':
318: case 'H':
319: secs *= HOURS;
320: break;
321: case 'd':
322: case 'D':
323: secs *= DAYS;
324: break;
325: case 'w':
326: case 'W':
327: secs *= WEEKS;
328: break;
329: default:
330: return -1;
331: }
332: total += secs;
333: if (total < 0)
334: return -1;
335: p = endp;
336: }
337:
338: return total;
1.56 dtucker 339: }
340:
341: /*
342: * Returns a standardized host+port identifier string.
343: * Caller must free returned string.
344: */
345: char *
346: put_host_port(const char *host, u_short port)
347: {
348: char *hoststr;
349:
350: if (port == 0 || port == SSH_DEFAULT_PORT)
351: return(xstrdup(host));
352: if (asprintf(&hoststr, "[%s]:%d", host, (int)port) < 0)
353: fatal("put_host_port: asprintf: %s", strerror(errno));
354: debug3("put_host_port: %s", hoststr);
355: return hoststr;
1.28 djm 356: }
357:
358: /*
359: * Search for next delimiter between hostnames/addresses and ports.
360: * Argument may be modified (for termination).
361: * Returns *cp if parsing succeeds.
362: * *cp is set to the start of the next delimiter, if one was found.
363: * If this is the last field, *cp is set to NULL.
364: */
365: char *
366: hpdelim(char **cp)
367: {
368: char *s, *old;
369:
370: if (cp == NULL || *cp == NULL)
371: return NULL;
372:
373: old = s = *cp;
374: if (*s == '[') {
375: if ((s = strchr(s, ']')) == NULL)
376: return NULL;
377: else
378: s++;
379: } else if ((s = strpbrk(s, ":/")) == NULL)
380: s = *cp + strlen(*cp); /* skip to end (see first case below) */
381:
382: switch (*s) {
383: case '\0':
384: *cp = NULL; /* no more fields*/
385: break;
1.29 deraadt 386:
1.28 djm 387: case ':':
388: case '/':
389: *s = '\0'; /* terminate */
390: *cp = s + 1;
391: break;
1.29 deraadt 392:
1.28 djm 393: default:
394: return NULL;
395: }
396:
397: return old;
1.6 mouring 398: }
399:
400: char *
401: cleanhostname(char *host)
402: {
403: if (*host == '[' && host[strlen(host) - 1] == ']') {
404: host[strlen(host) - 1] = '\0';
405: return (host + 1);
406: } else
407: return host;
408: }
409:
410: char *
411: colon(char *cp)
412: {
413: int flag = 0;
414:
415: if (*cp == ':') /* Leading colon is part of file name. */
1.76 djm 416: return NULL;
1.6 mouring 417: if (*cp == '[')
418: flag = 1;
419:
420: for (; *cp; ++cp) {
421: if (*cp == '@' && *(cp+1) == '[')
422: flag = 1;
423: if (*cp == ']' && *(cp+1) == ':' && flag)
424: return (cp+1);
425: if (*cp == ':' && !flag)
426: return (cp);
427: if (*cp == '/')
1.76 djm 428: return NULL;
1.6 mouring 429: }
1.76 djm 430: return NULL;
1.7 mouring 431: }
432:
1.12 markus 433: /* function to assist building execv() arguments */
1.7 mouring 434: void
435: addargs(arglist *args, char *fmt, ...)
436: {
437: va_list ap;
1.42 djm 438: char *cp;
1.25 avsm 439: u_int nalloc;
1.42 djm 440: int r;
1.7 mouring 441:
442: va_start(ap, fmt);
1.42 djm 443: r = vasprintf(&cp, fmt, ap);
1.7 mouring 444: va_end(ap);
1.42 djm 445: if (r == -1)
446: fatal("addargs: argument too long");
1.7 mouring 447:
1.22 markus 448: nalloc = args->nalloc;
1.7 mouring 449: if (args->list == NULL) {
1.22 markus 450: nalloc = 32;
1.7 mouring 451: args->num = 0;
1.22 markus 452: } else if (args->num+2 >= nalloc)
453: nalloc *= 2;
1.7 mouring 454:
1.50 djm 455: args->list = xrealloc(args->list, nalloc, sizeof(char *));
1.22 markus 456: args->nalloc = nalloc;
1.42 djm 457: args->list[args->num++] = cp;
1.7 mouring 458: args->list[args->num] = NULL;
1.42 djm 459: }
460:
461: void
462: replacearg(arglist *args, u_int which, char *fmt, ...)
463: {
464: va_list ap;
465: char *cp;
466: int r;
467:
468: va_start(ap, fmt);
469: r = vasprintf(&cp, fmt, ap);
470: va_end(ap);
471: if (r == -1)
472: fatal("replacearg: argument too long");
473:
474: if (which >= args->num)
475: fatal("replacearg: tried to replace invalid arg %d >= %d",
476: which, args->num);
477: xfree(args->list[which]);
478: args->list[which] = cp;
479: }
480:
481: void
482: freeargs(arglist *args)
483: {
484: u_int i;
485:
486: if (args->list != NULL) {
487: for (i = 0; i < args->num; i++)
488: xfree(args->list[i]);
489: xfree(args->list);
490: args->nalloc = args->num = 0;
491: args->list = NULL;
492: }
1.30 djm 493: }
494:
495: /*
496: * Expands tildes in the file name. Returns data allocated by xmalloc.
497: * Warning: this calls getpw*.
498: */
499: char *
500: tilde_expand_filename(const char *filename, uid_t uid)
501: {
502: const char *path;
503: char user[128], ret[MAXPATHLEN];
504: struct passwd *pw;
1.32 djm 505: u_int len, slash;
1.30 djm 506:
507: if (*filename != '~')
508: return (xstrdup(filename));
509: filename++;
510:
511: path = strchr(filename, '/');
512: if (path != NULL && path > filename) { /* ~user/path */
1.32 djm 513: slash = path - filename;
514: if (slash > sizeof(user) - 1)
1.30 djm 515: fatal("tilde_expand_filename: ~username too long");
1.32 djm 516: memcpy(user, filename, slash);
517: user[slash] = '\0';
1.30 djm 518: if ((pw = getpwnam(user)) == NULL)
519: fatal("tilde_expand_filename: No such user %s", user);
520: } else if ((pw = getpwuid(uid)) == NULL) /* ~/path */
1.69 dtucker 521: fatal("tilde_expand_filename: No such uid %ld", (long)uid);
1.30 djm 522:
523: if (strlcpy(ret, pw->pw_dir, sizeof(ret)) >= sizeof(ret))
524: fatal("tilde_expand_filename: Path too long");
525:
526: /* Make sure directory has a trailing '/' */
527: len = strlen(pw->pw_dir);
528: if ((len == 0 || pw->pw_dir[len - 1] != '/') &&
529: strlcat(ret, "/", sizeof(ret)) >= sizeof(ret))
530: fatal("tilde_expand_filename: Path too long");
531:
532: /* Skip leading '/' from specified path */
533: if (path != NULL)
534: filename = path + 1;
535: if (strlcat(ret, filename, sizeof(ret)) >= sizeof(ret))
536: fatal("tilde_expand_filename: Path too long");
537:
538: return (xstrdup(ret));
1.31 djm 539: }
540:
541: /*
542: * Expand a string with a set of %[char] escapes. A number of escapes may be
543: * specified as (char *escape_chars, char *replacement) pairs. The list must
1.34 dtucker 544: * be terminated by a NULL escape_char. Returns replaced string in memory
1.31 djm 545: * allocated by xmalloc.
546: */
547: char *
548: percent_expand(const char *string, ...)
549: {
550: #define EXPAND_MAX_KEYS 16
1.73 djm 551: u_int num_keys, i, j;
1.31 djm 552: struct {
553: const char *key;
554: const char *repl;
555: } keys[EXPAND_MAX_KEYS];
556: char buf[4096];
557: va_list ap;
558:
559: /* Gather keys */
560: va_start(ap, string);
561: for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
562: keys[num_keys].key = va_arg(ap, char *);
563: if (keys[num_keys].key == NULL)
564: break;
565: keys[num_keys].repl = va_arg(ap, char *);
566: if (keys[num_keys].repl == NULL)
1.73 djm 567: fatal("%s: NULL replacement", __func__);
1.31 djm 568: }
1.73 djm 569: if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
570: fatal("%s: too many keys", __func__);
1.31 djm 571: va_end(ap);
572:
573: /* Expand string */
574: *buf = '\0';
575: for (i = 0; *string != '\0'; string++) {
576: if (*string != '%') {
577: append:
578: buf[i++] = *string;
579: if (i >= sizeof(buf))
1.73 djm 580: fatal("%s: string too long", __func__);
1.31 djm 581: buf[i] = '\0';
582: continue;
583: }
584: string++;
1.73 djm 585: /* %% case */
1.31 djm 586: if (*string == '%')
587: goto append;
588: for (j = 0; j < num_keys; j++) {
589: if (strchr(keys[j].key, *string) != NULL) {
590: i = strlcat(buf, keys[j].repl, sizeof(buf));
591: if (i >= sizeof(buf))
1.73 djm 592: fatal("%s: string too long", __func__);
1.31 djm 593: break;
594: }
595: }
596: if (j >= num_keys)
1.73 djm 597: fatal("%s: unknown key %%%c", __func__, *string);
1.31 djm 598: }
599: return (xstrdup(buf));
600: #undef EXPAND_MAX_KEYS
1.26 dtucker 601: }
602:
603: /*
604: * Read an entire line from a public key file into a static buffer, discarding
605: * lines that exceed the buffer size. Returns 0 on success, -1 on failure.
606: */
607: int
608: read_keyfile_line(FILE *f, const char *filename, char *buf, size_t bufsz,
1.27 dtucker 609: u_long *lineno)
1.26 dtucker 610: {
611: while (fgets(buf, bufsz, f) != NULL) {
1.65 ray 612: if (buf[0] == '\0')
613: continue;
1.26 dtucker 614: (*lineno)++;
615: if (buf[strlen(buf) - 1] == '\n' || feof(f)) {
616: return 0;
617: } else {
1.27 dtucker 618: debug("%s: %s line %lu exceeds size limit", __func__,
619: filename, *lineno);
1.26 dtucker 620: /* discard remainder of line */
1.29 deraadt 621: while (fgetc(f) != '\n' && !feof(f))
1.26 dtucker 622: ; /* nothing */
623: }
624: }
625: return -1;
1.36 reyk 626: }
627:
628: int
1.37 reyk 629: tun_open(int tun, int mode)
1.36 reyk 630: {
1.37 reyk 631: struct ifreq ifr;
1.36 reyk 632: char name[100];
1.37 reyk 633: int fd = -1, sock;
1.36 reyk 634:
1.37 reyk 635: /* Open the tunnel device */
636: if (tun <= SSH_TUNID_MAX) {
1.36 reyk 637: snprintf(name, sizeof(name), "/dev/tun%d", tun);
1.37 reyk 638: fd = open(name, O_RDWR);
639: } else if (tun == SSH_TUNID_ANY) {
640: for (tun = 100; tun >= 0; tun--) {
641: snprintf(name, sizeof(name), "/dev/tun%d", tun);
642: if ((fd = open(name, O_RDWR)) >= 0)
643: break;
1.36 reyk 644: }
645: } else {
1.39 stevesk 646: debug("%s: invalid tunnel %u", __func__, tun);
1.37 reyk 647: return (-1);
648: }
649:
650: if (fd < 0) {
651: debug("%s: %s open failed: %s", __func__, name, strerror(errno));
652: return (-1);
1.36 reyk 653: }
1.37 reyk 654:
655: debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
656:
657: /* Set the tunnel device operation mode */
658: snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "tun%d", tun);
659: if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
660: goto failed;
661:
662: if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1)
663: goto failed;
1.40 reyk 664:
665: /* Set interface mode */
666: ifr.ifr_flags &= ~IFF_UP;
667: if (mode == SSH_TUNMODE_ETHERNET)
1.37 reyk 668: ifr.ifr_flags |= IFF_LINK0;
1.40 reyk 669: else
670: ifr.ifr_flags &= ~IFF_LINK0;
671: if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1)
672: goto failed;
673:
674: /* Bring interface up */
1.37 reyk 675: ifr.ifr_flags |= IFF_UP;
676: if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1)
677: goto failed;
678:
679: close(sock);
680: return (fd);
681:
682: failed:
683: if (fd >= 0)
684: close(fd);
685: if (sock >= 0)
686: close(sock);
687: debug("%s: failed to set %s mode %d: %s", __func__, name,
688: mode, strerror(errno));
1.36 reyk 689: return (-1);
1.35 djm 690: }
691:
692: void
693: sanitise_stdfd(void)
694: {
1.41 djm 695: int nullfd, dupfd;
1.35 djm 696:
1.41 djm 697: if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1.71 tobias 698: fprintf(stderr, "Couldn't open /dev/null: %s\n",
699: strerror(errno));
1.35 djm 700: exit(1);
701: }
1.41 djm 702: while (++dupfd <= 2) {
703: /* Only clobber closed fds */
704: if (fcntl(dupfd, F_GETFL, 0) >= 0)
705: continue;
706: if (dup2(nullfd, dupfd) == -1) {
1.71 tobias 707: fprintf(stderr, "dup2: %s\n", strerror(errno));
1.35 djm 708: exit(1);
709: }
710: }
711: if (nullfd > 2)
712: close(nullfd);
1.1 markus 713: }
1.33 djm 714:
715: char *
1.52 djm 716: tohex(const void *vp, size_t l)
1.33 djm 717: {
1.52 djm 718: const u_char *p = (const u_char *)vp;
1.33 djm 719: char b[3], *r;
1.52 djm 720: size_t i, hl;
721:
722: if (l > 65536)
723: return xstrdup("tohex: length > 65536");
1.33 djm 724:
725: hl = l * 2 + 1;
1.49 djm 726: r = xcalloc(1, hl);
1.33 djm 727: for (i = 0; i < l; i++) {
1.52 djm 728: snprintf(b, sizeof(b), "%02x", p[i]);
1.33 djm 729: strlcat(r, b, hl);
730: }
731: return (r);
732: }
733:
1.52 djm 734: u_int64_t
735: get_u64(const void *vp)
736: {
737: const u_char *p = (const u_char *)vp;
738: u_int64_t v;
739:
740: v = (u_int64_t)p[0] << 56;
741: v |= (u_int64_t)p[1] << 48;
742: v |= (u_int64_t)p[2] << 40;
743: v |= (u_int64_t)p[3] << 32;
744: v |= (u_int64_t)p[4] << 24;
745: v |= (u_int64_t)p[5] << 16;
746: v |= (u_int64_t)p[6] << 8;
747: v |= (u_int64_t)p[7];
748:
749: return (v);
750: }
751:
752: u_int32_t
753: get_u32(const void *vp)
754: {
755: const u_char *p = (const u_char *)vp;
756: u_int32_t v;
757:
758: v = (u_int32_t)p[0] << 24;
759: v |= (u_int32_t)p[1] << 16;
760: v |= (u_int32_t)p[2] << 8;
761: v |= (u_int32_t)p[3];
762:
763: return (v);
764: }
765:
766: u_int16_t
767: get_u16(const void *vp)
768: {
769: const u_char *p = (const u_char *)vp;
770: u_int16_t v;
771:
772: v = (u_int16_t)p[0] << 8;
773: v |= (u_int16_t)p[1];
774:
775: return (v);
776: }
777:
778: void
779: put_u64(void *vp, u_int64_t v)
780: {
781: u_char *p = (u_char *)vp;
782:
783: p[0] = (u_char)(v >> 56) & 0xff;
784: p[1] = (u_char)(v >> 48) & 0xff;
785: p[2] = (u_char)(v >> 40) & 0xff;
786: p[3] = (u_char)(v >> 32) & 0xff;
787: p[4] = (u_char)(v >> 24) & 0xff;
788: p[5] = (u_char)(v >> 16) & 0xff;
789: p[6] = (u_char)(v >> 8) & 0xff;
790: p[7] = (u_char)v & 0xff;
791: }
792:
793: void
794: put_u32(void *vp, u_int32_t v)
795: {
796: u_char *p = (u_char *)vp;
797:
798: p[0] = (u_char)(v >> 24) & 0xff;
799: p[1] = (u_char)(v >> 16) & 0xff;
800: p[2] = (u_char)(v >> 8) & 0xff;
801: p[3] = (u_char)v & 0xff;
802: }
803:
804:
805: void
806: put_u16(void *vp, u_int16_t v)
807: {
808: u_char *p = (u_char *)vp;
809:
810: p[0] = (u_char)(v >> 8) & 0xff;
811: p[1] = (u_char)v & 0xff;
812: }
1.68 dtucker 813:
814: void
815: ms_subtract_diff(struct timeval *start, int *ms)
816: {
817: struct timeval diff, finish;
818:
819: gettimeofday(&finish, NULL);
820: timersub(&finish, start, &diff);
821: *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
822: }
823:
824: void
825: ms_to_timeval(struct timeval *tv, int ms)
826: {
827: if (ms < 0)
828: ms = 0;
829: tv->tv_sec = ms / 1000;
830: tv->tv_usec = (ms % 1000) * 1000;
1.81 djm 831: }
832:
833: void
834: bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
835: {
836: bw->buflen = buflen;
837: bw->rate = kbps;
838: bw->thresh = bw->rate;
839: bw->lamt = 0;
840: timerclear(&bw->bwstart);
841: timerclear(&bw->bwend);
842: }
843:
844: /* Callback from read/write loop to insert bandwidth-limiting delays */
845: void
846: bandwidth_limit(struct bwlimit *bw, size_t read_len)
847: {
848: u_int64_t waitlen;
849: struct timespec ts, rm;
850:
851: if (!timerisset(&bw->bwstart)) {
852: gettimeofday(&bw->bwstart, NULL);
853: return;
854: }
855:
856: bw->lamt += read_len;
857: if (bw->lamt < bw->thresh)
858: return;
859:
860: gettimeofday(&bw->bwend, NULL);
861: timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
862: if (!timerisset(&bw->bwend))
863: return;
864:
865: bw->lamt *= 8;
866: waitlen = (double)1000000L * bw->lamt / bw->rate;
867:
868: bw->bwstart.tv_sec = waitlen / 1000000L;
869: bw->bwstart.tv_usec = waitlen % 1000000L;
870:
871: if (timercmp(&bw->bwstart, &bw->bwend, >)) {
872: timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
873:
874: /* Adjust the wait time */
875: if (bw->bwend.tv_sec) {
876: bw->thresh /= 2;
877: if (bw->thresh < bw->buflen / 4)
878: bw->thresh = bw->buflen / 4;
879: } else if (bw->bwend.tv_usec < 10000) {
880: bw->thresh *= 2;
881: if (bw->thresh > bw->buflen * 8)
882: bw->thresh = bw->buflen * 8;
883: }
884:
885: TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
886: while (nanosleep(&ts, &rm) == -1) {
887: if (errno != EINTR)
888: break;
889: ts = rm;
890: }
891: }
892:
893: bw->lamt = 0;
894: gettimeofday(&bw->bwstart, NULL);
1.68 dtucker 895: }