1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
|
/*
* $Id: ud_socket.c,v 1.4 2003/11/17 21:24:58 sunthockin Exp $
* A few routines for handling UNIX domain sockets
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <fcntl.h>
/*#include "acpid.h"*/
#include "ud_socket.h"
int
ud_create_socket(const char *name)
{
int fd;
int r;
struct sockaddr_un uds_addr;
/* JIC */
unlink(name);
fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (fd < 0) {
return fd;
}
/* setup address struct */
memset(&uds_addr, 0, sizeof(uds_addr));
uds_addr.sun_family = AF_UNIX;
strcpy(uds_addr.sun_path, name);
/* bind it to the socket */
r = bind(fd, (struct sockaddr *)&uds_addr, sizeof(uds_addr));
if (r < 0) {
return r;
}
/* listen - allow 10 to queue */
r = listen(fd, 10);
if (r < 0) {
return r;
}
return fd;
}
int
ud_accept(int listenfd, struct ucred *cred)
{
while (1) {
int newsock = 0;
struct sockaddr_un cliaddr;
int len = sizeof(struct sockaddr_un);
newsock = accept(listenfd, (struct sockaddr *)&cliaddr, &len);
if (newsock < 0) {
if (errno == EINTR) {
continue; /* signal */
}
return newsock;
}
if (cred) {
len = sizeof(struct ucred);
getsockopt(newsock, SOL_SOCKET, SO_PEERCRED,cred,&len);
}
return newsock;
}
}
int
ud_connect(const char *name)
{
int fd;
int r;
struct sockaddr_un addr;
fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (fd < 0) {
return fd;
}
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
sprintf(addr.sun_path, "%s", name);
r = connect(fd, (struct sockaddr *)&addr, sizeof(addr));
if (r < 0) {
close(fd);
return r;
}
return fd;
}
|