git migration: Refactor the ASTERISK_FILE_VERSION macro
[asterisk/asterisk.git] / main / srv.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * Funding provided by nic.at
9  *
10  * See http://www.asterisk.org for more information about
11  * the Asterisk project. Please do not directly contact
12  * any of the maintainers of this project for assistance;
13  * the project provides a web site, mailing lists and IRC
14  * channels for your use.
15  *
16  * This program is free software, distributed under the terms of
17  * the GNU General Public License Version 2. See the LICENSE file
18  * at the top of the source tree.
19  */
20
21 /*! \file
22  *
23  * \brief DNS SRV Record Lookup Support for Asterisk
24  *
25  * \author Mark Spencer <markster@digium.com>
26  *
27  * \arg See also \ref AstENUM
28  *
29  * \note Funding provided by nic.at
30  */
31
32 /*** MODULEINFO
33         <support_level>core</support_level>
34  ***/
35
36 #include "asterisk.h"
37
38 ASTERISK_REGISTER_FILE()
39
40 #include <netinet/in.h>
41 #include <arpa/nameser.h>
42 #ifdef __APPLE__
43 #include <arpa/nameser_compat.h>
44 #endif
45 #include <resolv.h>
46
47 #include "asterisk/channel.h"
48 #include "asterisk/srv.h"
49 #include "asterisk/dns.h"
50 #include "asterisk/utils.h"
51 #include "asterisk/linkedlists.h"
52
53 #ifdef __APPLE__
54 #undef T_SRV
55 #define T_SRV 33
56 #endif
57
58 struct srv_entry {
59         unsigned short priority;
60         unsigned short weight;
61         unsigned short port;
62         unsigned int weight_sum;
63         AST_LIST_ENTRY(srv_entry) list;
64         char host[1];
65 };
66
67 struct srv_context {
68         unsigned int have_weights:1;
69         struct srv_entry *prev;
70         unsigned int num_records;
71         AST_LIST_HEAD_NOLOCK(srv_entries, srv_entry) entries;
72 };
73
74 static int parse_srv(unsigned char *answer, int len, unsigned char *msg, struct srv_entry **result)
75 {
76         struct srv {
77                 unsigned short priority;
78                 unsigned short weight;
79                 unsigned short port;
80         } __attribute__((__packed__)) *srv = (struct srv *) answer;
81
82         int res = 0;
83         char repl[256] = "";
84         struct srv_entry *entry;
85
86         if (len < sizeof(*srv))
87                 return -1;
88
89         answer += sizeof(*srv);
90         len -= sizeof(*srv);
91
92         if ((res = dn_expand(msg, answer + len, answer, repl, sizeof(repl) - 1)) <= 0) {
93                 ast_log(LOG_WARNING, "Failed to expand hostname\n");
94                 return -1;
95         }
96
97         /* the magic value "." for the target domain means that this service
98            is *NOT* available at the domain we searched */
99         if (!strcmp(repl, "."))
100                 return -1;
101
102         if (!(entry = ast_calloc(1, sizeof(*entry) + strlen(repl))))
103                 return -1;
104
105         entry->priority = ntohs(srv->priority);
106         entry->weight = ntohs(srv->weight);
107         entry->port = ntohs(srv->port);
108         strcpy(entry->host, repl);
109
110         *result = entry;
111
112         return 0;
113 }
114
115 static int srv_callback(void *context, unsigned char *answer, int len, unsigned char *fullanswer)
116 {
117         struct srv_context *c = (struct srv_context *) context;
118         struct srv_entry *entry = NULL;
119         struct srv_entry *current;
120
121         if (parse_srv(answer, len, fullanswer, &entry))
122                 return -1;
123
124         if (entry->weight)
125                 c->have_weights = 1;
126
127         AST_LIST_TRAVERSE_SAFE_BEGIN(&c->entries, current, list) {
128                 /* insert this entry just before the first existing
129                    entry with a higher priority */
130                 if (current->priority <= entry->priority)
131                         continue;
132
133                 AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
134                 entry = NULL;
135                 break;
136         }
137         AST_LIST_TRAVERSE_SAFE_END;
138
139         /* if we didn't find a place to insert the entry before an existing
140            entry, then just add it to the end */
141         if (entry)
142                 AST_LIST_INSERT_TAIL(&c->entries, entry, list);
143
144         return 0;
145 }
146
147 /* Do the bizarre SRV record weight-handling algorithm
148    involving sorting and random number generation...
149
150    See RFC 2782 if you want know why this code does this
151 */
152 static void process_weights(struct srv_context *context)
153 {
154         struct srv_entry *current;
155         struct srv_entries newlist = AST_LIST_HEAD_NOLOCK_INIT_VALUE;
156
157         while (AST_LIST_FIRST(&context->entries)) {
158                 unsigned int random_weight;
159                 unsigned int weight_sum;
160                 unsigned short cur_priority = AST_LIST_FIRST(&context->entries)->priority;
161                 struct srv_entries temp_list = AST_LIST_HEAD_NOLOCK_INIT_VALUE;
162                 weight_sum = 0;
163
164                 AST_LIST_TRAVERSE_SAFE_BEGIN(&context->entries, current, list) {
165                         if (current->priority != cur_priority)
166                                 break;
167
168                         AST_LIST_MOVE_CURRENT(&temp_list, list);
169                 }
170                 AST_LIST_TRAVERSE_SAFE_END;
171
172                 while (AST_LIST_FIRST(&temp_list)) {
173                         weight_sum = 0;
174                         AST_LIST_TRAVERSE(&temp_list, current, list)
175                                 current->weight_sum = weight_sum += current->weight;
176
177                         /* if all the remaining entries have weight == 0,
178                            then just append them to the result list and quit */
179                         if (weight_sum == 0) {
180                                 AST_LIST_APPEND_LIST(&newlist, &temp_list, list);
181                                 break;
182                         }
183
184                         random_weight = 1 + (unsigned int) ((float) weight_sum * (ast_random() / ((float) RAND_MAX + 1.0)));
185
186                         AST_LIST_TRAVERSE_SAFE_BEGIN(&temp_list, current, list) {
187                                 if (current->weight < random_weight)
188                                         continue;
189
190                                 AST_LIST_MOVE_CURRENT(&newlist, list);
191                                 break;
192                         }
193                         AST_LIST_TRAVERSE_SAFE_END;
194                 }
195
196         }
197
198         /* now that the new list has been ordered,
199            put it in place */
200
201         AST_LIST_APPEND_LIST(&context->entries, &newlist, list);
202 }
203
204 int ast_srv_lookup(struct srv_context **context, const char *service, const char **host, unsigned short *port)
205 {
206         struct srv_entry *cur;
207
208         if (*context == NULL) {
209                 if (!(*context = ast_calloc(1, sizeof(struct srv_context)))) {
210                         return -1;
211                 }
212                 AST_LIST_HEAD_INIT_NOLOCK(&(*context)->entries);
213
214                 if ((ast_search_dns(*context, service, C_IN, T_SRV, srv_callback)) < 0) {
215                         ast_free(*context);
216                         *context = NULL;
217                         return -1;
218                 }
219
220                 if ((*context)->have_weights) {
221                         process_weights(*context);
222                 }
223
224                 (*context)->prev = AST_LIST_FIRST(&(*context)->entries);
225                 *host = (*context)->prev->host;
226                 *port = (*context)->prev->port;
227                 AST_LIST_TRAVERSE(&(*context)->entries, cur, list) {
228                         ++((*context)->num_records);
229                 }
230                 return 0;
231         }
232
233         if (((*context)->prev = AST_LIST_NEXT((*context)->prev, list))) {
234                 /* Retrieve next item in result */
235                 *host = (*context)->prev->host;
236                 *port = (*context)->prev->port;
237                 return 0;
238         } else {
239                 /* No more results */
240                 while ((cur = AST_LIST_REMOVE_HEAD(&(*context)->entries, list))) {
241                         ast_free(cur);
242                 }
243                 ast_free(*context);
244                 *context = NULL;
245                 return 1;
246         }
247 }
248
249 void ast_srv_cleanup(struct srv_context **context)
250 {
251         const char *host;
252         unsigned short port;
253
254         if (*context) {
255                 /* We have a context to clean up. */
256                 while (!(ast_srv_lookup(context, NULL, &host, &port))) {
257                 }
258         }
259 }
260
261 int ast_get_srv(struct ast_channel *chan, char *host, int hostlen, int *port, const char *service)
262 {
263         struct srv_context context = { .entries = AST_LIST_HEAD_NOLOCK_INIT_VALUE };
264         struct srv_entry *current;
265         int ret;
266
267         if (chan && ast_autoservice_start(chan) < 0) {
268                 return -1;
269         }
270
271         ret = ast_search_dns(&context, service, C_IN, T_SRV, srv_callback);
272
273         if (context.have_weights) {
274                 process_weights(&context);
275         }
276
277         if (chan) {
278                 ret |= ast_autoservice_stop(chan);
279         }
280
281         /* TODO: there could be a "." entry in the returned list of
282            answers... if so, this requires special handling */
283
284         /* the list of entries will be sorted in the proper selection order
285            already, so we just need the first one (if any) */
286
287         if ((ret > 0) && (current = AST_LIST_REMOVE_HEAD(&context.entries, list))) {
288                 ast_copy_string(host, current->host, hostlen);
289                 *port = current->port;
290                 ast_free(current);
291                 ast_debug(4, "ast_get_srv: SRV lookup for '%s' mapped to host %s, port %d\n",
292                                     service, host, *port);
293         } else {
294                 host[0] = '\0';
295                 *port = -1;
296         }
297
298         while ((current = AST_LIST_REMOVE_HEAD(&context.entries, list))) {
299                 ast_free(current);
300         }
301
302         return ret;
303 }
304
305 unsigned int ast_srv_get_record_count(struct srv_context *context)
306 {
307         return context->num_records;
308 }
309
310 int ast_srv_get_nth_record(struct srv_context *context, int record_num, const char **host,
311                 unsigned short *port, unsigned short *priority, unsigned short *weight)
312 {
313         int i = 1;
314         int res = -1;
315         struct srv_entry *entry;
316
317         if (record_num < 1 || record_num > context->num_records) {
318                 return res;
319         }
320
321         AST_LIST_TRAVERSE(&context->entries, entry, list) {
322                 if (i == record_num) {
323                         *host = entry->host;
324                         *port = entry->port;
325                         *priority = entry->priority;
326                         *weight = entry->weight;
327                         res = 0;
328                         break;
329                 }
330                 ++i;
331         }
332
333         return res;
334 }