Skip to content

Instantly share code, notes, and snippets.

@thelastlin
Last active August 28, 2023 05:25
Show Gist options
  • Save thelastlin/72baf145047bd18e6b5c4f8b1d9e9c0b to your computer and use it in GitHub Desktop.
Save thelastlin/72baf145047bd18e6b5c4f8b1d9e9c0b to your computer and use it in GitHub Desktop.
demo: launchd with inetdCompatibility
#include <arpa/inet.h>
#include <cstdlib>
#include <memory>
#include <syslog.h>
#include <thread>
#include <unistd.h>
int main()
{
openlog("demod", LOG_PID, LOG_DAEMON);
sockaddr_in sin;
socklen_t socket_type_len = sizeof(sin);
/* should be bound to stdin by inetd */
if (getsockname(0, (sockaddr*)&sin, &socket_type_len)) {
syslog(LOG_CRIT, "getsockname(): %s\n", strerror(errno));
exit(-1);
}
syslog(LOG_INFO, "%s:%d \n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
auto process = [](int fd, const sockaddr_in& peer) -> void {
auto ptr = std::make_unique<char[]>(256);
std::memset(ptr.get(), 0, 256);
while (read(fd, ptr.get(), 255) > 0) {
syslog(LOG_INFO, "fd %d (%s:%d): %s\n", fd, inet_ntoa(peer.sin_addr), ntohs(peer.sin_port), ptr.get());
}
close(fd);
};
while (true) {
sockaddr_in clientaddr;
socklen_t clientaddr_len = sizeof(clientaddr);
auto accepted = accept(0, (sockaddr*)&clientaddr, &clientaddr_len);
if (accepted < 0) {
syslog(LOG_CRIT, "accept(): %s\n", strerror(errno));
break;
}
syslog(LOG_INFO, "connected: %s:%d\n", inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port));
std::thread th(process, accepted, clientaddr);
th.detach();
}
closelog();
return 0;
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>demo.launchd_socket_listener</string>
<key>ProgramArguments</key>
<array>
<string>/Library/Application Support/socket_demo/launchd_inet_wait</string>
</array>
<key>Sockets</key>
<dict>
<key>Demo_SocketListerner</key>
<dict>
<key>SockPathName</key>
<string>/tmp/demo_launchd_socket</string>
</dict>
</dict>
<key>Sockets</key>
<dict>
<key>Listeners</key>
<dict>
<key>SockServiceName</key>
<string>29980</string>
</dict>
</dict>
<key>inetdCompatibility</key>
<dict>
<key>Wait</key>
<true/>
</dict>
</dict>
</plist>
@thelastlin
Copy link
Author

demo for systemd user: systemd-socket-activate -l 29980 --inetd

and then try to connect localhost:29980 by netcat

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment