blob: 78c00eb8e38a2986d475409d6909325c43b0b404 [file] [log] [blame]
djm@openbsd.org5485f8d2019-09-03 08:32:11 +00001/* $OpenBSD: misc.c,v 1.142 2019/09/03 08:32:11 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>
djm@openbsd.orgde4ae072017-08-18 05:36:45 +000032#include <sys/stat.h>
dtucker@openbsd.org65a3c0d2016-01-20 09:22:39 +000033#include <sys/time.h>
djm@openbsd.orgde4ae072017-08-18 05:36:45 +000034#include <sys/wait.h>
Damien Miller7acefbb2014-07-18 14:11:24 +100035#include <sys/un.h>
Damien Miller8ec8c3e2006-07-10 20:35:38 +100036
deraadt@openbsd.org2ae4f332015-01-16 06:40:12 +000037#include <limits.h>
djm@openbsd.orgde4ae072017-08-18 05:36:45 +000038#ifdef HAVE_LIBGEN_H
39# include <libgen.h>
40#endif
Darren Tucker6fc7e1c2019-10-28 15:53:25 +110041#ifdef HAVE_POLL_H
djm@openbsd.org0a843d92018-12-27 03:25:24 +000042#include <poll.h>
Darren Tucker6fc7e1c2019-10-28 15:53:25 +110043#endif
djm@openbsd.orgde4ae072017-08-18 05:36:45 +000044#include <signal.h>
Darren Tucker5d196262006-07-12 22:15:16 +100045#include <stdarg.h>
Damien Millera7a73ee2006-08-05 11:37:59 +100046#include <stdio.h>
Damien Millere7a1e5c2006-08-05 11:34:19 +100047#include <stdlib.h>
Damien Millere3476ed2006-07-24 14:13:33 +100048#include <string.h>
Damien Miller1708cb72011-01-13 12:21:34 +110049#include <time.h>
Damien Millere6b3b612006-07-24 14:01:23 +100050#include <unistd.h>
Darren Tucker5d196262006-07-12 22:15:16 +100051
Damien Miller8ec8c3e2006-07-10 20:35:38 +100052#include <netinet/in.h>
Damien Miller0dac6fb2010-11-20 15:19:38 +110053#include <netinet/in_systm.h>
54#include <netinet/ip.h>
Damien Miller3a4051e2006-03-15 11:19:42 +110055#include <netinet/tcp.h>
naddy@openbsd.org25813332018-10-05 14:26:09 +000056#include <arpa/inet.h>
Damien Miller8ec8c3e2006-07-10 20:35:38 +100057
Damien Millere9fc72e2013-10-15 12:14:12 +110058#include <ctype.h>
Darren Tucker39972492006-07-12 22:22:46 +100059#include <errno.h>
Damien Miller57cf6382006-07-10 21:13:46 +100060#include <fcntl.h>
Darren Tucker4abde772007-12-29 02:43:51 +110061#include <netdb.h>
Damien Miller03e20032006-03-15 11:16:59 +110062#ifdef HAVE_PATHS_H
Damien Millera9263d02006-03-15 11:18:26 +110063# include <paths.h>
Damien Miller9f2abc42006-07-10 20:53:08 +100064#include <pwd.h>
Damien Miller03e20032006-03-15 11:16:59 +110065#endif
Damien Miller3beb8522006-01-02 23:40:10 +110066#ifdef SSH_TUN_OPENBSD
67#include <net/if.h>
68#endif
Damien Miller61c51502000-08-18 14:01:04 +100069
Damien Millerd7834352006-08-05 12:39:39 +100070#include "xmalloc.h"
Kevin Stevesb6e773a2001-02-04 13:20:36 +000071#include "misc.h"
Ben Lindstrom226cfa02001-01-22 05:34:40 +000072#include "log.h"
Darren Tuckerda345532006-07-10 23:04:19 +100073#include "ssh.h"
djm@openbsd.orgde4ae072017-08-18 05:36:45 +000074#include "sshbuf.h"
75#include "ssherr.h"
Damien Miller07949bf2017-08-23 20:13:18 +100076#include "platform.h"
Damien Miller61c51502000-08-18 14:01:04 +100077
Ben Lindstrom4cc240d2001-07-04 04:46:56 +000078/* remove newline at end of string */
Damien Miller61c51502000-08-18 14:01:04 +100079char *
80chop(char *s)
81{
82 char *t = s;
83 while (*t) {
Ben Lindstrom1c37c6a2001-12-06 18:00:18 +000084 if (*t == '\n' || *t == '\r') {
Damien Miller61c51502000-08-18 14:01:04 +100085 *t = '\0';
86 return s;
87 }
88 t++;
89 }
90 return s;
91
92}
93
Ben Lindstrom4cc240d2001-07-04 04:46:56 +000094/* set/unset filedescriptor to non-blocking */
Damien Miller232711f2004-06-15 10:35:30 +100095int
Damien Miller61c51502000-08-18 14:01:04 +100096set_nonblock(int fd)
97{
98 int val;
Ben Lindstromc93e84c2001-05-12 00:08:37 +000099
krw@openbsd.org574def02016-04-02 14:37:42 +0000100 val = fcntl(fd, F_GETFL);
deraadt@openbsd.org4d28fa72019-06-28 13:35:04 +0000101 if (val == -1) {
krw@openbsd.org574def02016-04-02 14:37:42 +0000102 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
Damien Miller232711f2004-06-15 10:35:30 +1000103 return (-1);
Damien Miller61c51502000-08-18 14:01:04 +1000104 }
Damien Miller69b69aa2000-10-28 14:19:58 +1100105 if (val & O_NONBLOCK) {
Damien Miller232711f2004-06-15 10:35:30 +1000106 debug3("fd %d is O_NONBLOCK", fd);
107 return (0);
Damien Miller69b69aa2000-10-28 14:19:58 +1100108 }
Damien Milleref095ce2003-05-14 13:41:39 +1000109 debug2("fd %d setting O_NONBLOCK", fd);
Damien Miller61c51502000-08-18 14:01:04 +1000110 val |= O_NONBLOCK;
Damien Miller232711f2004-06-15 10:35:30 +1000111 if (fcntl(fd, F_SETFL, val) == -1) {
112 debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
113 strerror(errno));
114 return (-1);
115 }
116 return (0);
Damien Miller61c51502000-08-18 14:01:04 +1000117}
118
Damien Miller232711f2004-06-15 10:35:30 +1000119int
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000120unset_nonblock(int fd)
121{
122 int val;
123
krw@openbsd.org574def02016-04-02 14:37:42 +0000124 val = fcntl(fd, F_GETFL);
deraadt@openbsd.org4d28fa72019-06-28 13:35:04 +0000125 if (val == -1) {
krw@openbsd.org574def02016-04-02 14:37:42 +0000126 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
Damien Miller232711f2004-06-15 10:35:30 +1000127 return (-1);
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000128 }
129 if (!(val & O_NONBLOCK)) {
Damien Miller232711f2004-06-15 10:35:30 +1000130 debug3("fd %d is not O_NONBLOCK", fd);
131 return (0);
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000132 }
Ben Lindstrom352b1c22001-06-21 03:04:37 +0000133 debug("fd %d clearing O_NONBLOCK", fd);
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000134 val &= ~O_NONBLOCK;
Damien Miller232711f2004-06-15 10:35:30 +1000135 if (fcntl(fd, F_SETFL, val) == -1) {
136 debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
Ben Lindstrom84fcb312002-03-05 01:48:09 +0000137 fd, strerror(errno));
Damien Miller232711f2004-06-15 10:35:30 +1000138 return (-1);
139 }
140 return (0);
Ben Lindstromc93e84c2001-05-12 00:08:37 +0000141}
142
Darren Tucker4abde772007-12-29 02:43:51 +1100143const char *
144ssh_gai_strerror(int gaierr)
145{
Damien Miller7313fc92013-07-18 16:13:19 +1000146 if (gaierr == EAI_SYSTEM && errno != 0)
Darren Tucker912428c2008-01-01 20:33:35 +1100147 return strerror(errno);
148 return gai_strerror(gaierr);
Darren Tucker4abde772007-12-29 02:43:51 +1100149}
150
Damien Miller398e1cf2002-02-05 11:52:13 +1100151/* disable nagle on socket */
152void
153set_nodelay(int fd)
154{
Ben Lindstrome86de512002-03-05 01:28:14 +0000155 int opt;
156 socklen_t optlen;
Damien Miller398e1cf2002-02-05 11:52:13 +1100157
Ben Lindstrom1ebd7a52002-02-26 18:12:51 +0000158 optlen = sizeof opt;
159 if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
Darren Tucker6db8f932003-11-03 20:07:14 +1100160 debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
Ben Lindstrom1ebd7a52002-02-26 18:12:51 +0000161 return;
162 }
163 if (opt == 1) {
164 debug2("fd %d is TCP_NODELAY", fd);
165 return;
166 }
167 opt = 1;
Ben Lindstrom1d568f92002-12-23 02:44:36 +0000168 debug2("fd %d setting TCP_NODELAY", fd);
Ben Lindstrom1ebd7a52002-02-26 18:12:51 +0000169 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
Damien Miller398e1cf2002-02-05 11:52:13 +1100170 error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
171}
172
djm@openbsd.orgacf559e2017-10-25 00:15:35 +0000173/* Allow local port reuse in TIME_WAIT */
174int
175set_reuseaddr(int fd)
176{
177 int on = 1;
178
179 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
180 error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
181 return -1;
182 }
183 return 0;
184}
185
djm@openbsd.org35eb33f2017-10-25 00:17:08 +0000186/* Get/set routing domain */
187char *
188get_rdomain(int fd)
189{
Damien Miller43c29bb2017-10-25 13:10:59 +1100190#if defined(HAVE_SYS_GET_RDOMAIN)
191 return sys_get_rdomain(fd);
192#elif defined(__OpenBSD__)
djm@openbsd.org35eb33f2017-10-25 00:17:08 +0000193 int rtable;
194 char *ret;
195 socklen_t len = sizeof(rtable);
196
197 if (getsockopt(fd, SOL_SOCKET, SO_RTABLE, &rtable, &len) == -1) {
198 error("Failed to get routing domain for fd %d: %s",
199 fd, strerror(errno));
200 return NULL;
201 }
202 xasprintf(&ret, "%d", rtable);
203 return ret;
Damien Miller43c29bb2017-10-25 13:10:59 +1100204#else /* defined(__OpenBSD__) */
205 return NULL;
206#endif
djm@openbsd.org35eb33f2017-10-25 00:17:08 +0000207}
208
djm@openbsd.orgacf559e2017-10-25 00:15:35 +0000209int
210set_rdomain(int fd, const char *name)
211{
Damien Miller43c29bb2017-10-25 13:10:59 +1100212#if defined(HAVE_SYS_SET_RDOMAIN)
213 return sys_set_rdomain(fd, name);
214#elif defined(__OpenBSD__)
djm@openbsd.orgacf559e2017-10-25 00:15:35 +0000215 int rtable;
216 const char *errstr;
217
218 if (name == NULL)
219 return 0; /* default table */
220
221 rtable = (int)strtonum(name, 0, 255, &errstr);
222 if (errstr != NULL) {
223 /* Shouldn't happen */
224 error("Invalid routing domain \"%s\": %s", name, errstr);
225 return -1;
226 }
227 if (setsockopt(fd, SOL_SOCKET, SO_RTABLE,
228 &rtable, sizeof(rtable)) == -1) {
229 error("Failed to set routing domain %d on fd %d: %s",
230 rtable, fd, strerror(errno));
231 return -1;
232 }
233 return 0;
Damien Miller43c29bb2017-10-25 13:10:59 +1100234#else /* defined(__OpenBSD__) */
235 error("Setting routing domain is not supported on this platform");
236 return -1;
237#endif
djm@openbsd.orgacf559e2017-10-25 00:15:35 +0000238}
239
djm@openbsd.org0a843d92018-12-27 03:25:24 +0000240/*
241 * Wait up to *timeoutp milliseconds for fd to be readable. Updates
242 * *timeoutp with time remaining.
243 * Returns 0 if fd ready or -1 on timeout or error (see errno).
244 */
245int
246waitrfd(int fd, int *timeoutp)
247{
248 struct pollfd pfd;
249 struct timeval t_start;
250 int oerrno, r;
251
252 monotime_tv(&t_start);
253 pfd.fd = fd;
254 pfd.events = POLLIN;
255 for (; *timeoutp >= 0;) {
256 r = poll(&pfd, 1, *timeoutp);
257 oerrno = errno;
258 ms_subtract_diff(&t_start, timeoutp);
259 errno = oerrno;
260 if (r > 0)
261 return 0;
262 else if (r == -1 && errno != EAGAIN)
263 return -1;
264 else if (r == 0)
265 break;
266 }
267 /* timeout */
268 errno = ETIMEDOUT;
269 return -1;
270}
271
272/*
273 * Attempt a non-blocking connect(2) to the specified address, waiting up to
274 * *timeoutp milliseconds for the connection to complete. If the timeout is
275 * <=0, then wait indefinitely.
276 *
277 * Returns 0 on success or -1 on failure.
278 */
279int
280timeout_connect(int sockfd, const struct sockaddr *serv_addr,
281 socklen_t addrlen, int *timeoutp)
282{
283 int optval = 0;
284 socklen_t optlen = sizeof(optval);
285
286 /* No timeout: just do a blocking connect() */
287 if (timeoutp == NULL || *timeoutp <= 0)
288 return connect(sockfd, serv_addr, addrlen);
289
290 set_nonblock(sockfd);
291 if (connect(sockfd, serv_addr, addrlen) == 0) {
292 /* Succeeded already? */
293 unset_nonblock(sockfd);
294 return 0;
295 } else if (errno != EINPROGRESS)
296 return -1;
297
298 if (waitrfd(sockfd, timeoutp) == -1)
299 return -1;
300
301 /* Completed or failed */
302 if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval, &optlen) == -1) {
303 debug("getsockopt: %s", strerror(errno));
304 return -1;
305 }
306 if (optval != 0) {
307 errno = optval;
308 return -1;
309 }
310 unset_nonblock(sockfd);
311 return 0;
312}
313
Damien Miller61c51502000-08-18 14:01:04 +1000314/* Characters considered whitespace in strsep calls. */
315#define WHITESPACE " \t\r\n"
Damien Miller306d1182006-03-15 12:05:59 +1100316#define QUOTE "\""
Damien Miller61c51502000-08-18 14:01:04 +1000317
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000318/* return next token in configuration line */
djm@openbsd.org7082bb52018-06-09 03:01:12 +0000319static char *
320strdelim_internal(char **s, int split_equals)
Damien Miller61c51502000-08-18 14:01:04 +1000321{
djm@openbsd.orgc7c458e2018-03-07 23:53:08 +0000322 char *old;
Damien Miller61c51502000-08-18 14:01:04 +1000323 int wspace = 0;
324
325 if (*s == NULL)
326 return NULL;
327
328 old = *s;
329
djm@openbsd.org7082bb52018-06-09 03:01:12 +0000330 *s = strpbrk(*s,
331 split_equals ? WHITESPACE QUOTE "=" : WHITESPACE QUOTE);
Damien Miller61c51502000-08-18 14:01:04 +1000332 if (*s == NULL)
333 return (old);
334
Damien Miller306d1182006-03-15 12:05:59 +1100335 if (*s[0] == '\"') {
336 memmove(*s, *s + 1, strlen(*s)); /* move nul too */
337 /* Find matching quote */
djm@openbsd.orgc7c458e2018-03-07 23:53:08 +0000338 if ((*s = strpbrk(*s, QUOTE)) == NULL) {
339 return (NULL); /* no matching quote */
340 } else {
341 *s[0] = '\0';
342 *s += strspn(*s + 1, WHITESPACE) + 1;
343 return (old);
Damien Miller306d1182006-03-15 12:05:59 +1100344 }
345 }
346
Damien Miller61c51502000-08-18 14:01:04 +1000347 /* Allow only one '=' to be skipped */
djm@openbsd.org7082bb52018-06-09 03:01:12 +0000348 if (split_equals && *s[0] == '=')
Damien Miller61c51502000-08-18 14:01:04 +1000349 wspace = 1;
350 *s[0] = '\0';
351
Damien Miller306d1182006-03-15 12:05:59 +1100352 /* Skip any extra whitespace after first token */
Damien Miller61c51502000-08-18 14:01:04 +1000353 *s += strspn(*s + 1, WHITESPACE) + 1;
djm@openbsd.org7082bb52018-06-09 03:01:12 +0000354 if (split_equals && *s[0] == '=' && !wspace)
Damien Miller61c51502000-08-18 14:01:04 +1000355 *s += strspn(*s + 1, WHITESPACE) + 1;
356
357 return (old);
358}
Kevin Stevesb6e773a2001-02-04 13:20:36 +0000359
djm@openbsd.org7082bb52018-06-09 03:01:12 +0000360/*
361 * Return next token in configuration line; splts on whitespace or a
362 * single '=' character.
363 */
364char *
365strdelim(char **s)
366{
367 return strdelim_internal(s, 1);
368}
369
370/*
371 * Return next token in configuration line; splts on whitespace only.
372 */
373char *
374strdelimw(char **s)
375{
376 return strdelim_internal(s, 0);
377}
378
Ben Lindstrom086cf212001-03-05 05:56:40 +0000379struct passwd *
380pwcopy(struct passwd *pw)
381{
Damien Miller07d86be2006-03-26 14:19:21 +1100382 struct passwd *copy = xcalloc(1, sizeof(*copy));
Ben Lindstrom40304422001-03-05 06:22:01 +0000383
Ben Lindstrom086cf212001-03-05 05:56:40 +0000384 copy->pw_name = xstrdup(pw->pw_name);
385 copy->pw_passwd = xstrdup(pw->pw_passwd);
Damien Miller6332da22013-04-23 14:25:52 +1000386#ifdef HAVE_STRUCT_PASSWD_PW_GECOS
Ben Lindstrom40304422001-03-05 06:22:01 +0000387 copy->pw_gecos = xstrdup(pw->pw_gecos);
Damien Miller6332da22013-04-23 14:25:52 +1000388#endif
Ben Lindstrom086cf212001-03-05 05:56:40 +0000389 copy->pw_uid = pw->pw_uid;
390 copy->pw_gid = pw->pw_gid;
Damien Miller6332da22013-04-23 14:25:52 +1000391#ifdef HAVE_STRUCT_PASSWD_PW_EXPIRE
Ben Lindstrom3af4d462001-06-21 03:11:27 +0000392 copy->pw_expire = pw->pw_expire;
Kevin Steves82456952001-06-22 21:14:18 +0000393#endif
Damien Miller6332da22013-04-23 14:25:52 +1000394#ifdef HAVE_STRUCT_PASSWD_PW_CHANGE
Ben Lindstrom3af4d462001-06-21 03:11:27 +0000395 copy->pw_change = pw->pw_change;
Kevin Steves82456952001-06-22 21:14:18 +0000396#endif
Damien Miller6332da22013-04-23 14:25:52 +1000397#ifdef HAVE_STRUCT_PASSWD_PW_CLASS
Ben Lindstrom086cf212001-03-05 05:56:40 +0000398 copy->pw_class = xstrdup(pw->pw_class);
Ben Lindstrom0f68db42001-03-05 07:57:09 +0000399#endif
Ben Lindstrom086cf212001-03-05 05:56:40 +0000400 copy->pw_dir = xstrdup(pw->pw_dir);
401 copy->pw_shell = xstrdup(pw->pw_shell);
402 return copy;
403}
404
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000405/*
406 * Convert ASCII string to TCP/IP port number.
Damien Miller3dc71ad2009-01-28 16:31:22 +1100407 * Port must be >=0 and <=65535.
408 * Return -1 if invalid.
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000409 */
410int
411a2port(const char *s)
Ben Lindstrom19066a12001-04-12 23:39:26 +0000412{
naddy@openbsd.org25813332018-10-05 14:26:09 +0000413 struct servent *se;
Damien Miller3dc71ad2009-01-28 16:31:22 +1100414 long long port;
415 const char *errstr;
Ben Lindstrom19066a12001-04-12 23:39:26 +0000416
Damien Miller3dc71ad2009-01-28 16:31:22 +1100417 port = strtonum(s, 0, 65535, &errstr);
naddy@openbsd.org25813332018-10-05 14:26:09 +0000418 if (errstr == NULL)
419 return (int)port;
420 if ((se = getservbyname(s, "tcp")) != NULL)
421 return ntohs(se->s_port);
422 return -1;
Ben Lindstrom19066a12001-04-12 23:39:26 +0000423}
424
Damien Millerd27b9472005-12-13 19:29:02 +1100425int
426a2tun(const char *s, int *remote)
427{
428 const char *errstr = NULL;
429 char *sp, *ep;
430 int tun;
431
432 if (remote != NULL) {
Damien Miller7b58e802005-12-13 19:33:19 +1100433 *remote = SSH_TUNID_ANY;
Damien Millerd27b9472005-12-13 19:29:02 +1100434 sp = xstrdup(s);
435 if ((ep = strchr(sp, ':')) == NULL) {
Darren Tuckera627d422013-06-02 07:31:17 +1000436 free(sp);
Damien Millerd27b9472005-12-13 19:29:02 +1100437 return (a2tun(s, NULL));
438 }
439 ep[0] = '\0'; ep++;
440 *remote = a2tun(ep, NULL);
441 tun = a2tun(sp, NULL);
Darren Tuckera627d422013-06-02 07:31:17 +1000442 free(sp);
Damien Miller7b58e802005-12-13 19:33:19 +1100443 return (*remote == SSH_TUNID_ERR ? *remote : tun);
Damien Millerd27b9472005-12-13 19:29:02 +1100444 }
445
446 if (strcasecmp(s, "any") == 0)
Damien Miller7b58e802005-12-13 19:33:19 +1100447 return (SSH_TUNID_ANY);
Damien Millerd27b9472005-12-13 19:29:02 +1100448
Damien Miller7b58e802005-12-13 19:33:19 +1100449 tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
450 if (errstr != NULL)
451 return (SSH_TUNID_ERR);
Damien Millerd27b9472005-12-13 19:29:02 +1100452
453 return (tun);
454}
455
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000456#define SECONDS 1
457#define MINUTES (SECONDS * 60)
458#define HOURS (MINUTES * 60)
459#define DAYS (HOURS * 24)
460#define WEEKS (DAYS * 7)
461
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000462/*
463 * Convert a time string into seconds; format is
464 * a sequence of:
465 * time[qualifier]
466 *
467 * Valid time qualifiers are:
468 * <none> seconds
469 * s|S seconds
470 * m|M minutes
471 * h|H hours
472 * d|D days
473 * w|W weeks
474 *
475 * Examples:
476 * 90m 90 minutes
477 * 1h30m 90 minutes
478 * 2d 2 days
479 * 1w 1 week
480 *
481 * Return -1 if time string is invalid.
482 */
483long
484convtime(const char *s)
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000485{
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000486 long total, secs, multiplier = 1;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000487 const char *p;
488 char *endp;
489
490 errno = 0;
491 total = 0;
492 p = s;
493
494 if (p == NULL || *p == '\0')
495 return -1;
496
497 while (*p) {
498 secs = strtol(p, &endp, 10);
499 if (p == endp ||
500 (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
501 secs < 0)
502 return -1;
503
504 switch (*endp++) {
505 case '\0':
506 endp--;
Damien Miller69b72032006-03-26 14:02:35 +1100507 break;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000508 case 's':
509 case 'S':
510 break;
511 case 'm':
512 case 'M':
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000513 multiplier = MINUTES;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000514 break;
515 case 'h':
516 case 'H':
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000517 multiplier = HOURS;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000518 break;
519 case 'd':
520 case 'D':
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000521 multiplier = DAYS;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000522 break;
523 case 'w':
524 case 'W':
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000525 multiplier = WEEKS;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000526 break;
527 default:
528 return -1;
529 }
dtucker@openbsd.orgc6774d22017-03-14 00:55:37 +0000530 if (secs >= LONG_MAX / multiplier)
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000531 return -1;
532 secs *= multiplier;
dtucker@openbsd.orgc6774d22017-03-14 00:55:37 +0000533 if (total >= LONG_MAX - secs)
dtucker@openbsd.orgf5746b42017-03-14 00:25:03 +0000534 return -1;
Ben Lindstrom1bda4c82001-06-05 19:59:08 +0000535 total += secs;
536 if (total < 0)
537 return -1;
538 p = endp;
539 }
540
541 return total;
542}
543
Damien Millerf91ee4c2005-03-01 21:24:33 +1100544/*
Darren Tuckerda345532006-07-10 23:04:19 +1000545 * Returns a standardized host+port identifier string.
546 * Caller must free returned string.
547 */
548char *
549put_host_port(const char *host, u_short port)
550{
551 char *hoststr;
552
553 if (port == 0 || port == SSH_DEFAULT_PORT)
554 return(xstrdup(host));
deraadt@openbsd.org5cdbaa72019-06-27 18:03:37 +0000555 if (asprintf(&hoststr, "[%s]:%d", host, (int)port) == -1)
Darren Tuckerda345532006-07-10 23:04:19 +1000556 fatal("put_host_port: asprintf: %s", strerror(errno));
557 debug3("put_host_port: %s", hoststr);
558 return hoststr;
559}
560
561/*
Damien Millerf91ee4c2005-03-01 21:24:33 +1100562 * Search for next delimiter between hostnames/addresses and ports.
563 * Argument may be modified (for termination).
564 * Returns *cp if parsing succeeds.
millert@openbsd.org887669e2017-10-21 23:06:24 +0000565 * *cp is set to the start of the next field, if one was found.
566 * The delimiter char, if present, is stored in delim.
Damien Millerf91ee4c2005-03-01 21:24:33 +1100567 * If this is the last field, *cp is set to NULL.
568 */
dtucker@openbsd.orgd05ea252019-01-23 21:50:56 +0000569char *
millert@openbsd.org887669e2017-10-21 23:06:24 +0000570hpdelim2(char **cp, char *delim)
Damien Millerf91ee4c2005-03-01 21:24:33 +1100571{
572 char *s, *old;
573
574 if (cp == NULL || *cp == NULL)
575 return NULL;
576
577 old = s = *cp;
578 if (*s == '[') {
579 if ((s = strchr(s, ']')) == NULL)
580 return NULL;
581 else
582 s++;
583 } else if ((s = strpbrk(s, ":/")) == NULL)
584 s = *cp + strlen(*cp); /* skip to end (see first case below) */
585
586 switch (*s) {
587 case '\0':
588 *cp = NULL; /* no more fields*/
589 break;
Darren Tucker47eede72005-03-14 23:08:12 +1100590
Damien Millerf91ee4c2005-03-01 21:24:33 +1100591 case ':':
592 case '/':
millert@openbsd.org887669e2017-10-21 23:06:24 +0000593 if (delim != NULL)
594 *delim = *s;
Damien Millerf91ee4c2005-03-01 21:24:33 +1100595 *s = '\0'; /* terminate */
596 *cp = s + 1;
597 break;
Darren Tucker47eede72005-03-14 23:08:12 +1100598
Damien Millerf91ee4c2005-03-01 21:24:33 +1100599 default:
600 return NULL;
601 }
602
603 return old;
604}
605
Ben Lindstrom4529b702001-05-03 23:39:53 +0000606char *
millert@openbsd.org887669e2017-10-21 23:06:24 +0000607hpdelim(char **cp)
608{
609 return hpdelim2(cp, NULL);
610}
611
612char *
Ben Lindstrom4529b702001-05-03 23:39:53 +0000613cleanhostname(char *host)
614{
615 if (*host == '[' && host[strlen(host) - 1] == ']') {
616 host[strlen(host) - 1] = '\0';
617 return (host + 1);
618 } else
619 return host;
620}
621
622char *
623colon(char *cp)
624{
625 int flag = 0;
626
627 if (*cp == ':') /* Leading colon is part of file name. */
Damien Miller2e774462010-06-26 09:30:47 +1000628 return NULL;
Ben Lindstrom4529b702001-05-03 23:39:53 +0000629 if (*cp == '[')
630 flag = 1;
631
632 for (; *cp; ++cp) {
633 if (*cp == '@' && *(cp+1) == '[')
634 flag = 1;
635 if (*cp == ']' && *(cp+1) == ':' && flag)
636 return (cp+1);
637 if (*cp == ':' && !flag)
638 return (cp);
639 if (*cp == '/')
Damien Miller2e774462010-06-26 09:30:47 +1000640 return NULL;
Ben Lindstrom4529b702001-05-03 23:39:53 +0000641 }
Damien Miller2e774462010-06-26 09:30:47 +1000642 return NULL;
Ben Lindstrom4529b702001-05-03 23:39:53 +0000643}
644
djm@openbsd.orged877ef2016-07-15 00:24:30 +0000645/*
millert@openbsd.org887669e2017-10-21 23:06:24 +0000646 * Parse a [user@]host:[path] string.
647 * Caller must free returned user, host and path.
648 * Any of the pointer return arguments may be NULL (useful for syntax checking).
649 * If user was not specified then *userp will be set to NULL.
650 * If host was not specified then *hostp will be set to NULL.
651 * If path was not specified then *pathp will be set to ".".
652 * Returns 0 on success, -1 on failure.
653 */
654int
655parse_user_host_path(const char *s, char **userp, char **hostp, char **pathp)
656{
657 char *user = NULL, *host = NULL, *path = NULL;
658 char *sdup, *tmp;
659 int ret = -1;
660
661 if (userp != NULL)
662 *userp = NULL;
663 if (hostp != NULL)
664 *hostp = NULL;
665 if (pathp != NULL)
666 *pathp = NULL;
667
millert@openbsd.orgb9903ee2017-10-24 19:41:45 +0000668 sdup = xstrdup(s);
millert@openbsd.org887669e2017-10-21 23:06:24 +0000669
670 /* Check for remote syntax: [user@]host:[path] */
671 if ((tmp = colon(sdup)) == NULL)
672 goto out;
673
674 /* Extract optional path */
675 *tmp++ = '\0';
676 if (*tmp == '\0')
677 tmp = ".";
678 path = xstrdup(tmp);
679
680 /* Extract optional user and mandatory host */
681 tmp = strrchr(sdup, '@');
682 if (tmp != NULL) {
683 *tmp++ = '\0';
684 host = xstrdup(cleanhostname(tmp));
685 if (*sdup != '\0')
686 user = xstrdup(sdup);
687 } else {
688 host = xstrdup(cleanhostname(sdup));
689 user = NULL;
690 }
691
692 /* Success */
693 if (userp != NULL) {
694 *userp = user;
695 user = NULL;
696 }
697 if (hostp != NULL) {
698 *hostp = host;
699 host = NULL;
millert@openbsd.orgb9903ee2017-10-24 19:41:45 +0000700 }
millert@openbsd.org887669e2017-10-21 23:06:24 +0000701 if (pathp != NULL) {
702 *pathp = path;
703 path = NULL;
millert@openbsd.orgb9903ee2017-10-24 19:41:45 +0000704 }
millert@openbsd.org887669e2017-10-21 23:06:24 +0000705 ret = 0;
706out:
707 free(sdup);
708 free(user);
709 free(host);
710 free(path);
711 return ret;
712}
713
714/*
djm@openbsd.orged877ef2016-07-15 00:24:30 +0000715 * Parse a [user@]host[:port] string.
716 * Caller must free returned user and host.
717 * Any of the pointer return arguments may be NULL (useful for syntax checking).
718 * If user was not specified then *userp will be set to NULL.
719 * If port was not specified then *portp will be -1.
720 * Returns 0 on success, -1 on failure.
721 */
722int
723parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
724{
725 char *sdup, *cp, *tmp;
726 char *user = NULL, *host = NULL;
727 int port = -1, ret = -1;
728
729 if (userp != NULL)
730 *userp = NULL;
731 if (hostp != NULL)
732 *hostp = NULL;
733 if (portp != NULL)
734 *portp = -1;
735
736 if ((sdup = tmp = strdup(s)) == NULL)
737 return -1;
738 /* Extract optional username */
millert@openbsd.org887669e2017-10-21 23:06:24 +0000739 if ((cp = strrchr(tmp, '@')) != NULL) {
djm@openbsd.orged877ef2016-07-15 00:24:30 +0000740 *cp = '\0';
741 if (*tmp == '\0')
742 goto out;
743 if ((user = strdup(tmp)) == NULL)
744 goto out;
745 tmp = cp + 1;
746 }
747 /* Extract mandatory hostname */
748 if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
749 goto out;
750 host = xstrdup(cleanhostname(cp));
751 /* Convert and verify optional port */
752 if (tmp != NULL && *tmp != '\0') {
753 if ((port = a2port(tmp)) <= 0)
754 goto out;
755 }
756 /* Success */
757 if (userp != NULL) {
758 *userp = user;
759 user = NULL;
760 }
761 if (hostp != NULL) {
762 *hostp = host;
763 host = NULL;
764 }
765 if (portp != NULL)
766 *portp = port;
767 ret = 0;
768 out:
769 free(sdup);
770 free(user);
771 free(host);
772 return ret;
773}
774
millert@openbsd.org887669e2017-10-21 23:06:24 +0000775/*
776 * Converts a two-byte hex string to decimal.
777 * Returns the decimal value or -1 for invalid input.
778 */
779static int
780hexchar(const char *s)
781{
782 unsigned char result[2];
783 int i;
784
785 for (i = 0; i < 2; i++) {
786 if (s[i] >= '0' && s[i] <= '9')
787 result[i] = (unsigned char)(s[i] - '0');
788 else if (s[i] >= 'a' && s[i] <= 'f')
789 result[i] = (unsigned char)(s[i] - 'a') + 10;
790 else if (s[i] >= 'A' && s[i] <= 'F')
791 result[i] = (unsigned char)(s[i] - 'A') + 10;
792 else
793 return -1;
794 }
795 return (result[0] << 4) | result[1];
796}
797
798/*
799 * Decode an url-encoded string.
800 * Returns a newly allocated string on success or NULL on failure.
801 */
802static char *
803urldecode(const char *src)
804{
805 char *ret, *dst;
806 int ch;
807
808 ret = xmalloc(strlen(src) + 1);
809 for (dst = ret; *src != '\0'; src++) {
810 switch (*src) {
811 case '+':
812 *dst++ = ' ';
813 break;
814 case '%':
815 if (!isxdigit((unsigned char)src[1]) ||
816 !isxdigit((unsigned char)src[2]) ||
817 (ch = hexchar(src + 1)) == -1) {
818 free(ret);
819 return NULL;
820 }
821 *dst++ = ch;
822 src += 2;
823 break;
824 default:
825 *dst++ = *src;
826 break;
827 }
828 }
829 *dst = '\0';
830
831 return ret;
832}
833
834/*
835 * Parse an (scp|ssh|sftp)://[user@]host[:port][/path] URI.
836 * See https://tools.ietf.org/html/draft-ietf-secsh-scp-sftp-ssh-uri-04
837 * Either user or path may be url-encoded (but not host or port).
838 * Caller must free returned user, host and path.
839 * Any of the pointer return arguments may be NULL (useful for syntax checking)
840 * but the scheme must always be specified.
841 * If user was not specified then *userp will be set to NULL.
842 * If port was not specified then *portp will be -1.
843 * If path was not specified then *pathp will be set to NULL.
844 * Returns 0 on success, 1 if non-uri/wrong scheme, -1 on error/invalid uri.
845 */
846int
847parse_uri(const char *scheme, const char *uri, char **userp, char **hostp,
848 int *portp, char **pathp)
849{
850 char *uridup, *cp, *tmp, ch;
851 char *user = NULL, *host = NULL, *path = NULL;
852 int port = -1, ret = -1;
853 size_t len;
854
855 len = strlen(scheme);
856 if (strncmp(uri, scheme, len) != 0 || strncmp(uri + len, "://", 3) != 0)
857 return 1;
858 uri += len + 3;
859
860 if (userp != NULL)
861 *userp = NULL;
862 if (hostp != NULL)
863 *hostp = NULL;
864 if (portp != NULL)
865 *portp = -1;
866 if (pathp != NULL)
867 *pathp = NULL;
868
869 uridup = tmp = xstrdup(uri);
870
871 /* Extract optional ssh-info (username + connection params) */
872 if ((cp = strchr(tmp, '@')) != NULL) {
873 char *delim;
874
875 *cp = '\0';
876 /* Extract username and connection params */
877 if ((delim = strchr(tmp, ';')) != NULL) {
878 /* Just ignore connection params for now */
879 *delim = '\0';
880 }
881 if (*tmp == '\0') {
882 /* Empty username */
883 goto out;
884 }
885 if ((user = urldecode(tmp)) == NULL)
886 goto out;
887 tmp = cp + 1;
888 }
889
890 /* Extract mandatory hostname */
891 if ((cp = hpdelim2(&tmp, &ch)) == NULL || *cp == '\0')
892 goto out;
893 host = xstrdup(cleanhostname(cp));
894 if (!valid_domain(host, 0, NULL))
895 goto out;
896
897 if (tmp != NULL && *tmp != '\0') {
898 if (ch == ':') {
899 /* Convert and verify port. */
900 if ((cp = strchr(tmp, '/')) != NULL)
901 *cp = '\0';
902 if ((port = a2port(tmp)) <= 0)
903 goto out;
904 tmp = cp ? cp + 1 : NULL;
905 }
906 if (tmp != NULL && *tmp != '\0') {
907 /* Extract optional path */
908 if ((path = urldecode(tmp)) == NULL)
909 goto out;
910 }
911 }
912
913 /* Success */
914 if (userp != NULL) {
915 *userp = user;
916 user = NULL;
917 }
918 if (hostp != NULL) {
919 *hostp = host;
920 host = NULL;
921 }
922 if (portp != NULL)
923 *portp = port;
924 if (pathp != NULL) {
925 *pathp = path;
926 path = NULL;
927 }
928 ret = 0;
929 out:
930 free(uridup);
931 free(user);
932 free(host);
933 free(path);
934 return ret;
935}
936
Ben Lindstrom4cc240d2001-07-04 04:46:56 +0000937/* function to assist building execv() arguments */
Ben Lindstrom387c4722001-05-08 20:27:25 +0000938void
939addargs(arglist *args, char *fmt, ...)
940{
941 va_list ap;
Damien Miller3eec6b72006-01-31 21:49:27 +1100942 char *cp;
Darren Tuckerc7a6fc42004-08-13 21:18:00 +1000943 u_int nalloc;
Damien Miller3eec6b72006-01-31 21:49:27 +1100944 int r;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000945
946 va_start(ap, fmt);
Damien Miller3eec6b72006-01-31 21:49:27 +1100947 r = vasprintf(&cp, fmt, ap);
Ben Lindstrom387c4722001-05-08 20:27:25 +0000948 va_end(ap);
Damien Miller3eec6b72006-01-31 21:49:27 +1100949 if (r == -1)
950 fatal("addargs: argument too long");
Ben Lindstrom387c4722001-05-08 20:27:25 +0000951
Darren Tuckerfb16b242003-09-22 21:04:23 +1000952 nalloc = args->nalloc;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000953 if (args->list == NULL) {
Darren Tuckerfb16b242003-09-22 21:04:23 +1000954 nalloc = 32;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000955 args->num = 0;
Darren Tuckerfb16b242003-09-22 21:04:23 +1000956 } else if (args->num+2 >= nalloc)
957 nalloc *= 2;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000958
deraadt@openbsd.org9e509d42017-05-31 09:15:42 +0000959 args->list = xrecallocarray(args->list, args->nalloc, nalloc, sizeof(char *));
Darren Tuckerfb16b242003-09-22 21:04:23 +1000960 args->nalloc = nalloc;
Damien Miller3eec6b72006-01-31 21:49:27 +1100961 args->list[args->num++] = cp;
Ben Lindstrom387c4722001-05-08 20:27:25 +0000962 args->list[args->num] = NULL;
963}
Darren Tucker22cc7412004-12-06 22:47:41 +1100964
Damien Miller3eec6b72006-01-31 21:49:27 +1100965void
966replacearg(arglist *args, u_int which, char *fmt, ...)
967{
968 va_list ap;
969 char *cp;
970 int r;
971
972 va_start(ap, fmt);
973 r = vasprintf(&cp, fmt, ap);
974 va_end(ap);
975 if (r == -1)
976 fatal("replacearg: argument too long");
977
978 if (which >= args->num)
979 fatal("replacearg: tried to replace invalid arg %d >= %d",
980 which, args->num);
Darren Tuckera627d422013-06-02 07:31:17 +1000981 free(args->list[which]);
Damien Miller3eec6b72006-01-31 21:49:27 +1100982 args->list[which] = cp;
983}
984
985void
986freeargs(arglist *args)
987{
988 u_int i;
989
990 if (args->list != NULL) {
991 for (i = 0; i < args->num; i++)
Darren Tuckera627d422013-06-02 07:31:17 +1000992 free(args->list[i]);
993 free(args->list);
Damien Miller3eec6b72006-01-31 21:49:27 +1100994 args->nalloc = args->num = 0;
995 args->list = NULL;
996 }
997}
998
Darren Tucker22cc7412004-12-06 22:47:41 +1100999/*
Damien Miller5fd38c02005-05-26 12:02:14 +10001000 * Expands tildes in the file name. Returns data allocated by xmalloc.
1001 * Warning: this calls getpw*.
1002 */
1003char *
1004tilde_expand_filename(const char *filename, uid_t uid)
1005{
Darren Tucker2ca51bf2013-05-16 20:22:46 +10001006 const char *path, *sep;
1007 char user[128], *ret;
Damien Miller5fd38c02005-05-26 12:02:14 +10001008 struct passwd *pw;
Damien Millereccb9de2005-06-17 12:59:34 +10001009 u_int len, slash;
Damien Miller5fd38c02005-05-26 12:02:14 +10001010
1011 if (*filename != '~')
1012 return (xstrdup(filename));
1013 filename++;
1014
1015 path = strchr(filename, '/');
1016 if (path != NULL && path > filename) { /* ~user/path */
Damien Millereccb9de2005-06-17 12:59:34 +10001017 slash = path - filename;
1018 if (slash > sizeof(user) - 1)
Damien Miller5fd38c02005-05-26 12:02:14 +10001019 fatal("tilde_expand_filename: ~username too long");
Damien Millereccb9de2005-06-17 12:59:34 +10001020 memcpy(user, filename, slash);
1021 user[slash] = '\0';
Damien Miller5fd38c02005-05-26 12:02:14 +10001022 if ((pw = getpwnam(user)) == NULL)
1023 fatal("tilde_expand_filename: No such user %s", user);
1024 } else if ((pw = getpwuid(uid)) == NULL) /* ~/path */
Darren Tucker7517b5b2008-06-13 14:48:59 +10001025 fatal("tilde_expand_filename: No such uid %ld", (long)uid);
Damien Miller5fd38c02005-05-26 12:02:14 +10001026
Damien Miller5fd38c02005-05-26 12:02:14 +10001027 /* Make sure directory has a trailing '/' */
1028 len = strlen(pw->pw_dir);
Darren Tucker026d9db2013-05-16 20:23:52 +10001029 if (len == 0 || pw->pw_dir[len - 1] != '/')
Darren Tucker2ca51bf2013-05-16 20:22:46 +10001030 sep = "/";
1031 else
1032 sep = "";
Damien Miller5fd38c02005-05-26 12:02:14 +10001033
1034 /* Skip leading '/' from specified path */
1035 if (path != NULL)
1036 filename = path + 1;
Darren Tucker2ca51bf2013-05-16 20:22:46 +10001037
deraadt@openbsd.org2ae4f332015-01-16 06:40:12 +00001038 if (xasprintf(&ret, "%s%s%s", pw->pw_dir, sep, filename) >= PATH_MAX)
Damien Miller5fd38c02005-05-26 12:02:14 +10001039 fatal("tilde_expand_filename: Path too long");
1040
Darren Tucker2ca51bf2013-05-16 20:22:46 +10001041 return (ret);
Damien Miller5fd38c02005-05-26 12:02:14 +10001042}
1043
1044/*
Damien Miller6476cad2005-06-16 13:18:34 +10001045 * Expand a string with a set of %[char] escapes. A number of escapes may be
1046 * specified as (char *escape_chars, char *replacement) pairs. The list must
Darren Tuckerbee73d52005-07-14 17:05:02 +10001047 * be terminated by a NULL escape_char. Returns replaced string in memory
Damien Miller6476cad2005-06-16 13:18:34 +10001048 * allocated by xmalloc.
1049 */
1050char *
1051percent_expand(const char *string, ...)
1052{
1053#define EXPAND_MAX_KEYS 16
djm@openbsd.orge3b6c962019-08-16 06:13:15 +00001054 u_int num_keys, i;
Damien Miller6476cad2005-06-16 13:18:34 +10001055 struct {
1056 const char *key;
1057 const char *repl;
1058 } keys[EXPAND_MAX_KEYS];
djm@openbsd.orge3b6c962019-08-16 06:13:15 +00001059 struct sshbuf *buf;
Damien Miller6476cad2005-06-16 13:18:34 +10001060 va_list ap;
djm@openbsd.orge3b6c962019-08-16 06:13:15 +00001061 int r;
1062 char *ret;
1063
1064 if ((buf = sshbuf_new()) == NULL)
1065 fatal("%s: sshbuf_new failed", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +10001066
1067 /* Gather keys */
1068 va_start(ap, string);
1069 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
1070 keys[num_keys].key = va_arg(ap, char *);
1071 if (keys[num_keys].key == NULL)
1072 break;
1073 keys[num_keys].repl = va_arg(ap, char *);
1074 if (keys[num_keys].repl == NULL)
Darren Tucker70d87692010-01-08 18:49:16 +11001075 fatal("%s: NULL replacement", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +10001076 }
Darren Tucker70d87692010-01-08 18:49:16 +11001077 if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
1078 fatal("%s: too many keys", __func__);
Damien Miller6476cad2005-06-16 13:18:34 +10001079 va_end(ap);
1080
Damien Miller6476cad2005-06-16 13:18:34 +10001081 /* Expand string */
Damien Miller6476cad2005-06-16 13:18:34 +10001082 for (i = 0; *string != '\0'; string++) {
1083 if (*string != '%') {
1084 append:
djm@openbsd.orge3b6c962019-08-16 06:13:15 +00001085 if ((r = sshbuf_put_u8(buf, *string)) != 0) {
1086 fatal("%s: sshbuf_put_u8: %s",
1087 __func__, ssh_err(r));
1088 }
Damien Miller6476cad2005-06-16 13:18:34 +10001089 continue;
1090 }
1091 string++;
Darren Tucker70d87692010-01-08 18:49:16 +11001092 /* %% case */
Damien Miller6476cad2005-06-16 13:18:34 +10001093 if (*string == '%')
1094 goto append;
tobias@openbsd.org8b56e592015-12-04 21:51:06 +00001095 if (*string == '\0')
1096 fatal("%s: invalid format", __func__);
djm@openbsd.orge3b6c962019-08-16 06:13:15 +00001097 for (i = 0; i < num_keys; i++) {
1098 if (strchr(keys[i].key, *string) != NULL) {
1099 if ((r = sshbuf_put(buf, keys[i].repl,
1100 strlen(keys[i].repl))) != 0) {
1101 fatal("%s: sshbuf_put: %s",
1102 __func__, ssh_err(r));
1103 }
Damien Miller6476cad2005-06-16 13:18:34 +10001104 break;
1105 }
1106 }
djm@openbsd.orge3b6c962019-08-16 06:13:15 +00001107 if (i >= num_keys)
Darren Tucker70d87692010-01-08 18:49:16 +11001108 fatal("%s: unknown key %%%c", __func__, *string);
Damien Miller6476cad2005-06-16 13:18:34 +10001109 }
djm@openbsd.orge3b6c962019-08-16 06:13:15 +00001110 if ((ret = sshbuf_dup_string(buf)) == NULL)
1111 fatal("%s: sshbuf_dup_string failed", __func__);
1112 sshbuf_free(buf);
1113 return ret;
Damien Miller6476cad2005-06-16 13:18:34 +10001114#undef EXPAND_MAX_KEYS
1115}
1116
Damien Millerd27b9472005-12-13 19:29:02 +11001117int
djm@openbsd.orgb7548b12017-10-23 05:08:00 +00001118tun_open(int tun, int mode, char **ifname)
Damien Millerd27b9472005-12-13 19:29:02 +11001119{
Damien Miller62a31c92005-12-13 20:44:13 +11001120#if defined(CUSTOM_SYS_TUN_OPEN)
djm@openbsd.orgb7548b12017-10-23 05:08:00 +00001121 return (sys_tun_open(tun, mode, ifname));
Damien Miller2dcddbf2006-01-01 19:47:05 +11001122#elif defined(SSH_TUN_OPENBSD)
Damien Miller7b58e802005-12-13 19:33:19 +11001123 struct ifreq ifr;
Damien Millerd27b9472005-12-13 19:29:02 +11001124 char name[100];
Damien Miller7b58e802005-12-13 19:33:19 +11001125 int fd = -1, sock;
sthen@openbsd.orga820a862015-10-24 08:34:09 +00001126 const char *tunbase = "tun";
1127
djm@openbsd.orgb7548b12017-10-23 05:08:00 +00001128 if (ifname != NULL)
1129 *ifname = NULL;
1130
sthen@openbsd.orga820a862015-10-24 08:34:09 +00001131 if (mode == SSH_TUNMODE_ETHERNET)
1132 tunbase = "tap";
Damien Millerd27b9472005-12-13 19:29:02 +11001133
Damien Miller7b58e802005-12-13 19:33:19 +11001134 /* Open the tunnel device */
1135 if (tun <= SSH_TUNID_MAX) {
sthen@openbsd.orga820a862015-10-24 08:34:09 +00001136 snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
Damien Miller7b58e802005-12-13 19:33:19 +11001137 fd = open(name, O_RDWR);
1138 } else if (tun == SSH_TUNID_ANY) {
1139 for (tun = 100; tun >= 0; tun--) {
sthen@openbsd.orga820a862015-10-24 08:34:09 +00001140 snprintf(name, sizeof(name), "/dev/%s%d",
1141 tunbase, tun);
Damien Miller7b58e802005-12-13 19:33:19 +11001142 if ((fd = open(name, O_RDWR)) >= 0)
1143 break;
Damien Millerd27b9472005-12-13 19:29:02 +11001144 }
1145 } else {
Damien Millera210d522006-01-02 23:40:30 +11001146 debug("%s: invalid tunnel %u", __func__, tun);
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001147 return -1;
Damien Millerd27b9472005-12-13 19:29:02 +11001148 }
Damien Miller7b58e802005-12-13 19:33:19 +11001149
deraadt@openbsd.org4d28fa72019-06-28 13:35:04 +00001150 if (fd == -1) {
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001151 debug("%s: %s open: %s", __func__, name, strerror(errno));
1152 return -1;
Damien Miller7b58e802005-12-13 19:33:19 +11001153 }
1154
1155 debug("%s: %s mode %d fd %d", __func__, name, mode, fd);
1156
sthen@openbsd.orga820a862015-10-24 08:34:09 +00001157 /* Bring interface up if it is not already */
1158 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
1159 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
Damien Miller7b58e802005-12-13 19:33:19 +11001160 goto failed;
1161
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001162 if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
1163 debug("%s: get interface %s flags: %s", __func__,
1164 ifr.ifr_name, strerror(errno));
Damien Miller7b58e802005-12-13 19:33:19 +11001165 goto failed;
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001166 }
Damien Millera1d9a182006-01-02 23:41:21 +11001167
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001168 if (!(ifr.ifr_flags & IFF_UP)) {
1169 ifr.ifr_flags |= IFF_UP;
1170 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
1171 debug("%s: activate interface %s: %s", __func__,
1172 ifr.ifr_name, strerror(errno));
1173 goto failed;
1174 }
1175 }
Damien Miller7b58e802005-12-13 19:33:19 +11001176
djm@openbsd.orgb7548b12017-10-23 05:08:00 +00001177 if (ifname != NULL)
1178 *ifname = xstrdup(ifr.ifr_name);
1179
Damien Miller7b58e802005-12-13 19:33:19 +11001180 close(sock);
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001181 return fd;
Damien Miller7b58e802005-12-13 19:33:19 +11001182
1183 failed:
1184 if (fd >= 0)
1185 close(fd);
1186 if (sock >= 0)
1187 close(sock);
djm@openbsd.org2905d6f2015-10-07 00:54:06 +00001188 return -1;
Damien Miller62a31c92005-12-13 20:44:13 +11001189#else
1190 error("Tunnel interfaces are not supported on this platform");
1191 return (-1);
1192#endif
Damien Millerd27b9472005-12-13 19:29:02 +11001193}
1194
Darren Tuckerce321d82005-10-03 18:11:24 +10001195void
1196sanitise_stdfd(void)
1197{
Damien Miller72c5b7d2006-01-06 14:50:44 +11001198 int nullfd, dupfd;
Darren Tuckerce321d82005-10-03 18:11:24 +10001199
Damien Miller72c5b7d2006-01-06 14:50:44 +11001200 if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
Damien Miller9eab9562009-02-22 08:47:02 +11001201 fprintf(stderr, "Couldn't open /dev/null: %s\n",
1202 strerror(errno));
Darren Tuckerce321d82005-10-03 18:11:24 +10001203 exit(1);
1204 }
krw@openbsd.org574def02016-04-02 14:37:42 +00001205 while (++dupfd <= STDERR_FILENO) {
1206 /* Only populate closed fds. */
1207 if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
1208 if (dup2(nullfd, dupfd) == -1) {
1209 fprintf(stderr, "dup2: %s\n", strerror(errno));
1210 exit(1);
1211 }
Darren Tuckerce321d82005-10-03 18:11:24 +10001212 }
Darren Tuckerce321d82005-10-03 18:11:24 +10001213 }
krw@openbsd.org574def02016-04-02 14:37:42 +00001214 if (nullfd > STDERR_FILENO)
Darren Tuckerce321d82005-10-03 18:11:24 +10001215 close(nullfd);
1216}
1217
Damien Miller13390022005-07-06 09:44:19 +10001218char *
Damien Miller3f941882006-03-31 23:13:02 +11001219tohex(const void *vp, size_t l)
Damien Miller13390022005-07-06 09:44:19 +10001220{
Damien Miller3f941882006-03-31 23:13:02 +11001221 const u_char *p = (const u_char *)vp;
Damien Miller13390022005-07-06 09:44:19 +10001222 char b[3], *r;
Damien Miller3f941882006-03-31 23:13:02 +11001223 size_t i, hl;
1224
1225 if (l > 65536)
1226 return xstrdup("tohex: length > 65536");
Damien Miller13390022005-07-06 09:44:19 +10001227
1228 hl = l * 2 + 1;
Damien Miller07d86be2006-03-26 14:19:21 +11001229 r = xcalloc(1, hl);
Damien Miller13390022005-07-06 09:44:19 +10001230 for (i = 0; i < l; i++) {
Damien Miller3f941882006-03-31 23:13:02 +11001231 snprintf(b, sizeof(b), "%02x", p[i]);
Damien Miller13390022005-07-06 09:44:19 +10001232 strlcat(r, b, hl);
1233 }
1234 return (r);
1235}
1236
Damien Miller3f941882006-03-31 23:13:02 +11001237u_int64_t
1238get_u64(const void *vp)
1239{
1240 const u_char *p = (const u_char *)vp;
1241 u_int64_t v;
1242
1243 v = (u_int64_t)p[0] << 56;
1244 v |= (u_int64_t)p[1] << 48;
1245 v |= (u_int64_t)p[2] << 40;
1246 v |= (u_int64_t)p[3] << 32;
1247 v |= (u_int64_t)p[4] << 24;
1248 v |= (u_int64_t)p[5] << 16;
1249 v |= (u_int64_t)p[6] << 8;
1250 v |= (u_int64_t)p[7];
1251
1252 return (v);
1253}
1254
1255u_int32_t
1256get_u32(const void *vp)
1257{
1258 const u_char *p = (const u_char *)vp;
1259 u_int32_t v;
1260
1261 v = (u_int32_t)p[0] << 24;
1262 v |= (u_int32_t)p[1] << 16;
1263 v |= (u_int32_t)p[2] << 8;
1264 v |= (u_int32_t)p[3];
1265
1266 return (v);
1267}
1268
Damien Miller88856692014-04-20 13:33:19 +10001269u_int32_t
1270get_u32_le(const void *vp)
1271{
1272 const u_char *p = (const u_char *)vp;
1273 u_int32_t v;
1274
1275 v = (u_int32_t)p[0];
1276 v |= (u_int32_t)p[1] << 8;
1277 v |= (u_int32_t)p[2] << 16;
1278 v |= (u_int32_t)p[3] << 24;
1279
1280 return (v);
1281}
1282
Damien Miller3f941882006-03-31 23:13:02 +11001283u_int16_t
1284get_u16(const void *vp)
1285{
1286 const u_char *p = (const u_char *)vp;
1287 u_int16_t v;
1288
1289 v = (u_int16_t)p[0] << 8;
1290 v |= (u_int16_t)p[1];
1291
1292 return (v);
1293}
1294
1295void
1296put_u64(void *vp, u_int64_t v)
1297{
1298 u_char *p = (u_char *)vp;
1299
1300 p[0] = (u_char)(v >> 56) & 0xff;
1301 p[1] = (u_char)(v >> 48) & 0xff;
1302 p[2] = (u_char)(v >> 40) & 0xff;
1303 p[3] = (u_char)(v >> 32) & 0xff;
1304 p[4] = (u_char)(v >> 24) & 0xff;
1305 p[5] = (u_char)(v >> 16) & 0xff;
1306 p[6] = (u_char)(v >> 8) & 0xff;
1307 p[7] = (u_char)v & 0xff;
1308}
1309
1310void
1311put_u32(void *vp, u_int32_t v)
1312{
1313 u_char *p = (u_char *)vp;
1314
1315 p[0] = (u_char)(v >> 24) & 0xff;
1316 p[1] = (u_char)(v >> 16) & 0xff;
1317 p[2] = (u_char)(v >> 8) & 0xff;
1318 p[3] = (u_char)v & 0xff;
1319}
1320
Damien Miller88856692014-04-20 13:33:19 +10001321void
1322put_u32_le(void *vp, u_int32_t v)
1323{
1324 u_char *p = (u_char *)vp;
1325
1326 p[0] = (u_char)v & 0xff;
1327 p[1] = (u_char)(v >> 8) & 0xff;
1328 p[2] = (u_char)(v >> 16) & 0xff;
1329 p[3] = (u_char)(v >> 24) & 0xff;
1330}
Damien Miller3f941882006-03-31 23:13:02 +11001331
1332void
1333put_u16(void *vp, u_int16_t v)
1334{
1335 u_char *p = (u_char *)vp;
1336
1337 p[0] = (u_char)(v >> 8) & 0xff;
1338 p[1] = (u_char)v & 0xff;
1339}
Darren Tucker3fc464e2008-06-13 06:42:45 +10001340
1341void
1342ms_subtract_diff(struct timeval *start, int *ms)
1343{
1344 struct timeval diff, finish;
1345
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001346 monotime_tv(&finish);
1347 timersub(&finish, start, &diff);
Darren Tucker3fc464e2008-06-13 06:42:45 +10001348 *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
1349}
1350
1351void
1352ms_to_timeval(struct timeval *tv, int ms)
1353{
1354 if (ms < 0)
1355 ms = 0;
1356 tv->tv_sec = ms / 1000;
1357 tv->tv_usec = (ms % 1000) * 1000;
1358}
1359
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001360void
1361monotime_ts(struct timespec *ts)
Darren Tuckerb759c9c2013-06-02 07:46:16 +10001362{
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001363 struct timeval tv;
1364#if defined(HAVE_CLOCK_GETTIME) && (defined(CLOCK_BOOTTIME) || \
1365 defined(CLOCK_MONOTONIC) || defined(CLOCK_REALTIME))
Darren Tucker94396b72013-08-08 11:52:37 +10001366 static int gettime_failed = 0;
Darren Tuckerb759c9c2013-06-02 07:46:16 +10001367
Darren Tucker94396b72013-08-08 11:52:37 +10001368 if (!gettime_failed) {
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001369# ifdef CLOCK_BOOTTIME
1370 if (clock_gettime(CLOCK_BOOTTIME, ts) == 0)
1371 return;
1372# endif /* CLOCK_BOOTTIME */
1373# ifdef CLOCK_MONOTONIC
1374 if (clock_gettime(CLOCK_MONOTONIC, ts) == 0)
1375 return;
1376# endif /* CLOCK_MONOTONIC */
1377# ifdef CLOCK_REALTIME
1378 /* Not monotonic, but we're almost out of options here. */
1379 if (clock_gettime(CLOCK_REALTIME, ts) == 0)
1380 return;
1381# endif /* CLOCK_REALTIME */
Darren Tucker94396b72013-08-08 11:52:37 +10001382 debug3("clock_gettime: %s", strerror(errno));
1383 gettime_failed = 1;
1384 }
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001385#endif /* HAVE_CLOCK_GETTIME && (BOOTTIME || MONOTONIC || REALTIME) */
1386 gettimeofday(&tv, NULL);
1387 ts->tv_sec = tv.tv_sec;
1388 ts->tv_nsec = (long)tv.tv_usec * 1000;
1389}
Darren Tucker94396b72013-08-08 11:52:37 +10001390
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001391void
1392monotime_tv(struct timeval *tv)
1393{
1394 struct timespec ts;
1395
1396 monotime_ts(&ts);
1397 tv->tv_sec = ts.tv_sec;
1398 tv->tv_usec = ts.tv_nsec / 1000;
1399}
1400
1401time_t
1402monotime(void)
1403{
1404 struct timespec ts;
1405
1406 monotime_ts(&ts);
1407 return ts.tv_sec;
Darren Tuckerb759c9c2013-06-02 07:46:16 +10001408}
1409
dtucker@openbsd.orgb8d4eaf2016-03-02 22:42:40 +00001410double
1411monotime_double(void)
1412{
1413 struct timespec ts;
1414
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001415 monotime_ts(&ts);
1416 return ts.tv_sec + ((double)ts.tv_nsec / 1000000000);
dtucker@openbsd.orgb8d4eaf2016-03-02 22:42:40 +00001417}
1418
Damien Miller65e42f82010-09-24 22:15:11 +10001419void
1420bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
1421{
1422 bw->buflen = buflen;
1423 bw->rate = kbps;
dtucker@openbsd.org434b5872018-12-07 04:36:09 +00001424 bw->thresh = buflen;
Damien Miller65e42f82010-09-24 22:15:11 +10001425 bw->lamt = 0;
1426 timerclear(&bw->bwstart);
1427 timerclear(&bw->bwend);
dtucker@openbsd.org434b5872018-12-07 04:36:09 +00001428}
Damien Miller65e42f82010-09-24 22:15:11 +10001429
1430/* Callback from read/write loop to insert bandwidth-limiting delays */
1431void
1432bandwidth_limit(struct bwlimit *bw, size_t read_len)
1433{
1434 u_int64_t waitlen;
1435 struct timespec ts, rm;
1436
dtucker@openbsd.org434b5872018-12-07 04:36:09 +00001437 bw->lamt += read_len;
Damien Miller65e42f82010-09-24 22:15:11 +10001438 if (!timerisset(&bw->bwstart)) {
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001439 monotime_tv(&bw->bwstart);
Damien Miller65e42f82010-09-24 22:15:11 +10001440 return;
1441 }
Damien Miller65e42f82010-09-24 22:15:11 +10001442 if (bw->lamt < bw->thresh)
1443 return;
1444
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001445 monotime_tv(&bw->bwend);
Damien Miller65e42f82010-09-24 22:15:11 +10001446 timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
1447 if (!timerisset(&bw->bwend))
1448 return;
1449
1450 bw->lamt *= 8;
1451 waitlen = (double)1000000L * bw->lamt / bw->rate;
1452
1453 bw->bwstart.tv_sec = waitlen / 1000000L;
1454 bw->bwstart.tv_usec = waitlen % 1000000L;
1455
1456 if (timercmp(&bw->bwstart, &bw->bwend, >)) {
1457 timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
1458
1459 /* Adjust the wait time */
1460 if (bw->bwend.tv_sec) {
1461 bw->thresh /= 2;
1462 if (bw->thresh < bw->buflen / 4)
1463 bw->thresh = bw->buflen / 4;
1464 } else if (bw->bwend.tv_usec < 10000) {
1465 bw->thresh *= 2;
1466 if (bw->thresh > bw->buflen * 8)
1467 bw->thresh = bw->buflen * 8;
1468 }
1469
1470 TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
1471 while (nanosleep(&ts, &rm) == -1) {
1472 if (errno != EINTR)
1473 break;
1474 ts = rm;
1475 }
1476 }
1477
1478 bw->lamt = 0;
dtucker@openbsd.org@openbsd.org5db6fbf2017-11-25 06:46:22 +00001479 monotime_tv(&bw->bwstart);
Damien Miller65e42f82010-09-24 22:15:11 +10001480}
Damien Miller0dac6fb2010-11-20 15:19:38 +11001481
Damien Miller2cd62932010-12-01 11:50:35 +11001482/* Make a template filename for mk[sd]temp() */
1483void
1484mktemp_proto(char *s, size_t len)
1485{
1486 const char *tmpdir;
1487 int r;
1488
1489 if ((tmpdir = getenv("TMPDIR")) != NULL) {
1490 r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1491 if (r > 0 && (size_t)r < len)
1492 return;
1493 }
1494 r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1495 if (r < 0 || (size_t)r >= len)
1496 fatal("%s: template string too short", __func__);
1497}
1498
Damien Miller0dac6fb2010-11-20 15:19:38 +11001499static const struct {
1500 const char *name;
1501 int value;
1502} ipqos[] = {
djm@openbsd.org51676ec2017-07-23 23:37:02 +00001503 { "none", INT_MAX }, /* can't use 0 here; that's CS0 */
Damien Miller0dac6fb2010-11-20 15:19:38 +11001504 { "af11", IPTOS_DSCP_AF11 },
1505 { "af12", IPTOS_DSCP_AF12 },
1506 { "af13", IPTOS_DSCP_AF13 },
Damien Miller2918e032011-09-22 21:34:35 +10001507 { "af21", IPTOS_DSCP_AF21 },
Damien Miller0dac6fb2010-11-20 15:19:38 +11001508 { "af22", IPTOS_DSCP_AF22 },
1509 { "af23", IPTOS_DSCP_AF23 },
1510 { "af31", IPTOS_DSCP_AF31 },
1511 { "af32", IPTOS_DSCP_AF32 },
1512 { "af33", IPTOS_DSCP_AF33 },
1513 { "af41", IPTOS_DSCP_AF41 },
1514 { "af42", IPTOS_DSCP_AF42 },
1515 { "af43", IPTOS_DSCP_AF43 },
1516 { "cs0", IPTOS_DSCP_CS0 },
1517 { "cs1", IPTOS_DSCP_CS1 },
1518 { "cs2", IPTOS_DSCP_CS2 },
1519 { "cs3", IPTOS_DSCP_CS3 },
1520 { "cs4", IPTOS_DSCP_CS4 },
1521 { "cs5", IPTOS_DSCP_CS5 },
1522 { "cs6", IPTOS_DSCP_CS6 },
1523 { "cs7", IPTOS_DSCP_CS7 },
1524 { "ef", IPTOS_DSCP_EF },
1525 { "lowdelay", IPTOS_LOWDELAY },
1526 { "throughput", IPTOS_THROUGHPUT },
1527 { "reliability", IPTOS_RELIABILITY },
1528 { NULL, -1 }
1529};
1530
1531int
1532parse_ipqos(const char *cp)
1533{
1534 u_int i;
1535 char *ep;
1536 long val;
1537
1538 if (cp == NULL)
1539 return -1;
1540 for (i = 0; ipqos[i].name != NULL; i++) {
1541 if (strcasecmp(cp, ipqos[i].name) == 0)
1542 return ipqos[i].value;
1543 }
1544 /* Try parsing as an integer */
1545 val = strtol(cp, &ep, 0);
1546 if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1547 return -1;
1548 return val;
1549}
1550
Damien Miller91475862011-05-05 14:14:34 +10001551const char *
1552iptos2str(int iptos)
1553{
1554 int i;
1555 static char iptos_str[sizeof "0xff"];
1556
1557 for (i = 0; ipqos[i].name != NULL; i++) {
1558 if (ipqos[i].value == iptos)
1559 return ipqos[i].name;
1560 }
1561 snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1562 return iptos_str;
1563}
Damien Millere9fc72e2013-10-15 12:14:12 +11001564
1565void
1566lowercase(char *s)
1567{
1568 for (; *s; s++)
1569 *s = tolower((u_char)*s);
1570}
Damien Miller7acefbb2014-07-18 14:11:24 +10001571
1572int
1573unix_listener(const char *path, int backlog, int unlink_first)
1574{
1575 struct sockaddr_un sunaddr;
1576 int saved_errno, sock;
1577
1578 memset(&sunaddr, 0, sizeof(sunaddr));
1579 sunaddr.sun_family = AF_UNIX;
djm@openbsd.org155072f2017-12-08 02:13:02 +00001580 if (strlcpy(sunaddr.sun_path, path,
1581 sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1582 error("%s: path \"%s\" too long for Unix domain socket",
1583 __func__, path);
Damien Miller7acefbb2014-07-18 14:11:24 +10001584 errno = ENAMETOOLONG;
1585 return -1;
1586 }
1587
1588 sock = socket(PF_UNIX, SOCK_STREAM, 0);
deraadt@openbsd.org4d28fa72019-06-28 13:35:04 +00001589 if (sock == -1) {
Damien Miller7acefbb2014-07-18 14:11:24 +10001590 saved_errno = errno;
djm@openbsd.org155072f2017-12-08 02:13:02 +00001591 error("%s: socket: %.100s", __func__, strerror(errno));
Damien Miller7acefbb2014-07-18 14:11:24 +10001592 errno = saved_errno;
1593 return -1;
1594 }
1595 if (unlink_first == 1) {
1596 if (unlink(path) != 0 && errno != ENOENT)
1597 error("unlink(%s): %.100s", path, strerror(errno));
1598 }
deraadt@openbsd.org4d28fa72019-06-28 13:35:04 +00001599 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
Damien Miller7acefbb2014-07-18 14:11:24 +10001600 saved_errno = errno;
djm@openbsd.org155072f2017-12-08 02:13:02 +00001601 error("%s: cannot bind to path %s: %s",
1602 __func__, path, strerror(errno));
djm@openbsd.orgfd4eeee2017-12-08 02:14:33 +00001603 close(sock);
Damien Miller7acefbb2014-07-18 14:11:24 +10001604 errno = saved_errno;
1605 return -1;
1606 }
deraadt@openbsd.org4d28fa72019-06-28 13:35:04 +00001607 if (listen(sock, backlog) == -1) {
Damien Miller7acefbb2014-07-18 14:11:24 +10001608 saved_errno = errno;
djm@openbsd.org155072f2017-12-08 02:13:02 +00001609 error("%s: cannot listen on path %s: %s",
1610 __func__, path, strerror(errno));
djm@openbsd.orgfd4eeee2017-12-08 02:14:33 +00001611 close(sock);
1612 unlink(path);
Damien Miller7acefbb2014-07-18 14:11:24 +10001613 errno = saved_errno;
1614 return -1;
1615 }
1616 return sock;
1617}
Damien Miller46878022014-08-30 03:29:19 +10001618
Damien Miller04ee0f82009-11-18 17:48:30 +11001619void
1620sock_set_v6only(int s)
1621{
Damien Millerd86a3ba2015-12-09 09:18:45 +11001622#if defined(IPV6_V6ONLY) && !defined(__OpenBSD__)
Damien Miller04ee0f82009-11-18 17:48:30 +11001623 int on = 1;
1624
1625 debug3("%s: set socket %d IPV6_V6ONLY", __func__, s);
1626 if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) == -1)
1627 error("setsockopt IPV6_V6ONLY: %s", strerror(errno));
1628#endif
1629}
djm@openbsd.org0ccbd5e2016-04-06 06:42:17 +00001630
1631/*
1632 * Compares two strings that maybe be NULL. Returns non-zero if strings
1633 * are both NULL or are identical, returns zero otherwise.
1634 */
1635static int
1636strcmp_maybe_null(const char *a, const char *b)
1637{
1638 if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1639 return 0;
1640 if (a != NULL && strcmp(a, b) != 0)
1641 return 0;
1642 return 1;
1643}
1644
1645/*
1646 * Compare two forwards, returning non-zero if they are identical or
1647 * zero otherwise.
1648 */
1649int
1650forward_equals(const struct Forward *a, const struct Forward *b)
1651{
1652 if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
1653 return 0;
1654 if (a->listen_port != b->listen_port)
1655 return 0;
1656 if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
1657 return 0;
1658 if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
1659 return 0;
1660 if (a->connect_port != b->connect_port)
1661 return 0;
1662 if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
1663 return 0;
1664 /* allocated_port and handle are not checked */
1665 return 1;
1666}
1667
dtucker@openbsd.org7fc47662016-11-30 00:28:31 +00001668/* returns 1 if process is already daemonized, 0 otherwise */
1669int
1670daemonized(void)
1671{
1672 int fd;
1673
1674 if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
1675 close(fd);
1676 return 0; /* have controlling terminal */
1677 }
1678 if (getppid() != 1)
1679 return 0; /* parent is not init */
1680 if (getsid(0) != getpid())
1681 return 0; /* not session leader */
1682 debug3("already daemonized");
1683 return 1;
1684}
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001685
1686
1687/*
1688 * Splits 's' into an argument vector. Handles quoted string and basic
1689 * escape characters (\\, \", \'). Caller must free the argument vector
1690 * and its members.
1691 */
1692int
1693argv_split(const char *s, int *argcp, char ***argvp)
1694{
1695 int r = SSH_ERR_INTERNAL_ERROR;
1696 int argc = 0, quote, i, j;
1697 char *arg, **argv = xcalloc(1, sizeof(*argv));
1698
1699 *argvp = NULL;
1700 *argcp = 0;
1701
1702 for (i = 0; s[i] != '\0'; i++) {
1703 /* Skip leading whitespace */
1704 if (s[i] == ' ' || s[i] == '\t')
1705 continue;
1706
1707 /* Start of a token */
1708 quote = 0;
1709 if (s[i] == '\\' &&
1710 (s[i + 1] == '\'' || s[i + 1] == '\"' || s[i + 1] == '\\'))
1711 i++;
1712 else if (s[i] == '\'' || s[i] == '"')
1713 quote = s[i++];
1714
1715 argv = xreallocarray(argv, (argc + 2), sizeof(*argv));
1716 arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1);
1717 argv[argc] = NULL;
1718
1719 /* Copy the token in, removing escapes */
1720 for (j = 0; s[i] != '\0'; i++) {
1721 if (s[i] == '\\') {
1722 if (s[i + 1] == '\'' ||
1723 s[i + 1] == '\"' ||
1724 s[i + 1] == '\\') {
1725 i++; /* Skip '\' */
1726 arg[j++] = s[i];
1727 } else {
1728 /* Unrecognised escape */
1729 arg[j++] = s[i];
1730 }
1731 } else if (quote == 0 && (s[i] == ' ' || s[i] == '\t'))
1732 break; /* done */
1733 else if (quote != 0 && s[i] == quote)
1734 break; /* done */
1735 else
1736 arg[j++] = s[i];
1737 }
1738 if (s[i] == '\0') {
1739 if (quote != 0) {
1740 /* Ran out of string looking for close quote */
1741 r = SSH_ERR_INVALID_FORMAT;
1742 goto out;
1743 }
1744 break;
1745 }
1746 }
1747 /* Success */
1748 *argcp = argc;
1749 *argvp = argv;
1750 argc = 0;
1751 argv = NULL;
1752 r = 0;
1753 out:
1754 if (argc != 0 && argv != NULL) {
1755 for (i = 0; i < argc; i++)
1756 free(argv[i]);
1757 free(argv);
1758 }
1759 return r;
1760}
1761
1762/*
1763 * Reassemble an argument vector into a string, quoting and escaping as
1764 * necessary. Caller must free returned string.
1765 */
1766char *
1767argv_assemble(int argc, char **argv)
1768{
1769 int i, j, ws, r;
1770 char c, *ret;
1771 struct sshbuf *buf, *arg;
1772
1773 if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL)
1774 fatal("%s: sshbuf_new failed", __func__);
1775
1776 for (i = 0; i < argc; i++) {
1777 ws = 0;
1778 sshbuf_reset(arg);
1779 for (j = 0; argv[i][j] != '\0'; j++) {
1780 r = 0;
1781 c = argv[i][j];
1782 switch (c) {
1783 case ' ':
1784 case '\t':
1785 ws = 1;
1786 r = sshbuf_put_u8(arg, c);
1787 break;
1788 case '\\':
1789 case '\'':
1790 case '"':
1791 if ((r = sshbuf_put_u8(arg, '\\')) != 0)
1792 break;
1793 /* FALLTHROUGH */
1794 default:
1795 r = sshbuf_put_u8(arg, c);
1796 break;
1797 }
1798 if (r != 0)
1799 fatal("%s: sshbuf_put_u8: %s",
1800 __func__, ssh_err(r));
1801 }
1802 if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) ||
1803 (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) ||
1804 (r = sshbuf_putb(buf, arg)) != 0 ||
1805 (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0))
1806 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1807 }
1808 if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL)
1809 fatal("%s: malloc failed", __func__);
1810 memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf));
1811 ret[sshbuf_len(buf)] = '\0';
1812 sshbuf_free(buf);
1813 sshbuf_free(arg);
1814 return ret;
1815}
1816
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001817/* Returns 0 if pid exited cleanly, non-zero otherwise */
1818int
djm@openbsd.orgb074c3c2017-08-18 05:48:04 +00001819exited_cleanly(pid_t pid, const char *tag, const char *cmd, int quiet)
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001820{
1821 int status;
1822
1823 while (waitpid(pid, &status, 0) == -1) {
1824 if (errno != EINTR) {
1825 error("%s: waitpid: %s", tag, strerror(errno));
1826 return -1;
1827 }
1828 }
1829 if (WIFSIGNALED(status)) {
1830 error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status));
1831 return -1;
1832 } else if (WEXITSTATUS(status) != 0) {
djm@openbsd.orgb074c3c2017-08-18 05:48:04 +00001833 do_log2(quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_INFO,
1834 "%s %s failed, status %d", tag, cmd, WEXITSTATUS(status));
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001835 return -1;
1836 }
1837 return 0;
1838}
1839
1840/*
1841 * Check a given path for security. This is defined as all components
1842 * of the path to the file must be owned by either the owner of
1843 * of the file or root and no directories must be group or world writable.
1844 *
1845 * XXX Should any specific check be done for sym links ?
1846 *
1847 * Takes a file name, its stat information (preferably from fstat() to
1848 * avoid races), the uid of the expected owner, their home directory and an
1849 * error buffer plus max size as arguments.
1850 *
1851 * Returns 0 on success and -1 on failure
1852 */
1853int
1854safe_path(const char *name, struct stat *stp, const char *pw_dir,
1855 uid_t uid, char *err, size_t errlen)
1856{
1857 char buf[PATH_MAX], homedir[PATH_MAX];
1858 char *cp;
1859 int comparehome = 0;
1860 struct stat st;
1861
1862 if (realpath(name, buf) == NULL) {
1863 snprintf(err, errlen, "realpath %s failed: %s", name,
1864 strerror(errno));
1865 return -1;
1866 }
1867 if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
1868 comparehome = 1;
1869
1870 if (!S_ISREG(stp->st_mode)) {
1871 snprintf(err, errlen, "%s is not a regular file", buf);
1872 return -1;
1873 }
1874 if ((!platform_sys_dir_uid(stp->st_uid) && stp->st_uid != uid) ||
1875 (stp->st_mode & 022) != 0) {
1876 snprintf(err, errlen, "bad ownership or modes for file %s",
1877 buf);
1878 return -1;
1879 }
1880
1881 /* for each component of the canonical path, walking upwards */
1882 for (;;) {
1883 if ((cp = dirname(buf)) == NULL) {
1884 snprintf(err, errlen, "dirname() failed");
1885 return -1;
1886 }
1887 strlcpy(buf, cp, sizeof(buf));
1888
deraadt@openbsd.org4d28fa72019-06-28 13:35:04 +00001889 if (stat(buf, &st) == -1 ||
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001890 (!platform_sys_dir_uid(st.st_uid) && st.st_uid != uid) ||
1891 (st.st_mode & 022) != 0) {
1892 snprintf(err, errlen,
1893 "bad ownership or modes for directory %s", buf);
1894 return -1;
1895 }
1896
1897 /* If are past the homedir then we can stop */
1898 if (comparehome && strcmp(homedir, buf) == 0)
1899 break;
1900
1901 /*
1902 * dirname should always complete with a "/" path,
1903 * but we can be paranoid and check for "." too
1904 */
1905 if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
1906 break;
1907 }
1908 return 0;
1909}
1910
1911/*
1912 * Version of safe_path() that accepts an open file descriptor to
1913 * avoid races.
1914 *
1915 * Returns 0 on success and -1 on failure
1916 */
1917int
1918safe_path_fd(int fd, const char *file, struct passwd *pw,
1919 char *err, size_t errlen)
1920{
1921 struct stat st;
1922
1923 /* check the open file to avoid races */
deraadt@openbsd.org4d28fa72019-06-28 13:35:04 +00001924 if (fstat(fd, &st) == -1) {
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001925 snprintf(err, errlen, "cannot stat file %s: %s",
1926 file, strerror(errno));
1927 return -1;
1928 }
1929 return safe_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
1930}
1931
1932/*
1933 * Sets the value of the given variable in the environment. If the variable
1934 * already exists, its value is overridden.
1935 */
1936void
1937child_set_env(char ***envp, u_int *envsizep, const char *name,
1938 const char *value)
1939{
1940 char **env;
1941 u_int envsize;
1942 u_int i, namelen;
1943
1944 if (strchr(name, '=') != NULL) {
1945 error("Invalid environment variable \"%.100s\"", name);
1946 return;
1947 }
1948
1949 /*
1950 * If we're passed an uninitialized list, allocate a single null
1951 * entry before continuing.
1952 */
1953 if (*envp == NULL && *envsizep == 0) {
1954 *envp = xmalloc(sizeof(char *));
1955 *envp[0] = NULL;
1956 *envsizep = 1;
1957 }
1958
1959 /*
1960 * Find the slot where the value should be stored. If the variable
1961 * already exists, we reuse the slot; otherwise we append a new slot
1962 * at the end of the array, expanding if necessary.
1963 */
1964 env = *envp;
1965 namelen = strlen(name);
1966 for (i = 0; env[i]; i++)
1967 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
1968 break;
1969 if (env[i]) {
1970 /* Reuse the slot. */
1971 free(env[i]);
1972 } else {
1973 /* New variable. Expand if necessary. */
1974 envsize = *envsizep;
1975 if (i >= envsize - 1) {
1976 if (envsize >= 1000)
1977 fatal("child_set_env: too many env vars");
1978 envsize += 50;
1979 env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
1980 *envsizep = envsize;
1981 }
1982 /* Need to set the NULL pointer at end of array beyond the new slot. */
1983 env[i + 1] = NULL;
1984 }
1985
1986 /* Allocate space and format the variable in the appropriate slot. */
djm@openbsd.org7c856852018-03-03 03:15:51 +00001987 /* XXX xasprintf */
djm@openbsd.orgde4ae072017-08-18 05:36:45 +00001988 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
1989 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
1990}
1991
millert@openbsd.org887669e2017-10-21 23:06:24 +00001992/*
1993 * Check and optionally lowercase a domain name, also removes trailing '.'
1994 * Returns 1 on success and 0 on failure, storing an error message in errstr.
1995 */
1996int
1997valid_domain(char *name, int makelower, const char **errstr)
1998{
1999 size_t i, l = strlen(name);
2000 u_char c, last = '\0';
2001 static char errbuf[256];
2002
2003 if (l == 0) {
2004 strlcpy(errbuf, "empty domain name", sizeof(errbuf));
2005 goto bad;
2006 }
2007 if (!isalpha((u_char)name[0]) && !isdigit((u_char)name[0])) {
2008 snprintf(errbuf, sizeof(errbuf), "domain name \"%.100s\" "
2009 "starts with invalid character", name);
2010 goto bad;
2011 }
2012 for (i = 0; i < l; i++) {
2013 c = tolower((u_char)name[i]);
2014 if (makelower)
2015 name[i] = (char)c;
2016 if (last == '.' && c == '.') {
2017 snprintf(errbuf, sizeof(errbuf), "domain name "
2018 "\"%.100s\" contains consecutive separators", name);
2019 goto bad;
2020 }
2021 if (c != '.' && c != '-' && !isalnum(c) &&
2022 c != '_') /* technically invalid, but common */ {
2023 snprintf(errbuf, sizeof(errbuf), "domain name "
2024 "\"%.100s\" contains invalid characters", name);
2025 goto bad;
2026 }
2027 last = c;
2028 }
2029 if (name[l - 1] == '.')
2030 name[l - 1] = '\0';
2031 if (errstr != NULL)
2032 *errstr = NULL;
2033 return 1;
2034bad:
2035 if (errstr != NULL)
2036 *errstr = errbuf;
2037 return 0;
2038}
dtucker@openbsd.org609d96b2017-12-05 23:59:47 +00002039
djm@openbsd.org5eff5b82018-10-03 06:38:35 +00002040/*
2041 * Verify that a environment variable name (not including initial '$') is
2042 * valid; consisting of one or more alphanumeric or underscore characters only.
2043 * Returns 1 on valid, 0 otherwise.
2044 */
2045int
2046valid_env_name(const char *name)
2047{
2048 const char *cp;
2049
2050 if (name[0] == '\0')
2051 return 0;
2052 for (cp = name; *cp != '\0'; cp++) {
2053 if (!isalnum((u_char)*cp) && *cp != '_')
2054 return 0;
2055 }
2056 return 1;
2057}
2058
dtucker@openbsd.org609d96b2017-12-05 23:59:47 +00002059const char *
2060atoi_err(const char *nptr, int *val)
2061{
2062 const char *errstr = NULL;
2063 long long num;
2064
2065 if (nptr == NULL || *nptr == '\0')
2066 return "missing";
2067 num = strtonum(nptr, 0, INT_MAX, &errstr);
2068 if (errstr == NULL)
2069 *val = (int)num;
2070 return errstr;
2071}
djm@openbsd.orgbf0fbf22018-03-12 00:52:01 +00002072
2073int
2074parse_absolute_time(const char *s, uint64_t *tp)
2075{
2076 struct tm tm;
2077 time_t tt;
2078 char buf[32], *fmt;
2079
2080 *tp = 0;
2081
2082 /*
2083 * POSIX strptime says "The application shall ensure that there
2084 * is white-space or other non-alphanumeric characters between
2085 * any two conversion specifications" so arrange things this way.
2086 */
2087 switch (strlen(s)) {
2088 case 8: /* YYYYMMDD */
2089 fmt = "%Y-%m-%d";
2090 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
2091 break;
2092 case 12: /* YYYYMMDDHHMM */
2093 fmt = "%Y-%m-%dT%H:%M";
2094 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s",
2095 s, s + 4, s + 6, s + 8, s + 10);
2096 break;
2097 case 14: /* YYYYMMDDHHMMSS */
2098 fmt = "%Y-%m-%dT%H:%M:%S";
2099 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
2100 s, s + 4, s + 6, s + 8, s + 10, s + 12);
2101 break;
2102 default:
2103 return SSH_ERR_INVALID_FORMAT;
2104 }
2105
2106 memset(&tm, 0, sizeof(tm));
2107 if (strptime(buf, fmt, &tm) == NULL)
2108 return SSH_ERR_INVALID_FORMAT;
2109 if ((tt = mktime(&tm)) < 0)
2110 return SSH_ERR_INVALID_FORMAT;
2111 /* success */
2112 *tp = (uint64_t)tt;
2113 return 0;
2114}
2115
2116void
2117format_absolute_time(uint64_t t, char *buf, size_t len)
2118{
2119 time_t tt = t > INT_MAX ? INT_MAX : t; /* XXX revisit in 2038 :P */
2120 struct tm tm;
2121
2122 localtime_r(&tt, &tm);
2123 strftime(buf, len, "%Y-%m-%dT%H:%M:%S", &tm);
2124}
djm@openbsd.org2a358622018-11-16 03:26:01 +00002125
2126/* check if path is absolute */
2127int
2128path_absolute(const char *path)
2129{
2130 return (*path == '/') ? 1 : 0;
2131}
djm@openbsd.orgc72d78c2019-09-03 08:29:58 +00002132
2133void
2134skip_space(char **cpp)
2135{
2136 char *cp;
2137
2138 for (cp = *cpp; *cp == ' ' || *cp == '\t'; cp++)
2139 ;
2140 *cpp = cp;
2141}
djm@openbsd.org5485f8d2019-09-03 08:32:11 +00002142
2143/* authorized_key-style options parsing helpers */
2144
2145/*
2146 * Match flag 'opt' in *optsp, and if allow_negate is set then also match
2147 * 'no-opt'. Returns -1 if option not matched, 1 if option matches or 0
2148 * if negated option matches.
2149 * If the option or negated option matches, then *optsp is updated to
2150 * point to the first character after the option.
2151 */
2152int
2153opt_flag(const char *opt, int allow_negate, const char **optsp)
2154{
2155 size_t opt_len = strlen(opt);
2156 const char *opts = *optsp;
2157 int negate = 0;
2158
2159 if (allow_negate && strncasecmp(opts, "no-", 3) == 0) {
2160 opts += 3;
2161 negate = 1;
2162 }
2163 if (strncasecmp(opts, opt, opt_len) == 0) {
2164 *optsp = opts + opt_len;
2165 return negate ? 0 : 1;
2166 }
2167 return -1;
2168}
2169
2170char *
2171opt_dequote(const char **sp, const char **errstrp)
2172{
2173 const char *s = *sp;
2174 char *ret;
2175 size_t i;
2176
2177 *errstrp = NULL;
2178 if (*s != '"') {
2179 *errstrp = "missing start quote";
2180 return NULL;
2181 }
2182 s++;
2183 if ((ret = malloc(strlen((s)) + 1)) == NULL) {
2184 *errstrp = "memory allocation failed";
2185 return NULL;
2186 }
2187 for (i = 0; *s != '\0' && *s != '"';) {
2188 if (s[0] == '\\' && s[1] == '"')
2189 s++;
2190 ret[i++] = *s++;
2191 }
2192 if (*s == '\0') {
2193 *errstrp = "missing end quote";
2194 free(ret);
2195 return NULL;
2196 }
2197 ret[i] = '\0';
2198 s++;
2199 *sp = s;
2200 return ret;
2201}
2202
2203int
2204opt_match(const char **opts, const char *term)
2205{
2206 if (strncasecmp((*opts), term, strlen(term)) == 0 &&
2207 (*opts)[strlen(term)] == '=') {
2208 *opts += strlen(term) + 1;
2209 return 1;
2210 }
2211 return 0;
2212}
2213