blob: cfd32729ac7a50de28551186f2e1da03dc8b1dd2 [file] [log] [blame]
dtucker@openbsd.orgc6774d22017-03-14 00:55:37 +00001/* $OpenBSD: misc.c,v 1.109 2017/03/14 00:55:37 dtucker Exp $ */
Damien Millere4340be2000-09-16 13:29:08 +11002/*
3 * Copyright (c) 2000 Markus Friedl. All rights reserved.
Damien Miller3f941882006-03-31 23:13:02 +11004 * Copyright (c) 2005,2006 Damien Miller. All rights reserved.
Damien Millere4340be2000-09-16 13:29:08 +11005 *
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
Damien Miller61c51502000-08-18 14:01:04 +100027#include "includes.h"
Damien Miller17e91c02006-03-15 11:28:34 +110028
Damien Miller9f2abc42006-07-10 20:53:08 +100029#include <sys/types.h>
Damien Millerd7834352006-08-05 12:39:39 +100030#include <sys/ioctl.h>
Damien Miller8ec8c3e2006-07-10 20:35:38 +100031#include <sys/socket.h>
dtucker@openbsd.org65a3c0d2016-01-20 09:22:39 +000032#include <sys/time.h>
Damien Miller7acefbb2014-07-18 14:11:24 +100033#include <sys/un.h>
Damien Miller8ec8c3e2006-07-10 20:35:38 +100034
deraadt@openbsd.org2ae4f332015-01-16 06:40:12 +000035#include <limits.h>
Darren Tucker5d196262006-07-12 22:15:16 +100036#include <stdarg.h>
Damien Millera7a73ee2006-08-05 11:37:59 +100037#include <stdio.h>
Damien Millere7a1e5c2006-08-05 11:34:19 +100038#include <stdlib.h>
Damien Millere3476ed2006-07-24 14:13:33 +100039#include <string.h>
Damien Miller1708cb72011-01-13 12:21:34 +110040#include <time.h>
Damien Millere6b3b612006-07-24 14:01:23 +100041#include <unistd.h>
Darren Tucker5d196262006-07-12 22:15:16 +100042
Damien Miller8ec8c3e2006-07-10 20:35:38 +100043#include <netinet/in.h>
Damien Miller0dac6fb2010-11-20 15:19:38 +110044#include <netinet/in_systm.h>
45#include <netinet/ip.h>
Damien Miller3a4051e2006-03-15 11:19:42 +110046#include <netinet/tcp.h>
Damien Miller8ec8c3e2006-07-10 20:35:38 +100047
Damien Millere9fc72e2013-10-15 12:14:12 +110048#include <ctype.h>
Darren Tucker39972492006-07-12 22:22:46 +100049#include <errno.h>
Damien Miller57cf6382006-07-10 21:13:46 +100050#include <fcntl.h>
Darren Tucker4abde772007-12-29 02:43:51 +110051#include <netdb.h>
Damien Miller03e20032006-03-15 11:16:59 +110052#ifdef HAVE_PATHS_H
Damien Millera9263d02006-03-15 11:18:26 +110053# include <paths.h>
Damien Miller9f2abc42006-07-10 20:53:08 +100054#include <pwd.h>
Damien Miller03e20032006-03-15 11:16:59 +110055#endif
Damien Miller3beb8522006-01-02 23:40:10 +110056#ifdef SSH_TUN_OPENBSD
57#include <net/if.h>
58#endif
Damien Miller61c51502000-08-18 14:01:04 +100059
Damien Millerd7834352006-08-05 12:39:39 +100060#include "xmalloc.h"
Kevin Stevesb6e773a2001-02-04 13:20:36 +000061#include "misc.h"
Ben Lindstrom226cfa02001-01-22 05:34:40 +000062#include "log.h"
Darren Tuckerda345532006-07-10 23:04:19 +100063#include "ssh.h"
Damien Miller61c51502000-08-18 14:01:04 +100064
Ben Lindstrom4cc240d2001-07-04 04:46:56 +000065/* remove newline at end of string */
Damien Miller61c51502000-08-18 14:01:04 +100066char *
67chop(char *s)
68{
69 char *t = s;
70 while (*t) {
Ben Lindstrom1c37c6a2001-12-06 18:00:18 +000071 if (*t == '\n' || *t == '\r') {
Damien Miller61c51502000-08-18 14:01:04 +100072 *t = '\0';
73 return s;
74 }
75 t++;
76 }
77 return s;
78
79}
80
Ben Lindstrom4cc240d2001-07-04 04:46:56 +000081/* set/unset filedescriptor to non-blocking */
Damien Miller232711f2004-06-15 10:35:30 +100082int
Damien Miller61c51502000-08-18 14:01:04 +100083set_nonblock(int fd)
84{
85 int val;
Ben Lindstromc93e84c2001-05-12 00:08:37 +000086
krw@openbsd.org574def02016-04-02 14:37:42 +000087 val = fcntl(fd, F_GETFL);
Damien Miller61c51502000-08-18 14:01:04 +100088 if (val < 0) {
krw@openbsd.org574def02016-04-02 14:37:42 +000089 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
Damien Miller232711f2004-06-15 10:35:30 +100090 return (-1);
Damien Miller61c51502000-08-18 14:01:04 +100091 }
Damien Miller69b69aa2000-10-28 14:19:58 +110092 if (val & O_NONBLOCK) {
Damien Miller232711f2004-06-15 10:35:30 +100093 debug3("fd %d is O_NONBLOCK", fd);
94 return (0);
Damien Miller69b69aa2000-10-28 14:19:58 +110095 }
Damien Milleref095ce2003-05-14 13:41:39 +100096 debug2("fd %d setting O_NONBLOCK", fd);
Damien Miller61c51502000-08-18 14:01:04 +100097 val |= O_NONBLOCK;
Damien Miller232711f2004-06-15 10:35:30 +100098 if (fcntl(fd, F_SETFL, val) == -1) {
99 debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
100 strerror(errno));
101 return (-1);
102 }
103 return (0);
Damien Miller61c51502000-08-18 14:01:04 +1000104}
105
Damien Miller232711f2004-06-15 10:35:30 +1000106int
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000107unset_nonblock(int fd)
108{
109 int val;
110
krw@openbsd.org574def02016-04-02 14:37:42 +0000111 val = fcntl(fd, F_GETFL);
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000112 if (val < 0) {
krw@openbsd.org574def02016-04-02 14:37:42 +0000113 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
Damien Miller232711f2004-06-15 10:35:30 +1000114 return (-1);
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000115 }
116 if (!(val & O_NONBLOCK)) {
Damien Miller232711f2004-06-15 10:35:30 +1000117 debug3("fd %d is not O_NONBLOCK", fd);
118 return (0);
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000119 }
Ben Lindstrom352b1c22001-06-21 03:04:37 +0000120 debug("fd %d clearing O_NONBLOCK", fd);
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000121 val &= ~O_NONBLOCK;
Damien Miller232711f2004-06-15 10:35:30 +1000122 if (fcntl(fd, F_SETFL, val) == -1) {
123 debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
Ben Lindstrom84fcb312002-03-05 01:48:09 +0000124 fd, strerror(errno));
Damien Miller232711f2004-06-15 10:35:30 +1000125 return (-1);
126 }
127 return (0);
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000128}
129
Darren Tucker4abde772007-12-29 02:43:51 +1100130const char *
131ssh_gai_strerror(int gaierr)
132{
Damien Miller7313fc92013-07-18 16:13:19 +1000133 if (gaierr == EAI_SYSTEM && errno != 0)
Darren Tucker912428c2008-01-01 20:33:35 +1100134 return strerror(errno);
135 return gai_strerror(gaierr);
Darren Tucker4abde772007-12-29 02:43:51 +1100136}
137
Damien Miller398e1cf2002-02-05 11:52:13 +1100138/* disable nagle on socket */
139void
140set_nodelay(int fd)
141{
Ben Lindstrome86de512002-03-05 01:28:14 +0000142 int opt;
143 socklen_t optlen;
Damien Miller398e1cf2002-02-05 11:52:13 +1100144
Ben Lindstrom1ebd7a52002-02-26 18:12:51 +0000145 optlen = sizeof opt;
146 if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
Darren Tucker6db8f932003-11-03 20:07:14 +1100147 debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
Ben Lindstrom1ebd7a52002-02-26 18:12:51 +0000148 return;
149 }
150 if (opt == 1) {
151 debug2("fd %d is TCP_NODELAY", fd);
152 return;
153 }
154 opt = 1;
Ben Lindstrom1d568f92002-12-23 02:44:36 +0000155 debug2("fd %d setting TCP_NODELAY", fd);
Ben Lindstrom1ebd7a52002-02-26 18:12:51 +0000156 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
Damien Miller398e1cf2002-02-05 11:52:13 +1100157 error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
158}
159
Damien Miller61c51502000-08-18 14:01:04 +1000160/* Characters considered whitespace in strsep calls. */
161#define WHITESPACE " \t\r\n"
Damien Miller306d1182006-03-15 12:05:59 +1100162#define QUOTE "\""
Damien Miller61c51502000-08-18 14:01:04 +1000163
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000164/* return next token in configuration line */
Damien Miller61c51502000-08-18 14:01:04 +1000165char *
166strdelim(char **s)
167{
168 char *old;
169 int wspace = 0;
170
171 if (*s == NULL)
172 return NULL;
173
174 old = *s;
175
Damien Miller306d1182006-03-15 12:05:59 +1100176 *s = strpbrk(*s, WHITESPACE QUOTE "=");
Damien Miller61c51502000-08-18 14:01:04 +1000177 if (*s == NULL)
178 return (old);
179
Damien Miller306d1182006-03-15 12:05:59 +1100180 if (*s[0] == '\"') {
181 memmove(*s, *s + 1, strlen(*s)); /* move nul too */
182 /* Find matching quote */
183 if ((*s = strpbrk(*s, QUOTE)) == NULL) {
184 return (NULL); /* no matching quote */
185 } else {
186 *s[0] = '\0';
Damien Miller9308fc72010-07-16 13:56:01 +1000187 *s += strspn(*s + 1, WHITESPACE) + 1;
Damien Miller306d1182006-03-15 12:05:59 +1100188 return (old);
189 }
190 }
191
Damien Miller61c51502000-08-18 14:01:04 +1000192 /* Allow only one '=' to be skipped */
193 if (*s[0] == '=')
194 wspace = 1;
195 *s[0] = '\0';
196
Damien Miller306d1182006-03-15 12:05:59 +1100197 /* Skip any extra whitespace after first token */
Damien Miller61c51502000-08-18 14:01:04 +1000198 *s += strspn(*s + 1, WHITESPACE) + 1;
199 if (*s[0] == '=' && !wspace)
200 *s += strspn(*s + 1, WHITESPACE) + 1;
201
202 return (old);
203}
Kevin Stevesb6e773a2001-02-04 13:20:36 +0000204
Ben Lindstrom086cf212001-03-05 05:56:40 +0000205struct passwd *
206pwcopy(struct passwd *pw)
207{
Damien Miller07d86be2006-03-26 14:19:21 +1100208 struct passwd *copy = xcalloc(1, sizeof(*copy));
Ben Lindstrom40304422001-03-05 06:22:01 +0000209
Ben Lindstrom086cf212001-03-05 05:56:40 +0000210 copy->pw_name = xstrdup(pw->pw_name);
211 copy->pw_passwd = xstrdup(pw->pw_passwd);
Damien Miller6332da22013-04-23 14:25:52 +1000212#ifdef HAVE_STRUCT_PASSWD_PW_GECOS
Ben Lindstrom40304422001-03-05 06:22:01 +0000213 copy->pw_gecos = xstrdup(pw->pw_gecos);
Damien Miller6332da22013-04-23 14:25:52 +1000214#endif
Ben Lindstrom086cf212001-03-05 05:56:40 +0000215 copy->pw_uid = pw->pw_uid;
216 copy->pw_gid = pw->pw_gid;
Damien Miller6332da22013-04-23 14:25:52 +1000217#ifdef HAVE_STRUCT_PASSWD_PW_EXPIRE
Ben Lindstrom3af4d462001-06-21 03:11:27 +0000218 copy->pw_expire = pw->pw_expire;
Kevin Steves82456952001-06-22 21:14:18 +0000219#endif
Damien Miller6332da22013-04-23 14:25:52 +1000220#ifdef HAVE_STRUCT_PASSWD_PW_CHANGE
Ben Lindstrom3af4d462001-06-21 03:11:27 +0000221 copy->pw_change = pw->pw_change;
Kevin Steves82456952001-06-22 21:14:18 +0000222#endif
Damien Miller6332da22013-04-23 14:25:52 +1000223#ifdef HAVE_STRUCT_PASSWD_PW_CLASS
Ben Lindstrom086cf212001-03-05 05:56:40 +0000224 copy->pw_class = xstrdup(pw->pw_class);
Ben Lindstrom0f68db42001-03-05 07:57:09 +0000225#endif
Ben Lindstrom086cf212001-03-05 05:56:40 +0000226 copy->pw_dir = xstrdup(pw->pw_dir);
227 copy->pw_shell = xstrdup(pw->pw_shell);
228 return copy;
229}
230
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000231/*
232 * Convert ASCII string to TCP/IP port number.
Damien Miller3dc71ad2009-01-28 16:31:22 +1100233 * Port must be >=0 and <=65535.
234 * Return -1 if invalid.
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000235 */
236int
237a2port(const char *s)
Ben Lindstrom19066a12001-04-12 23:39:26 +0000238{
Damien Miller3dc71ad2009-01-28 16:31:22 +1100239 long long port;
240 const char *errstr;
Ben Lindstrom19066a12001-04-12 23:39:26 +0000241
Damien Miller3dc71ad2009-01-28 16:31:22 +1100242 port = strtonum(s, 0, 65535, &errstr);
243 if (errstr != NULL)
244 return -1;
245 return (int)port;
Ben Lindstrom19066a12001-04-12 23:39:26 +0000246}
247
Damien Millerd27b9472005-12-13 19:29:02 +1100248int
249a2tun(const char *s, int *remote)
250{
251 const char *errstr = NULL;
252 char *sp, *ep;
253 int tun;
254
255 if (remote != NULL) {
Damien Miller7b58e802005-12-13 19:33:19 +1100256 *remote = SSH_TUNID_ANY;
Damien Millerd27b9472005-12-13 19:29:02 +1100257 sp = xstrdup(s);
258 if ((ep = strchr(sp, ':')) == NULL) {
Darren Tuckera627d422013-06-02 07:31:17 +1000259 free(sp);
Damien Millerd27b9472005-12-13 19:29:02 +1100260 return (a2tun(s, NULL));
261 }
262 ep[0] = '\0'; ep++;
263 *remote = a2tun(ep, NULL);
264 tun = a2tun(sp, NULL);
Darren Tuckera627d422013-06-02 07:31:17 +1000265 free(sp);
Damien Miller7b58e802005-12-13 19:33:19 +1100266 return (*remote == SSH_TUNID_ERR ? *remote : tun);
Damien Millerd27b9472005-12-13 19:29:02 +1100267 }
268
269 if (strcasecmp(s, "any") == 0)
Damien Miller7b58e802005-12-13 19:33:19 +1100270 return (SSH_TUNID_ANY);
Damien Millerd27b9472005-12-13 19:29:02 +1100271
Damien Miller7b58e802005-12-13 19:33:19 +1100272 tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
273 if (errstr != NULL)
274 return (SSH_TUNID_ERR);
Damien Millerd27b9472005-12-13 19:29:02 +1100275
276 return (tun);
277}
278
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000279#define SECONDS 1
280#define MINUTES (SECONDS * 60)
281#define HOURS (MINUTES * 60)
282#define DAYS (HOURS * 24)
283#define WEEKS (DAYS * 7)
284
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000285/*
286 * Convert a time string into seconds; format is
287 * a sequence of:
288 * time[qualifier]
289 *
290 * Valid time qualifiers are:
291 * <none> seconds
292 * s|S seconds
293 * m|M minutes
294 * h|H hours
295 * d|D days
296 * w|W weeks
297 *
298 * Examples:
299 * 90m 90 minutes
300 * 1h30m 90 minutes
301 * 2d 2 days
302 * 1w 1 week
303 *
304 * Return -1 if time string is invalid.
305 */
306long
307convtime(const char *s)
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000308{
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000309 long total, secs, multiplier = 1;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000310 const char *p;
311 char *endp;
312
313 errno = 0;
314 total = 0;
315 p = s;
316
317 if (p == NULL || *p == '\0')
318 return -1;
319
320 while (*p) {
321 secs = strtol(p, &endp, 10);
322 if (p == endp ||
323 (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
324 secs < 0)
325 return -1;
326
327 switch (*endp++) {
328 case '\0':
329 endp--;
Damien Miller69b72032006-03-26 14:02:35 +1100330 break;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000331 case 's':
332 case 'S':
333 break;
334 case 'm':
335 case 'M':
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000336 multiplier = MINUTES;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000337 break;
338 case 'h':
339 case 'H':
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000340 multiplier = HOURS;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000341 break;
342 case 'd':
343 case 'D':
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000344 multiplier = DAYS;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000345 break;
346 case 'w':
347 case 'W':
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000348 multiplier = WEEKS;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000349 break;
350 default:
351 return -1;
352 }
dtucker@openbsd.orgc6774d22017-03-14 00:55:37 +0000353 if (secs >= LONG_MAX / multiplier)
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000354 return -1;
355 secs *= multiplier;
dtucker@openbsd.orgc6774d22017-03-14 00:55:37 +0000356 if (total >= LONG_MAX - secs)
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000357 return -1;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000358 total += secs;
359 if (total < 0)
360 return -1;
361 p = endp;
362 }
363
364 return total;
365}
366
Damien Millerf91ee4c2005-03-01 21:24:33 +1100367/*
Darren Tuckerda345532006-07-10 23:04:19 +1000368 * Returns a standardized host+port identifier string.
369 * Caller must free returned string.
370 */
371char *
372put_host_port(const char *host, u_short port)
373{
374 char *hoststr;
375
376 if (port == 0 || port == SSH_DEFAULT_PORT)
377 return(xstrdup(host));
378 if (asprintf(&hoststr, "[%s]:%d", host, (int)port) < 0)
379 fatal("put_host_port: asprintf: %s", strerror(errno));
380 debug3("put_host_port: %s", hoststr);
381 return hoststr;
382}
383
384/*
Damien Millerf91ee4c2005-03-01 21:24:33 +1100385 * Search for next delimiter between hostnames/addresses and ports.
386 * Argument may be modified (for termination).
387 * Returns *cp if parsing succeeds.
388 * *cp is set to the start of the next delimiter, if one was found.
389 * If this is the last field, *cp is set to NULL.
390 */
391char *
392hpdelim(char **cp)
393{
394 char *s, *old;
395
396 if (cp == NULL || *cp == NULL)
397 return NULL;
398
399 old = s = *cp;
400 if (*s == '[') {
401 if ((s = strchr(s, ']')) == NULL)
402 return NULL;
403 else
404 s++;
405 } else if ((s = strpbrk(s, ":/")) == NULL)
406 s = *cp + strlen(*cp); /* skip to end (see first case below) */
407
408 switch (*s) {
409 case '\0':
410 *cp = NULL; /* no more fields*/
411 break;
Darren Tucker47eede72005-03-14 23:08:12 +1100412
Damien Millerf91ee4c2005-03-01 21:24:33 +1100413 case ':':
414 case '/':
415 *s = '\0'; /* terminate */
416 *cp = s + 1;
417 break;
Darren Tucker47eede72005-03-14 23:08:12 +1100418
Damien Millerf91ee4c2005-03-01 21:24:33 +1100419 default:
420 return NULL;
421 }
422
423 return old;
424}
425
Ben Lindstrom4529b702001-05-03 23:39:53 +0000426char *
427cleanhostname(char *host)
428{
429 if (*host == '[' && host[strlen(host) - 1] == ']') {
430 host[strlen(host) - 1] = '\0';
431 return (host + 1);
432 } else
433 return host;
434}
435
436char *
437colon(char *cp)
438{
439 int flag = 0;
440
441 if (*cp == ':') /* Leading colon is part of file name. */
Damien Miller2e774462010-06-26 09:30:47 +1000442 return NULL;
Ben Lindstrom4529b702001-05-03 23:39:53 +0000443 if (*cp == '[')
444 flag = 1;
445
446 for (; *cp; ++cp) {
447 if (*cp == '@' && *(cp+1) == '[')
448 flag = 1;
449 if (*cp == ']' && *(cp+1) == ':' && flag)
450 return (cp+1);
451 if (*cp == ':' && !flag)
452 return (cp);
453 if (*cp == '/')
Damien Miller2e774462010-06-26 09:30:47 +1000454 return NULL;
Ben Lindstrom4529b702001-05-03 23:39:53 +0000455 }
Damien Miller2e774462010-06-26 09:30:47 +1000456 return NULL;
Ben Lindstrom4529b702001-05-03 23:39:53 +0000457}
458
djm@openbsd.orged877ef2016-07-15 00:24:30 +0000459/*
460 * Parse a [user@]host[:port] string.
461 * Caller must free returned user and host.
462 * Any of the pointer return arguments may be NULL (useful for syntax checking).
463 * If user was not specified then *userp will be set to NULL.
464 * If port was not specified then *portp will be -1.
465 * Returns 0 on success, -1 on failure.
466 */
467int
468parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
469{
470 char *sdup, *cp, *tmp;
471 char *user = NULL, *host = NULL;
472 int port = -1, ret = -1;
473
474 if (userp != NULL)
475 *userp = NULL;
476 if (hostp != NULL)
477 *hostp = NULL;
478 if (portp != NULL)
479 *portp = -1;
480
481 if ((sdup = tmp = strdup(s)) == NULL)
482 return -1;
483 /* Extract optional username */
484 if ((cp = strchr(tmp, '@')) != NULL) {
485 *cp = '\0';
486 if (*tmp == '\0')
487 goto out;
488 if ((user = strdup(tmp)) == NULL)
489 goto out;
490 tmp = cp + 1;
491 }
492 /* Extract mandatory hostname */
493 if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
494 goto out;
495 host = xstrdup(cleanhostname(cp));
496 /* Convert and verify optional port */
497 if (tmp != NULL && *tmp != '\0') {
498 if ((port = a2port(tmp)) <= 0)
499 goto out;
500 }
501 /* Success */
502 if (userp != NULL) {
503 *userp = user;
504 user = NULL;
505 }
506 if (hostp != NULL) {
507 *hostp = host;
508 host = NULL;
509 }
510 if (portp != NULL)
511 *portp = port;
512 ret = 0;
513 out:
514 free(sdup);
515 free(user);
516 free(host);
517 return ret;
518}
519
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000520/* function to assist building execv() arguments */
Ben Lindstrom387c4722001-05-08 20:27:25 +0000521void
522addargs(arglist *args, char *fmt, ...)
523{
524 va_list ap;
Damien Miller3eec6b72006-01-31 21:49:27 +1100525 char *cp;
Darren Tuckerc7a6fc42004-08-13 21:18:00 +1000526 u_int nalloc;
Damien Miller3eec6b72006-01-31 21:49:27 +1100527 int r;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000528
529 va_start(ap, fmt);
Damien Miller3eec6b72006-01-31 21:49:27 +1100530 r = vasprintf(&cp, fmt, ap);
Ben Lindstrom387c4722001-05-08 20:27:25 +0000531 va_end(ap);
Damien Miller3eec6b72006-01-31 21:49:27 +1100532 if (r == -1)
533 fatal("addargs: argument too long");
Ben Lindstrom387c4722001-05-08 20:27:25 +0000534
Darren Tuckerfb16b242003-09-22 21:04:23 +1000535 nalloc = args->nalloc;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000536 if (args->list == NULL) {
Darren Tuckerfb16b242003-09-22 21:04:23 +1000537 nalloc = 32;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000538 args->num = 0;
Darren Tuckerfb16b242003-09-22 21:04:23 +1000539 } else if (args->num+2 >= nalloc)
540 nalloc *= 2;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000541
deraadt@openbsd.org657a5fb2015-04-24 01:36:00 +0000542 args->list = xreallocarray(args->list, nalloc, sizeof(char *));
Darren Tuckerfb16b242003-09-22 21:04:23 +1000543 args->nalloc = nalloc;
Damien Miller3eec6b72006-01-31 21:49:27 +1100544 args->list[args->num++] = cp;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000545 args->list[args->num] = NULL;
546}
Darren Tucker22cc7412004-12-06 22:47:41 +1100547
Damien Miller3eec6b72006-01-31 21:49:27 +1100548void
549replacearg(arglist *args, u_int which, char *fmt, ...)
550{
551 va_list ap;
552 char *cp;
553 int r;
554
555 va_start(ap, fmt);
556 r = vasprintf(&cp, fmt, ap);
557 va_end(ap);
558 if (r == -1)
559 fatal("replacearg: argument too long");
560
561 if (which >= args->num)
562 fatal("replacearg: tried to replace invalid arg %d >= %d",
563 which, args->num);
Darren Tuckera627d422013-06-02 07:31:17 +1000564 free(args->list[which]);
Damien Miller3eec6b72006-01-31 21:49:27 +1100565 args->list[which] = cp;
566}
567
568void
569freeargs(arglist *args)
570{
571 u_int i;
572
573 if (args->list != NULL) {
574 for (i = 0; i < args->num; i++)
Darren Tuckera627d422013-06-02 07:31:17 +1000575 free(args->list[i]);
576 free(args->list);
Damien Miller3eec6b72006-01-31 21:49:27 +1100577 args->nalloc = args->num = 0;
578 args->list = NULL;
579 }
580}
581
Darren Tucker22cc7412004-12-06 22:47:41 +1100582/*
Damien Miller5fd38c02005-05-26 12:02:14 +1000583 * Expands tildes in the file name. Returns data allocated by xmalloc.
584 * Warning: this calls getpw*.
585 */
586char *
587tilde_expand_filename(const char *filename, uid_t uid)
588{
Darren Tucker2ca51bf2013-05-16 20:22:46 +1000589 const char *path, *sep;
590 char user[128], *ret;
Damien Miller5fd38c02005-05-26 12:02:14 +1000591 struct passwd *pw;
Damien Millereccb9de2005-06-17 12:59:34 +1000592 u_int len, slash;
Damien Miller5fd38c02005-05-26 12:02:14 +1000593
594 if (*filename != '~')
595 return (xstrdup(filename));
596 filename++;
597
598 path = strchr(filename, '/');
599 if (path != NULL && path > filename) { /* ~user/path */
Damien Millereccb9de2005-06-17 12:59:34 +1000600 slash = path - filename;
601 if (slash > sizeof(user) - 1)
Damien Miller5fd38c02005-05-26 12:02:14 +1000602 fatal("tilde_expand_filename: ~username too long");
Damien Millereccb9de2005-06-17 12:59:34 +1000603 memcpy(user, filename, slash);
604 user[slash] = '\0';
Damien Miller5fd38c02005-05-26 12:02:14 +1000605 if ((pw = getpwnam(user)) == NULL)
606 fatal("tilde_expand_filename: No such user %s", user);
607 } else if ((pw = getpwuid(uid)) == NULL) /* ~/path */
Darren Tucker7517b5b2008-06-13 14:48:59 +1000608 fatal("tilde_expand_filename: No such uid %ld", (long)uid);
Damien Miller5fd38c02005-05-26 12:02:14 +1000609
Damien Miller5fd38c02005-05-26 12:02:14 +1000610 /* Make sure directory has a trailing '/' */
611 len = strlen(pw->pw_dir);
Darren Tucker026d9db2013-05-16 20:23:52 +1000612 if (len == 0 || pw->pw_dir[len - 1] != '/')
Darren Tucker2ca51bf2013-05-16 20:22:46 +1000613 sep = "/";
614 else
615 sep = "";
Damien Miller5fd38c02005-05-26 12:02:14 +1000616
617 /* Skip leading '/' from specified path */
618 if (path != NULL)
619 filename = path + 1;
Darren Tucker2ca51bf2013-05-16 20:22:46 +1000620
deraadt@openbsd.org2ae4f332015-01-16 06:40:12 +0000621 if (xasprintf(&ret, "%s%s%s", pw->pw_dir, sep, filename) >= PATH_MAX)
Damien Miller5fd38c02005-05-26 12:02:14 +1000622 fatal("tilde_expand_filename: Path too long");
623
Darren Tucker2ca51bf2013-05-16 20:22:46 +1000624 return (ret);
Damien Miller5fd38c02005-05-26 12:02:14 +1000625}
626
627/*
Damien Miller6476cad2005-06-16 13:18:34 +1000628 * Expand a string with a set of %[char] escapes. A number of escapes may be
629 * specified as (char *escape_chars, char *replacement) pairs. The list must
Darren Tuckerbee73d52005-07-14 17:05:02 +1000630 * be terminated by a NULL escape_char. Returns replaced string in memory
Damien Miller6476cad2005-06-16 13:18:34 +1000631 * allocated by xmalloc.
632 */
633char *
634percent_expand(const char *string, ...)
635{
636#define EXPAND_MAX_KEYS 16
Darren Tucker70d87692010-01-08 18:49:16 +1100637 u_int num_keys, i, j;
Damien Miller6476cad2005-06-16 13:18:34 +1000638 struct {
639 const char *key;
640 const char *repl;
641 } keys[EXPAND_MAX_KEYS];
Damien Miller6476cad2005-06-16 13:18:34 +1000642 char buf[4096];
643 va_list ap;
644
645 /* Gather keys */
646 va_start(ap, string);
647 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
648 keys[num_keys].key = va_arg(ap, char *);
649 if (keys[num_keys].key == NULL)
650 break;
651 keys[num_keys].repl = va_arg(ap, char *);
652 if (keys[num_keys].repl == NULL)
Darren Tucker70d87692010-01-08 18:49:16 +1100653 fatal("%s: NULL replacement", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +1000654 }
Darren Tucker70d87692010-01-08 18:49:16 +1100655 if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
656 fatal("%s: too many keys", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +1000657 va_end(ap);
658
Damien Miller6476cad2005-06-16 13:18:34 +1000659 /* Expand string */
660 *buf = '\0';
661 for (i = 0; *string != '\0'; string++) {
662 if (*string != '%') {
663 append:
664 buf[i++] = *string;
665 if (i >= sizeof(buf))
Darren Tucker70d87692010-01-08 18:49:16 +1100666 fatal("%s: string too long", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +1000667 buf[i] = '\0';
668 continue;
669 }
670 string++;
Darren Tucker70d87692010-01-08 18:49:16 +1100671 /* %% case */
Damien Miller6476cad2005-06-16 13:18:34 +1000672 if (*string == '%')
673 goto append;
tobias@openbsd.org8b56e592015-12-04 21:51:06 +0000674 if (*string == '\0')
675 fatal("%s: invalid format", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +1000676 for (j = 0; j < num_keys; j++) {
677 if (strchr(keys[j].key, *string) != NULL) {
678 i = strlcat(buf, keys[j].repl, sizeof(buf));
679 if (i >= sizeof(buf))
Darren Tucker70d87692010-01-08 18:49:16 +1100680 fatal("%s: string too long", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +1000681 break;
682 }
683 }
684 if (j >= num_keys)
Darren Tucker70d87692010-01-08 18:49:16 +1100685 fatal("%s: unknown key %%%c", __func__, *string);
Damien Miller6476cad2005-06-16 13:18:34 +1000686 }
687 return (xstrdup(buf));
688#undef EXPAND_MAX_KEYS
689}
690
691/*
Darren Tucker22cc7412004-12-06 22:47:41 +1100692 * Read an entire line from a public key file into a static buffer, discarding
693 * lines that exceed the buffer size. Returns 0 on success, -1 on failure.
694 */
695int
696read_keyfile_line(FILE *f, const char *filename, char *buf, size_t bufsz,
Darren Tuckerf0f90982004-12-11 13:39:50 +1100697 u_long *lineno)
Darren Tucker22cc7412004-12-06 22:47:41 +1100698{
699 while (fgets(buf, bufsz, f) != NULL) {
Damien Miller3ca8b772007-01-05 16:24:47 +1100700 if (buf[0] == '\0')
701 continue;
Darren Tucker22cc7412004-12-06 22:47:41 +1100702 (*lineno)++;
703 if (buf[strlen(buf) - 1] == '\n' || feof(f)) {
704 return 0;
705 } else {
Darren Tuckerf0f90982004-12-11 13:39:50 +1100706 debug("%s: %s line %lu exceeds size limit", __func__,
707 filename, *lineno);
Darren Tucker22cc7412004-12-06 22:47:41 +1100708 /* discard remainder of line */
Darren Tucker47eede72005-03-14 23:08:12 +1100709 while (fgetc(f) != '\n' && !feof(f))
Darren Tucker22cc7412004-12-06 22:47:41 +1100710 ; /* nothing */
711 }
712 }
713 return -1;
714}
Damien Miller13390022005-07-06 09:44:19 +1000715
Damien Millerd27b9472005-12-13 19:29:02 +1100716int
Damien Miller7b58e802005-12-13 19:33:19 +1100717tun_open(int tun, int mode)
Damien Millerd27b9472005-12-13 19:29:02 +1100718{
Damien Miller62a31c92005-12-13 20:44:13 +1100719#if defined(CUSTOM_SYS_TUN_OPEN)
720 return (sys_tun_open(tun, mode));
Damien Miller2dcddbf2006-01-01 19:47:05 +1100721#elif defined(SSH_TUN_OPENBSD)
Damien Miller7b58e802005-12-13 19:33:19 +1100722 struct ifreq ifr;
Damien Millerd27b9472005-12-13 19:29:02 +1100723 char name[100];
Damien Miller7b58e802005-12-13 19:33:19 +1100724 int fd = -1, sock;
sthen@openbsd.orga820a862015-10-24 08:34:09 +0000725 const char *tunbase = "tun";
726
727 if (mode == SSH_TUNMODE_ETHERNET)
728 tunbase = "tap";
Damien Millerd27b9472005-12-13 19:29:02 +1100729
Damien Miller7b58e802005-12-13 19:33:19 +1100730 /* Open the tunnel device */
731 if (tun <= SSH_TUNID_MAX) {
sthen@openbsd.orga820a862015-10-24 08:34:09 +0000732 snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
Damien Miller7b58e802005-12-13 19:33:19 +1100733 fd = open(name, O_RDWR);
734 } else if (tun == SSH_TUNID_ANY) {
735 for (tun = 100; tun >= 0; tun--) {
sthen@openbsd.orga820a862015-10-24 08:34:09 +0000736 snprintf(name, sizeof(name), "/dev/%s%d",
737 tunbase, tun);
Damien Miller7b58e802005-12-13 19:33:19 +1100738 if ((fd = open(name, O_RDWR)) >= 0)
739 break;
Damien Millerd27b9472005-12-13 19:29:02 +1100740 }
741 } else {
Damien Millera210d522006-01-02 23:40:30 +1100742 debug("%s: invalid tunnel %u", __func__, tun);
djm@openbsd.org2905d6f2015-10-07 00:54:06 +0000743 return -1;
Damien Millerd27b9472005-12-13 19:29:02 +1100744 }
Damien Miller7b58e802005-12-13 19:33:19 +1100745
746 if (fd < 0) {
djm@openbsd.org2905d6f2015-10-07 00:54:06 +0000747 debug("%s: %s open: %s", __func__, name, strerror(errno));
748 return -1;
Damien Miller7b58e802005-12-13 19:33:19 +1100749 }
750
751 debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
752
sthen@openbsd.orga820a862015-10-24 08:34:09 +0000753 /* Bring interface up if it is not already */
754 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
755 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
Damien Miller7b58e802005-12-13 19:33:19 +1100756 goto failed;
757
djm@openbsd.org2905d6f2015-10-07 00:54:06 +0000758 if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
759 debug("%s: get interface %s flags: %s", __func__,
760 ifr.ifr_name, strerror(errno));
Damien Miller7b58e802005-12-13 19:33:19 +1100761 goto failed;
djm@openbsd.org2905d6f2015-10-07 00:54:06 +0000762 }
Damien Millera1d9a182006-01-02 23:41:21 +1100763
djm@openbsd.org2905d6f2015-10-07 00:54:06 +0000764 if (!(ifr.ifr_flags & IFF_UP)) {
765 ifr.ifr_flags |= IFF_UP;
766 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
767 debug("%s: activate interface %s: %s", __func__,
768 ifr.ifr_name, strerror(errno));
769 goto failed;
770 }
771 }
Damien Miller7b58e802005-12-13 19:33:19 +1100772
773 close(sock);
djm@openbsd.org2905d6f2015-10-07 00:54:06 +0000774 return fd;
Damien Miller7b58e802005-12-13 19:33:19 +1100775
776 failed:
777 if (fd >= 0)
778 close(fd);
779 if (sock >= 0)
780 close(sock);
djm@openbsd.org2905d6f2015-10-07 00:54:06 +0000781 return -1;
Damien Miller62a31c92005-12-13 20:44:13 +1100782#else
783 error("Tunnel interfaces are not supported on this platform");
784 return (-1);
785#endif
Damien Millerd27b9472005-12-13 19:29:02 +1100786}
787
Darren Tuckerce321d82005-10-03 18:11:24 +1000788void
789sanitise_stdfd(void)
790{
Damien Miller72c5b7d2006-01-06 14:50:44 +1100791 int nullfd, dupfd;
Darren Tuckerce321d82005-10-03 18:11:24 +1000792
Damien Miller72c5b7d2006-01-06 14:50:44 +1100793 if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
Damien Miller9eab9562009-02-22 08:47:02 +1100794 fprintf(stderr, "Couldn't open /dev/null: %s\n",
795 strerror(errno));
Darren Tuckerce321d82005-10-03 18:11:24 +1000796 exit(1);
797 }
krw@openbsd.org574def02016-04-02 14:37:42 +0000798 while (++dupfd <= STDERR_FILENO) {
799 /* Only populate closed fds. */
800 if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
801 if (dup2(nullfd, dupfd) == -1) {
802 fprintf(stderr, "dup2: %s\n", strerror(errno));
803 exit(1);
804 }
Darren Tuckerce321d82005-10-03 18:11:24 +1000805 }
Darren Tuckerce321d82005-10-03 18:11:24 +1000806 }
krw@openbsd.org574def02016-04-02 14:37:42 +0000807 if (nullfd > STDERR_FILENO)
Darren Tuckerce321d82005-10-03 18:11:24 +1000808 close(nullfd);
809}
810
Damien Miller13390022005-07-06 09:44:19 +1000811char *
Damien Miller3f941882006-03-31 23:13:02 +1100812tohex(const void *vp, size_t l)
Damien Miller13390022005-07-06 09:44:19 +1000813{
Damien Miller3f941882006-03-31 23:13:02 +1100814 const u_char *p = (const u_char *)vp;
Damien Miller13390022005-07-06 09:44:19 +1000815 char b[3], *r;
Damien Miller3f941882006-03-31 23:13:02 +1100816 size_t i, hl;
817
818 if (l > 65536)
819 return xstrdup("tohex: length > 65536");
Damien Miller13390022005-07-06 09:44:19 +1000820
821 hl = l * 2 + 1;
Damien Miller07d86be2006-03-26 14:19:21 +1100822 r = xcalloc(1, hl);
Damien Miller13390022005-07-06 09:44:19 +1000823 for (i = 0; i < l; i++) {
Damien Miller3f941882006-03-31 23:13:02 +1100824 snprintf(b, sizeof(b), "%02x", p[i]);
Damien Miller13390022005-07-06 09:44:19 +1000825 strlcat(r, b, hl);
826 }
827 return (r);
828}
829
Damien Miller3f941882006-03-31 23:13:02 +1100830u_int64_t
831get_u64(const void *vp)
832{
833 const u_char *p = (const u_char *)vp;
834 u_int64_t v;
835
836 v = (u_int64_t)p[0] << 56;
837 v |= (u_int64_t)p[1] << 48;
838 v |= (u_int64_t)p[2] << 40;
839 v |= (u_int64_t)p[3] << 32;
840 v |= (u_int64_t)p[4] << 24;
841 v |= (u_int64_t)p[5] << 16;
842 v |= (u_int64_t)p[6] << 8;
843 v |= (u_int64_t)p[7];
844
845 return (v);
846}
847
848u_int32_t
849get_u32(const void *vp)
850{
851 const u_char *p = (const u_char *)vp;
852 u_int32_t v;
853
854 v = (u_int32_t)p[0] << 24;
855 v |= (u_int32_t)p[1] << 16;
856 v |= (u_int32_t)p[2] << 8;
857 v |= (u_int32_t)p[3];
858
859 return (v);
860}
861
Damien Miller88856692014-04-20 13:33:19 +1000862u_int32_t
863get_u32_le(const void *vp)
864{
865 const u_char *p = (const u_char *)vp;
866 u_int32_t v;
867
868 v = (u_int32_t)p[0];
869 v |= (u_int32_t)p[1] << 8;
870 v |= (u_int32_t)p[2] << 16;
871 v |= (u_int32_t)p[3] << 24;
872
873 return (v);
874}
875
Damien Miller3f941882006-03-31 23:13:02 +1100876u_int16_t
877get_u16(const void *vp)
878{
879 const u_char *p = (const u_char *)vp;
880 u_int16_t v;
881
882 v = (u_int16_t)p[0] << 8;
883 v |= (u_int16_t)p[1];
884
885 return (v);
886}
887
888void
889put_u64(void *vp, u_int64_t v)
890{
891 u_char *p = (u_char *)vp;
892
893 p[0] = (u_char)(v >> 56) & 0xff;
894 p[1] = (u_char)(v >> 48) & 0xff;
895 p[2] = (u_char)(v >> 40) & 0xff;
896 p[3] = (u_char)(v >> 32) & 0xff;
897 p[4] = (u_char)(v >> 24) & 0xff;
898 p[5] = (u_char)(v >> 16) & 0xff;
899 p[6] = (u_char)(v >> 8) & 0xff;
900 p[7] = (u_char)v & 0xff;
901}
902
903void
904put_u32(void *vp, u_int32_t v)
905{
906 u_char *p = (u_char *)vp;
907
908 p[0] = (u_char)(v >> 24) & 0xff;
909 p[1] = (u_char)(v >> 16) & 0xff;
910 p[2] = (u_char)(v >> 8) & 0xff;
911 p[3] = (u_char)v & 0xff;
912}
913
Damien Miller88856692014-04-20 13:33:19 +1000914void
915put_u32_le(void *vp, u_int32_t v)
916{
917 u_char *p = (u_char *)vp;
918
919 p[0] = (u_char)v & 0xff;
920 p[1] = (u_char)(v >> 8) & 0xff;
921 p[2] = (u_char)(v >> 16) & 0xff;
922 p[3] = (u_char)(v >> 24) & 0xff;
923}
Damien Miller3f941882006-03-31 23:13:02 +1100924
925void
926put_u16(void *vp, u_int16_t v)
927{
928 u_char *p = (u_char *)vp;
929
930 p[0] = (u_char)(v >> 8) & 0xff;
931 p[1] = (u_char)v & 0xff;
932}
Darren Tucker3fc464e2008-06-13 06:42:45 +1000933
934void
935ms_subtract_diff(struct timeval *start, int *ms)
936{
937 struct timeval diff, finish;
938
939 gettimeofday(&finish, NULL);
940 timersub(&finish, start, &diff);
941 *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
942}
943
944void
945ms_to_timeval(struct timeval *tv, int ms)
946{
947 if (ms < 0)
948 ms = 0;
949 tv->tv_sec = ms / 1000;
950 tv->tv_usec = (ms % 1000) * 1000;
951}
952
Darren Tuckerb759c9c2013-06-02 07:46:16 +1000953time_t
954monotime(void)
955{
Damien Miller795b8632014-05-21 17:12:53 +1000956#if defined(HAVE_CLOCK_GETTIME) && \
957 (defined(CLOCK_MONOTONIC) || defined(CLOCK_BOOTTIME))
Darren Tuckerb759c9c2013-06-02 07:46:16 +1000958 struct timespec ts;
Darren Tucker94396b72013-08-08 11:52:37 +1000959 static int gettime_failed = 0;
Darren Tuckerb759c9c2013-06-02 07:46:16 +1000960
Darren Tucker94396b72013-08-08 11:52:37 +1000961 if (!gettime_failed) {
Damien Miller795b8632014-05-21 17:12:53 +1000962#if defined(CLOCK_BOOTTIME)
963 if (clock_gettime(CLOCK_BOOTTIME, &ts) == 0)
964 return (ts.tv_sec);
965#endif
966#if defined(CLOCK_MONOTONIC)
Darren Tucker94396b72013-08-08 11:52:37 +1000967 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
968 return (ts.tv_sec);
Damien Miller795b8632014-05-21 17:12:53 +1000969#endif
Darren Tucker94396b72013-08-08 11:52:37 +1000970 debug3("clock_gettime: %s", strerror(errno));
971 gettime_failed = 1;
972 }
Damien Miller795b8632014-05-21 17:12:53 +1000973#endif /* HAVE_CLOCK_GETTIME && (CLOCK_MONOTONIC || CLOCK_BOOTTIME */
Darren Tucker94396b72013-08-08 11:52:37 +1000974
975 return time(NULL);
Darren Tuckerb759c9c2013-06-02 07:46:16 +1000976}
977
dtucker@openbsd.orgb8d4eaf2016-03-02 22:42:40 +0000978double
979monotime_double(void)
980{
Darren Tucker2c48bd32016-03-09 12:46:50 +1100981#if defined(HAVE_CLOCK_GETTIME) && \
982 (defined(CLOCK_MONOTONIC) || defined(CLOCK_BOOTTIME))
dtucker@openbsd.orgb8d4eaf2016-03-02 22:42:40 +0000983 struct timespec ts;
Darren Tucker2c48bd32016-03-09 12:46:50 +1100984 static int gettime_failed = 0;
dtucker@openbsd.orgb8d4eaf2016-03-02 22:42:40 +0000985
Darren Tucker2c48bd32016-03-09 12:46:50 +1100986 if (!gettime_failed) {
987#if defined(CLOCK_BOOTTIME)
988 if (clock_gettime(CLOCK_BOOTTIME, &ts) == 0)
989 return (ts.tv_sec + (double)ts.tv_nsec / 1000000000);
990#endif
991#if defined(CLOCK_MONOTONIC)
992 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
993 return (ts.tv_sec + (double)ts.tv_nsec / 1000000000);
994#endif
995 debug3("clock_gettime: %s", strerror(errno));
996 gettime_failed = 1;
997 }
998#endif /* HAVE_CLOCK_GETTIME && (CLOCK_MONOTONIC || CLOCK_BOOTTIME */
dtucker@openbsd.orgb8d4eaf2016-03-02 22:42:40 +0000999
Darren Tucker2c48bd32016-03-09 12:46:50 +11001000 return (double)time(NULL);
dtucker@openbsd.orgb8d4eaf2016-03-02 22:42:40 +00001001}
1002
Damien Miller65e42f82010-09-24 22:15:11 +10001003void
1004bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
1005{
1006 bw->buflen = buflen;
1007 bw->rate = kbps;
1008 bw->thresh = bw->rate;
1009 bw->lamt = 0;
1010 timerclear(&bw->bwstart);
1011 timerclear(&bw->bwend);
1012}
1013
1014/* Callback from read/write loop to insert bandwidth-limiting delays */
1015void
1016bandwidth_limit(struct bwlimit *bw, size_t read_len)
1017{
1018 u_int64_t waitlen;
1019 struct timespec ts, rm;
1020
1021 if (!timerisset(&bw->bwstart)) {
1022 gettimeofday(&bw->bwstart, NULL);
1023 return;
1024 }
1025
1026 bw->lamt += read_len;
1027 if (bw->lamt < bw->thresh)
1028 return;
1029
1030 gettimeofday(&bw->bwend, NULL);
1031 timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
1032 if (!timerisset(&bw->bwend))
1033 return;
1034
1035 bw->lamt *= 8;
1036 waitlen = (double)1000000L * bw->lamt / bw->rate;
1037
1038 bw->bwstart.tv_sec = waitlen / 1000000L;
1039 bw->bwstart.tv_usec = waitlen % 1000000L;
1040
1041 if (timercmp(&bw->bwstart, &bw->bwend, >)) {
1042 timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
1043
1044 /* Adjust the wait time */
1045 if (bw->bwend.tv_sec) {
1046 bw->thresh /= 2;
1047 if (bw->thresh < bw->buflen / 4)
1048 bw->thresh = bw->buflen / 4;
1049 } else if (bw->bwend.tv_usec < 10000) {
1050 bw->thresh *= 2;
1051 if (bw->thresh > bw->buflen * 8)
1052 bw->thresh = bw->buflen * 8;
1053 }
1054
1055 TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
1056 while (nanosleep(&ts, &rm) == -1) {
1057 if (errno != EINTR)
1058 break;
1059 ts = rm;
1060 }
1061 }
1062
1063 bw->lamt = 0;
1064 gettimeofday(&bw->bwstart, NULL);
1065}
Damien Miller0dac6fb2010-11-20 15:19:38 +11001066
Damien Miller2cd62932010-12-01 11:50:35 +11001067/* Make a template filename for mk[sd]temp() */
1068void
1069mktemp_proto(char *s, size_t len)
1070{
1071 const char *tmpdir;
1072 int r;
1073
1074 if ((tmpdir = getenv("TMPDIR")) != NULL) {
1075 r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1076 if (r > 0 && (size_t)r < len)
1077 return;
1078 }
1079 r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1080 if (r < 0 || (size_t)r >= len)
1081 fatal("%s: template string too short", __func__);
1082}
1083
Damien Miller0dac6fb2010-11-20 15:19:38 +11001084static const struct {
1085 const char *name;
1086 int value;
1087} ipqos[] = {
1088 { "af11", IPTOS_DSCP_AF11 },
1089 { "af12", IPTOS_DSCP_AF12 },
1090 { "af13", IPTOS_DSCP_AF13 },
Damien Miller2918e032011-09-22 21:34:35 +10001091 { "af21", IPTOS_DSCP_AF21 },
Damien Miller0dac6fb2010-11-20 15:19:38 +11001092 { "af22", IPTOS_DSCP_AF22 },
1093 { "af23", IPTOS_DSCP_AF23 },
1094 { "af31", IPTOS_DSCP_AF31 },
1095 { "af32", IPTOS_DSCP_AF32 },
1096 { "af33", IPTOS_DSCP_AF33 },
1097 { "af41", IPTOS_DSCP_AF41 },
1098 { "af42", IPTOS_DSCP_AF42 },
1099 { "af43", IPTOS_DSCP_AF43 },
1100 { "cs0", IPTOS_DSCP_CS0 },
1101 { "cs1", IPTOS_DSCP_CS1 },
1102 { "cs2", IPTOS_DSCP_CS2 },
1103 { "cs3", IPTOS_DSCP_CS3 },
1104 { "cs4", IPTOS_DSCP_CS4 },
1105 { "cs5", IPTOS_DSCP_CS5 },
1106 { "cs6", IPTOS_DSCP_CS6 },
1107 { "cs7", IPTOS_DSCP_CS7 },
1108 { "ef", IPTOS_DSCP_EF },
1109 { "lowdelay", IPTOS_LOWDELAY },
1110 { "throughput", IPTOS_THROUGHPUT },
1111 { "reliability", IPTOS_RELIABILITY },
1112 { NULL, -1 }
1113};
1114
1115int
1116parse_ipqos(const char *cp)
1117{
1118 u_int i;
1119 char *ep;
1120 long val;
1121
1122 if (cp == NULL)
1123 return -1;
1124 for (i = 0; ipqos[i].name != NULL; i++) {
1125 if (strcasecmp(cp, ipqos[i].name) == 0)
1126 return ipqos[i].value;
1127 }
1128 /* Try parsing as an integer */
1129 val = strtol(cp, &ep, 0);
1130 if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1131 return -1;
1132 return val;
1133}
1134
Damien Miller91475862011-05-05 14:14:34 +10001135const char *
1136iptos2str(int iptos)
1137{
1138 int i;
1139 static char iptos_str[sizeof "0xff"];
1140
1141 for (i = 0; ipqos[i].name != NULL; i++) {
1142 if (ipqos[i].value == iptos)
1143 return ipqos[i].name;
1144 }
1145 snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1146 return iptos_str;
1147}
Damien Millere9fc72e2013-10-15 12:14:12 +11001148
1149void
1150lowercase(char *s)
1151{
1152 for (; *s; s++)
1153 *s = tolower((u_char)*s);
1154}
Damien Miller7acefbb2014-07-18 14:11:24 +10001155
1156int
1157unix_listener(const char *path, int backlog, int unlink_first)
1158{
1159 struct sockaddr_un sunaddr;
1160 int saved_errno, sock;
1161
1162 memset(&sunaddr, 0, sizeof(sunaddr));
1163 sunaddr.sun_family = AF_UNIX;
1164 if (strlcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1165 error("%s: \"%s\" too long for Unix domain socket", __func__,
1166 path);
1167 errno = ENAMETOOLONG;
1168 return -1;
1169 }
1170
1171 sock = socket(PF_UNIX, SOCK_STREAM, 0);
1172 if (sock < 0) {
1173 saved_errno = errno;
1174 error("socket: %.100s", strerror(errno));
1175 errno = saved_errno;
1176 return -1;
1177 }
1178 if (unlink_first == 1) {
1179 if (unlink(path) != 0 && errno != ENOENT)
1180 error("unlink(%s): %.100s", path, strerror(errno));
1181 }
1182 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) < 0) {
1183 saved_errno = errno;
1184 error("bind: %.100s", strerror(errno));
1185 close(sock);
1186 error("%s: cannot bind to path: %s", __func__, path);
1187 errno = saved_errno;
1188 return -1;
1189 }
1190 if (listen(sock, backlog) < 0) {
1191 saved_errno = errno;
1192 error("listen: %.100s", strerror(errno));
1193 close(sock);
1194 unlink(path);
1195 error("%s: cannot listen on path: %s", __func__, path);
1196 errno = saved_errno;
1197 return -1;
1198 }
1199 return sock;
1200}
Damien Miller46878022014-08-30 03:29:19 +10001201
Damien Miller04ee0f82009-11-18 17:48:30 +11001202void
1203sock_set_v6only(int s)
1204{
Damien Millerd86a3ba2015-12-09 09:18:45 +11001205#if defined(IPV6_V6ONLY) && !defined(__OpenBSD__)
Damien Miller04ee0f82009-11-18 17:48:30 +11001206 int on = 1;
1207
1208 debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
1209 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
1210 error("setsockopt IPV6_V6ONLY: %s", strerror(errno));
1211#endif
1212}
djm@openbsd.org0ccbd5e2016-04-06 06:42:17 +00001213
1214/*
1215 * Compares two strings that maybe be NULL. Returns non-zero if strings
1216 * are both NULL or are identical, returns zero otherwise.
1217 */
1218static int
1219strcmp_maybe_null(const char *a, const char *b)
1220{
1221 if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1222 return 0;
1223 if (a != NULL && strcmp(a, b) != 0)
1224 return 0;
1225 return 1;
1226}
1227
1228/*
1229 * Compare two forwards, returning non-zero if they are identical or
1230 * zero otherwise.
1231 */
1232int
1233forward_equals(const struct Forward *a, const struct Forward *b)
1234{
1235 if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
1236 return 0;
1237 if (a->listen_port != b->listen_port)
1238 return 0;
1239 if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
1240 return 0;
1241 if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
1242 return 0;
1243 if (a->connect_port != b->connect_port)
1244 return 0;
1245 if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
1246 return 0;
1247 /* allocated_port and handle are not checked */
1248 return 1;
1249}
1250
dtucker@openbsd.org1c4ef0b2016-10-23 22:04:05 +00001251/* returns 1 if bind to specified port by specified user is permitted */
1252int
1253bind_permitted(int port, uid_t uid)
1254{
1255 if (port < IPPORT_RESERVED && uid != 0)
1256 return 0;
1257 return 1;
1258}
dtucker@openbsd.org7fc47662016-11-30 00:28:31 +00001259
1260/* returns 1 if process is already daemonized, 0 otherwise */
1261int
1262daemonized(void)
1263{
1264 int fd;
1265
1266 if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
1267 close(fd);
1268 return 0; /* have controlling terminal */
1269 }
1270 if (getppid() != 1)
1271 return 0; /* parent is not init */
1272 if (getsid(0) != getpid())
1273 return 0; /* not session leader */
1274 debug3("already daemonized");
1275 return 1;
1276}