|
18 | 18 |
|
19 | 19 | #include <cassert>
|
20 | 20 |
|
21 |
| - |
22 | 21 | static memcached_return_t set_hostinfo(memcached_instance_st *server) {
|
23 | 22 | assert(server->type != MEMCACHED_CONNECTION_UNIX_SOCKET);
|
| 23 | + assert(server->hostname()); |
| 24 | + |
24 | 25 | server->clear_addrinfo();
|
25 | 26 |
|
26 |
| - char str_port[MEMCACHED_NI_MAXSERV] = {0}; |
| 27 | + char str_host[MEMCACHED_NI_MAXHOST] = {0}, str_port[MEMCACHED_NI_MAXSERV] = {0}; |
27 | 28 | errno = 0;
|
28 |
| - int length = snprintf(str_port, MEMCACHED_NI_MAXSERV, "%u", uint32_t(server->port())); |
29 |
| - if (length >= MEMCACHED_NI_MAXSERV or length <= 0 or errno) { |
| 29 | + |
| 30 | + auto length = snprintf(str_port, MEMCACHED_NI_MAXSERV, "%u", uint32_t(server->port())); |
| 31 | + if (length <= 0 or errno) { |
30 | 32 | return memcached_set_error(*server, MEMCACHED_MEMORY_ALLOCATION_FAILURE, MEMCACHED_AT,
|
31 | 33 | memcached_literal_param("snprintf(NI_MAXSERV)"));
|
32 | 34 | }
|
33 | 35 |
|
34 |
| - struct addrinfo hints; |
35 |
| - memset(&hints, 0, sizeof(struct addrinfo)); |
36 |
| - |
| 36 | + struct addrinfo hints{}; |
37 | 37 | hints.ai_family = AF_UNSPEC;
|
38 | 38 | if (memcached_is_udp(server->root)) {
|
39 | 39 | hints.ai_protocol = IPPROTO_UDP;
|
40 | 40 | hints.ai_socktype = SOCK_DGRAM;
|
41 | 41 | } else {
|
42 |
| - hints.ai_socktype = SOCK_STREAM; |
43 | 42 | hints.ai_protocol = IPPROTO_TCP;
|
| 43 | + hints.ai_socktype = SOCK_STREAM; |
44 | 44 | }
|
45 | 45 |
|
46 |
| - assert(server->address_info == NULL); |
47 |
| - assert(server->address_info_next == NULL); |
48 |
| - int errcode; |
49 |
| - char hostname[MEMCACHED_NI_MAXHOST]; |
50 |
| - const char *addr; |
51 |
| - char *p; |
52 |
| - |
53 |
| - assert(server->hostname()); |
54 |
| - // drop [] from address, commonly used for IPv6 |
55 |
| - addr = server->hostname(); |
56 |
| - if (*addr == '[') { |
57 |
| - strcpy(hostname, addr +1); |
58 |
| - p = strchr(hostname, ']'); |
59 |
| - if (p) { |
60 |
| - *p = 0; |
61 |
| - addr = hostname; |
62 |
| - } |
| 46 | + auto hostname = server->hostname(); |
| 47 | + if (*hostname == '[') { |
| 48 | + auto closing_bracket = &hostname[strlen(hostname) - 1]; |
| 49 | + if (*closing_bracket == ']') { |
| 50 | + auto host_len = closing_bracket - hostname - 1; |
| 51 | + if (host_len < MEMCACHED_NI_MAXHOST) { |
| 52 | + hostname = strncpy(str_host, hostname + 1, host_len); |
| 53 | + } |
| 54 | + } |
63 | 55 | }
|
64 |
| - switch (errcode = getaddrinfo(addr, str_port, &hints, &server->address_info)) { |
| 56 | + |
| 57 | + auto errcode = getaddrinfo(hostname, str_port, &hints, &server->address_info); |
| 58 | + switch (errcode) { |
65 | 59 | case 0:
|
66 | 60 | server->address_info_next = server->address_info;
|
67 | 61 | server->state = MEMCACHED_SERVER_STATE_ADDRINFO;
|
|
0 commit comments