Create iterative method for querying SRV results, and use that for finding AGI servers.
[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 #include "asterisk.h"
33
34 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
35
36 #include <netinet/in.h>
37 #include <arpa/nameser.h>
38 #ifdef __APPLE__
39 #if __APPLE_CC__ >= 1495
40 #include <arpa/nameser_compat.h>
41 #endif
42 #endif
43 #include <resolv.h>
44
45 #include "asterisk/channel.h"
46 #include "asterisk/srv.h"
47 #include "asterisk/dns.h"
48 #include "asterisk/utils.h"
49 #include "asterisk/linkedlists.h"
50
51 #ifdef __APPLE__
52 #undef T_SRV
53 #define T_SRV 33
54 #endif
55
56 struct srv_entry {
57         unsigned short priority;
58         unsigned short weight;
59         unsigned short port;
60         unsigned int weight_sum;
61         AST_LIST_ENTRY(srv_entry) list;
62         char host[1];
63 };
64
65 struct srv_context {
66         unsigned int have_weights:1;
67         struct srv_entry *prev;
68         AST_LIST_HEAD_NOLOCK(srv_entries, srv_entry) entries;
69 };
70
71 static int parse_srv(unsigned char *answer, int len, unsigned char *msg, struct srv_entry **result)
72 {
73         struct srv {
74                 unsigned short priority;
75                 unsigned short weight;
76                 unsigned short port;
77         } __attribute__((__packed__)) *srv = (struct srv *) answer;
78
79         int res = 0;
80         char repl[256] = "";
81         struct srv_entry *entry;
82
83         if (len < sizeof(*srv))
84                 return -1;
85
86         answer += sizeof(*srv);
87         len -= sizeof(*srv);
88
89         if ((res = dn_expand(msg, answer + len, answer, repl, sizeof(repl) - 1)) <= 0) {
90                 ast_log(LOG_WARNING, "Failed to expand hostname\n");
91                 return -1;
92         }
93
94         /* the magic value "." for the target domain means that this service
95            is *NOT* available at the domain we searched */
96         if (!strcmp(repl, "."))
97                 return -1;
98
99         if (!(entry = ast_calloc(1, sizeof(*entry) + strlen(repl))))
100                 return -1;
101         
102         entry->priority = ntohs(srv->priority);
103         entry->weight = ntohs(srv->weight);
104         entry->port = ntohs(srv->port);
105         strcpy(entry->host, repl);
106
107         *result = entry;
108         
109         return 0;
110 }
111
112 static int srv_callback(void *context, unsigned char *answer, int len, unsigned char *fullanswer)
113 {
114         struct srv_context *c = (struct srv_context *) context;
115         struct srv_entry *entry = NULL;
116         struct srv_entry *current;
117
118         if (parse_srv(answer, len, fullanswer, &entry))
119                 return -1;
120
121         if (entry->weight)
122                 c->have_weights = 1;
123
124         AST_LIST_TRAVERSE_SAFE_BEGIN(&c->entries, current, list) {
125                 /* insert this entry just before the first existing
126                    entry with a higher priority */
127                 if (current->priority <= entry->priority)
128                         continue;
129
130                 AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
131                 entry = NULL;
132                 break;
133         }
134         AST_LIST_TRAVERSE_SAFE_END;
135
136         /* if we didn't find a place to insert the entry before an existing
137            entry, then just add it to the end */
138         if (entry)
139                 AST_LIST_INSERT_TAIL(&c->entries, entry, list);
140
141         return 0;
142 }
143
144 /* Do the bizarre SRV record weight-handling algorithm
145    involving sorting and random number generation...
146
147    See RFC 2782 if you want know why this code does this
148 */
149 static void process_weights(struct srv_context *context)
150 {
151         struct srv_entry *current;
152         struct srv_entries newlist = AST_LIST_HEAD_NOLOCK_INIT_VALUE;
153
154         while (AST_LIST_FIRST(&context->entries)) {
155                 unsigned int random_weight;
156                 unsigned int weight_sum;
157                 unsigned short cur_priority = AST_LIST_FIRST(&context->entries)->priority;
158                 struct srv_entries temp_list = AST_LIST_HEAD_NOLOCK_INIT_VALUE;
159                 weight_sum = 0;
160
161                 AST_LIST_TRAVERSE_SAFE_BEGIN(&context->entries, current, list) {
162                         if (current->priority != cur_priority)
163                                 break;
164
165                         AST_LIST_MOVE_CURRENT(&temp_list, list);
166                 }
167                 AST_LIST_TRAVERSE_SAFE_END;
168
169                 while (AST_LIST_FIRST(&temp_list)) {
170                         weight_sum = 0;
171                         AST_LIST_TRAVERSE(&temp_list, current, list)
172                                 current->weight_sum = weight_sum += current->weight;
173
174                         /* if all the remaining entries have weight == 0,
175                            then just append them to the result list and quit */
176                         if (weight_sum == 0) {
177                                 AST_LIST_APPEND_LIST(&newlist, &temp_list, list);
178                                 break;
179                         }
180
181                         random_weight = 1 + (unsigned int) ((float) weight_sum * (ast_random() / ((float) RAND_MAX + 1.0)));
182
183                         AST_LIST_TRAVERSE_SAFE_BEGIN(&temp_list, current, list) {
184                                 if (current->weight < random_weight)
185                                         continue;
186
187                                 AST_LIST_MOVE_CURRENT(&newlist, list);
188                                 break;
189                         }
190                         AST_LIST_TRAVERSE_SAFE_END;
191                 }
192
193         }
194
195         /* now that the new list has been ordered,
196            put it in place */
197
198         AST_LIST_APPEND_LIST(&context->entries, &newlist, list);
199 }
200
201 int ast_srv_lookup(struct srv_context **context, const char *service, const char **host, unsigned short *port)
202 {
203         struct srv_entry *cur;
204
205         if (*context == NULL) {
206                 if (!(*context = ast_calloc(1, sizeof(struct srv_context)))) {
207                         return -1;
208                 }
209                 AST_LIST_HEAD_INIT_NOLOCK(&(*context)->entries);
210
211                 if ((ast_search_dns(*context, service, C_IN, T_SRV, srv_callback)) < 0) {
212                         ast_free(*context);
213                         *context = NULL;
214                         return -1;
215                 }
216
217                 if ((*context)->have_weights) {
218                         process_weights(*context);
219                 }
220
221                 (*context)->prev = AST_LIST_FIRST(&(*context)->entries);
222                 *host = (*context)->prev->host;
223                 *port = (*context)->prev->port;
224                 return 0;
225         }
226
227         if (((*context)->prev = AST_LIST_NEXT((*context)->prev, list))) {
228                 /* Retrieve next item in result */
229                 *host = (*context)->prev->host;
230                 *port = (*context)->prev->port;
231                 return 0;
232         } else {
233                 /* No more results */
234                 while ((cur = AST_LIST_REMOVE_HEAD(&(*context)->entries, list))) {
235                         ast_free(cur);
236                 }
237                 ast_free(*context);
238                 *context = NULL;
239                 return 1;
240         }
241 }
242
243 void ast_srv_cleanup(struct srv_context **context)
244 {
245         const char *host;
246         unsigned short port;
247         while (!(ast_srv_lookup(context, NULL, &host, &port)));
248 }
249
250 int ast_get_srv(struct ast_channel *chan, char *host, int hostlen, int *port, const char *service)
251 {
252         struct srv_context context = { .entries = AST_LIST_HEAD_NOLOCK_INIT_VALUE };
253         struct srv_entry *current;
254         int ret;
255
256         if (chan && ast_autoservice_start(chan) < 0)
257                 return -1;
258
259         ret = ast_search_dns(&context, service, C_IN, T_SRV, srv_callback);
260
261         if (context.have_weights)
262                 process_weights(&context);
263
264         if (chan)
265                 ret |= ast_autoservice_stop(chan);
266
267         /* TODO: there could be a "." entry in the returned list of
268            answers... if so, this requires special handling */
269
270         /* the list of entries will be sorted in the proper selection order
271            already, so we just need the first one (if any) */
272
273         if ((ret > 0) && (current = AST_LIST_REMOVE_HEAD(&context.entries, list))) {
274                 ast_copy_string(host, current->host, hostlen);
275                 *port = current->port;
276                 ast_free(current);
277                 ast_verb(4, "ast_get_srv: SRV lookup for '%s' mapped to host %s, port %d\n",
278                                     service, host, *port);
279         } else {
280                 host[0] = '\0';
281                 *port = -1;
282         }
283
284         while ((current = AST_LIST_REMOVE_HEAD(&context.entries, list)))
285                 ast_free(current);
286
287         return ret;
288 }