Coverage Report

Created: 2024-05-20 01:00

/src/openiked-portable/compat/strtonum.c
Line
Count
Source (jump to first uncovered line)
1
/*  $OpenBSD: strtonum.c,v 1.8 2015/09/13 08:31:48 guenther Exp $ */
2
3
/*
4
 * Copyright (c) 2004 Ted Unangst and Todd Miller
5
 * All rights reserved.
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
#include <errno.h>
21
#include <limits.h>
22
#include <stdlib.h>
23
24
0
#define INVALID   1
25
0
#define TOOSMALL  2
26
0
#define TOOLARGE  3
27
28
long long
29
strtonum(const char *numstr, long long minval, long long maxval,
30
    const char **errstrp)
31
0
{
32
0
  long long ll = 0;
33
0
  int error = 0;
34
0
  char *ep;
35
0
  struct errval {
36
0
    const char *errstr;
37
0
    int err;
38
0
  } ev[4] = {
39
0
    { NULL,   0 },
40
0
    { "invalid",  EINVAL },
41
0
    { "too small",  ERANGE },
42
0
    { "too large",  ERANGE },
43
0
  };
44
45
0
  ev[0].err = errno;
46
0
  errno = 0;
47
0
  if (minval > maxval) {
48
0
    error = INVALID;
49
0
  } else {
50
0
    ll = strtoll(numstr, &ep, 10);
51
0
    if (numstr == ep || *ep != '\0')
52
0
      error = INVALID;
53
0
    else if ((ll == LLONG_MIN && errno == ERANGE) || ll < minval)
54
0
      error = TOOSMALL;
55
0
    else if ((ll == LLONG_MAX && errno == ERANGE) || ll > maxval)
56
0
      error = TOOLARGE;
57
0
  }
58
0
  if (errstrp != NULL)
59
0
    *errstrp = ev[error].errstr;
60
0
  errno = ev[error].err;
61
0
  if (error)
62
0
    ll = 0;
63
64
0
  return (ll);
65
0
}