9 #include <netinet/in.h>
12 #include <sys/types.h>
13 #include <netinet/tcp.h>
14 #include <netinet/ip.h>
16 #include "socket-util.h"
18 void pa_socket_peer_to_string(int fd, char *c, size_t l) {
21 assert(c && l && fd >= 0);
23 if (fstat(fd, &st) < 0) {
24 snprintf(c, l, "Invalid client fd");
28 if (S_ISSOCK(st.st_mode)) {
31 struct sockaddr_in in;
32 struct sockaddr_un un;
34 socklen_t sa_len = sizeof(sa);
36 if (getpeername(fd, &sa.sa, &sa_len) >= 0) {
38 if (sa.sa.sa_family == AF_INET) {
39 uint32_t ip = ntohl(sa.in.sin_addr.s_addr);
41 snprintf(c, l, "TCP/IP client from %i.%i.%i.%i:%u",
46 ntohs(sa.in.sin_port));
48 } else if (sa.sa.sa_family == AF_LOCAL) {
49 snprintf(c, l, "UNIX socket client");
54 snprintf(c, l, "Unknown network client");
56 } else if (S_ISCHR(st.st_mode) && (fd == 0 || fd == 1)) {
57 snprintf(c, l, "STDIN/STDOUT client");
61 snprintf(c, l, "Unknown client");
64 int pa_socket_low_delay(int fd) {
69 if (setsockopt(fd, SOL_SOCKET, SO_PRIORITY, &priority, sizeof(priority)) < 0)
75 int pa_socket_tcp_low_delay(int fd) {
80 ret = pa_socket_low_delay(fd);
83 /* if (setsockopt(fd, SOL_TCP, TCP_NODELAY, &on, sizeof(on)) < 0) */
87 if (setsockopt(fd, SOL_IP, IP_TOS, &tos, sizeof(tos)) < 0)
94 int pa_socket_set_rcvbuf(int fd, size_t l) {
97 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &l, sizeof(l)) < 0)
103 int pa_socket_set_sndbuf(int fd, size_t l) {
106 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &l, sizeof(l)) < 0)
112 int pa_unix_socket_is_stale(const char *fn) {
113 struct sockaddr_un sa;
114 int fd = -1, ret = -1;
116 if ((fd = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0) {
117 fprintf(stderr, "socket(): %s\n", strerror(errno));
121 sa.sun_family = AF_LOCAL;
122 strncpy(sa.sun_path, fn, sizeof(sa.sun_path)-1);
123 sa.sun_path[sizeof(sa.sun_path) - 1] = 0;
125 if (connect(fd, (struct sockaddr*) &sa, sizeof(sa)) < 0) {
126 if (errno == ECONNREFUSED)
138 int pa_unix_socket_remove_stale(const char *fn) {
141 if ((r = pa_unix_socket_is_stale(fn)) < 0)
142 return errno != ENOENT ? -1 : 0;
147 /* Yes, here is a race condition. But who cares? */