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