misc.c revision 1.24 1 1.21 christos /* $NetBSD: misc.c,v 1.24 2020/12/04 18:42:50 christos Exp $ */
2 1.24 christos /* $OpenBSD: misc.c,v 1.153 2020/06/26 05:16:38 djm Exp $ */
3 1.24 christos
4 1.1 christos /*
5 1.1 christos * Copyright (c) 2000 Markus Friedl. All rights reserved.
6 1.24 christos * Copyright (c) 2005-2020 Damien Miller. All rights reserved.
7 1.24 christos * Copyright (c) 2004 Henning Brauer <henning (at) openbsd.org>
8 1.1 christos *
9 1.24 christos * Permission to use, copy, modify, and distribute this software for any
10 1.24 christos * purpose with or without fee is hereby granted, provided that the above
11 1.24 christos * copyright notice and this permission notice appear in all copies.
12 1.1 christos *
13 1.24 christos * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
14 1.24 christos * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
15 1.24 christos * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
16 1.24 christos * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
17 1.24 christos * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
18 1.24 christos * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
19 1.24 christos * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20 1.1 christos */
21 1.1 christos
22 1.2 christos #include "includes.h"
23 1.21 christos __RCSID("$NetBSD: misc.c,v 1.24 2020/12/04 18:42:50 christos Exp $");
24 1.24 christos
25 1.1 christos #include <sys/types.h>
26 1.1 christos #include <sys/ioctl.h>
27 1.1 christos #include <sys/socket.h>
28 1.16 christos #include <sys/stat.h>
29 1.12 christos #include <sys/time.h>
30 1.16 christos #include <sys/wait.h>
31 1.9 christos #include <sys/un.h>
32 1.1 christos
33 1.1 christos #include <net/if.h>
34 1.2 christos #include <net/if_tun.h>
35 1.1 christos #include <netinet/in.h>
36 1.5 christos #include <netinet/ip.h>
37 1.1 christos #include <netinet/tcp.h>
38 1.20 christos #include <arpa/inet.h>
39 1.1 christos
40 1.9 christos #include <ctype.h>
41 1.1 christos #include <errno.h>
42 1.1 christos #include <fcntl.h>
43 1.1 christos #include <netdb.h>
44 1.1 christos #include <paths.h>
45 1.1 christos #include <pwd.h>
46 1.16 christos #include <libgen.h>
47 1.10 christos #include <limits.h>
48 1.20 christos #include <poll.h>
49 1.16 christos #include <signal.h>
50 1.1 christos #include <stdarg.h>
51 1.1 christos #include <stdio.h>
52 1.1 christos #include <stdlib.h>
53 1.1 christos #include <string.h>
54 1.1 christos #include <unistd.h>
55 1.1 christos
56 1.1 christos #include "xmalloc.h"
57 1.1 christos #include "misc.h"
58 1.1 christos #include "log.h"
59 1.1 christos #include "ssh.h"
60 1.16 christos #include "sshbuf.h"
61 1.16 christos #include "ssherr.h"
62 1.1 christos
63 1.1 christos /* remove newline at end of string */
64 1.1 christos char *
65 1.1 christos chop(char *s)
66 1.1 christos {
67 1.1 christos char *t = s;
68 1.1 christos while (*t) {
69 1.1 christos if (*t == '\n' || *t == '\r') {
70 1.1 christos *t = '\0';
71 1.1 christos return s;
72 1.1 christos }
73 1.1 christos t++;
74 1.1 christos }
75 1.1 christos return s;
76 1.1 christos
77 1.1 christos }
78 1.1 christos
79 1.1 christos /* set/unset filedescriptor to non-blocking */
80 1.1 christos int
81 1.1 christos set_nonblock(int fd)
82 1.1 christos {
83 1.1 christos int val;
84 1.1 christos
85 1.13 christos val = fcntl(fd, F_GETFL);
86 1.21 christos if (val == -1) {
87 1.13 christos error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
88 1.1 christos return (-1);
89 1.1 christos }
90 1.1 christos if (val & O_NONBLOCK) {
91 1.1 christos debug3("fd %d is O_NONBLOCK", fd);
92 1.1 christos return (0);
93 1.1 christos }
94 1.1 christos debug2("fd %d setting O_NONBLOCK", fd);
95 1.1 christos val |= O_NONBLOCK;
96 1.1 christos if (fcntl(fd, F_SETFL, val) == -1) {
97 1.1 christos debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
98 1.1 christos strerror(errno));
99 1.1 christos return (-1);
100 1.1 christos }
101 1.1 christos return (0);
102 1.1 christos }
103 1.1 christos
104 1.1 christos int
105 1.1 christos unset_nonblock(int fd)
106 1.1 christos {
107 1.1 christos int val;
108 1.1 christos
109 1.13 christos val = fcntl(fd, F_GETFL);
110 1.21 christos if (val == -1) {
111 1.13 christos error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
112 1.1 christos return (-1);
113 1.1 christos }
114 1.1 christos if (!(val & O_NONBLOCK)) {
115 1.1 christos debug3("fd %d is not O_NONBLOCK", fd);
116 1.1 christos return (0);
117 1.1 christos }
118 1.1 christos debug("fd %d clearing O_NONBLOCK", fd);
119 1.1 christos val &= ~O_NONBLOCK;
120 1.1 christos if (fcntl(fd, F_SETFL, val) == -1) {
121 1.1 christos debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
122 1.1 christos fd, strerror(errno));
123 1.1 christos return (-1);
124 1.1 christos }
125 1.1 christos return (0);
126 1.1 christos }
127 1.1 christos
128 1.1 christos const char *
129 1.1 christos ssh_gai_strerror(int gaierr)
130 1.1 christos {
131 1.8 christos if (gaierr == EAI_SYSTEM && errno != 0)
132 1.1 christos return strerror(errno);
133 1.1 christos return gai_strerror(gaierr);
134 1.1 christos }
135 1.1 christos
136 1.1 christos /* disable nagle on socket */
137 1.1 christos void
138 1.1 christos set_nodelay(int fd)
139 1.1 christos {
140 1.1 christos int opt;
141 1.1 christos socklen_t optlen;
142 1.1 christos
143 1.1 christos optlen = sizeof opt;
144 1.1 christos if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
145 1.1 christos debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
146 1.1 christos return;
147 1.1 christos }
148 1.1 christos if (opt == 1) {
149 1.1 christos debug2("fd %d is TCP_NODELAY", fd);
150 1.1 christos return;
151 1.1 christos }
152 1.1 christos opt = 1;
153 1.1 christos debug2("fd %d setting TCP_NODELAY", fd);
154 1.1 christos if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
155 1.1 christos error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
156 1.1 christos }
157 1.1 christos
158 1.17 christos /* Allow local port reuse in TIME_WAIT */
159 1.17 christos int
160 1.17 christos set_reuseaddr(int fd)
161 1.17 christos {
162 1.17 christos int on = 1;
163 1.17 christos
164 1.17 christos if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
165 1.17 christos error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
166 1.17 christos return -1;
167 1.17 christos }
168 1.17 christos return 0;
169 1.17 christos }
170 1.17 christos
171 1.17 christos /* Get/set routing domain */
172 1.17 christos char *
173 1.17 christos get_rdomain(int fd)
174 1.17 christos {
175 1.17 christos #ifdef SO_RTABLE
176 1.17 christos int rtable;
177 1.17 christos char *ret;
178 1.17 christos socklen_t len = sizeof(rtable);
179 1.17 christos
180 1.17 christos if (getsockopt(fd, SOL_SOCKET, SO_RTABLE, &rtable, &len) == -1) {
181 1.17 christos error("Failed to get routing domain for fd %d: %s",
182 1.17 christos fd, strerror(errno));
183 1.17 christos return NULL;
184 1.17 christos }
185 1.17 christos xasprintf(&ret, "%d", rtable);
186 1.17 christos return ret;
187 1.17 christos #else
188 1.17 christos return NULL;
189 1.17 christos #endif
190 1.17 christos }
191 1.17 christos
192 1.17 christos int
193 1.17 christos set_rdomain(int fd, const char *name)
194 1.17 christos {
195 1.17 christos #ifdef SO_RTABLE
196 1.17 christos int rtable;
197 1.17 christos const char *errstr;
198 1.17 christos
199 1.17 christos if (name == NULL)
200 1.17 christos return 0; /* default table */
201 1.17 christos
202 1.17 christos rtable = (int)strtonum(name, 0, 255, &errstr);
203 1.17 christos if (errstr != NULL) {
204 1.17 christos /* Shouldn't happen */
205 1.17 christos error("Invalid routing domain \"%s\": %s", name, errstr);
206 1.17 christos return -1;
207 1.17 christos }
208 1.17 christos if (setsockopt(fd, SOL_SOCKET, SO_RTABLE,
209 1.17 christos &rtable, sizeof(rtable)) == -1) {
210 1.17 christos error("Failed to set routing domain %d on fd %d: %s",
211 1.17 christos rtable, fd, strerror(errno));
212 1.17 christos return -1;
213 1.17 christos }
214 1.17 christos return 0;
215 1.17 christos #else
216 1.17 christos return -1;
217 1.17 christos #endif
218 1.17 christos }
219 1.17 christos
220 1.20 christos /*
221 1.22 christos * Wait up to *timeoutp milliseconds for events on fd. Updates
222 1.20 christos * *timeoutp with time remaining.
223 1.20 christos * Returns 0 if fd ready or -1 on timeout or error (see errno).
224 1.20 christos */
225 1.22 christos static int
226 1.22 christos waitfd(int fd, int *timeoutp, short events)
227 1.20 christos {
228 1.20 christos struct pollfd pfd;
229 1.20 christos struct timeval t_start;
230 1.20 christos int oerrno, r;
231 1.20 christos
232 1.20 christos monotime_tv(&t_start);
233 1.20 christos pfd.fd = fd;
234 1.22 christos pfd.events = events;
235 1.20 christos for (; *timeoutp >= 0;) {
236 1.20 christos r = poll(&pfd, 1, *timeoutp);
237 1.20 christos oerrno = errno;
238 1.20 christos ms_subtract_diff(&t_start, timeoutp);
239 1.20 christos errno = oerrno;
240 1.20 christos if (r > 0)
241 1.20 christos return 0;
242 1.24 christos else if (r == -1 && errno != EAGAIN && errno != EINTR)
243 1.20 christos return -1;
244 1.20 christos else if (r == 0)
245 1.20 christos break;
246 1.20 christos }
247 1.20 christos /* timeout */
248 1.20 christos errno = ETIMEDOUT;
249 1.20 christos return -1;
250 1.20 christos }
251 1.20 christos
252 1.20 christos /*
253 1.22 christos * Wait up to *timeoutp milliseconds for fd to be readable. Updates
254 1.22 christos * *timeoutp with time remaining.
255 1.22 christos * Returns 0 if fd ready or -1 on timeout or error (see errno).
256 1.22 christos */
257 1.22 christos int
258 1.22 christos waitrfd(int fd, int *timeoutp) {
259 1.22 christos return waitfd(fd, timeoutp, POLLIN);
260 1.22 christos }
261 1.22 christos
262 1.22 christos /*
263 1.20 christos * Attempt a non-blocking connect(2) to the specified address, waiting up to
264 1.20 christos * *timeoutp milliseconds for the connection to complete. If the timeout is
265 1.20 christos * <=0, then wait indefinitely.
266 1.20 christos *
267 1.20 christos * Returns 0 on success or -1 on failure.
268 1.20 christos */
269 1.20 christos int
270 1.20 christos timeout_connect(int sockfd, const struct sockaddr *serv_addr,
271 1.20 christos socklen_t addrlen, int *timeoutp)
272 1.20 christos {
273 1.20 christos int optval = 0;
274 1.20 christos socklen_t optlen = sizeof(optval);
275 1.20 christos
276 1.20 christos /* No timeout: just do a blocking connect() */
277 1.20 christos if (timeoutp == NULL || *timeoutp <= 0)
278 1.20 christos return connect(sockfd, serv_addr, addrlen);
279 1.20 christos
280 1.20 christos set_nonblock(sockfd);
281 1.24 christos for (;;) {
282 1.24 christos if (connect(sockfd, serv_addr, addrlen) == 0) {
283 1.24 christos /* Succeeded already? */
284 1.24 christos unset_nonblock(sockfd);
285 1.24 christos return 0;
286 1.24 christos } else if (errno == EINTR)
287 1.24 christos continue;
288 1.24 christos else if (errno != EINPROGRESS)
289 1.24 christos return -1;
290 1.24 christos break;
291 1.24 christos }
292 1.20 christos
293 1.22 christos if (waitfd(sockfd, timeoutp, POLLIN | POLLOUT) == -1)
294 1.20 christos return -1;
295 1.20 christos
296 1.20 christos /* Completed or failed */
297 1.20 christos if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval, &optlen) == -1) {
298 1.20 christos debug("getsockopt: %s", strerror(errno));
299 1.20 christos return -1;
300 1.20 christos }
301 1.20 christos if (optval != 0) {
302 1.20 christos errno = optval;
303 1.20 christos return -1;
304 1.20 christos }
305 1.20 christos unset_nonblock(sockfd);
306 1.20 christos return 0;
307 1.20 christos }
308 1.20 christos
309 1.1 christos /* Characters considered whitespace in strsep calls. */
310 1.1 christos #define WHITESPACE " \t\r\n"
311 1.1 christos #define QUOTE "\""
312 1.1 christos
313 1.1 christos /* return next token in configuration line */
314 1.18 christos static char *
315 1.18 christos strdelim_internal(char **s, int split_equals)
316 1.1 christos {
317 1.1 christos char *old;
318 1.1 christos int wspace = 0;
319 1.1 christos
320 1.1 christos if (*s == NULL)
321 1.1 christos return NULL;
322 1.1 christos
323 1.1 christos old = *s;
324 1.1 christos
325 1.18 christos *s = strpbrk(*s,
326 1.18 christos split_equals ? WHITESPACE QUOTE "=" : WHITESPACE QUOTE);
327 1.1 christos if (*s == NULL)
328 1.1 christos return (old);
329 1.1 christos
330 1.1 christos if (*s[0] == '\"') {
331 1.1 christos memmove(*s, *s + 1, strlen(*s)); /* move nul too */
332 1.1 christos /* Find matching quote */
333 1.1 christos if ((*s = strpbrk(*s, QUOTE)) == NULL) {
334 1.1 christos return (NULL); /* no matching quote */
335 1.1 christos } else {
336 1.1 christos *s[0] = '\0';
337 1.4 adam *s += strspn(*s + 1, WHITESPACE) + 1;
338 1.1 christos return (old);
339 1.1 christos }
340 1.1 christos }
341 1.1 christos
342 1.1 christos /* Allow only one '=' to be skipped */
343 1.18 christos if (split_equals && *s[0] == '=')
344 1.1 christos wspace = 1;
345 1.1 christos *s[0] = '\0';
346 1.1 christos
347 1.1 christos /* Skip any extra whitespace after first token */
348 1.1 christos *s += strspn(*s + 1, WHITESPACE) + 1;
349 1.18 christos if (split_equals && *s[0] == '=' && !wspace)
350 1.1 christos *s += strspn(*s + 1, WHITESPACE) + 1;
351 1.1 christos
352 1.1 christos return (old);
353 1.1 christos }
354 1.1 christos
355 1.18 christos /*
356 1.18 christos * Return next token in configuration line; splts on whitespace or a
357 1.18 christos * single '=' character.
358 1.18 christos */
359 1.18 christos char *
360 1.18 christos strdelim(char **s)
361 1.18 christos {
362 1.18 christos return strdelim_internal(s, 1);
363 1.18 christos }
364 1.18 christos
365 1.18 christos /*
366 1.18 christos * Return next token in configuration line; splts on whitespace only.
367 1.18 christos */
368 1.18 christos char *
369 1.18 christos strdelimw(char **s)
370 1.18 christos {
371 1.18 christos return strdelim_internal(s, 0);
372 1.18 christos }
373 1.18 christos
374 1.1 christos struct passwd *
375 1.1 christos pwcopy(struct passwd *pw)
376 1.1 christos {
377 1.1 christos struct passwd *copy = xcalloc(1, sizeof(*copy));
378 1.1 christos
379 1.1 christos copy->pw_name = xstrdup(pw->pw_name);
380 1.1 christos copy->pw_passwd = xstrdup(pw->pw_passwd);
381 1.1 christos copy->pw_gecos = xstrdup(pw->pw_gecos);
382 1.1 christos copy->pw_uid = pw->pw_uid;
383 1.1 christos copy->pw_gid = pw->pw_gid;
384 1.1 christos copy->pw_expire = pw->pw_expire;
385 1.1 christos copy->pw_change = pw->pw_change;
386 1.1 christos copy->pw_class = xstrdup(pw->pw_class);
387 1.1 christos copy->pw_dir = xstrdup(pw->pw_dir);
388 1.1 christos copy->pw_shell = xstrdup(pw->pw_shell);
389 1.1 christos return copy;
390 1.1 christos }
391 1.1 christos
392 1.1 christos /*
393 1.1 christos * Convert ASCII string to TCP/IP port number.
394 1.1 christos * Port must be >=0 and <=65535.
395 1.1 christos * Return -1 if invalid.
396 1.1 christos */
397 1.1 christos int
398 1.1 christos a2port(const char *s)
399 1.1 christos {
400 1.20 christos struct servent *se;
401 1.1 christos long long port;
402 1.1 christos const char *errstr;
403 1.1 christos
404 1.1 christos port = strtonum(s, 0, 65535, &errstr);
405 1.20 christos if (errstr == NULL)
406 1.20 christos return (int)port;
407 1.20 christos if ((se = getservbyname(s, "tcp")) != NULL)
408 1.20 christos return ntohs(se->s_port);
409 1.20 christos return -1;
410 1.1 christos }
411 1.1 christos
412 1.1 christos int
413 1.1 christos a2tun(const char *s, int *remote)
414 1.1 christos {
415 1.1 christos const char *errstr = NULL;
416 1.1 christos char *sp, *ep;
417 1.1 christos int tun;
418 1.1 christos
419 1.1 christos if (remote != NULL) {
420 1.1 christos *remote = SSH_TUNID_ANY;
421 1.1 christos sp = xstrdup(s);
422 1.1 christos if ((ep = strchr(sp, ':')) == NULL) {
423 1.8 christos free(sp);
424 1.1 christos return (a2tun(s, NULL));
425 1.1 christos }
426 1.1 christos ep[0] = '\0'; ep++;
427 1.1 christos *remote = a2tun(ep, NULL);
428 1.1 christos tun = a2tun(sp, NULL);
429 1.8 christos free(sp);
430 1.1 christos return (*remote == SSH_TUNID_ERR ? *remote : tun);
431 1.1 christos }
432 1.1 christos
433 1.1 christos if (strcasecmp(s, "any") == 0)
434 1.1 christos return (SSH_TUNID_ANY);
435 1.1 christos
436 1.1 christos tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
437 1.1 christos if (errstr != NULL)
438 1.1 christos return (SSH_TUNID_ERR);
439 1.1 christos
440 1.1 christos return (tun);
441 1.1 christos }
442 1.1 christos
443 1.1 christos #define SECONDS 1
444 1.1 christos #define MINUTES (SECONDS * 60)
445 1.1 christos #define HOURS (MINUTES * 60)
446 1.1 christos #define DAYS (HOURS * 24)
447 1.1 christos #define WEEKS (DAYS * 7)
448 1.1 christos
449 1.1 christos /*
450 1.1 christos * Convert a time string into seconds; format is
451 1.1 christos * a sequence of:
452 1.1 christos * time[qualifier]
453 1.1 christos *
454 1.1 christos * Valid time qualifiers are:
455 1.1 christos * <none> seconds
456 1.1 christos * s|S seconds
457 1.1 christos * m|M minutes
458 1.1 christos * h|H hours
459 1.1 christos * d|D days
460 1.1 christos * w|W weeks
461 1.1 christos *
462 1.1 christos * Examples:
463 1.1 christos * 90m 90 minutes
464 1.1 christos * 1h30m 90 minutes
465 1.1 christos * 2d 2 days
466 1.1 christos * 1w 1 week
467 1.1 christos *
468 1.1 christos * Return -1 if time string is invalid.
469 1.1 christos */
470 1.1 christos long
471 1.1 christos convtime(const char *s)
472 1.1 christos {
473 1.24 christos long total, secs, multiplier;
474 1.1 christos const char *p;
475 1.1 christos char *endp;
476 1.1 christos
477 1.1 christos errno = 0;
478 1.1 christos total = 0;
479 1.1 christos p = s;
480 1.1 christos
481 1.1 christos if (p == NULL || *p == '\0')
482 1.1 christos return -1;
483 1.1 christos
484 1.1 christos while (*p) {
485 1.1 christos secs = strtol(p, &endp, 10);
486 1.1 christos if (p == endp ||
487 1.1 christos (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
488 1.1 christos secs < 0)
489 1.1 christos return -1;
490 1.1 christos
491 1.24 christos multiplier = 1;
492 1.1 christos switch (*endp++) {
493 1.1 christos case '\0':
494 1.1 christos endp--;
495 1.1 christos break;
496 1.1 christos case 's':
497 1.1 christos case 'S':
498 1.1 christos break;
499 1.1 christos case 'm':
500 1.1 christos case 'M':
501 1.15 christos multiplier = MINUTES;
502 1.1 christos break;
503 1.1 christos case 'h':
504 1.1 christos case 'H':
505 1.15 christos multiplier = HOURS;
506 1.1 christos break;
507 1.1 christos case 'd':
508 1.1 christos case 'D':
509 1.15 christos multiplier = DAYS;
510 1.1 christos break;
511 1.1 christos case 'w':
512 1.1 christos case 'W':
513 1.15 christos multiplier = WEEKS;
514 1.1 christos break;
515 1.1 christos default:
516 1.1 christos return -1;
517 1.1 christos }
518 1.15 christos if (secs >= LONG_MAX / multiplier)
519 1.15 christos return -1;
520 1.15 christos secs *= multiplier;
521 1.15 christos if (total >= LONG_MAX - secs)
522 1.15 christos return -1;
523 1.1 christos total += secs;
524 1.1 christos if (total < 0)
525 1.1 christos return -1;
526 1.1 christos p = endp;
527 1.1 christos }
528 1.1 christos
529 1.1 christos return total;
530 1.1 christos }
531 1.1 christos
532 1.24 christos #define TF_BUFS 8
533 1.24 christos #define TF_LEN 21
534 1.24 christos
535 1.24 christos const char *
536 1.24 christos fmt_timeframe(time_t t)
537 1.24 christos {
538 1.24 christos char *buf;
539 1.24 christos static char tfbuf[TF_BUFS][TF_LEN]; /* ring buffer */
540 1.24 christos static int idx = 0;
541 1.24 christos unsigned int sec, min, hrs, day;
542 1.24 christos unsigned long long week;
543 1.24 christos
544 1.24 christos buf = tfbuf[idx++];
545 1.24 christos if (idx == TF_BUFS)
546 1.24 christos idx = 0;
547 1.24 christos
548 1.24 christos week = t;
549 1.24 christos
550 1.24 christos sec = week % 60;
551 1.24 christos week /= 60;
552 1.24 christos min = week % 60;
553 1.24 christos week /= 60;
554 1.24 christos hrs = week % 24;
555 1.24 christos week /= 24;
556 1.24 christos day = week % 7;
557 1.24 christos week /= 7;
558 1.24 christos
559 1.24 christos if (week > 0)
560 1.24 christos snprintf(buf, TF_LEN, "%02lluw%01ud%02uh", week, day, hrs);
561 1.24 christos else if (day > 0)
562 1.24 christos snprintf(buf, TF_LEN, "%01ud%02uh%02um", day, hrs, min);
563 1.24 christos else
564 1.24 christos snprintf(buf, TF_LEN, "%02u:%02u:%02u", hrs, min, sec);
565 1.24 christos
566 1.24 christos return (buf);
567 1.24 christos }
568 1.24 christos
569 1.1 christos /*
570 1.1 christos * Returns a standardized host+port identifier string.
571 1.1 christos * Caller must free returned string.
572 1.1 christos */
573 1.1 christos char *
574 1.1 christos put_host_port(const char *host, u_short port)
575 1.1 christos {
576 1.1 christos char *hoststr;
577 1.1 christos
578 1.1 christos if (port == 0 || port == SSH_DEFAULT_PORT)
579 1.1 christos return(xstrdup(host));
580 1.21 christos if (asprintf(&hoststr, "[%s]:%d", host, (int)port) == -1)
581 1.1 christos fatal("put_host_port: asprintf: %s", strerror(errno));
582 1.1 christos debug3("put_host_port: %s", hoststr);
583 1.1 christos return hoststr;
584 1.1 christos }
585 1.1 christos
586 1.1 christos /*
587 1.1 christos * Search for next delimiter between hostnames/addresses and ports.
588 1.1 christos * Argument may be modified (for termination).
589 1.1 christos * Returns *cp if parsing succeeds.
590 1.17 christos * *cp is set to the start of the next field, if one was found.
591 1.17 christos * The delimiter char, if present, is stored in delim.
592 1.1 christos * If this is the last field, *cp is set to NULL.
593 1.1 christos */
594 1.20 christos char *
595 1.17 christos hpdelim2(char **cp, char *delim)
596 1.1 christos {
597 1.1 christos char *s, *old;
598 1.1 christos
599 1.1 christos if (cp == NULL || *cp == NULL)
600 1.1 christos return NULL;
601 1.1 christos
602 1.1 christos old = s = *cp;
603 1.1 christos if (*s == '[') {
604 1.1 christos if ((s = strchr(s, ']')) == NULL)
605 1.1 christos return NULL;
606 1.1 christos else
607 1.1 christos s++;
608 1.1 christos } else if ((s = strpbrk(s, ":/")) == NULL)
609 1.1 christos s = *cp + strlen(*cp); /* skip to end (see first case below) */
610 1.1 christos
611 1.1 christos switch (*s) {
612 1.1 christos case '\0':
613 1.1 christos *cp = NULL; /* no more fields*/
614 1.1 christos break;
615 1.1 christos
616 1.1 christos case ':':
617 1.1 christos case '/':
618 1.17 christos if (delim != NULL)
619 1.17 christos *delim = *s;
620 1.1 christos *s = '\0'; /* terminate */
621 1.1 christos *cp = s + 1;
622 1.1 christos break;
623 1.1 christos
624 1.1 christos default:
625 1.1 christos return NULL;
626 1.1 christos }
627 1.1 christos
628 1.1 christos return old;
629 1.1 christos }
630 1.1 christos
631 1.1 christos char *
632 1.17 christos hpdelim(char **cp)
633 1.17 christos {
634 1.17 christos return hpdelim2(cp, NULL);
635 1.17 christos }
636 1.17 christos
637 1.17 christos char *
638 1.1 christos cleanhostname(char *host)
639 1.1 christos {
640 1.1 christos if (*host == '[' && host[strlen(host) - 1] == ']') {
641 1.1 christos host[strlen(host) - 1] = '\0';
642 1.1 christos return (host + 1);
643 1.1 christos } else
644 1.1 christos return host;
645 1.1 christos }
646 1.1 christos
647 1.1 christos char *
648 1.1 christos colon(char *cp)
649 1.1 christos {
650 1.1 christos int flag = 0;
651 1.1 christos
652 1.1 christos if (*cp == ':') /* Leading colon is part of file name. */
653 1.4 adam return NULL;
654 1.1 christos if (*cp == '[')
655 1.1 christos flag = 1;
656 1.1 christos
657 1.1 christos for (; *cp; ++cp) {
658 1.1 christos if (*cp == '@' && *(cp+1) == '[')
659 1.1 christos flag = 1;
660 1.1 christos if (*cp == ']' && *(cp+1) == ':' && flag)
661 1.1 christos return (cp+1);
662 1.1 christos if (*cp == ':' && !flag)
663 1.1 christos return (cp);
664 1.1 christos if (*cp == '/')
665 1.4 adam return NULL;
666 1.1 christos }
667 1.4 adam return NULL;
668 1.1 christos }
669 1.1 christos
670 1.13 christos /*
671 1.17 christos * Parse a [user@]host:[path] string.
672 1.17 christos * Caller must free returned user, host and path.
673 1.17 christos * Any of the pointer return arguments may be NULL (useful for syntax checking).
674 1.17 christos * If user was not specified then *userp will be set to NULL.
675 1.17 christos * If host was not specified then *hostp will be set to NULL.
676 1.17 christos * If path was not specified then *pathp will be set to ".".
677 1.17 christos * Returns 0 on success, -1 on failure.
678 1.17 christos */
679 1.17 christos int
680 1.17 christos parse_user_host_path(const char *s, char **userp, char **hostp,
681 1.17 christos const char **pathp)
682 1.17 christos {
683 1.17 christos char *user = NULL, *host = NULL, *path = NULL;
684 1.17 christos char *tmp, *sdup;
685 1.17 christos int ret = -1;
686 1.17 christos
687 1.17 christos if (userp != NULL)
688 1.17 christos *userp = NULL;
689 1.17 christos if (hostp != NULL)
690 1.17 christos *hostp = NULL;
691 1.17 christos if (pathp != NULL)
692 1.17 christos *pathp = NULL;
693 1.17 christos
694 1.17 christos sdup = xstrdup(s);
695 1.17 christos
696 1.17 christos /* Check for remote syntax: [user@]host:[path] */
697 1.17 christos if ((tmp = colon(sdup)) == NULL)
698 1.17 christos goto out;
699 1.17 christos
700 1.17 christos /* Extract optional path */
701 1.17 christos *tmp++ = '\0';
702 1.17 christos if (*tmp == '\0')
703 1.17 christos tmp = __UNCONST(".");
704 1.17 christos path = xstrdup(tmp);
705 1.17 christos
706 1.17 christos /* Extract optional user and mandatory host */
707 1.17 christos tmp = strrchr(sdup, '@');
708 1.17 christos if (tmp != NULL) {
709 1.17 christos *tmp++ = '\0';
710 1.17 christos host = xstrdup(cleanhostname(tmp));
711 1.17 christos if (*sdup != '\0')
712 1.17 christos user = xstrdup(sdup);
713 1.17 christos } else {
714 1.17 christos host = xstrdup(cleanhostname(sdup));
715 1.17 christos user = NULL;
716 1.17 christos }
717 1.17 christos
718 1.17 christos /* Success */
719 1.17 christos if (userp != NULL) {
720 1.17 christos *userp = user;
721 1.17 christos user = NULL;
722 1.17 christos }
723 1.17 christos if (hostp != NULL) {
724 1.17 christos *hostp = host;
725 1.17 christos host = NULL;
726 1.17 christos }
727 1.17 christos if (pathp != NULL) {
728 1.17 christos *pathp = path;
729 1.17 christos path = NULL;
730 1.17 christos }
731 1.17 christos ret = 0;
732 1.17 christos out:
733 1.17 christos free(sdup);
734 1.17 christos free(user);
735 1.17 christos free(host);
736 1.17 christos free(path);
737 1.17 christos return ret;
738 1.17 christos }
739 1.17 christos
740 1.17 christos /*
741 1.13 christos * Parse a [user@]host[:port] string.
742 1.13 christos * Caller must free returned user and host.
743 1.13 christos * Any of the pointer return arguments may be NULL (useful for syntax checking).
744 1.13 christos * If user was not specified then *userp will be set to NULL.
745 1.13 christos * If port was not specified then *portp will be -1.
746 1.13 christos * Returns 0 on success, -1 on failure.
747 1.13 christos */
748 1.13 christos int
749 1.13 christos parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
750 1.13 christos {
751 1.13 christos char *sdup, *cp, *tmp;
752 1.13 christos char *user = NULL, *host = NULL;
753 1.13 christos int port = -1, ret = -1;
754 1.13 christos
755 1.13 christos if (userp != NULL)
756 1.13 christos *userp = NULL;
757 1.13 christos if (hostp != NULL)
758 1.13 christos *hostp = NULL;
759 1.13 christos if (portp != NULL)
760 1.13 christos *portp = -1;
761 1.13 christos
762 1.13 christos if ((sdup = tmp = strdup(s)) == NULL)
763 1.13 christos return -1;
764 1.13 christos /* Extract optional username */
765 1.17 christos if ((cp = strrchr(tmp, '@')) != NULL) {
766 1.13 christos *cp = '\0';
767 1.13 christos if (*tmp == '\0')
768 1.13 christos goto out;
769 1.13 christos if ((user = strdup(tmp)) == NULL)
770 1.13 christos goto out;
771 1.13 christos tmp = cp + 1;
772 1.13 christos }
773 1.13 christos /* Extract mandatory hostname */
774 1.13 christos if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
775 1.13 christos goto out;
776 1.13 christos host = xstrdup(cleanhostname(cp));
777 1.13 christos /* Convert and verify optional port */
778 1.13 christos if (tmp != NULL && *tmp != '\0') {
779 1.13 christos if ((port = a2port(tmp)) <= 0)
780 1.13 christos goto out;
781 1.13 christos }
782 1.13 christos /* Success */
783 1.13 christos if (userp != NULL) {
784 1.13 christos *userp = user;
785 1.13 christos user = NULL;
786 1.13 christos }
787 1.13 christos if (hostp != NULL) {
788 1.13 christos *hostp = host;
789 1.13 christos host = NULL;
790 1.13 christos }
791 1.13 christos if (portp != NULL)
792 1.13 christos *portp = port;
793 1.13 christos ret = 0;
794 1.13 christos out:
795 1.13 christos free(sdup);
796 1.13 christos free(user);
797 1.13 christos free(host);
798 1.13 christos return ret;
799 1.13 christos }
800 1.13 christos
801 1.17 christos /*
802 1.17 christos * Converts a two-byte hex string to decimal.
803 1.17 christos * Returns the decimal value or -1 for invalid input.
804 1.17 christos */
805 1.17 christos static int
806 1.17 christos hexchar(const char *s)
807 1.17 christos {
808 1.17 christos unsigned char result[2];
809 1.17 christos int i;
810 1.17 christos
811 1.17 christos for (i = 0; i < 2; i++) {
812 1.17 christos if (s[i] >= '0' && s[i] <= '9')
813 1.17 christos result[i] = (unsigned char)(s[i] - '0');
814 1.17 christos else if (s[i] >= 'a' && s[i] <= 'f')
815 1.17 christos result[i] = (unsigned char)(s[i] - 'a') + 10;
816 1.17 christos else if (s[i] >= 'A' && s[i] <= 'F')
817 1.17 christos result[i] = (unsigned char)(s[i] - 'A') + 10;
818 1.17 christos else
819 1.17 christos return -1;
820 1.17 christos }
821 1.17 christos return (result[0] << 4) | result[1];
822 1.17 christos }
823 1.17 christos
824 1.17 christos /*
825 1.17 christos * Decode an url-encoded string.
826 1.17 christos * Returns a newly allocated string on success or NULL on failure.
827 1.17 christos */
828 1.17 christos static char *
829 1.17 christos urldecode(const char *src)
830 1.17 christos {
831 1.17 christos char *ret, *dst;
832 1.17 christos int ch;
833 1.17 christos
834 1.17 christos ret = xmalloc(strlen(src) + 1);
835 1.17 christos for (dst = ret; *src != '\0'; src++) {
836 1.17 christos switch (*src) {
837 1.17 christos case '+':
838 1.17 christos *dst++ = ' ';
839 1.17 christos break;
840 1.17 christos case '%':
841 1.17 christos if (!isxdigit((unsigned char)src[1]) ||
842 1.17 christos !isxdigit((unsigned char)src[2]) ||
843 1.17 christos (ch = hexchar(src + 1)) == -1) {
844 1.17 christos free(ret);
845 1.17 christos return NULL;
846 1.17 christos }
847 1.17 christos *dst++ = ch;
848 1.17 christos src += 2;
849 1.17 christos break;
850 1.17 christos default:
851 1.17 christos *dst++ = *src;
852 1.17 christos break;
853 1.17 christos }
854 1.17 christos }
855 1.17 christos *dst = '\0';
856 1.17 christos
857 1.17 christos return ret;
858 1.17 christos }
859 1.17 christos
860 1.17 christos /*
861 1.17 christos * Parse an (scp|ssh|sftp)://[user@]host[:port][/path] URI.
862 1.17 christos * See https://tools.ietf.org/html/draft-ietf-secsh-scp-sftp-ssh-uri-04
863 1.17 christos * Either user or path may be url-encoded (but not host or port).
864 1.17 christos * Caller must free returned user, host and path.
865 1.17 christos * Any of the pointer return arguments may be NULL (useful for syntax checking)
866 1.17 christos * but the scheme must always be specified.
867 1.17 christos * If user was not specified then *userp will be set to NULL.
868 1.17 christos * If port was not specified then *portp will be -1.
869 1.17 christos * If path was not specified then *pathp will be set to NULL.
870 1.17 christos * Returns 0 on success, 1 if non-uri/wrong scheme, -1 on error/invalid uri.
871 1.17 christos */
872 1.17 christos int
873 1.17 christos parse_uri(const char *scheme, const char *uri, char **userp, char **hostp,
874 1.17 christos int *portp, const char **pathp)
875 1.17 christos {
876 1.17 christos char *uridup, *cp, *tmp, ch;
877 1.17 christos char *user = NULL, *host = NULL, *path = NULL;
878 1.17 christos int port = -1, ret = -1;
879 1.17 christos size_t len;
880 1.17 christos
881 1.17 christos len = strlen(scheme);
882 1.17 christos if (strncmp(uri, scheme, len) != 0 || strncmp(uri + len, "://", 3) != 0)
883 1.17 christos return 1;
884 1.17 christos uri += len + 3;
885 1.17 christos
886 1.17 christos if (userp != NULL)
887 1.17 christos *userp = NULL;
888 1.17 christos if (hostp != NULL)
889 1.17 christos *hostp = NULL;
890 1.17 christos if (portp != NULL)
891 1.17 christos *portp = -1;
892 1.17 christos if (pathp != NULL)
893 1.17 christos *pathp = NULL;
894 1.17 christos
895 1.17 christos uridup = tmp = xstrdup(uri);
896 1.17 christos
897 1.17 christos /* Extract optional ssh-info (username + connection params) */
898 1.17 christos if ((cp = strchr(tmp, '@')) != NULL) {
899 1.17 christos char *delim;
900 1.17 christos
901 1.17 christos *cp = '\0';
902 1.17 christos /* Extract username and connection params */
903 1.17 christos if ((delim = strchr(tmp, ';')) != NULL) {
904 1.17 christos /* Just ignore connection params for now */
905 1.17 christos *delim = '\0';
906 1.17 christos }
907 1.17 christos if (*tmp == '\0') {
908 1.17 christos /* Empty username */
909 1.17 christos goto out;
910 1.17 christos }
911 1.17 christos if ((user = urldecode(tmp)) == NULL)
912 1.17 christos goto out;
913 1.17 christos tmp = cp + 1;
914 1.17 christos }
915 1.17 christos
916 1.17 christos /* Extract mandatory hostname */
917 1.17 christos if ((cp = hpdelim2(&tmp, &ch)) == NULL || *cp == '\0')
918 1.17 christos goto out;
919 1.17 christos host = xstrdup(cleanhostname(cp));
920 1.17 christos if (!valid_domain(host, 0, NULL))
921 1.17 christos goto out;
922 1.17 christos
923 1.17 christos if (tmp != NULL && *tmp != '\0') {
924 1.17 christos if (ch == ':') {
925 1.17 christos /* Convert and verify port. */
926 1.17 christos if ((cp = strchr(tmp, '/')) != NULL)
927 1.17 christos *cp = '\0';
928 1.17 christos if ((port = a2port(tmp)) <= 0)
929 1.17 christos goto out;
930 1.17 christos tmp = cp ? cp + 1 : NULL;
931 1.17 christos }
932 1.17 christos if (tmp != NULL && *tmp != '\0') {
933 1.17 christos /* Extract optional path */
934 1.17 christos if ((path = urldecode(tmp)) == NULL)
935 1.17 christos goto out;
936 1.17 christos }
937 1.17 christos }
938 1.17 christos
939 1.17 christos /* Success */
940 1.17 christos if (userp != NULL) {
941 1.17 christos *userp = user;
942 1.17 christos user = NULL;
943 1.17 christos }
944 1.17 christos if (hostp != NULL) {
945 1.17 christos *hostp = host;
946 1.17 christos host = NULL;
947 1.17 christos }
948 1.17 christos if (portp != NULL)
949 1.17 christos *portp = port;
950 1.17 christos if (pathp != NULL) {
951 1.17 christos *pathp = path;
952 1.17 christos path = NULL;
953 1.17 christos }
954 1.17 christos ret = 0;
955 1.17 christos out:
956 1.17 christos free(uridup);
957 1.17 christos free(user);
958 1.17 christos free(host);
959 1.17 christos free(path);
960 1.17 christos return ret;
961 1.17 christos }
962 1.17 christos
963 1.1 christos /* function to assist building execv() arguments */
964 1.1 christos void
965 1.5 christos addargs(arglist *args, const char *fmt, ...)
966 1.1 christos {
967 1.1 christos va_list ap;
968 1.1 christos char *cp;
969 1.1 christos u_int nalloc;
970 1.1 christos int r;
971 1.1 christos
972 1.1 christos va_start(ap, fmt);
973 1.1 christos r = vasprintf(&cp, fmt, ap);
974 1.1 christos va_end(ap);
975 1.1 christos if (r == -1)
976 1.1 christos fatal("addargs: argument too long");
977 1.1 christos
978 1.1 christos nalloc = args->nalloc;
979 1.1 christos if (args->list == NULL) {
980 1.1 christos nalloc = 32;
981 1.1 christos args->num = 0;
982 1.1 christos } else if (args->num+2 >= nalloc)
983 1.1 christos nalloc *= 2;
984 1.1 christos
985 1.16 christos args->list = xrecallocarray(args->list, args->nalloc, nalloc, sizeof(char *));
986 1.1 christos args->nalloc = nalloc;
987 1.1 christos args->list[args->num++] = cp;
988 1.1 christos args->list[args->num] = NULL;
989 1.1 christos }
990 1.1 christos
991 1.1 christos void
992 1.5 christos replacearg(arglist *args, u_int which, const char *fmt, ...)
993 1.1 christos {
994 1.1 christos va_list ap;
995 1.1 christos char *cp;
996 1.1 christos int r;
997 1.1 christos
998 1.1 christos va_start(ap, fmt);
999 1.1 christos r = vasprintf(&cp, fmt, ap);
1000 1.1 christos va_end(ap);
1001 1.1 christos if (r == -1)
1002 1.1 christos fatal("replacearg: argument too long");
1003 1.1 christos
1004 1.1 christos if (which >= args->num)
1005 1.1 christos fatal("replacearg: tried to replace invalid arg %d >= %d",
1006 1.1 christos which, args->num);
1007 1.8 christos free(args->list[which]);
1008 1.1 christos args->list[which] = cp;
1009 1.1 christos }
1010 1.1 christos
1011 1.1 christos void
1012 1.1 christos freeargs(arglist *args)
1013 1.1 christos {
1014 1.1 christos u_int i;
1015 1.1 christos
1016 1.1 christos if (args->list != NULL) {
1017 1.1 christos for (i = 0; i < args->num; i++)
1018 1.8 christos free(args->list[i]);
1019 1.8 christos free(args->list);
1020 1.1 christos args->nalloc = args->num = 0;
1021 1.1 christos args->list = NULL;
1022 1.1 christos }
1023 1.1 christos }
1024 1.1 christos
1025 1.1 christos /*
1026 1.1 christos * Expands tildes in the file name. Returns data allocated by xmalloc.
1027 1.1 christos * Warning: this calls getpw*.
1028 1.1 christos */
1029 1.1 christos char *
1030 1.1 christos tilde_expand_filename(const char *filename, uid_t uid)
1031 1.1 christos {
1032 1.8 christos const char *path, *sep;
1033 1.8 christos char user[128], *ret, *homedir;
1034 1.1 christos struct passwd *pw;
1035 1.1 christos u_int len, slash;
1036 1.1 christos
1037 1.1 christos if (*filename != '~')
1038 1.1 christos return (xstrdup(filename));
1039 1.1 christos filename++;
1040 1.1 christos
1041 1.1 christos path = strchr(filename, '/');
1042 1.1 christos if (path != NULL && path > filename) { /* ~user/path */
1043 1.1 christos slash = path - filename;
1044 1.1 christos if (slash > sizeof(user) - 1)
1045 1.1 christos fatal("tilde_expand_filename: ~username too long");
1046 1.1 christos memcpy(user, filename, slash);
1047 1.1 christos user[slash] = '\0';
1048 1.1 christos if ((pw = getpwnam(user)) == NULL)
1049 1.1 christos fatal("tilde_expand_filename: No such user %s", user);
1050 1.2 christos homedir = pw->pw_dir;
1051 1.2 christos } else {
1052 1.2 christos if ((pw = getpwuid(uid)) == NULL) /* ~/path */
1053 1.2 christos fatal("tilde_expand_filename: No such uid %ld",
1054 1.2 christos (long)uid);
1055 1.2 christos homedir = pw->pw_dir;
1056 1.2 christos }
1057 1.1 christos
1058 1.1 christos /* Make sure directory has a trailing '/' */
1059 1.2 christos len = strlen(homedir);
1060 1.8 christos if (len == 0 || homedir[len - 1] != '/')
1061 1.8 christos sep = "/";
1062 1.8 christos else
1063 1.8 christos sep = "";
1064 1.1 christos
1065 1.1 christos /* Skip leading '/' from specified path */
1066 1.1 christos if (path != NULL)
1067 1.1 christos filename = path + 1;
1068 1.8 christos
1069 1.10 christos if (xasprintf(&ret, "%s%s%s", homedir, sep, filename) >= PATH_MAX)
1070 1.1 christos fatal("tilde_expand_filename: Path too long");
1071 1.1 christos
1072 1.8 christos return (ret);
1073 1.1 christos }
1074 1.1 christos
1075 1.1 christos /*
1076 1.24 christos * Expand a string with a set of %[char] escapes and/or ${ENVIRONMENT}
1077 1.24 christos * substitutions. A number of escapes may be specified as
1078 1.24 christos * (char *escape_chars, char *replacement) pairs. The list must be terminated
1079 1.24 christos * by a NULL escape_char. Returns replaced string in memory allocated by
1080 1.24 christos * xmalloc which the caller must free.
1081 1.1 christos */
1082 1.24 christos static char *
1083 1.24 christos vdollar_percent_expand(int *parseerror, int dollar, int percent,
1084 1.24 christos const char *string, va_list ap)
1085 1.1 christos {
1086 1.1 christos #define EXPAND_MAX_KEYS 16
1087 1.24 christos u_int num_keys = 0, i;
1088 1.1 christos struct {
1089 1.1 christos const char *key;
1090 1.1 christos const char *repl;
1091 1.1 christos } keys[EXPAND_MAX_KEYS];
1092 1.21 christos struct sshbuf *buf;
1093 1.24 christos int r, missingvar = 0;
1094 1.24 christos char *ret = NULL, *var, *varend, *val;
1095 1.24 christos size_t len;
1096 1.21 christos
1097 1.21 christos if ((buf = sshbuf_new()) == NULL)
1098 1.21 christos fatal("%s: sshbuf_new failed", __func__);
1099 1.24 christos if (parseerror == NULL)
1100 1.24 christos fatal("%s: null parseerror arg", __func__);
1101 1.24 christos *parseerror = 1;
1102 1.24 christos
1103 1.24 christos /* Gather keys if we're doing percent expansion. */
1104 1.24 christos if (percent) {
1105 1.24 christos for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
1106 1.24 christos keys[num_keys].key = va_arg(ap, char *);
1107 1.24 christos if (keys[num_keys].key == NULL)
1108 1.24 christos break;
1109 1.24 christos keys[num_keys].repl = va_arg(ap, char *);
1110 1.24 christos if (keys[num_keys].repl == NULL)
1111 1.24 christos fatal("%s: NULL replacement for token %s", __func__, keys[num_keys].key);
1112 1.24 christos }
1113 1.24 christos if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
1114 1.24 christos fatal("%s: too many keys", __func__);
1115 1.24 christos if (num_keys == 0)
1116 1.24 christos fatal("%s: percent expansion without token list",
1117 1.24 christos __func__);
1118 1.1 christos }
1119 1.1 christos
1120 1.1 christos /* Expand string */
1121 1.1 christos for (i = 0; *string != '\0'; string++) {
1122 1.24 christos /* Optionally process ${ENVIRONMENT} expansions. */
1123 1.24 christos if (dollar && string[0] == '$' && string[1] == '{') {
1124 1.24 christos string += 2; /* skip over '${' */
1125 1.24 christos if ((varend = strchr(string, '}')) == NULL) {
1126 1.24 christos error("%s: environment variable '%s' missing "
1127 1.24 christos "closing '}'", __func__, string);
1128 1.24 christos goto out;
1129 1.24 christos }
1130 1.24 christos len = varend - string;
1131 1.24 christos if (len == 0) {
1132 1.24 christos error("%s: zero-length environment variable",
1133 1.24 christos __func__);
1134 1.24 christos goto out;
1135 1.24 christos }
1136 1.24 christos var = xmalloc(len + 1);
1137 1.24 christos (void)strlcpy(var, string, len + 1);
1138 1.24 christos if ((val = getenv(var)) == NULL) {
1139 1.24 christos error("%s: env var ${%s} has no value",
1140 1.24 christos __func__, var);
1141 1.24 christos missingvar = 1;
1142 1.24 christos } else {
1143 1.24 christos debug3("%s: expand ${%s} -> '%s'", __func__,
1144 1.24 christos var, val);
1145 1.24 christos if ((r = sshbuf_put(buf, val, strlen(val))) !=0)
1146 1.24 christos fatal("%s: sshbuf_put: %s", __func__,
1147 1.24 christos ssh_err(r));
1148 1.24 christos }
1149 1.24 christos free(var);
1150 1.24 christos string += len;
1151 1.24 christos continue;
1152 1.24 christos }
1153 1.24 christos
1154 1.24 christos /*
1155 1.24 christos * Process percent expansions if we have a list of TOKENs.
1156 1.24 christos * If we're not doing percent expansion everything just gets
1157 1.24 christos * appended here.
1158 1.24 christos */
1159 1.24 christos if (*string != '%' || !percent) {
1160 1.1 christos append:
1161 1.21 christos if ((r = sshbuf_put_u8(buf, *string)) != 0) {
1162 1.21 christos fatal("%s: sshbuf_put_u8: %s",
1163 1.21 christos __func__, ssh_err(r));
1164 1.21 christos }
1165 1.1 christos continue;
1166 1.1 christos }
1167 1.1 christos string++;
1168 1.4 adam /* %% case */
1169 1.1 christos if (*string == '%')
1170 1.1 christos goto append;
1171 1.24 christos if (*string == '\0') {
1172 1.24 christos error("%s: invalid format", __func__);
1173 1.24 christos goto out;
1174 1.24 christos }
1175 1.21 christos for (i = 0; i < num_keys; i++) {
1176 1.21 christos if (strchr(keys[i].key, *string) != NULL) {
1177 1.21 christos if ((r = sshbuf_put(buf, keys[i].repl,
1178 1.21 christos strlen(keys[i].repl))) != 0) {
1179 1.21 christos fatal("%s: sshbuf_put: %s",
1180 1.21 christos __func__, ssh_err(r));
1181 1.21 christos }
1182 1.1 christos break;
1183 1.1 christos }
1184 1.1 christos }
1185 1.24 christos if (i >= num_keys) {
1186 1.24 christos error("%s: unknown key %%%c", __func__, *string);
1187 1.24 christos goto out;
1188 1.24 christos }
1189 1.1 christos }
1190 1.24 christos if (!missingvar && (ret = sshbuf_dup_string(buf)) == NULL)
1191 1.21 christos fatal("%s: sshbuf_dup_string failed", __func__);
1192 1.24 christos *parseerror = 0;
1193 1.24 christos out:
1194 1.21 christos sshbuf_free(buf);
1195 1.24 christos return *parseerror ? NULL : ret;
1196 1.24 christos #undef EXPAND_MAX_KEYS
1197 1.24 christos }
1198 1.24 christos
1199 1.24 christos /*
1200 1.24 christos * Expand only environment variables.
1201 1.24 christos * Note that although this function is variadic like the other similar
1202 1.24 christos * functions, any such arguments will be unused.
1203 1.24 christos */
1204 1.24 christos
1205 1.24 christos char *
1206 1.24 christos dollar_expand(int *parseerr, const char *string, ...)
1207 1.24 christos {
1208 1.24 christos char *ret;
1209 1.24 christos int err;
1210 1.24 christos va_list ap;
1211 1.24 christos
1212 1.24 christos va_start(ap, string);
1213 1.24 christos ret = vdollar_percent_expand(&err, 1, 0, string, ap);
1214 1.24 christos va_end(ap);
1215 1.24 christos if (parseerr != NULL)
1216 1.24 christos *parseerr = err;
1217 1.24 christos return ret;
1218 1.24 christos }
1219 1.24 christos
1220 1.24 christos /*
1221 1.24 christos * Returns expanded string or NULL if a specified environment variable is
1222 1.24 christos * not defined, or calls fatal if the string is invalid.
1223 1.24 christos */
1224 1.24 christos char *
1225 1.24 christos percent_expand(const char *string, ...)
1226 1.24 christos {
1227 1.24 christos char *ret;
1228 1.24 christos int err;
1229 1.24 christos va_list ap;
1230 1.24 christos
1231 1.24 christos va_start(ap, string);
1232 1.24 christos ret = vdollar_percent_expand(&err, 0, 1, string, ap);
1233 1.24 christos va_end(ap);
1234 1.24 christos if (err)
1235 1.24 christos fatal("%s failed", __func__);
1236 1.24 christos return ret;
1237 1.24 christos }
1238 1.24 christos
1239 1.24 christos /*
1240 1.24 christos * Returns expanded string or NULL if a specified environment variable is
1241 1.24 christos * not defined, or calls fatal if the string is invalid.
1242 1.24 christos */
1243 1.24 christos char *
1244 1.24 christos percent_dollar_expand(const char *string, ...)
1245 1.24 christos {
1246 1.24 christos char *ret;
1247 1.24 christos int err;
1248 1.24 christos va_list ap;
1249 1.24 christos
1250 1.24 christos va_start(ap, string);
1251 1.24 christos ret = vdollar_percent_expand(&err, 1, 1, string, ap);
1252 1.24 christos va_end(ap);
1253 1.24 christos if (err)
1254 1.24 christos fatal("%s failed", __func__);
1255 1.21 christos return ret;
1256 1.1 christos }
1257 1.1 christos
1258 1.1 christos int
1259 1.17 christos tun_open(int tun, int mode, char **ifname)
1260 1.1 christos {
1261 1.1 christos struct ifreq ifr;
1262 1.12 christos char name[100];
1263 1.12 christos int fd = -1, sock;
1264 1.12 christos const char *tunbase = "tun";
1265 1.12 christos
1266 1.17 christos if (ifname != NULL)
1267 1.17 christos *ifname = NULL;
1268 1.17 christos
1269 1.12 christos if (mode == SSH_TUNMODE_ETHERNET)
1270 1.12 christos tunbase = "tap";
1271 1.1 christos
1272 1.1 christos /* Open the tunnel device */
1273 1.1 christos if (tun <= SSH_TUNID_MAX) {
1274 1.12 christos snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
1275 1.12 christos fd = open(name, O_RDWR);
1276 1.1 christos } else if (tun == SSH_TUNID_ANY) {
1277 1.1 christos for (tun = 100; tun >= 0; tun--) {
1278 1.12 christos snprintf(name, sizeof(name), "/dev/%s%d",
1279 1.12 christos tunbase, tun);
1280 1.12 christos if ((fd = open(name, O_RDWR)) >= 0)
1281 1.1 christos break;
1282 1.1 christos }
1283 1.1 christos } else {
1284 1.1 christos debug("%s: invalid tunnel %u", __func__, tun);
1285 1.12 christos return -1;
1286 1.1 christos }
1287 1.1 christos
1288 1.21 christos if (fd == -1) {
1289 1.12 christos debug("%s: %s open: %s", __func__, name, strerror(errno));
1290 1.12 christos return -1;
1291 1.1 christos }
1292 1.1 christos
1293 1.1 christos
1294 1.12 christos #ifdef TUNSIFHEAD
1295 1.2 christos /* Turn on tunnel headers */
1296 1.12 christos int flag = 1;
1297 1.2 christos if (mode != SSH_TUNMODE_ETHERNET &&
1298 1.2 christos ioctl(fd, TUNSIFHEAD, &flag) == -1) {
1299 1.2 christos debug("%s: ioctl(%d, TUNSIFHEAD, 1): %s", __func__, fd,
1300 1.2 christos strerror(errno));
1301 1.2 christos close(fd);
1302 1.2 christos return -1;
1303 1.2 christos }
1304 1.12 christos #endif
1305 1.2 christos
1306 1.2 christos debug("%s: %s mode %d fd %d", __func__, ifr.ifr_name, mode, fd);
1307 1.12 christos /* Bring interface up if it is not already */
1308 1.3 jnemeth snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
1309 1.1 christos if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
1310 1.1 christos goto failed;
1311 1.1 christos
1312 1.12 christos if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
1313 1.12 christos debug("%s: get interface %s flags: %s", __func__,
1314 1.12 christos ifr.ifr_name, strerror(errno));
1315 1.1 christos goto failed;
1316 1.12 christos }
1317 1.1 christos
1318 1.12 christos if (!(ifr.ifr_flags & IFF_UP)) {
1319 1.12 christos ifr.ifr_flags |= IFF_UP;
1320 1.12 christos if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
1321 1.12 christos debug("%s: activate interface %s: %s", __func__,
1322 1.12 christos ifr.ifr_name, strerror(errno));
1323 1.12 christos goto failed;
1324 1.12 christos }
1325 1.12 christos }
1326 1.1 christos
1327 1.17 christos if (ifname != NULL)
1328 1.17 christos *ifname = xstrdup(ifr.ifr_name);
1329 1.17 christos
1330 1.1 christos close(sock);
1331 1.12 christos return fd;
1332 1.1 christos
1333 1.1 christos failed:
1334 1.1 christos if (fd >= 0)
1335 1.1 christos close(fd);
1336 1.1 christos if (sock >= 0)
1337 1.1 christos close(sock);
1338 1.2 christos debug("%s: failed to set %s mode %d: %s", __func__, ifr.ifr_name,
1339 1.1 christos mode, strerror(errno));
1340 1.12 christos return -1;
1341 1.1 christos }
1342 1.1 christos
1343 1.1 christos void
1344 1.1 christos sanitise_stdfd(void)
1345 1.1 christos {
1346 1.1 christos int nullfd, dupfd;
1347 1.1 christos
1348 1.1 christos if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1349 1.1 christos fprintf(stderr, "Couldn't open /dev/null: %s\n",
1350 1.1 christos strerror(errno));
1351 1.1 christos exit(1);
1352 1.1 christos }
1353 1.13 christos while (++dupfd <= STDERR_FILENO) {
1354 1.13 christos /* Only populate closed fds. */
1355 1.13 christos if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
1356 1.13 christos if (dup2(nullfd, dupfd) == -1) {
1357 1.13 christos fprintf(stderr, "dup2: %s\n", strerror(errno));
1358 1.13 christos exit(1);
1359 1.13 christos }
1360 1.1 christos }
1361 1.1 christos }
1362 1.13 christos if (nullfd > STDERR_FILENO)
1363 1.1 christos close(nullfd);
1364 1.1 christos }
1365 1.1 christos
1366 1.1 christos char *
1367 1.1 christos tohex(const void *vp, size_t l)
1368 1.1 christos {
1369 1.1 christos const u_char *p = (const u_char *)vp;
1370 1.1 christos char b[3], *r;
1371 1.1 christos size_t i, hl;
1372 1.1 christos
1373 1.1 christos if (l > 65536)
1374 1.1 christos return xstrdup("tohex: length > 65536");
1375 1.1 christos
1376 1.1 christos hl = l * 2 + 1;
1377 1.1 christos r = xcalloc(1, hl);
1378 1.1 christos for (i = 0; i < l; i++) {
1379 1.1 christos snprintf(b, sizeof(b), "%02x", p[i]);
1380 1.1 christos strlcat(r, b, hl);
1381 1.1 christos }
1382 1.1 christos return (r);
1383 1.1 christos }
1384 1.1 christos
1385 1.22 christos /*
1386 1.22 christos * Extend string *sp by the specified format. If *sp is not NULL (or empty),
1387 1.22 christos * then the separator 'sep' will be prepended before the formatted arguments.
1388 1.22 christos * Extended strings are heap allocated.
1389 1.22 christos */
1390 1.22 christos void
1391 1.22 christos xextendf(char **sp, const char *sep, const char *fmt, ...)
1392 1.22 christos {
1393 1.22 christos va_list ap;
1394 1.22 christos char *tmp1, *tmp2;
1395 1.22 christos
1396 1.22 christos va_start(ap, fmt);
1397 1.22 christos xvasprintf(&tmp1, fmt, ap);
1398 1.22 christos va_end(ap);
1399 1.22 christos
1400 1.22 christos if (*sp == NULL || **sp == '\0') {
1401 1.22 christos free(*sp);
1402 1.22 christos *sp = tmp1;
1403 1.22 christos return;
1404 1.22 christos }
1405 1.22 christos xasprintf(&tmp2, "%s%s%s", *sp, sep == NULL ? "" : sep, tmp1);
1406 1.22 christos free(tmp1);
1407 1.22 christos free(*sp);
1408 1.22 christos *sp = tmp2;
1409 1.22 christos }
1410 1.22 christos
1411 1.22 christos
1412 1.1 christos u_int64_t
1413 1.1 christos get_u64(const void *vp)
1414 1.1 christos {
1415 1.1 christos const u_char *p = (const u_char *)vp;
1416 1.1 christos u_int64_t v;
1417 1.1 christos
1418 1.1 christos v = (u_int64_t)p[0] << 56;
1419 1.1 christos v |= (u_int64_t)p[1] << 48;
1420 1.1 christos v |= (u_int64_t)p[2] << 40;
1421 1.1 christos v |= (u_int64_t)p[3] << 32;
1422 1.1 christos v |= (u_int64_t)p[4] << 24;
1423 1.1 christos v |= (u_int64_t)p[5] << 16;
1424 1.1 christos v |= (u_int64_t)p[6] << 8;
1425 1.1 christos v |= (u_int64_t)p[7];
1426 1.1 christos
1427 1.1 christos return (v);
1428 1.1 christos }
1429 1.1 christos
1430 1.1 christos u_int32_t
1431 1.1 christos get_u32(const void *vp)
1432 1.1 christos {
1433 1.1 christos const u_char *p = (const u_char *)vp;
1434 1.1 christos u_int32_t v;
1435 1.1 christos
1436 1.1 christos v = (u_int32_t)p[0] << 24;
1437 1.1 christos v |= (u_int32_t)p[1] << 16;
1438 1.1 christos v |= (u_int32_t)p[2] << 8;
1439 1.1 christos v |= (u_int32_t)p[3];
1440 1.1 christos
1441 1.1 christos return (v);
1442 1.1 christos }
1443 1.1 christos
1444 1.9 christos u_int32_t
1445 1.9 christos get_u32_le(const void *vp)
1446 1.9 christos {
1447 1.9 christos const u_char *p = (const u_char *)vp;
1448 1.9 christos u_int32_t v;
1449 1.9 christos
1450 1.9 christos v = (u_int32_t)p[0];
1451 1.9 christos v |= (u_int32_t)p[1] << 8;
1452 1.9 christos v |= (u_int32_t)p[2] << 16;
1453 1.9 christos v |= (u_int32_t)p[3] << 24;
1454 1.9 christos
1455 1.9 christos return (v);
1456 1.9 christos }
1457 1.9 christos
1458 1.1 christos u_int16_t
1459 1.1 christos get_u16(const void *vp)
1460 1.1 christos {
1461 1.1 christos const u_char *p = (const u_char *)vp;
1462 1.1 christos u_int16_t v;
1463 1.1 christos
1464 1.1 christos v = (u_int16_t)p[0] << 8;
1465 1.1 christos v |= (u_int16_t)p[1];
1466 1.1 christos
1467 1.1 christos return (v);
1468 1.1 christos }
1469 1.1 christos
1470 1.1 christos void
1471 1.1 christos put_u64(void *vp, u_int64_t v)
1472 1.1 christos {
1473 1.1 christos u_char *p = (u_char *)vp;
1474 1.1 christos
1475 1.1 christos p[0] = (u_char)(v >> 56) & 0xff;
1476 1.1 christos p[1] = (u_char)(v >> 48) & 0xff;
1477 1.1 christos p[2] = (u_char)(v >> 40) & 0xff;
1478 1.1 christos p[3] = (u_char)(v >> 32) & 0xff;
1479 1.1 christos p[4] = (u_char)(v >> 24) & 0xff;
1480 1.1 christos p[5] = (u_char)(v >> 16) & 0xff;
1481 1.1 christos p[6] = (u_char)(v >> 8) & 0xff;
1482 1.1 christos p[7] = (u_char)v & 0xff;
1483 1.1 christos }
1484 1.1 christos
1485 1.1 christos void
1486 1.1 christos put_u32(void *vp, u_int32_t v)
1487 1.1 christos {
1488 1.1 christos u_char *p = (u_char *)vp;
1489 1.1 christos
1490 1.1 christos p[0] = (u_char)(v >> 24) & 0xff;
1491 1.1 christos p[1] = (u_char)(v >> 16) & 0xff;
1492 1.1 christos p[2] = (u_char)(v >> 8) & 0xff;
1493 1.1 christos p[3] = (u_char)v & 0xff;
1494 1.1 christos }
1495 1.1 christos
1496 1.9 christos void
1497 1.9 christos put_u32_le(void *vp, u_int32_t v)
1498 1.9 christos {
1499 1.9 christos u_char *p = (u_char *)vp;
1500 1.9 christos
1501 1.9 christos p[0] = (u_char)v & 0xff;
1502 1.9 christos p[1] = (u_char)(v >> 8) & 0xff;
1503 1.9 christos p[2] = (u_char)(v >> 16) & 0xff;
1504 1.9 christos p[3] = (u_char)(v >> 24) & 0xff;
1505 1.9 christos }
1506 1.1 christos
1507 1.1 christos void
1508 1.1 christos put_u16(void *vp, u_int16_t v)
1509 1.1 christos {
1510 1.1 christos u_char *p = (u_char *)vp;
1511 1.1 christos
1512 1.1 christos p[0] = (u_char)(v >> 8) & 0xff;
1513 1.1 christos p[1] = (u_char)v & 0xff;
1514 1.1 christos }
1515 1.1 christos
1516 1.1 christos void
1517 1.1 christos ms_subtract_diff(struct timeval *start, int *ms)
1518 1.1 christos {
1519 1.1 christos struct timeval diff, finish;
1520 1.1 christos
1521 1.17 christos monotime_tv(&finish);
1522 1.17 christos timersub(&finish, start, &diff);
1523 1.1 christos *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
1524 1.1 christos }
1525 1.1 christos
1526 1.1 christos void
1527 1.1 christos ms_to_timeval(struct timeval *tv, int ms)
1528 1.1 christos {
1529 1.1 christos if (ms < 0)
1530 1.1 christos ms = 0;
1531 1.1 christos tv->tv_sec = ms / 1000;
1532 1.1 christos tv->tv_usec = (ms % 1000) * 1000;
1533 1.1 christos }
1534 1.1 christos
1535 1.17 christos void
1536 1.17 christos monotime_ts(struct timespec *ts)
1537 1.17 christos {
1538 1.17 christos if (clock_gettime(CLOCK_MONOTONIC, ts) != 0)
1539 1.17 christos fatal("clock_gettime: %s", strerror(errno));
1540 1.17 christos }
1541 1.17 christos
1542 1.17 christos void
1543 1.17 christos monotime_tv(struct timeval *tv)
1544 1.17 christos {
1545 1.17 christos struct timespec ts;
1546 1.17 christos
1547 1.17 christos monotime_ts(&ts);
1548 1.17 christos tv->tv_sec = ts.tv_sec;
1549 1.17 christos tv->tv_usec = ts.tv_nsec / 1000;
1550 1.17 christos }
1551 1.17 christos
1552 1.8 christos time_t
1553 1.8 christos monotime(void)
1554 1.8 christos {
1555 1.8 christos struct timespec ts;
1556 1.8 christos
1557 1.17 christos monotime_ts(&ts);
1558 1.8 christos return (ts.tv_sec);
1559 1.8 christos }
1560 1.8 christos
1561 1.13 christos double
1562 1.13 christos monotime_double(void)
1563 1.13 christos {
1564 1.13 christos struct timespec ts;
1565 1.13 christos
1566 1.17 christos monotime_ts(&ts);
1567 1.17 christos return (double)ts.tv_sec + (double)ts.tv_nsec / 1000000000.0;
1568 1.13 christos }
1569 1.13 christos
1570 1.5 christos void
1571 1.5 christos bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
1572 1.5 christos {
1573 1.5 christos bw->buflen = buflen;
1574 1.5 christos bw->rate = kbps;
1575 1.20 christos bw->thresh = buflen;
1576 1.5 christos bw->lamt = 0;
1577 1.5 christos timerclear(&bw->bwstart);
1578 1.5 christos timerclear(&bw->bwend);
1579 1.20 christos }
1580 1.5 christos
1581 1.5 christos /* Callback from read/write loop to insert bandwidth-limiting delays */
1582 1.5 christos void
1583 1.5 christos bandwidth_limit(struct bwlimit *bw, size_t read_len)
1584 1.5 christos {
1585 1.5 christos u_int64_t waitlen;
1586 1.5 christos struct timespec ts, rm;
1587 1.5 christos
1588 1.20 christos bw->lamt += read_len;
1589 1.5 christos if (!timerisset(&bw->bwstart)) {
1590 1.17 christos monotime_tv(&bw->bwstart);
1591 1.5 christos return;
1592 1.5 christos }
1593 1.5 christos if (bw->lamt < bw->thresh)
1594 1.5 christos return;
1595 1.5 christos
1596 1.17 christos monotime_tv(&bw->bwend);
1597 1.5 christos timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
1598 1.5 christos if (!timerisset(&bw->bwend))
1599 1.5 christos return;
1600 1.5 christos
1601 1.5 christos bw->lamt *= 8;
1602 1.5 christos waitlen = (double)1000000L * bw->lamt / bw->rate;
1603 1.5 christos
1604 1.5 christos bw->bwstart.tv_sec = waitlen / 1000000L;
1605 1.5 christos bw->bwstart.tv_usec = waitlen % 1000000L;
1606 1.5 christos
1607 1.5 christos if (timercmp(&bw->bwstart, &bw->bwend, >)) {
1608 1.5 christos timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
1609 1.5 christos
1610 1.5 christos /* Adjust the wait time */
1611 1.5 christos if (bw->bwend.tv_sec) {
1612 1.5 christos bw->thresh /= 2;
1613 1.5 christos if (bw->thresh < bw->buflen / 4)
1614 1.5 christos bw->thresh = bw->buflen / 4;
1615 1.5 christos } else if (bw->bwend.tv_usec < 10000) {
1616 1.5 christos bw->thresh *= 2;
1617 1.5 christos if (bw->thresh > bw->buflen * 8)
1618 1.5 christos bw->thresh = bw->buflen * 8;
1619 1.5 christos }
1620 1.5 christos
1621 1.5 christos TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
1622 1.5 christos while (nanosleep(&ts, &rm) == -1) {
1623 1.5 christos if (errno != EINTR)
1624 1.5 christos break;
1625 1.5 christos ts = rm;
1626 1.5 christos }
1627 1.5 christos }
1628 1.5 christos
1629 1.5 christos bw->lamt = 0;
1630 1.17 christos monotime_tv(&bw->bwstart);
1631 1.5 christos }
1632 1.5 christos
1633 1.5 christos /* Make a template filename for mk[sd]temp() */
1634 1.5 christos void
1635 1.5 christos mktemp_proto(char *s, size_t len)
1636 1.5 christos {
1637 1.5 christos const char *tmpdir;
1638 1.5 christos int r;
1639 1.5 christos
1640 1.5 christos if ((tmpdir = getenv("TMPDIR")) != NULL) {
1641 1.5 christos r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1642 1.5 christos if (r > 0 && (size_t)r < len)
1643 1.5 christos return;
1644 1.5 christos }
1645 1.5 christos r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1646 1.5 christos if (r < 0 || (size_t)r >= len)
1647 1.5 christos fatal("%s: template string too short", __func__);
1648 1.5 christos }
1649 1.5 christos
1650 1.5 christos static const struct {
1651 1.5 christos const char *name;
1652 1.5 christos int value;
1653 1.5 christos } ipqos[] = {
1654 1.16 christos { "none", INT_MAX }, /* can't use 0 here; that's CS0 */
1655 1.5 christos { "af11", IPTOS_DSCP_AF11 },
1656 1.5 christos { "af12", IPTOS_DSCP_AF12 },
1657 1.5 christos { "af13", IPTOS_DSCP_AF13 },
1658 1.7 christos { "af21", IPTOS_DSCP_AF21 },
1659 1.5 christos { "af22", IPTOS_DSCP_AF22 },
1660 1.5 christos { "af23", IPTOS_DSCP_AF23 },
1661 1.5 christos { "af31", IPTOS_DSCP_AF31 },
1662 1.5 christos { "af32", IPTOS_DSCP_AF32 },
1663 1.5 christos { "af33", IPTOS_DSCP_AF33 },
1664 1.5 christos { "af41", IPTOS_DSCP_AF41 },
1665 1.5 christos { "af42", IPTOS_DSCP_AF42 },
1666 1.5 christos { "af43", IPTOS_DSCP_AF43 },
1667 1.5 christos { "cs0", IPTOS_DSCP_CS0 },
1668 1.5 christos { "cs1", IPTOS_DSCP_CS1 },
1669 1.5 christos { "cs2", IPTOS_DSCP_CS2 },
1670 1.5 christos { "cs3", IPTOS_DSCP_CS3 },
1671 1.5 christos { "cs4", IPTOS_DSCP_CS4 },
1672 1.5 christos { "cs5", IPTOS_DSCP_CS5 },
1673 1.5 christos { "cs6", IPTOS_DSCP_CS6 },
1674 1.5 christos { "cs7", IPTOS_DSCP_CS7 },
1675 1.5 christos { "ef", IPTOS_DSCP_EF },
1676 1.22 christos #ifdef IPTOS_DSCP_LE
1677 1.22 christos { "le", IPTOS_DSCP_LE },
1678 1.22 christos #endif
1679 1.5 christos { "lowdelay", IPTOS_LOWDELAY },
1680 1.5 christos { "throughput", IPTOS_THROUGHPUT },
1681 1.5 christos { "reliability", IPTOS_RELIABILITY },
1682 1.5 christos { NULL, -1 }
1683 1.5 christos };
1684 1.5 christos
1685 1.5 christos int
1686 1.5 christos parse_ipqos(const char *cp)
1687 1.5 christos {
1688 1.5 christos u_int i;
1689 1.5 christos char *ep;
1690 1.5 christos long val;
1691 1.5 christos
1692 1.5 christos if (cp == NULL)
1693 1.5 christos return -1;
1694 1.5 christos for (i = 0; ipqos[i].name != NULL; i++) {
1695 1.5 christos if (strcasecmp(cp, ipqos[i].name) == 0)
1696 1.5 christos return ipqos[i].value;
1697 1.5 christos }
1698 1.5 christos /* Try parsing as an integer */
1699 1.5 christos val = strtol(cp, &ep, 0);
1700 1.5 christos if (*cp == '\0' || *ep != '\0' || val < 0 || val > 255)
1701 1.5 christos return -1;
1702 1.5 christos return val;
1703 1.5 christos }
1704 1.5 christos
1705 1.6 christos const char *
1706 1.6 christos iptos2str(int iptos)
1707 1.6 christos {
1708 1.6 christos int i;
1709 1.6 christos static char iptos_str[sizeof "0xff"];
1710 1.6 christos
1711 1.6 christos for (i = 0; ipqos[i].name != NULL; i++) {
1712 1.6 christos if (ipqos[i].value == iptos)
1713 1.6 christos return ipqos[i].name;
1714 1.6 christos }
1715 1.6 christos snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1716 1.6 christos return iptos_str;
1717 1.6 christos }
1718 1.6 christos
1719 1.9 christos void
1720 1.9 christos lowercase(char *s)
1721 1.9 christos {
1722 1.9 christos for (; *s; s++)
1723 1.9 christos *s = tolower((u_char)*s);
1724 1.9 christos }
1725 1.9 christos
1726 1.4 adam int
1727 1.9 christos unix_listener(const char *path, int backlog, int unlink_first)
1728 1.4 adam {
1729 1.9 christos struct sockaddr_un sunaddr;
1730 1.9 christos int saved_errno, sock;
1731 1.4 adam
1732 1.9 christos memset(&sunaddr, 0, sizeof(sunaddr));
1733 1.9 christos sunaddr.sun_family = AF_UNIX;
1734 1.17 christos if (strlcpy(sunaddr.sun_path, path,
1735 1.17 christos sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1736 1.17 christos error("%s: path \"%s\" too long for Unix domain socket",
1737 1.17 christos __func__, path);
1738 1.9 christos errno = ENAMETOOLONG;
1739 1.9 christos return -1;
1740 1.9 christos }
1741 1.9 christos
1742 1.9 christos sock = socket(PF_UNIX, SOCK_STREAM, 0);
1743 1.21 christos if (sock == -1) {
1744 1.9 christos saved_errno = errno;
1745 1.17 christos error("%s: socket: %.100s", __func__, strerror(errno));
1746 1.9 christos errno = saved_errno;
1747 1.9 christos return -1;
1748 1.9 christos }
1749 1.9 christos if (unlink_first == 1) {
1750 1.9 christos if (unlink(path) != 0 && errno != ENOENT)
1751 1.9 christos error("unlink(%s): %.100s", path, strerror(errno));
1752 1.9 christos }
1753 1.21 christos if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1754 1.9 christos saved_errno = errno;
1755 1.17 christos error("%s: cannot bind to path %s: %s",
1756 1.17 christos __func__, path, strerror(errno));
1757 1.9 christos close(sock);
1758 1.9 christos errno = saved_errno;
1759 1.9 christos return -1;
1760 1.9 christos }
1761 1.21 christos if (listen(sock, backlog) == -1) {
1762 1.9 christos saved_errno = errno;
1763 1.17 christos error("%s: cannot listen on path %s: %s",
1764 1.17 christos __func__, path, strerror(errno));
1765 1.9 christos close(sock);
1766 1.9 christos unlink(path);
1767 1.9 christos errno = saved_errno;
1768 1.9 christos return -1;
1769 1.9 christos }
1770 1.9 christos return sock;
1771 1.4 adam }
1772 1.13 christos
1773 1.13 christos /*
1774 1.13 christos * Compares two strings that maybe be NULL. Returns non-zero if strings
1775 1.13 christos * are both NULL or are identical, returns zero otherwise.
1776 1.13 christos */
1777 1.13 christos static int
1778 1.13 christos strcmp_maybe_null(const char *a, const char *b)
1779 1.13 christos {
1780 1.13 christos if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1781 1.13 christos return 0;
1782 1.13 christos if (a != NULL && strcmp(a, b) != 0)
1783 1.13 christos return 0;
1784 1.13 christos return 1;
1785 1.13 christos }
1786 1.13 christos
1787 1.13 christos /*
1788 1.13 christos * Compare two forwards, returning non-zero if they are identical or
1789 1.13 christos * zero otherwise.
1790 1.13 christos */
1791 1.13 christos int
1792 1.13 christos forward_equals(const struct Forward *a, const struct Forward *b)
1793 1.13 christos {
1794 1.13 christos if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
1795 1.13 christos return 0;
1796 1.13 christos if (a->listen_port != b->listen_port)
1797 1.13 christos return 0;
1798 1.13 christos if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
1799 1.13 christos return 0;
1800 1.13 christos if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
1801 1.13 christos return 0;
1802 1.13 christos if (a->connect_port != b->connect_port)
1803 1.13 christos return 0;
1804 1.13 christos if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
1805 1.13 christos return 0;
1806 1.13 christos /* allocated_port and handle are not checked */
1807 1.13 christos return 1;
1808 1.13 christos }
1809 1.13 christos
1810 1.14 christos /* returns 1 if process is already daemonized, 0 otherwise */
1811 1.14 christos int
1812 1.14 christos daemonized(void)
1813 1.14 christos {
1814 1.14 christos int fd;
1815 1.14 christos
1816 1.14 christos if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
1817 1.14 christos close(fd);
1818 1.14 christos return 0; /* have controlling terminal */
1819 1.14 christos }
1820 1.14 christos if (getppid() != 1)
1821 1.14 christos return 0; /* parent is not init */
1822 1.14 christos if (getsid(0) != getpid())
1823 1.14 christos return 0; /* not session leader */
1824 1.14 christos debug3("already daemonized");
1825 1.14 christos return 1;
1826 1.14 christos }
1827 1.16 christos
1828 1.16 christos
1829 1.16 christos /*
1830 1.16 christos * Splits 's' into an argument vector. Handles quoted string and basic
1831 1.16 christos * escape characters (\\, \", \'). Caller must free the argument vector
1832 1.16 christos * and its members.
1833 1.16 christos */
1834 1.16 christos int
1835 1.16 christos argv_split(const char *s, int *argcp, char ***argvp)
1836 1.16 christos {
1837 1.16 christos int r = SSH_ERR_INTERNAL_ERROR;
1838 1.16 christos int argc = 0, quote, i, j;
1839 1.16 christos char *arg, **argv = xcalloc(1, sizeof(*argv));
1840 1.16 christos
1841 1.16 christos *argvp = NULL;
1842 1.16 christos *argcp = 0;
1843 1.16 christos
1844 1.16 christos for (i = 0; s[i] != '\0'; i++) {
1845 1.16 christos /* Skip leading whitespace */
1846 1.16 christos if (s[i] == ' ' || s[i] == '\t')
1847 1.16 christos continue;
1848 1.16 christos
1849 1.16 christos /* Start of a token */
1850 1.16 christos quote = 0;
1851 1.16 christos if (s[i] == '\\' &&
1852 1.16 christos (s[i + 1] == '\'' || s[i + 1] == '\"' || s[i + 1] == '\\'))
1853 1.16 christos i++;
1854 1.16 christos else if (s[i] == '\'' || s[i] == '"')
1855 1.16 christos quote = s[i++];
1856 1.16 christos
1857 1.16 christos argv = xreallocarray(argv, (argc + 2), sizeof(*argv));
1858 1.16 christos arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1);
1859 1.16 christos argv[argc] = NULL;
1860 1.16 christos
1861 1.16 christos /* Copy the token in, removing escapes */
1862 1.16 christos for (j = 0; s[i] != '\0'; i++) {
1863 1.16 christos if (s[i] == '\\') {
1864 1.16 christos if (s[i + 1] == '\'' ||
1865 1.16 christos s[i + 1] == '\"' ||
1866 1.16 christos s[i + 1] == '\\') {
1867 1.16 christos i++; /* Skip '\' */
1868 1.16 christos arg[j++] = s[i];
1869 1.16 christos } else {
1870 1.16 christos /* Unrecognised escape */
1871 1.16 christos arg[j++] = s[i];
1872 1.16 christos }
1873 1.16 christos } else if (quote == 0 && (s[i] == ' ' || s[i] == '\t'))
1874 1.16 christos break; /* done */
1875 1.16 christos else if (quote != 0 && s[i] == quote)
1876 1.16 christos break; /* done */
1877 1.16 christos else
1878 1.16 christos arg[j++] = s[i];
1879 1.16 christos }
1880 1.16 christos if (s[i] == '\0') {
1881 1.16 christos if (quote != 0) {
1882 1.16 christos /* Ran out of string looking for close quote */
1883 1.16 christos r = SSH_ERR_INVALID_FORMAT;
1884 1.16 christos goto out;
1885 1.16 christos }
1886 1.16 christos break;
1887 1.16 christos }
1888 1.16 christos }
1889 1.16 christos /* Success */
1890 1.16 christos *argcp = argc;
1891 1.16 christos *argvp = argv;
1892 1.16 christos argc = 0;
1893 1.16 christos argv = NULL;
1894 1.16 christos r = 0;
1895 1.16 christos out:
1896 1.16 christos if (argc != 0 && argv != NULL) {
1897 1.16 christos for (i = 0; i < argc; i++)
1898 1.16 christos free(argv[i]);
1899 1.16 christos free(argv);
1900 1.16 christos }
1901 1.16 christos return r;
1902 1.16 christos }
1903 1.16 christos
1904 1.16 christos /*
1905 1.16 christos * Reassemble an argument vector into a string, quoting and escaping as
1906 1.16 christos * necessary. Caller must free returned string.
1907 1.16 christos */
1908 1.16 christos char *
1909 1.16 christos argv_assemble(int argc, char **argv)
1910 1.16 christos {
1911 1.16 christos int i, j, ws, r;
1912 1.16 christos char c, *ret;
1913 1.16 christos struct sshbuf *buf, *arg;
1914 1.16 christos
1915 1.16 christos if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL)
1916 1.16 christos fatal("%s: sshbuf_new failed", __func__);
1917 1.16 christos
1918 1.16 christos for (i = 0; i < argc; i++) {
1919 1.16 christos ws = 0;
1920 1.16 christos sshbuf_reset(arg);
1921 1.16 christos for (j = 0; argv[i][j] != '\0'; j++) {
1922 1.16 christos r = 0;
1923 1.16 christos c = argv[i][j];
1924 1.16 christos switch (c) {
1925 1.16 christos case ' ':
1926 1.16 christos case '\t':
1927 1.16 christos ws = 1;
1928 1.16 christos r = sshbuf_put_u8(arg, c);
1929 1.16 christos break;
1930 1.16 christos case '\\':
1931 1.16 christos case '\'':
1932 1.16 christos case '"':
1933 1.16 christos if ((r = sshbuf_put_u8(arg, '\\')) != 0)
1934 1.16 christos break;
1935 1.16 christos /* FALLTHROUGH */
1936 1.16 christos default:
1937 1.16 christos r = sshbuf_put_u8(arg, c);
1938 1.16 christos break;
1939 1.16 christos }
1940 1.16 christos if (r != 0)
1941 1.16 christos fatal("%s: sshbuf_put_u8: %s",
1942 1.16 christos __func__, ssh_err(r));
1943 1.16 christos }
1944 1.16 christos if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) ||
1945 1.16 christos (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) ||
1946 1.16 christos (r = sshbuf_putb(buf, arg)) != 0 ||
1947 1.16 christos (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0))
1948 1.16 christos fatal("%s: buffer error: %s", __func__, ssh_err(r));
1949 1.16 christos }
1950 1.16 christos if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL)
1951 1.16 christos fatal("%s: malloc failed", __func__);
1952 1.16 christos memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf));
1953 1.16 christos ret[sshbuf_len(buf)] = '\0';
1954 1.16 christos sshbuf_free(buf);
1955 1.16 christos sshbuf_free(arg);
1956 1.16 christos return ret;
1957 1.16 christos }
1958 1.16 christos
1959 1.16 christos /* Returns 0 if pid exited cleanly, non-zero otherwise */
1960 1.16 christos int
1961 1.16 christos exited_cleanly(pid_t pid, const char *tag, const char *cmd, int quiet)
1962 1.16 christos {
1963 1.16 christos int status;
1964 1.16 christos
1965 1.16 christos while (waitpid(pid, &status, 0) == -1) {
1966 1.16 christos if (errno != EINTR) {
1967 1.16 christos error("%s: waitpid: %s", tag, strerror(errno));
1968 1.16 christos return -1;
1969 1.16 christos }
1970 1.16 christos }
1971 1.16 christos if (WIFSIGNALED(status)) {
1972 1.16 christos error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status));
1973 1.16 christos return -1;
1974 1.16 christos } else if (WEXITSTATUS(status) != 0) {
1975 1.16 christos do_log2(quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_INFO,
1976 1.16 christos "%s %s failed, status %d", tag, cmd, WEXITSTATUS(status));
1977 1.16 christos return -1;
1978 1.16 christos }
1979 1.16 christos return 0;
1980 1.16 christos }
1981 1.16 christos
1982 1.16 christos /*
1983 1.16 christos * Check a given path for security. This is defined as all components
1984 1.16 christos * of the path to the file must be owned by either the owner of
1985 1.16 christos * of the file or root and no directories must be group or world writable.
1986 1.16 christos *
1987 1.16 christos * XXX Should any specific check be done for sym links ?
1988 1.16 christos *
1989 1.16 christos * Takes a file name, its stat information (preferably from fstat() to
1990 1.16 christos * avoid races), the uid of the expected owner, their home directory and an
1991 1.16 christos * error buffer plus max size as arguments.
1992 1.16 christos *
1993 1.16 christos * Returns 0 on success and -1 on failure
1994 1.16 christos */
1995 1.16 christos int
1996 1.16 christos safe_path(const char *name, struct stat *stp, const char *pw_dir,
1997 1.16 christos uid_t uid, char *err, size_t errlen)
1998 1.16 christos {
1999 1.16 christos char buf[PATH_MAX], homedir[PATH_MAX];
2000 1.16 christos char *cp;
2001 1.16 christos int comparehome = 0;
2002 1.16 christos struct stat st;
2003 1.16 christos
2004 1.16 christos if (realpath(name, buf) == NULL) {
2005 1.16 christos snprintf(err, errlen, "realpath %s failed: %s", name,
2006 1.16 christos strerror(errno));
2007 1.16 christos return -1;
2008 1.16 christos }
2009 1.16 christos if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
2010 1.16 christos comparehome = 1;
2011 1.16 christos
2012 1.16 christos if (!S_ISREG(stp->st_mode)) {
2013 1.16 christos snprintf(err, errlen, "%s is not a regular file", buf);
2014 1.16 christos return -1;
2015 1.16 christos }
2016 1.16 christos if ((stp->st_uid != 0 && stp->st_uid != uid) ||
2017 1.16 christos (stp->st_mode & 022) != 0) {
2018 1.16 christos snprintf(err, errlen, "bad ownership or modes for file %s",
2019 1.16 christos buf);
2020 1.16 christos return -1;
2021 1.16 christos }
2022 1.16 christos
2023 1.16 christos /* for each component of the canonical path, walking upwards */
2024 1.16 christos for (;;) {
2025 1.16 christos if ((cp = dirname(buf)) == NULL) {
2026 1.16 christos snprintf(err, errlen, "dirname() failed");
2027 1.16 christos return -1;
2028 1.16 christos }
2029 1.16 christos strlcpy(buf, cp, sizeof(buf));
2030 1.16 christos
2031 1.21 christos if (stat(buf, &st) == -1 ||
2032 1.16 christos (st.st_uid != 0 && st.st_uid != uid) ||
2033 1.16 christos (st.st_mode & 022) != 0) {
2034 1.16 christos snprintf(err, errlen,
2035 1.16 christos "bad ownership or modes for directory %s", buf);
2036 1.16 christos return -1;
2037 1.16 christos }
2038 1.16 christos
2039 1.16 christos /* If are past the homedir then we can stop */
2040 1.16 christos if (comparehome && strcmp(homedir, buf) == 0)
2041 1.16 christos break;
2042 1.16 christos
2043 1.16 christos /*
2044 1.16 christos * dirname should always complete with a "/" path,
2045 1.16 christos * but we can be paranoid and check for "." too
2046 1.16 christos */
2047 1.16 christos if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
2048 1.16 christos break;
2049 1.16 christos }
2050 1.16 christos return 0;
2051 1.16 christos }
2052 1.16 christos
2053 1.16 christos /*
2054 1.16 christos * Version of safe_path() that accepts an open file descriptor to
2055 1.16 christos * avoid races.
2056 1.16 christos *
2057 1.16 christos * Returns 0 on success and -1 on failure
2058 1.16 christos */
2059 1.16 christos int
2060 1.16 christos safe_path_fd(int fd, const char *file, struct passwd *pw,
2061 1.16 christos char *err, size_t errlen)
2062 1.16 christos {
2063 1.16 christos struct stat st;
2064 1.16 christos
2065 1.16 christos /* check the open file to avoid races */
2066 1.21 christos if (fstat(fd, &st) == -1) {
2067 1.16 christos snprintf(err, errlen, "cannot stat file %s: %s",
2068 1.16 christos file, strerror(errno));
2069 1.16 christos return -1;
2070 1.16 christos }
2071 1.16 christos return safe_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
2072 1.16 christos }
2073 1.16 christos
2074 1.16 christos /*
2075 1.16 christos * Sets the value of the given variable in the environment. If the variable
2076 1.16 christos * already exists, its value is overridden.
2077 1.16 christos */
2078 1.16 christos void
2079 1.16 christos child_set_env(char ***envp, u_int *envsizep, const char *name,
2080 1.16 christos const char *value)
2081 1.16 christos {
2082 1.16 christos char **env;
2083 1.16 christos u_int envsize;
2084 1.16 christos u_int i, namelen;
2085 1.16 christos
2086 1.16 christos if (strchr(name, '=') != NULL) {
2087 1.16 christos error("Invalid environment variable \"%.100s\"", name);
2088 1.16 christos return;
2089 1.16 christos }
2090 1.16 christos
2091 1.16 christos /*
2092 1.16 christos * Find the slot where the value should be stored. If the variable
2093 1.16 christos * already exists, we reuse the slot; otherwise we append a new slot
2094 1.16 christos * at the end of the array, expanding if necessary.
2095 1.16 christos */
2096 1.16 christos env = *envp;
2097 1.16 christos namelen = strlen(name);
2098 1.16 christos for (i = 0; env[i]; i++)
2099 1.16 christos if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
2100 1.16 christos break;
2101 1.16 christos if (env[i]) {
2102 1.16 christos /* Reuse the slot. */
2103 1.16 christos free(env[i]);
2104 1.16 christos } else {
2105 1.16 christos /* New variable. Expand if necessary. */
2106 1.16 christos envsize = *envsizep;
2107 1.16 christos if (i >= envsize - 1) {
2108 1.16 christos if (envsize >= 1000)
2109 1.16 christos fatal("child_set_env: too many env vars");
2110 1.16 christos envsize += 50;
2111 1.16 christos env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
2112 1.16 christos *envsizep = envsize;
2113 1.16 christos }
2114 1.16 christos /* Need to set the NULL pointer at end of array beyond the new slot. */
2115 1.16 christos env[i + 1] = NULL;
2116 1.16 christos }
2117 1.16 christos
2118 1.16 christos /* Allocate space and format the variable in the appropriate slot. */
2119 1.17 christos /* XXX xasprintf */
2120 1.16 christos env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
2121 1.16 christos snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
2122 1.16 christos }
2123 1.16 christos
2124 1.17 christos /*
2125 1.17 christos * Check and optionally lowercase a domain name, also removes trailing '.'
2126 1.17 christos * Returns 1 on success and 0 on failure, storing an error message in errstr.
2127 1.17 christos */
2128 1.17 christos int
2129 1.17 christos valid_domain(char *name, int makelower, const char **errstr)
2130 1.17 christos {
2131 1.17 christos size_t i, l = strlen(name);
2132 1.17 christos u_char c, last = '\0';
2133 1.17 christos static char errbuf[256];
2134 1.17 christos
2135 1.17 christos if (l == 0) {
2136 1.17 christos strlcpy(errbuf, "empty domain name", sizeof(errbuf));
2137 1.17 christos goto bad;
2138 1.17 christos }
2139 1.17 christos if (!isalpha((u_char)name[0]) && !isdigit((u_char)name[0])) {
2140 1.17 christos snprintf(errbuf, sizeof(errbuf), "domain name \"%.100s\" "
2141 1.17 christos "starts with invalid character", name);
2142 1.17 christos goto bad;
2143 1.17 christos }
2144 1.17 christos for (i = 0; i < l; i++) {
2145 1.17 christos c = tolower((u_char)name[i]);
2146 1.17 christos if (makelower)
2147 1.17 christos name[i] = (char)c;
2148 1.17 christos if (last == '.' && c == '.') {
2149 1.17 christos snprintf(errbuf, sizeof(errbuf), "domain name "
2150 1.17 christos "\"%.100s\" contains consecutive separators", name);
2151 1.17 christos goto bad;
2152 1.17 christos }
2153 1.17 christos if (c != '.' && c != '-' && !isalnum(c) &&
2154 1.17 christos c != '_') /* technically invalid, but common */ {
2155 1.17 christos snprintf(errbuf, sizeof(errbuf), "domain name "
2156 1.17 christos "\"%.100s\" contains invalid characters", name);
2157 1.17 christos goto bad;
2158 1.17 christos }
2159 1.17 christos last = c;
2160 1.17 christos }
2161 1.17 christos if (name[l - 1] == '.')
2162 1.17 christos name[l - 1] = '\0';
2163 1.17 christos if (errstr != NULL)
2164 1.17 christos *errstr = NULL;
2165 1.17 christos return 1;
2166 1.17 christos bad:
2167 1.17 christos if (errstr != NULL)
2168 1.17 christos *errstr = errbuf;
2169 1.17 christos return 0;
2170 1.17 christos }
2171 1.17 christos
2172 1.20 christos /*
2173 1.20 christos * Verify that a environment variable name (not including initial '$') is
2174 1.20 christos * valid; consisting of one or more alphanumeric or underscore characters only.
2175 1.20 christos * Returns 1 on valid, 0 otherwise.
2176 1.20 christos */
2177 1.20 christos int
2178 1.20 christos valid_env_name(const char *name)
2179 1.20 christos {
2180 1.20 christos const char *cp;
2181 1.20 christos
2182 1.20 christos if (name[0] == '\0')
2183 1.20 christos return 0;
2184 1.20 christos for (cp = name; *cp != '\0'; cp++) {
2185 1.20 christos if (!isalnum((u_char)*cp) && *cp != '_')
2186 1.20 christos return 0;
2187 1.20 christos }
2188 1.20 christos return 1;
2189 1.20 christos }
2190 1.20 christos
2191 1.17 christos const char *
2192 1.17 christos atoi_err(const char *nptr, int *val)
2193 1.17 christos {
2194 1.17 christos const char *errstr = NULL;
2195 1.17 christos long long num;
2196 1.17 christos
2197 1.17 christos if (nptr == NULL || *nptr == '\0')
2198 1.17 christos return "missing";
2199 1.17 christos num = strtonum(nptr, 0, INT_MAX, &errstr);
2200 1.17 christos if (errstr == NULL)
2201 1.17 christos *val = (int)num;
2202 1.17 christos return errstr;
2203 1.17 christos }
2204 1.17 christos
2205 1.17 christos int
2206 1.17 christos parse_absolute_time(const char *s, uint64_t *tp)
2207 1.17 christos {
2208 1.17 christos struct tm tm;
2209 1.17 christos time_t tt;
2210 1.17 christos char buf[32];
2211 1.17 christos const char *fmt;
2212 1.17 christos
2213 1.17 christos *tp = 0;
2214 1.17 christos
2215 1.17 christos /*
2216 1.17 christos * POSIX strptime says "The application shall ensure that there
2217 1.17 christos * is white-space or other non-alphanumeric characters between
2218 1.17 christos * any two conversion specifications" so arrange things this way.
2219 1.17 christos */
2220 1.17 christos switch (strlen(s)) {
2221 1.17 christos case 8: /* YYYYMMDD */
2222 1.17 christos fmt = "%Y-%m-%d";
2223 1.17 christos snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
2224 1.17 christos break;
2225 1.17 christos case 12: /* YYYYMMDDHHMM */
2226 1.17 christos fmt = "%Y-%m-%dT%H:%M";
2227 1.17 christos snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s",
2228 1.17 christos s, s + 4, s + 6, s + 8, s + 10);
2229 1.17 christos break;
2230 1.17 christos case 14: /* YYYYMMDDHHMMSS */
2231 1.17 christos fmt = "%Y-%m-%dT%H:%M:%S";
2232 1.17 christos snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
2233 1.17 christos s, s + 4, s + 6, s + 8, s + 10, s + 12);
2234 1.17 christos break;
2235 1.17 christos default:
2236 1.17 christos return SSH_ERR_INVALID_FORMAT;
2237 1.17 christos }
2238 1.17 christos
2239 1.17 christos memset(&tm, 0, sizeof(tm));
2240 1.17 christos if (strptime(buf, fmt, &tm) == NULL)
2241 1.17 christos return SSH_ERR_INVALID_FORMAT;
2242 1.17 christos if ((tt = mktime(&tm)) < 0)
2243 1.17 christos return SSH_ERR_INVALID_FORMAT;
2244 1.17 christos /* success */
2245 1.17 christos *tp = (uint64_t)tt;
2246 1.17 christos return 0;
2247 1.17 christos }
2248 1.17 christos
2249 1.17 christos void
2250 1.17 christos format_absolute_time(uint64_t t, char *buf, size_t len)
2251 1.17 christos {
2252 1.17 christos time_t tt = t > INT_MAX ? INT_MAX : t; /* XXX revisit in 2038 :P */
2253 1.17 christos struct tm tm;
2254 1.17 christos
2255 1.17 christos localtime_r(&tt, &tm);
2256 1.17 christos strftime(buf, len, "%Y-%m-%dT%H:%M:%S", &tm);
2257 1.17 christos }
2258 1.20 christos
2259 1.20 christos /* check if path is absolute */
2260 1.20 christos int
2261 1.20 christos path_absolute(const char *path)
2262 1.20 christos {
2263 1.20 christos return (*path == '/') ? 1 : 0;
2264 1.20 christos }
2265 1.21 christos
2266 1.21 christos void
2267 1.21 christos skip_space(char **cpp)
2268 1.21 christos {
2269 1.21 christos char *cp;
2270 1.21 christos
2271 1.21 christos for (cp = *cpp; *cp == ' ' || *cp == '\t'; cp++)
2272 1.21 christos ;
2273 1.21 christos *cpp = cp;
2274 1.21 christos }
2275 1.21 christos
2276 1.21 christos /* authorized_key-style options parsing helpers */
2277 1.21 christos
2278 1.21 christos /*
2279 1.21 christos * Match flag 'opt' in *optsp, and if allow_negate is set then also match
2280 1.21 christos * 'no-opt'. Returns -1 if option not matched, 1 if option matches or 0
2281 1.21 christos * if negated option matches.
2282 1.21 christos * If the option or negated option matches, then *optsp is updated to
2283 1.21 christos * point to the first character after the option.
2284 1.21 christos */
2285 1.21 christos int
2286 1.21 christos opt_flag(const char *opt, int allow_negate, const char **optsp)
2287 1.21 christos {
2288 1.21 christos size_t opt_len = strlen(opt);
2289 1.21 christos const char *opts = *optsp;
2290 1.21 christos int negate = 0;
2291 1.21 christos
2292 1.21 christos if (allow_negate && strncasecmp(opts, "no-", 3) == 0) {
2293 1.21 christos opts += 3;
2294 1.21 christos negate = 1;
2295 1.21 christos }
2296 1.21 christos if (strncasecmp(opts, opt, opt_len) == 0) {
2297 1.21 christos *optsp = opts + opt_len;
2298 1.21 christos return negate ? 0 : 1;
2299 1.21 christos }
2300 1.21 christos return -1;
2301 1.21 christos }
2302 1.21 christos
2303 1.21 christos char *
2304 1.21 christos opt_dequote(const char **sp, const char **errstrp)
2305 1.21 christos {
2306 1.21 christos const char *s = *sp;
2307 1.21 christos char *ret;
2308 1.21 christos size_t i;
2309 1.21 christos
2310 1.21 christos *errstrp = NULL;
2311 1.21 christos if (*s != '"') {
2312 1.21 christos *errstrp = "missing start quote";
2313 1.21 christos return NULL;
2314 1.21 christos }
2315 1.21 christos s++;
2316 1.21 christos if ((ret = malloc(strlen((s)) + 1)) == NULL) {
2317 1.21 christos *errstrp = "memory allocation failed";
2318 1.21 christos return NULL;
2319 1.21 christos }
2320 1.21 christos for (i = 0; *s != '\0' && *s != '"';) {
2321 1.21 christos if (s[0] == '\\' && s[1] == '"')
2322 1.21 christos s++;
2323 1.21 christos ret[i++] = *s++;
2324 1.21 christos }
2325 1.21 christos if (*s == '\0') {
2326 1.21 christos *errstrp = "missing end quote";
2327 1.21 christos free(ret);
2328 1.21 christos return NULL;
2329 1.21 christos }
2330 1.21 christos ret[i] = '\0';
2331 1.21 christos s++;
2332 1.21 christos *sp = s;
2333 1.21 christos return ret;
2334 1.21 christos }
2335 1.21 christos
2336 1.21 christos int
2337 1.21 christos opt_match(const char **opts, const char *term)
2338 1.21 christos {
2339 1.21 christos if (strncasecmp((*opts), term, strlen(term)) == 0 &&
2340 1.21 christos (*opts)[strlen(term)] == '=') {
2341 1.21 christos *opts += strlen(term) + 1;
2342 1.21 christos return 1;
2343 1.21 christos }
2344 1.21 christos return 0;
2345 1.21 christos }
2346 1.21 christos
2347 1.22 christos sshsig_t
2348 1.22 christos ssh_signal(int signum, sshsig_t handler)
2349 1.22 christos {
2350 1.22 christos struct sigaction sa, osa;
2351 1.22 christos
2352 1.22 christos /* mask all other signals while in handler */
2353 1.23 christos memset(&sa, 0, sizeof(sa));
2354 1.22 christos sa.sa_handler = handler;
2355 1.22 christos sigfillset(&sa.sa_mask);
2356 1.22 christos if (signum != SIGALRM)
2357 1.22 christos sa.sa_flags = SA_RESTART;
2358 1.22 christos if (sigaction(signum, &sa, &osa) == -1) {
2359 1.22 christos debug3("sigaction(%s): %s", strsignal(signum), strerror(errno));
2360 1.22 christos return SIG_ERR;
2361 1.22 christos }
2362 1.22 christos return osa.sa_handler;
2363 1.22 christos }
2364