* Copyright (C) 2005 Thomas Butter <butter@uni-mannheim.de> * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA #define _PURPLE_DNSSRV_C_ #include <arpa/nameser.h> #ifdef HAVE_ARPA_NAMESER_COMPAT_H #include <arpa/nameser_compat.h> /* Missing from the mingw headers */ # define DNS_TYPE_SRV PurpleDnsTypeSrv # define DNS_TYPE_TXT PurpleDnsTypeTxt #define T_SRV PurpleDnsTypeSrv #define T_TXT PurpleDnsTypeTxt static PurpleSrvTxtQueryUiOps *srv_txt_query_ui_ops = NULL; struct _PurpleSrvTxtQueryData { typedef struct _PurpleSrvInternalQuery { } PurpleSrvInternalQuery; typedef struct _PurpleSrvResponseContainer { PurpleSrvResponse *response; } PurpleSrvResponseContainer; static gboolean purple_srv_txt_query_ui_resolve(PurpleSrvTxtQueryData *query_data); * Sort by priority, then by weight. Strictly numerically--no * randomness. Technically we only need to sort by pref and then * make sure any records with weight 0 are at the beginning of * their group, but it's just as easy to sort by weight. responsecompare(gconstpointer ar, gconstpointer br) PurpleSrvResponse *a = (PurpleSrvResponse*)ar; PurpleSrvResponse *b = (PurpleSrvResponse*)br; if(a->weight == b->weight) if(a->weight < b->weight) * Iterate over a list of PurpleSrvResponseContainer making the sum * the running total of the sums. Select a random integer in the range * (1, sum+1), then find the first element greater than or equal to the * number selected. From RFC 2782. * @param list The list of PurpleSrvResponseContainer. This function * removes a node from this list and returns the new list. * @param container_ptr The PurpleSrvResponseContainer that was chosen select_random_response(GList *list, PurpleSrvResponseContainer **container_ptr) PurpleSrvResponseContainer *container = cur->data; runningtotal += container->response->weight; container->sum = runningtotal; * If the running total is greater than 0, pick a number between * 1 and the runningtotal inclusive. (This is not precisely what * the RFC algorithm describes, but we wish to deal with integers * and avoid floats. This is functionally equivalent.) * If running total is 0, then choose r = 0. r = runningtotal ? g_random_int_range(1, runningtotal + 1) : 0; while (r > ((PurpleSrvResponseContainer *)cur->data)->sum) { /* Set the return parameter and remove cur from the list */ *container_ptr = cur->data; return g_list_delete_link(list, cur); * Reorder a GList of PurpleSrvResponses that have the same priority srv_reorder(GList *list, int num) GList *cur, *container_list = NULL; PurpleSrvResponseContainer *container; /* First build a list of container structs */ for (i = 0, cur = list; i < num; i++, cur = cur->next) { container = g_new(PurpleSrvResponseContainer, 1); container->response = cur->data; container_list = g_list_prepend(container_list, container); container_list = g_list_reverse(container_list); * Re-order the list that was passed in as a parameter. We leave * the list nodes in place, but replace their data pointers. container_list = select_random_response(container_list, &container); cur->data = container->response; * Sorts a GList of PurpleSrvResponses according to the * algorithm described in RFC 2782. * @param response GList of PurpleSrvResponse's * @param The original list, resorted purple_srv_sort(GList *list) if (!list || !list->next) { list = g_list_sort(list, responsecompare); PurpleSrvResponse *next_response; pref = ((PurpleSrvResponse *)cur->data)->pref; next_response = cur->next ? cur->next->data : NULL; if (!next_response || next_response->pref != pref) { * The 'count' records starting at 'start' all have the same * priority. Sort them by weight. srv_reorder(start, count); static PurpleSrvTxtQueryData * query_data_new(int type, gchar *query, gpointer extradata) PurpleSrvTxtQueryData *query_data = g_new0(PurpleSrvTxtQueryData, 1); query_data->extradata = extradata; query_data->query = query; purple_srv_txt_query_destroy(PurpleSrvTxtQueryData *query_data) PurpleSrvTxtQueryUiOps *ops = purple_srv_txt_query_get_ui_ops(); ops->destroy(query_data); if (query_data->handle > 0) purple_input_remove(query_data->handle); if (query_data->resolver != NULL) * It's not really possible to kill a thread. So instead we * just set the callback to NULL and let the DNS lookup query_data->cb.srv = NULL; g_free(query_data->error_message); if (query_data->fd_out != -1) close(query_data->fd_out); if (query_data->fd_in != -1) close(query_data->fd_in); g_free(query_data->query); dns_str_is_ascii(const char *name) for (c = (guchar *)name; c && *c; ++c) { write_to_parent(int in, int out, gconstpointer data, gsize size) const guchar *buf = data; w = write(out, buf, size); } else if (w < 0 && errno == EINTR) { /* Let's try some more; */ } while (size > 0 && w > 0); /* Read size bytes to data. Dies if an error occurs. */ read_from_parent(int in, int out, gpointer data, gsize size) r = read(in, data, size); } else if (r < 0 && errno == EINTR) { /* Let's try some more; */ } while (size > 0 && r > 0); G_GNUC_NORETURN static void PurpleSrvResponse *srvres; PurpleTxtResponse *txtres; int size, qdcount, ancount; guint16 type, dlen, pref, weight, port; PurpleSrvInternalQuery query; purple_restore_default_signal_handlers(); read_from_parent(in, out, &query, sizeof(query)); size = res_query( query.query, C_IN, query.type, (u_char*)&answer, sizeof( answer)); write_to_parent(in, out, &(query.type), sizeof(query.type)); write_to_parent(in, out, &size, sizeof(size)); qdcount = ntohs(answer.hdr.qdcount); ancount = ntohs(answer.hdr.ancount); cp = (guchar*)&answer + sizeof(HEADER); end = (guchar*)&answer + size; /* skip over unwanted stuff */ while (qdcount-- > 0 && cp < end) { size = dn_expand( (unsigned char*)&answer, end, cp, name, 256); while (ancount-- > 0 && cp < end) { size = dn_expand((unsigned char*)&answer, end, cp, name, 256); /* skip ttl and class since we already know it */ size = dn_expand( (unsigned char*)&answer, end, cp, name, 256); srvres = g_new0(PurpleSrvResponse, 1); if (strlen(name) > sizeof(srvres->hostname) - 1) { purple_debug_error("dnssrv", "hostname is longer than available buffer ('%s', %zd bytes)!", g_strlcpy(srvres->hostname, name, sizeof(srvres->hostname)); ret = g_list_prepend(ret, srvres); } else if (type == T_TXT) { txtres = g_new0(PurpleTxtResponse, 1); txtres->content = g_strndup((gchar*)(++cp), dlen-1); ret = g_list_append(ret, txtres); size = g_list_length(ret); ret = purple_srv_sort(ret); write_to_parent(in, out, &(query.type), sizeof(query.type)); write_to_parent(in, out, &size, sizeof(size)); write_to_parent(in, out, ret->data, sizeof(PurpleSrvResponse)); if (query.type == T_TXT) { PurpleTxtResponse *response = ret->data; gsize l = strlen(response->content) + 1 /* null byte */; write_to_parent(in, out, &l, sizeof(l)); write_to_parent(in, out, response->content, l); ret = g_list_remove(ret, ret->data); resolved(gpointer data, gint source, PurpleInputCondition cond) PurpleSrvTxtQueryData *query_data = (PurpleSrvTxtQueryData*)data; if (read(source, &type, sizeof(type)) == sizeof(type)) { if (read(source, &size, sizeof(size)) == sizeof(size)) { if (size == -1 || size == 0) { purple_debug_warning("dnssrv", "res_query returned an error\n"); /* Re-read resolv.conf and friends in case DNS servers have changed */ purple_debug_info("dnssrv", "Found 0 entries, errno is %i\n", errno); PurpleSrvCallback cb = query_data->cb.srv; cb(NULL, 0, query_data->extradata); } else if (type == T_TXT) { PurpleTxtCallback cb = query_data->cb.txt; cb(NULL, query_data->extradata); purple_debug_error("dnssrv", "type unknown of DNS result entry; errno is %i\n", errno); PurpleSrvCallback cb = query_data->cb.srv; purple_debug_info("dnssrv","found %d SRV entries\n", size); tmp = res = g_new0(PurpleSrvResponse, size); for (i = 0; i < size; i++) { red = read(source, tmp++, sizeof(PurpleSrvResponse)); if (red != sizeof(PurpleSrvResponse)) { purple_debug_error("dnssrv","unable to read srv " "response: %s\n", g_strerror(errno)); cb(res, size, query_data->extradata); } else if (type == T_TXT) { PurpleTxtCallback cb = query_data->cb.txt; purple_debug_info("dnssrv","found %d TXT entries\n", size); for (i = 0; i < size; i++) { red = read(source, &len, sizeof(len)); if (red != sizeof(len)) { purple_debug_error("dnssrv","unable to read txt " "response length: %s\n", g_strerror(errno)); g_list_foreach(responses, (GFunc)purple_txt_response_destroy, NULL); res = g_new0(PurpleTxtResponse, 1); res->content = g_new0(gchar, len); red = read(source, res->content, len); purple_debug_error("dnssrv","unable to read txt " "response: %s\n", g_strerror(errno)); purple_txt_response_destroy(res); g_list_foreach(responses, (GFunc)purple_txt_response_destroy, NULL); responses = g_list_prepend(responses, res); responses = g_list_reverse(responses); cb(responses, query_data->extradata); purple_debug_error("dnssrv", "type unknown of DNS result entry; errno is %i\n", errno); waitpid(query_data->pid, &status, 0); purple_srv_txt_query_destroy(query_data); /** The Jabber Server code was inspiration for parts of this. */ res_main_thread_cb(gpointer data) PurpleSrvResponse *srvres = NULL; PurpleSrvTxtQueryData *query_data = data; if(query_data->error_message != NULL) { purple_debug_error("dnssrv", "%s", query_data->error_message); if (query_data->type == DNS_TYPE_SRV) { query_data->cb.srv(srvres, 0, query_data->extradata); } else if (query_data->type == DNS_TYPE_TXT) { query_data->cb.txt(NULL, query_data->extradata); if (query_data->type == DNS_TYPE_SRV) { PurpleSrvResponse *srvres_tmp = NULL; GList *lst = query_data->results; int size = g_list_length(lst); if(query_data->cb.srv && size > 0) srvres_tmp = srvres = g_new0(PurpleSrvResponse, size); PurpleSrvResponse *lstdata = lst->data; lst = g_list_delete_link(lst, lst); memcpy(srvres_tmp++, lstdata, sizeof(PurpleSrvResponse)); query_data->results = NULL; purple_debug_info("dnssrv", "found %d SRV entries\n", size); if(query_data->cb.srv) query_data->cb.srv(srvres, size, query_data->extradata); } else if (query_data->type == DNS_TYPE_TXT) { GList *lst = query_data->results; purple_debug_info("dnssrv", "found %d TXT entries\n", g_list_length(lst)); if (query_data->cb.txt) { query_data->results = NULL; query_data->cb.txt(lst, query_data->extradata); purple_debug_error("dnssrv", "unknown query type"); query_data->resolver = NULL; purple_srv_txt_query_destroy(query_data); res_thread(gpointer data) PurpleSrvTxtQueryData *query_data = data; ds = DnsQuery_UTF8(query_data->query, type, DNS_QUERY_STANDARD, NULL, &dr, NULL); if (ds != ERROR_SUCCESS) { gchar *msg = g_win32_error_message(ds); if (type == DNS_TYPE_SRV) { query_data->error_message = g_strdup_printf("Couldn't look up SRV record. %s (%lu).\n", msg, ds); } else if (type == DNS_TYPE_TXT) { query_data->error_message = g_strdup_printf("Couldn't look up TXT record. %s (%lu).\n", msg, ds); if (type == DNS_TYPE_SRV) { PurpleSrvResponse *srvres; for (dr_tmp = dr; dr_tmp != NULL; dr_tmp = dr_tmp->pNext) { /* Discard any incorrect entries. I'm not sure if this is necessary */ if (dr_tmp->wType != type || strcmp(dr_tmp->pName, query_data->query) != 0) { srv_data = &dr_tmp->Data.SRV; srvres = g_new0(PurpleSrvResponse, 1); strncpy(srvres->hostname, srv_data->pNameTarget, 255); srvres->hostname[255] = '\0'; srvres->pref = srv_data->wPriority; srvres->port = srv_data->wPort; srvres->weight = srv_data->wWeight; lst = g_list_prepend(lst, srvres); DnsRecordListFree(dr, DnsFreeRecordList); query_data->results = purple_srv_sort(lst); } else if (type == DNS_TYPE_TXT) { PurpleTxtResponse *txtres; for (dr_tmp = dr; dr_tmp != NULL; dr_tmp = dr_tmp->pNext) { /* Discard any incorrect entries. I'm not sure if this is necessary */ if (dr_tmp->wType != type || strcmp(dr_tmp->pName, query_data->query) != 0) { txt_data = &dr_tmp->Data.TXT; txtres = g_new0(PurpleTxtResponse, 1); for (i = 0; i < txt_data->dwStringCount; ++i) s = g_string_append(s, txt_data->pStringArray[i]); txtres->content = g_string_free(s, FALSE); lst = g_list_append(lst, txtres); DnsRecordListFree(dr, DnsFreeRecordList); query_data->results = lst; /* back to main thread */ /* Note: this should *not* be attached to query_data->handle - it will cause leakage */ purple_timeout_add(0, res_main_thread_cb, query_data); purple_srv_resolve(const char *protocol, const char *transport, const char *domain, PurpleSrvCallback cb, gpointer extradata) return purple_srv_resolve_account(NULL, protocol, transport, domain, purple_srv_resolve_account(PurpleAccount *account, const char *protocol, const char *transport, const char *domain, PurpleSrvCallback cb, PurpleSrvTxtQueryData *query_data; PurpleProxyType proxy_type; PurpleSrvInternalQuery internal_query; if (!protocol || !*protocol || !transport || !*transport || !domain || !*domain) { purple_debug_error("dnssrv", "Wrong arguments\n"); g_return_val_if_reached(NULL); proxy_type = purple_proxy_info_get_type( purple_proxy_get_setup(account)); if (proxy_type == PURPLE_PROXY_TOR) { purple_debug_info("dnssrv", "Aborting SRV lookup in Tor Proxy mode."); if (!dns_str_is_ascii(domain)) { int ret = purple_network_convert_idn_to_ascii(domain, &hostname); purple_debug_error("dnssrv", "IDNA ToASCII failed\n"); } else /* Fallthru is intentional */ hostname = g_strdup(domain); query = g_strdup_printf("_%s._%s.%s", protocol, transport, hostname); purple_debug_info("dnssrv","querying SRV record for %s: %s\n", domain, query_data = query_data_new(PurpleDnsTypeSrv, query, extradata); if (purple_srv_txt_query_ui_resolve(query_data)) if(pipe(in) || pipe(out)) { purple_debug_error("dnssrv", "Could not create pipe\n"); purple_debug_error("dnssrv", "Could not create process!\n"); /* resolve() does not return */ internal_query.type = T_SRV; strncpy(internal_query.query, query, 255); internal_query.query[255] = '\0'; if (write(in[1], &internal_query, sizeof(internal_query)) < 0) purple_debug_error("dnssrv", "Could not write to SRV resolver\n"); query_data->fd_out = out[0]; query_data->fd_in = in[1]; query_data->handle = purple_input_add(out[0], PURPLE_INPUT_READ, resolved, query_data); query_data->resolver = g_thread_create(res_thread, query_data, FALSE, &err); if (query_data->resolver == NULL) { query_data->error_message = g_strdup_printf("SRV thread create failure: %s\n", (err && err->message) ? err->message : ""); /* The query isn't going to happen, so finish the SRV lookup now. * Asynchronously call the callback since stuff may not expect * the callback to be called before this returns */ if (query_data->error_message != NULL) query_data->handle = purple_timeout_add(0, res_main_thread_cb, query_data); PurpleSrvTxtQueryData *purple_txt_resolve(const char *owner, const char *domain, PurpleTxtCallback cb, gpointer extradata) return purple_txt_resolve_account(NULL, owner, domain, cb, extradata); PurpleSrvTxtQueryData *purple_txt_resolve_account(PurpleAccount *account, const char *owner, const char *domain, PurpleTxtCallback cb, PurpleSrvTxtQueryData *query_data; PurpleProxyType proxy_type; PurpleSrvInternalQuery internal_query; proxy_type = purple_proxy_info_get_type( purple_proxy_get_setup(account)); if (proxy_type == PURPLE_PROXY_TOR) { purple_debug_info("dnssrv", "Aborting TXT lookup in Tor Proxy mode."); if (!dns_str_is_ascii(domain)) { int ret = purple_network_convert_idn_to_ascii(domain, &hostname); purple_debug_error("dnssrv", "IDNA ToASCII failed\n"); } else /* fallthru is intentional */ hostname = g_strdup(domain); query = g_strdup_printf("%s.%s", owner, hostname); purple_debug_info("dnssrv","querying TXT record for %s: %s\n", domain, query_data = query_data_new(PurpleDnsTypeTxt, query, extradata); if (purple_srv_txt_query_ui_resolve(query_data)) { /* query intentionally not freed if(pipe(in) || pipe(out)) { purple_debug_error("dnssrv", "Could not create pipe\n"); purple_debug_error("dnssrv", "Could not create process!\n"); /* resolve() does not return */ internal_query.type = T_TXT; strncpy(internal_query.query, query, 255); internal_query.query[255] = '\0'; if (write(in[1], &internal_query, sizeof(internal_query)) < 0) purple_debug_error("dnssrv", "Could not write to TXT resolver\n"); query_data->fd_out = out[0]; query_data->fd_in = in[1]; query_data->handle = purple_input_add(out[0], PURPLE_INPUT_READ, resolved, query_data); query_data->resolver = g_thread_create(res_thread, query_data, FALSE, &err); if (query_data->resolver == NULL) { query_data->error_message = g_strdup_printf("TXT thread create failure: %s\n", (err && err->message) ? err->message : ""); /* The query isn't going to happen, so finish the TXT lookup now. * Asynchronously call the callback since stuff may not expect * the callback to be called before this returns */ if (query_data->error_message != NULL) query_data->handle = purple_timeout_add(0, res_main_thread_cb, query_data); purple_txt_cancel(PurpleSrvTxtQueryData *query_data) purple_srv_txt_query_destroy(query_data); purple_srv_cancel(PurpleSrvTxtQueryData *query_data) purple_srv_txt_query_destroy(query_data); purple_txt_response_get_content(PurpleTxtResponse *resp) g_return_val_if_fail(resp != NULL, NULL); void purple_txt_response_destroy(PurpleTxtResponse *resp) g_return_if_fail(resp != NULL); * Only used as the callback for the ui ops. purple_srv_query_resolved(PurpleSrvTxtQueryData *query_data, GList *records) PurpleSrvResponse *records_array; g_return_if_fail(records != NULL); if (query_data->cb.srv == NULL) { purple_srv_txt_query_destroy(query_data); records = g_list_delete_link(records, records); records = purple_srv_sort(records); length = g_list_length(records); purple_debug_info("dnssrv", "SRV records resolved for %s, count: %d\n", query_data->query, length); records_array = g_new(PurpleSrvResponse, length); for (l = records; l; l = l->next, i++) { records_array[i] = *(PurpleSrvResponse *)l->data; query_data->cb.srv(records_array, length, query_data->extradata); purple_srv_txt_query_destroy(query_data); records = g_list_delete_link(records, records); * Only used as the callback for the ui ops. purple_txt_query_resolved(PurpleSrvTxtQueryData *query_data, GList *entries) g_return_if_fail(entries != NULL); purple_debug_info("dnssrv", "TXT entries resolved for %s, count: %d\n", query_data->query, g_list_length(entries)); /* the callback should g_free the entries. if (query_data->cb.txt != NULL) query_data->cb.txt(entries, query_data->extradata); entries = g_list_delete_link(entries, entries); purple_srv_txt_query_destroy(query_data); purple_srv_query_failed(PurpleSrvTxtQueryData *query_data, const gchar *error_message) purple_debug_error("dnssrv", "%s\n", error_message); if (query_data->cb.srv != NULL) query_data->cb.srv(NULL, 0, query_data->extradata); purple_srv_txt_query_destroy(query_data); purple_srv_txt_query_ui_resolve(PurpleSrvTxtQueryData *query_data) PurpleSrvTxtQueryUiOps *ops = purple_srv_txt_query_get_ui_ops(); return ops->resolve(query_data, (query_data->type == T_SRV ? purple_srv_query_resolved : purple_txt_query_resolved), purple_srv_query_failed); purple_srv_txt_query_set_ui_ops(PurpleSrvTxtQueryUiOps *ops) srv_txt_query_ui_ops = ops; purple_srv_txt_query_get_ui_ops(void) /* It is perfectly acceptable for srv_txt_query_ui_ops to be NULL; this just * means that the default platform-specific implementation will be used. return srv_txt_query_ui_ops; purple_srv_txt_query_get_query(PurpleSrvTxtQueryData *query_data) g_return_val_if_fail(query_data != NULL, NULL); return query_data->query; purple_srv_txt_query_get_type(PurpleSrvTxtQueryData *query_data) g_return_val_if_fail(query_data != NULL, 0);