-static int api_ws_socket_unix(const char *path, int server)
-{
- int fd, rc;
- struct sockaddr_un addr;
- size_t length;
-
- length = strlen(path);
- if (length >= 108) {
- errno = ENAMETOOLONG;
- return -1;
- }
-
- if (server && path[0] != '@')
- unlink(path);
-
- fd = socket(AF_UNIX, SOCK_STREAM, 0);
- if (fd < 0)
- return fd;
-
- memset(&addr, 0, sizeof addr);
- addr.sun_family = AF_UNIX;
- strcpy(addr.sun_path, path);
- if (addr.sun_path[0] == '@')
- addr.sun_path[0] = 0; /* implement abstract sockets */
- if (server) {
- rc = bind(fd, (struct sockaddr *) &addr, (socklen_t)(sizeof addr));
- } else {
- rc = connect(fd, (struct sockaddr *) &addr, (socklen_t)(sizeof addr));
- }
- if (rc < 0) {
- close(fd);
- return rc;
- }
- return fd;
-}
-
-static int api_ws_socket_inet(const char *path, int server)
-{
- int rc, fd;
- const char *service, *host, *api;
- struct addrinfo hint, *rai, *iai;
-
- /* scan the uri */
- api = strrchr(path, '/');
- service = strrchr(path, ':');
- if (api == NULL || service == NULL || api < service) {
- errno = EINVAL;
- return -1;
- }
- host = strndupa(path, service++ - path);
- service = strndupa(service, api - service);
-
- /* get addr */
- memset(&hint, 0, sizeof hint);
- hint.ai_family = AF_INET;
- hint.ai_socktype = SOCK_STREAM;
- rc = getaddrinfo(host, service, &hint, &rai);
- if (rc != 0) {
- errno = EINVAL;
- return -1;
- }
-
- /* get the socket */
- iai = rai;
- while (iai != NULL) {
- fd = socket(iai->ai_family, iai->ai_socktype, iai->ai_protocol);
- if (fd >= 0) {
- if (server) {
- rc = bind(fd, iai->ai_addr, iai->ai_addrlen);
- } else {
- rc = connect(fd, iai->ai_addr, iai->ai_addrlen);
- }
- if (rc == 0) {
- freeaddrinfo(rai);
- return fd;
- }
- close(fd);
- }
- iai = iai->ai_next;
- }
- freeaddrinfo(rai);
- return -1;
-}
-
-static int api_ws_socket(const char *path, int server)
-{
- int fd, rc;
-
- /* check for systemd socket */
- if (0 == strncmp(path, "sd:", 3))
- fd = sd_fds_for(path + 3);
- else {
- /* check for unix socket */
- if (0 == strncmp(path, "unix:", 5))
- /* unix socket */
- fd = api_ws_socket_unix(path + 5, server);
- else
- /* inet socket */
- fd = api_ws_socket_inet(path, server);
-
- if (fd >= 0 && server) {
- rc = 1;
- setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &rc, sizeof rc);
- rc = listen(fd, 5);
- }
- }
- /* configure the socket */
- if (fd >= 0) {
- fcntl(fd, F_SETFD, FD_CLOEXEC);
- fcntl(fd, F_SETFL, O_NONBLOCK);
- }
- return fd;
-}
-