| b.liu | e958203 | 2025-04-17 19:18:16 +0800 | [diff] [blame] | 1 | |
| 2 | /****************************************************************************** |
| 3 | *(C) Copyright 2015 Marvell International Ltd. |
| 4 | * All Rights Reserved |
| 5 | ******************************************************************************/ |
| 6 | |
| 7 | #include <arpa/inet.h> |
| 8 | #include <stdbool.h> |
| 9 | #include <string.h> |
| 10 | #include <include/log.h> |
| 11 | #include "chl_util.h" |
| 12 | |
| 13 | #define INET_PROCF "/proc/net/if_inet6" |
| 14 | #define INET_PROCF_FORMAT \ |
| 15 | " %2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx %*x %x %x %*x %s" |
| 16 | |
| 17 | int validate_ip(const char *addr, int family) |
| 18 | { |
| 19 | unsigned char buf[sizeof(struct in6_addr)]; |
| 20 | |
| 21 | if (family != AF_INET6 && family != AF_INET) |
| 22 | return 1; |
| 23 | |
| 24 | return inet_pton(family, addr, buf) != 1; |
| 25 | } |
| 26 | |
| 27 | int get_global_ipv6(const char *ifname, char *addr, int *prefix) |
| 28 | { |
| 29 | FILE *f; |
| 30 | int scope, ret = 1; |
| 31 | unsigned char ipv6[16]; |
| 32 | char dname[16]; |
| 33 | |
| 34 | f = fopen(INET_PROCF, "r"); |
| 35 | if (!f) { |
| 36 | CHL_ERR("failed to open %s\n", INET_PROCF); |
| 37 | return 1; |
| 38 | } |
| 39 | |
| 40 | while (fscanf(f, INET_PROCF_FORMAT, &ipv6[0], &ipv6[1], |
| 41 | &ipv6[2],&ipv6[3], &ipv6[4], &ipv6[5], &ipv6[6], |
| 42 | &ipv6[7],&ipv6[8], &ipv6[9], &ipv6[10], &ipv6[11], |
| 43 | &ipv6[12], &ipv6[13], &ipv6[14], &ipv6[15], |
| 44 | prefix, &scope, dname) != EOF) { |
| 45 | |
| 46 | if (strcmp(ifname, dname)) |
| 47 | continue; |
| 48 | |
| 49 | if (scope) |
| 50 | continue; |
| 51 | |
| 52 | if (inet_ntop(AF_INET6, ipv6, addr, INET6_ADDRSTRLEN) == NULL) |
| 53 | continue; |
| 54 | |
| 55 | ret = 0; |
| 56 | break; |
| 57 | } |
| 58 | |
| 59 | fclose(f); |
| 60 | return ret; |
| 61 | } |
| 62 | |
| 63 | bool str_starts_with(const char *str, const char *prefix) |
| 64 | { |
| 65 | size_t lenpre = strlen(prefix), lenstr = strlen(str); |
| 66 | return lenstr < lenpre ? false : strncasecmp(prefix, str, lenpre) == 0; |
| 67 | } |
| 68 | |
| 69 | void cid_to_ccinet(int cid, char *ccinet) |
| 70 | { |
| 71 | sprintf(ccinet, "ccinet%d", cid - 1); |
| 72 | } |
| 73 | |
| 74 | void cid_to_section(int cid, char *wan) |
| 75 | { |
| 76 | sprintf(wan, "wan%d", cid - 1); |
| 77 | } |
| 78 | |
| 79 | void cid_to_section6(int cid, char *wan6) |
| 80 | { |
| 81 | sprintf(wan6, "wan6%d", cid - 1); |
| 82 | } |