1 /* SPDX-License-Identifier: BSD-3-Clause 2 * Copyright(c) 2023 Marvell. 3 */ 4 5 #include <ctype.h> 6 #include <errno.h> 7 #include <stdio.h> 8 #include <stdlib.h> 9 #include <string.h> 10 11 #include <rte_common.h> 12 #include <rte_string_fns.h> 13 14 #include "module_api.h" 15 16 static void 17 hex_string_to_uint64(uint64_t *dst, const char *hexs) 18 { 19 char buf[2] = {0}; 20 uint8_t shift = 4; 21 int iter = 0; 22 char c; 23 24 while ((c = *hexs++)) { 25 buf[0] = c; 26 *dst |= (strtol(buf, NULL, 16) << shift); 27 shift -= 4; 28 iter++; 29 if (iter == 2) { 30 iter = 0; 31 shift = 4; 32 dst++; 33 } 34 } 35 } 36 37 int 38 parser_uint64_read(uint64_t *value, const char *p) 39 { 40 char *next; 41 uint64_t val; 42 43 p = rte_str_skip_leading_spaces(p); 44 if (!isdigit(*p)) 45 return -EINVAL; 46 47 val = strtoul(p, &next, 0); 48 if (p == next) 49 return -EINVAL; 50 51 p = next; 52 switch (*p) { 53 case 'T': 54 val *= 1024ULL; 55 /* fall through */ 56 case 'G': 57 val *= 1024ULL; 58 /* fall through */ 59 case 'M': 60 val *= 1024ULL; 61 /* fall through */ 62 case 'k': 63 case 'K': 64 val *= 1024ULL; 65 p++; 66 break; 67 } 68 69 p = rte_str_skip_leading_spaces(p); 70 if (*p != '\0') 71 return -EINVAL; 72 73 *value = val; 74 return 0; 75 } 76 77 int 78 parser_uint32_read(uint32_t *value, const char *p) 79 { 80 uint64_t val = 0; 81 int rc = parser_uint64_read(&val, p); 82 83 if (rc < 0) 84 return rc; 85 86 if (val > UINT32_MAX) 87 return -ERANGE; 88 89 *value = val; 90 return 0; 91 } 92 93 int 94 parser_ip4_read(uint32_t *value, char *p) 95 { 96 uint8_t shift = 24; 97 uint32_t ip = 0; 98 char *token, *saveptr = NULL; 99 100 token = strtok_r(p, ".", &saveptr); 101 while (token != NULL) { 102 ip |= (((uint32_t)strtoul(token, NULL, 10)) << shift); 103 token = strtok_r(NULL, ".", &saveptr); 104 shift -= 8; 105 } 106 107 *value = ip; 108 109 return 0; 110 } 111 112 int 113 parser_ip6_read(uint8_t *value, char *p) 114 { 115 uint64_t val = 0; 116 char *token, *saveptr = NULL; 117 118 token = strtok_r(p, ":", &saveptr); 119 while (token != NULL) { 120 hex_string_to_uint64(&val, token); 121 *value = val; 122 token = strtok_r(NULL, ":", &saveptr); 123 value++; 124 val = 0; 125 } 126 127 return 0; 128 } 129 130 int 131 parser_mac_read(uint64_t *value, char *p) 132 { 133 uint64_t mac = 0, val = 0; 134 uint8_t shift = 40; 135 char *token, *saveptr = NULL; 136 137 token = strtok_r(p, ":", &saveptr); 138 while (token != NULL) { 139 hex_string_to_uint64(&val, token); 140 mac |= val << shift; 141 token = strtok_r(NULL, ":", &saveptr); 142 shift -= 8; 143 val = 0; 144 } 145 146 *value = mac; 147 148 return 0; 149 } 150