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