1/***
2  This file is part of PulseAudio.
3
4  Copyright 2004-2006 Lennart Poettering
5
6  PulseAudio is free software; you can redistribute it and/or modify
7  it under the terms of the GNU Lesser General Public License as
8  published by the Free Software Foundation; either version 2.1 of the
9  License, or (at your option) any later version.
10
11  PulseAudio is distributed in the hope that it will be useful, but
12  WITHOUT ANY WARRANTY; without even the implied warranty of
13  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  General Public License for more details.
15
16  You should have received a copy of the GNU Lesser General Public
17  License along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
18***/
19
20#ifdef HAVE_CONFIG_H
21#include <config.h>
22#endif
23
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
27#include <unistd.h>
28
29#include <avahi-client/client.h>
30#include <avahi-client/lookup.h>
31#include <avahi-common/alternative.h>
32#include <avahi-common/error.h>
33#include <avahi-common/domain.h>
34#include <avahi-common/malloc.h>
35
36#include <pulse/xmalloc.h>
37
38#include <pulsecore/core-util.h>
39#include <pulsecore/log.h>
40#include <pulsecore/hashmap.h>
41#include <pulsecore/modargs.h>
42#include <pulsecore/namereg.h>
43#include <pulsecore/avahi-wrap.h>
44
45PA_MODULE_AUTHOR("Lennart Poettering");
46PA_MODULE_DESCRIPTION("mDNS/DNS-SD Service Discovery");
47PA_MODULE_VERSION(PACKAGE_VERSION);
48PA_MODULE_LOAD_ONCE(true);
49
50#define SERVICE_TYPE_SINK "_pulse-sink._tcp"
51#define SERVICE_TYPE_SOURCE "_non-monitor._sub._pulse-source._tcp"
52
53static const char* const valid_modargs[] = {
54    NULL
55};
56
57struct tunnel {
58    AvahiIfIndex interface;
59    AvahiProtocol protocol;
60    char *name, *type, *domain;
61    uint32_t module_index;
62};
63
64struct userdata {
65    pa_core *core;
66    pa_module *module;
67    AvahiPoll *avahi_poll;
68    AvahiClient *client;
69    AvahiServiceBrowser *source_browser, *sink_browser;
70
71    pa_hashmap *tunnels;
72};
73
74static unsigned tunnel_hash(const void *p) {
75    const struct tunnel *t = p;
76
77    return
78        (unsigned) t->interface +
79        (unsigned) t->protocol +
80        pa_idxset_string_hash_func(t->name) +
81        pa_idxset_string_hash_func(t->type) +
82        pa_idxset_string_hash_func(t->domain);
83}
84
85static int tunnel_compare(const void *a, const void *b) {
86    const struct tunnel *ta = a, *tb = b;
87    int r;
88
89    if (ta->interface != tb->interface)
90        return 1;
91    if (ta->protocol != tb->protocol)
92        return 1;
93    if ((r = strcmp(ta->name, tb->name)))
94        return r;
95    if ((r = strcmp(ta->type, tb->type)))
96        return r;
97    if ((r = strcmp(ta->domain, tb->domain)))
98        return r;
99
100    return 0;
101}
102
103static struct tunnel *tunnel_new(
104        AvahiIfIndex interface, AvahiProtocol protocol,
105        const char *name, const char *type, const char *domain) {
106
107    struct tunnel *t;
108    t = pa_xnew(struct tunnel, 1);
109    t->interface = interface;
110    t->protocol = protocol;
111    t->name = pa_xstrdup(name);
112    t->type = pa_xstrdup(type);
113    t->domain = pa_xstrdup(domain);
114    t->module_index = PA_IDXSET_INVALID;
115    return t;
116}
117
118static void tunnel_free(struct tunnel *t) {
119    pa_assert(t);
120    pa_xfree(t->name);
121    pa_xfree(t->type);
122    pa_xfree(t->domain);
123    pa_xfree(t);
124}
125
126static void resolver_cb(
127        AvahiServiceResolver *r,
128        AvahiIfIndex interface, AvahiProtocol protocol,
129        AvahiResolverEvent event,
130        const char *name, const char *type, const char *domain,
131        const char *host_name, const AvahiAddress *a, uint16_t port,
132        AvahiStringList *txt,
133        AvahiLookupResultFlags flags,
134        void *userdata) {
135
136    struct userdata *u = userdata;
137    struct tunnel *tnl;
138
139    pa_assert(u);
140
141    tnl = tunnel_new(interface, protocol, name, type, domain);
142
143    if (event != AVAHI_RESOLVER_FOUND)
144        pa_log("Resolving of '%s' failed: %s", name, avahi_strerror(avahi_client_errno(u->client)));
145    else {
146        char *device = NULL, *dname, *module_name, *args;
147        const char *t;
148        char *if_suffix = NULL;
149        char at[AVAHI_ADDRESS_STR_MAX], cmt[PA_CHANNEL_MAP_SNPRINT_MAX];
150        char *properties = NULL;
151        pa_sample_spec ss;
152        pa_channel_map cm;
153        AvahiStringList *l;
154        bool channel_map_set = false;
155        pa_module *m;
156
157        ss = u->core->default_sample_spec;
158        cm = u->core->default_channel_map;
159
160        for (l = txt; l; l = l->next) {
161            char *key, *value;
162            pa_assert_se(avahi_string_list_get_pair(l, &key, &value, NULL) == 0);
163
164            if (pa_streq(key, "device")) {
165                pa_xfree(device);
166                device = value;
167                value = NULL;
168            } else if (pa_streq(key, "rate"))
169                ss.rate = (uint32_t) atoi(value);
170            else if (pa_streq(key, "channels"))
171                ss.channels = (uint8_t) atoi(value);
172            else if (pa_streq(key, "format"))
173                ss.format = pa_parse_sample_format(value);
174            else if (pa_streq(key, "icon-name")) {
175                pa_xfree(properties);
176                properties = pa_sprintf_malloc("device.icon_name=%s", value);
177            } else if (pa_streq(key, "channel_map")) {
178                pa_channel_map_parse(&cm, value);
179                channel_map_set = true;
180            }
181
182            avahi_free(key);
183            avahi_free(value);
184        }
185
186        if (!channel_map_set && cm.channels != ss.channels)
187            pa_channel_map_init_extend(&cm, ss.channels, PA_CHANNEL_MAP_DEFAULT);
188
189        if (!pa_sample_spec_valid(&ss)) {
190            pa_log("Service '%s' contains an invalid sample specification.", name);
191            avahi_free(device);
192            pa_xfree(properties);
193            goto finish;
194        }
195
196        if (!pa_channel_map_valid(&cm) || cm.channels != ss.channels) {
197            pa_log("Service '%s' contains an invalid channel map.", name);
198            avahi_free(device);
199            pa_xfree(properties);
200            goto finish;
201        }
202
203        if (device)
204            dname = pa_sprintf_malloc("tunnel.%s.%s", host_name, device);
205        else
206            dname = pa_sprintf_malloc("tunnel.%s", host_name);
207
208        if (!pa_namereg_is_valid_name(dname)) {
209            pa_log("Cannot construct valid device name from credentials of service '%s'.", dname);
210            avahi_free(device);
211            pa_xfree(dname);
212            pa_xfree(properties);
213            goto finish;
214        }
215
216        t = strstr(type, "sink") ? "sink" : "source";
217        if (a->proto == AVAHI_PROTO_INET6 &&
218            a->data.ipv6.address[0] == 0xfe &&
219            (a->data.ipv6.address[1] & 0xc0) == 0x80)
220            if_suffix = pa_sprintf_malloc("%%%d", interface);
221
222        module_name = pa_sprintf_malloc("module-tunnel-%s", t);
223        args = pa_sprintf_malloc("server=[%s%s]:%u "
224                                 "%s=%s "
225                                 "format=%s "
226                                 "channels=%u "
227                                 "rate=%u "
228                                 "%s_properties=%s "
229                                 "%s_name=%s "
230                                 "channel_map=%s",
231                                 avahi_address_snprint(at, sizeof(at), a),
232                                 if_suffix ? if_suffix : "", port,
233                                 t, device,
234                                 pa_sample_format_to_string(ss.format),
235                                 ss.channels,
236                                 ss.rate,
237                                 t, properties ? properties : "",
238                                 t, dname,
239                                 pa_channel_map_snprint(cmt, sizeof(cmt), &cm));
240
241        pa_log_debug("Loading %s with arguments '%s'", module_name, args);
242
243        if (pa_module_load(&m, u->core, module_name, args) >= 0) {
244            tnl->module_index = m->index;
245            pa_hashmap_put(u->tunnels, tnl, tnl);
246            tnl = NULL;
247        }
248
249        pa_xfree(module_name);
250        pa_xfree(dname);
251        pa_xfree(args);
252        pa_xfree(if_suffix);
253        pa_xfree(properties);
254        avahi_free(device);
255    }
256
257finish:
258
259    avahi_service_resolver_free(r);
260
261    if (tnl)
262        tunnel_free(tnl);
263}
264
265static void browser_cb(
266        AvahiServiceBrowser *b,
267        AvahiIfIndex interface, AvahiProtocol protocol,
268        AvahiBrowserEvent event,
269        const char *name, const char *type, const char *domain,
270        AvahiLookupResultFlags flags,
271        void *userdata) {
272
273    struct userdata *u = userdata;
274    struct tunnel *t;
275
276    pa_assert(u);
277
278    if (flags & AVAHI_LOOKUP_RESULT_LOCAL)
279        return;
280
281    t = tunnel_new(interface, protocol, name, type, domain);
282
283    if (event == AVAHI_BROWSER_NEW) {
284
285        if (!pa_hashmap_get(u->tunnels, t))
286            if (!(avahi_service_resolver_new(u->client, interface, protocol, name, type, domain, AVAHI_PROTO_UNSPEC, 0, resolver_cb, u)))
287                pa_log("avahi_service_resolver_new() failed: %s", avahi_strerror(avahi_client_errno(u->client)));
288
289        /* We ignore the returned resolver object here, since the we don't
290         * need to attach any special data to it, and we can still destroy
291         * it from the callback */
292
293    } else if (event == AVAHI_BROWSER_REMOVE) {
294        struct tunnel *t2;
295
296        if ((t2 = pa_hashmap_get(u->tunnels, t))) {
297            pa_module_unload_request_by_index(u->core, t2->module_index, true);
298            pa_hashmap_remove(u->tunnels, t2);
299            tunnel_free(t2);
300        }
301    }
302
303    tunnel_free(t);
304}
305
306static void client_callback(AvahiClient *c, AvahiClientState state, void *userdata) {
307    struct userdata *u = userdata;
308
309    pa_assert(c);
310    pa_assert(u);
311
312    u->client = c;
313
314    switch (state) {
315        case AVAHI_CLIENT_S_REGISTERING:
316        case AVAHI_CLIENT_S_RUNNING:
317        case AVAHI_CLIENT_S_COLLISION:
318
319            if (!u->sink_browser) {
320
321                if (!(u->sink_browser = avahi_service_browser_new(
322                              c,
323                              AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC,
324                              SERVICE_TYPE_SINK,
325                              NULL,
326                              0,
327                              browser_cb, u))) {
328
329                    pa_log("avahi_service_browser_new() failed: %s", avahi_strerror(avahi_client_errno(c)));
330                    pa_module_unload_request(u->module, true);
331                }
332            }
333
334            if (!u->source_browser) {
335
336                if (!(u->source_browser = avahi_service_browser_new(
337                              c,
338                              AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC,
339                              SERVICE_TYPE_SOURCE,
340                              NULL,
341                              0,
342                              browser_cb, u))) {
343
344                    pa_log("avahi_service_browser_new() failed: %s", avahi_strerror(avahi_client_errno(c)));
345                    pa_module_unload_request(u->module, true);
346                }
347            }
348
349            break;
350
351        case AVAHI_CLIENT_FAILURE:
352            if (avahi_client_errno(c) == AVAHI_ERR_DISCONNECTED) {
353                int error;
354
355                pa_log_debug("Avahi daemon disconnected.");
356
357                if (!(u->client = avahi_client_new(u->avahi_poll, AVAHI_CLIENT_NO_FAIL, client_callback, u, &error))) {
358                    pa_log("avahi_client_new() failed: %s", avahi_strerror(error));
359                    pa_module_unload_request(u->module, true);
360                }
361            }
362
363            /* Fall through */
364
365        case AVAHI_CLIENT_CONNECTING:
366
367            if (u->sink_browser) {
368                avahi_service_browser_free(u->sink_browser);
369                u->sink_browser = NULL;
370            }
371
372            if (u->source_browser) {
373                avahi_service_browser_free(u->source_browser);
374                u->source_browser = NULL;
375            }
376
377            break;
378
379        default: ;
380    }
381}
382
383int pa__init(pa_module*m) {
384
385    struct userdata *u;
386    pa_modargs *ma = NULL;
387    int error;
388
389    if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
390        pa_log("Failed to parse module arguments.");
391        goto fail;
392    }
393
394    m->userdata = u = pa_xnew(struct userdata, 1);
395    u->core = m->core;
396    u->module = m;
397    u->sink_browser = u->source_browser = NULL;
398
399    u->tunnels = pa_hashmap_new(tunnel_hash, tunnel_compare);
400
401    u->avahi_poll = pa_avahi_poll_new(m->core->mainloop);
402
403    if (!(u->client = avahi_client_new(u->avahi_poll, AVAHI_CLIENT_NO_FAIL, client_callback, u, &error))) {
404        pa_log("pa_avahi_client_new() failed: %s", avahi_strerror(error));
405        goto fail;
406    }
407
408    pa_modargs_free(ma);
409
410    return 0;
411
412fail:
413    pa__done(m);
414
415    if (ma)
416        pa_modargs_free(ma);
417
418    return -1;
419}
420
421void pa__done(pa_module*m) {
422    struct userdata*u;
423    pa_assert(m);
424
425    if (!(u = m->userdata))
426        return;
427
428    if (u->client)
429        avahi_client_free(u->client);
430
431    if (u->avahi_poll)
432        pa_avahi_poll_free(u->avahi_poll);
433
434    if (u->tunnels) {
435        struct tunnel *t;
436
437        while ((t = pa_hashmap_steal_first(u->tunnels))) {
438            pa_module_unload_request_by_index(u->core, t->module_index, true);
439            tunnel_free(t);
440        }
441
442        pa_hashmap_free(u->tunnels);
443    }
444
445    pa_xfree(u);
446}
447