2 * This file is part of DisOrder.
3 * Copyright (C) 2005, 2007 Richard Kettlewell
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
20 /** @file lib/speaker-protocol.c
21 * @brief Speaker/server protocol support
27 #include <sys/socket.h>
32 #include "speaker-protocol.h"
35 /** @brief Send a speaker message
36 * @param fd File descriptor to send to
37 * @param sm Pointer to message
38 * @param datafd File descriptoxr to pass with message or -1
40 * @p datafd will be the output from some decoder.
42 void speaker_send(int fd, const struct speaker_message *sm, int datafd) {
47 char size[CMSG_SPACE(sizeof (int))];
51 memset(&m, 0, sizeof m);
54 iov.iov_base = (void *)sm;
55 iov.iov_len = sizeof *sm;
57 m.msg_control = (void *)&u.cmsg;
58 m.msg_controllen = sizeof u;
59 memset(&u, 0, sizeof u);
60 u.cmsg.cmsg_len = CMSG_LEN(sizeof (int));
61 u.cmsg.cmsg_level = SOL_SOCKET;
62 u.cmsg.cmsg_type = SCM_RIGHTS;
63 *(int *)CMSG_DATA(&u.cmsg) = datafd;
66 ret = sendmsg(fd, &m, 0);
67 } while(ret < 0 && errno == EINTR);
69 fatal(errno, "sendmsg");
72 /** @brief Receive a speaker message
73 * @param fd File descriptor to read from
74 * @param sm Where to store received message
75 * @param datafd Where to store received file descriptor or NULL
76 * @return -ve on @c EAGAIN, 0 at EOF, +ve on success
78 * If @p datafd is NULL but a file descriptor is nonetheless received,
79 * the process is terminated with an error.
81 int speaker_recv(int fd, struct speaker_message *sm, int *datafd) {
86 char size[CMSG_SPACE(sizeof (int))];
90 memset(&m, 0, sizeof m);
93 iov.iov_base = (void *)sm;
94 iov.iov_len = sizeof *sm;
96 m.msg_control = (void *)&u.cmsg;
97 m.msg_controllen = sizeof u;
98 memset(&u, 0, sizeof u);
99 u.cmsg.cmsg_len = CMSG_LEN(sizeof (int));
100 u.cmsg.cmsg_level = SOL_SOCKET;
101 u.cmsg.cmsg_type = SCM_RIGHTS;
105 ret = recvmsg(fd, &m, MSG_DONTWAIT);
106 } while(ret < 0 && errno == EINTR);
108 if(errno != EAGAIN) fatal(errno, "recvmsg");
111 if((size_t)m.msg_controllen >= CMSG_LEN(sizeof (int))) {
113 fatal(0, "got an unexpected file descriptor from recvmsg");
115 *datafd = *(int *)CMSG_DATA(&u.cmsg);