-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon_resolver.cpp
169 lines (149 loc) · 5.15 KB
/
common_resolver.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
#include "resolver.h"
#include "resolvererror.h"
#include "liberror.h"
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <stdexcept>
Resolver::Resolver(
const char* hostname,
const char* servname,
bool is_passive) {
struct addrinfo hints;
this->result = this->_next = nullptr;
/*
* `getaddrinfo` nos resuelve el nombre de una máquina (host) y de un
* servicio a una dirección.
* Nos puede retornar múltiples direcciones incluso de
* protocolos/tecnologías que no nos interesan.
* Para pre-seleccionar que direcciones nos interesan le pasamos
* un hint, una estructura con algunos campos completados (no todos)
* que le indicaran que tipo de direcciones queremos.
*
* Para nuestros fines queremos direcciones de internet IPv4
* y para servicios de TCP.
* */
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET; /* IPv4 (or AF_INET6 for IPv6) */
hints.ai_socktype = SOCK_STREAM; /* TCP (or SOCK_DGRAM for UDP) */
hints.ai_flags = is_passive ? AI_PASSIVE : 0;
/* Obtengo la (o las) direcciones según el nombre de host y servicio que
* busco
*
* De todas las direcciones posibles, solo me interesan aquellas que sean
* IPv4 y TCP (según lo definido en hints)
*
* El resultado lo guarda en result que es un puntero al primer nodo
* de una lista simplemente enlazada.
* */
int s = getaddrinfo(hostname, servname, &hints, &this->result);
/* Es muy importante chequear los errores.
*
* En C, Golang, Rust, la forma de comunicar errores al caller (a quien
* nos llamó) es retornando un código de error.
*
* La página de manual de `getaddrinfo` aclara que si `s == 0`
* entonces todo salio bien.
*
* Si `s == EAI_SYSTEM` entonces el error es del sistema y deberemos
* inspeccionar la variable global `errno`.
*
* Si `s != EAI_SYSTEM`, entonces el valor de retorno debe ser
* inspeccionado con `gai_strerror`.
* */
if (s != 0) {
if (s == EAI_SYSTEM) {
/*
* Como `errno` es global y puede ser modificada por *cualquier* otra
* función, es *importantísimo* copiarla apenas detectemos el error.
*
* En este caso, `LibError` lo hara por nosotros.
*/
throw LibError(
errno,
"Name resolution failed for hostname '%s' y servname '%s'",
(hostname ? hostname : ""),
(servname ? servname : ""));
} else {
/*
* La documentación de `getaddrinfo` dice que en este caso
* debemos usar `gai_strerror` para obtener el mensaje de error.
* */
throw ResolverError(s);
}
}
this->_next = this->result;
}
Resolver::Resolver(Resolver&& other) {
/* Nos copiamos del otro resolver... */
this->result = other.result;
this->_next = other._next;
/* ...pero luego le sacamos al otro resolver
* el ownership del recurso.
* Efectivamente el ownership pasó de él
* a nosotros: el ownership se movió.
*
* En el caso de `Resolver` podemos marcar los
* punteros como `nullptr`.
* Tendremos que chequear en el destructor `~Resolver`
* este caso y evitar llamar a `freeaddrinfo` si es `nullptr`.
* */
other.result = nullptr;
other._next = nullptr;
}
Resolver& Resolver::operator=(Resolver&& other) {
/* Si el usuario hace algo como tratar de moverse
* a si mismo (`resolver = resolver;`) simplemente no hacemos
* nada.
* */
if (this == &other)
return *this;
/* A diferencia del constructor por movimiento,
* `this` (nosotros) es un resolver completamente creado
* y debemos desinicializarlo primero antes de pisarle
* el recurso con el que le robaremos al otro resolver (`other`)
* */
if (this->result)
freeaddrinfo(this->result);
/* Ahora hacemos los mismos pasos que en el move constructor */
this->result = other.result;
this->_next = other._next;
other.result = nullptr;
other._next = nullptr;
return *this;
}
bool Resolver::has_next() {
chk_addr_or_fail();
return this->_next != NULL;
}
struct addrinfo* Resolver::next() {
chk_addr_or_fail();
struct addrinfo *ret = this->_next;
this->_next = ret->ai_next;
return ret;
}
Resolver::~Resolver() {
/*
* `getaddrinfo` reservó recursos en algún lado (posiblemente el heap).
* Es nuestra obligación liberar dichos recursos cuando no los necesitamos
* más.
*
* La manpage dice q debemos usar `freeaddrinfo` para ello y
* así lo hacemos.
* */
if (this->result)
freeaddrinfo(this->result);
}
void Resolver::chk_addr_or_fail() const {
if (result == nullptr) {
throw std::runtime_error(
"addresses list is invalid (null), "
"perhaps you are using a *previously moved* "
"resolver (and therefore invalid).");
}
}