/*
 * Copyright 2014 Cloud Linux Zug GmbH
 *
 * Licensed under CLOUD LINUX LICENSE AGREEMENT
 * http://cloudlinux.com/docs/LICENSE.TXT
 *
 * The part the support library for lsapi & proxy_lsapi Apache modules
 * author Alexander Demeshko <ademeshko@cloudlinux.com>
 *
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/un.h>

int create_listen_socket( const char *sock_name, int backlog )
{
    struct sockaddr_un sock_addr;
    int sock, saved_errno, flag;

    sock_addr.sun_family = AF_UNIX;
    strncpy(sock_addr.sun_path, sock_name, sizeof sock_addr.sun_path );
    sock_addr.sun_path[sizeof(sock_addr.sun_path)-1] = '\0';
    unlink(sock_addr.sun_path);

    sock = socket( AF_UNIX, SOCK_STREAM, 0 );
    if ( sock == -1 )
        return -1;
        
    flag = 1;
    if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof flag )
       || bind(sock, (struct sockaddr*)(&sock_addr), sizeof sock_addr) 
       || listen(sock, backlog) )
    {
        saved_errno = errno;
        close(sock);
        errno = saved_errno;
    }
        
    return sock;
}
