Coverage Report

Created: 2026-10-17 06:39

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