]> code.delx.au - pulseaudio/blob - src/util.c
main part of the native protocol
[pulseaudio] / src / util.c
1 #include <assert.h>
2 #include <string.h>
3 #include <stdio.h>
4 #include <sys/un.h>
5 #include <netinet/in.h>
6 #include <fcntl.h>
7
8 #include "util.h"
9
10 void make_nonblock_fd(int fd) {
11 int v;
12
13 if ((v = fcntl(fd, F_GETFL)) >= 0)
14 if (!(v & O_NONBLOCK))
15 fcntl(fd, F_SETFL, v|O_NONBLOCK);
16 }
17
18 void peer_to_string(char *c, size_t l, int fd) {
19 struct stat st;
20
21 assert(c && l && fd >= 0);
22
23 if (fstat(fd, &st) < 0) {
24 snprintf(c, l, "Invalid client fd");
25 return;
26 }
27
28 if (S_ISSOCK(st.st_mode)) {
29 union {
30 struct sockaddr sa;
31 struct sockaddr_in in;
32 struct sockaddr_un un;
33 } sa;
34 socklen_t sa_len = sizeof(sa);
35
36 if (getpeername(fd, &sa.sa, &sa_len) >= 0) {
37
38 if (sa.sa.sa_family == AF_INET) {
39 uint32_t ip = ntohl(sa.in.sin_addr.s_addr);
40
41 snprintf(c, l, "TCP/IP client from %i.%i.%i.%i:%u",
42 ip >> 24,
43 (ip >> 16) & 0xFF,
44 (ip >> 8) & 0xFF,
45 ip & 0xFF,
46 ntohs(sa.in.sin_port));
47 return;
48 } else if (sa.sa.sa_family == AF_LOCAL) {
49 snprintf(c, l, "UNIX client for %s", sa.un.sun_path);
50 return;
51 }
52
53 }
54 snprintf(c, l, "Unknown network client");
55 return;
56 } else if (S_ISCHR(st.st_mode) && (fd == 0 || fd == 1)) {
57 snprintf(c, l, "STDIN/STDOUT client");
58 return;
59 }
60
61 snprintf(c, l, "Unknown client");
62 }