• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
2  * Use of this source code is governed by a BSD-style license that can be
3  * found in the LICENSE file.
4  */
5 
6 #define _GNU_SOURCE /* Needed for Linux socket credential passing. */
7 
8 #ifdef CRAS_DBUS
9 #include <dbus/dbus.h>
10 #endif
11 #include <errno.h>
12 #include <poll.h>
13 #include <stdint.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <sys/param.h>
18 #include <sys/select.h>
19 #include <sys/socket.h>
20 #include <sys/stat.h>
21 #include <sys/types.h>
22 #include <sys/un.h>
23 #include <syslog.h>
24 #include <unistd.h>
25 
26 #ifdef CRAS_DBUS
27 #include "cras_a2dp_endpoint.h"
28 #include "cras_bt_manager.h"
29 #include "cras_bt_device.h"
30 #include "cras_bt_player.h"
31 #include "cras_dbus.h"
32 #include "cras_dbus_control.h"
33 #include "cras_hfp_ag_profile.h"
34 #include "cras_telephony.h"
35 #endif
36 #include "cras_alert.h"
37 #include "cras_audio_thread_monitor.h"
38 #include "cras_config.h"
39 #include "cras_device_monitor.h"
40 #include "cras_hotword_handler.h"
41 #include "cras_iodev_list.h"
42 #include "cras_main_message.h"
43 #include "cras_messages.h"
44 #include "cras_metrics.h"
45 #include "cras_non_empty_audio_handler.h"
46 #include "cras_observer.h"
47 #include "cras_rclient.h"
48 #include "cras_server.h"
49 #include "cras_server_metrics.h"
50 #include "cras_system_state.h"
51 #include "cras_tm.h"
52 #include "cras_udev.h"
53 #include "cras_util.h"
54 #include "cras_mix.h"
55 #include "utlist.h"
56 
57 /* Store a list of clients that are attached to the server.
58  * Members:
59  *    id - Unique identifier for this client.
60  *    fd - socket file descriptor used to communicate with client.
61  *    ucred - Process, user, and group ID of the client.
62  *    client - rclient to handle messages from this client.
63  *    pollfd - Pointer to struct pollfd for this callback.
64  */
65 struct attached_client {
66 	size_t id;
67 	int fd;
68 	struct ucred ucred;
69 	struct cras_rclient *client;
70 	struct pollfd *pollfd;
71 	struct attached_client *next, *prev;
72 };
73 
74 /* Stores file descriptors to callback mappings for clients. Callback/fd/data
75  * args are registered by clients.  When fd is ready, the callback will be
76  * called on the main server thread and the callback data will be passed back to
77  * it.  This allows the use of the main server loop instead of spawning a thread
78  * to watch file descriptors.  The client can then read or write the fd.
79  * Members:
80  *    fd - The file descriptor passed to select.
81  *    callack - The funciton to call when fd is ready.
82  *    callback_data - Pointer passed to the callback.
83  *    pollfd - Pointer to struct pollfd for this callback.
84  */
85 struct client_callback {
86 	int select_fd;
87 	void (*callback)(void *);
88 	void *callback_data;
89 	struct pollfd *pollfd;
90 	int deleted;
91 	struct client_callback *prev, *next;
92 };
93 
94 /* Stores callback function and argument data to be executed later. */
95 struct system_task {
96 	void (*callback)(void *);
97 	void *callback_data;
98 	struct system_task *next, *prev;
99 };
100 
101 /* Local server data. */
102 struct server_data {
103 	struct attached_client *clients_head;
104 	size_t num_clients;
105 	struct client_callback *client_callbacks;
106 	struct system_task *system_tasks;
107 	size_t num_client_callbacks;
108 	size_t next_client_id;
109 } server_instance;
110 
111 /* Remove a client from the list and destroy it.  Calling rclient_destroy will
112  * also free all the streams owned by the client */
remove_client(struct attached_client * client)113 static void remove_client(struct attached_client *client)
114 {
115 	close(client->fd);
116 	DL_DELETE(server_instance.clients_head, client);
117 	server_instance.num_clients--;
118 	cras_rclient_destroy(client->client);
119 	free(client);
120 }
121 
122 /* This is called when "select" indicates that the client has written data to
123  * the socket.  Read out one message and pass it to the client message handler.
124  */
handle_message_from_client(struct attached_client * client)125 static void handle_message_from_client(struct attached_client *client)
126 {
127 	uint8_t buf[CRAS_SERV_MAX_MSG_SIZE];
128 	int nread;
129 	int fd;
130 	unsigned int num_fds = 1;
131 
132 	nread = cras_recv_with_fds(client->fd, buf, sizeof(buf), &fd, &num_fds);
133         if (nread < 0)
134                 goto read_error;
135         if (cras_rclient_buffer_from_client(client->client, buf, nread, fd) < 0)
136 		goto read_error;
137 	return;
138 
139 read_error:
140 	if (fd != -1)
141 		close(fd);
142 	switch (nread) {
143 	case 0:
144 		break;
145 	default:
146 		syslog(LOG_DEBUG, "read err [%d] '%s', removing client %zu",
147 		       -nread, strerror(-nread), client->id);
148 		break;
149 	}
150 	remove_client(client);
151 }
152 
153 /* Discovers and fills in info about the client that can be obtained from the
154  * socket. The pid of the attaching client identifies it in logs. */
fill_client_info(struct attached_client * client)155 static void fill_client_info(struct attached_client *client)
156 {
157 	socklen_t ucred_length = sizeof(client->ucred);
158 
159 	if (getsockopt(client->fd, SOL_SOCKET, SO_PEERCRED,
160 		       &client->ucred, &ucred_length))
161 		syslog(LOG_INFO, "Failed to get client socket info\n");
162 }
163 
164 /* Fills the server_state with the current list of attached clients. */
send_client_list_to_clients(struct server_data * serv)165 static void send_client_list_to_clients(struct server_data *serv)
166 {
167 	struct attached_client *c;
168 	struct cras_attached_client_info *info;
169 	struct cras_server_state *state;
170 	unsigned i;
171 
172 	state = cras_system_state_update_begin();
173 	if (!state)
174 		return;
175 
176 	state->num_attached_clients =
177 		MIN(CRAS_MAX_ATTACHED_CLIENTS, serv->num_clients);
178 
179 	info = state->client_info;
180 	i = 0;
181 	DL_FOREACH(serv->clients_head, c) {
182 		info->id = c->id;
183 		info->pid = c->ucred.pid;
184 		info->uid = c->ucred.uid;
185 		info->gid = c->ucred.gid;
186 		info++;
187 		if (++i == CRAS_MAX_ATTACHED_CLIENTS)
188 			break;
189 	}
190 
191 	cras_system_state_update_complete();
192 }
193 
194 /* Handles requests from a client to attach to the server.  Create a local
195  * structure to track the client, assign it a unique id and let it attach */
handle_new_connection(struct sockaddr_un * address,int fd)196 static void handle_new_connection(struct sockaddr_un *address, int fd)
197 {
198 	int connection_fd;
199 	struct attached_client *poll_client;
200 	socklen_t address_length;
201 
202 	poll_client = malloc(sizeof(struct attached_client));
203 	if (poll_client == NULL) {
204 		syslog(LOG_ERR, "Allocating poll_client");
205 		return;
206 	}
207 
208 	memset(&address_length, 0, sizeof(address_length));
209 	connection_fd = accept(fd, (struct sockaddr *) address,
210 			       &address_length);
211 	if (connection_fd < 0) {
212 		syslog(LOG_ERR, "connecting");
213 		free(poll_client);
214 		return;
215 	}
216 
217 	/* find next available client id */
218 	while (1) {
219 		struct attached_client *out;
220 		DL_SEARCH_SCALAR(server_instance.clients_head, out, id,
221 				 server_instance.next_client_id);
222 		poll_client->id = server_instance.next_client_id;
223 		server_instance.next_client_id++;
224 		if (out == NULL)
225 			break;
226 	}
227 
228 	/* When full, getting an error is preferable to blocking. */
229 	cras_make_fd_nonblocking(connection_fd);
230 
231 	poll_client->fd = connection_fd;
232 	poll_client->next = NULL;
233 	poll_client->pollfd = NULL;
234 	fill_client_info(poll_client);
235 	poll_client->client = cras_rclient_create(connection_fd,
236 						  poll_client->id);
237 	if (poll_client->client == NULL) {
238 		syslog(LOG_ERR, "failed to create client");
239 		close(connection_fd);
240 		free(poll_client);
241 		return;
242 	}
243 
244 	DL_APPEND(server_instance.clients_head, poll_client);
245 	server_instance.num_clients++;
246 	/* Send a current list of available inputs and outputs. */
247 	cras_iodev_list_update_device_list();
248 	send_client_list_to_clients(&server_instance);
249 }
250 
251 /* Add a file descriptor to be passed to select in the main loop. This is
252  * registered with system state so that it is called when any client asks to
253  * have a callback triggered based on an fd being readable. */
add_select_fd(int fd,void (* cb)(void * data),void * callback_data,void * server_data)254 static int add_select_fd(int fd, void (*cb)(void *data),
255 			 void *callback_data, void *server_data)
256 {
257 	struct client_callback *new_cb;
258 	struct client_callback *client_cb;
259 	struct server_data *serv;
260 
261 	serv = (struct server_data *)server_data;
262 	if (serv == NULL)
263 		return -EINVAL;
264 
265 	/* Check if fd already exists. */
266 	DL_FOREACH(serv->client_callbacks, client_cb)
267 		if (client_cb->select_fd == fd && !client_cb->deleted)
268 			return -EEXIST;
269 
270 	new_cb = (struct  client_callback *)calloc(1, sizeof(*new_cb));
271 	if (new_cb == NULL)
272 		return -ENOMEM;
273 
274 	new_cb->select_fd = fd;
275 	new_cb->callback = cb;
276 	new_cb->callback_data = callback_data;
277 	new_cb->deleted = 0;
278 	new_cb->pollfd = NULL;
279 
280 	DL_APPEND(serv->client_callbacks, new_cb);
281 	server_instance.num_client_callbacks++;
282 	return 0;
283 }
284 
285 /* Removes a file descriptor to be passed to select in the main loop. This is
286  * registered with system state so that it is called when any client asks to
287  * remove a callback added with add_select_fd. */
rm_select_fd(int fd,void * server_data)288 static void rm_select_fd(int fd, void *server_data)
289 {
290 	struct server_data *serv;
291 	struct client_callback *client_cb;
292 
293 	serv = (struct server_data *)server_data;
294 	if (serv == NULL)
295 		return;
296 
297 	DL_FOREACH(serv->client_callbacks, client_cb)
298 		if (client_cb->select_fd == fd)
299 			client_cb->deleted = 1;
300 }
301 
302 /* Creates a new task entry and append to system_tasks list, which will be
303  * executed in main loop later without wait time.
304  */
add_task(void (* cb)(void * data),void * callback_data,void * server_data)305 static int add_task(void (*cb)(void *data),
306 		    void *callback_data,
307 		    void *server_data)
308 {
309 	struct server_data *serv;
310 	struct system_task *new_task;
311 
312 	serv = (struct server_data *)server_data;
313 	if (serv == NULL)
314 		return -EINVAL;
315 
316 	new_task = (struct system_task *)calloc(1, sizeof(*new_task));
317 	if (new_task == NULL)
318 		return -ENOMEM;
319 
320 	new_task->callback = cb;
321 	new_task->callback_data = callback_data;
322 
323 	DL_APPEND(serv->system_tasks, new_task);
324 	return 0;
325 }
326 
327 /* Cleans up the file descriptor list removing items deleted during the main
328  * loop iteration. */
cleanup_select_fds(void * server_data)329 static void cleanup_select_fds(void *server_data)
330 {
331 	struct server_data *serv;
332 	struct client_callback *client_cb;
333 
334 	serv = (struct server_data *)server_data;
335 	if (serv == NULL)
336 		return;
337 
338 	DL_FOREACH(serv->client_callbacks, client_cb)
339 		if (client_cb->deleted) {
340 			DL_DELETE(serv->client_callbacks, client_cb);
341 			server_instance.num_client_callbacks--;
342 			free(client_cb);
343 		}
344 }
345 
346 /* Checks that at least two outputs are present (one will be the "empty"
347  * default device. */
check_output_exists(struct cras_timer * t,void * data)348 void check_output_exists(struct cras_timer *t, void *data)
349 {
350 	if (cras_iodev_list_get_outputs(NULL) < 2)
351 		cras_metrics_log_event(kNoCodecsFoundMetric);
352 }
353 
354 #if defined(__amd64__)
355 /* CPU detection - probaby best to move this elsewhere */
cpuid(unsigned int * eax,unsigned int * ebx,unsigned int * ecx,unsigned int * edx,unsigned int op)356 static void cpuid(unsigned int *eax, unsigned int *ebx, unsigned int *ecx,
357 	          unsigned int *edx, unsigned int op)
358 {
359 	__asm__ __volatile__ (
360 		"cpuid"
361 		: "=a" (*eax),
362 		  "=b" (*ebx),
363 		  "=c" (*ecx),
364 		  "=d" (*edx)
365 		: "a" (op), "c" (0)
366     );
367 }
368 
cpu_x86_flags(void)369 static unsigned int cpu_x86_flags(void)
370 {
371 	unsigned int eax, ebx, ecx, edx, id;
372 	unsigned int cpu_flags = 0;
373 
374 	cpuid(&id, &ebx, &ecx, &edx, 0);
375 
376 	if (id >= 1) {
377 		cpuid(&eax, &ebx, &ecx, &edx, 1);
378 
379 		if (ecx & (1 << 20))
380 			cpu_flags |= CPU_X86_SSE4_2;
381 
382 		if (ecx & (1 << 28))
383 			cpu_flags |= CPU_X86_AVX;
384 
385 		if (ecx & (1 << 12))
386 			cpu_flags |= CPU_X86_FMA;
387 	}
388 
389 	if (id >= 7) {
390 		cpuid(&eax, &ebx, &ecx, &edx, 7);
391 
392 		if (ebx & (1 << 5))
393 			cpu_flags |= CPU_X86_AVX2;
394 	}
395 
396 	return cpu_flags;
397 }
398 #endif
399 
cpu_get_flags(void)400 int cpu_get_flags(void)
401 {
402 #if defined(__amd64__)
403 	return cpu_x86_flags();
404 #endif
405 	return 0;
406 }
407 
408 /*
409  * Exported Interface.
410  */
411 
cras_server_init()412 int cras_server_init()
413 {
414 	/* Log to syslog. */
415 	openlog("cras_server", LOG_PID, LOG_USER);
416 
417 	server_instance.next_client_id = RESERVED_CLIENT_IDS;
418 
419 	/* Initialize global observer. */
420 	cras_observer_server_init();
421 
422 	/* init mixer with CPU capabilities */
423 	cras_mix_init(cpu_get_flags());
424 
425 	/* Allow clients to register callbacks for file descriptors.
426 	 * add_select_fd and rm_select_fd will add and remove file descriptors
427 	 * from the list that are passed to select in the main loop below. */
428 	cras_system_set_select_handler(add_select_fd, rm_select_fd,
429 				       &server_instance);
430 	cras_system_set_add_task_handler(add_task, &server_instance);
431 	cras_main_message_init();
432 
433 	return 0;
434 }
435 
cras_server_run(unsigned int profile_disable_mask)436 int cras_server_run(unsigned int profile_disable_mask)
437 {
438 	static const unsigned int OUTPUT_CHECK_MS = 5 * 1000;
439 #ifdef CRAS_DBUS
440 	DBusConnection *dbus_conn;
441 #endif
442 	int socket_fd = -1;
443 	int rc = 0;
444 	const char *sockdir;
445 	struct sockaddr_un addr;
446 	struct attached_client *elm;
447 	struct client_callback *client_cb;
448 	struct system_task *tasks;
449 	struct system_task *system_task;
450 	struct cras_tm *tm;
451 	struct timespec ts, *poll_timeout;
452 	int timers_active;
453 	struct pollfd *pollfds;
454 	unsigned int pollfds_size = 32;
455 	unsigned int num_pollfds, poll_size_needed;
456 
457 	pollfds = malloc(sizeof(*pollfds) * pollfds_size);
458 
459 	cras_udev_start_sound_subsystem_monitor();
460 #ifdef CRAS_DBUS
461 	cras_bt_device_start_monitor();
462 #endif
463 
464 	cras_server_metrics_init();
465 
466 	cras_device_monitor_init();
467 
468 	cras_hotword_handler_init();
469 
470 	cras_non_empty_audio_handler_init();
471 
472 	cras_audio_thread_monitor_init();
473 
474 #ifdef CRAS_DBUS
475 	dbus_threads_init_default();
476 	dbus_conn = cras_dbus_connect_system_bus();
477 	if (dbus_conn) {
478 		cras_bt_start(dbus_conn);
479 		if (!(profile_disable_mask & CRAS_SERVER_PROFILE_MASK_HFP))
480 			cras_hfp_ag_profile_create(dbus_conn);
481 		if (!(profile_disable_mask & CRAS_SERVER_PROFILE_MASK_HSP))
482 			cras_hsp_ag_profile_create(dbus_conn);
483 		cras_telephony_start(dbus_conn);
484 		if (!(profile_disable_mask & CRAS_SERVER_PROFILE_MASK_A2DP))
485 			cras_a2dp_endpoint_create(dbus_conn);
486 		cras_bt_player_create(dbus_conn);
487 		cras_dbus_control_start(dbus_conn);
488 	}
489 #endif
490 
491 	socket_fd = socket(PF_UNIX, SOCK_SEQPACKET, 0);
492 	if (socket_fd < 0) {
493 		syslog(LOG_ERR, "Main server socket failed.");
494 		rc = socket_fd;
495 		goto bail;
496 	}
497 
498 	sockdir = cras_config_get_system_socket_file_dir();
499 	if (sockdir == NULL) {
500 		rc = -ENOTDIR;
501 		goto bail;
502 	}
503 
504 	memset(&addr, 0, sizeof(addr));
505 	addr.sun_family = AF_UNIX;
506 	snprintf(addr.sun_path, sizeof(addr.sun_path),
507 		 "%s/%s", sockdir, CRAS_SOCKET_FILE);
508 	unlink(addr.sun_path);
509 
510 	/* Linux quirk: calling fchmod before bind, sets the permissions of the
511 	 * file created by bind, leaving no window for it to be modified. Start
512 	 * with very restricted permissions. */
513 	rc = fchmod(socket_fd, 0700);
514 	if (rc < 0)
515 		goto bail;
516 
517 	if (bind(socket_fd, (struct sockaddr *) &addr,
518 		 sizeof(struct sockaddr_un)) != 0) {
519 		syslog(LOG_ERR, "Bind to server socket failed.");
520 		rc = errno;
521 		goto bail;
522 	}
523 
524 	/* Let other members in our group play audio through this socket. */
525 	rc = chmod(addr.sun_path, 0770);
526 	if (rc < 0)
527 		goto bail;
528 
529 	if (listen(socket_fd, 5) != 0) {
530 		syslog(LOG_ERR, "Listen on server socket failed.");
531 		rc = errno;
532 		goto bail;
533 	}
534 
535 	tm = cras_system_state_get_tm();
536 	if (!tm) {
537 		syslog(LOG_ERR, "Getting timer manager.");
538 		rc = -ENOMEM;
539 		goto bail;
540 	}
541 
542 	/* After a delay, make sure there is at least one real output device. */
543 	cras_tm_create_timer(tm, OUTPUT_CHECK_MS, check_output_exists, 0);
544 
545 	/* Main server loop - client callbacks are run from this context. */
546 	while (1) {
547 		poll_size_needed = 1 + server_instance.num_clients +
548 					server_instance.num_client_callbacks;
549 		if (poll_size_needed > pollfds_size) {
550 			pollfds_size = 2 * poll_size_needed;
551 			pollfds = realloc(pollfds,
552 					sizeof(*pollfds) * pollfds_size);
553 		}
554 
555 		pollfds[0].fd = socket_fd;
556 		pollfds[0].events = POLLIN;
557 		num_pollfds = 1;
558 
559 		DL_FOREACH(server_instance.clients_head, elm) {
560 			pollfds[num_pollfds].fd = elm->fd;
561 			pollfds[num_pollfds].events = POLLIN;
562 			elm->pollfd = &pollfds[num_pollfds];
563 			num_pollfds++;
564 		}
565 		DL_FOREACH(server_instance.client_callbacks, client_cb) {
566 			if (client_cb->deleted)
567 				continue;
568 			pollfds[num_pollfds].fd = client_cb->select_fd;
569 			pollfds[num_pollfds].events = POLLIN;
570 			client_cb->pollfd = &pollfds[num_pollfds];
571 			num_pollfds++;
572 		}
573 
574 		tasks = server_instance.system_tasks;
575 		server_instance.system_tasks = NULL;
576 		DL_FOREACH(tasks, system_task) {
577 			system_task->callback(system_task->callback_data);
578 			DL_DELETE(tasks, system_task);
579 			free(system_task);
580 		}
581 
582 		timers_active = cras_tm_get_next_timeout(tm, &ts);
583 
584 		/*
585 		 * If new client task has been scheduled, no need to wait
586 		 * for timeout, just do another loop to execute them.
587 		 */
588 		if (server_instance.system_tasks)
589 			poll_timeout = NULL;
590 		else
591 			poll_timeout = timers_active ? &ts : NULL;
592 
593 		rc = ppoll(pollfds, num_pollfds, poll_timeout, NULL);
594 		if  (rc < 0)
595 			continue;
596 
597 		cras_tm_call_callbacks(tm);
598 
599 		/* Check for new connections. */
600 		if (pollfds[0].revents & POLLIN)
601 			handle_new_connection(&addr, socket_fd);
602 		/* Check if there are messages pending for any clients. */
603 		DL_FOREACH(server_instance.clients_head, elm)
604 			if (elm->pollfd && elm->pollfd->revents & POLLIN)
605 				handle_message_from_client(elm);
606 		/* Check any client-registered fd/callback pairs. */
607 		DL_FOREACH(server_instance.client_callbacks, client_cb)
608 			if (!client_cb->deleted &&
609 			    client_cb->pollfd &&
610 			    (client_cb->pollfd->revents & POLLIN))
611 				client_cb->callback(client_cb->callback_data);
612 
613 		cleanup_select_fds(&server_instance);
614 
615 #ifdef CRAS_DBUS
616 		if (dbus_conn)
617 			cras_dbus_dispatch(dbus_conn);
618 #endif
619 
620 		cras_alert_process_all_pending_alerts();
621 	}
622 
623 bail:
624 	if (socket_fd >= 0) {
625 		close(socket_fd);
626 		unlink(addr.sun_path);
627 	}
628 	free(pollfds);
629 	cras_observer_server_free();
630 	return rc;
631 }
632 
cras_server_send_to_all_clients(const struct cras_client_message * msg)633 void cras_server_send_to_all_clients(const struct cras_client_message *msg)
634 {
635 	struct attached_client *client;
636 
637 	DL_FOREACH(server_instance.clients_head, client)
638 		cras_rclient_send_message(client->client, msg, NULL, 0);
639 }
640