blob: 1c57ce0acb7551a3c65cd1cba4535b93536284a1 [file] [log] [blame]
Damien Miller2cd62932010-12-01 11:50:35 +11001/* $OpenBSD: misc.c,v 1.84 2010/11/21 01:01:13 djm 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>
Damien Miller8dbffe72006-08-05 11:02:17 +100032#include <sys/param.h>
Damien Miller8ec8c3e2006-07-10 20:35:38 +100033
Darren Tucker5d196262006-07-12 22:15:16 +100034#include <stdarg.h>
Damien Millera7a73ee2006-08-05 11:37:59 +100035#include <stdio.h>
Damien Millere7a1e5c2006-08-05 11:34:19 +100036#include <stdlib.h>
Damien Millere3476ed2006-07-24 14:13:33 +100037#include <string.h>
Damien Millere6b3b612006-07-24 14:01:23 +100038#include <unistd.h>
Darren Tucker5d196262006-07-12 22:15:16 +100039
Damien Miller8ec8c3e2006-07-10 20:35:38 +100040#include <netinet/in.h>
Damien Miller0dac6fb2010-11-20 15:19:38 +110041#include <netinet/in_systm.h>
42#include <netinet/ip.h>
Damien Miller3a4051e2006-03-15 11:19:42 +110043#include <netinet/tcp.h>
Damien Miller8ec8c3e2006-07-10 20:35:38 +100044
Darren Tucker39972492006-07-12 22:22:46 +100045#include <errno.h>
Damien Miller57cf6382006-07-10 21:13:46 +100046#include <fcntl.h>
Darren Tucker4abde772007-12-29 02:43:51 +110047#include <netdb.h>
Damien Miller03e20032006-03-15 11:16:59 +110048#ifdef HAVE_PATHS_H
Damien Millera9263d02006-03-15 11:18:26 +110049# include <paths.h>
Damien Miller9f2abc42006-07-10 20:53:08 +100050#include <pwd.h>
Damien Miller03e20032006-03-15 11:16:59 +110051#endif
Damien Miller3beb8522006-01-02 23:40:10 +110052#ifdef SSH_TUN_OPENBSD
53#include <net/if.h>
54#endif
Damien Miller61c51502000-08-18 14:01:04 +100055
Damien Millerd7834352006-08-05 12:39:39 +100056#include "xmalloc.h"
Kevin Stevesb6e773a2001-02-04 13:20:36 +000057#include "misc.h"
Ben Lindstrom226cfa02001-01-22 05:34:40 +000058#include "log.h"
Darren Tuckerda345532006-07-10 23:04:19 +100059#include "ssh.h"
Damien Miller61c51502000-08-18 14:01:04 +100060
Ben Lindstrom4cc240d2001-07-04 04:46:56 +000061/* remove newline at end of string */
Damien Miller61c51502000-08-18 14:01:04 +100062char *
63chop(char *s)
64{
65 char *t = s;
66 while (*t) {
Ben Lindstrom1c37c6a2001-12-06 18:00:18 +000067 if (*t == '\n' || *t == '\r') {
Damien Miller61c51502000-08-18 14:01:04 +100068 *t = '\0';
69 return s;
70 }
71 t++;
72 }
73 return s;
74
75}
76
Ben Lindstrom4cc240d2001-07-04 04:46:56 +000077/* set/unset filedescriptor to non-blocking */
Damien Miller232711f2004-06-15 10:35:30 +100078int
Damien Miller61c51502000-08-18 14:01:04 +100079set_nonblock(int fd)
80{
81 int val;
Ben Lindstromc93e84c2001-05-12 00:08:37 +000082
Damien Miller61c51502000-08-18 14:01:04 +100083 val = fcntl(fd, F_GETFL, 0);
84 if (val < 0) {
85 error("fcntl(%d, F_GETFL, 0): %s", fd, strerror(errno));
Damien Miller232711f2004-06-15 10:35:30 +100086 return (-1);
Damien Miller61c51502000-08-18 14:01:04 +100087 }
Damien Miller69b69aa2000-10-28 14:19:58 +110088 if (val & O_NONBLOCK) {
Damien Miller232711f2004-06-15 10:35:30 +100089 debug3("fd %d is O_NONBLOCK", fd);
90 return (0);
Damien Miller69b69aa2000-10-28 14:19:58 +110091 }
Damien Milleref095ce2003-05-14 13:41:39 +100092 debug2("fd %d setting O_NONBLOCK", fd);
Damien Miller61c51502000-08-18 14:01:04 +100093 val |= O_NONBLOCK;
Damien Miller232711f2004-06-15 10:35:30 +100094 if (fcntl(fd, F_SETFL, val) == -1) {
95 debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
96 strerror(errno));
97 return (-1);
98 }
99 return (0);
Damien Miller61c51502000-08-18 14:01:04 +1000100}
101
Damien Miller232711f2004-06-15 10:35:30 +1000102int
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000103unset_nonblock(int fd)
104{
105 int val;
106
107 val = fcntl(fd, F_GETFL, 0);
108 if (val < 0) {
109 error("fcntl(%d, F_GETFL, 0): %s", fd, strerror(errno));
Damien Miller232711f2004-06-15 10:35:30 +1000110 return (-1);
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000111 }
112 if (!(val & O_NONBLOCK)) {
Damien Miller232711f2004-06-15 10:35:30 +1000113 debug3("fd %d is not O_NONBLOCK", fd);
114 return (0);
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000115 }
Ben Lindstrom352b1c22001-06-21 03:04:37 +0000116 debug("fd %d clearing O_NONBLOCK", fd);
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000117 val &= ~O_NONBLOCK;
Damien Miller232711f2004-06-15 10:35:30 +1000118 if (fcntl(fd, F_SETFL, val) == -1) {
119 debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
Ben Lindstrom84fcb312002-03-05 01:48:09 +0000120 fd, strerror(errno));
Damien Miller232711f2004-06-15 10:35:30 +1000121 return (-1);
122 }
123 return (0);
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000124}
125
Darren Tucker4abde772007-12-29 02:43:51 +1100126const char *
127ssh_gai_strerror(int gaierr)
128{
Darren Tucker912428c2008-01-01 20:33:35 +1100129 if (gaierr == EAI_SYSTEM)
130 return strerror(errno);
131 return gai_strerror(gaierr);
Darren Tucker4abde772007-12-29 02:43:51 +1100132}
133
Damien Miller398e1cf2002-02-05 11:52:13 +1100134/* disable nagle on socket */
135void
136set_nodelay(int fd)
137{
Ben Lindstrome86de512002-03-05 01:28:14 +0000138 int opt;
139 socklen_t optlen;
Damien Miller398e1cf2002-02-05 11:52:13 +1100140
Ben Lindstrom1ebd7a52002-02-26 18:12:51 +0000141 optlen = sizeof opt;
142 if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
Darren Tucker6db8f932003-11-03 20:07:14 +1100143 debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
Ben Lindstrom1ebd7a52002-02-26 18:12:51 +0000144 return;
145 }
146 if (opt == 1) {
147 debug2("fd %d is TCP_NODELAY", fd);
148 return;
149 }
150 opt = 1;
Ben Lindstrom1d568f92002-12-23 02:44:36 +0000151 debug2("fd %d setting TCP_NODELAY", fd);
Ben Lindstrom1ebd7a52002-02-26 18:12:51 +0000152 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
Damien Miller398e1cf2002-02-05 11:52:13 +1100153 error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
154}
155
Damien Miller61c51502000-08-18 14:01:04 +1000156/* Characters considered whitespace in strsep calls. */
157#define WHITESPACE " \t\r\n"
Damien Miller306d1182006-03-15 12:05:59 +1100158#define QUOTE "\""
Damien Miller61c51502000-08-18 14:01:04 +1000159
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000160/* return next token in configuration line */
Damien Miller61c51502000-08-18 14:01:04 +1000161char *
162strdelim(char **s)
163{
164 char *old;
165 int wspace = 0;
166
167 if (*s == NULL)
168 return NULL;
169
170 old = *s;
171
Damien Miller306d1182006-03-15 12:05:59 +1100172 *s = strpbrk(*s, WHITESPACE QUOTE "=");
Damien Miller61c51502000-08-18 14:01:04 +1000173 if (*s == NULL)
174 return (old);
175
Damien Miller306d1182006-03-15 12:05:59 +1100176 if (*s[0] == '\"') {
177 memmove(*s, *s + 1, strlen(*s)); /* move nul too */
178 /* Find matching quote */
179 if ((*s = strpbrk(*s, QUOTE)) == NULL) {
180 return (NULL); /* no matching quote */
181 } else {
182 *s[0] = '\0';
Damien Miller9308fc72010-07-16 13:56:01 +1000183 *s += strspn(*s + 1, WHITESPACE) + 1;
Damien Miller306d1182006-03-15 12:05:59 +1100184 return (old);
185 }
186 }
187
Damien Miller61c51502000-08-18 14:01:04 +1000188 /* Allow only one '=' to be skipped */
189 if (*s[0] == '=')
190 wspace = 1;
191 *s[0] = '\0';
192
Damien Miller306d1182006-03-15 12:05:59 +1100193 /* Skip any extra whitespace after first token */
Damien Miller61c51502000-08-18 14:01:04 +1000194 *s += strspn(*s + 1, WHITESPACE) + 1;
195 if (*s[0] == '=' && !wspace)
196 *s += strspn(*s + 1, WHITESPACE) + 1;
197
198 return (old);
199}
Kevin Stevesb6e773a2001-02-04 13:20:36 +0000200
Ben Lindstrom086cf212001-03-05 05:56:40 +0000201struct passwd *
202pwcopy(struct passwd *pw)
203{
Damien Miller07d86be2006-03-26 14:19:21 +1100204 struct passwd *copy = xcalloc(1, sizeof(*copy));
Ben Lindstrom40304422001-03-05 06:22:01 +0000205
Ben Lindstrom086cf212001-03-05 05:56:40 +0000206 copy->pw_name = xstrdup(pw->pw_name);
207 copy->pw_passwd = xstrdup(pw->pw_passwd);
Ben Lindstrom40304422001-03-05 06:22:01 +0000208 copy->pw_gecos = xstrdup(pw->pw_gecos);
Ben Lindstrom086cf212001-03-05 05:56:40 +0000209 copy->pw_uid = pw->pw_uid;
210 copy->pw_gid = pw->pw_gid;
Kevin Steves82456952001-06-22 21:14:18 +0000211#ifdef HAVE_PW_EXPIRE_IN_PASSWD
Ben Lindstrom3af4d462001-06-21 03:11:27 +0000212 copy->pw_expire = pw->pw_expire;
Kevin Steves82456952001-06-22 21:14:18 +0000213#endif
214#ifdef HAVE_PW_CHANGE_IN_PASSWD
Ben Lindstrom3af4d462001-06-21 03:11:27 +0000215 copy->pw_change = pw->pw_change;
Kevin Steves82456952001-06-22 21:14:18 +0000216#endif
Ben Lindstrom0f68db42001-03-05 07:57:09 +0000217#ifdef HAVE_PW_CLASS_IN_PASSWD
Ben Lindstrom086cf212001-03-05 05:56:40 +0000218 copy->pw_class = xstrdup(pw->pw_class);
Ben Lindstrom0f68db42001-03-05 07:57:09 +0000219#endif
Ben Lindstrom086cf212001-03-05 05:56:40 +0000220 copy->pw_dir = xstrdup(pw->pw_dir);
221 copy->pw_shell = xstrdup(pw->pw_shell);
222 return copy;
223}
224
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000225/*
226 * Convert ASCII string to TCP/IP port number.
Damien Miller3dc71ad2009-01-28 16:31:22 +1100227 * Port must be >=0 and <=65535.
228 * Return -1 if invalid.
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000229 */
230int
231a2port(const char *s)
Ben Lindstrom19066a12001-04-12 23:39:26 +0000232{
Damien Miller3dc71ad2009-01-28 16:31:22 +1100233 long long port;
234 const char *errstr;
Ben Lindstrom19066a12001-04-12 23:39:26 +0000235
Damien Miller3dc71ad2009-01-28 16:31:22 +1100236 port = strtonum(s, 0, 65535, &errstr);
237 if (errstr != NULL)
238 return -1;
239 return (int)port;
Ben Lindstrom19066a12001-04-12 23:39:26 +0000240}
241
Damien Millerd27b9472005-12-13 19:29:02 +1100242int
243a2tun(const char *s, int *remote)
244{
245 const char *errstr = NULL;
246 char *sp, *ep;
247 int tun;
248
249 if (remote != NULL) {
Damien Miller7b58e802005-12-13 19:33:19 +1100250 *remote = SSH_TUNID_ANY;
Damien Millerd27b9472005-12-13 19:29:02 +1100251 sp = xstrdup(s);
252 if ((ep = strchr(sp, ':')) == NULL) {
253 xfree(sp);
254 return (a2tun(s, NULL));
255 }
256 ep[0] = '\0'; ep++;
257 *remote = a2tun(ep, NULL);
258 tun = a2tun(sp, NULL);
259 xfree(sp);
Damien Miller7b58e802005-12-13 19:33:19 +1100260 return (*remote == SSH_TUNID_ERR ? *remote : tun);
Damien Millerd27b9472005-12-13 19:29:02 +1100261 }
262
263 if (strcasecmp(s, "any") == 0)
Damien Miller7b58e802005-12-13 19:33:19 +1100264 return (SSH_TUNID_ANY);
Damien Millerd27b9472005-12-13 19:29:02 +1100265
Damien Miller7b58e802005-12-13 19:33:19 +1100266 tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
267 if (errstr != NULL)
268 return (SSH_TUNID_ERR);
Damien Millerd27b9472005-12-13 19:29:02 +1100269
270 return (tun);
271}
272
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000273#define SECONDS 1
274#define MINUTES (SECONDS * 60)
275#define HOURS (MINUTES * 60)
276#define DAYS (HOURS * 24)
277#define WEEKS (DAYS * 7)
278
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000279/*
280 * Convert a time string into seconds; format is
281 * a sequence of:
282 * time[qualifier]
283 *
284 * Valid time qualifiers are:
285 * <none> seconds
286 * s|S seconds
287 * m|M minutes
288 * h|H hours
289 * d|D days
290 * w|W weeks
291 *
292 * Examples:
293 * 90m 90 minutes
294 * 1h30m 90 minutes
295 * 2d 2 days
296 * 1w 1 week
297 *
298 * Return -1 if time string is invalid.
299 */
300long
301convtime(const char *s)
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000302{
303 long total, secs;
304 const char *p;
305 char *endp;
306
307 errno = 0;
308 total = 0;
309 p = s;
310
311 if (p == NULL || *p == '\0')
312 return -1;
313
314 while (*p) {
315 secs = strtol(p, &endp, 10);
316 if (p == endp ||
317 (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
318 secs < 0)
319 return -1;
320
321 switch (*endp++) {
322 case '\0':
323 endp--;
Damien Miller69b72032006-03-26 14:02:35 +1100324 break;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000325 case 's':
326 case 'S':
327 break;
328 case 'm':
329 case 'M':
330 secs *= MINUTES;
331 break;
332 case 'h':
333 case 'H':
334 secs *= HOURS;
335 break;
336 case 'd':
337 case 'D':
338 secs *= DAYS;
339 break;
340 case 'w':
341 case 'W':
342 secs *= WEEKS;
343 break;
344 default:
345 return -1;
346 }
347 total += secs;
348 if (total < 0)
349 return -1;
350 p = endp;
351 }
352
353 return total;
354}
355
Damien Millerf91ee4c2005-03-01 21:24:33 +1100356/*
Darren Tuckerda345532006-07-10 23:04:19 +1000357 * Returns a standardized host+port identifier string.
358 * Caller must free returned string.
359 */
360char *
361put_host_port(const char *host, u_short port)
362{
363 char *hoststr;
364
365 if (port == 0 || port == SSH_DEFAULT_PORT)
366 return(xstrdup(host));
367 if (asprintf(&hoststr, "[%s]:%d", host, (int)port) < 0)
368 fatal("put_host_port: asprintf: %s", strerror(errno));
369 debug3("put_host_port: %s", hoststr);
370 return hoststr;
371}
372
373/*
Damien Millerf91ee4c2005-03-01 21:24:33 +1100374 * Search for next delimiter between hostnames/addresses and ports.
375 * Argument may be modified (for termination).
376 * Returns *cp if parsing succeeds.
377 * *cp is set to the start of the next delimiter, if one was found.
378 * If this is the last field, *cp is set to NULL.
379 */
380char *
381hpdelim(char **cp)
382{
383 char *s, *old;
384
385 if (cp == NULL || *cp == NULL)
386 return NULL;
387
388 old = s = *cp;
389 if (*s == '[') {
390 if ((s = strchr(s, ']')) == NULL)
391 return NULL;
392 else
393 s++;
394 } else if ((s = strpbrk(s, ":/")) == NULL)
395 s = *cp + strlen(*cp); /* skip to end (see first case below) */
396
397 switch (*s) {
398 case '\0':
399 *cp = NULL; /* no more fields*/
400 break;
Darren Tucker47eede72005-03-14 23:08:12 +1100401
Damien Millerf91ee4c2005-03-01 21:24:33 +1100402 case ':':
403 case '/':
404 *s = '\0'; /* terminate */
405 *cp = s + 1;
406 break;
Darren Tucker47eede72005-03-14 23:08:12 +1100407
Damien Millerf91ee4c2005-03-01 21:24:33 +1100408 default:
409 return NULL;
410 }
411
412 return old;
413}
414
Ben Lindstrom4529b702001-05-03 23:39:53 +0000415char *
416cleanhostname(char *host)
417{
418 if (*host == '[' && host[strlen(host) - 1] == ']') {
419 host[strlen(host) - 1] = '\0';
420 return (host + 1);
421 } else
422 return host;
423}
424
425char *
426colon(char *cp)
427{
428 int flag = 0;
429
430 if (*cp == ':') /* Leading colon is part of file name. */
Damien Miller2e774462010-06-26 09:30:47 +1000431 return NULL;
Ben Lindstrom4529b702001-05-03 23:39:53 +0000432 if (*cp == '[')
433 flag = 1;
434
435 for (; *cp; ++cp) {
436 if (*cp == '@' && *(cp+1) == '[')
437 flag = 1;
438 if (*cp == ']' && *(cp+1) == ':' && flag)
439 return (cp+1);
440 if (*cp == ':' && !flag)
441 return (cp);
442 if (*cp == '/')
Damien Miller2e774462010-06-26 09:30:47 +1000443 return NULL;
Ben Lindstrom4529b702001-05-03 23:39:53 +0000444 }
Damien Miller2e774462010-06-26 09:30:47 +1000445 return NULL;
Ben Lindstrom4529b702001-05-03 23:39:53 +0000446}
447
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000448/* function to assist building execv() arguments */
Ben Lindstrom387c4722001-05-08 20:27:25 +0000449void
450addargs(arglist *args, char *fmt, ...)
451{
452 va_list ap;
Damien Miller3eec6b72006-01-31 21:49:27 +1100453 char *cp;
Darren Tuckerc7a6fc42004-08-13 21:18:00 +1000454 u_int nalloc;
Damien Miller3eec6b72006-01-31 21:49:27 +1100455 int r;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000456
457 va_start(ap, fmt);
Damien Miller3eec6b72006-01-31 21:49:27 +1100458 r = vasprintf(&cp, fmt, ap);
Ben Lindstrom387c4722001-05-08 20:27:25 +0000459 va_end(ap);
Damien Miller3eec6b72006-01-31 21:49:27 +1100460 if (r == -1)
461 fatal("addargs: argument too long");
Ben Lindstrom387c4722001-05-08 20:27:25 +0000462
Darren Tuckerfb16b242003-09-22 21:04:23 +1000463 nalloc = args->nalloc;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000464 if (args->list == NULL) {
Darren Tuckerfb16b242003-09-22 21:04:23 +1000465 nalloc = 32;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000466 args->num = 0;
Darren Tuckerfb16b242003-09-22 21:04:23 +1000467 } else if (args->num+2 >= nalloc)
468 nalloc *= 2;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000469
Damien Miller36812092006-03-26 14:22:47 +1100470 args->list = xrealloc(args->list, nalloc, sizeof(char *));
Darren Tuckerfb16b242003-09-22 21:04:23 +1000471 args->nalloc = nalloc;
Damien Miller3eec6b72006-01-31 21:49:27 +1100472 args->list[args->num++] = cp;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000473 args->list[args->num] = NULL;
474}
Darren Tucker22cc7412004-12-06 22:47:41 +1100475
Damien Miller3eec6b72006-01-31 21:49:27 +1100476void
477replacearg(arglist *args, u_int which, char *fmt, ...)
478{
479 va_list ap;
480 char *cp;
481 int r;
482
483 va_start(ap, fmt);
484 r = vasprintf(&cp, fmt, ap);
485 va_end(ap);
486 if (r == -1)
487 fatal("replacearg: argument too long");
488
489 if (which >= args->num)
490 fatal("replacearg: tried to replace invalid arg %d >= %d",
491 which, args->num);
492 xfree(args->list[which]);
493 args->list[which] = cp;
494}
495
496void
497freeargs(arglist *args)
498{
499 u_int i;
500
501 if (args->list != NULL) {
502 for (i = 0; i < args->num; i++)
503 xfree(args->list[i]);
504 xfree(args->list);
505 args->nalloc = args->num = 0;
506 args->list = NULL;
507 }
508}
509
Darren Tucker22cc7412004-12-06 22:47:41 +1100510/*
Damien Miller5fd38c02005-05-26 12:02:14 +1000511 * Expands tildes in the file name. Returns data allocated by xmalloc.
512 * Warning: this calls getpw*.
513 */
514char *
515tilde_expand_filename(const char *filename, uid_t uid)
516{
517 const char *path;
518 char user[128], ret[MAXPATHLEN];
519 struct passwd *pw;
Damien Millereccb9de2005-06-17 12:59:34 +1000520 u_int len, slash;
Damien Miller5fd38c02005-05-26 12:02:14 +1000521
522 if (*filename != '~')
523 return (xstrdup(filename));
524 filename++;
525
526 path = strchr(filename, '/');
527 if (path != NULL && path > filename) { /* ~user/path */
Damien Millereccb9de2005-06-17 12:59:34 +1000528 slash = path - filename;
529 if (slash > sizeof(user) - 1)
Damien Miller5fd38c02005-05-26 12:02:14 +1000530 fatal("tilde_expand_filename: ~username too long");
Damien Millereccb9de2005-06-17 12:59:34 +1000531 memcpy(user, filename, slash);
532 user[slash] = '\0';
Damien Miller5fd38c02005-05-26 12:02:14 +1000533 if ((pw = getpwnam(user)) == NULL)
534 fatal("tilde_expand_filename: No such user %s", user);
535 } else if ((pw = getpwuid(uid)) == NULL) /* ~/path */
Darren Tucker7517b5b2008-06-13 14:48:59 +1000536 fatal("tilde_expand_filename: No such uid %ld", (long)uid);
Damien Miller5fd38c02005-05-26 12:02:14 +1000537
538 if (strlcpy(ret, pw->pw_dir, sizeof(ret)) >= sizeof(ret))
539 fatal("tilde_expand_filename: Path too long");
540
541 /* Make sure directory has a trailing '/' */
542 len = strlen(pw->pw_dir);
543 if ((len == 0 || pw->pw_dir[len - 1] != '/') &&
544 strlcat(ret, "/", sizeof(ret)) >= sizeof(ret))
545 fatal("tilde_expand_filename: Path too long");
546
547 /* Skip leading '/' from specified path */
548 if (path != NULL)
549 filename = path + 1;
550 if (strlcat(ret, filename, sizeof(ret)) >= sizeof(ret))
551 fatal("tilde_expand_filename: Path too long");
552
553 return (xstrdup(ret));
554}
555
556/*
Damien Miller6476cad2005-06-16 13:18:34 +1000557 * Expand a string with a set of %[char] escapes. A number of escapes may be
558 * specified as (char *escape_chars, char *replacement) pairs. The list must
Darren Tuckerbee73d52005-07-14 17:05:02 +1000559 * be terminated by a NULL escape_char. Returns replaced string in memory
Damien Miller6476cad2005-06-16 13:18:34 +1000560 * allocated by xmalloc.
561 */
562char *
563percent_expand(const char *string, ...)
564{
565#define EXPAND_MAX_KEYS 16
Darren Tucker70d87692010-01-08 18:49:16 +1100566 u_int num_keys, i, j;
Damien Miller6476cad2005-06-16 13:18:34 +1000567 struct {
568 const char *key;
569 const char *repl;
570 } keys[EXPAND_MAX_KEYS];
Damien Miller6476cad2005-06-16 13:18:34 +1000571 char buf[4096];
572 va_list ap;
573
574 /* Gather keys */
575 va_start(ap, string);
576 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
577 keys[num_keys].key = va_arg(ap, char *);
578 if (keys[num_keys].key == NULL)
579 break;
580 keys[num_keys].repl = va_arg(ap, char *);
581 if (keys[num_keys].repl == NULL)
Darren Tucker70d87692010-01-08 18:49:16 +1100582 fatal("%s: NULL replacement", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +1000583 }
Darren Tucker70d87692010-01-08 18:49:16 +1100584 if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
585 fatal("%s: too many keys", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +1000586 va_end(ap);
587
Damien Miller6476cad2005-06-16 13:18:34 +1000588 /* Expand string */
589 *buf = '\0';
590 for (i = 0; *string != '\0'; string++) {
591 if (*string != '%') {
592 append:
593 buf[i++] = *string;
594 if (i >= sizeof(buf))
Darren Tucker70d87692010-01-08 18:49:16 +1100595 fatal("%s: string too long", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +1000596 buf[i] = '\0';
597 continue;
598 }
599 string++;
Darren Tucker70d87692010-01-08 18:49:16 +1100600 /* %% case */
Damien Miller6476cad2005-06-16 13:18:34 +1000601 if (*string == '%')
602 goto append;
603 for (j = 0; j < num_keys; j++) {
604 if (strchr(keys[j].key, *string) != NULL) {
605 i = strlcat(buf, keys[j].repl, sizeof(buf));
606 if (i >= sizeof(buf))
Darren Tucker70d87692010-01-08 18:49:16 +1100607 fatal("%s: string too long", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +1000608 break;
609 }
610 }
611 if (j >= num_keys)
Darren Tucker70d87692010-01-08 18:49:16 +1100612 fatal("%s: unknown key %%%c", __func__, *string);
Damien Miller6476cad2005-06-16 13:18:34 +1000613 }
614 return (xstrdup(buf));
615#undef EXPAND_MAX_KEYS
616}
617
618/*
Darren Tucker22cc7412004-12-06 22:47:41 +1100619 * Read an entire line from a public key file into a static buffer, discarding
620 * lines that exceed the buffer size. Returns 0 on success, -1 on failure.
621 */
622int
623read_keyfile_line(FILE *f, const char *filename, char *buf, size_t bufsz,
Darren Tuckerf0f90982004-12-11 13:39:50 +1100624 u_long *lineno)
Darren Tucker22cc7412004-12-06 22:47:41 +1100625{
626 while (fgets(buf, bufsz, f) != NULL) {
Damien Miller3ca8b772007-01-05 16:24:47 +1100627 if (buf[0] == '\0')
628 continue;
Darren Tucker22cc7412004-12-06 22:47:41 +1100629 (*lineno)++;
630 if (buf[strlen(buf) - 1] == '\n' || feof(f)) {
631 return 0;
632 } else {
Darren Tuckerf0f90982004-12-11 13:39:50 +1100633 debug("%s: %s line %lu exceeds size limit", __func__,
634 filename, *lineno);
Darren Tucker22cc7412004-12-06 22:47:41 +1100635 /* discard remainder of line */
Darren Tucker47eede72005-03-14 23:08:12 +1100636 while (fgetc(f) != '\n' && !feof(f))
Darren Tucker22cc7412004-12-06 22:47:41 +1100637 ; /* nothing */
638 }
639 }
640 return -1;
641}
Damien Miller13390022005-07-06 09:44:19 +1000642
Damien Millerd27b9472005-12-13 19:29:02 +1100643int
Damien Miller7b58e802005-12-13 19:33:19 +1100644tun_open(int tun, int mode)
Damien Millerd27b9472005-12-13 19:29:02 +1100645{
Damien Miller62a31c92005-12-13 20:44:13 +1100646#if defined(CUSTOM_SYS_TUN_OPEN)
647 return (sys_tun_open(tun, mode));
Damien Miller2dcddbf2006-01-01 19:47:05 +1100648#elif defined(SSH_TUN_OPENBSD)
Damien Miller7b58e802005-12-13 19:33:19 +1100649 struct ifreq ifr;
Damien Millerd27b9472005-12-13 19:29:02 +1100650 char name[100];
Damien Miller7b58e802005-12-13 19:33:19 +1100651 int fd = -1, sock;
Damien Millerd27b9472005-12-13 19:29:02 +1100652
Damien Miller7b58e802005-12-13 19:33:19 +1100653 /* Open the tunnel device */
654 if (tun <= SSH_TUNID_MAX) {
Damien Millerd27b9472005-12-13 19:29:02 +1100655 snprintf(name, sizeof(name), "/dev/tun%d", tun);
Damien Miller7b58e802005-12-13 19:33:19 +1100656 fd = open(name, O_RDWR);
657 } else if (tun == SSH_TUNID_ANY) {
658 for (tun = 100; tun >= 0; tun--) {
659 snprintf(name, sizeof(name), "/dev/tun%d", tun);
660 if ((fd = open(name, O_RDWR)) >= 0)
661 break;
Damien Millerd27b9472005-12-13 19:29:02 +1100662 }
663 } else {
Damien Millera210d522006-01-02 23:40:30 +1100664 debug("%s: invalid tunnel %u", __func__, tun);
Damien Miller7b58e802005-12-13 19:33:19 +1100665 return (-1);
Damien Millerd27b9472005-12-13 19:29:02 +1100666 }
Damien Miller7b58e802005-12-13 19:33:19 +1100667
668 if (fd < 0) {
669 debug("%s: %s open failed: %s", __func__, name, strerror(errno));
670 return (-1);
671 }
672
673 debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
674
675 /* Set the tunnel device operation mode */
676 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "tun%d", tun);
677 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
678 goto failed;
679
680 if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1)
681 goto failed;
Damien Millera1d9a182006-01-02 23:41:21 +1100682
683 /* Set interface mode */
684 ifr.ifr_flags &= ~IFF_UP;
685 if (mode == SSH_TUNMODE_ETHERNET)
Damien Miller7b58e802005-12-13 19:33:19 +1100686 ifr.ifr_flags |= IFF_LINK0;
Damien Millera1d9a182006-01-02 23:41:21 +1100687 else
688 ifr.ifr_flags &= ~IFF_LINK0;
689 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1)
690 goto failed;
691
692 /* Bring interface up */
Damien Miller7b58e802005-12-13 19:33:19 +1100693 ifr.ifr_flags |= IFF_UP;
694 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1)
695 goto failed;
696
697 close(sock);
698 return (fd);
699
700 failed:
701 if (fd >= 0)
702 close(fd);
703 if (sock >= 0)
704 close(sock);
705 debug("%s: failed to set %s mode %d: %s", __func__, name,
706 mode, strerror(errno));
Damien Millerd27b9472005-12-13 19:29:02 +1100707 return (-1);
Damien Miller62a31c92005-12-13 20:44:13 +1100708#else
709 error("Tunnel interfaces are not supported on this platform");
710 return (-1);
711#endif
Damien Millerd27b9472005-12-13 19:29:02 +1100712}
713
Darren Tuckerce321d82005-10-03 18:11:24 +1000714void
715sanitise_stdfd(void)
716{
Damien Miller72c5b7d2006-01-06 14:50:44 +1100717 int nullfd, dupfd;
Darren Tuckerce321d82005-10-03 18:11:24 +1000718
Damien Miller72c5b7d2006-01-06 14:50:44 +1100719 if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
Damien Miller9eab9562009-02-22 08:47:02 +1100720 fprintf(stderr, "Couldn't open /dev/null: %s\n",
721 strerror(errno));
Darren Tuckerce321d82005-10-03 18:11:24 +1000722 exit(1);
723 }
Damien Miller72c5b7d2006-01-06 14:50:44 +1100724 while (++dupfd <= 2) {
725 /* Only clobber closed fds */
726 if (fcntl(dupfd, F_GETFL, 0) >= 0)
727 continue;
728 if (dup2(nullfd, dupfd) == -1) {
Damien Miller9eab9562009-02-22 08:47:02 +1100729 fprintf(stderr, "dup2: %s\n", strerror(errno));
Darren Tuckerce321d82005-10-03 18:11:24 +1000730 exit(1);
731 }
Darren Tuckerce321d82005-10-03 18:11:24 +1000732 }
733 if (nullfd > 2)
734 close(nullfd);
735}
736
Damien Miller13390022005-07-06 09:44:19 +1000737char *
Damien Miller3f941882006-03-31 23:13:02 +1100738tohex(const void *vp, size_t l)
Damien Miller13390022005-07-06 09:44:19 +1000739{
Damien Miller3f941882006-03-31 23:13:02 +1100740 const u_char *p = (const u_char *)vp;
Damien Miller13390022005-07-06 09:44:19 +1000741 char b[3], *r;
Damien Miller3f941882006-03-31 23:13:02 +1100742 size_t i, hl;
743
744 if (l > 65536)
745 return xstrdup("tohex: length > 65536");
Damien Miller13390022005-07-06 09:44:19 +1000746
747 hl = l * 2 + 1;
Damien Miller07d86be2006-03-26 14:19:21 +1100748 r = xcalloc(1, hl);
Damien Miller13390022005-07-06 09:44:19 +1000749 for (i = 0; i < l; i++) {
Damien Miller3f941882006-03-31 23:13:02 +1100750 snprintf(b, sizeof(b), "%02x", p[i]);
Damien Miller13390022005-07-06 09:44:19 +1000751 strlcat(r, b, hl);
752 }
753 return (r);
754}
755
Damien Miller3f941882006-03-31 23:13:02 +1100756u_int64_t
757get_u64(const void *vp)
758{
759 const u_char *p = (const u_char *)vp;
760 u_int64_t v;
761
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];
770
771 return (v);
772}
773
774u_int32_t
775get_u32(const void *vp)
776{
777 const u_char *p = (const u_char *)vp;
778 u_int32_t v;
779
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];
784
785 return (v);
786}
787
788u_int16_t
789get_u16(const void *vp)
790{
791 const u_char *p = (const u_char *)vp;
792 u_int16_t v;
793
794 v = (u_int16_t)p[0] << 8;
795 v |= (u_int16_t)p[1];
796
797 return (v);
798}
799
800void
801put_u64(void *vp, u_int64_t v)
802{
803 u_char *p = (u_char *)vp;
804
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;
813}
814
815void
816put_u32(void *vp, u_int32_t v)
817{
818 u_char *p = (u_char *)vp;
819
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;
824}
825
826
827void
828put_u16(void *vp, u_int16_t v)
829{
830 u_char *p = (u_char *)vp;
831
832 p[0] = (u_char)(v >> 8) & 0xff;
833 p[1] = (u_char)v & 0xff;
834}
Darren Tucker3fc464e2008-06-13 06:42:45 +1000835
836void
837ms_subtract_diff(struct timeval *start, int *ms)
838{
839 struct timeval diff, finish;
840
841 gettimeofday(&finish, NULL);
842 timersub(&finish, start, &diff);
843 *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
844}
845
846void
847ms_to_timeval(struct timeval *tv, int ms)
848{
849 if (ms < 0)
850 ms = 0;
851 tv->tv_sec = ms / 1000;
852 tv->tv_usec = (ms % 1000) * 1000;
853}
854
Damien Miller65e42f82010-09-24 22:15:11 +1000855void
856bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
857{
858 bw->buflen = buflen;
859 bw->rate = kbps;
860 bw->thresh = bw->rate;
861 bw->lamt = 0;
862 timerclear(&bw->bwstart);
863 timerclear(&bw->bwend);
864}
865
866/* Callback from read/write loop to insert bandwidth-limiting delays */
867void
868bandwidth_limit(struct bwlimit *bw, size_t read_len)
869{
870 u_int64_t waitlen;
871 struct timespec ts, rm;
872
873 if (!timerisset(&bw->bwstart)) {
874 gettimeofday(&bw->bwstart, NULL);
875 return;
876 }
877
878 bw->lamt += read_len;
879 if (bw->lamt < bw->thresh)
880 return;
881
882 gettimeofday(&bw->bwend, NULL);
883 timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
884 if (!timerisset(&bw->bwend))
885 return;
886
887 bw->lamt *= 8;
888 waitlen = (double)1000000L * bw->lamt / bw->rate;
889
890 bw->bwstart.tv_sec = waitlen / 1000000L;
891 bw->bwstart.tv_usec = waitlen % 1000000L;
892
893 if (timercmp(&bw->bwstart, &bw->bwend, >)) {
894 timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
895
896 /* Adjust the wait time */
897 if (bw->bwend.tv_sec) {
898 bw->thresh /= 2;
899 if (bw->thresh < bw->buflen / 4)
900 bw->thresh = bw->buflen / 4;
901 } else if (bw->bwend.tv_usec < 10000) {
902 bw->thresh *= 2;
903 if (bw->thresh > bw->buflen * 8)
904 bw->thresh = bw->buflen * 8;
905 }
906
907 TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
908 while (nanosleep(&ts, &rm) == -1) {
909 if (errno != EINTR)
910 break;
911 ts = rm;
912 }
913 }
914
915 bw->lamt = 0;
916 gettimeofday(&bw->bwstart, NULL);
917}
Damien Miller0dac6fb2010-11-20 15:19:38 +1100918
Damien Miller2cd62932010-12-01 11:50:35 +1100919/* Make a template filename for mk[sd]temp() */
920void
921mktemp_proto(char *s, size_t len)
922{
923 const char *tmpdir;
924 int r;
925
926 if ((tmpdir = getenv("TMPDIR")) != NULL) {
927 r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
928 if (r > 0 && (size_t)r < len)
929 return;
930 }
931 r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
932 if (r < 0 || (size_t)r >= len)
933 fatal("%s: template string too short", __func__);
934}
935
Damien Miller0dac6fb2010-11-20 15:19:38 +1100936static const struct {
937 const char *name;
938 int value;
939} ipqos[] = {
940 { "af11", IPTOS_DSCP_AF11 },
941 { "af12", IPTOS_DSCP_AF12 },
942 { "af13", IPTOS_DSCP_AF13 },
943 { "af14", IPTOS_DSCP_AF21 },
944 { "af22", IPTOS_DSCP_AF22 },
945 { "af23", IPTOS_DSCP_AF23 },
946 { "af31", IPTOS_DSCP_AF31 },
947 { "af32", IPTOS_DSCP_AF32 },
948 { "af33", IPTOS_DSCP_AF33 },
949 { "af41", IPTOS_DSCP_AF41 },
950 { "af42", IPTOS_DSCP_AF42 },
951 { "af43", IPTOS_DSCP_AF43 },
952 { "cs0", IPTOS_DSCP_CS0 },
953 { "cs1", IPTOS_DSCP_CS1 },
954 { "cs2", IPTOS_DSCP_CS2 },
955 { "cs3", IPTOS_DSCP_CS3 },
956 { "cs4", IPTOS_DSCP_CS4 },
957 { "cs5", IPTOS_DSCP_CS5 },
958 { "cs6", IPTOS_DSCP_CS6 },
959 { "cs7", IPTOS_DSCP_CS7 },
960 { "ef", IPTOS_DSCP_EF },
961 { "lowdelay", IPTOS_LOWDELAY },
962 { "throughput", IPTOS_THROUGHPUT },
963 { "reliability", IPTOS_RELIABILITY },
964 { NULL, -1 }
965};
966
967int
968parse_ipqos(const char *cp)
969{
970 u_int i;
971 char *ep;
972 long val;
973
974 if (cp == NULL)
975 return -1;
976 for (i = 0; ipqos[i].name != NULL; i++) {
977 if (strcasecmp(cp, ipqos[i].name) == 0)
978 return ipqos[i].value;
979 }
980 /* Try parsing as an integer */
981 val = strtol(cp, &ep, 0);
982 if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
983 return -1;
984 return val;
985}
986
Damien Miller04ee0f82009-11-18 17:48:30 +1100987void
988sock_set_v6only(int s)
989{
990#ifdef IPV6_V6ONLY
991 int on = 1;
992
993 debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
994 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
995 error("setsockopt IPV6_V6ONLY: %s", strerror(errno));
996#endif
997}