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