+static int try_next_connection(struct pa_context *c) {
+ char *u = NULL;
+ int r = -1;
+ assert(c && !c->client);
+
+ for (;;) {
+ if (u)
+ pa_xfree(u);
+ u = NULL;
+
+ c->server_list = pa_strlist_pop(c->server_list, &u);
+
+ if (!u) {
+
+ if (c->do_autospawn) {
+ r = context_connect_spawn(c);
+ goto finish;
+ }
+
+ pa_context_fail(c, PA_ERROR_CONNECTIONREFUSED);
+ goto finish;
+ }
+
+/* pa_log(__FILE__": Trying to connect to %s...\n", u); */
+
+ if (!(c->client = pa_socket_client_new_string(c->mainloop, u, PA_NATIVE_DEFAULT_PORT)))
+ continue;
+
+ c->local = pa_socket_client_is_local(c->client);
+ pa_socket_client_set_callback(c->client, on_connection, c);
+ break;
+ }
+
+ r = 0;
+
+finish:
+ if (u)
+ pa_xfree(u);
+
+ return r;
+}
+
+static void on_connection(struct pa_socket_client *client, struct pa_iochannel*io, void *userdata) {
+ struct pa_context *c = userdata;
+ assert(client && c && c->state == PA_CONTEXT_CONNECTING);
+
+ pa_context_ref(c);
+
+ pa_socket_client_unref(client);
+ c->client = NULL;
+
+ if (!io) {
+ /* Try the item in the list */
+ if (errno == ECONNREFUSED || errno == ETIMEDOUT || errno == EHOSTUNREACH) {
+ try_next_connection(c);
+ goto finish;
+ }
+
+ pa_context_fail(c, PA_ERROR_CONNECTIONREFUSED);
+ goto finish;
+ }
+
+ unlock_autospawn_lock_file(c);
+ setup_context(c, io);
+
+finish:
+ pa_context_unref(c);
+}
+