Coverage Report

Created: 2026-06-10 06:24

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