-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.cpp
More file actions
83 lines (78 loc) · 2.51 KB
/
server.cpp
File metadata and controls
83 lines (78 loc) · 2.51 KB
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
#include <iostream>
#include <memory>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/mman.h>
using namespace std;
int retrieve_fd(int sock_fd) {
struct alignas(struct cmsghdr) dummy {
char buf[CMSG_SPACE(sizeof(int))];
} u;
char iobuf[256] = {0};
struct iovec io = {
.iov_base = iobuf,
.iov_len = sizeof(iobuf) - 1
};
struct msghdr msg{};
msg.msg_iov = &io;
msg.msg_iovlen = 1;
msg.msg_control = reinterpret_cast<void*>(&u);
msg.msg_controllen = sizeof(u);
if (recvmsg(sock_fd, &msg, 0) < 0) {
cout << "recvmsg failed: " << strerror(errno) << endl;
} else {
for (auto cmsg = CMSG_FIRSTHDR(&msg); cmsg != nullptr; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
int fd;
memcpy(&fd, CMSG_DATA(cmsg), sizeof(fd));
close(sock_fd);
return fd;
}
}
}
close(sock_fd);
return -1;
}
int main() {
int listen_sock = socket(AF_UNIX, SOCK_STREAM, 0);
if (listen_sock <= 0) {
cout << "try to listen failed: " << strerror(errno) << endl;
return 1;
}
sockaddr_un listen_addr{AF_UNIX};
string sock_path = "/tmp/server.sock";
memcpy(reinterpret_cast<void*>(listen_addr.sun_path),
reinterpret_cast<const void*>(sock_path.c_str()), sock_path.length() + 1);
if (bind(listen_sock, reinterpret_cast<sockaddr*>(&listen_addr), sizeof(listen_addr))) {
cout << "try to bind failed: " << strerror(errno) << endl;
return 1;
}
if (listen(listen_sock, 128)) {
cout << "try to listen failed: " << strerror(errno) << endl;
return 1;
}
constexpr size_t buf_len = 1024;
auto buf = make_unique<char[]>(buf_len);
while (true) {
int client_sock = accept(listen_sock, nullptr, nullptr);
if (client_sock == -1) {
cout << "failed to accept new client: " << strerror(errno) << endl;
return 1;
}
int fd = retrieve_fd(client_sock);
if (fd < 0) {
continue;
}
auto addr = mmap(nullptr, 4096, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
if (addr == MAP_FAILED) {
cout << "mmap failed: " << strerror(errno) << endl;
close(fd);
continue;
}
strcpy(reinterpret_cast<char*>(addr), "some testing content\n");
}
return 0;
}