connect to localhost via IP address instead of host name, to avoid needless NSS lookup
[platform/upstream/pulseaudio.git] / src / pulse / context.c
1 /***
2   This file is part of PulseAudio.
3
4   Copyright 2004-2008 Lennart Poettering
5   Copyright 2006 Pierre Ossman <ossman@cendio.se> for Cendio AB
6
7   PulseAudio is free software; you can redistribute it and/or modify
8   it under the terms of the GNU Lesser General Public License as published
9   by the Free Software Foundation; either version 2 of the License,
10   or (at your option) any later version.
11
12   PulseAudio is distributed in the hope that it will be useful, but
13   WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15   General Public License for more details.
16
17   You should have received a copy of the GNU Lesser General Public License
18   along with PulseAudio; if not, write to the Free Software
19   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
20   USA.
21 ***/
22
23 #ifdef HAVE_CONFIG_H
24 #include <config.h>
25 #endif
26
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <sys/types.h>
31 #include <unistd.h>
32 #include <sys/stat.h>
33 #include <errno.h>
34 #include <signal.h>
35 #include <limits.h>
36 #include <locale.h>
37
38 #ifdef HAVE_SYS_WAIT_H
39 #include <sys/wait.h>
40 #endif
41
42 #ifdef HAVE_SYS_SOCKET_H
43 #include <sys/socket.h>
44 #endif
45 #ifdef HAVE_SYS_UN_H
46 #include <sys/un.h>
47 #endif
48 #ifdef HAVE_NETDB_H
49 #include <netdb.h>
50 #endif
51
52 #include <pulse/version.h>
53 #include <pulse/xmalloc.h>
54 #include <pulse/utf8.h>
55 #include <pulse/util.h>
56 #include <pulse/i18n.h>
57 #include <pulse/lock-autospawn.h>
58
59 #include <pulsecore/winsock.h>
60 #include <pulsecore/core-error.h>
61
62 #include <pulsecore/native-common.h>
63 #include <pulsecore/pdispatch.h>
64 #include <pulsecore/pstream.h>
65 #include <pulsecore/dynarray.h>
66 #include <pulsecore/socket-client.h>
67 #include <pulsecore/pstream-util.h>
68 #include <pulsecore/core-util.h>
69 #include <pulsecore/log.h>
70 #include <pulsecore/socket-util.h>
71 #include <pulsecore/creds.h>
72 #include <pulsecore/macro.h>
73 #include <pulsecore/proplist-util.h>
74
75 #include "internal.h"
76
77 #include "client-conf.h"
78
79 #ifdef HAVE_X11
80 #include "client-conf-x11.h"
81 #endif
82
83 #include "context.h"
84
85 void pa_command_extension(pa_pdispatch *pd, uint32_t command, uint32_t tag, pa_tagstruct *t, void *userdata);
86
87 static const pa_pdispatch_cb_t command_table[PA_COMMAND_MAX] = {
88     [PA_COMMAND_REQUEST] = pa_command_request,
89     [PA_COMMAND_OVERFLOW] = pa_command_overflow_or_underflow,
90     [PA_COMMAND_UNDERFLOW] = pa_command_overflow_or_underflow,
91     [PA_COMMAND_PLAYBACK_STREAM_KILLED] = pa_command_stream_killed,
92     [PA_COMMAND_RECORD_STREAM_KILLED] = pa_command_stream_killed,
93     [PA_COMMAND_PLAYBACK_STREAM_MOVED] = pa_command_stream_moved,
94     [PA_COMMAND_RECORD_STREAM_MOVED] = pa_command_stream_moved,
95     [PA_COMMAND_PLAYBACK_STREAM_SUSPENDED] = pa_command_stream_suspended,
96     [PA_COMMAND_RECORD_STREAM_SUSPENDED] = pa_command_stream_suspended,
97     [PA_COMMAND_STARTED] = pa_command_stream_started,
98     [PA_COMMAND_SUBSCRIBE_EVENT] = pa_command_subscribe_event,
99     [PA_COMMAND_EXTENSION] = pa_command_extension
100 };
101
102 static void unlock_autospawn(pa_context *c) {
103     pa_assert(c);
104
105     if (c->autospawn_fd >= 0) {
106
107         if (c->autospawn_locked)
108             pa_autospawn_lock_release();
109
110         if (c->autospawn_event)
111             c->mainloop->io_free(c->autospawn_event);
112
113         pa_autospawn_lock_done(FALSE);
114     }
115
116     c->autospawn_locked = FALSE;
117     c->autospawn_fd = -1;
118     c->autospawn_event = NULL;
119 }
120
121 static void context_free(pa_context *c);
122
123 pa_context *pa_context_new(pa_mainloop_api *mainloop, const char *name) {
124     return pa_context_new_with_proplist(mainloop, name, NULL);
125 }
126
127 static void reset_callbacks(pa_context *c) {
128     pa_assert(c);
129
130     c->state_callback = NULL;
131     c->state_userdata = NULL;
132
133     c->subscribe_callback = NULL;
134     c->subscribe_userdata = NULL;
135
136     c->ext_stream_restore.callback = NULL;
137     c->ext_stream_restore.userdata = NULL;
138 }
139
140 pa_context *pa_context_new_with_proplist(pa_mainloop_api *mainloop, const char *name, pa_proplist *p) {
141     pa_context *c;
142
143     pa_assert(mainloop);
144
145     pa_init_i18n();
146
147     if (!name && !pa_proplist_contains(p, PA_PROP_APPLICATION_NAME))
148         return NULL;
149
150     c = pa_xnew(pa_context, 1);
151     PA_REFCNT_INIT(c);
152
153     c->proplist = p ? pa_proplist_copy(p) : pa_proplist_new();
154
155     if (name)
156         pa_proplist_sets(c->proplist, PA_PROP_APPLICATION_NAME, name);
157
158     c->mainloop = mainloop;
159     c->client = NULL;
160     c->pstream = NULL;
161     c->pdispatch = NULL;
162     c->playback_streams = pa_dynarray_new();
163     c->record_streams = pa_dynarray_new();
164     c->client_index = PA_INVALID_INDEX;
165
166     PA_LLIST_HEAD_INIT(pa_stream, c->streams);
167     PA_LLIST_HEAD_INIT(pa_operation, c->operations);
168
169     c->error = PA_OK;
170     c->state = PA_CONTEXT_UNCONNECTED;
171     c->ctag = 0;
172     c->csyncid = 0;
173
174     reset_callbacks(c);
175
176     c->is_local = FALSE;
177     c->server_list = NULL;
178     c->server = NULL;
179
180     c->do_shm = FALSE;
181
182     c->do_autospawn = FALSE;
183     c->autospawn_fd = -1;
184     c->autospawn_locked = FALSE;
185     c->autospawn_event = NULL;
186     memset(&c->spawn_api, 0, sizeof(c->spawn_api));
187
188 #ifndef MSG_NOSIGNAL
189 #ifdef SIGPIPE
190     pa_check_signal_is_blocked(SIGPIPE);
191 #endif
192 #endif
193
194     c->conf = pa_client_conf_new();
195 #ifdef HAVE_X11
196     pa_client_conf_from_x11(c->conf, NULL);
197 #endif
198     pa_client_conf_load(c->conf, NULL);
199     pa_client_conf_env(c->conf);
200
201     if (!(c->mempool = pa_mempool_new(!c->conf->disable_shm))) {
202
203         if (!c->conf->disable_shm)
204             c->mempool = pa_mempool_new(FALSE);
205
206         if (!c->mempool) {
207             context_free(c);
208             return NULL;
209         }
210     }
211
212     return c;
213 }
214
215 static void context_unlink(pa_context *c) {
216     pa_stream *s;
217
218     pa_assert(c);
219
220     s = c->streams ? pa_stream_ref(c->streams) : NULL;
221     while (s) {
222         pa_stream *n = s->next ? pa_stream_ref(s->next) : NULL;
223         pa_stream_set_state(s, c->state == PA_CONTEXT_FAILED ? PA_STREAM_FAILED : PA_STREAM_TERMINATED);
224         pa_stream_unref(s);
225         s = n;
226     }
227
228     while (c->operations)
229         pa_operation_cancel(c->operations);
230
231     if (c->pdispatch) {
232         pa_pdispatch_unref(c->pdispatch);
233         c->pdispatch = NULL;
234     }
235
236     if (c->pstream) {
237         pa_pstream_unlink(c->pstream);
238         pa_pstream_unref(c->pstream);
239         c->pstream = NULL;
240     }
241
242     if (c->client) {
243         pa_socket_client_unref(c->client);
244         c->client = NULL;
245     }
246
247     reset_callbacks(c);
248 }
249
250 static void context_free(pa_context *c) {
251     pa_assert(c);
252
253     context_unlink(c);
254
255     unlock_autospawn(c);
256
257     if (c->record_streams)
258         pa_dynarray_free(c->record_streams, NULL, NULL);
259     if (c->playback_streams)
260         pa_dynarray_free(c->playback_streams, NULL, NULL);
261
262     if (c->mempool)
263         pa_mempool_free(c->mempool);
264
265     if (c->conf)
266         pa_client_conf_free(c->conf);
267
268     pa_strlist_free(c->server_list);
269
270     if (c->proplist)
271         pa_proplist_free(c->proplist);
272
273     pa_xfree(c->server);
274     pa_xfree(c);
275 }
276
277 pa_context* pa_context_ref(pa_context *c) {
278     pa_assert(c);
279     pa_assert(PA_REFCNT_VALUE(c) >= 1);
280
281     PA_REFCNT_INC(c);
282     return c;
283 }
284
285 void pa_context_unref(pa_context *c) {
286     pa_assert(c);
287     pa_assert(PA_REFCNT_VALUE(c) >= 1);
288
289     if (PA_REFCNT_DEC(c) <= 0)
290         context_free(c);
291 }
292
293 void pa_context_set_state(pa_context *c, pa_context_state_t st) {
294     pa_assert(c);
295     pa_assert(PA_REFCNT_VALUE(c) >= 1);
296
297     if (c->state == st)
298         return;
299
300     pa_context_ref(c);
301
302     c->state = st;
303
304     if (c->state_callback)
305         c->state_callback(c, c->state_userdata);
306
307     if (st == PA_CONTEXT_FAILED || st == PA_CONTEXT_TERMINATED)
308         context_unlink(c);
309
310     pa_context_unref(c);
311 }
312
313 int pa_context_set_error(pa_context *c, int error) {
314     pa_assert(error >= 0);
315     pa_assert(error < PA_ERR_MAX);
316
317     if (c)
318         c->error = error;
319
320     return error;
321 }
322
323 void pa_context_fail(pa_context *c, int error) {
324     pa_assert(c);
325     pa_assert(PA_REFCNT_VALUE(c) >= 1);
326
327     pa_context_set_error(c, error);
328     pa_context_set_state(c, PA_CONTEXT_FAILED);
329 }
330
331 static void pstream_die_callback(pa_pstream *p, void *userdata) {
332     pa_context *c = userdata;
333
334     pa_assert(p);
335     pa_assert(c);
336
337     pa_context_fail(c, PA_ERR_CONNECTIONTERMINATED);
338 }
339
340 static void pstream_packet_callback(pa_pstream *p, pa_packet *packet, const pa_creds *creds, void *userdata) {
341     pa_context *c = userdata;
342
343     pa_assert(p);
344     pa_assert(packet);
345     pa_assert(c);
346
347     pa_context_ref(c);
348
349     if (pa_pdispatch_run(c->pdispatch, packet, creds, c) < 0)
350         pa_context_fail(c, PA_ERR_PROTOCOL);
351
352     pa_context_unref(c);
353 }
354
355 static void pstream_memblock_callback(pa_pstream *p, uint32_t channel, int64_t offset, pa_seek_mode_t seek, const pa_memchunk *chunk, void *userdata) {
356     pa_context *c = userdata;
357     pa_stream *s;
358
359     pa_assert(p);
360     pa_assert(chunk);
361     pa_assert(chunk->memblock);
362     pa_assert(chunk->length);
363     pa_assert(c);
364     pa_assert(PA_REFCNT_VALUE(c) >= 1);
365
366     pa_context_ref(c);
367
368     if ((s = pa_dynarray_get(c->record_streams, channel))) {
369
370         pa_assert(seek == PA_SEEK_RELATIVE);
371         pa_assert(offset == 0);
372
373         pa_memblockq_seek(s->record_memblockq, offset, seek);
374         pa_memblockq_push_align(s->record_memblockq, chunk);
375
376         if (s->read_callback) {
377             size_t l;
378
379             if ((l = pa_memblockq_get_length(s->record_memblockq)) > 0)
380                 s->read_callback(s, l, s->read_userdata);
381         }
382     }
383
384     pa_context_unref(c);
385 }
386
387 int pa_context_handle_error(pa_context *c, uint32_t command, pa_tagstruct *t, pa_bool_t fail) {
388     uint32_t err;
389     pa_assert(c);
390     pa_assert(PA_REFCNT_VALUE(c) >= 1);
391
392     if (command == PA_COMMAND_ERROR) {
393         pa_assert(t);
394
395         if (pa_tagstruct_getu32(t, &err) < 0) {
396             pa_context_fail(c, PA_ERR_PROTOCOL);
397             return -1;
398         }
399
400     } else if (command == PA_COMMAND_TIMEOUT)
401         err = PA_ERR_TIMEOUT;
402     else {
403         pa_context_fail(c, PA_ERR_PROTOCOL);
404         return -1;
405     }
406
407     if (err == PA_OK) {
408         pa_context_fail(c, PA_ERR_PROTOCOL);
409         return -1;
410     }
411
412     if (err >= PA_ERR_MAX)
413         err = PA_ERR_UNKNOWN;
414
415     if (fail) {
416         pa_context_fail(c, (int) err);
417         return -1;
418     }
419
420     pa_context_set_error(c, (int) err);
421
422     return 0;
423 }
424
425 static void setup_complete_callback(pa_pdispatch *pd, uint32_t command, uint32_t tag, pa_tagstruct *t, void *userdata) {
426     pa_context *c = userdata;
427
428     pa_assert(pd);
429     pa_assert(c);
430     pa_assert(c->state == PA_CONTEXT_AUTHORIZING || c->state == PA_CONTEXT_SETTING_NAME);
431
432     pa_context_ref(c);
433
434     if (command != PA_COMMAND_REPLY) {
435         pa_context_handle_error(c, command, t, TRUE);
436         goto finish;
437     }
438
439     switch(c->state) {
440         case PA_CONTEXT_AUTHORIZING: {
441             pa_tagstruct *reply;
442             pa_bool_t shm_on_remote = FALSE;
443
444             if (pa_tagstruct_getu32(t, &c->version) < 0 ||
445                 !pa_tagstruct_eof(t)) {
446                 pa_context_fail(c, PA_ERR_PROTOCOL);
447                 goto finish;
448             }
449
450             /* Minimum supported version */
451             if (c->version < 8) {
452                 pa_context_fail(c, PA_ERR_VERSION);
453                 goto finish;
454             }
455
456             /* Starting with protocol version 13 the MSB of the version
457                tag reflects if shm is available for this connection or
458                not. */
459             if (c->version >= 13) {
460                 shm_on_remote = !!(c->version & 0x80000000U);
461                 c->version &= 0x7FFFFFFFU;
462             }
463
464             pa_log_debug("Protocol version: remote %u, local %u", c->version, PA_PROTOCOL_VERSION);
465
466             /* Enable shared memory support if possible */
467             if (c->do_shm)
468                 if (c->version < 10 || (c->version >= 13 && !shm_on_remote))
469                     c->do_shm = FALSE;
470
471             if (c->do_shm) {
472
473                 /* Only enable SHM if both sides are owned by the same
474                  * user. This is a security measure because otherwise
475                  * data private to the user might leak. */
476
477 #ifdef HAVE_CREDS
478                 const pa_creds *creds;
479                 if (!(creds = pa_pdispatch_creds(pd)) || getuid() != creds->uid)
480                     c->do_shm = FALSE;
481 #endif
482             }
483
484             pa_log_debug("Negotiated SHM: %s", pa_yes_no(c->do_shm));
485             pa_pstream_enable_shm(c->pstream, c->do_shm);
486
487             reply = pa_tagstruct_command(c, PA_COMMAND_SET_CLIENT_NAME, &tag);
488
489             if (c->version >= 13) {
490                 pa_init_proplist(c->proplist);
491                 pa_tagstruct_put_proplist(reply, c->proplist);
492             } else
493                 pa_tagstruct_puts(reply, pa_proplist_gets(c->proplist, PA_PROP_APPLICATION_NAME));
494
495             pa_pstream_send_tagstruct(c->pstream, reply);
496             pa_pdispatch_register_reply(c->pdispatch, tag, DEFAULT_TIMEOUT, setup_complete_callback, c, NULL);
497
498             pa_context_set_state(c, PA_CONTEXT_SETTING_NAME);
499             break;
500         }
501
502         case PA_CONTEXT_SETTING_NAME :
503
504             if ((c->version >= 13 && (pa_tagstruct_getu32(t, &c->client_index) < 0 ||
505                                       c->client_index == PA_INVALID_INDEX)) ||
506                 !pa_tagstruct_eof(t)) {
507                 pa_context_fail(c, PA_ERR_PROTOCOL);
508                 goto finish;
509             }
510
511             pa_context_set_state(c, PA_CONTEXT_READY);
512             break;
513
514         default:
515             pa_assert_not_reached();
516     }
517
518 finish:
519     pa_context_unref(c);
520 }
521
522 static void setup_context(pa_context *c, pa_iochannel *io) {
523     pa_tagstruct *t;
524     uint32_t tag;
525
526     pa_assert(c);
527     pa_assert(io);
528
529     pa_context_ref(c);
530
531     pa_assert(!c->pstream);
532     c->pstream = pa_pstream_new(c->mainloop, io, c->mempool);
533
534     pa_pstream_set_die_callback(c->pstream, pstream_die_callback, c);
535     pa_pstream_set_recieve_packet_callback(c->pstream, pstream_packet_callback, c);
536     pa_pstream_set_recieve_memblock_callback(c->pstream, pstream_memblock_callback, c);
537
538     pa_assert(!c->pdispatch);
539     c->pdispatch = pa_pdispatch_new(c->mainloop, command_table, PA_COMMAND_MAX);
540
541     if (!c->conf->cookie_valid)
542         pa_log_info(_("No cookie loaded. Attempting to connect without."));
543
544     t = pa_tagstruct_command(c, PA_COMMAND_AUTH, &tag);
545
546     c->do_shm =
547         pa_mempool_is_shared(c->mempool) &&
548         c->is_local;
549
550     pa_log_debug("SHM possible: %s", pa_yes_no(c->do_shm));
551
552     /* Starting with protocol version 13 we use the MSB of the version
553      * tag for informing the other side if we could do SHM or not */
554     pa_tagstruct_putu32(t, PA_PROTOCOL_VERSION | (c->do_shm ? 0x80000000U : 0));
555     pa_tagstruct_put_arbitrary(t, c->conf->cookie, sizeof(c->conf->cookie));
556
557 #ifdef HAVE_CREDS
558 {
559     pa_creds ucred;
560
561     if (pa_iochannel_creds_supported(io))
562         pa_iochannel_creds_enable(io);
563
564     ucred.uid = getuid();
565     ucred.gid = getgid();
566
567     pa_pstream_send_tagstruct_with_creds(c->pstream, t, &ucred);
568 }
569 #else
570     pa_pstream_send_tagstruct(c->pstream, t);
571 #endif
572
573     pa_pdispatch_register_reply(c->pdispatch, tag, DEFAULT_TIMEOUT, setup_complete_callback, c, NULL);
574
575     pa_context_set_state(c, PA_CONTEXT_AUTHORIZING);
576
577     pa_context_unref(c);
578 }
579
580 static void on_connection(pa_socket_client *client, pa_iochannel*io, void *userdata);
581
582 #ifndef OS_IS_WIN32
583
584 static int context_connect_spawn(pa_context *c) {
585     pid_t pid;
586     int status, r;
587     int fds[2] = { -1, -1} ;
588     pa_iochannel *io;
589
590     if (getuid() == 0)
591         return -1;
592
593     pa_context_ref(c);
594
595     if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) < 0) {
596         pa_log_error(_("socketpair(): %s"), pa_cstrerror(errno));
597         pa_context_fail(c, PA_ERR_INTERNAL);
598         goto fail;
599     }
600
601     pa_make_fd_cloexec(fds[0]);
602
603     pa_make_socket_low_delay(fds[0]);
604     pa_make_socket_low_delay(fds[1]);
605
606     if (c->spawn_api.prefork)
607         c->spawn_api.prefork();
608
609     if ((pid = fork()) < 0) {
610         pa_log_error(_("fork(): %s"), pa_cstrerror(errno));
611         pa_context_fail(c, PA_ERR_INTERNAL);
612
613         if (c->spawn_api.postfork)
614             c->spawn_api.postfork();
615
616         goto fail;
617     } else if (!pid) {
618         /* Child */
619
620         char t[128];
621         const char *state = NULL;
622 #define MAX_ARGS 64
623         const char * argv[MAX_ARGS+1];
624         int n;
625         char *f;
626
627         pa_close_all(fds[1], -1);
628
629         f = pa_sprintf_malloc("%i", fds[1]);
630         pa_set_env("PULSE_PASSED_FD", f);
631         pa_xfree(f);
632
633         if (c->spawn_api.atfork)
634             c->spawn_api.atfork();
635
636         /* Setup argv */
637
638         n = 0;
639
640         argv[n++] = c->conf->daemon_binary;
641         argv[n++] = "--daemonize=yes";
642
643         pa_snprintf(t, sizeof(t), "-Lmodule-native-protocol-fd fd=%i", fds[1]);
644         argv[n++] = strdup(t);
645
646         while (n < MAX_ARGS) {
647             char *a;
648
649             if (!(a = pa_split_spaces(c->conf->extra_arguments, &state)))
650                 break;
651
652             argv[n++] = a;
653         }
654
655         argv[n++] = NULL;
656
657         execv(argv[0], (char * const *) argv);
658         _exit(1);
659 #undef MAX_ARGS
660     }
661
662     /* Parent */
663
664     pa_assert_se(pa_close(fds[1]) == 0);
665     fds[1] = -1;
666
667     r = waitpid(pid, &status, 0);
668
669     if (c->spawn_api.postfork)
670         c->spawn_api.postfork();
671
672     if (r < 0) {
673         pa_log(_("waitpid(): %s"), pa_cstrerror(errno));
674         pa_context_fail(c, PA_ERR_INTERNAL);
675         goto fail;
676     } else if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
677         pa_context_fail(c, PA_ERR_CONNECTIONREFUSED);
678         goto fail;
679     }
680
681     c->is_local = TRUE;
682
683     unlock_autospawn(c);
684
685     io = pa_iochannel_new(c->mainloop, fds[0], fds[0]);
686     setup_context(c, io);
687
688     pa_context_unref(c);
689
690     return 0;
691
692 fail:
693     pa_close_pipe(fds);
694
695     unlock_autospawn(c);
696
697     pa_context_unref(c);
698
699     return -1;
700 }
701
702 #endif /* OS_IS_WIN32 */
703
704 static int try_next_connection(pa_context *c) {
705     char *u = NULL;
706     int r = -1;
707
708     pa_assert(c);
709     pa_assert(!c->client);
710
711     for (;;) {
712         pa_xfree(u);
713         u = NULL;
714
715         c->server_list = pa_strlist_pop(c->server_list, &u);
716
717         if (!u) {
718
719 #ifndef OS_IS_WIN32
720             if (c->do_autospawn) {
721                 r = context_connect_spawn(c);
722                 goto finish;
723             }
724 #endif
725
726             pa_context_fail(c, PA_ERR_CONNECTIONREFUSED);
727             goto finish;
728         }
729
730         pa_log_debug("Trying to connect to %s...", u);
731
732         pa_xfree(c->server);
733         c->server = pa_xstrdup(u);
734
735         if (!(c->client = pa_socket_client_new_string(c->mainloop, u, PA_NATIVE_DEFAULT_PORT)))
736             continue;
737
738         c->is_local = !!pa_socket_client_is_local(c->client);
739         pa_socket_client_set_callback(c->client, on_connection, c);
740         break;
741     }
742
743     r = 0;
744
745 finish:
746     pa_xfree(u);
747
748     return r;
749 }
750
751 static void on_connection(pa_socket_client *client, pa_iochannel*io, void *userdata) {
752     pa_context *c = userdata;
753     int saved_errno = errno;
754
755     pa_assert(client);
756     pa_assert(c);
757     pa_assert(c->state == PA_CONTEXT_CONNECTING);
758
759     pa_context_ref(c);
760
761     pa_socket_client_unref(client);
762     c->client = NULL;
763
764     if (!io) {
765         /* Try the item in the list */
766         if (saved_errno == ECONNREFUSED ||
767             saved_errno == ETIMEDOUT ||
768             saved_errno == EHOSTUNREACH) {
769             try_next_connection(c);
770             goto finish;
771         }
772
773         pa_context_fail(c, PA_ERR_CONNECTIONREFUSED);
774         goto finish;
775     }
776
777     unlock_autospawn(c);
778     setup_context(c, io);
779
780 finish:
781     pa_context_unref(c);
782 }
783
784 static void autospawn_cb(pa_mainloop_api*a, pa_io_event *e, int fd, pa_io_event_flags_t events, void *userdata) {
785     pa_context *c = userdata;
786     int k;
787
788     pa_assert(a);
789     pa_assert(e);
790     pa_assert(fd >= 0);
791     pa_assert(events == PA_IO_EVENT_INPUT);
792     pa_assert(c);
793     pa_assert(e == c->autospawn_event);
794     pa_assert(fd == c->autospawn_fd);
795
796     pa_context_ref(c);
797
798     /* Check whether we can get the lock right now*/
799     if ((k = pa_autospawn_lock_acquire(FALSE)) < 0) {
800         pa_context_fail(c, PA_ERR_ACCESS);
801         goto finish;
802     }
803
804     if (k > 0) {
805         /* So we got it, rock on! */
806         c->autospawn_locked = TRUE;
807         try_next_connection(c);
808
809         c->mainloop->io_free(c->autospawn_event);
810         c->autospawn_event = NULL;
811     }
812
813 finish:
814
815     pa_context_unref(c);
816 }
817
818 static char *get_old_legacy_runtime_dir(void) {
819     char *p, u[128];
820     struct stat st;
821
822     if (!pa_get_user_name(u, sizeof(u)))
823         return NULL;
824
825     p = pa_sprintf_malloc("/tmp/pulse-%s", u);
826
827     if (stat(p, &st) < 0) {
828         pa_xfree(p);
829         return NULL;
830     }
831
832     if (st.st_uid != getuid()) {
833         pa_xfree(p);
834         return NULL;
835     }
836
837     return p;
838 }
839
840 static char *get_very_old_legacy_runtime_dir(void) {
841     char *p, h[128];
842     struct stat st;
843
844     if (!pa_get_home_dir(h, sizeof(h)))
845         return NULL;
846
847     p = pa_sprintf_malloc("%s/.pulse", h);
848
849     if (stat(p, &st) < 0) {
850         pa_xfree(p);
851         return NULL;
852     }
853
854     if (st.st_uid != getuid()) {
855         pa_xfree(p);
856         return NULL;
857     }
858
859     return p;
860 }
861
862 int pa_context_connect(
863         pa_context *c,
864         const char *server,
865         pa_context_flags_t flags,
866         const pa_spawn_api *api) {
867
868     int r = -1;
869
870     pa_assert(c);
871     pa_assert(PA_REFCNT_VALUE(c) >= 1);
872
873     PA_CHECK_VALIDITY(c, c->state == PA_CONTEXT_UNCONNECTED, PA_ERR_BADSTATE);
874     PA_CHECK_VALIDITY(c, !(flags & ~PA_CONTEXT_NOAUTOSPAWN), PA_ERR_INVALID);
875     PA_CHECK_VALIDITY(c, !server || *server, PA_ERR_INVALID);
876
877     if (!server)
878         server = c->conf->default_server;
879
880     pa_context_ref(c);
881
882     pa_assert(!c->server_list);
883
884     if (server) {
885         if (!(c->server_list = pa_strlist_parse(server))) {
886             pa_context_fail(c, PA_ERR_INVALIDSERVER);
887             goto finish;
888         }
889
890     } else {
891         char *d, *ufn;
892         static char *legacy_dir;
893
894         /* Prepend in reverse order */
895
896         if ((d = getenv("DISPLAY"))) {
897             char *e;
898             d = pa_xstrdup(d);
899             if ((e = strchr(d, ':')))
900                 *e = 0;
901
902             if (*d)
903                 c->server_list = pa_strlist_prepend(c->server_list, d);
904
905             pa_xfree(d);
906         }
907
908         /* Add TCP/IP on the localhost */
909         c->server_list = pa_strlist_prepend(c->server_list, "tcp6:[::1]");
910         c->server_list = pa_strlist_prepend(c->server_list, "tcp4:127.0.0.1");
911
912         /* The system wide instance */
913         c->server_list = pa_strlist_prepend(c->server_list, PA_SYSTEM_RUNTIME_PATH PA_PATH_SEP PA_NATIVE_DEFAULT_UNIX_SOCKET);
914
915         /* The very old per-user instance path (< 0.9.11). This is supported only to ease upgrades */
916         if ((legacy_dir = get_very_old_legacy_runtime_dir())) {
917             char *p = pa_sprintf_malloc("%s" PA_PATH_SEP PA_NATIVE_DEFAULT_UNIX_SOCKET, legacy_dir);
918             c->server_list = pa_strlist_prepend(c->server_list, p);
919             pa_xfree(p);
920             pa_xfree(legacy_dir);
921         }
922
923         /* The old per-user instance path (< 0.9.12). This is supported only to ease upgrades */
924         if ((legacy_dir = get_old_legacy_runtime_dir())) {
925             char *p = pa_sprintf_malloc("%s" PA_PATH_SEP PA_NATIVE_DEFAULT_UNIX_SOCKET, legacy_dir);
926             c->server_list = pa_strlist_prepend(c->server_list, p);
927             pa_xfree(p);
928             pa_xfree(legacy_dir);
929         }
930
931         /* The per-user instance */
932         if ((ufn = pa_runtime_path(PA_NATIVE_DEFAULT_UNIX_SOCKET))) {
933             c->server_list = pa_strlist_prepend(c->server_list, ufn);
934             pa_xfree(ufn);
935         }
936
937         /* Wrap the connection attempts in a single transaction for sane autospawn locking */
938         if (!(flags & PA_CONTEXT_NOAUTOSPAWN) && c->conf->autospawn) {
939             int k;
940
941             pa_assert(c->autospawn_fd < 0);
942             pa_assert(!c->autospawn_locked);
943
944             /* Start the locking procedure */
945             if ((c->autospawn_fd = pa_autospawn_lock_init()) < 0) {
946                 pa_context_fail(c, PA_ERR_ACCESS);
947                 goto finish;
948             }
949
950             if (api)
951                 c->spawn_api = *api;
952
953             c->do_autospawn = TRUE;
954
955             /* Check whether we can get the lock right now*/
956             if ((k = pa_autospawn_lock_acquire(FALSE)) < 0) {
957                 pa_context_fail(c, PA_ERR_ACCESS);
958                 goto finish;
959             }
960
961             if (k > 0)
962                 /* So we got it, rock on! */
963                 c->autospawn_locked = TRUE;
964             else {
965                 /* Hmm, we didn't get it, so let's wait for it */
966                 c->autospawn_event = c->mainloop->io_new(c->mainloop, c->autospawn_fd, PA_IO_EVENT_INPUT, autospawn_cb, c);
967
968                 pa_context_set_state(c, PA_CONTEXT_CONNECTING);
969                 r = 0;
970                 goto finish;
971             }
972
973         }
974     }
975
976     pa_context_set_state(c, PA_CONTEXT_CONNECTING);
977     r = try_next_connection(c);
978
979 finish:
980     pa_context_unref(c);
981
982     return r;
983 }
984
985 void pa_context_disconnect(pa_context *c) {
986     pa_assert(c);
987     pa_assert(PA_REFCNT_VALUE(c) >= 1);
988
989     if (PA_CONTEXT_IS_GOOD(c->state))
990         pa_context_set_state(c, PA_CONTEXT_TERMINATED);
991 }
992
993 pa_context_state_t pa_context_get_state(pa_context *c) {
994     pa_assert(c);
995     pa_assert(PA_REFCNT_VALUE(c) >= 1);
996
997     return c->state;
998 }
999
1000 int pa_context_errno(pa_context *c) {
1001     pa_assert(c);
1002     pa_assert(PA_REFCNT_VALUE(c) >= 1);
1003
1004     return c->error;
1005 }
1006
1007 void pa_context_set_state_callback(pa_context *c, pa_context_notify_cb_t cb, void *userdata) {
1008     pa_assert(c);
1009     pa_assert(PA_REFCNT_VALUE(c) >= 1);
1010
1011     if (c->state == PA_CONTEXT_TERMINATED || c->state == PA_CONTEXT_FAILED)
1012         return;
1013
1014     c->state_callback = cb;
1015     c->state_userdata = userdata;
1016 }
1017
1018 int pa_context_is_pending(pa_context *c) {
1019     pa_assert(c);
1020     pa_assert(PA_REFCNT_VALUE(c) >= 1);
1021
1022     PA_CHECK_VALIDITY(c, PA_CONTEXT_IS_GOOD(c->state), PA_ERR_BADSTATE);
1023
1024     return (c->pstream && pa_pstream_is_pending(c->pstream)) ||
1025         (c->pdispatch && pa_pdispatch_is_pending(c->pdispatch)) ||
1026         c->client;
1027 }
1028
1029 static void set_dispatch_callbacks(pa_operation *o);
1030
1031 static void pdispatch_drain_callback(pa_pdispatch*pd, void *userdata) {
1032     set_dispatch_callbacks(userdata);
1033 }
1034
1035 static void pstream_drain_callback(pa_pstream *s, void *userdata) {
1036     set_dispatch_callbacks(userdata);
1037 }
1038
1039 static void set_dispatch_callbacks(pa_operation *o) {
1040     int done = 1;
1041
1042     pa_assert(o);
1043     pa_assert(PA_REFCNT_VALUE(o) >= 1);
1044     pa_assert(o->context);
1045     pa_assert(PA_REFCNT_VALUE(o->context) >= 1);
1046     pa_assert(o->context->state == PA_CONTEXT_READY);
1047
1048     pa_pstream_set_drain_callback(o->context->pstream, NULL, NULL);
1049     pa_pdispatch_set_drain_callback(o->context->pdispatch, NULL, NULL);
1050
1051     if (pa_pdispatch_is_pending(o->context->pdispatch)) {
1052         pa_pdispatch_set_drain_callback(o->context->pdispatch, pdispatch_drain_callback, o);
1053         done = 0;
1054     }
1055
1056     if (pa_pstream_is_pending(o->context->pstream)) {
1057         pa_pstream_set_drain_callback(o->context->pstream, pstream_drain_callback, o);
1058         done = 0;
1059     }
1060
1061     if (done) {
1062         if (o->callback) {
1063             pa_context_notify_cb_t cb = (pa_context_notify_cb_t) o->callback;
1064             cb(o->context, o->userdata);
1065         }
1066
1067         pa_operation_done(o);
1068         pa_operation_unref(o);
1069     }
1070 }
1071
1072 pa_operation* pa_context_drain(pa_context *c, pa_context_notify_cb_t cb, void *userdata) {
1073     pa_operation *o;
1074
1075     pa_assert(c);
1076     pa_assert(PA_REFCNT_VALUE(c) >= 1);
1077
1078     PA_CHECK_VALIDITY_RETURN_NULL(c, c->state == PA_CONTEXT_READY, PA_ERR_BADSTATE);
1079     PA_CHECK_VALIDITY_RETURN_NULL(c, pa_context_is_pending(c), PA_ERR_BADSTATE);
1080
1081     o = pa_operation_new(c, NULL, (pa_operation_cb_t) cb, userdata);
1082     set_dispatch_callbacks(pa_operation_ref(o));
1083
1084     return o;
1085 }
1086
1087 void pa_context_simple_ack_callback(pa_pdispatch *pd, uint32_t command, uint32_t tag, pa_tagstruct *t, void *userdata) {
1088     pa_operation *o = userdata;
1089     int success = 1;
1090
1091     pa_assert(pd);
1092     pa_assert(o);
1093     pa_assert(PA_REFCNT_VALUE(o) >= 1);
1094
1095     if (!o->context)
1096         goto finish;
1097
1098     if (command != PA_COMMAND_REPLY) {
1099         if (pa_context_handle_error(o->context, command, t, FALSE) < 0)
1100             goto finish;
1101
1102         success = 0;
1103     } else if (!pa_tagstruct_eof(t)) {
1104         pa_context_fail(o->context, PA_ERR_PROTOCOL);
1105         goto finish;
1106     }
1107
1108     if (o->callback) {
1109         pa_context_success_cb_t cb = (pa_context_success_cb_t) o->callback;
1110         cb(o->context, success, o->userdata);
1111     }
1112
1113 finish:
1114     pa_operation_done(o);
1115     pa_operation_unref(o);
1116 }
1117
1118 pa_operation* pa_context_send_simple_command(pa_context *c, uint32_t command, pa_pdispatch_cb_t internal_cb, pa_operation_cb_t cb, void *userdata) {
1119     pa_tagstruct *t;
1120     pa_operation *o;
1121     uint32_t tag;
1122
1123     pa_assert(c);
1124     pa_assert(PA_REFCNT_VALUE(c) >= 1);
1125
1126     PA_CHECK_VALIDITY_RETURN_NULL(c, c->state == PA_CONTEXT_READY, PA_ERR_BADSTATE);
1127
1128     o = pa_operation_new(c, NULL, cb, userdata);
1129
1130     t = pa_tagstruct_command(c, command, &tag);
1131     pa_pstream_send_tagstruct(c->pstream, t);
1132     pa_pdispatch_register_reply(c->pdispatch, tag, DEFAULT_TIMEOUT, internal_cb, pa_operation_ref(o), (pa_free_cb_t) pa_operation_unref);
1133
1134     return o;
1135 }
1136
1137 pa_operation* pa_context_exit_daemon(pa_context *c, pa_context_success_cb_t cb, void *userdata) {
1138     pa_assert(c);
1139     pa_assert(PA_REFCNT_VALUE(c) >= 1);
1140
1141     return pa_context_send_simple_command(c, PA_COMMAND_EXIT, pa_context_simple_ack_callback, (pa_operation_cb_t) cb, userdata);
1142 }
1143
1144 pa_operation* pa_context_set_default_sink(pa_context *c, const char *name, pa_context_success_cb_t cb, void *userdata) {
1145     pa_tagstruct *t;
1146     pa_operation *o;
1147     uint32_t tag;
1148
1149     pa_assert(c);
1150     pa_assert(PA_REFCNT_VALUE(c) >= 1);
1151
1152     PA_CHECK_VALIDITY_RETURN_NULL(c, c->state == PA_CONTEXT_READY, PA_ERR_BADSTATE);
1153
1154     o = pa_operation_new(c, NULL, (pa_operation_cb_t) cb, userdata);
1155     t = pa_tagstruct_command(c, PA_COMMAND_SET_DEFAULT_SINK, &tag);
1156     pa_tagstruct_puts(t, name);
1157     pa_pstream_send_tagstruct(c->pstream, t);
1158     pa_pdispatch_register_reply(c->pdispatch, tag, DEFAULT_TIMEOUT,  pa_context_simple_ack_callback, pa_operation_ref(o), (pa_free_cb_t) pa_operation_unref);
1159
1160     return o;
1161 }
1162
1163 pa_operation* pa_context_set_default_source(pa_context *c, const char *name, pa_context_success_cb_t cb, void *userdata) {
1164     pa_tagstruct *t;
1165     pa_operation *o;
1166     uint32_t tag;
1167
1168     pa_assert(c);
1169     pa_assert(PA_REFCNT_VALUE(c) >= 1);
1170
1171     PA_CHECK_VALIDITY_RETURN_NULL(c, c->state == PA_CONTEXT_READY, PA_ERR_BADSTATE);
1172
1173     o = pa_operation_new(c, NULL, (pa_operation_cb_t) cb, userdata);
1174     t = pa_tagstruct_command(c, PA_COMMAND_SET_DEFAULT_SOURCE, &tag);
1175     pa_tagstruct_puts(t, name);
1176     pa_pstream_send_tagstruct(c->pstream, t);
1177     pa_pdispatch_register_reply(c->pdispatch, tag, DEFAULT_TIMEOUT,  pa_context_simple_ack_callback, pa_operation_ref(o), (pa_free_cb_t) pa_operation_unref);
1178
1179     return o;
1180 }
1181
1182 int pa_context_is_local(pa_context *c) {
1183     pa_assert(c);
1184     pa_assert(PA_REFCNT_VALUE(c) >= 1);
1185
1186     PA_CHECK_VALIDITY_RETURN_ANY(c, PA_CONTEXT_IS_GOOD(c->state), PA_ERR_BADSTATE, -1);
1187
1188     return !!c->is_local;
1189 }
1190
1191 pa_operation* pa_context_set_name(pa_context *c, const char *name, pa_context_success_cb_t cb, void *userdata) {
1192     pa_operation *o;
1193
1194     pa_assert(c);
1195     pa_assert(PA_REFCNT_VALUE(c) >= 1);
1196     pa_assert(name);
1197
1198     PA_CHECK_VALIDITY_RETURN_NULL(c, c->state == PA_CONTEXT_READY, PA_ERR_BADSTATE);
1199
1200     if (c->version >= 13) {
1201         pa_proplist *p = pa_proplist_new();
1202
1203         pa_proplist_sets(p, PA_PROP_APPLICATION_NAME, name);
1204         o = pa_context_proplist_update(c, PA_UPDATE_REPLACE, p, cb, userdata);
1205         pa_proplist_free(p);
1206     } else {
1207         pa_tagstruct *t;
1208         uint32_t tag;
1209
1210         o = pa_operation_new(c, NULL, (pa_operation_cb_t) cb, userdata);
1211         t = pa_tagstruct_command(c, PA_COMMAND_SET_CLIENT_NAME, &tag);
1212         pa_tagstruct_puts(t, name);
1213         pa_pstream_send_tagstruct(c->pstream, t);
1214         pa_pdispatch_register_reply(c->pdispatch, tag, DEFAULT_TIMEOUT,  pa_context_simple_ack_callback, pa_operation_ref(o), (pa_free_cb_t) pa_operation_unref);
1215     }
1216
1217     return o;
1218 }
1219
1220 const char* pa_get_library_version(void) {
1221     return PACKAGE_VERSION;
1222 }
1223
1224 const char* pa_context_get_server(pa_context *c) {
1225     pa_assert(c);
1226     pa_assert(PA_REFCNT_VALUE(c) >= 1);
1227
1228     if (!c->server)
1229         return NULL;
1230
1231     if (*c->server == '{') {
1232         char *e = strchr(c->server+1, '}');
1233         return e ? e+1 : c->server;
1234     }
1235
1236     return c->server;
1237 }
1238
1239 uint32_t pa_context_get_protocol_version(pa_context *c) {
1240     return PA_PROTOCOL_VERSION;
1241 }
1242
1243 uint32_t pa_context_get_server_protocol_version(pa_context *c) {
1244     pa_assert(c);
1245     pa_assert(PA_REFCNT_VALUE(c) >= 1);
1246
1247     PA_CHECK_VALIDITY_RETURN_ANY(c, PA_CONTEXT_IS_GOOD(c->state), PA_ERR_BADSTATE, PA_INVALID_INDEX);
1248
1249     return c->version;
1250 }
1251
1252 pa_tagstruct *pa_tagstruct_command(pa_context *c, uint32_t command, uint32_t *tag) {
1253     pa_tagstruct *t;
1254
1255     pa_assert(c);
1256     pa_assert(tag);
1257
1258     t = pa_tagstruct_new(NULL, 0);
1259     pa_tagstruct_putu32(t, command);
1260     pa_tagstruct_putu32(t, *tag = c->ctag++);
1261
1262     return t;
1263 }
1264
1265 uint32_t pa_context_get_index(pa_context *c) {
1266     pa_assert(c);
1267     pa_assert(PA_REFCNT_VALUE(c) >= 1);
1268
1269     PA_CHECK_VALIDITY_RETURN_ANY(c, c->state == PA_CONTEXT_READY, PA_ERR_BADSTATE, PA_INVALID_INDEX);
1270     PA_CHECK_VALIDITY_RETURN_ANY(c, c->version >= 13, PA_ERR_NOTSUPPORTED, PA_INVALID_INDEX);
1271
1272     return c->client_index;
1273 }
1274
1275 pa_operation *pa_context_proplist_update(pa_context *c, pa_update_mode_t mode, pa_proplist *p, pa_context_success_cb_t cb, void *userdata) {
1276     pa_operation *o;
1277     pa_tagstruct *t;
1278     uint32_t tag;
1279
1280     pa_assert(c);
1281     pa_assert(PA_REFCNT_VALUE(c) >= 1);
1282
1283     PA_CHECK_VALIDITY_RETURN_NULL(c, mode == PA_UPDATE_SET || mode == PA_UPDATE_MERGE || mode == PA_UPDATE_REPLACE, PA_ERR_INVALID);
1284     PA_CHECK_VALIDITY_RETURN_NULL(c, c->state == PA_CONTEXT_READY, PA_ERR_BADSTATE);
1285     PA_CHECK_VALIDITY_RETURN_NULL(c, c->version >= 13, PA_ERR_NOTSUPPORTED);
1286
1287     o = pa_operation_new(c, NULL, (pa_operation_cb_t) cb, userdata);
1288
1289     t = pa_tagstruct_command(c, PA_COMMAND_UPDATE_CLIENT_PROPLIST, &tag);
1290     pa_tagstruct_putu32(t, (uint32_t) mode);
1291     pa_tagstruct_put_proplist(t, p);
1292
1293     pa_pstream_send_tagstruct(c->pstream, t);
1294     pa_pdispatch_register_reply(c->pdispatch, tag, DEFAULT_TIMEOUT, pa_context_simple_ack_callback, pa_operation_ref(o), (pa_free_cb_t) pa_operation_unref);
1295
1296     /* Please note that we don't update c->proplist here, because we
1297      * don't export that field */
1298
1299     return o;
1300 }
1301
1302 pa_operation *pa_context_proplist_remove(pa_context *c, const char *const keys[], pa_context_success_cb_t cb, void *userdata) {
1303     pa_operation *o;
1304     pa_tagstruct *t;
1305     uint32_t tag;
1306     const char * const *k;
1307
1308     pa_assert(c);
1309     pa_assert(PA_REFCNT_VALUE(c) >= 1);
1310
1311     PA_CHECK_VALIDITY_RETURN_NULL(c, keys && keys[0], PA_ERR_INVALID);
1312     PA_CHECK_VALIDITY_RETURN_NULL(c, c->state == PA_CONTEXT_READY, PA_ERR_BADSTATE);
1313     PA_CHECK_VALIDITY_RETURN_NULL(c, c->version >= 13, PA_ERR_NOTSUPPORTED);
1314
1315     o = pa_operation_new(c, NULL, (pa_operation_cb_t) cb, userdata);
1316
1317     t = pa_tagstruct_command(c, PA_COMMAND_REMOVE_CLIENT_PROPLIST, &tag);
1318
1319     for (k = keys; *k; k++)
1320         pa_tagstruct_puts(t, *k);
1321
1322     pa_tagstruct_puts(t, NULL);
1323
1324     pa_pstream_send_tagstruct(c->pstream, t);
1325     pa_pdispatch_register_reply(c->pdispatch, tag, DEFAULT_TIMEOUT, pa_context_simple_ack_callback, pa_operation_ref(o), (pa_free_cb_t) pa_operation_unref);
1326
1327     /* Please note that we don't update c->proplist here, because we
1328      * don't export that field */
1329
1330     return o;
1331 }
1332
1333 void pa_command_extension(pa_pdispatch *pd, uint32_t command, uint32_t tag, pa_tagstruct *t, void *userdata) {
1334     pa_context *c = userdata;
1335     uint32_t idx;
1336     const char *name;
1337
1338     pa_assert(pd);
1339     pa_assert(command == PA_COMMAND_EXTENSION);
1340     pa_assert(t);
1341     pa_assert(c);
1342     pa_assert(PA_REFCNT_VALUE(c) >= 1);
1343
1344     pa_context_ref(c);
1345
1346     if (pa_tagstruct_getu32(t, &idx) < 0 ||
1347         pa_tagstruct_gets(t, &name) < 0) {
1348         pa_context_fail(c, PA_ERR_PROTOCOL);
1349         goto finish;
1350     }
1351
1352     if (!strcmp(name, "module-stream-restore"))
1353         pa_ext_stream_restore_command(c, tag, t);
1354     else
1355         pa_log(_("Received message for unknown extension '%s'"), name);
1356
1357 finish:
1358     pa_context_unref(c);
1359 }