1 /* $OpenBSD: misc.c,v 1.198 2024/10/24 03:14:37 djm Exp $ */
2 /*
3 * Copyright (c) 2000 Markus Friedl. All rights reserved.
4 * Copyright (c) 2005-2020 Damien Miller. All rights reserved.
5 * Copyright (c) 2004 Henning Brauer <henning@openbsd.org>
6 *
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 */
19
20
21 #include <sys/types.h>
22 #include <sys/ioctl.h>
23 #include <sys/socket.h>
24 #include <sys/stat.h>
25 #include <sys/time.h>
26 #include <sys/wait.h>
27 #include <sys/un.h>
28
29 #include <net/if.h>
30 #include <netinet/in.h>
31 #include <netinet/ip.h>
32 #include <netinet/tcp.h>
33 #include <arpa/inet.h>
34
35 #include <ctype.h>
36 #include <errno.h>
37 #include <fcntl.h>
38 #include <netdb.h>
39 #include <paths.h>
40 #include <pwd.h>
41 #include <libgen.h>
42 #include <limits.h>
43 #include <nlist.h>
44 #include <poll.h>
45 #include <signal.h>
46 #include <stdarg.h>
47 #include <stdio.h>
48 #include <stdint.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <unistd.h>
52
53 #include "xmalloc.h"
54 #include "misc.h"
55 #include "log.h"
56 #include "ssh.h"
57 #include "sshbuf.h"
58 #include "ssherr.h"
59
60 /* remove newline at end of string */
61 char *
chop(char * s)62 chop(char *s)
63 {
64 char *t = s;
65 while (*t) {
66 if (*t == '\n' || *t == '\r') {
67 *t = '\0';
68 return s;
69 }
70 t++;
71 }
72 return s;
73
74 }
75
76 /* remove whitespace from end of string */
77 void
rtrim(char * s)78 rtrim(char *s)
79 {
80 size_t i;
81
82 if ((i = strlen(s)) == 0)
83 return;
84 for (i--; i > 0; i--) {
85 if (isspace((unsigned char)s[i]))
86 s[i] = '\0';
87 }
88 }
89
90 /*
91 * returns pointer to character after 'prefix' in 's' or otherwise NULL
92 * if the prefix is not present.
93 */
94 const char *
strprefix(const char * s,const char * prefix,int ignorecase)95 strprefix(const char *s, const char *prefix, int ignorecase)
96 {
97 size_t prefixlen;
98
99 if ((prefixlen = strlen(prefix)) == 0)
100 return s;
101 if (ignorecase) {
102 if (strncasecmp(s, prefix, prefixlen) != 0)
103 return NULL;
104 } else {
105 if (strncmp(s, prefix, prefixlen) != 0)
106 return NULL;
107 }
108 return s + prefixlen;
109 }
110
111 /* set/unset filedescriptor to non-blocking */
112 int
set_nonblock(int fd)113 set_nonblock(int fd)
114 {
115 int val;
116
117 val = fcntl(fd, F_GETFL);
118 if (val == -1) {
119 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
120 return (-1);
121 }
122 if (val & O_NONBLOCK) {
123 debug3("fd %d is O_NONBLOCK", fd);
124 return (0);
125 }
126 debug2("fd %d setting O_NONBLOCK", fd);
127 val |= O_NONBLOCK;
128 if (fcntl(fd, F_SETFL, val) == -1) {
129 debug("fcntl(%d, F_SETFL, O_NONBLOCK): %s", fd,
130 strerror(errno));
131 return (-1);
132 }
133 return (0);
134 }
135
136 int
unset_nonblock(int fd)137 unset_nonblock(int fd)
138 {
139 int val;
140
141 val = fcntl(fd, F_GETFL);
142 if (val == -1) {
143 error("fcntl(%d, F_GETFL): %s", fd, strerror(errno));
144 return (-1);
145 }
146 if (!(val & O_NONBLOCK)) {
147 debug3("fd %d is not O_NONBLOCK", fd);
148 return (0);
149 }
150 debug("fd %d clearing O_NONBLOCK", fd);
151 val &= ~O_NONBLOCK;
152 if (fcntl(fd, F_SETFL, val) == -1) {
153 debug("fcntl(%d, F_SETFL, ~O_NONBLOCK): %s",
154 fd, strerror(errno));
155 return (-1);
156 }
157 return (0);
158 }
159
160 const char *
ssh_gai_strerror(int gaierr)161 ssh_gai_strerror(int gaierr)
162 {
163 if (gaierr == EAI_SYSTEM && errno != 0)
164 return strerror(errno);
165 return gai_strerror(gaierr);
166 }
167
168 /* disable nagle on socket */
169 void
set_nodelay(int fd)170 set_nodelay(int fd)
171 {
172 int opt;
173 socklen_t optlen;
174
175 optlen = sizeof opt;
176 if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, &optlen) == -1) {
177 debug("getsockopt TCP_NODELAY: %.100s", strerror(errno));
178 return;
179 }
180 if (opt == 1) {
181 debug2("fd %d is TCP_NODELAY", fd);
182 return;
183 }
184 opt = 1;
185 debug2("fd %d setting TCP_NODELAY", fd);
186 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof opt) == -1)
187 error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
188 }
189
190 /* Allow local port reuse in TIME_WAIT */
191 int
set_reuseaddr(int fd)192 set_reuseaddr(int fd)
193 {
194 int on = 1;
195
196 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) {
197 error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
198 return -1;
199 }
200 return 0;
201 }
202
203 /* Get/set routing domain */
204 char *
get_rdomain(int fd)205 get_rdomain(int fd)
206 {
207 int rtable;
208 char *ret;
209 socklen_t len = sizeof(rtable);
210
211 if (getsockopt(fd, SOL_SOCKET, SO_RTABLE, &rtable, &len) == -1) {
212 error("Failed to get routing domain for fd %d: %s",
213 fd, strerror(errno));
214 return NULL;
215 }
216 xasprintf(&ret, "%d", rtable);
217 return ret;
218 }
219
220 int
set_rdomain(int fd,const char * name)221 set_rdomain(int fd, const char *name)
222 {
223 int rtable;
224 const char *errstr;
225
226 if (name == NULL)
227 return 0; /* default table */
228
229 rtable = (int)strtonum(name, 0, 255, &errstr);
230 if (errstr != NULL) {
231 /* Shouldn't happen */
232 error("Invalid routing domain \"%s\": %s", name, errstr);
233 return -1;
234 }
235 if (setsockopt(fd, SOL_SOCKET, SO_RTABLE,
236 &rtable, sizeof(rtable)) == -1) {
237 error("Failed to set routing domain %d on fd %d: %s",
238 rtable, fd, strerror(errno));
239 return -1;
240 }
241 return 0;
242 }
243
244 int
get_sock_af(int fd)245 get_sock_af(int fd)
246 {
247 struct sockaddr_storage to;
248 socklen_t tolen = sizeof(to);
249
250 memset(&to, 0, sizeof(to));
251 if (getsockname(fd, (struct sockaddr *)&to, &tolen) == -1)
252 return -1;
253 return to.ss_family;
254 }
255
256 void
set_sock_tos(int fd,int tos)257 set_sock_tos(int fd, int tos)
258 {
259 int af;
260
261 switch ((af = get_sock_af(fd))) {
262 case -1:
263 /* assume not a socket */
264 break;
265 case AF_INET:
266 debug3_f("set socket %d IP_TOS 0x%02x", fd, tos);
267 if (setsockopt(fd, IPPROTO_IP, IP_TOS,
268 &tos, sizeof(tos)) == -1) {
269 error("setsockopt socket %d IP_TOS %d: %s",
270 fd, tos, strerror(errno));
271 }
272 break;
273 case AF_INET6:
274 debug3_f("set socket %d IPV6_TCLASS 0x%02x", fd, tos);
275 if (setsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS,
276 &tos, sizeof(tos)) == -1) {
277 error("setsockopt socket %d IPV6_TCLASS %d: %s",
278 fd, tos, strerror(errno));
279 }
280 break;
281 default:
282 debug2_f("unsupported socket family %d", af);
283 break;
284 }
285 }
286
287 /*
288 * Wait up to *timeoutp milliseconds for events on fd. Updates
289 * *timeoutp with time remaining.
290 * Returns 0 if fd ready or -1 on timeout or error (see errno).
291 */
292 static int
waitfd(int fd,int * timeoutp,short events,volatile sig_atomic_t * stop)293 waitfd(int fd, int *timeoutp, short events, volatile sig_atomic_t *stop)
294 {
295 struct pollfd pfd;
296 struct timespec timeout;
297 int oerrno, r;
298 sigset_t nsigset, osigset;
299
300 if (timeoutp && *timeoutp == -1)
301 timeoutp = NULL;
302 pfd.fd = fd;
303 pfd.events = events;
304 ptimeout_init(&timeout);
305 if (timeoutp != NULL)
306 ptimeout_deadline_ms(&timeout, *timeoutp);
307 if (stop != NULL)
308 sigfillset(&nsigset);
309 for (; timeoutp == NULL || *timeoutp >= 0;) {
310 if (stop != NULL) {
311 sigprocmask(SIG_BLOCK, &nsigset, &osigset);
312 if (*stop) {
313 sigprocmask(SIG_SETMASK, &osigset, NULL);
314 errno = EINTR;
315 return -1;
316 }
317 }
318 r = ppoll(&pfd, 1, ptimeout_get_tsp(&timeout),
319 stop != NULL ? &osigset : NULL);
320 oerrno = errno;
321 if (stop != NULL)
322 sigprocmask(SIG_SETMASK, &osigset, NULL);
323 if (timeoutp)
324 *timeoutp = ptimeout_get_ms(&timeout);
325 errno = oerrno;
326 if (r > 0)
327 return 0;
328 else if (r == -1 && errno != EAGAIN && errno != EINTR)
329 return -1;
330 else if (r == 0)
331 break;
332 }
333 /* timeout */
334 errno = ETIMEDOUT;
335 return -1;
336 }
337
338 /*
339 * Wait up to *timeoutp milliseconds for fd to be readable. Updates
340 * *timeoutp with time remaining.
341 * Returns 0 if fd ready or -1 on timeout or error (see errno).
342 */
343 int
waitrfd(int fd,int * timeoutp,volatile sig_atomic_t * stop)344 waitrfd(int fd, int *timeoutp, volatile sig_atomic_t *stop) {
345 return waitfd(fd, timeoutp, POLLIN, stop);
346 }
347
348 /*
349 * Attempt a non-blocking connect(2) to the specified address, waiting up to
350 * *timeoutp milliseconds for the connection to complete. If the timeout is
351 * <=0, then wait indefinitely.
352 *
353 * Returns 0 on success or -1 on failure.
354 */
355 int
timeout_connect(int sockfd,const struct sockaddr * serv_addr,socklen_t addrlen,int * timeoutp)356 timeout_connect(int sockfd, const struct sockaddr *serv_addr,
357 socklen_t addrlen, int *timeoutp)
358 {
359 int optval = 0;
360 socklen_t optlen = sizeof(optval);
361
362 /* No timeout: just do a blocking connect() */
363 if (timeoutp == NULL || *timeoutp <= 0)
364 return connect(sockfd, serv_addr, addrlen);
365
366 set_nonblock(sockfd);
367 for (;;) {
368 if (connect(sockfd, serv_addr, addrlen) == 0) {
369 /* Succeeded already? */
370 unset_nonblock(sockfd);
371 return 0;
372 } else if (errno == EINTR)
373 continue;
374 else if (errno != EINPROGRESS)
375 return -1;
376 break;
377 }
378
379 if (waitfd(sockfd, timeoutp, POLLIN | POLLOUT, NULL) == -1)
380 return -1;
381
382 /* Completed or failed */
383 if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval, &optlen) == -1) {
384 debug("getsockopt: %s", strerror(errno));
385 return -1;
386 }
387 if (optval != 0) {
388 errno = optval;
389 return -1;
390 }
391 unset_nonblock(sockfd);
392 return 0;
393 }
394
395 /* Characters considered whitespace in strsep calls. */
396 #define WHITESPACE " \t\r\n"
397 #define QUOTE "\""
398
399 /* return next token in configuration line */
400 static char *
strdelim_internal(char ** s,int split_equals)401 strdelim_internal(char **s, int split_equals)
402 {
403 char *old;
404 int wspace = 0;
405
406 if (*s == NULL)
407 return NULL;
408
409 old = *s;
410
411 *s = strpbrk(*s,
412 split_equals ? WHITESPACE QUOTE "=" : WHITESPACE QUOTE);
413 if (*s == NULL)
414 return (old);
415
416 if (*s[0] == '\"') {
417 memmove(*s, *s + 1, strlen(*s)); /* move nul too */
418 /* Find matching quote */
419 if ((*s = strpbrk(*s, QUOTE)) == NULL) {
420 return (NULL); /* no matching quote */
421 } else {
422 *s[0] = '\0';
423 *s += strspn(*s + 1, WHITESPACE) + 1;
424 return (old);
425 }
426 }
427
428 /* Allow only one '=' to be skipped */
429 if (split_equals && *s[0] == '=')
430 wspace = 1;
431 *s[0] = '\0';
432
433 /* Skip any extra whitespace after first token */
434 *s += strspn(*s + 1, WHITESPACE) + 1;
435 if (split_equals && *s[0] == '=' && !wspace)
436 *s += strspn(*s + 1, WHITESPACE) + 1;
437
438 return (old);
439 }
440
441 /*
442 * Return next token in configuration line; splts on whitespace or a
443 * single '=' character.
444 */
445 char *
strdelim(char ** s)446 strdelim(char **s)
447 {
448 return strdelim_internal(s, 1);
449 }
450
451 /*
452 * Return next token in configuration line; splts on whitespace only.
453 */
454 char *
strdelimw(char ** s)455 strdelimw(char **s)
456 {
457 return strdelim_internal(s, 0);
458 }
459
460 struct passwd *
pwcopy(struct passwd * pw)461 pwcopy(struct passwd *pw)
462 {
463 struct passwd *copy = xcalloc(1, sizeof(*copy));
464
465 copy->pw_name = xstrdup(pw->pw_name);
466 copy->pw_passwd = xstrdup(pw->pw_passwd);
467 copy->pw_gecos = xstrdup(pw->pw_gecos);
468 copy->pw_uid = pw->pw_uid;
469 copy->pw_gid = pw->pw_gid;
470 copy->pw_expire = pw->pw_expire;
471 copy->pw_change = pw->pw_change;
472 copy->pw_class = xstrdup(pw->pw_class);
473 copy->pw_dir = xstrdup(pw->pw_dir);
474 copy->pw_shell = xstrdup(pw->pw_shell);
475 return copy;
476 }
477
478 /*
479 * Convert ASCII string to TCP/IP port number.
480 * Port must be >=0 and <=65535.
481 * Return -1 if invalid.
482 */
483 int
a2port(const char * s)484 a2port(const char *s)
485 {
486 struct servent *se;
487 long long port;
488 const char *errstr;
489
490 port = strtonum(s, 0, 65535, &errstr);
491 if (errstr == NULL)
492 return (int)port;
493 if ((se = getservbyname(s, "tcp")) != NULL)
494 return ntohs(se->s_port);
495 return -1;
496 }
497
498 int
a2tun(const char * s,int * remote)499 a2tun(const char *s, int *remote)
500 {
501 const char *errstr = NULL;
502 char *sp, *ep;
503 int tun;
504
505 if (remote != NULL) {
506 *remote = SSH_TUNID_ANY;
507 sp = xstrdup(s);
508 if ((ep = strchr(sp, ':')) == NULL) {
509 free(sp);
510 return (a2tun(s, NULL));
511 }
512 ep[0] = '\0'; ep++;
513 *remote = a2tun(ep, NULL);
514 tun = a2tun(sp, NULL);
515 free(sp);
516 return (*remote == SSH_TUNID_ERR ? *remote : tun);
517 }
518
519 if (strcasecmp(s, "any") == 0)
520 return (SSH_TUNID_ANY);
521
522 tun = strtonum(s, 0, SSH_TUNID_MAX, &errstr);
523 if (errstr != NULL)
524 return (SSH_TUNID_ERR);
525
526 return (tun);
527 }
528
529 #define SECONDS 1
530 #define MINUTES (SECONDS * 60)
531 #define HOURS (MINUTES * 60)
532 #define DAYS (HOURS * 24)
533 #define WEEKS (DAYS * 7)
534
535 static char *
scandigits(char * s)536 scandigits(char *s)
537 {
538 while (isdigit((unsigned char)*s))
539 s++;
540 return s;
541 }
542
543 /*
544 * Convert a time string into seconds; format is
545 * a sequence of:
546 * time[qualifier]
547 *
548 * Valid time qualifiers are:
549 * <none> seconds
550 * s|S seconds
551 * m|M minutes
552 * h|H hours
553 * d|D days
554 * w|W weeks
555 *
556 * Examples:
557 * 90m 90 minutes
558 * 1h30m 90 minutes
559 * 2d 2 days
560 * 1w 1 week
561 *
562 * Return -1 if time string is invalid.
563 */
564 int
convtime(const char * s)565 convtime(const char *s)
566 {
567 int secs, total = 0, multiplier;
568 char *p, *os, *np, c = 0;
569 const char *errstr;
570
571 if (s == NULL || *s == '\0')
572 return -1;
573 p = os = strdup(s); /* deal with const */
574 if (os == NULL)
575 return -1;
576
577 while (*p) {
578 np = scandigits(p);
579 if (np) {
580 c = *np;
581 *np = '\0';
582 }
583 secs = (int)strtonum(p, 0, INT_MAX, &errstr);
584 if (errstr)
585 goto fail;
586 *np = c;
587
588 multiplier = 1;
589 switch (c) {
590 case '\0':
591 np--; /* back up */
592 break;
593 case 's':
594 case 'S':
595 break;
596 case 'm':
597 case 'M':
598 multiplier = MINUTES;
599 break;
600 case 'h':
601 case 'H':
602 multiplier = HOURS;
603 break;
604 case 'd':
605 case 'D':
606 multiplier = DAYS;
607 break;
608 case 'w':
609 case 'W':
610 multiplier = WEEKS;
611 break;
612 default:
613 goto fail;
614 }
615 if (secs > INT_MAX / multiplier)
616 goto fail;
617 secs *= multiplier;
618 if (total > INT_MAX - secs)
619 goto fail;
620 total += secs;
621 if (total < 0)
622 goto fail;
623 p = ++np;
624 }
625 free(os);
626 return total;
627 fail:
628 free(os);
629 return -1;
630 }
631
632 #define TF_BUFS 8
633 #define TF_LEN 9
634
635 const char *
fmt_timeframe(time_t t)636 fmt_timeframe(time_t t)
637 {
638 char *buf;
639 static char tfbuf[TF_BUFS][TF_LEN]; /* ring buffer */
640 static int idx = 0;
641 unsigned int sec, min, hrs, day;
642 unsigned long long week;
643
644 buf = tfbuf[idx++];
645 if (idx == TF_BUFS)
646 idx = 0;
647
648 week = t;
649
650 sec = week % 60;
651 week /= 60;
652 min = week % 60;
653 week /= 60;
654 hrs = week % 24;
655 week /= 24;
656 day = week % 7;
657 week /= 7;
658
659 if (week > 0)
660 snprintf(buf, TF_LEN, "%02lluw%01ud%02uh", week, day, hrs);
661 else if (day > 0)
662 snprintf(buf, TF_LEN, "%01ud%02uh%02um", day, hrs, min);
663 else
664 snprintf(buf, TF_LEN, "%02u:%02u:%02u", hrs, min, sec);
665
666 return (buf);
667 }
668
669 /*
670 * Returns a standardized host+port identifier string.
671 * Caller must free returned string.
672 */
673 char *
put_host_port(const char * host,u_short port)674 put_host_port(const char *host, u_short port)
675 {
676 char *hoststr;
677
678 if (port == 0 || port == SSH_DEFAULT_PORT)
679 return(xstrdup(host));
680 if (asprintf(&hoststr, "[%s]:%d", host, (int)port) == -1)
681 fatal("put_host_port: asprintf: %s", strerror(errno));
682 debug3("put_host_port: %s", hoststr);
683 return hoststr;
684 }
685
686 /*
687 * Search for next delimiter between hostnames/addresses and ports.
688 * Argument may be modified (for termination).
689 * Returns *cp if parsing succeeds.
690 * *cp is set to the start of the next field, if one was found.
691 * The delimiter char, if present, is stored in delim.
692 * If this is the last field, *cp is set to NULL.
693 */
694 char *
hpdelim2(char ** cp,char * delim)695 hpdelim2(char **cp, char *delim)
696 {
697 char *s, *old;
698
699 if (cp == NULL || *cp == NULL)
700 return NULL;
701
702 old = s = *cp;
703 if (*s == '[') {
704 if ((s = strchr(s, ']')) == NULL)
705 return NULL;
706 else
707 s++;
708 } else if ((s = strpbrk(s, ":/")) == NULL)
709 s = *cp + strlen(*cp); /* skip to end (see first case below) */
710
711 switch (*s) {
712 case '\0':
713 *cp = NULL; /* no more fields*/
714 break;
715
716 case ':':
717 case '/':
718 if (delim != NULL)
719 *delim = *s;
720 *s = '\0'; /* terminate */
721 *cp = s + 1;
722 break;
723
724 default:
725 return NULL;
726 }
727
728 return old;
729 }
730
731 /* The common case: only accept colon as delimiter. */
732 char *
hpdelim(char ** cp)733 hpdelim(char **cp)
734 {
735 char *r, delim = '\0';
736
737 r = hpdelim2(cp, &delim);
738 if (delim == '/')
739 return NULL;
740 return r;
741 }
742
743 char *
cleanhostname(char * host)744 cleanhostname(char *host)
745 {
746 if (*host == '[' && host[strlen(host) - 1] == ']') {
747 host[strlen(host) - 1] = '\0';
748 return (host + 1);
749 } else
750 return host;
751 }
752
753 char *
colon(char * cp)754 colon(char *cp)
755 {
756 int flag = 0;
757
758 if (*cp == ':') /* Leading colon is part of file name. */
759 return NULL;
760 if (*cp == '[')
761 flag = 1;
762
763 for (; *cp; ++cp) {
764 if (*cp == '@' && *(cp+1) == '[')
765 flag = 1;
766 if (*cp == ']' && *(cp+1) == ':' && flag)
767 return (cp+1);
768 if (*cp == ':' && !flag)
769 return (cp);
770 if (*cp == '/')
771 return NULL;
772 }
773 return NULL;
774 }
775
776 /*
777 * Parse a [user@]host:[path] string.
778 * Caller must free returned user, host and path.
779 * Any of the pointer return arguments may be NULL (useful for syntax checking).
780 * If user was not specified then *userp will be set to NULL.
781 * If host was not specified then *hostp will be set to NULL.
782 * If path was not specified then *pathp will be set to ".".
783 * Returns 0 on success, -1 on failure.
784 */
785 int
parse_user_host_path(const char * s,char ** userp,char ** hostp,char ** pathp)786 parse_user_host_path(const char *s, char **userp, char **hostp, char **pathp)
787 {
788 char *user = NULL, *host = NULL, *path = NULL;
789 char *sdup, *tmp;
790 int ret = -1;
791
792 if (userp != NULL)
793 *userp = NULL;
794 if (hostp != NULL)
795 *hostp = NULL;
796 if (pathp != NULL)
797 *pathp = NULL;
798
799 sdup = xstrdup(s);
800
801 /* Check for remote syntax: [user@]host:[path] */
802 if ((tmp = colon(sdup)) == NULL)
803 goto out;
804
805 /* Extract optional path */
806 *tmp++ = '\0';
807 if (*tmp == '\0')
808 tmp = ".";
809 path = xstrdup(tmp);
810
811 /* Extract optional user and mandatory host */
812 tmp = strrchr(sdup, '@');
813 if (tmp != NULL) {
814 *tmp++ = '\0';
815 host = xstrdup(cleanhostname(tmp));
816 if (*sdup != '\0')
817 user = xstrdup(sdup);
818 } else {
819 host = xstrdup(cleanhostname(sdup));
820 user = NULL;
821 }
822
823 /* Success */
824 if (userp != NULL) {
825 *userp = user;
826 user = NULL;
827 }
828 if (hostp != NULL) {
829 *hostp = host;
830 host = NULL;
831 }
832 if (pathp != NULL) {
833 *pathp = path;
834 path = NULL;
835 }
836 ret = 0;
837 out:
838 free(sdup);
839 free(user);
840 free(host);
841 free(path);
842 return ret;
843 }
844
845 /*
846 * Parse a [user@]host[:port] string.
847 * Caller must free returned user and host.
848 * Any of the pointer return arguments may be NULL (useful for syntax checking).
849 * If user was not specified then *userp will be set to NULL.
850 * If port was not specified then *portp will be -1.
851 * Returns 0 on success, -1 on failure.
852 */
853 int
parse_user_host_port(const char * s,char ** userp,char ** hostp,int * portp)854 parse_user_host_port(const char *s, char **userp, char **hostp, int *portp)
855 {
856 char *sdup, *cp, *tmp;
857 char *user = NULL, *host = NULL;
858 int port = -1, ret = -1;
859
860 if (userp != NULL)
861 *userp = NULL;
862 if (hostp != NULL)
863 *hostp = NULL;
864 if (portp != NULL)
865 *portp = -1;
866
867 if ((sdup = tmp = strdup(s)) == NULL)
868 return -1;
869 /* Extract optional username */
870 if ((cp = strrchr(tmp, '@')) != NULL) {
871 *cp = '\0';
872 if (*tmp == '\0')
873 goto out;
874 if ((user = strdup(tmp)) == NULL)
875 goto out;
876 tmp = cp + 1;
877 }
878 /* Extract mandatory hostname */
879 if ((cp = hpdelim(&tmp)) == NULL || *cp == '\0')
880 goto out;
881 host = xstrdup(cleanhostname(cp));
882 /* Convert and verify optional port */
883 if (tmp != NULL && *tmp != '\0') {
884 if ((port = a2port(tmp)) <= 0)
885 goto out;
886 }
887 /* Success */
888 if (userp != NULL) {
889 *userp = user;
890 user = NULL;
891 }
892 if (hostp != NULL) {
893 *hostp = host;
894 host = NULL;
895 }
896 if (portp != NULL)
897 *portp = port;
898 ret = 0;
899 out:
900 free(sdup);
901 free(user);
902 free(host);
903 return ret;
904 }
905
906 /*
907 * Converts a two-byte hex string to decimal.
908 * Returns the decimal value or -1 for invalid input.
909 */
910 static int
hexchar(const char * s)911 hexchar(const char *s)
912 {
913 unsigned char result[2];
914 int i;
915
916 for (i = 0; i < 2; i++) {
917 if (s[i] >= '0' && s[i] <= '9')
918 result[i] = (unsigned char)(s[i] - '0');
919 else if (s[i] >= 'a' && s[i] <= 'f')
920 result[i] = (unsigned char)(s[i] - 'a') + 10;
921 else if (s[i] >= 'A' && s[i] <= 'F')
922 result[i] = (unsigned char)(s[i] - 'A') + 10;
923 else
924 return -1;
925 }
926 return (result[0] << 4) | result[1];
927 }
928
929 /*
930 * Decode an url-encoded string.
931 * Returns a newly allocated string on success or NULL on failure.
932 */
933 static char *
urldecode(const char * src)934 urldecode(const char *src)
935 {
936 char *ret, *dst;
937 int ch;
938 size_t srclen;
939
940 if ((srclen = strlen(src)) >= SIZE_MAX)
941 fatal_f("input too large");
942 ret = xmalloc(srclen + 1);
943 for (dst = ret; *src != '\0'; src++) {
944 switch (*src) {
945 case '+':
946 *dst++ = ' ';
947 break;
948 case '%':
949 if (!isxdigit((unsigned char)src[1]) ||
950 !isxdigit((unsigned char)src[2]) ||
951 (ch = hexchar(src + 1)) == -1) {
952 free(ret);
953 return NULL;
954 }
955 *dst++ = ch;
956 src += 2;
957 break;
958 default:
959 *dst++ = *src;
960 break;
961 }
962 }
963 *dst = '\0';
964
965 return ret;
966 }
967
968 /*
969 * Parse an (scp|ssh|sftp)://[user@]host[:port][/path] URI.
970 * See https://tools.ietf.org/html/draft-ietf-secsh-scp-sftp-ssh-uri-04
971 * Either user or path may be url-encoded (but not host or port).
972 * Caller must free returned user, host and path.
973 * Any of the pointer return arguments may be NULL (useful for syntax checking)
974 * but the scheme must always be specified.
975 * If user was not specified then *userp will be set to NULL.
976 * If port was not specified then *portp will be -1.
977 * If path was not specified then *pathp will be set to NULL.
978 * Returns 0 on success, 1 if non-uri/wrong scheme, -1 on error/invalid uri.
979 */
980 int
parse_uri(const char * scheme,const char * uri,char ** userp,char ** hostp,int * portp,char ** pathp)981 parse_uri(const char *scheme, const char *uri, char **userp, char **hostp,
982 int *portp, char **pathp)
983 {
984 char *uridup, *cp, *tmp, ch;
985 char *user = NULL, *host = NULL, *path = NULL;
986 int port = -1, ret = -1;
987 size_t len;
988
989 len = strlen(scheme);
990 if (strncmp(uri, scheme, len) != 0 || strncmp(uri + len, "://", 3) != 0)
991 return 1;
992 uri += len + 3;
993
994 if (userp != NULL)
995 *userp = NULL;
996 if (hostp != NULL)
997 *hostp = NULL;
998 if (portp != NULL)
999 *portp = -1;
1000 if (pathp != NULL)
1001 *pathp = NULL;
1002
1003 uridup = tmp = xstrdup(uri);
1004
1005 /* Extract optional ssh-info (username + connection params) */
1006 if ((cp = strchr(tmp, '@')) != NULL) {
1007 char *delim;
1008
1009 *cp = '\0';
1010 /* Extract username and connection params */
1011 if ((delim = strchr(tmp, ';')) != NULL) {
1012 /* Just ignore connection params for now */
1013 *delim = '\0';
1014 }
1015 if (*tmp == '\0') {
1016 /* Empty username */
1017 goto out;
1018 }
1019 if ((user = urldecode(tmp)) == NULL)
1020 goto out;
1021 tmp = cp + 1;
1022 }
1023
1024 /* Extract mandatory hostname */
1025 if ((cp = hpdelim2(&tmp, &ch)) == NULL || *cp == '\0')
1026 goto out;
1027 host = xstrdup(cleanhostname(cp));
1028 if (!valid_domain(host, 0, NULL))
1029 goto out;
1030
1031 if (tmp != NULL && *tmp != '\0') {
1032 if (ch == ':') {
1033 /* Convert and verify port. */
1034 if ((cp = strchr(tmp, '/')) != NULL)
1035 *cp = '\0';
1036 if ((port = a2port(tmp)) <= 0)
1037 goto out;
1038 tmp = cp ? cp + 1 : NULL;
1039 }
1040 if (tmp != NULL && *tmp != '\0') {
1041 /* Extract optional path */
1042 if ((path = urldecode(tmp)) == NULL)
1043 goto out;
1044 }
1045 }
1046
1047 /* Success */
1048 if (userp != NULL) {
1049 *userp = user;
1050 user = NULL;
1051 }
1052 if (hostp != NULL) {
1053 *hostp = host;
1054 host = NULL;
1055 }
1056 if (portp != NULL)
1057 *portp = port;
1058 if (pathp != NULL) {
1059 *pathp = path;
1060 path = NULL;
1061 }
1062 ret = 0;
1063 out:
1064 free(uridup);
1065 free(user);
1066 free(host);
1067 free(path);
1068 return ret;
1069 }
1070
1071 /* function to assist building execv() arguments */
1072 void
addargs(arglist * args,char * fmt,...)1073 addargs(arglist *args, char *fmt, ...)
1074 {
1075 va_list ap;
1076 char *cp;
1077 u_int nalloc;
1078 int r;
1079
1080 va_start(ap, fmt);
1081 r = vasprintf(&cp, fmt, ap);
1082 va_end(ap);
1083 if (r == -1)
1084 fatal_f("argument too long");
1085
1086 nalloc = args->nalloc;
1087 if (args->list == NULL) {
1088 nalloc = 32;
1089 args->num = 0;
1090 } else if (args->num > (256 * 1024))
1091 fatal_f("too many arguments");
1092 else if (args->num >= args->nalloc)
1093 fatal_f("arglist corrupt");
1094 else if (args->num+2 >= nalloc)
1095 nalloc *= 2;
1096
1097 args->list = xrecallocarray(args->list, args->nalloc,
1098 nalloc, sizeof(char *));
1099 args->nalloc = nalloc;
1100 args->list[args->num++] = cp;
1101 args->list[args->num] = NULL;
1102 }
1103
1104 void
replacearg(arglist * args,u_int which,char * fmt,...)1105 replacearg(arglist *args, u_int which, char *fmt, ...)
1106 {
1107 va_list ap;
1108 char *cp;
1109 int r;
1110
1111 va_start(ap, fmt);
1112 r = vasprintf(&cp, fmt, ap);
1113 va_end(ap);
1114 if (r == -1)
1115 fatal_f("argument too long");
1116 if (args->list == NULL || args->num >= args->nalloc)
1117 fatal_f("arglist corrupt");
1118
1119 if (which >= args->num)
1120 fatal_f("tried to replace invalid arg %d >= %d",
1121 which, args->num);
1122 free(args->list[which]);
1123 args->list[which] = cp;
1124 }
1125
1126 void
freeargs(arglist * args)1127 freeargs(arglist *args)
1128 {
1129 u_int i;
1130
1131 if (args == NULL)
1132 return;
1133 if (args->list != NULL && args->num < args->nalloc) {
1134 for (i = 0; i < args->num; i++)
1135 free(args->list[i]);
1136 free(args->list);
1137 }
1138 args->nalloc = args->num = 0;
1139 args->list = NULL;
1140 }
1141
1142 /*
1143 * Expands tildes in the file name. Returns data allocated by xmalloc.
1144 * Warning: this calls getpw*.
1145 */
1146 int
tilde_expand(const char * filename,uid_t uid,char ** retp)1147 tilde_expand(const char *filename, uid_t uid, char **retp)
1148 {
1149 char *ocopy = NULL, *copy, *s = NULL;
1150 const char *path = NULL, *user = NULL;
1151 struct passwd *pw;
1152 size_t len;
1153 int ret = -1, r, slash;
1154
1155 *retp = NULL;
1156 if (*filename != '~') {
1157 *retp = xstrdup(filename);
1158 return 0;
1159 }
1160 ocopy = copy = xstrdup(filename + 1);
1161
1162 if (*copy == '\0') /* ~ */
1163 path = NULL;
1164 else if (*copy == '/') {
1165 copy += strspn(copy, "/");
1166 if (*copy == '\0')
1167 path = NULL; /* ~/ */
1168 else
1169 path = copy; /* ~/path */
1170 } else {
1171 user = copy;
1172 if ((path = strchr(copy, '/')) != NULL) {
1173 copy[path - copy] = '\0';
1174 path++;
1175 path += strspn(path, "/");
1176 if (*path == '\0') /* ~user/ */
1177 path = NULL;
1178 /* else ~user/path */
1179 }
1180 /* else ~user */
1181 }
1182 if (user != NULL) {
1183 if ((pw = getpwnam(user)) == NULL) {
1184 error_f("No such user %s", user);
1185 goto out;
1186 }
1187 } else if ((pw = getpwuid(uid)) == NULL) {
1188 error_f("No such uid %ld", (long)uid);
1189 goto out;
1190 }
1191
1192 /* Make sure directory has a trailing '/' */
1193 slash = (len = strlen(pw->pw_dir)) == 0 || pw->pw_dir[len - 1] != '/';
1194
1195 if ((r = xasprintf(&s, "%s%s%s", pw->pw_dir,
1196 slash ? "/" : "", path != NULL ? path : "")) <= 0) {
1197 error_f("xasprintf failed");
1198 goto out;
1199 }
1200 if (r >= PATH_MAX) {
1201 error_f("Path too long");
1202 goto out;
1203 }
1204 /* success */
1205 ret = 0;
1206 *retp = s;
1207 s = NULL;
1208 out:
1209 free(s);
1210 free(ocopy);
1211 return ret;
1212 }
1213
1214 char *
tilde_expand_filename(const char * filename,uid_t uid)1215 tilde_expand_filename(const char *filename, uid_t uid)
1216 {
1217 char *ret;
1218
1219 if (tilde_expand(filename, uid, &ret) != 0)
1220 cleanup_exit(255);
1221 return ret;
1222 }
1223
1224 /*
1225 * Expand a string with a set of %[char] escapes and/or ${ENVIRONMENT}
1226 * substitutions. A number of escapes may be specified as
1227 * (char *escape_chars, char *replacement) pairs. The list must be terminated
1228 * by a NULL escape_char. Returns replaced string in memory allocated by
1229 * xmalloc which the caller must free.
1230 */
1231 static char *
vdollar_percent_expand(int * parseerror,int dollar,int percent,const char * string,va_list ap)1232 vdollar_percent_expand(int *parseerror, int dollar, int percent,
1233 const char *string, va_list ap)
1234 {
1235 #define EXPAND_MAX_KEYS 64
1236 u_int num_keys = 0, i;
1237 struct {
1238 const char *key;
1239 const char *repl;
1240 } keys[EXPAND_MAX_KEYS];
1241 struct sshbuf *buf;
1242 int r, missingvar = 0;
1243 char *ret = NULL, *var, *varend, *val;
1244 size_t len;
1245
1246 if ((buf = sshbuf_new()) == NULL)
1247 fatal_f("sshbuf_new failed");
1248 if (parseerror == NULL)
1249 fatal_f("null parseerror arg");
1250 *parseerror = 1;
1251
1252 /* Gather keys if we're doing percent expansion. */
1253 if (percent) {
1254 for (num_keys = 0; num_keys < EXPAND_MAX_KEYS; num_keys++) {
1255 keys[num_keys].key = va_arg(ap, char *);
1256 if (keys[num_keys].key == NULL)
1257 break;
1258 keys[num_keys].repl = va_arg(ap, char *);
1259 if (keys[num_keys].repl == NULL) {
1260 fatal_f("NULL replacement for token %s",
1261 keys[num_keys].key);
1262 }
1263 }
1264 if (num_keys == EXPAND_MAX_KEYS && va_arg(ap, char *) != NULL)
1265 fatal_f("too many keys");
1266 if (num_keys == 0)
1267 fatal_f("percent expansion without token list");
1268 }
1269
1270 /* Expand string */
1271 for (i = 0; *string != '\0'; string++) {
1272 /* Optionally process ${ENVIRONMENT} expansions. */
1273 if (dollar && string[0] == '$' && string[1] == '{') {
1274 string += 2; /* skip over '${' */
1275 if ((varend = strchr(string, '}')) == NULL) {
1276 error_f("environment variable '%s' missing "
1277 "closing '}'", string);
1278 goto out;
1279 }
1280 len = varend - string;
1281 if (len == 0) {
1282 error_f("zero-length environment variable");
1283 goto out;
1284 }
1285 var = xmalloc(len + 1);
1286 (void)strlcpy(var, string, len + 1);
1287 if ((val = getenv(var)) == NULL) {
1288 error_f("env var ${%s} has no value", var);
1289 missingvar = 1;
1290 } else {
1291 debug3_f("expand ${%s} -> '%s'", var, val);
1292 if ((r = sshbuf_put(buf, val, strlen(val))) !=0)
1293 fatal_fr(r, "sshbuf_put ${}");
1294 }
1295 free(var);
1296 string += len;
1297 continue;
1298 }
1299
1300 /*
1301 * Process percent expansions if we have a list of TOKENs.
1302 * If we're not doing percent expansion everything just gets
1303 * appended here.
1304 */
1305 if (*string != '%' || !percent) {
1306 append:
1307 if ((r = sshbuf_put_u8(buf, *string)) != 0)
1308 fatal_fr(r, "sshbuf_put_u8 %%");
1309 continue;
1310 }
1311 string++;
1312 /* %% case */
1313 if (*string == '%')
1314 goto append;
1315 if (*string == '\0') {
1316 error_f("invalid format");
1317 goto out;
1318 }
1319 for (i = 0; i < num_keys; i++) {
1320 if (strchr(keys[i].key, *string) != NULL) {
1321 if ((r = sshbuf_put(buf, keys[i].repl,
1322 strlen(keys[i].repl))) != 0)
1323 fatal_fr(r, "sshbuf_put %%-repl");
1324 break;
1325 }
1326 }
1327 if (i >= num_keys) {
1328 error_f("unknown key %%%c", *string);
1329 goto out;
1330 }
1331 }
1332 if (!missingvar && (ret = sshbuf_dup_string(buf)) == NULL)
1333 fatal_f("sshbuf_dup_string failed");
1334 *parseerror = 0;
1335 out:
1336 sshbuf_free(buf);
1337 return *parseerror ? NULL : ret;
1338 #undef EXPAND_MAX_KEYS
1339 }
1340
1341 /*
1342 * Expand only environment variables.
1343 * Note that although this function is variadic like the other similar
1344 * functions, any such arguments will be unused.
1345 */
1346
1347 char *
dollar_expand(int * parseerr,const char * string,...)1348 dollar_expand(int *parseerr, const char *string, ...)
1349 {
1350 char *ret;
1351 int err;
1352 va_list ap;
1353
1354 va_start(ap, string);
1355 ret = vdollar_percent_expand(&err, 1, 0, string, ap);
1356 va_end(ap);
1357 if (parseerr != NULL)
1358 *parseerr = err;
1359 return ret;
1360 }
1361
1362 /*
1363 * Returns expanded string or NULL if a specified environment variable is
1364 * not defined, or calls fatal if the string is invalid.
1365 */
1366 char *
percent_expand(const char * string,...)1367 percent_expand(const char *string, ...)
1368 {
1369 char *ret;
1370 int err;
1371 va_list ap;
1372
1373 va_start(ap, string);
1374 ret = vdollar_percent_expand(&err, 0, 1, string, ap);
1375 va_end(ap);
1376 if (err)
1377 fatal_f("failed");
1378 return ret;
1379 }
1380
1381 /*
1382 * Returns expanded string or NULL if a specified environment variable is
1383 * not defined, or calls fatal if the string is invalid.
1384 */
1385 char *
percent_dollar_expand(const char * string,...)1386 percent_dollar_expand(const char *string, ...)
1387 {
1388 char *ret;
1389 int err;
1390 va_list ap;
1391
1392 va_start(ap, string);
1393 ret = vdollar_percent_expand(&err, 1, 1, string, ap);
1394 va_end(ap);
1395 if (err)
1396 fatal_f("failed");
1397 return ret;
1398 }
1399
1400 int
tun_open(int tun,int mode,char ** ifname)1401 tun_open(int tun, int mode, char **ifname)
1402 {
1403 struct ifreq ifr;
1404 char name[100];
1405 int fd = -1, sock;
1406 const char *tunbase = "tun";
1407
1408 if (ifname != NULL)
1409 *ifname = NULL;
1410
1411 if (mode == SSH_TUNMODE_ETHERNET)
1412 tunbase = "tap";
1413
1414 /* Open the tunnel device */
1415 if (tun <= SSH_TUNID_MAX) {
1416 snprintf(name, sizeof(name), "/dev/%s%d", tunbase, tun);
1417 fd = open(name, O_RDWR);
1418 } else if (tun == SSH_TUNID_ANY) {
1419 for (tun = 100; tun >= 0; tun--) {
1420 snprintf(name, sizeof(name), "/dev/%s%d",
1421 tunbase, tun);
1422 if ((fd = open(name, O_RDWR)) >= 0)
1423 break;
1424 }
1425 } else {
1426 debug_f("invalid tunnel %u", tun);
1427 return -1;
1428 }
1429
1430 if (fd == -1) {
1431 debug_f("%s open: %s", name, strerror(errno));
1432 return -1;
1433 }
1434
1435 debug_f("%s mode %d fd %d", name, mode, fd);
1436
1437 /* Bring interface up if it is not already */
1438 snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s%d", tunbase, tun);
1439 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) == -1)
1440 goto failed;
1441
1442 if (ioctl(sock, SIOCGIFFLAGS, &ifr) == -1) {
1443 debug_f("get interface %s flags: %s", ifr.ifr_name,
1444 strerror(errno));
1445 goto failed;
1446 }
1447
1448 if (!(ifr.ifr_flags & IFF_UP)) {
1449 ifr.ifr_flags |= IFF_UP;
1450 if (ioctl(sock, SIOCSIFFLAGS, &ifr) == -1) {
1451 debug_f("activate interface %s: %s", ifr.ifr_name,
1452 strerror(errno));
1453 goto failed;
1454 }
1455 }
1456
1457 if (ifname != NULL)
1458 *ifname = xstrdup(ifr.ifr_name);
1459
1460 close(sock);
1461 return fd;
1462
1463 failed:
1464 if (fd >= 0)
1465 close(fd);
1466 if (sock >= 0)
1467 close(sock);
1468 return -1;
1469 }
1470
1471 void
sanitise_stdfd(void)1472 sanitise_stdfd(void)
1473 {
1474 int nullfd, dupfd;
1475
1476 if ((nullfd = dupfd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1477 fprintf(stderr, "Couldn't open /dev/null: %s\n",
1478 strerror(errno));
1479 exit(1);
1480 }
1481 while (++dupfd <= STDERR_FILENO) {
1482 /* Only populate closed fds. */
1483 if (fcntl(dupfd, F_GETFL) == -1 && errno == EBADF) {
1484 if (dup2(nullfd, dupfd) == -1) {
1485 fprintf(stderr, "dup2: %s\n", strerror(errno));
1486 exit(1);
1487 }
1488 }
1489 }
1490 if (nullfd > STDERR_FILENO)
1491 close(nullfd);
1492 }
1493
1494 char *
tohex(const void * vp,size_t l)1495 tohex(const void *vp, size_t l)
1496 {
1497 const u_char *p = (const u_char *)vp;
1498 char b[3], *r;
1499 size_t i, hl;
1500
1501 if (l > 65536)
1502 return xstrdup("tohex: length > 65536");
1503
1504 hl = l * 2 + 1;
1505 r = xcalloc(1, hl);
1506 for (i = 0; i < l; i++) {
1507 snprintf(b, sizeof(b), "%02x", p[i]);
1508 strlcat(r, b, hl);
1509 }
1510 return (r);
1511 }
1512
1513 /*
1514 * Extend string *sp by the specified format. If *sp is not NULL (or empty),
1515 * then the separator 'sep' will be prepended before the formatted arguments.
1516 * Extended strings are heap allocated.
1517 */
1518 void
xextendf(char ** sp,const char * sep,const char * fmt,...)1519 xextendf(char **sp, const char *sep, const char *fmt, ...)
1520 {
1521 va_list ap;
1522 char *tmp1, *tmp2;
1523
1524 va_start(ap, fmt);
1525 xvasprintf(&tmp1, fmt, ap);
1526 va_end(ap);
1527
1528 if (*sp == NULL || **sp == '\0') {
1529 free(*sp);
1530 *sp = tmp1;
1531 return;
1532 }
1533 xasprintf(&tmp2, "%s%s%s", *sp, sep == NULL ? "" : sep, tmp1);
1534 free(tmp1);
1535 free(*sp);
1536 *sp = tmp2;
1537 }
1538
1539
1540 u_int64_t
get_u64(const void * vp)1541 get_u64(const void *vp)
1542 {
1543 const u_char *p = (const u_char *)vp;
1544 u_int64_t v;
1545
1546 v = (u_int64_t)p[0] << 56;
1547 v |= (u_int64_t)p[1] << 48;
1548 v |= (u_int64_t)p[2] << 40;
1549 v |= (u_int64_t)p[3] << 32;
1550 v |= (u_int64_t)p[4] << 24;
1551 v |= (u_int64_t)p[5] << 16;
1552 v |= (u_int64_t)p[6] << 8;
1553 v |= (u_int64_t)p[7];
1554
1555 return (v);
1556 }
1557
1558 u_int32_t
get_u32(const void * vp)1559 get_u32(const void *vp)
1560 {
1561 const u_char *p = (const u_char *)vp;
1562 u_int32_t v;
1563
1564 v = (u_int32_t)p[0] << 24;
1565 v |= (u_int32_t)p[1] << 16;
1566 v |= (u_int32_t)p[2] << 8;
1567 v |= (u_int32_t)p[3];
1568
1569 return (v);
1570 }
1571
1572 u_int32_t
get_u32_le(const void * vp)1573 get_u32_le(const void *vp)
1574 {
1575 const u_char *p = (const u_char *)vp;
1576 u_int32_t v;
1577
1578 v = (u_int32_t)p[0];
1579 v |= (u_int32_t)p[1] << 8;
1580 v |= (u_int32_t)p[2] << 16;
1581 v |= (u_int32_t)p[3] << 24;
1582
1583 return (v);
1584 }
1585
1586 u_int16_t
get_u16(const void * vp)1587 get_u16(const void *vp)
1588 {
1589 const u_char *p = (const u_char *)vp;
1590 u_int16_t v;
1591
1592 v = (u_int16_t)p[0] << 8;
1593 v |= (u_int16_t)p[1];
1594
1595 return (v);
1596 }
1597
1598 void
put_u64(void * vp,u_int64_t v)1599 put_u64(void *vp, u_int64_t v)
1600 {
1601 u_char *p = (u_char *)vp;
1602
1603 p[0] = (u_char)(v >> 56) & 0xff;
1604 p[1] = (u_char)(v >> 48) & 0xff;
1605 p[2] = (u_char)(v >> 40) & 0xff;
1606 p[3] = (u_char)(v >> 32) & 0xff;
1607 p[4] = (u_char)(v >> 24) & 0xff;
1608 p[5] = (u_char)(v >> 16) & 0xff;
1609 p[6] = (u_char)(v >> 8) & 0xff;
1610 p[7] = (u_char)v & 0xff;
1611 }
1612
1613 void
put_u32(void * vp,u_int32_t v)1614 put_u32(void *vp, u_int32_t v)
1615 {
1616 u_char *p = (u_char *)vp;
1617
1618 p[0] = (u_char)(v >> 24) & 0xff;
1619 p[1] = (u_char)(v >> 16) & 0xff;
1620 p[2] = (u_char)(v >> 8) & 0xff;
1621 p[3] = (u_char)v & 0xff;
1622 }
1623
1624 void
put_u32_le(void * vp,u_int32_t v)1625 put_u32_le(void *vp, u_int32_t v)
1626 {
1627 u_char *p = (u_char *)vp;
1628
1629 p[0] = (u_char)v & 0xff;
1630 p[1] = (u_char)(v >> 8) & 0xff;
1631 p[2] = (u_char)(v >> 16) & 0xff;
1632 p[3] = (u_char)(v >> 24) & 0xff;
1633 }
1634
1635 void
put_u16(void * vp,u_int16_t v)1636 put_u16(void *vp, u_int16_t v)
1637 {
1638 u_char *p = (u_char *)vp;
1639
1640 p[0] = (u_char)(v >> 8) & 0xff;
1641 p[1] = (u_char)v & 0xff;
1642 }
1643
1644 void
ms_subtract_diff(struct timeval * start,int * ms)1645 ms_subtract_diff(struct timeval *start, int *ms)
1646 {
1647 struct timeval diff, finish;
1648
1649 monotime_tv(&finish);
1650 timersub(&finish, start, &diff);
1651 *ms -= (diff.tv_sec * 1000) + (diff.tv_usec / 1000);
1652 }
1653
1654 void
ms_to_timespec(struct timespec * ts,int ms)1655 ms_to_timespec(struct timespec *ts, int ms)
1656 {
1657 if (ms < 0)
1658 ms = 0;
1659 ts->tv_sec = ms / 1000;
1660 ts->tv_nsec = (ms % 1000) * 1000 * 1000;
1661 }
1662
1663 void
monotime_ts(struct timespec * ts)1664 monotime_ts(struct timespec *ts)
1665 {
1666 if (clock_gettime(CLOCK_MONOTONIC, ts) != 0)
1667 fatal("clock_gettime: %s", strerror(errno));
1668 }
1669
1670 void
monotime_tv(struct timeval * tv)1671 monotime_tv(struct timeval *tv)
1672 {
1673 struct timespec ts;
1674
1675 monotime_ts(&ts);
1676 tv->tv_sec = ts.tv_sec;
1677 tv->tv_usec = ts.tv_nsec / 1000;
1678 }
1679
1680 time_t
monotime(void)1681 monotime(void)
1682 {
1683 struct timespec ts;
1684
1685 monotime_ts(&ts);
1686 return (ts.tv_sec);
1687 }
1688
1689 double
monotime_double(void)1690 monotime_double(void)
1691 {
1692 struct timespec ts;
1693
1694 monotime_ts(&ts);
1695 return (double)ts.tv_sec + (double)ts.tv_nsec / 1000000000.0;
1696 }
1697
1698 void
bandwidth_limit_init(struct bwlimit * bw,u_int64_t kbps,size_t buflen)1699 bandwidth_limit_init(struct bwlimit *bw, u_int64_t kbps, size_t buflen)
1700 {
1701 bw->buflen = buflen;
1702 bw->rate = kbps;
1703 bw->thresh = buflen;
1704 bw->lamt = 0;
1705 timerclear(&bw->bwstart);
1706 timerclear(&bw->bwend);
1707 }
1708
1709 /* Callback from read/write loop to insert bandwidth-limiting delays */
1710 void
bandwidth_limit(struct bwlimit * bw,size_t read_len)1711 bandwidth_limit(struct bwlimit *bw, size_t read_len)
1712 {
1713 u_int64_t waitlen;
1714 struct timespec ts, rm;
1715
1716 bw->lamt += read_len;
1717 if (!timerisset(&bw->bwstart)) {
1718 monotime_tv(&bw->bwstart);
1719 return;
1720 }
1721 if (bw->lamt < bw->thresh)
1722 return;
1723
1724 monotime_tv(&bw->bwend);
1725 timersub(&bw->bwend, &bw->bwstart, &bw->bwend);
1726 if (!timerisset(&bw->bwend))
1727 return;
1728
1729 bw->lamt *= 8;
1730 waitlen = (double)1000000L * bw->lamt / bw->rate;
1731
1732 bw->bwstart.tv_sec = waitlen / 1000000L;
1733 bw->bwstart.tv_usec = waitlen % 1000000L;
1734
1735 if (timercmp(&bw->bwstart, &bw->bwend, >)) {
1736 timersub(&bw->bwstart, &bw->bwend, &bw->bwend);
1737
1738 /* Adjust the wait time */
1739 if (bw->bwend.tv_sec) {
1740 bw->thresh /= 2;
1741 if (bw->thresh < bw->buflen / 4)
1742 bw->thresh = bw->buflen / 4;
1743 } else if (bw->bwend.tv_usec < 10000) {
1744 bw->thresh *= 2;
1745 if (bw->thresh > bw->buflen * 8)
1746 bw->thresh = bw->buflen * 8;
1747 }
1748
1749 TIMEVAL_TO_TIMESPEC(&bw->bwend, &ts);
1750 while (nanosleep(&ts, &rm) == -1) {
1751 if (errno != EINTR)
1752 break;
1753 ts = rm;
1754 }
1755 }
1756
1757 bw->lamt = 0;
1758 monotime_tv(&bw->bwstart);
1759 }
1760
1761 /* Make a template filename for mk[sd]temp() */
1762 void
mktemp_proto(char * s,size_t len)1763 mktemp_proto(char *s, size_t len)
1764 {
1765 const char *tmpdir;
1766 int r;
1767
1768 if ((tmpdir = getenv("TMPDIR")) != NULL) {
1769 r = snprintf(s, len, "%s/ssh-XXXXXXXXXXXX", tmpdir);
1770 if (r > 0 && (size_t)r < len)
1771 return;
1772 }
1773 r = snprintf(s, len, "/tmp/ssh-XXXXXXXXXXXX");
1774 if (r < 0 || (size_t)r >= len)
1775 fatal_f("template string too short");
1776 }
1777
1778 static const struct {
1779 const char *name;
1780 int value;
1781 } ipqos[] = {
1782 { "none", INT_MAX }, /* can't use 0 here; that's CS0 */
1783 { "af11", IPTOS_DSCP_AF11 },
1784 { "af12", IPTOS_DSCP_AF12 },
1785 { "af13", IPTOS_DSCP_AF13 },
1786 { "af21", IPTOS_DSCP_AF21 },
1787 { "af22", IPTOS_DSCP_AF22 },
1788 { "af23", IPTOS_DSCP_AF23 },
1789 { "af31", IPTOS_DSCP_AF31 },
1790 { "af32", IPTOS_DSCP_AF32 },
1791 { "af33", IPTOS_DSCP_AF33 },
1792 { "af41", IPTOS_DSCP_AF41 },
1793 { "af42", IPTOS_DSCP_AF42 },
1794 { "af43", IPTOS_DSCP_AF43 },
1795 { "cs0", IPTOS_DSCP_CS0 },
1796 { "cs1", IPTOS_DSCP_CS1 },
1797 { "cs2", IPTOS_DSCP_CS2 },
1798 { "cs3", IPTOS_DSCP_CS3 },
1799 { "cs4", IPTOS_DSCP_CS4 },
1800 { "cs5", IPTOS_DSCP_CS5 },
1801 { "cs6", IPTOS_DSCP_CS6 },
1802 { "cs7", IPTOS_DSCP_CS7 },
1803 { "ef", IPTOS_DSCP_EF },
1804 { "le", IPTOS_DSCP_LE },
1805 { "lowdelay", IPTOS_LOWDELAY },
1806 { "throughput", IPTOS_THROUGHPUT },
1807 { "reliability", IPTOS_RELIABILITY },
1808 { NULL, -1 }
1809 };
1810
1811 int
parse_ipqos(const char * cp)1812 parse_ipqos(const char *cp)
1813 {
1814 const char *errstr;
1815 u_int i;
1816 int val;
1817
1818 if (cp == NULL)
1819 return -1;
1820 for (i = 0; ipqos[i].name != NULL; i++) {
1821 if (strcasecmp(cp, ipqos[i].name) == 0)
1822 return ipqos[i].value;
1823 }
1824 /* Try parsing as an integer */
1825 val = (int)strtonum(cp, 0, 255, &errstr);
1826 if (errstr)
1827 return -1;
1828 return val;
1829 }
1830
1831 const char *
iptos2str(int iptos)1832 iptos2str(int iptos)
1833 {
1834 int i;
1835 static char iptos_str[sizeof "0xff"];
1836
1837 for (i = 0; ipqos[i].name != NULL; i++) {
1838 if (ipqos[i].value == iptos)
1839 return ipqos[i].name;
1840 }
1841 snprintf(iptos_str, sizeof iptos_str, "0x%02x", iptos);
1842 return iptos_str;
1843 }
1844
1845 void
lowercase(char * s)1846 lowercase(char *s)
1847 {
1848 for (; *s; s++)
1849 *s = tolower((u_char)*s);
1850 }
1851
1852 int
unix_listener(const char * path,int backlog,int unlink_first)1853 unix_listener(const char *path, int backlog, int unlink_first)
1854 {
1855 struct sockaddr_un sunaddr;
1856 int saved_errno, sock;
1857
1858 memset(&sunaddr, 0, sizeof(sunaddr));
1859 sunaddr.sun_family = AF_UNIX;
1860 if (strlcpy(sunaddr.sun_path, path,
1861 sizeof(sunaddr.sun_path)) >= sizeof(sunaddr.sun_path)) {
1862 error_f("path \"%s\" too long for Unix domain socket", path);
1863 errno = ENAMETOOLONG;
1864 return -1;
1865 }
1866
1867 sock = socket(PF_UNIX, SOCK_STREAM, 0);
1868 if (sock == -1) {
1869 saved_errno = errno;
1870 error_f("socket: %.100s", strerror(errno));
1871 errno = saved_errno;
1872 return -1;
1873 }
1874 if (unlink_first == 1) {
1875 if (unlink(path) != 0 && errno != ENOENT)
1876 error("unlink(%s): %.100s", path, strerror(errno));
1877 }
1878 if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
1879 saved_errno = errno;
1880 error_f("cannot bind to path %s: %s", path, strerror(errno));
1881 close(sock);
1882 errno = saved_errno;
1883 return -1;
1884 }
1885 if (listen(sock, backlog) == -1) {
1886 saved_errno = errno;
1887 error_f("cannot listen on path %s: %s", path, strerror(errno));
1888 close(sock);
1889 unlink(path);
1890 errno = saved_errno;
1891 return -1;
1892 }
1893 return sock;
1894 }
1895
1896 /*
1897 * Compares two strings that maybe be NULL. Returns non-zero if strings
1898 * are both NULL or are identical, returns zero otherwise.
1899 */
1900 static int
strcmp_maybe_null(const char * a,const char * b)1901 strcmp_maybe_null(const char *a, const char *b)
1902 {
1903 if ((a == NULL && b != NULL) || (a != NULL && b == NULL))
1904 return 0;
1905 if (a != NULL && strcmp(a, b) != 0)
1906 return 0;
1907 return 1;
1908 }
1909
1910 /*
1911 * Compare two forwards, returning non-zero if they are identical or
1912 * zero otherwise.
1913 */
1914 int
forward_equals(const struct Forward * a,const struct Forward * b)1915 forward_equals(const struct Forward *a, const struct Forward *b)
1916 {
1917 if (strcmp_maybe_null(a->listen_host, b->listen_host) == 0)
1918 return 0;
1919 if (a->listen_port != b->listen_port)
1920 return 0;
1921 if (strcmp_maybe_null(a->listen_path, b->listen_path) == 0)
1922 return 0;
1923 if (strcmp_maybe_null(a->connect_host, b->connect_host) == 0)
1924 return 0;
1925 if (a->connect_port != b->connect_port)
1926 return 0;
1927 if (strcmp_maybe_null(a->connect_path, b->connect_path) == 0)
1928 return 0;
1929 /* allocated_port and handle are not checked */
1930 return 1;
1931 }
1932
1933 /* returns port number, FWD_PERMIT_ANY_PORT or -1 on error */
1934 int
permitopen_port(const char * p)1935 permitopen_port(const char *p)
1936 {
1937 int port;
1938
1939 if (strcmp(p, "*") == 0)
1940 return FWD_PERMIT_ANY_PORT;
1941 if ((port = a2port(p)) > 0)
1942 return port;
1943 return -1;
1944 }
1945
1946 /* returns 1 if process is already daemonized, 0 otherwise */
1947 int
daemonized(void)1948 daemonized(void)
1949 {
1950 int fd;
1951
1952 if ((fd = open(_PATH_TTY, O_RDONLY | O_NOCTTY)) >= 0) {
1953 close(fd);
1954 return 0; /* have controlling terminal */
1955 }
1956 if (getppid() != 1)
1957 return 0; /* parent is not init */
1958 if (getsid(0) != getpid())
1959 return 0; /* not session leader */
1960 debug3("already daemonized");
1961 return 1;
1962 }
1963
1964 /*
1965 * Splits 's' into an argument vector. Handles quoted string and basic
1966 * escape characters (\\, \", \'). Caller must free the argument vector
1967 * and its members.
1968 */
1969 int
argv_split(const char * s,int * argcp,char *** argvp,int terminate_on_comment)1970 argv_split(const char *s, int *argcp, char ***argvp, int terminate_on_comment)
1971 {
1972 int r = SSH_ERR_INTERNAL_ERROR;
1973 int argc = 0, quote, i, j;
1974 char *arg, **argv = xcalloc(1, sizeof(*argv));
1975
1976 *argvp = NULL;
1977 *argcp = 0;
1978
1979 for (i = 0; s[i] != '\0'; i++) {
1980 /* Skip leading whitespace */
1981 if (s[i] == ' ' || s[i] == '\t')
1982 continue;
1983 if (terminate_on_comment && s[i] == '#')
1984 break;
1985 /* Start of a token */
1986 quote = 0;
1987
1988 argv = xreallocarray(argv, (argc + 2), sizeof(*argv));
1989 arg = argv[argc++] = xcalloc(1, strlen(s + i) + 1);
1990 argv[argc] = NULL;
1991
1992 /* Copy the token in, removing escapes */
1993 for (j = 0; s[i] != '\0'; i++) {
1994 if (s[i] == '\\') {
1995 if (s[i + 1] == '\'' ||
1996 s[i + 1] == '\"' ||
1997 s[i + 1] == '\\' ||
1998 (quote == 0 && s[i + 1] == ' ')) {
1999 i++; /* Skip '\' */
2000 arg[j++] = s[i];
2001 } else {
2002 /* Unrecognised escape */
2003 arg[j++] = s[i];
2004 }
2005 } else if (quote == 0 && (s[i] == ' ' || s[i] == '\t'))
2006 break; /* done */
2007 else if (quote == 0 && (s[i] == '\"' || s[i] == '\''))
2008 quote = s[i]; /* quote start */
2009 else if (quote != 0 && s[i] == quote)
2010 quote = 0; /* quote end */
2011 else
2012 arg[j++] = s[i];
2013 }
2014 if (s[i] == '\0') {
2015 if (quote != 0) {
2016 /* Ran out of string looking for close quote */
2017 r = SSH_ERR_INVALID_FORMAT;
2018 goto out;
2019 }
2020 break;
2021 }
2022 }
2023 /* Success */
2024 *argcp = argc;
2025 *argvp = argv;
2026 argc = 0;
2027 argv = NULL;
2028 r = 0;
2029 out:
2030 if (argc != 0 && argv != NULL) {
2031 for (i = 0; i < argc; i++)
2032 free(argv[i]);
2033 free(argv);
2034 }
2035 return r;
2036 }
2037
2038 /*
2039 * Reassemble an argument vector into a string, quoting and escaping as
2040 * necessary. Caller must free returned string.
2041 */
2042 char *
argv_assemble(int argc,char ** argv)2043 argv_assemble(int argc, char **argv)
2044 {
2045 int i, j, ws, r;
2046 char c, *ret;
2047 struct sshbuf *buf, *arg;
2048
2049 if ((buf = sshbuf_new()) == NULL || (arg = sshbuf_new()) == NULL)
2050 fatal_f("sshbuf_new failed");
2051
2052 for (i = 0; i < argc; i++) {
2053 ws = 0;
2054 sshbuf_reset(arg);
2055 for (j = 0; argv[i][j] != '\0'; j++) {
2056 r = 0;
2057 c = argv[i][j];
2058 switch (c) {
2059 case ' ':
2060 case '\t':
2061 ws = 1;
2062 r = sshbuf_put_u8(arg, c);
2063 break;
2064 case '\\':
2065 case '\'':
2066 case '"':
2067 if ((r = sshbuf_put_u8(arg, '\\')) != 0)
2068 break;
2069 /* FALLTHROUGH */
2070 default:
2071 r = sshbuf_put_u8(arg, c);
2072 break;
2073 }
2074 if (r != 0)
2075 fatal_fr(r, "sshbuf_put_u8");
2076 }
2077 if ((i != 0 && (r = sshbuf_put_u8(buf, ' ')) != 0) ||
2078 (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0) ||
2079 (r = sshbuf_putb(buf, arg)) != 0 ||
2080 (ws != 0 && (r = sshbuf_put_u8(buf, '"')) != 0))
2081 fatal_fr(r, "assemble");
2082 }
2083 if ((ret = malloc(sshbuf_len(buf) + 1)) == NULL)
2084 fatal_f("malloc failed");
2085 memcpy(ret, sshbuf_ptr(buf), sshbuf_len(buf));
2086 ret[sshbuf_len(buf)] = '\0';
2087 sshbuf_free(buf);
2088 sshbuf_free(arg);
2089 return ret;
2090 }
2091
2092 char *
argv_next(int * argcp,char *** argvp)2093 argv_next(int *argcp, char ***argvp)
2094 {
2095 char *ret = (*argvp)[0];
2096
2097 if (*argcp > 0 && ret != NULL) {
2098 (*argcp)--;
2099 (*argvp)++;
2100 }
2101 return ret;
2102 }
2103
2104 void
argv_consume(int * argcp)2105 argv_consume(int *argcp)
2106 {
2107 *argcp = 0;
2108 }
2109
2110 void
argv_free(char ** av,int ac)2111 argv_free(char **av, int ac)
2112 {
2113 int i;
2114
2115 if (av == NULL)
2116 return;
2117 for (i = 0; i < ac; i++)
2118 free(av[i]);
2119 free(av);
2120 }
2121
2122 /* Returns 0 if pid exited cleanly, non-zero otherwise */
2123 int
exited_cleanly(pid_t pid,const char * tag,const char * cmd,int quiet)2124 exited_cleanly(pid_t pid, const char *tag, const char *cmd, int quiet)
2125 {
2126 int status;
2127
2128 while (waitpid(pid, &status, 0) == -1) {
2129 if (errno != EINTR) {
2130 error("%s waitpid: %s", tag, strerror(errno));
2131 return -1;
2132 }
2133 }
2134 if (WIFSIGNALED(status)) {
2135 error("%s %s exited on signal %d", tag, cmd, WTERMSIG(status));
2136 return -1;
2137 } else if (WEXITSTATUS(status) != 0) {
2138 do_log2(quiet ? SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_INFO,
2139 "%s %s failed, status %d", tag, cmd, WEXITSTATUS(status));
2140 return -1;
2141 }
2142 return 0;
2143 }
2144
2145 /*
2146 * Check a given path for security. This is defined as all components
2147 * of the path to the file must be owned by either the owner of
2148 * of the file or root and no directories must be group or world writable.
2149 *
2150 * XXX Should any specific check be done for sym links ?
2151 *
2152 * Takes a file name, its stat information (preferably from fstat() to
2153 * avoid races), the uid of the expected owner, their home directory and an
2154 * error buffer plus max size as arguments.
2155 *
2156 * Returns 0 on success and -1 on failure
2157 */
2158 int
safe_path(const char * name,struct stat * stp,const char * pw_dir,uid_t uid,char * err,size_t errlen)2159 safe_path(const char *name, struct stat *stp, const char *pw_dir,
2160 uid_t uid, char *err, size_t errlen)
2161 {
2162 char buf[PATH_MAX], homedir[PATH_MAX];
2163 char *cp;
2164 int comparehome = 0;
2165 struct stat st;
2166
2167 if (realpath(name, buf) == NULL) {
2168 snprintf(err, errlen, "realpath %s failed: %s", name,
2169 strerror(errno));
2170 return -1;
2171 }
2172 if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
2173 comparehome = 1;
2174
2175 if (!S_ISREG(stp->st_mode)) {
2176 snprintf(err, errlen, "%s is not a regular file", buf);
2177 return -1;
2178 }
2179 if ((stp->st_uid != 0 && stp->st_uid != uid) ||
2180 (stp->st_mode & 022) != 0) {
2181 snprintf(err, errlen, "bad ownership or modes for file %s",
2182 buf);
2183 return -1;
2184 }
2185
2186 /* for each component of the canonical path, walking upwards */
2187 for (;;) {
2188 if ((cp = dirname(buf)) == NULL) {
2189 snprintf(err, errlen, "dirname() failed");
2190 return -1;
2191 }
2192 strlcpy(buf, cp, sizeof(buf));
2193
2194 if (stat(buf, &st) == -1 ||
2195 (st.st_uid != 0 && st.st_uid != uid) ||
2196 (st.st_mode & 022) != 0) {
2197 snprintf(err, errlen,
2198 "bad ownership or modes for directory %s", buf);
2199 return -1;
2200 }
2201
2202 /* If are past the homedir then we can stop */
2203 if (comparehome && strcmp(homedir, buf) == 0)
2204 break;
2205
2206 /*
2207 * dirname should always complete with a "/" path,
2208 * but we can be paranoid and check for "." too
2209 */
2210 if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
2211 break;
2212 }
2213 return 0;
2214 }
2215
2216 /*
2217 * Version of safe_path() that accepts an open file descriptor to
2218 * avoid races.
2219 *
2220 * Returns 0 on success and -1 on failure
2221 */
2222 int
safe_path_fd(int fd,const char * file,struct passwd * pw,char * err,size_t errlen)2223 safe_path_fd(int fd, const char *file, struct passwd *pw,
2224 char *err, size_t errlen)
2225 {
2226 struct stat st;
2227
2228 /* check the open file to avoid races */
2229 if (fstat(fd, &st) == -1) {
2230 snprintf(err, errlen, "cannot stat file %s: %s",
2231 file, strerror(errno));
2232 return -1;
2233 }
2234 return safe_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
2235 }
2236
2237 /*
2238 * Sets the value of the given variable in the environment. If the variable
2239 * already exists, its value is overridden.
2240 */
2241 void
child_set_env(char *** envp,u_int * envsizep,const char * name,const char * value)2242 child_set_env(char ***envp, u_int *envsizep, const char *name,
2243 const char *value)
2244 {
2245 char **env;
2246 u_int envsize;
2247 u_int i, namelen;
2248
2249 if (strchr(name, '=') != NULL) {
2250 error("Invalid environment variable \"%.100s\"", name);
2251 return;
2252 }
2253
2254 /*
2255 * Find the slot where the value should be stored. If the variable
2256 * already exists, we reuse the slot; otherwise we append a new slot
2257 * at the end of the array, expanding if necessary.
2258 */
2259 env = *envp;
2260 namelen = strlen(name);
2261 for (i = 0; env[i]; i++)
2262 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
2263 break;
2264 if (env[i]) {
2265 /* Reuse the slot. */
2266 free(env[i]);
2267 } else {
2268 /* New variable. Expand if necessary. */
2269 envsize = *envsizep;
2270 if (i >= envsize - 1) {
2271 if (envsize >= 1000)
2272 fatal("child_set_env: too many env vars");
2273 envsize += 50;
2274 env = (*envp) = xreallocarray(env, envsize, sizeof(char *));
2275 *envsizep = envsize;
2276 }
2277 /* Need to set the NULL pointer at end of array beyond the new slot. */
2278 env[i + 1] = NULL;
2279 }
2280
2281 /* Allocate space and format the variable in the appropriate slot. */
2282 /* XXX xasprintf */
2283 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
2284 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
2285 }
2286
2287 /*
2288 * Check and optionally lowercase a domain name, also removes trailing '.'
2289 * Returns 1 on success and 0 on failure, storing an error message in errstr.
2290 */
2291 int
valid_domain(char * name,int makelower,const char ** errstr)2292 valid_domain(char *name, int makelower, const char **errstr)
2293 {
2294 size_t i, l = strlen(name);
2295 u_char c, last = '\0';
2296 static char errbuf[256];
2297
2298 if (l == 0) {
2299 strlcpy(errbuf, "empty domain name", sizeof(errbuf));
2300 goto bad;
2301 }
2302 if (!isalpha((u_char)name[0]) && !isdigit((u_char)name[0]) &&
2303 name[0] != '_' /* technically invalid, but common */) {
2304 snprintf(errbuf, sizeof(errbuf), "domain name \"%.100s\" "
2305 "starts with invalid character", name);
2306 goto bad;
2307 }
2308 for (i = 0; i < l; i++) {
2309 c = tolower((u_char)name[i]);
2310 if (makelower)
2311 name[i] = (char)c;
2312 if (last == '.' && c == '.') {
2313 snprintf(errbuf, sizeof(errbuf), "domain name "
2314 "\"%.100s\" contains consecutive separators", name);
2315 goto bad;
2316 }
2317 if (c != '.' && c != '-' && !isalnum(c) &&
2318 c != '_') /* technically invalid, but common */ {
2319 snprintf(errbuf, sizeof(errbuf), "domain name "
2320 "\"%.100s\" contains invalid characters", name);
2321 goto bad;
2322 }
2323 last = c;
2324 }
2325 if (name[l - 1] == '.')
2326 name[l - 1] = '\0';
2327 if (errstr != NULL)
2328 *errstr = NULL;
2329 return 1;
2330 bad:
2331 if (errstr != NULL)
2332 *errstr = errbuf;
2333 return 0;
2334 }
2335
2336 /*
2337 * Verify that a environment variable name (not including initial '$') is
2338 * valid; consisting of one or more alphanumeric or underscore characters only.
2339 * Returns 1 on valid, 0 otherwise.
2340 */
2341 int
valid_env_name(const char * name)2342 valid_env_name(const char *name)
2343 {
2344 const char *cp;
2345
2346 if (name[0] == '\0')
2347 return 0;
2348 for (cp = name; *cp != '\0'; cp++) {
2349 if (!isalnum((u_char)*cp) && *cp != '_')
2350 return 0;
2351 }
2352 return 1;
2353 }
2354
2355 const char *
atoi_err(const char * nptr,int * val)2356 atoi_err(const char *nptr, int *val)
2357 {
2358 const char *errstr = NULL;
2359
2360 if (nptr == NULL || *nptr == '\0')
2361 return "missing";
2362 *val = strtonum(nptr, 0, INT_MAX, &errstr);
2363 return errstr;
2364 }
2365
2366 int
parse_absolute_time(const char * s,uint64_t * tp)2367 parse_absolute_time(const char *s, uint64_t *tp)
2368 {
2369 struct tm tm;
2370 time_t tt;
2371 char buf[32], *fmt;
2372 const char *cp;
2373 size_t l;
2374 int is_utc = 0;
2375
2376 *tp = 0;
2377
2378 l = strlen(s);
2379 if (l > 1 && strcasecmp(s + l - 1, "Z") == 0) {
2380 is_utc = 1;
2381 l--;
2382 } else if (l > 3 && strcasecmp(s + l - 3, "UTC") == 0) {
2383 is_utc = 1;
2384 l -= 3;
2385 }
2386 /*
2387 * POSIX strptime says "The application shall ensure that there
2388 * is white-space or other non-alphanumeric characters between
2389 * any two conversion specifications" so arrange things this way.
2390 */
2391 switch (l) {
2392 case 8: /* YYYYMMDD */
2393 fmt = "%Y-%m-%d";
2394 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
2395 break;
2396 case 12: /* YYYYMMDDHHMM */
2397 fmt = "%Y-%m-%dT%H:%M";
2398 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s",
2399 s, s + 4, s + 6, s + 8, s + 10);
2400 break;
2401 case 14: /* YYYYMMDDHHMMSS */
2402 fmt = "%Y-%m-%dT%H:%M:%S";
2403 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
2404 s, s + 4, s + 6, s + 8, s + 10, s + 12);
2405 break;
2406 default:
2407 return SSH_ERR_INVALID_FORMAT;
2408 }
2409
2410 memset(&tm, 0, sizeof(tm));
2411 if ((cp = strptime(buf, fmt, &tm)) == NULL || *cp != '\0')
2412 return SSH_ERR_INVALID_FORMAT;
2413 if (is_utc) {
2414 if ((tt = timegm(&tm)) < 0)
2415 return SSH_ERR_INVALID_FORMAT;
2416 } else {
2417 if ((tt = mktime(&tm)) < 0)
2418 return SSH_ERR_INVALID_FORMAT;
2419 }
2420 /* success */
2421 *tp = (uint64_t)tt;
2422 return 0;
2423 }
2424
2425 void
format_absolute_time(uint64_t t,char * buf,size_t len)2426 format_absolute_time(uint64_t t, char *buf, size_t len)
2427 {
2428 time_t tt = t > SSH_TIME_T_MAX ? SSH_TIME_T_MAX : t;
2429 struct tm tm;
2430
2431 localtime_r(&tt, &tm);
2432 strftime(buf, len, "%Y-%m-%dT%H:%M:%S", &tm);
2433 }
2434
2435 /*
2436 * Parse a "pattern=interval" clause (e.g. a ChannelTimeout).
2437 * Returns 0 on success or non-zero on failure.
2438 * Caller must free *typep.
2439 */
2440 int
parse_pattern_interval(const char * s,char ** typep,int * secsp)2441 parse_pattern_interval(const char *s, char **typep, int *secsp)
2442 {
2443 char *cp, *sdup;
2444 int secs;
2445
2446 if (typep != NULL)
2447 *typep = NULL;
2448 if (secsp != NULL)
2449 *secsp = 0;
2450 if (s == NULL)
2451 return -1;
2452 sdup = xstrdup(s);
2453
2454 if ((cp = strchr(sdup, '=')) == NULL || cp == sdup) {
2455 free(sdup);
2456 return -1;
2457 }
2458 *cp++ = '\0';
2459 if ((secs = convtime(cp)) < 0) {
2460 free(sdup);
2461 return -1;
2462 }
2463 /* success */
2464 if (typep != NULL)
2465 *typep = xstrdup(sdup);
2466 if (secsp != NULL)
2467 *secsp = secs;
2468 free(sdup);
2469 return 0;
2470 }
2471
2472 /* check if path is absolute */
2473 int
path_absolute(const char * path)2474 path_absolute(const char *path)
2475 {
2476 return (*path == '/') ? 1 : 0;
2477 }
2478
2479 void
skip_space(char ** cpp)2480 skip_space(char **cpp)
2481 {
2482 char *cp;
2483
2484 for (cp = *cpp; *cp == ' ' || *cp == '\t'; cp++)
2485 ;
2486 *cpp = cp;
2487 }
2488
2489 /* authorized_key-style options parsing helpers */
2490
2491 /*
2492 * Match flag 'opt' in *optsp, and if allow_negate is set then also match
2493 * 'no-opt'. Returns -1 if option not matched, 1 if option matches or 0
2494 * if negated option matches.
2495 * If the option or negated option matches, then *optsp is updated to
2496 * point to the first character after the option.
2497 */
2498 int
opt_flag(const char * opt,int allow_negate,const char ** optsp)2499 opt_flag(const char *opt, int allow_negate, const char **optsp)
2500 {
2501 size_t opt_len = strlen(opt);
2502 const char *opts = *optsp;
2503 int negate = 0;
2504
2505 if (allow_negate && strncasecmp(opts, "no-", 3) == 0) {
2506 opts += 3;
2507 negate = 1;
2508 }
2509 if (strncasecmp(opts, opt, opt_len) == 0) {
2510 *optsp = opts + opt_len;
2511 return negate ? 0 : 1;
2512 }
2513 return -1;
2514 }
2515
2516 char *
opt_dequote(const char ** sp,const char ** errstrp)2517 opt_dequote(const char **sp, const char **errstrp)
2518 {
2519 const char *s = *sp;
2520 char *ret;
2521 size_t i;
2522
2523 *errstrp = NULL;
2524 if (*s != '"') {
2525 *errstrp = "missing start quote";
2526 return NULL;
2527 }
2528 s++;
2529 if ((ret = malloc(strlen((s)) + 1)) == NULL) {
2530 *errstrp = "memory allocation failed";
2531 return NULL;
2532 }
2533 for (i = 0; *s != '\0' && *s != '"';) {
2534 if (s[0] == '\\' && s[1] == '"')
2535 s++;
2536 ret[i++] = *s++;
2537 }
2538 if (*s == '\0') {
2539 *errstrp = "missing end quote";
2540 free(ret);
2541 return NULL;
2542 }
2543 ret[i] = '\0';
2544 s++;
2545 *sp = s;
2546 return ret;
2547 }
2548
2549 int
opt_match(const char ** opts,const char * term)2550 opt_match(const char **opts, const char *term)
2551 {
2552 if (strncasecmp((*opts), term, strlen(term)) == 0 &&
2553 (*opts)[strlen(term)] == '=') {
2554 *opts += strlen(term) + 1;
2555 return 1;
2556 }
2557 return 0;
2558 }
2559
2560 void
opt_array_append2(const char * file,const int line,const char * directive,char *** array,int ** iarray,u_int * lp,const char * s,int i)2561 opt_array_append2(const char *file, const int line, const char *directive,
2562 char ***array, int **iarray, u_int *lp, const char *s, int i)
2563 {
2564
2565 if (*lp >= INT_MAX)
2566 fatal("%s line %d: Too many %s entries", file, line, directive);
2567
2568 if (iarray != NULL) {
2569 *iarray = xrecallocarray(*iarray, *lp, *lp + 1,
2570 sizeof(**iarray));
2571 (*iarray)[*lp] = i;
2572 }
2573
2574 *array = xrecallocarray(*array, *lp, *lp + 1, sizeof(**array));
2575 (*array)[*lp] = xstrdup(s);
2576 (*lp)++;
2577 }
2578
2579 void
opt_array_append(const char * file,const int line,const char * directive,char *** array,u_int * lp,const char * s)2580 opt_array_append(const char *file, const int line, const char *directive,
2581 char ***array, u_int *lp, const char *s)
2582 {
2583 opt_array_append2(file, line, directive, array, NULL, lp, s, 0);
2584 }
2585
2586 void
opt_array_free2(char ** array,int ** iarray,u_int l)2587 opt_array_free2(char **array, int **iarray, u_int l)
2588 {
2589 u_int i;
2590
2591 if (array == NULL || l == 0)
2592 return;
2593 for (i = 0; i < l; i++)
2594 free(array[i]);
2595 free(array);
2596 free(iarray);
2597 }
2598
2599 sshsig_t
ssh_signal(int signum,sshsig_t handler)2600 ssh_signal(int signum, sshsig_t handler)
2601 {
2602 struct sigaction sa, osa;
2603
2604 /* mask all other signals while in handler */
2605 memset(&sa, 0, sizeof(sa));
2606 sa.sa_handler = handler;
2607 sigfillset(&sa.sa_mask);
2608 if (signum != SIGALRM)
2609 sa.sa_flags = SA_RESTART;
2610 if (sigaction(signum, &sa, &osa) == -1) {
2611 debug3("sigaction(%s): %s", strsignal(signum), strerror(errno));
2612 return SIG_ERR;
2613 }
2614 return osa.sa_handler;
2615 }
2616
2617 int
stdfd_devnull(int do_stdin,int do_stdout,int do_stderr)2618 stdfd_devnull(int do_stdin, int do_stdout, int do_stderr)
2619 {
2620 int devnull, ret = 0;
2621
2622 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
2623 error_f("open %s: %s", _PATH_DEVNULL,
2624 strerror(errno));
2625 return -1;
2626 }
2627 if ((do_stdin && dup2(devnull, STDIN_FILENO) == -1) ||
2628 (do_stdout && dup2(devnull, STDOUT_FILENO) == -1) ||
2629 (do_stderr && dup2(devnull, STDERR_FILENO) == -1)) {
2630 error_f("dup2: %s", strerror(errno));
2631 ret = -1;
2632 }
2633 if (devnull > STDERR_FILENO)
2634 close(devnull);
2635 return ret;
2636 }
2637
2638 /*
2639 * Runs command in a subprocess with a minimal environment.
2640 * Returns pid on success, 0 on failure.
2641 * The child stdout and stderr maybe captured, left attached or sent to
2642 * /dev/null depending on the contents of flags.
2643 * "tag" is prepended to log messages.
2644 * NB. "command" is only used for logging; the actual command executed is
2645 * av[0].
2646 */
2647 pid_t
subprocess(const char * tag,const char * command,int ac,char ** av,FILE ** child,u_int flags,struct passwd * pw,privdrop_fn * drop_privs,privrestore_fn * restore_privs)2648 subprocess(const char *tag, const char *command,
2649 int ac, char **av, FILE **child, u_int flags,
2650 struct passwd *pw, privdrop_fn *drop_privs, privrestore_fn *restore_privs)
2651 {
2652 FILE *f = NULL;
2653 struct stat st;
2654 int fd, devnull, p[2], i;
2655 pid_t pid;
2656 char *cp, errmsg[512];
2657 u_int nenv = 0;
2658 char **env = NULL;
2659
2660 /* If dropping privs, then must specify user and restore function */
2661 if (drop_privs != NULL && (pw == NULL || restore_privs == NULL)) {
2662 error("%s: inconsistent arguments", tag); /* XXX fatal? */
2663 return 0;
2664 }
2665 if (pw == NULL && (pw = getpwuid(getuid())) == NULL) {
2666 error("%s: no user for current uid", tag);
2667 return 0;
2668 }
2669 if (child != NULL)
2670 *child = NULL;
2671
2672 debug3_f("%s command \"%s\" running as %s (flags 0x%x)",
2673 tag, command, pw->pw_name, flags);
2674
2675 /* Check consistency */
2676 if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
2677 (flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0) {
2678 error_f("inconsistent flags");
2679 return 0;
2680 }
2681 if (((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0) != (child == NULL)) {
2682 error_f("inconsistent flags/output");
2683 return 0;
2684 }
2685
2686 /*
2687 * If executing an explicit binary, then verify the it exists
2688 * and appears safe-ish to execute
2689 */
2690 if (!path_absolute(av[0])) {
2691 error("%s path is not absolute", tag);
2692 return 0;
2693 }
2694 if (drop_privs != NULL)
2695 drop_privs(pw);
2696 if (stat(av[0], &st) == -1) {
2697 error("Could not stat %s \"%s\": %s", tag,
2698 av[0], strerror(errno));
2699 goto restore_return;
2700 }
2701 if ((flags & SSH_SUBPROCESS_UNSAFE_PATH) == 0 &&
2702 safe_path(av[0], &st, NULL, 0, errmsg, sizeof(errmsg)) != 0) {
2703 error("Unsafe %s \"%s\": %s", tag, av[0], errmsg);
2704 goto restore_return;
2705 }
2706 /* Prepare to keep the child's stdout if requested */
2707 if (pipe(p) == -1) {
2708 error("%s: pipe: %s", tag, strerror(errno));
2709 restore_return:
2710 if (restore_privs != NULL)
2711 restore_privs();
2712 return 0;
2713 }
2714 if (restore_privs != NULL)
2715 restore_privs();
2716
2717 switch ((pid = fork())) {
2718 case -1: /* error */
2719 error("%s: fork: %s", tag, strerror(errno));
2720 close(p[0]);
2721 close(p[1]);
2722 return 0;
2723 case 0: /* child */
2724 /* Prepare a minimal environment for the child. */
2725 if ((flags & SSH_SUBPROCESS_PRESERVE_ENV) == 0) {
2726 nenv = 5;
2727 env = xcalloc(sizeof(*env), nenv);
2728 child_set_env(&env, &nenv, "PATH", _PATH_STDPATH);
2729 child_set_env(&env, &nenv, "USER", pw->pw_name);
2730 child_set_env(&env, &nenv, "LOGNAME", pw->pw_name);
2731 child_set_env(&env, &nenv, "HOME", pw->pw_dir);
2732 if ((cp = getenv("LANG")) != NULL)
2733 child_set_env(&env, &nenv, "LANG", cp);
2734 }
2735
2736 for (i = 1; i < NSIG; i++)
2737 ssh_signal(i, SIG_DFL);
2738
2739 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
2740 error("%s: open %s: %s", tag, _PATH_DEVNULL,
2741 strerror(errno));
2742 _exit(1);
2743 }
2744 if (dup2(devnull, STDIN_FILENO) == -1) {
2745 error("%s: dup2: %s", tag, strerror(errno));
2746 _exit(1);
2747 }
2748
2749 /* Set up stdout as requested; leave stderr in place for now. */
2750 fd = -1;
2751 if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0)
2752 fd = p[1];
2753 else if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0)
2754 fd = devnull;
2755 if (fd != -1 && dup2(fd, STDOUT_FILENO) == -1) {
2756 error("%s: dup2: %s", tag, strerror(errno));
2757 _exit(1);
2758 }
2759 closefrom(STDERR_FILENO + 1);
2760
2761 if (geteuid() == 0 &&
2762 initgroups(pw->pw_name, pw->pw_gid) == -1) {
2763 error("%s: initgroups(%s, %u): %s", tag,
2764 pw->pw_name, (u_int)pw->pw_gid, strerror(errno));
2765 _exit(1);
2766 }
2767 if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1) {
2768 error("%s: setresgid %u: %s", tag, (u_int)pw->pw_gid,
2769 strerror(errno));
2770 _exit(1);
2771 }
2772 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1) {
2773 error("%s: setresuid %u: %s", tag, (u_int)pw->pw_uid,
2774 strerror(errno));
2775 _exit(1);
2776 }
2777 /* stdin is pointed to /dev/null at this point */
2778 if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
2779 dup2(STDIN_FILENO, STDERR_FILENO) == -1) {
2780 error("%s: dup2: %s", tag, strerror(errno));
2781 _exit(1);
2782 }
2783 if (env != NULL)
2784 execve(av[0], av, env);
2785 else
2786 execv(av[0], av);
2787 error("%s %s \"%s\": %s", tag, env == NULL ? "execv" : "execve",
2788 command, strerror(errno));
2789 _exit(127);
2790 default: /* parent */
2791 break;
2792 }
2793
2794 close(p[1]);
2795 if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0)
2796 close(p[0]);
2797 else if ((f = fdopen(p[0], "r")) == NULL) {
2798 error("%s: fdopen: %s", tag, strerror(errno));
2799 close(p[0]);
2800 /* Don't leave zombie child */
2801 kill(pid, SIGTERM);
2802 while (waitpid(pid, NULL, 0) == -1 && errno == EINTR)
2803 ;
2804 return 0;
2805 }
2806 /* Success */
2807 debug3_f("%s pid %ld", tag, (long)pid);
2808 if (child != NULL)
2809 *child = f;
2810 return pid;
2811 }
2812
2813 const char *
lookup_env_in_list(const char * env,char * const * envs,size_t nenvs)2814 lookup_env_in_list(const char *env, char * const *envs, size_t nenvs)
2815 {
2816 size_t i, envlen;
2817
2818 envlen = strlen(env);
2819 for (i = 0; i < nenvs; i++) {
2820 if (strncmp(envs[i], env, envlen) == 0 &&
2821 envs[i][envlen] == '=') {
2822 return envs[i] + envlen + 1;
2823 }
2824 }
2825 return NULL;
2826 }
2827
2828 const char *
lookup_setenv_in_list(const char * env,char * const * envs,size_t nenvs)2829 lookup_setenv_in_list(const char *env, char * const *envs, size_t nenvs)
2830 {
2831 char *name, *cp;
2832 const char *ret;
2833
2834 name = xstrdup(env);
2835 if ((cp = strchr(name, '=')) == NULL) {
2836 free(name);
2837 return NULL; /* not env=val */
2838 }
2839 *cp = '\0';
2840 ret = lookup_env_in_list(name, envs, nenvs);
2841 free(name);
2842 return ret;
2843 }
2844
2845 /*
2846 * Helpers for managing poll(2)/ppoll(2) timeouts
2847 * Will remember the earliest deadline and return it for use in poll/ppoll.
2848 */
2849
2850 /* Initialise a poll/ppoll timeout with an indefinite deadline */
2851 void
ptimeout_init(struct timespec * pt)2852 ptimeout_init(struct timespec *pt)
2853 {
2854 /*
2855 * Deliberately invalid for ppoll(2).
2856 * Will be converted to NULL in ptimeout_get_tspec() later.
2857 */
2858 pt->tv_sec = -1;
2859 pt->tv_nsec = 0;
2860 }
2861
2862 /* Specify a poll/ppoll deadline of at most 'sec' seconds */
2863 void
ptimeout_deadline_sec(struct timespec * pt,long sec)2864 ptimeout_deadline_sec(struct timespec *pt, long sec)
2865 {
2866 if (pt->tv_sec == -1 || pt->tv_sec >= sec) {
2867 pt->tv_sec = sec;
2868 pt->tv_nsec = 0;
2869 }
2870 }
2871
2872 /* Specify a poll/ppoll deadline of at most 'p' (timespec) */
2873 static void
ptimeout_deadline_tsp(struct timespec * pt,struct timespec * p)2874 ptimeout_deadline_tsp(struct timespec *pt, struct timespec *p)
2875 {
2876 if (pt->tv_sec == -1 || timespeccmp(pt, p, >=))
2877 *pt = *p;
2878 }
2879
2880 /* Specify a poll/ppoll deadline of at most 'ms' milliseconds */
2881 void
ptimeout_deadline_ms(struct timespec * pt,long ms)2882 ptimeout_deadline_ms(struct timespec *pt, long ms)
2883 {
2884 struct timespec p;
2885
2886 p.tv_sec = ms / 1000;
2887 p.tv_nsec = (ms % 1000) * 1000000;
2888 ptimeout_deadline_tsp(pt, &p);
2889 }
2890
2891 /* Specify a poll/ppoll deadline at wall clock monotime 'when' (timespec) */
2892 void
ptimeout_deadline_monotime_tsp(struct timespec * pt,struct timespec * when)2893 ptimeout_deadline_monotime_tsp(struct timespec *pt, struct timespec *when)
2894 {
2895 struct timespec now, t;
2896
2897 monotime_ts(&now);
2898
2899 if (timespeccmp(&now, when, >=)) {
2900 /* 'when' is now or in the past. Timeout ASAP */
2901 pt->tv_sec = 0;
2902 pt->tv_nsec = 0;
2903 } else {
2904 timespecsub(when, &now, &t);
2905 ptimeout_deadline_tsp(pt, &t);
2906 }
2907 }
2908
2909 /* Specify a poll/ppoll deadline at wall clock monotime 'when' */
2910 void
ptimeout_deadline_monotime(struct timespec * pt,time_t when)2911 ptimeout_deadline_monotime(struct timespec *pt, time_t when)
2912 {
2913 struct timespec t;
2914
2915 t.tv_sec = when;
2916 t.tv_nsec = 0;
2917 ptimeout_deadline_monotime_tsp(pt, &t);
2918 }
2919
2920 /* Get a poll(2) timeout value in milliseconds */
2921 int
ptimeout_get_ms(struct timespec * pt)2922 ptimeout_get_ms(struct timespec *pt)
2923 {
2924 if (pt->tv_sec == -1)
2925 return -1;
2926 if (pt->tv_sec >= (INT_MAX - (pt->tv_nsec / 1000000)) / 1000)
2927 return INT_MAX;
2928 return (pt->tv_sec * 1000) + (pt->tv_nsec / 1000000);
2929 }
2930
2931 /* Get a ppoll(2) timeout value as a timespec pointer */
2932 struct timespec *
ptimeout_get_tsp(struct timespec * pt)2933 ptimeout_get_tsp(struct timespec *pt)
2934 {
2935 return pt->tv_sec == -1 ? NULL : pt;
2936 }
2937
2938 /* Returns non-zero if a timeout has been set (i.e. is not indefinite) */
2939 int
ptimeout_isset(struct timespec * pt)2940 ptimeout_isset(struct timespec *pt)
2941 {
2942 return pt->tv_sec != -1;
2943 }
2944
2945 /*
2946 * Returns zero if the library at 'path' contains symbol 's', nonzero
2947 * otherwise.
2948 */
2949 int
lib_contains_symbol(const char * path,const char * s)2950 lib_contains_symbol(const char *path, const char *s)
2951 {
2952 struct nlist nl[2];
2953 int ret = -1, r;
2954
2955 memset(nl, 0, sizeof(nl));
2956 nl[0].n_name = xstrdup(s);
2957 nl[1].n_name = NULL;
2958 if ((r = nlist(path, nl)) == -1) {
2959 error_f("nlist failed for %s", path);
2960 goto out;
2961 }
2962 if (r != 0 || nl[0].n_value == 0 || nl[0].n_type == 0) {
2963 error_f("library %s does not contain symbol %s", path, s);
2964 goto out;
2965 }
2966 /* success */
2967 ret = 0;
2968 out:
2969 free(nl[0].n_name);
2970 return ret;
2971 }
2972
2973 int
signal_is_crash(int sig)2974 signal_is_crash(int sig)
2975 {
2976 switch (sig) {
2977 case SIGSEGV:
2978 case SIGBUS:
2979 case SIGTRAP:
2980 case SIGSYS:
2981 case SIGFPE:
2982 case SIGILL:
2983 case SIGABRT:
2984 return 1;
2985 }
2986 return 0;
2987 }
2988