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