Add copyright notices to all relevant files. (based on svn log)
[profile/ivi/pulseaudio.git] / src / pulse / context.c
1 /* $Id$ */
2
3 /***
4   This file is part of PulseAudio.
5
6   Copyright 2004-2006 Lennart Poettering
7   Copyright 2006 Pierre Ossman <ossman@cendio.se> for Cendio AB
8
9   PulseAudio is free software; you can redistribute it and/or modify
10   it under the terms of the GNU Lesser General Public License as published
11   by the Free Software Foundation; either version 2 of the License,
12   or (at your option) any later version.
13
14   PulseAudio is distributed in the hope that it will be useful, but
15   WITHOUT ANY WARRANTY; without even the implied warranty of
16   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17   General Public License for more details.
18
19   You should have received a copy of the GNU Lesser General Public License
20   along with PulseAudio; if not, write to the Free Software
21   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
22   USA.
23 ***/
24
25 #ifdef HAVE_CONFIG_H
26 #include <config.h>
27 #endif
28
29 #include <stdio.h>
30 #include <assert.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <sys/types.h>
34 #include <unistd.h>
35 #include <sys/stat.h>
36 #include <errno.h>
37 #include <signal.h>
38 #include <limits.h>
39
40 #ifdef HAVE_SYS_WAIT_H
41 #include <sys/wait.h>
42 #endif
43
44 #ifdef HAVE_SYS_SOCKET_H
45 #include <sys/socket.h>
46 #endif
47 #ifdef HAVE_SYS_UN_H
48 #include <sys/un.h>
49 #endif
50 #ifdef HAVE_NETDB_H
51 #include <netdb.h>
52 #endif
53
54 #include "../pulsecore/winsock.h"
55
56 #include <pulsecore/core-error.h>
57 #include <pulse/version.h>
58 #include <pulse/xmalloc.h>
59
60 #include <pulsecore/native-common.h>
61 #include <pulsecore/pdispatch.h>
62 #include <pulsecore/pstream.h>
63 #include <pulsecore/dynarray.h>
64 #include <pulsecore/socket-client.h>
65 #include <pulsecore/pstream-util.h>
66 #include <pulsecore/core-util.h>
67 #include <pulsecore/log.h>
68 #include <pulsecore/socket-util.h>
69 #include <pulsecore/creds.h>
70
71 #include "internal.h"
72
73 #include "client-conf.h"
74
75 #ifdef HAVE_X11
76 #include "client-conf-x11.h"
77 #endif
78
79 #include "context.h"
80
81 #define AUTOSPAWN_LOCK "autospawn.lock"
82
83 static const pa_pdispatch_cb_t command_table[PA_COMMAND_MAX] = {
84     [PA_COMMAND_REQUEST] = pa_command_request,
85     [PA_COMMAND_OVERFLOW] = pa_command_overflow_or_underflow,
86     [PA_COMMAND_UNDERFLOW] = pa_command_overflow_or_underflow,
87     [PA_COMMAND_PLAYBACK_STREAM_KILLED] = pa_command_stream_killed,
88     [PA_COMMAND_RECORD_STREAM_KILLED] = pa_command_stream_killed,
89     [PA_COMMAND_SUBSCRIBE_EVENT] = pa_command_subscribe_event
90 };
91
92 static void unlock_autospawn_lock_file(pa_context *c) {
93     assert(c);
94
95     if (c->autospawn_lock_fd >= 0) {
96         char lf[PATH_MAX];
97         pa_runtime_path(AUTOSPAWN_LOCK, lf, sizeof(lf));
98
99         pa_unlock_lockfile(lf, c->autospawn_lock_fd);
100         c->autospawn_lock_fd = -1;
101     }
102 }
103
104 static void context_free(pa_context *c);
105
106 pa_context *pa_context_new(pa_mainloop_api *mainloop, const char *name) {
107     pa_context *c;
108
109     assert(mainloop);
110     assert(name);
111
112     c = pa_xnew(pa_context, 1);
113     c->ref = 1;
114     c->name = pa_xstrdup(name);
115     c->mainloop = mainloop;
116     c->client = NULL;
117     c->pstream = NULL;
118     c->pdispatch = NULL;
119     c->playback_streams = pa_dynarray_new();
120     c->record_streams = pa_dynarray_new();
121
122     PA_LLIST_HEAD_INIT(pa_stream, c->streams);
123     PA_LLIST_HEAD_INIT(pa_operation, c->operations);
124
125     c->error = PA_OK;
126     c->state = PA_CONTEXT_UNCONNECTED;
127     c->ctag = 0;
128     c->csyncid = 0;
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->is_local = -1;
137     c->server_list = NULL;
138     c->server = NULL;
139     c->autospawn_lock_fd = -1;
140     memset(&c->spawn_api, 0, sizeof(c->spawn_api));
141     c->do_autospawn = 0;
142
143 #ifndef MSG_NOSIGNAL
144 #ifdef SIGPIPE
145     pa_check_signal_is_blocked(SIGPIPE);
146 #endif
147 #endif
148
149     c->conf = pa_client_conf_new();
150     pa_client_conf_load(c->conf, NULL);
151 #ifdef HAVE_X11
152     pa_client_conf_from_x11(c->conf, NULL);
153 #endif
154     pa_client_conf_env(c->conf);
155
156     if (!(c->mempool = pa_mempool_new(!c->conf->disable_shm))) {
157
158         if (!c->conf->disable_shm)
159             c->mempool = pa_mempool_new(0);
160
161         if (!c->mempool) {
162             context_free(c);
163             return NULL;
164         }
165     }
166
167     return c;
168 }
169
170 static void context_free(pa_context *c) {
171     assert(c);
172
173     unlock_autospawn_lock_file(c);
174
175     while (c->operations)
176         pa_operation_cancel(c->operations);
177
178     while (c->streams)
179         pa_stream_set_state(c->streams, PA_STREAM_TERMINATED);
180
181     if (c->client)
182         pa_socket_client_unref(c->client);
183     if (c->pdispatch)
184         pa_pdispatch_unref(c->pdispatch);
185     if (c->pstream) {
186         pa_pstream_close(c->pstream);
187         pa_pstream_unref(c->pstream);
188     }
189
190     if (c->record_streams)
191         pa_dynarray_free(c->record_streams, NULL, NULL);
192     if (c->playback_streams)
193         pa_dynarray_free(c->playback_streams, NULL, NULL);
194
195     if (c->mempool)
196         pa_mempool_free(c->mempool);
197
198     if (c->conf)
199         pa_client_conf_free(c->conf);
200
201     pa_strlist_free(c->server_list);
202
203     pa_xfree(c->name);
204     pa_xfree(c->server);
205     pa_xfree(c);
206 }
207
208 pa_context* pa_context_ref(pa_context *c) {
209     assert(c);
210     assert(c->ref >= 1);
211
212     c->ref++;
213     return c;
214 }
215
216 void pa_context_unref(pa_context *c) {
217     assert(c);
218     assert(c->ref >= 1);
219
220     if (--c->ref <= 0)
221         context_free(c);
222 }
223
224 void pa_context_set_state(pa_context *c, pa_context_state_t st) {
225     assert(c);
226     assert(c->ref >= 1);
227
228     if (c->state == st)
229         return;
230
231     pa_context_ref(c);
232
233     c->state = st;
234     if (c->state_callback)
235         c->state_callback(c, c->state_userdata);
236
237     if (st == PA_CONTEXT_FAILED || st == PA_CONTEXT_TERMINATED) {
238         pa_stream *s;
239
240         s = c->streams ? pa_stream_ref(c->streams) : NULL;
241         while (s) {
242             pa_stream *n = s->next ? pa_stream_ref(s->next) : NULL;
243             pa_stream_set_state(s, st == PA_CONTEXT_FAILED ? PA_STREAM_FAILED : PA_STREAM_TERMINATED);
244             pa_stream_unref(s);
245             s = n;
246         }
247
248         if (c->pdispatch)
249             pa_pdispatch_unref(c->pdispatch);
250         c->pdispatch = NULL;
251
252         if (c->pstream) {
253             pa_pstream_close(c->pstream);
254             pa_pstream_unref(c->pstream);
255         }
256         c->pstream = NULL;
257
258         if (c->client)
259             pa_socket_client_unref(c->client);
260         c->client = NULL;
261     }
262
263     pa_context_unref(c);
264 }
265
266 void pa_context_fail(pa_context *c, int error) {
267     assert(c);
268     assert(c->ref >= 1);
269
270     pa_context_set_error(c, error);
271     pa_context_set_state(c, PA_CONTEXT_FAILED);
272 }
273
274 int pa_context_set_error(pa_context *c, int error) {
275     assert(error >= 0);
276     assert(error < PA_ERR_MAX);
277
278     if (c)
279         c->error = error;
280
281     return error;
282 }
283
284 static void pstream_die_callback(pa_pstream *p, void *userdata) {
285     pa_context *c = userdata;
286
287     assert(p);
288     assert(c);
289
290     pa_context_fail(c, PA_ERR_CONNECTIONTERMINATED);
291 }
292
293 static void pstream_packet_callback(pa_pstream *p, pa_packet *packet, const pa_creds *creds, void *userdata) {
294     pa_context *c = userdata;
295
296     assert(p);
297     assert(packet);
298     assert(c);
299
300     pa_context_ref(c);
301
302     if (pa_pdispatch_run(c->pdispatch, packet, creds, c) < 0)
303         pa_context_fail(c, PA_ERR_PROTOCOL);
304
305     pa_context_unref(c);
306 }
307
308 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) {
309     pa_context *c = userdata;
310     pa_stream *s;
311
312     assert(p);
313     assert(chunk);
314     assert(chunk->memblock);
315     assert(chunk->length);
316     assert(c);
317     assert(c->ref >= 1);
318
319     pa_context_ref(c);
320
321     if ((s = pa_dynarray_get(c->record_streams, channel))) {
322
323         assert(seek == PA_SEEK_RELATIVE && offset == 0);
324
325         pa_memblockq_seek(s->record_memblockq, offset, seek);
326         pa_memblockq_push_align(s->record_memblockq, chunk);
327
328         if (s->read_callback) {
329             size_t l;
330
331             if ((l = pa_memblockq_get_length(s->record_memblockq)) > 0)
332                 s->read_callback(s, l, s->read_userdata);
333         }
334     }
335
336     pa_context_unref(c);
337 }
338
339 int pa_context_handle_error(pa_context *c, uint32_t command, pa_tagstruct *t) {
340     assert(c);
341     assert(c->ref >= 1);
342
343     if (command == PA_COMMAND_ERROR) {
344         assert(t);
345
346         if (pa_tagstruct_getu32(t, &c->error) < 0) {
347             pa_context_fail(c, PA_ERR_PROTOCOL);
348             return -1;
349
350         }
351     } else if (command == PA_COMMAND_TIMEOUT)
352         c->error = PA_ERR_TIMEOUT;
353     else {
354         pa_context_fail(c, PA_ERR_PROTOCOL);
355         return -1;
356     }
357
358     return 0;
359 }
360
361 static void setup_complete_callback(pa_pdispatch *pd, uint32_t command, uint32_t tag, pa_tagstruct *t, void *userdata) {
362     pa_context *c = userdata;
363
364     assert(pd);
365     assert(c);
366     assert(c->state == PA_CONTEXT_AUTHORIZING || c->state == PA_CONTEXT_SETTING_NAME);
367
368     pa_context_ref(c);
369
370     if (command != PA_COMMAND_REPLY) {
371
372         if (pa_context_handle_error(c, command, t) < 0)
373             pa_context_fail(c, PA_ERR_PROTOCOL);
374
375         pa_context_fail(c, c->error);
376         goto finish;
377     }
378
379     switch(c->state) {
380         case PA_CONTEXT_AUTHORIZING: {
381             pa_tagstruct *reply;
382
383             if (pa_tagstruct_getu32(t, &c->version) < 0 ||
384                 !pa_tagstruct_eof(t)) {
385                 pa_context_fail(c, PA_ERR_PROTOCOL);
386                 goto finish;
387             }
388
389             /* Minimum supported version */
390             if (c->version < 8) {
391                 pa_context_fail(c, PA_ERR_VERSION);
392                 goto finish;
393             }
394
395             /* Enable shared memory support if possible */
396             if (c->version >= 10 &&
397                 pa_mempool_is_shared(c->mempool) &&
398                 c->is_local) {
399
400                 /* Only enable SHM if both sides are owned by the same
401                  * user. This is a security measure because otherwise
402                  * data private to the user might leak. */
403
404 #ifdef HAVE_CREDS
405                 const pa_creds *creds;
406                 if ((creds = pa_pdispatch_creds(pd)))
407                     if (getuid() == creds->uid)
408                         pa_pstream_use_shm(c->pstream, 1);
409 #endif
410             }
411
412             reply = pa_tagstruct_command(c, PA_COMMAND_SET_CLIENT_NAME, &tag);
413             pa_tagstruct_puts(reply, c->name);
414             pa_pstream_send_tagstruct(c->pstream, reply);
415             pa_pdispatch_register_reply(c->pdispatch, tag, DEFAULT_TIMEOUT, setup_complete_callback, c, NULL);
416
417             pa_context_set_state(c, PA_CONTEXT_SETTING_NAME);
418             break;
419         }
420
421         case PA_CONTEXT_SETTING_NAME :
422             pa_context_set_state(c, PA_CONTEXT_READY);
423             break;
424
425         default:
426             assert(0);
427     }
428
429 finish:
430     pa_context_unref(c);
431 }
432
433 static void setup_context(pa_context *c, pa_iochannel *io) {
434     pa_tagstruct *t;
435     uint32_t tag;
436
437     assert(c);
438     assert(io);
439
440     pa_context_ref(c);
441
442     assert(!c->pstream);
443     c->pstream = pa_pstream_new(c->mainloop, io, c->mempool);
444
445     pa_pstream_set_die_callback(c->pstream, pstream_die_callback, c);
446     pa_pstream_set_recieve_packet_callback(c->pstream, pstream_packet_callback, c);
447     pa_pstream_set_recieve_memblock_callback(c->pstream, pstream_memblock_callback, c);
448
449     assert(!c->pdispatch);
450     c->pdispatch = pa_pdispatch_new(c->mainloop, command_table, PA_COMMAND_MAX);
451
452     if (!c->conf->cookie_valid)
453         pa_log_warn("No cookie loaded. Attempting to connect without.");
454
455     t = pa_tagstruct_command(c, PA_COMMAND_AUTH, &tag);
456     pa_tagstruct_putu32(t, PA_PROTOCOL_VERSION);
457     pa_tagstruct_put_arbitrary(t, c->conf->cookie, sizeof(c->conf->cookie));
458
459 #ifdef HAVE_CREDS
460 {
461     pa_creds ucred;
462
463     if (pa_iochannel_creds_supported(io))
464         pa_iochannel_creds_enable(io);
465
466     ucred.uid = getuid();
467     ucred.gid = getgid();
468
469     pa_pstream_send_tagstruct_with_creds(c->pstream, t, &ucred);
470 }
471 #else
472     pa_pstream_send_tagstruct(c->pstream, t);
473 #endif
474
475     pa_pdispatch_register_reply(c->pdispatch, tag, DEFAULT_TIMEOUT, setup_complete_callback, c, NULL);
476
477     pa_context_set_state(c, PA_CONTEXT_AUTHORIZING);
478
479     pa_context_unref(c);
480 }
481
482 static void on_connection(pa_socket_client *client, pa_iochannel*io, void *userdata);
483
484 #ifndef OS_IS_WIN32
485
486 static int context_connect_spawn(pa_context *c) {
487     pid_t pid;
488     int status, r;
489     int fds[2] = { -1, -1} ;
490     pa_iochannel *io;
491
492     pa_context_ref(c);
493
494     if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) < 0) {
495         pa_log("socketpair(): %s", pa_cstrerror(errno));
496         pa_context_fail(c, PA_ERR_INTERNAL);
497         goto fail;
498     }
499
500     pa_fd_set_cloexec(fds[0], 1);
501
502     pa_socket_low_delay(fds[0]);
503     pa_socket_low_delay(fds[1]);
504
505     if (c->spawn_api.prefork)
506         c->spawn_api.prefork();
507
508     if ((pid = fork()) < 0) {
509         pa_log("fork(): %s", pa_cstrerror(errno));
510         pa_context_fail(c, PA_ERR_INTERNAL);
511
512         if (c->spawn_api.postfork)
513             c->spawn_api.postfork();
514
515         goto fail;
516     } else if (!pid) {
517         /* Child */
518
519         char t[128];
520         const char *state = NULL;
521 #define MAX_ARGS 64
522         const char * argv[MAX_ARGS+1];
523         int n;
524
525         /* Not required, since fds[0] has CLOEXEC enabled anyway */
526         close(fds[0]);
527
528         if (c->spawn_api.atfork)
529             c->spawn_api.atfork();
530
531         /* Setup argv */
532
533         n = 0;
534
535         argv[n++] = c->conf->daemon_binary;
536         argv[n++] = "--daemonize=yes";
537
538         snprintf(t, sizeof(t), "-Lmodule-native-protocol-fd fd=%i", fds[1]);
539         argv[n++] = strdup(t);
540
541         while (n < MAX_ARGS) {
542             char *a;
543
544             if (!(a = pa_split_spaces(c->conf->extra_arguments, &state)))
545                 break;
546
547             argv[n++] = a;
548         }
549
550         argv[n++] = NULL;
551
552         execv(argv[0], (char * const *) argv);
553         _exit(1);
554 #undef MAX_ARGS
555     }
556
557     /* Parent */
558
559     r = waitpid(pid, &status, 0);
560
561     if (c->spawn_api.postfork)
562         c->spawn_api.postfork();
563
564     if (r < 0) {
565         pa_log("waitpid(): %s", pa_cstrerror(errno));
566         pa_context_fail(c, PA_ERR_INTERNAL);
567         goto fail;
568     } else if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
569         pa_context_fail(c, PA_ERR_CONNECTIONREFUSED);
570         goto fail;
571     }
572
573     close(fds[1]);
574
575     c->is_local = 1;
576
577     io = pa_iochannel_new(c->mainloop, fds[0], fds[0]);
578
579     setup_context(c, io);
580     unlock_autospawn_lock_file(c);
581
582     pa_context_unref(c);
583
584     return 0;
585
586 fail:
587     if (fds[0] != -1)
588         close(fds[0]);
589     if (fds[1] != -1)
590         close(fds[1]);
591
592     unlock_autospawn_lock_file(c);
593
594     pa_context_unref(c);
595
596     return -1;
597 }
598
599 #endif /* OS_IS_WIN32 */
600
601 static int try_next_connection(pa_context *c) {
602     char *u = NULL;
603     int r = -1;
604
605     assert(c);
606     assert(!c->client);
607
608     for (;;) {
609         pa_xfree(u);
610         u = NULL;
611
612         c->server_list = pa_strlist_pop(c->server_list, &u);
613
614         if (!u) {
615
616 #ifndef OS_IS_WIN32
617             if (c->do_autospawn) {
618                 r = context_connect_spawn(c);
619                 goto finish;
620             }
621 #endif
622
623             pa_context_fail(c, PA_ERR_CONNECTIONREFUSED);
624             goto finish;
625         }
626
627         pa_log_debug("Trying to connect to %s...", u);
628
629         pa_xfree(c->server);
630         c->server = pa_xstrdup(u);
631
632         if (!(c->client = pa_socket_client_new_string(c->mainloop, u, PA_NATIVE_DEFAULT_PORT)))
633             continue;
634
635         c->is_local = pa_socket_client_is_local(c->client);
636         pa_socket_client_set_callback(c->client, on_connection, c);
637         break;
638     }
639
640     r = 0;
641
642 finish:
643     pa_xfree(u);
644
645     return r;
646 }
647
648 static void on_connection(pa_socket_client *client, pa_iochannel*io, void *userdata) {
649     pa_context *c = userdata;
650
651     assert(client);
652     assert(c);
653     assert(c->state == PA_CONTEXT_CONNECTING);
654
655     pa_context_ref(c);
656
657     pa_socket_client_unref(client);
658     c->client = NULL;
659
660     if (!io) {
661         /* Try the item in the list */
662         if (errno == ECONNREFUSED || errno == ETIMEDOUT || errno == EHOSTUNREACH) {
663             try_next_connection(c);
664             goto finish;
665         }
666
667         pa_context_fail(c, PA_ERR_CONNECTIONREFUSED);
668         goto finish;
669     }
670
671     unlock_autospawn_lock_file(c);
672     setup_context(c, io);
673
674 finish:
675     pa_context_unref(c);
676 }
677
678 int pa_context_connect(
679         pa_context *c,
680         const char *server,
681         pa_context_flags_t flags,
682         const pa_spawn_api *api) {
683
684     int r = -1;
685
686     assert(c);
687     assert(c->ref >= 1);
688
689     PA_CHECK_VALIDITY(c, c->state == PA_CONTEXT_UNCONNECTED, PA_ERR_BADSTATE);
690     PA_CHECK_VALIDITY(c, !(flags & ~PA_CONTEXT_NOAUTOSPAWN), PA_ERR_INVALID);
691     PA_CHECK_VALIDITY(c, !server || *server, PA_ERR_INVALID);
692
693     if (!server)
694         server = c->conf->default_server;
695
696     pa_context_ref(c);
697
698     assert(!c->server_list);
699
700     if (server) {
701         if (!(c->server_list = pa_strlist_parse(server))) {
702             pa_context_fail(c, PA_ERR_INVALIDSERVER);
703             goto finish;
704         }
705     } else {
706         char *d;
707         char ufn[PATH_MAX];
708
709         /* Prepend in reverse order */
710
711         if ((d = getenv("DISPLAY"))) {
712             char *e;
713             d = pa_xstrdup(d);
714             if ((e = strchr(d, ':')))
715                 *e = 0;
716
717             if (*d)
718                 c->server_list = pa_strlist_prepend(c->server_list, d);
719
720             pa_xfree(d);
721         }
722
723         c->server_list = pa_strlist_prepend(c->server_list, "tcp6:localhost");
724         c->server_list = pa_strlist_prepend(c->server_list, "tcp4:localhost");
725
726         /* The system wide instance */
727         c->server_list = pa_strlist_prepend(c->server_list, PA_SYSTEM_RUNTIME_PATH "/" PA_NATIVE_DEFAULT_UNIX_SOCKET);
728
729         /* The per-user instance */
730         c->server_list = pa_strlist_prepend(c->server_list, pa_runtime_path(PA_NATIVE_DEFAULT_UNIX_SOCKET, ufn, sizeof(ufn)));
731
732         /* Wrap the connection attempts in a single transaction for sane autospawn locking */
733         if (!(flags & PA_CONTEXT_NOAUTOSPAWN) && c->conf->autospawn) {
734             char lf[PATH_MAX];
735
736             pa_runtime_path(AUTOSPAWN_LOCK, lf, sizeof(lf));
737             pa_make_secure_parent_dir(lf, 0700, (uid_t)-1, (gid_t)-1);
738             assert(c->autospawn_lock_fd <= 0);
739             c->autospawn_lock_fd = pa_lock_lockfile(lf);
740
741             if (api)
742                 c->spawn_api = *api;
743             c->do_autospawn = 1;
744         }
745
746     }
747
748     pa_context_set_state(c, PA_CONTEXT_CONNECTING);
749     r = try_next_connection(c);
750
751 finish:
752     pa_context_unref(c);
753
754     return r;
755 }
756
757 void pa_context_disconnect(pa_context *c) {
758     assert(c);
759     assert(c->ref >= 1);
760
761     pa_context_set_state(c, PA_CONTEXT_TERMINATED);
762 }
763
764 pa_context_state_t pa_context_get_state(pa_context *c) {
765     assert(c);
766     assert(c->ref >= 1);
767
768     return c->state;
769 }
770
771 int pa_context_errno(pa_context *c) {
772     assert(c);
773     assert(c->ref >= 1);
774
775     return c->error;
776 }
777
778 void pa_context_set_state_callback(pa_context *c, pa_context_notify_cb_t cb, void *userdata) {
779     assert(c);
780     assert(c->ref >= 1);
781
782     c->state_callback = cb;
783     c->state_userdata = userdata;
784 }
785
786 int pa_context_is_pending(pa_context *c) {
787     assert(c);
788     assert(c->ref >= 1);
789
790     PA_CHECK_VALIDITY(c,
791                       c->state == PA_CONTEXT_CONNECTING ||
792                       c->state == PA_CONTEXT_AUTHORIZING ||
793                       c->state == PA_CONTEXT_SETTING_NAME ||
794                       c->state == PA_CONTEXT_READY, PA_ERR_BADSTATE);
795
796     return (c->pstream && pa_pstream_is_pending(c->pstream)) ||
797         (c->pdispatch && pa_pdispatch_is_pending(c->pdispatch)) ||
798         c->client;
799 }
800
801 static void set_dispatch_callbacks(pa_operation *o);
802
803 static void pdispatch_drain_callback(PA_GCC_UNUSED pa_pdispatch*pd, void *userdata) {
804     set_dispatch_callbacks(userdata);
805 }
806
807 static void pstream_drain_callback(PA_GCC_UNUSED pa_pstream *s, void *userdata) {
808     set_dispatch_callbacks(userdata);
809 }
810
811 static void set_dispatch_callbacks(pa_operation *o) {
812     int done = 1;
813
814     assert(o);
815     assert(o->ref >= 1);
816     assert(o->context);
817     assert(o->context->ref >= 1);
818     assert(o->context->state == PA_CONTEXT_READY);
819
820     pa_pstream_set_drain_callback(o->context->pstream, NULL, NULL);
821     pa_pdispatch_set_drain_callback(o->context->pdispatch, NULL, NULL);
822
823     if (pa_pdispatch_is_pending(o->context->pdispatch)) {
824         pa_pdispatch_set_drain_callback(o->context->pdispatch, pdispatch_drain_callback, o);
825         done = 0;
826     }
827
828     if (pa_pstream_is_pending(o->context->pstream)) {
829         pa_pstream_set_drain_callback(o->context->pstream, pstream_drain_callback, o);
830         done = 0;
831     }
832
833     if (done) {
834         if (o->callback) {
835             pa_context_notify_cb_t cb = (pa_context_notify_cb_t) o->callback;
836             cb(o->context, o->userdata);
837         }
838
839         pa_operation_done(o);
840         pa_operation_unref(o);
841     }
842 }
843
844 pa_operation* pa_context_drain(pa_context *c, pa_context_notify_cb_t cb, void *userdata) {
845     pa_operation *o;
846
847     assert(c);
848     assert(c->ref >= 1);
849
850     PA_CHECK_VALIDITY_RETURN_NULL(c, c->state == PA_CONTEXT_READY, PA_ERR_BADSTATE);
851     PA_CHECK_VALIDITY_RETURN_NULL(c, pa_context_is_pending(c), PA_ERR_BADSTATE);
852
853     o = pa_operation_new(c, NULL, (pa_operation_cb_t) cb, userdata);
854     set_dispatch_callbacks(pa_operation_ref(o));
855
856     return o;
857 }
858
859 void pa_context_simple_ack_callback(pa_pdispatch *pd, uint32_t command, PA_GCC_UNUSED uint32_t tag, pa_tagstruct *t, void *userdata) {
860     pa_operation *o = userdata;
861     int success = 1;
862
863     assert(pd);
864     assert(o);
865     assert(o->ref >= 1);
866
867     if (!o->context)
868         goto finish;
869
870     if (command != PA_COMMAND_REPLY) {
871         if (pa_context_handle_error(o->context, command, t) < 0)
872             goto finish;
873
874         success = 0;
875     } else if (!pa_tagstruct_eof(t)) {
876         pa_context_fail(o->context, PA_ERR_PROTOCOL);
877         goto finish;
878     }
879
880     if (o->callback) {
881         pa_context_success_cb_t cb = (pa_context_success_cb_t) o->callback;
882         cb(o->context, success, o->userdata);
883     }
884
885 finish:
886     pa_operation_done(o);
887     pa_operation_unref(o);
888 }
889
890 pa_operation* pa_context_exit_daemon(pa_context *c, pa_context_success_cb_t cb, void *userdata) {
891     pa_tagstruct *t;
892     pa_operation *o;
893     uint32_t tag;
894
895     assert(c);
896     assert(c->ref >= 1);
897
898     PA_CHECK_VALIDITY_RETURN_NULL(c, c->state == PA_CONTEXT_READY, PA_ERR_BADSTATE);
899
900     o = pa_operation_new(c, NULL, (pa_operation_cb_t) cb, userdata);
901
902     t = pa_tagstruct_command(c, PA_COMMAND_EXIT, &tag);
903     pa_pstream_send_tagstruct(c->pstream, t);
904     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);
905
906     return o;
907 }
908
909 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) {
910     pa_tagstruct *t;
911     pa_operation *o;
912     uint32_t tag;
913
914     assert(c);
915     assert(c->ref >= 1);
916
917     PA_CHECK_VALIDITY_RETURN_NULL(c, c->state == PA_CONTEXT_READY, PA_ERR_BADSTATE);
918
919     o = pa_operation_new(c, NULL, cb, userdata);
920
921     t = pa_tagstruct_command(c, command, &tag);
922     pa_pstream_send_tagstruct(c->pstream, t);
923     pa_pdispatch_register_reply(c->pdispatch, tag, DEFAULT_TIMEOUT, internal_cb, pa_operation_ref(o), (pa_free_cb_t) pa_operation_unref);
924
925     return o;
926 }
927
928 pa_operation* pa_context_set_default_sink(pa_context *c, const char *name, pa_context_success_cb_t cb, void *userdata) {
929     pa_tagstruct *t;
930     pa_operation *o;
931     uint32_t tag;
932
933     assert(c);
934     assert(c->ref >= 1);
935
936     PA_CHECK_VALIDITY_RETURN_NULL(c, c->state == PA_CONTEXT_READY, PA_ERR_BADSTATE);
937
938     o = pa_operation_new(c, NULL, (pa_operation_cb_t) cb, userdata);
939
940     t = pa_tagstruct_command(c, PA_COMMAND_SET_DEFAULT_SINK, &tag);
941     pa_tagstruct_puts(t, name);
942     pa_pstream_send_tagstruct(c->pstream, t);
943     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);
944
945     return o;
946 }
947
948 pa_operation* pa_context_set_default_source(pa_context *c, const char *name, pa_context_success_cb_t cb, void *userdata) {
949     pa_tagstruct *t;
950     pa_operation *o;
951     uint32_t tag;
952
953     assert(c);
954     assert(c->ref >= 1);
955
956     PA_CHECK_VALIDITY_RETURN_NULL(c, c->state == PA_CONTEXT_READY, PA_ERR_BADSTATE);
957
958     o = pa_operation_new(c, NULL, (pa_operation_cb_t) cb, userdata);
959
960     t = pa_tagstruct_command(c, PA_COMMAND_SET_DEFAULT_SOURCE, &tag);
961     pa_tagstruct_puts(t, name);
962     pa_pstream_send_tagstruct(c->pstream, t);
963     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);
964
965     return o;
966 }
967
968 int pa_context_is_local(pa_context *c) {
969     assert(c);
970
971     return c->is_local;
972 }
973
974 pa_operation* pa_context_set_name(pa_context *c, const char *name, pa_context_success_cb_t cb, void *userdata) {
975     pa_tagstruct *t;
976     pa_operation *o;
977     uint32_t tag;
978
979     assert(c);
980     assert(c->ref >= 1);
981     assert(name);
982
983     PA_CHECK_VALIDITY_RETURN_NULL(c, c->state == PA_CONTEXT_READY, PA_ERR_BADSTATE);
984
985     o = pa_operation_new(c, NULL, (pa_operation_cb_t) cb, userdata);
986
987     t = pa_tagstruct_command(c, PA_COMMAND_SET_CLIENT_NAME, &tag);
988     pa_tagstruct_puts(t, name);
989     pa_pstream_send_tagstruct(c->pstream, t);
990     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);
991
992     return o;
993 }
994
995 const char* pa_get_library_version(void) {
996     return PACKAGE_VERSION;
997 }
998
999 const char* pa_context_get_server(pa_context *c) {
1000     assert(c);
1001     assert(c->ref >= 1);
1002
1003     if (!c->server)
1004         return NULL;
1005
1006     if (*c->server == '{') {
1007         char *e = strchr(c->server+1, '}');
1008         return e ? e+1 : c->server;
1009     }
1010
1011     return c->server;
1012 }
1013
1014 uint32_t pa_context_get_protocol_version(PA_GCC_UNUSED pa_context *c) {
1015     return PA_PROTOCOL_VERSION;
1016 }
1017
1018 uint32_t pa_context_get_server_protocol_version(pa_context *c) {
1019     assert(c);
1020     assert(c->ref >= 1);
1021
1022     return c->version;
1023 }
1024
1025 pa_tagstruct *pa_tagstruct_command(pa_context *c, uint32_t command, uint32_t *tag) {
1026     pa_tagstruct *t;
1027
1028     assert(c);
1029     assert(tag);
1030
1031     t = pa_tagstruct_new(NULL, 0);
1032     pa_tagstruct_putu32(t, command);
1033     pa_tagstruct_putu32(t, *tag = c->ctag++);
1034
1035     return t;
1036 }