262be8079d9ef1cd183f5dc856f895cce1635f1d
[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/logger.h"
47 #include "asterisk/srv.h"
48 #include "asterisk/dns.h"
49 #include "asterisk/options.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         AST_LIST_HEAD_NOLOCK(srv_entries, srv_entry) entries;
70 };
71
72 static int parse_srv(unsigned char *answer, int len, unsigned char *msg, struct srv_entry **result)
73 {
74         struct srv {
75                 unsigned short priority;
76                 unsigned short weight;
77                 unsigned short port;
78         } __attribute__ ((__packed__)) *srv = (struct srv *) answer;
79
80         int res = 0;
81         char repl[256] = "";
82         struct srv_entry *entry;
83
84         if (len < sizeof(*srv))
85                 return -1;
86
87         answer += sizeof(*srv);
88         len -= sizeof(*srv);
89
90         if ((res = dn_expand(msg, answer + len, answer, repl, sizeof(repl) - 1)) <= 0) {
91                 ast_log(LOG_WARNING, "Failed to expand hostname\n");
92                 return -1;
93         }
94
95         /* the magic value "." for the target domain means that this service
96            is *NOT* available at the domain we searched */
97         if (!strcmp(repl, "."))
98                 return -1;
99
100         if (!(entry = ast_calloc(1, sizeof(*entry) + strlen(repl))))
101                 return -1;
102         
103         entry->priority = ntohs(srv->priority);
104         entry->weight = ntohs(srv->weight);
105         entry->port = ntohs(srv->port);
106         strcpy(entry->host, repl);
107
108         *result = entry;
109         
110         return 0;
111 }
112
113 static int srv_callback(void *context, unsigned char *answer, int len, unsigned char *fullanswer)
114 {
115         struct srv_context *c = (struct srv_context *) context;
116         struct srv_entry *entry = NULL;
117         struct srv_entry *current;
118
119         if (parse_srv(answer, len, fullanswer, &entry))
120                 return -1;
121
122         if (entry->weight)
123                 c->have_weights = 1;
124
125         AST_LIST_TRAVERSE_SAFE_BEGIN(&c->entries, current, list) {
126                 /* insert this entry just before the first existing
127                    entry with a higher priority */
128                 if (current->priority <= entry->priority)
129                         continue;
130
131                 AST_LIST_INSERT_BEFORE_CURRENT(entry, list);
132                 entry = NULL;
133                 break;
134         }
135         AST_LIST_TRAVERSE_SAFE_END;
136
137         /* if we didn't find a place to insert the entry before an existing
138            entry, then just add it to the end */
139         if (entry)
140                 AST_LIST_INSERT_TAIL(&c->entries, entry, list);
141
142         return 1;
143 }
144
145 /* Do the bizarre SRV record weight-handling algorithm
146    involving sorting and random number generation...
147
148    See RFC 2782 if you want know why this code does this
149 */
150 static void process_weights(struct srv_context *context)
151 {
152         struct srv_entry *current;
153         struct srv_entries newlist = AST_LIST_HEAD_NOLOCK_INIT_VALUE;
154
155         while (AST_LIST_FIRST(&context->entries)) {
156                 unsigned int random_weight;
157                 unsigned int weight_sum;
158                 unsigned short cur_priority = AST_LIST_FIRST(&context->entries)->priority;
159                 struct srv_entries temp_list = AST_LIST_HEAD_NOLOCK_INIT_VALUE;
160                 weight_sum = 0;
161
162                 AST_LIST_TRAVERSE_SAFE_BEGIN(&context->entries, current, list) {
163                         if (current->priority != cur_priority)
164                                 break;
165
166                         AST_LIST_MOVE_CURRENT(&temp_list, list);
167                 }
168                 AST_LIST_TRAVERSE_SAFE_END;
169
170                 while (AST_LIST_FIRST(&temp_list)) {
171                         weight_sum = 0;
172                         AST_LIST_TRAVERSE(&temp_list, current, list)
173                                 current->weight_sum = weight_sum += current->weight;
174
175                         /* if all the remaining entries have weight == 0,
176                            then just append them to the result list and quit */
177                         if (weight_sum == 0) {
178                                 AST_LIST_APPEND_LIST(&newlist, &temp_list, list);
179                                 break;
180                         }
181
182                         random_weight = 1 + (unsigned int) ((float) weight_sum * (ast_random() / ((float) RAND_MAX + 1.0)));
183
184                         AST_LIST_TRAVERSE_SAFE_BEGIN(&temp_list, current, list) {
185                                 if (current->weight < random_weight)
186                                         continue;
187
188                                 AST_LIST_MOVE_CURRENT(&newlist, list);
189                                 break;
190                         }
191                         AST_LIST_TRAVERSE_SAFE_END;
192                 }
193
194         }
195
196         /* now that the new list has been ordered,
197            put it in place */
198
199         AST_LIST_APPEND_LIST(&context->entries, &newlist, list);
200 }
201
202 int ast_get_srv(struct ast_channel *chan, char *host, int hostlen, int *port, const char *service)
203 {
204         struct srv_context context = { .entries = AST_LIST_HEAD_NOLOCK_INIT_VALUE };
205         struct srv_entry *current;
206         int ret;
207
208         if (chan && ast_autoservice_start(chan) < 0)
209                 return -1;
210
211         ret = ast_search_dns(&context, service, C_IN, T_SRV, srv_callback);
212
213         if (context.have_weights)
214                 process_weights(&context);
215
216         if (chan)
217                 ret |= ast_autoservice_stop(chan);
218
219         /* TODO: there could be a "." entry in the returned list of
220            answers... if so, this requires special handling */
221
222         /* the list of entries will be sorted in the proper selection order
223            already, so we just need the first one (if any) */
224
225         if ((ret > 0) && (current = AST_LIST_REMOVE_HEAD(&context.entries, list))) {
226                 ast_copy_string(host, current->host, hostlen);
227                 *port = current->port;
228                 ast_free(current);
229                 if (option_verbose > 3) {
230                         ast_verbose(VERBOSE_PREFIX_3 "ast_get_srv: SRV lookup for '%s' mapped to host %s, port %d\n",
231                                     service, host, *port);
232                 }
233         } else {
234                 host[0] = '\0';
235                 *port = -1;
236         }
237
238         while ((current = AST_LIST_REMOVE_HEAD(&context.entries, list)))
239                 ast_free(current);
240
241         return ret;
242 }