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 messages
36 * @param fd File descriptor to send to
37 * @param sm Pointer to message
38 * @param datafd File descriptor to pass with message or -1
40 void speaker_send(int fd, const struct speaker_message *sm, int datafd) {
45 char size[CMSG_SPACE(sizeof (int))];
49 memset(&m, 0, sizeof m);
52 iov.iov_base = (void *)sm;
53 iov.iov_len = sizeof *sm;
55 m.msg_control = (void *)&u.cmsg;
56 m.msg_controllen = sizeof u;
57 memset(&u, 0, sizeof u);
58 u.cmsg.cmsg_len = CMSG_LEN(sizeof (int));
59 u.cmsg.cmsg_level = SOL_SOCKET;
60 u.cmsg.cmsg_type = SCM_RIGHTS;
61 *(int *)CMSG_DATA(&u.cmsg) = datafd;
64 ret = sendmsg(fd, &m, 0);
65 } while(ret < 0 && errno == EINTR);
67 fatal(errno, "sendmsg");
70 /** @brief Receive a speaker message
71 * @param fd File descriptor to read from
72 * @param sm Where to store received message
73 * @param datafd Where to store received file descriptor or NULL
74 * @return -ve on @c EAGAIN, 0 at EOF, +ve on success
76 * If @p datafd is NULL but a file descriptor is nonetheless received,
77 * the process is terminated with an error.
79 int speaker_recv(int fd, struct speaker_message *sm, int *datafd) {
84 char size[CMSG_SPACE(sizeof (int))];
88 memset(&m, 0, sizeof m);
91 iov.iov_base = (void *)sm;
92 iov.iov_len = sizeof *sm;
94 m.msg_control = (void *)&u.cmsg;
95 m.msg_controllen = sizeof u;
96 memset(&u, 0, sizeof u);
97 u.cmsg.cmsg_len = CMSG_LEN(sizeof (int));
98 u.cmsg.cmsg_level = SOL_SOCKET;
99 u.cmsg.cmsg_type = SCM_RIGHTS;
103 ret = recvmsg(fd, &m, MSG_DONTWAIT);
104 } while(ret < 0 && errno == EINTR);
106 if(errno != EAGAIN) fatal(errno, "recvmsg");
109 if((size_t)m.msg_controllen >= CMSG_LEN(sizeof (int))) {
111 fatal(0, "got an unexpected file descriptor from recvmsg");
113 *datafd = *(int *)CMSG_DATA(&u.cmsg);