<commit_before>/**
 * xrdp: A Remote Desktop Protocol server.
 *
 * Copyright (C) <NAME> 2004-2014
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * generic operating system calls
 *
 * put all the os / arch define in here you want
 */

/* To test for Windows (64 bit or 32 bit) use _WIN32 and _WIN64 in addition
   for 64 bit windows.  _WIN32 is defined for both.
   To test for Linux use __linux__.
   To test for BSD use BSD */

#if defined(HAVE_CONFIG_H)
#include "config_ac.h"
#endif
#if defined(_WIN32)
#include <windows.h>
#include <winsock.h>
#else
/* fix for solaris 10 with gcc 3.3.2 problem */
#if defined(sun) || defined(__sun)
#define ctid_t id_t
#endif
#include <unistd.h>
#include <errno.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/socket.h>
#if defined(XRDP_ENABLE_VSOCK)
#include <linux/vm_sockets.h>
#endif
#include <sys/un.h>
#include <sys/time.h>
#include <sys/times.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <dlfcn.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <signal.h>
#include <fcntl.h>
#include <pwd.h>
#include <time.h>
#include <grp.h>
#endif

#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <stdio.h>
#include <locale.h>

/* this is so we can use #ifdef BSD later */
/* This is the recommended way of detecting BSD in the
   FreeBSD Porter's Handbook. */
#if (defined(__unix__) || defined(unix)) && !defined(USG)
#include <sys/param.h>
#endif

#include "os_calls.h"
#include "arch.h"
#include "log.h"

/* for clearenv() */
#if defined(_WIN32)
#else
extern char **environ;
#endif

#if defined(__linux__)
#include <linux/unistd.h>
#endif

/* sys/ucred.h needs to be included to use struct xucred
 * in FreeBSD and OS X. No need for other BSDs except GNU/kFreeBSD */
#if defined(__FreeBSD__) || defined(__APPLE__) || defined(__FreeBSD_kernel__)
#include <sys/ucred.h>
#endif

/* for solaris */
#if !defined(PF_LOCAL)
#define PF_LOCAL AF_UNIX
#endif
#if !defined(INADDR_NONE)
#define INADDR_NONE ((unsigned long)-1)
#endif

/*****************************************************************************/
int
g_rm_temp_dir(void)
{
    return 0;
}

/*****************************************************************************/
int
g_mk_socket_path(const char *app_name)
{
    if (!g_directory_exist(XRDP_SOCKET_PATH))
    {
        if (!g_create_path(XRDP_SOCKET_PATH"/"))
        {
            /* if failed, still check if it got created by someone else */
            if (!g_directory_exist(XRDP_SOCKET_PATH))
            {
                log_message(LOG_LEVEL_ERROR,
                            "g_mk_socket_path: g_create_path(%s) failed",
                            XRDP_SOCKET_PATH);
                return 1;
            }
        }
        g_chmod_hex(XRDP_SOCKET_PATH, 0x1777);
    }
    return 0;
}

/*****************************************************************************/
void
g_init(const char *app_name)
{
#if defined(_WIN32)
    WSADATA wsadata;

    WSAStartup(2, &wsadata);
#endif

    /* In order to get g_mbstowcs and g_wcstombs to work properly with
       UTF-8 non-ASCII characters, LC_CTYPE cannot be "C" or blank.
       To select UTF-8 encoding without specifying any countries/languages,
       "C.UTF-8" is used but provided in few systems.

       See also: https://sourceware.org/glibc/wiki/Proposals/C.UTF-8 */
    char *lc_ctype;
    lc_ctype = setlocale(LC_CTYPE, "C.UTF-8");
    if (lc_ctype == NULL)
    {
        /* use en_US.UTF-8 instead if not available */
        setlocale(LC_CTYPE, "en_US.UTF-8");
    }

    g_mk_socket_path(app_name);
}

/*****************************************************************************/
void
g_deinit(void)
{
#if defined(_WIN32)
    WSACleanup();
#endif
    g_rm_temp_dir();
}

/*****************************************************************************/
/* allocate memory, returns a pointer to it, size bytes are allocated,
   if zero is non zero, each byte will be set to zero */
void *
g_malloc(int size, int zero)
{
    char *rv;

    rv = (char *)malloc(size);

    if (zero)
    {
        if (rv != 0)
        {
            memset(rv, 0, size);
        }
    }

    return rv;
}

/*****************************************************************************/
/* free the memory pointed to by ptr, ptr can be zero */
void
g_free(void *ptr)
{
    if (ptr != 0)
    {
        free(ptr);
    }
}

/*****************************************************************************/
/* output text to stdout, try to use g_write / g_writeln instead to avoid
   linux / windows EOL problems */
void
g_printf(const char *format, ...)
{
    va_list ap;

    va_start(ap, format);
    vfprintf(stdout, format, ap);
    va_end(ap);
}

/*****************************************************************************/
void
g_sprintf(char *dest, const char *format, ...)
{
    va_list ap;

    va_start(ap, format);
    vsprintf(dest, format, ap);
    va_end(ap);
}

/*****************************************************************************/
int
g_snprintf(char *dest, int len, const char *format, ...)
{
    int err;
    va_list ap;

    va_start(ap, format);
    err = vsnprintf(dest, len, format, ap);
    va_end(ap);

    return err;
}

/*****************************************************************************/
void
g_writeln(const char *format, ...)
{
    va_list ap;

    va_start(ap, format);
    vfprintf(stdout, format, ap);
    va_end(ap);
#if defined(_WIN32)
    g_printf("\r\n");
#else
    g_printf("\n");
#endif
}

/*****************************************************************************/
void
g_write(const char *format, ...)
{
    va_list ap;

    va_start(ap, format);
    vfprintf(stdout, format, ap);
    va_end(ap);
}

/*****************************************************************************/
/* produce a hex dump */
void
g_hexdump(const char *p, int len)
{
    unsigned char *line;
    int i;
    int thisline;
    int offset;

    line = (unsigned char *)p;
    offset = 0;

    while (offset < len)
    {
        g_printf("%04x ", offset);
        thisline = len - offset;

        if (thisline > 16)
        {
            thisline = 16;
        }

        for (i = 0; i < thisline; i++)
        {
            g_printf("%02x ", line[i]);
        }

        for (; i < 16; i++)
        {
            g_printf("   ");
        }

        for (i = 0; i < thisline; i++)
        {
            g_printf("%c", (line[i] >= 0x20 && line[i] < 0x7f) ? line[i] : '.');
        }

        g_writeln("%s", "");
        offset += thisline;
        line += thisline;
    }
}

/*****************************************************************************/
void
g_memset(void *ptr, int val, int size)
{
    memset(ptr, val, size);
}

/*****************************************************************************/
void
g_memcpy(void *d_ptr, const void *s_ptr, int size)
{
    memcpy(d_ptr, s_ptr, size);
}

/*****************************************************************************/
int
g_getchar(void)
{
    return getchar();
}

/*****************************************************************************/
/*Returns 0 on success*/
int
g_tcp_set_no_delay(int sck)
{
    int ret = 1; /* error */
    int option_value;
    socklen_t option_len;

    option_len = sizeof(option_value);

    /* SOL_TCP IPPROTO_TCP */
    if (getsockopt(sck, IPPROTO_TCP, TCP_NODELAY, (char *)&option_value,
                   &option_len) == 0)
    {
        if (option_value == 0)
        {
            option_value = 1;
            option_len = sizeof(option_value);

            if (setsockopt(sck, IPPROTO_TCP, TCP_NODELAY, (char *)&option_value,
                           option_len) == 0)
            {
                ret = 0; /* success */
            }
            else
            {
                g_writeln("Error setting tcp_nodelay");
            }
        }
    }
    else
    {
        g_writeln("Error getting tcp_nodelay");
    }

    return ret;
}

/*****************************************************************************/
/*Returns 0 on success*/
int
g_tcp_set_keepalive(int sck)
{
    int ret = 1; /* error */
    int option_value;
    socklen_t option_len;

    option_len = sizeof(option_value);

    /* SOL_TCP IPPROTO_TCP */
    if (getsockopt(sck, SOL_SOCKET, SO_KEEPALIVE, (char *)&option_value,
                   &option_len) == 0)
    {
        if (option_value == 0)
        {
            option_value = 1;
            option_len = sizeof(option_value);

            if (setsockopt(sck, SOL_SOCKET, SO_KEEPALIVE, (char *)&option_value,
                           option_len) == 0)
            {
                ret = 0; /* success */
            }
            else
            {
                g_writeln("Error setting tcp_keepalive");
            }
        }
    }
    else
    {
        g_writeln("Error getting tcp_keepalive");
    }

    return ret;
}

/*****************************************************************************/
/* returns a newly created socket or -1 on error */
/* in win32 a socket is an unsigned int, in linux, it's an int */
int
g_tcp_socket(void)
{
    int rv;
    int option_value;
    socklen_t option_len;

#if defined(XRDP_ENABLE_IPV6)
    rv = (int)socket(AF_INET6, SOCK_STREAM, 0);
    if (rv < 0)
    {
        switch (errno)
        {
            case EAFNOSUPPORT: /* if IPv6 not supported, retry IPv4 */
                log_message(LOG_LEVEL_INFO, "IPv6 not supported, falling back to IPv4");
                rv = (int)socket(AF_INET, SOCK_STREAM, 0);
                break;

            default:
                log_message(LOG_LEVEL_ERROR, "g_tcp_socket: %s", g_get_strerror());
                return -1;
        }
    }
#else
    rv = (int)socket(AF_INET, SOCK_STREAM, 0);
#endif
    if (rv < 0)
    {
        log_message(LOG_LEVEL_ERROR, "g_tcp_socket: %s", g_get_strerror());
        return -1;
    }
#if defined(XRDP_ENABLE_IPV6)
    option_len = sizeof(option_value);
    if (getsockopt(rv, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&option_value,
                   &option_len) == 0)
    {
        if (option_value != 0)
        {
#if defined(XRDP_ENABLE_IPV6ONLY)
            option_value = 1;
#else
            option_value = 0;
#endif
            option_len = sizeof(option_value);
            if (setsockopt(rv, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&option_value,
                       option_len) < 0)
            {
                log_message(LOG_LEVEL_ERROR, "g_tcp_socket: setsockopt() failed");
            }
        }
    }
#endif
    option_len = sizeof(option_value);
    if (getsockopt(rv, SOL_SOCKET, SO_REUSEADDR, (char *)&option_value,
                   &option_len) == 0)
    {
        if (option_value == 0)
        {
            option_value = 1;
            option_len = sizeof(option_value);
            if (setsockopt(rv, SOL_SOCKET, SO_REUSEADDR, (char *)&option_value,
                       option_len) < 0)
            {
                log_message(LOG_LEVEL_ERROR, "g_tcp_socket: setsockopt() failed");
            }
        }
    }

    option_len = sizeof(option_value);

    if (getsockopt(rv, SOL_SOCKET, SO_SNDBUF, (char *)&option_value,
                   &option_len) == 0)
    {
        if (option_value < (1024 * 32))
        {
            option_value = 1024 * 32;
            option_len = sizeof(option_value);
            if (setsockopt(rv, SOL_SOCKET, SO_SNDBUF, (char *)&option_value,
                       option_len) < 0)
            {
                log_message(LOG_LEVEL_ERROR, "g_tcp_socket: setsockopt() failed");
            }
        }
    }

    return rv;
}

/*****************************************************************************/
/* returns error */
int
g_sck_set_send_buffer_bytes(int sck, int bytes)
{
    int option_value;
    socklen_t option_len;

    option_value = bytes;
    option_len = sizeof(option_value);
    if (setsockopt(sck, SOL_SOCKET, SO_SNDBUF, (char *)&option_value,
                   option_len) != 0)
    {
        return 1;
    }
    return 0;
}

/*****************************************************************************/
/* returns error */
int
g_sck_get_send_buffer_bytes(int sck, int *bytes)
{
    int option_value;
    socklen_t option_len;

    option_value = 0;
    option_len = sizeof(option_value);
    if (getsockopt(sck, SOL_SOCKET, SO_SNDBUF, (char *)&option_value,
                   &option_len) != 0)
    {
        return 1;
    }
    *bytes = option_value;
    return 0;
}

/*****************************************************************************/
/* returns error */
int
g_sck_set_recv_buffer_bytes(int sck, int bytes)
{
    int option_value;
    socklen_t option_len;

    option_value = bytes;
    option_len = sizeof(option_value);
    if (setsockopt(sck, SOL_SOCKET, SO_RCVBUF, (char *)&option_value,
                   option_len) != 0)
    {
        return 1;
    }
    return 0;
}

/*****************************************************************************/
/* returns error */
int
g_sck_get_recv_buffer_bytes(int sck, int *bytes)
{
    int option_value;
    socklen_t option_len;

    option_value = 0;
    option_len = sizeof(option_value);
    if (getsockopt(sck, SOL_SOCKET, SO_RCVBUF, (char *)&option_value,
                   &option_len) != 0)
    {
        return 1;
    }
    *bytes = option_value;
    return 0;
}

/*****************************************************************************/
int
g_sck_local_socket(void)
{
#if defined(_WIN32)
    return -1;
#else
    return socket(PF_LOCAL, SOCK_STREAM, 0);
#endif
}

/*****************************************************************************/
int
g_sck_vsock_socket(void)
{
#if defined(XRDP_ENABLE_VSOCK)
    return socket(PF_VSOCK, SOCK_STREAM, 0);
#else
    return -1;
#endif
}

/*****************************************************************************/
/* returns error */
int
g_sck_get_peer_cred(int sck, int *pid, int *uid, int *gid)
{
#if defined(SO_PEERCRED)
    socklen_t ucred_length;
    struct myucred
    {
        pid_t pid;
        uid_t uid;
        gid_t gid;
    } credentials;

    ucred_length = sizeof(credentials);
    if (getsockopt(sck, SOL_SOCKET, SO_PEERCRED, &credentials, &ucred_length))
    {
        return 1;
    }
    if (pid != 0)
    {
        *pid = credentials.pid;
    }
    if (uid != 0)
    {
        *uid = credentials.uid;
    }
    if (gid != 0)
    {
        *gid = credentials.gid;
    }
    return 0;
#elif defined(LOCAL_PEERCRED)
    /* FreeBSD, OS X reach here*/
    struct xucred xucred;
    unsigned int xucred_length;
    xucred_length = sizeof(xucred);

    if (getsockopt(sck, SOL_SOCKET, LOCAL_PEERCRED, &xucred, &xucred_length))
    {
            return 1;
    }
    if (pid !=0)
    {
        *pid = 0; /* can't get pid in FreeBSD, OS X */
    }
    if (uid != 0)
    {
        *uid = xucred.cr_uid;
    }
    if (gid != 0) {
        *gid = xucred.cr_gid;
    }
    return 0;
#else
    return 1;
#endif
}

/*****************************************************************************/
void
g_sck_close(int sck)
{
#if defined(_WIN32)
    closesocket(sck);
#else
    char sockname[128];
    union
    {
        struct sockaddr sock_addr;
        struct sockaddr_in sock_addr_in;
#if defined(XRDP_ENABLE_IPV6)
        struct sockaddr_in6 sock_addr_in6;
#endif
    } sock_info;
    socklen_t sock_len = sizeof(sock_info);

    memset(&sock_info, 0, sizeof(sock_info));

    if (getsockname(sck, &sock_info.sock_addr, &sock_len) == 0)
    {
        switch (sock_info.sock_addr.sa_family)
        {
            case AF_INET:
            {
                struct sockaddr_in *sock_addr_in = &sock_info.sock_addr_in;

                g_snprintf(sockname, sizeof(sockname), "AF_INET %s:%d",
                           inet_ntoa(sock_addr_in->sin_addr),
                           ntohs(sock_addr_in->sin_port));
                break;
            }

#if defined(XRDP_ENABLE_IPV6)

            case AF_INET6:
            {
                char addr[48];
                struct sockaddr_in6 *sock_addr_in6 = &sock_info.sock_addr_in6;

                g_snprintf(sockname, sizeof(sockname), "AF_INET6 %s port %d",
                           inet_ntop(sock_addr_in6->sin6_family,
                                     &sock_addr_in6->sin6_addr, addr, sizeof(addr)),
                           ntohs(sock_addr_in6->sin6_port));
                break;
            }

#endif

            case AF_UNIX:
                g_snprintf(sockname, sizeof(sockname), "AF_UNIX");
                break;

            default:
                g_snprintf(sockname, sizeof(sockname), "unknown family %d",
                           sock_info.sock_addr.sa_family);
                break;
        }
    }
    else
    {
        log_message(LOG_LEVEL_WARNING, "getsockname() failed on socket %d: %s",
                    sck, g_get_strerror());

        if (errno == EBADF || errno == ENOTSOCK)
        {
            return;
        }

        g_snprintf(sockname, sizeof(sockname), "unknown");
    }

    if (close(sck) == 0)
    {
        log_message(LOG_LEVEL_DEBUG, "Closed socket %d (%s)", sck, sockname);
    }
    else
    {
        log_message(LOG_LEVEL_WARNING, "Cannot close socket %d (%s): %s", sck,
                    sockname, g_get_strerror());
    }

#endif
}

#if defined(XRDP_ENABLE_IPV6)
/*****************************************************************************/
/* Helper function for g_tcp_connect.                                        */
static int
connect_loopback(int sck, const char *port)
{
    struct sockaddr_in6 sa;
    struct sockaddr_in s;
    int res;

    // First IPv6
    g_memset(&sa, 0, sizeof(sa));
    sa.sin6_family = AF_INET6;
    sa.sin6_addr = in6addr_loopback;             // IPv6 ::1
    sa.sin6_port = htons((tui16)atoi(port));
    res = connect(sck, (struct sockaddr*)&sa, sizeof(sa));
    if (res == -1 && errno == EINPROGRESS)
    {
        return -1;
    }
    if (res == 0 || (res == -1 && errno == EISCONN))
    {
        return 0;
    }

    // else IPv4
    g_memset(&s, 0, sizeof(s));
    s.sin_family = AF_INET;
    s.sin_addr.s_addr = htonl(INADDR_LOOPBACK);  // IPv4 127.0.0.1
    s.sin_port = htons((tui16)atoi(port));
    res = connect(sck, (struct sockaddr*)&s, sizeof(s));
    if (res == -1 && errno == EINPROGRESS)
    {
        return -1;
    }
    if (res == 0 || (res == -1 && errno == EISCONN))
    {
        return 0;
    }

    // else IPv6 with IPv4 address
    g_memset(&sa, 0, sizeof(sa));
    sa.sin6_family = AF_INET6;
    inet_pton(AF_INET6, "::FFFF:127.0.0.1", &sa.sin6_addr);
    sa.sin6_port = htons((tui16)atoi(port));
    res = connect(sck, (struct sockaddr*)&sa, sizeof(sa));
    if (res == -1 && errno == EINPROGRESS)
    {
        return -1;
    }
    if (res == 0 || (res == -1 && errno == EISCONN))
    {
        return 0;
    }

    return -1;
}
#endif

/*****************************************************************************/
/* returns error, zero is good                                               */
/* The connection might get to be in progress, if so -1 is returned.         */
/* The caller needs to call again to check if succeed.                       */
#if defined(XRDP_ENABLE_IPV6)
int
g_tcp_connect(int sck, const char *address, const char *port)
{
    int res = 0;
    struct addrinfo p;
    struct addrinfo *h = (struct addrinfo *)NULL;
    struct addrinfo *rp = (struct addrinfo *)NULL;

    g_memset(&p, 0, sizeof(struct addrinfo));

    p.ai_socktype = SOCK_STREAM;
    p.ai_protocol = IPPROTO_TCP;
    p.ai_flags = AI_ADDRCONFIG | AI_V4MAPPED;
    p.ai_family = AF_INET6;
    if (g_strcmp(address, "127.0.0.1") == 0)
    {
        return connect_loopback(sck, port);
    }
    else
    {
        res = getaddrinfo(address, port, &p, &h);
    }
    if (res != 0)
    {
        log_message(LOG_LEVEL_ERROR, "g_tcp_connect(%d, %s, %s): getaddrinfo() failed: %s",
                    sck, address, port, gai_strerror(res));
    }
    if (res > -1)
    {
        if (h != NULL)
        {
            for (rp = h; rp != NULL; rp = rp->ai_next)
            {
                res = connect(sck, (struct sockaddr *)(rp->ai_addr),
                              rp->ai_addrlen);
                if (res == -1 && errno == EINPROGRESS)
                {
                    break; /* Return -1 */
                }
                if (res == 0 || (res == -1 && errno == EISCONN))
                {
                    res = 0;
                    break; /* Success */
                }
            }
            freeaddrinfo(h);
        }
    }

    return res;
}
#else
int
g_tcp_connect(int sck, const char* address, const char* port)
{
    struct sockaddr_in s;
    struct hostent* h;
    int res;

    g_memset(&s, 0, sizeof(struct sockaddr_in));
    s.sin_family = AF_INET;
    s.sin_port = htons((tui16)atoi(port));
    s.sin_addr.s_addr = inet_addr(address);
    if (s.sin_addr.s_addr == INADDR_NONE)
    {
        h = gethostbyname(address);
        if (h != 0)
        {
            if (h->h_name != 0)
            {
                if (h->h_addr_list != 0)
                {
                    if ((*(h->h_addr_list)) != 0)
                    {
                        s.sin_addr.s_addr = *((int*)(*(h->h_addr_list)));
                    }
                }
            }
        }
    }
    res = connect(sck, (struct sockaddr*)&s, sizeof(struct sockaddr_in));

    /* Mac OSX connect() returns -1 for already established connections */
    if (res == -1 && errno == EISCONN)
    {
        res = 0;
    }

    return res;
}
#endif

/*****************************************************************************/
/* returns error, zero is good */
int
g_sck_local_connect(int sck, const char *port)
{
#if defined(_WIN32)
    return -1;
#else
    struct sockaddr_un s;

    memset(&s, 0, sizeof(struct sockaddr_un));
    s.sun_family = AF_UNIX;
    strncpy(s.sun_path, port, sizeof(s.sun_path));
    s.sun_path[sizeof(s.sun_path) - 1] = 0;

    return connect(sck, (struct sockaddr *)&s, sizeof(struct sockaddr_un));
#endif
}

/*****************************************************************************/
int
g_sck_set_non_blocking(int sck)
{
    unsigned long i;

#if defined(_WIN32)
    i = 1;
    ioctlsocket(sck, FIONBIO, &i);
#else
    i = fcntl(sck, F_GETFL);
    i = i | O_NONBLOCK;
    if (fcntl(sck, F_SETFL, i) < 0)
    {
        log_message(LOG_LEVEL_ERROR, "g_sck_set_non_blocking: fcntl() failed");
    }
#endif
    return 0;
}

#if defined(XRDP_ENABLE_IPV6)
/*****************************************************************************/
/* returns error, zero is good */
int
g_tcp_bind(int sck, const char *port)
{
    struct sockaddr_in6 sa;
    struct sockaddr_in s;
    int errno6;

    // First IPv6
    g_memset(&sa, 0, sizeof(sa));
    sa.sin6_family = AF_INET6;
    sa.sin6_addr = in6addr_any;                 // IPv6 ::
    sa.sin6_port = htons((tui16)atoi(port));
    if (bind(sck, (struct sockaddr*)&sa, sizeof(sa)) == 0)
    {
        return 0;
    }
    errno6 = errno;

    // else IPv4
    g_memset(&s, 0, sizeof(s));
    s.sin_family = AF_INET;
    s.sin_addr.s_addr = htonl(INADDR_ANY);     // IPv4 0.0.0.0
    s.sin_port = htons((tui16)atoi(port));
    if (bind(sck, (struct sockaddr*)&s, sizeof(s)) == 0)
    {
        return 0;
    }

    log_message(LOG_LEVEL_ERROR, "g_tcp_bind(%d, %s) failed "
                "bind IPv6 (errno=%d) and IPv4 (errno=%d).",
                sck, port, errno6, errno);
    return -1;
}
#else
int
g_tcp_bind(int sck, const char* port)
{
    struct sockaddr_in s;

    memset(&s, 0, sizeof(struct sockaddr_in));
    s.sin_family = AF_INET;
    s.sin_port = htons((tui16)atoi(port));
    s.sin_addr.s_addr = INADDR_ANY;
    return bind(sck, (struct sockaddr*)&s, sizeof(struct sockaddr_in));
}
#endif

/*****************************************************************************/
int
g_sck_local_bind(int sck, const char *port)
{
#if defined(_WIN32)
    return -1;
#else
    struct sockaddr_un s;

    memset(&s, 0, sizeof(struct sockaddr_un));
    s.sun_family = AF_UNIX;
    strncpy(s.sun_path, port, sizeof(s.sun_path));
    s.sun_path[sizeof(s.sun_path) - 1] = 0;

    return bind(sck, (struct sockaddr *)&s, sizeof(struct sockaddr_un));
#endif
}

/*****************************************************************************/
int
g_sck_vsock_bind(int sck, const char *port)
{
#if defined(XRDP_ENABLE_VSOCK)
    struct sockaddr_vm s;

    g_memset(&s, 0, sizeof(struct sockaddr_vm));
    s.svm_family = AF_VSOCK;
    s.svm_port = atoi(port);
    s.svm_cid = VMADDR_CID_ANY;

    return bind(sck, (struct sockaddr *)&s, sizeof(struct sockaddr_vm));
#else
    return -1;
#endif
}

#if defined(XRDP_ENABLE_IPV6)
/*****************************************************************************/
/* Helper function for g_tcp_bind_address.                                   */
static int
bind_loopback(int sck, const char *port)
{
    struct sockaddr_in6 sa;
    struct sockaddr_in s;
    int errno6;
    int errno4;

    // First IPv6
    g_memset(&sa, 0, sizeof(sa));
    sa.sin6_family = AF_INET6;
    sa.sin6_addr = in6addr_loopback;             // IPv6 ::1
    sa.sin6_port = htons((tui16)atoi(port));
    if (bind(sck, (struct sockaddr*)&sa, sizeof(sa)) == 0)
    {
        return 0;
    }
    errno6 = errno;

    // else IPv4
    g_memset(&s, 0, sizeof(s));
    s.sin_family = AF_INET;
    s.sin_addr.s_addr = htonl(INADDR_LOOPBACK);  // IPv4 127.0.0.1
    s.sin_port = htons((tui16)atoi(port));
    if (bind(sck, (struct sockaddr*)&s, sizeof(s)) == 0)
    {
        return 0;
    }
    errno4 = errno;

    // else IPv6 with IPv4 address
    g_memset(&sa, 0, sizeof(sa));
    sa.sin6_family = AF_INET6;
    inet_pton(AF_INET6, "::FFFF:127.0.0.1", &sa.sin6_addr);
    sa.sin6_port = htons((tui16)atoi(port));
    if (bind(sck, (struct sockaddr*)&sa, sizeof(sa)) == 0)
    {
        return 0;
    }

    log_message(LOG_LEVEL_ERROR, "bind_loopback(%d, %s) failed; "
                "IPv6 ::1 (errno=%d), IPv4 127.0.0.1 (errno=%d) and IPv6 fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b:127.0.0.1 (errno=%d).",
                sck, port, errno6, errno4, errno);
    return -1;
}

/*****************************************************************************/
/* Helper function for g_tcp_bind_address.                                   */
/* Returns error, zero is good.                                              */
static int
getaddrinfo_bind(int sck, const char *port, const char *address)
{
    int res;
    int error;
    struct addrinfo hints;
    struct addrinfo *list;
    struct addrinfo *i;

    res = -1;
    g_memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_flags = 0;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    error = getaddrinfo(address, port, &hints, &list);
    if (error == 0)
    {
        i = list;
        while ((i != 0) && (res < 0))
        {
            res = bind(sck, i->ai_addr, i->ai_addrlen);
            i = i->ai_next;
        }
        freeaddrinfo(list);
    }
    else
    {
        log_message(LOG_LEVEL_ERROR, "getaddrinfo error: %s", gai_strerror(error));
        return -1;
    }
    return res;
}

/*****************************************************************************/
/* Binds a socket to a port. If no specified address the port will be bind   */
/* to 'any', i.e. available on all network.                                  */
/* For bind to local host, see valid address strings below.                  */
/* Returns error, zero is good.                                              */
int
g_tcp_bind_address(int sck, const char *port, const char *address)
{
    int res;

    if ((address == 0) ||
        (address[0] == 0) ||
        (g_strcmp(address, "0.0.0.0") == 0) ||
        (g_strcmp(address, "::") == 0))
    {
        return g_tcp_bind(sck, port);
    }

    if ((g_strcmp(address, "127.0.0.1") == 0) ||
        (g_strcmp(address, "::1") == 0) ||
        (g_strcmp(address, "localhost") == 0))
    {
        return bind_loopback(sck, port);
    }

    // Let getaddrinfo translate the address string...
    // IPv4: ddd.ddd.ddd.ddd
    // IPv6: x:x:x:x:x:x:x:x%<interface>, or x::x:x:x:x%<interface>
    res = getaddrinfo_bind(sck, port, address);
    if (res != 0)
    {
        // If fail and it is an IPv4 address, try with the mapped address
        struct in_addr a;
        if ((inet_aton(address, &a) == 1) && (strlen(address) <= 15))
        {
            char sz[7+15+1];
            sprintf(sz, "::FFFF:%s", address);
            res = getaddrinfo_bind(sck, port, sz);
            if (res == 0)
            {
                return 0;
            }
        }

        log_message(LOG_LEVEL_ERROR, "g_tcp_bind_address(%d, %s, %s) Failed!",
                    sck, port, address);
        return -1;
    }
    return 0;
}
#else
int
g_tcp_bind_address(int sck, const char* port, const char* address)
{
    struct sockaddr_in s;

    memset(&s, 0, sizeof(struct sockaddr_in));
    s.sin_family = AF_INET;
    s.sin_port = htons((tui16)atoi(port));
    s.sin_addr.s_addr = INADDR_ANY;
    if (inet_aton(address, &s.sin_addr) < 0)
    {
        return -1; /* bad address */
    }
    return bind(sck, (struct sockaddr*)&s, sizeof(struct sockaddr_in));
}
#endif

/*****************************************************************************/
/* returns error, zero is good */
int
g_sck_listen(int sck)
{
    return listen(sck, 2);
}

/*****************************************************************************/
int
g_tcp_accept(int sck)
{
    int ret;
    char msg[256];
    union
    {
        struct sockaddr sock_addr;
        struct sockaddr_in sock_addr_in;
#if defined(XRDP_ENABLE_IPV6)
        struct sockaddr_in6 sock_addr_in6;
#endif
    } sock_info;

    socklen_t sock_len = sizeof(sock_info);
    memset(&sock_info, 0, sock_len);

    ret = accept(sck, (struct sockaddr *)&sock_info, &sock_len);

    if (ret > 0)
    {
        switch(sock_info.sock_addr.sa_family)
        {
            case AF_INET:
            {
                struct sockaddr_in *sock_addr_in = &sock_info.sock_addr_in;

                g_snprintf(msg, sizeof(msg), "A connection received from %s port %d",
                           inet_ntoa(sock_addr_in->sin_addr),
                           ntohs(sock_addr_in->sin_port));
                log_message(LOG_LEVEL_INFO, "%s", msg);

                break;
            }

#if defined(XRDP_ENABLE_IPV6)

            case AF_INET6:
            {
                struct sockaddr_in6 *sock_addr_in6 = &sock_info.sock_addr_in6;
                char addr[256];

                inet_ntop(sock_addr_in6->sin6_family,
                          &sock_addr_in6->sin6_addr, addr, sizeof(addr));
                g_snprintf(msg, sizeof(msg), "A connection received from %s port %d",
                           addr, ntohs(sock_addr_in6->sin6_port));
                log_message(LOG_LEVEL_INFO, "%s", msg);

                break;

            }

#endif
        }
    }

    return ret;
}

/*****************************************************************************/
int
g_sck_accept(int sck, char *addr, int addr_bytes, char *port, int port_bytes)
{
    int ret;
    char msg[256];
    union
    {
        struct sockaddr sock_addr;
        struct sockaddr_in sock_addr_in;
#if defined(XRDP_ENABLE_IPV6)
        struct sockaddr_in6 sock_addr_in6;
#endif
        struct sockaddr_un sock_addr_un;
    } sock_info;

    socklen_t sock_len = sizeof(sock_info);
    memset(&sock_info, 0, sock_len);

    ret = accept(sck, (struct sockaddr *)&sock_info, &sock_len);

    if (ret > 0)
    {
        switch(sock_info.sock_addr.sa_family)
        {
            case AF_INET:
            {
                struct sockaddr_in *sock_addr_in = &sock_info.sock_addr_in;

                g_snprintf(addr, addr_bytes, "%s", inet_ntoa(sock_addr_in->sin_addr));
                g_snprintf(port, port_bytes, "%d", ntohs(sock_addr_in->sin_port));
                g_snprintf(msg, sizeof(msg),
                           "AF_INET connection received from %s port %s",
                           addr, port);
                break;
            }

#if defined(XRDP_ENABLE_IPV6)

            case AF_INET6:
            {
                struct sockaddr_in6 *sock_addr_in6 = &sock_info.sock_addr_in6;

                inet_ntop(sock_addr_in6->sin6_family,
                          &sock_addr_in6->sin6_addr, addr, addr_bytes);
                g_snprintf(port, port_bytes, "%d", ntohs(sock_addr_in6->sin6_port));
                g_snprintf(msg, sizeof(msg),
                           "AF_INET6 connection received from %s port %s",
                           addr, port);
                break;
            }

#endif

            case AF_UNIX:
            {
                g_strncpy(addr, "", addr_bytes - 1);
                g_strncpy(port, "", port_bytes - 1);
                g_snprintf(msg, sizeof(msg), "AF_UNIX connection received");
                break;
            }
            default:
            {
                g_strncpy(addr, "", addr_bytes - 1);
                g_strncpy(port, "", port_bytes - 1);
                g_snprintf(msg, sizeof(msg),
                           "connection received, unknown socket family %d",
                           sock_info.sock_addr.sa_family);
                break;
            }
        }


        log_message(LOG_LEVEL_INFO, "Socket %d: %s", ret, msg);

    }

    return ret;
}

/*****************************************************************************/
/*
 * TODO: this function writes not only IP address, name is confusing<commit_msg>Implements the accept/close logic for vsock<commit_after>/**
 * xrdp: A Remote Desktop Protocol server.
 *
 * Copyright (C) <NAME> 2004-2014
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * generic operating system calls
 *
 * put all the os / arch define in here you want
 */

/* To test for Windows (64 bit or 32 bit) use _WIN32 and _WIN64 in addition
   for 64 bit windows.  _WIN32 is defined for both.
   To test for Linux use __linux__.
   To test for BSD use BSD */

#if defined(HAVE_CONFIG_H)
#include "config_ac.h"
#endif
#if defined(_WIN32)
#include <windows.h>
#include <winsock.h>
#else
/* fix for solaris 10 with gcc 3.3.2 problem */
#if defined(sun) || defined(__sun)
#define ctid_t id_t
#endif
#include <unistd.h>
#include <errno.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/socket.h>
#if defined(XRDP_ENABLE_VSOCK)
#include <linux/vm_sockets.h>
#endif
#include <sys/un.h>
#include <sys/time.h>
#include <sys/times.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <dlfcn.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <signal.h>
#include <fcntl.h>
#include <pwd.h>
#include <time.h>
#include <grp.h>
#endif

#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <stdio.h>
#include <locale.h>

/* this is so we can use #ifdef BSD later */
/* This is the recommended way of detecting BSD in the
   FreeBSD Porter's Handbook. */
#if (defined(__unix__) || defined(unix)) && !defined(USG)
#include <sys/param.h>
#endif

#include "os_calls.h"
#include "arch.h"
#include "log.h"

/* for clearenv() */
#if defined(_WIN32)
#else
extern char **environ;
#endif

#if defined(__linux__)
#include <linux/unistd.h>
#endif

/* sys/ucred.h needs to be included to use struct xucred
 * in FreeBSD and OS X. No need for other BSDs except GNU/kFreeBSD */
#if defined(__FreeBSD__) || defined(__APPLE__) || defined(__FreeBSD_kernel__)
#include <sys/ucred.h>
#endif

/* for solaris */
#if !defined(PF_LOCAL)
#define PF_LOCAL AF_UNIX
#endif
#if !defined(INADDR_NONE)
#define INADDR_NONE ((unsigned long)-1)
#endif

/*****************************************************************************/
int
g_rm_temp_dir(void)
{
    return 0;
}

/*****************************************************************************/
int
g_mk_socket_path(const char *app_name)
{
    if (!g_directory_exist(XRDP_SOCKET_PATH))
    {
        if (!g_create_path(XRDP_SOCKET_PATH"/"))
        {
            /* if failed, still check if it got created by someone else */
            if (!g_directory_exist(XRDP_SOCKET_PATH))
            {
                log_message(LOG_LEVEL_ERROR,
                            "g_mk_socket_path: g_create_path(%s) failed",
                            XRDP_SOCKET_PATH);
                return 1;
            }
        }
        g_chmod_hex(XRDP_SOCKET_PATH, 0x1777);
    }
    return 0;
}

/*****************************************************************************/
void
g_init(const char *app_name)
{
#if defined(_WIN32)
    WSADATA wsadata;

    WSAStartup(2, &wsadata);
#endif

    /* In order to get g_mbstowcs and g_wcstombs to work properly with
       UTF-8 non-ASCII characters, LC_CTYPE cannot be "C" or blank.
       To select UTF-8 encoding without specifying any countries/languages,
       "C.UTF-8" is used but provided in few systems.

       See also: https://sourceware.org/glibc/wiki/Proposals/C.UTF-8 */
    char *lc_ctype;
    lc_ctype = setlocale(LC_CTYPE, "C.UTF-8");
    if (lc_ctype == NULL)
    {
        /* use en_US.UTF-8 instead if not available */
        setlocale(LC_CTYPE, "en_US.UTF-8");
    }

    g_mk_socket_path(app_name);
}

/*****************************************************************************/
void
g_deinit(void)
{
#if defined(_WIN32)
    WSACleanup();
#endif
    g_rm_temp_dir();
}

/*****************************************************************************/
/* allocate memory, returns a pointer to it, size bytes are allocated,
   if zero is non zero, each byte will be set to zero */
void *
g_malloc(int size, int zero)
{
    char *rv;

    rv = (char *)malloc(size);

    if (zero)
    {
        if (rv != 0)
        {
            memset(rv, 0, size);
        }
    }

    return rv;
}

/*****************************************************************************/
/* free the memory pointed to by ptr, ptr can be zero */
void
g_free(void *ptr)
{
    if (ptr != 0)
    {
        free(ptr);
    }
}

/*****************************************************************************/
/* output text to stdout, try to use g_write / g_writeln instead to avoid
   linux / windows EOL problems */
void
g_printf(const char *format, ...)
{
    va_list ap;

    va_start(ap, format);
    vfprintf(stdout, format, ap);
    va_end(ap);
}

/*****************************************************************************/
void
g_sprintf(char *dest, const char *format, ...)
{
    va_list ap;

    va_start(ap, format);
    vsprintf(dest, format, ap);
    va_end(ap);
}

/*****************************************************************************/
int
g_snprintf(char *dest, int len, const char *format, ...)
{
    int err;
    va_list ap;

    va_start(ap, format);
    err = vsnprintf(dest, len, format, ap);
    va_end(ap);

    return err;
}

/*****************************************************************************/
void
g_writeln(const char *format, ...)
{
    va_list ap;

    va_start(ap, format);
    vfprintf(stdout, format, ap);
    va_end(ap);
#if defined(_WIN32)
    g_printf("\r\n");
#else
    g_printf("\n");
#endif
}

/*****************************************************************************/
void
g_write(const char *format, ...)
{
    va_list ap;

    va_start(ap, format);
    vfprintf(stdout, format, ap);
    va_end(ap);
}

/*****************************************************************************/
/* produce a hex dump */
void
g_hexdump(const char *p, int len)
{
    unsigned char *line;
    int i;
    int thisline;
    int offset;

    line = (unsigned char *)p;
    offset = 0;

    while (offset < len)
    {
        g_printf("%04x ", offset);
        thisline = len - offset;

        if (thisline > 16)
        {
            thisline = 16;
        }

        for (i = 0; i < thisline; i++)
        {
            g_printf("%02x ", line[i]);
        }

        for (; i < 16; i++)
        {
            g_printf("   ");
        }

        for (i = 0; i < thisline; i++)
        {
            g_printf("%c", (line[i] >= 0x20 && line[i] < 0x7f) ? line[i] : '.');
        }

        g_writeln("%s", "");
        offset += thisline;
        line += thisline;
    }
}

/*****************************************************************************/
void
g_memset(void *ptr, int val, int size)
{
    memset(ptr, val, size);
}

/*****************************************************************************/
void
g_memcpy(void *d_ptr, const void *s_ptr, int size)
{
    memcpy(d_ptr, s_ptr, size);
}

/*****************************************************************************/
int
g_getchar(void)
{
    return getchar();
}

/*****************************************************************************/
/*Returns 0 on success*/
int
g_tcp_set_no_delay(int sck)
{
    int ret = 1; /* error */
    int option_value;
    socklen_t option_len;

    option_len = sizeof(option_value);

    /* SOL_TCP IPPROTO_TCP */
    if (getsockopt(sck, IPPROTO_TCP, TCP_NODELAY, (char *)&option_value,
                   &option_len) == 0)
    {
        if (option_value == 0)
        {
            option_value = 1;
            option_len = sizeof(option_value);

            if (setsockopt(sck, IPPROTO_TCP, TCP_NODELAY, (char *)&option_value,
                           option_len) == 0)
            {
                ret = 0; /* success */
            }
            else
            {
                g_writeln("Error setting tcp_nodelay");
            }
        }
    }
    else
    {
        g_writeln("Error getting tcp_nodelay");
    }

    return ret;
}

/*****************************************************************************/
/*Returns 0 on success*/
int
g_tcp_set_keepalive(int sck)
{
    int ret = 1; /* error */
    int option_value;
    socklen_t option_len;

    option_len = sizeof(option_value);

    /* SOL_TCP IPPROTO_TCP */
    if (getsockopt(sck, SOL_SOCKET, SO_KEEPALIVE, (char *)&option_value,
                   &option_len) == 0)
    {
        if (option_value == 0)
        {
            option_value = 1;
            option_len = sizeof(option_value);

            if (setsockopt(sck, SOL_SOCKET, SO_KEEPALIVE, (char *)&option_value,
                           option_len) == 0)
            {
                ret = 0; /* success */
            }
            else
            {
                g_writeln("Error setting tcp_keepalive");
            }
        }
    }
    else
    {
        g_writeln("Error getting tcp_keepalive");
    }

    return ret;
}

/*****************************************************************************/
/* returns a newly created socket or -1 on error */
/* in win32 a socket is an unsigned int, in linux, it's an int */
int
g_tcp_socket(void)
{
    int rv;
    int option_value;
    socklen_t option_len;

#if defined(XRDP_ENABLE_IPV6)
    rv = (int)socket(AF_INET6, SOCK_STREAM, 0);
    if (rv < 0)
    {
        switch (errno)
        {
            case EAFNOSUPPORT: /* if IPv6 not supported, retry IPv4 */
                log_message(LOG_LEVEL_INFO, "IPv6 not supported, falling back to IPv4");
                rv = (int)socket(AF_INET, SOCK_STREAM, 0);
                break;

            default:
                log_message(LOG_LEVEL_ERROR, "g_tcp_socket: %s", g_get_strerror());
                return -1;
        }
    }
#else
    rv = (int)socket(AF_INET, SOCK_STREAM, 0);
#endif
    if (rv < 0)
    {
        log_message(LOG_LEVEL_ERROR, "g_tcp_socket: %s", g_get_strerror());
        return -1;
    }
#if defined(XRDP_ENABLE_IPV6)
    option_len = sizeof(option_value);
    if (getsockopt(rv, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&option_value,
                   &option_len) == 0)
    {
        if (option_value != 0)
        {
#if defined(XRDP_ENABLE_IPV6ONLY)
            option_value = 1;
#else
            option_value = 0;
#endif
            option_len = sizeof(option_value);
            if (setsockopt(rv, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&option_value,
                       option_len) < 0)
            {
                log_message(LOG_LEVEL_ERROR, "g_tcp_socket: setsockopt() failed");
            }
        }
    }
#endif
    option_len = sizeof(option_value);
    if (getsockopt(rv, SOL_SOCKET, SO_REUSEADDR, (char *)&option_value,
                   &option_len) == 0)
    {
        if (option_value == 0)
        {
            option_value = 1;
            option_len = sizeof(option_value);
            if (setsockopt(rv, SOL_SOCKET, SO_REUSEADDR, (char *)&option_value,
                       option_len) < 0)
            {
                log_message(LOG_LEVEL_ERROR, "g_tcp_socket: setsockopt() failed");
            }
        }
    }

    option_len = sizeof(option_value);

    if (getsockopt(rv, SOL_SOCKET, SO_SNDBUF, (char *)&option_value,
                   &option_len) == 0)
    {
        if (option_value < (1024 * 32))
        {
            option_value = 1024 * 32;
            option_len = sizeof(option_value);
            if (setsockopt(rv, SOL_SOCKET, SO_SNDBUF, (char *)&option_value,
                       option_len) < 0)
            {
                log_message(LOG_LEVEL_ERROR, "g_tcp_socket: setsockopt() failed");
            }
        }
    }

    return rv;
}

/*****************************************************************************/
/* returns error */
int
g_sck_set_send_buffer_bytes(int sck, int bytes)
{
    int option_value;
    socklen_t option_len;

    option_value = bytes;
    option_len = sizeof(option_value);
    if (setsockopt(sck, SOL_SOCKET, SO_SNDBUF, (char *)&option_value,
                   option_len) != 0)
    {
        return 1;
    }
    return 0;
}

/*****************************************************************************/
/* returns error */
int
g_sck_get_send_buffer_bytes(int sck, int *bytes)
{
    int option_value;
    socklen_t option_len;

    option_value = 0;
    option_len = sizeof(option_value);
    if (getsockopt(sck, SOL_SOCKET, SO_SNDBUF, (char *)&option_value,
                   &option_len) != 0)
    {
        return 1;
    }
    *bytes = option_value;
    return 0;
}

/*****************************************************************************/
/* returns error */
int
g_sck_set_recv_buffer_bytes(int sck, int bytes)
{
    int option_value;
    socklen_t option_len;

    option_value = bytes;
    option_len = sizeof(option_value);
    if (setsockopt(sck, SOL_SOCKET, SO_RCVBUF, (char *)&option_value,
                   option_len) != 0)
    {
        return 1;
    }
    return 0;
}

/*****************************************************************************/
/* returns error */
int
g_sck_get_recv_buffer_bytes(int sck, int *bytes)
{
    int option_value;
    socklen_t option_len;

    option_value = 0;
    option_len = sizeof(option_value);
    if (getsockopt(sck, SOL_SOCKET, SO_RCVBUF, (char *)&option_value,
                   &option_len) != 0)
    {
        return 1;
    }
    *bytes = option_value;
    return 0;
}

/*****************************************************************************/
int
g_sck_local_socket(void)
{
#if defined(_WIN32)
    return -1;
#else
    return socket(PF_LOCAL, SOCK_STREAM, 0);
#endif
}

/*****************************************************************************/
int
g_sck_vsock_socket(void)
{
#if defined(XRDP_ENABLE_VSOCK)
    return socket(PF_VSOCK, SOCK_STREAM, 0);
#else
    return -1;
#endif
}

/*****************************************************************************/
/* returns error */
int
g_sck_get_peer_cred(int sck, int *pid, int *uid, int *gid)
{
#if defined(SO_PEERCRED)
    socklen_t ucred_length;
    struct myucred
    {
        pid_t pid;
        uid_t uid;
        gid_t gid;
    } credentials;

    ucred_length = sizeof(credentials);
    if (getsockopt(sck, SOL_SOCKET, SO_PEERCRED, &credentials, &ucred_length))
    {
        return 1;
    }
    if (pid != 0)
    {
        *pid = credentials.pid;
    }
    if (uid != 0)
    {
        *uid = credentials.uid;
    }
    if (gid != 0)
    {
        *gid = credentials.gid;
    }
    return 0;
#elif defined(LOCAL_PEERCRED)
    /* FreeBSD, OS X reach here*/
    struct xucred xucred;
    unsigned int xucred_length;
    xucred_length = sizeof(xucred);

    if (getsockopt(sck, SOL_SOCKET, LOCAL_PEERCRED, &xucred, &xucred_length))
    {
            return 1;
    }
    if (pid !=0)
    {
        *pid = 0; /* can't get pid in FreeBSD, OS X */
    }
    if (uid != 0)
    {
        *uid = xucred.cr_uid;
    }
    if (gid != 0) {
        *gid = xucred.cr_gid;
    }
    return 0;
#else
    return 1;
#endif
}

/*****************************************************************************/
void
g_sck_close(int sck)
{
#if defined(_WIN32)
    closesocket(sck);
#else
    char sockname[128];
    union
    {
        struct sockaddr sock_addr;
        struct sockaddr_in sock_addr_in;
#if defined(XRDP_ENABLE_IPV6)
        struct sockaddr_in6 sock_addr_in6;
#endif
#if defined(XRDP_ENABLE_VSOCK)
        struct sockaddr_vm sock_addr_vm;
#endif
    } sock_info;
    socklen_t sock_len = sizeof(sock_info);

    memset(&sock_info, 0, sizeof(sock_info));

    if (getsockname(sck, &sock_info.sock_addr, &sock_len) == 0)
    {
        switch (sock_info.sock_addr.sa_family)
        {
            case AF_INET:
            {
                struct sockaddr_in *sock_addr_in = &sock_info.sock_addr_in;

                g_snprintf(sockname, sizeof(sockname), "AF_INET %s:%d",
                           inet_ntoa(sock_addr_in->sin_addr),
                           ntohs(sock_addr_in->sin_port));
                break;
            }

#if defined(XRDP_ENABLE_IPV6)

            case AF_INET6:
            {
                char addr[48];
                struct sockaddr_in6 *sock_addr_in6 = &sock_info.sock_addr_in6;

                g_snprintf(sockname, sizeof(sockname), "AF_INET6 %s port %d",
                           inet_ntop(sock_addr_in6->sin6_family,
                                     &sock_addr_in6->sin6_addr, addr, sizeof(addr)),
                           ntohs(sock_addr_in6->sin6_port));
                break;
            }

#endif

            case AF_UNIX:
                g_snprintf(sockname, sizeof(sockname), "AF_UNIX");
                break;

#if defined(XRDP_ENABLE_VSOCK)

            case AF_VSOCK:
            {
                struct sockaddr_vm *sock_addr_vm = &sock_info.sock_addr_vm;

                g_snprintf(sockname,
                           sizeof(sockname),
                           "AF_VSOCK cid %d port %d",
                           sock_addr_vm->svm_cid,
                           sock_addr_vm->svm_port);
                break;
            }

#endif

            default:
                g_snprintf(sockname, sizeof(sockname), "unknown family %d",
                           sock_info.sock_addr.sa_family);
                break;
        }
    }
    else
    {
        log_message(LOG_LEVEL_WARNING, "getsockname() failed on socket %d: %s",
                    sck, g_get_strerror());

        if (errno == EBADF || errno == ENOTSOCK)
        {
            return;
        }

        g_snprintf(sockname, sizeof(sockname), "unknown");
    }

    if (close(sck) == 0)
    {
        log_message(LOG_LEVEL_DEBUG, "Closed socket %d (%s)", sck, sockname);
    }
    else
    {
        log_message(LOG_LEVEL_WARNING, "Cannot close socket %d (%s): %s", sck,
                    sockname, g_get_strerror());
    }

#endif
}

#if defined(XRDP_ENABLE_IPV6)
/*****************************************************************************/
/* Helper function for g_tcp_connect.                                        */
static int
connect_loopback(int sck, const char *port)
{
    struct sockaddr_in6 sa;
    struct sockaddr_in s;
    int res;

    // First IPv6
    g_memset(&sa, 0, sizeof(sa));
    sa.sin6_family = AF_INET6;
    sa.sin6_addr = in6addr_loopback;             // IPv6 ::1
    sa.sin6_port = htons((tui16)atoi(port));
    res = connect(sck, (struct sockaddr*)&sa, sizeof(sa));
    if (res == -1 && errno == EINPROGRESS)
    {
        return -1;
    }
    if (res == 0 || (res == -1 && errno == EISCONN))
    {
        return 0;
    }

    // else IPv4
    g_memset(&s, 0, sizeof(s));
    s.sin_family = AF_INET;
    s.sin_addr.s_addr = htonl(INADDR_LOOPBACK);  // IPv4 127.0.0.1
    s.sin_port = htons((tui16)atoi(port));
    res = connect(sck, (struct sockaddr*)&s, sizeof(s));
    if (res == -1 && errno == EINPROGRESS)
    {
        return -1;
    }
    if (res == 0 || (res == -1 && errno == EISCONN))
    {
        return 0;
    }

    // else IPv6 with IPv4 address
    g_memset(&sa, 0, sizeof(sa));
    sa.sin6_family = AF_INET6;
    inet_pton(AF_INET6, "::FFFF:127.0.0.1", &sa.sin6_addr);
    sa.sin6_port = htons((tui16)atoi(port));
    res = connect(sck, (struct sockaddr*)&sa, sizeof(sa));
    if (res == -1 && errno == EINPROGRESS)
    {
        return -1;
    }
    if (res == 0 || (res == -1 && errno == EISCONN))
    {
        return 0;
    }

    return -1;
}
#endif

/*****************************************************************************/
/* returns error, zero is good                                               */
/* The connection might get to be in progress, if so -1 is returned.         */
/* The caller needs to call again to check if succeed.                       */
#if defined(XRDP_ENABLE_IPV6)
int
g_tcp_connect(int sck, const char *address, const char *port)
{
    int res = 0;
    struct addrinfo p;
    struct addrinfo *h = (struct addrinfo *)NULL;
    struct addrinfo *rp = (struct addrinfo *)NULL;

    g_memset(&p, 0, sizeof(struct addrinfo));

    p.ai_socktype = SOCK_STREAM;
    p.ai_protocol = IPPROTO_TCP;
    p.ai_flags = AI_ADDRCONFIG | AI_V4MAPPED;
    p.ai_family = AF_INET6;
    if (g_strcmp(address, "127.0.0.1") == 0)
    {
        return connect_loopback(sck, port);
    }
    else
    {
        res = getaddrinfo(address, port, &p, &h);
    }
    if (res != 0)
    {
        log_message(LOG_LEVEL_ERROR, "g_tcp_connect(%d, %s, %s): getaddrinfo() failed: %s",
                    sck, address, port, gai_strerror(res));
    }
    if (res > -1)
    {
        if (h != NULL)
        {
            for (rp = h; rp != NULL; rp = rp->ai_next)
            {
                res = connect(sck, (struct sockaddr *)(rp->ai_addr),
                              rp->ai_addrlen);
                if (res == -1 && errno == EINPROGRESS)
                {
                    break; /* Return -1 */
                }
                if (res == 0 || (res == -1 && errno == EISCONN))
                {
                    res = 0;
                    break; /* Success */
                }
            }
            freeaddrinfo(h);
        }
    }

    return res;
}
#else
int
g_tcp_connect(int sck, const char* address, const char* port)
{
    struct sockaddr_in s;
    struct hostent* h;
    int res;

    g_memset(&s, 0, sizeof(struct sockaddr_in));
    s.sin_family = AF_INET;
    s.sin_port = htons((tui16)atoi(port));
    s.sin_addr.s_addr = inet_addr(address);
    if (s.sin_addr.s_addr == INADDR_NONE)
    {
        h = gethostbyname(address);
        if (h != 0)
        {
            if (h->h_name != 0)
            {
                if (h->h_addr_list != 0)
                {
                    if ((*(h->h_addr_list)) != 0)
                    {
                        s.sin_addr.s_addr = *((int*)(*(h->h_addr_list)));
                    }
                }
            }
        }
    }
    res = connect(sck, (struct sockaddr*)&s, sizeof(struct sockaddr_in));

    /* Mac OSX connect() returns -1 for already established connections */
    if (res == -1 && errno == EISCONN)
    {
        res = 0;
    }

    return res;
}
#endif

/*****************************************************************************/
/* returns error, zero is good */
int
g_sck_local_connect(int sck, const char *port)
{
#if defined(_WIN32)
    return -1;
#else
    struct sockaddr_un s;

    memset(&s, 0, sizeof(struct sockaddr_un));
    s.sun_family = AF_UNIX;
    strncpy(s.sun_path, port, sizeof(s.sun_path));
    s.sun_path[sizeof(s.sun_path) - 1] = 0;

    return connect(sck, (struct sockaddr *)&s, sizeof(struct sockaddr_un));
#endif
}

/*****************************************************************************/
int
g_sck_set_non_blocking(int sck)
{
    unsigned long i;

#if defined(_WIN32)
    i = 1;
    ioctlsocket(sck, FIONBIO, &i);
#else
    i = fcntl(sck, F_GETFL);
    i = i | O_NONBLOCK;
    if (fcntl(sck, F_SETFL, i) < 0)
    {
        log_message(LOG_LEVEL_ERROR, "g_sck_set_non_blocking: fcntl() failed");
    }
#endif
    return 0;
}

#if defined(XRDP_ENABLE_IPV6)
/*****************************************************************************/
/* returns error, zero is good */
int
g_tcp_bind(int sck, const char *port)
{
    struct sockaddr_in6 sa;
    struct sockaddr_in s;
    int errno6;

    // First IPv6
    g_memset(&sa, 0, sizeof(sa));
    sa.sin6_family = AF_INET6;
    sa.sin6_addr = in6addr_any;                 // IPv6 ::
    sa.sin6_port = htons((tui16)atoi(port));
    if (bind(sck, (struct sockaddr*)&sa, sizeof(sa)) == 0)
    {
        return 0;
    }
    errno6 = errno;

    // else IPv4
    g_memset(&s, 0, sizeof(s));
    s.sin_family = AF_INET;
    s.sin_addr.s_addr = htonl(INADDR_ANY);     // IPv4 0.0.0.0
    s.sin_port = htons((tui16)atoi(port));
    if (bind(sck, (struct sockaddr*)&s, sizeof(s)) == 0)
    {
        return 0;
    }

    log_message(LOG_LEVEL_ERROR, "g_tcp_bind(%d, %s) failed "
                "bind IPv6 (errno=%d) and IPv4 (errno=%d).",
                sck, port, errno6, errno);
    return -1;
}
#else
int
g_tcp_bind(int sck, const char* port)
{
    struct sockaddr_in s;

    memset(&s, 0, sizeof(struct sockaddr_in));
    s.sin_family = AF_INET;
    s.sin_port = htons((tui16)atoi(port));
    s.sin_addr.s_addr = INADDR_ANY;
    return bind(sck, (struct sockaddr*)&s, sizeof(struct sockaddr_in));
}
#endif

/*****************************************************************************/
int
g_sck_local_bind(int sck, const char *port)
{
#if defined(_WIN32)
    return -1;
#else
    struct sockaddr_un s;

    memset(&s, 0, sizeof(struct sockaddr_un));
    s.sun_family = AF_UNIX;
    strncpy(s.sun_path, port, sizeof(s.sun_path));
    s.sun_path[sizeof(s.sun_path) - 1] = 0;

    return bind(sck, (struct sockaddr *)&s, sizeof(struct sockaddr_un));
#endif
}

/*****************************************************************************/
int
g_sck_vsock_bind(int sck, const char *port)
{
#if defined(XRDP_ENABLE_VSOCK)
    struct sockaddr_vm s;

    g_memset(&s, 0, sizeof(struct sockaddr_vm));
    s.svm_family = AF_VSOCK;
    s.svm_port = atoi(port);
    s.svm_cid = VMADDR_CID_ANY;

    return bind(sck, (struct sockaddr *)&s, sizeof(struct sockaddr_vm));
#else
    return -1;
#endif
}

#if defined(XRDP_ENABLE_IPV6)
/*****************************************************************************/
/* Helper function for g_tcp_bind_address.                                   */
static int
bind_loopback(int sck, const char *port)
{
    struct sockaddr_in6 sa;
    struct sockaddr_in s;
    int errno6;
    int errno4;

    // First IPv6
    g_memset(&sa, 0, sizeof(sa));
    sa.sin6_family = AF_INET6;
    sa.sin6_addr = in6addr_loopback;             // IPv6 ::1
    sa.sin6_port = htons((tui16)atoi(port));
    if (bind(sck, (struct sockaddr*)&sa, sizeof(sa)) == 0)
    {
        return 0;
    }
    errno6 = errno;

    // else IPv4
    g_memset(&s, 0, sizeof(s));
    s.sin_family = AF_INET;
    s.sin_addr.s_addr = htonl(INADDR_LOOPBACK);  // IPv4 127.0.0.1
    s.sin_port = htons((tui16)atoi(port));
    if (bind(sck, (struct sockaddr*)&s, sizeof(s)) == 0)
    {
        return 0;
    }
    errno4 = errno;

    // else IPv6 with IPv4 address
    g_memset(&sa, 0, sizeof(sa));
    sa.sin6_family = AF_INET6;
    inet_pton(AF_INET6, "::FFFF:127.0.0.1", &sa.sin6_addr);
    sa.sin6_port = htons((tui16)atoi(port));
    if (bind(sck, (struct sockaddr*)&sa, sizeof(sa)) == 0)
    {
        return 0;
    }

    log_message(LOG_LEVEL_ERROR, "bind_loopback(%d, %s) failed; "
                "IPv6 ::1 (errno=%d), IPv4 127.0.0.1 (errno=%d) and IPv6 fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b:127.0.0.1 (errno=%d).",
                sck, port, errno6, errno4, errno);
    return -1;
}

/*****************************************************************************/
/* Helper function for g_tcp_bind_address.                                   */
/* Returns error, zero is good.                                              */
static int
getaddrinfo_bind(int sck, const char *port, const char *address)
{
    int res;
    int error;
    struct addrinfo hints;
    struct addrinfo *list;
    struct addrinfo *i;

    res = -1;
    g_memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_flags = 0;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    error = getaddrinfo(address, port, &hints, &list);
    if (error == 0)
    {
        i = list;
        while ((i != 0) && (res < 0))
        {
            res = bind(sck, i->ai_addr, i->ai_addrlen);
            i = i->ai_next;
        }
        freeaddrinfo(list);
    }
    else
    {
        log_message(LOG_LEVEL_ERROR, "getaddrinfo error: %s", gai_strerror(error));
        return -1;
    }
    return res;
}

/*****************************************************************************/
/* Binds a socket to a port. If no specified address the port will be bind   */
/* to 'any', i.e. available on all network.                                  */
/* For bind to local host, see valid address strings below.                  */
/* Returns error, zero is good.                                              */
int
g_tcp_bind_address(int sck, const char *port, const char *address)
{
    int res;

    if ((address == 0) ||
        (address[0] == 0) ||
        (g_strcmp(address, "0.0.0.0") == 0) ||
        (g_strcmp(address, "::") == 0))
    {
        return g_tcp_bind(sck, port);
    }

    if ((g_strcmp(address, "127.0.0.1") == 0) ||
        (g_strcmp(address, "::1") == 0) ||
        (g_strcmp(address, "localhost") == 0))
    {
        return bind_loopback(sck, port);
    }

    // Let getaddrinfo translate the address string...
    // IPv4: ddd.ddd.ddd.ddd
    // IPv6: x:x:x:x:x:x:x:x%<interface>, or x::x:x:x:x%<interface>
    res = getaddrinfo_bind(sck, port, address);
    if (res != 0)
    {
        // If fail and it is an IPv4 address, try with the mapped address
        struct in_addr a;
        if ((inet_aton(address, &a) == 1) && (strlen(address) <= 15))
        {
            char sz[7+15+1];
            sprintf(sz, "::FFFF:%s", address);
            res = getaddrinfo_bind(sck, port, sz);
            if (res == 0)
            {
                return 0;
            }
        }

        log_message(LOG_LEVEL_ERROR, "g_tcp_bind_address(%d, %s, %s) Failed!",
                    sck, port, address);
        return -1;
    }
    return 0;
}
#else
int
g_tcp_bind_address(int sck, const char* port, const char* address)
{
    struct sockaddr_in s;

    memset(&s, 0, sizeof(struct sockaddr_in));
    s.sin_family = AF_INET;
    s.sin_port = htons((tui16)atoi(port));
    s.sin_addr.s_addr = INADDR_ANY;
    if (inet_aton(address, &s.sin_addr) < 0)
    {
        return -1; /* bad address */
    }
    return bind(sck, (struct sockaddr*)&s, sizeof(struct sockaddr_in));
}
#endif

/*****************************************************************************/
/* returns error, zero is good */
int
g_sck_listen(int sck)
{
    return listen(sck, 2);
}

/*****************************************************************************/
int
g_tcp_accept(int sck)
{
    int ret;
    char msg[256];
    union
    {
        struct sockaddr sock_addr;
        struct sockaddr_in sock_addr_in;
#if defined(XRDP_ENABLE_IPV6)
        struct sockaddr_in6 sock_addr_in6;
#endif
    } sock_info;

    socklen_t sock_len = sizeof(sock_info);
    memset(&sock_info, 0, sock_len);

    ret = accept(sck, (struct sockaddr *)&sock_info, &sock_len);

    if (ret > 0)
    {
        switch(sock_info.sock_addr.sa_family)
        {
            case AF_INET:
            {
                struct sockaddr_in *sock_addr_in = &sock_info.sock_addr_in;

                g_snprintf(msg, sizeof(msg), "A connection received from %s port %d",
                           inet_ntoa(sock_addr_in->sin_addr),
                           ntohs(sock_addr_in->sin_port));
                log_message(LOG_LEVEL_INFO, "%s", msg);

                break;
            }

#if defined(XRDP_ENABLE_IPV6)

            case AF_INET6:
            {
                struct sockaddr_in6 *sock_addr_in6 = &sock_info.sock_addr_in6;
                char addr[256];

                inet_ntop(sock_addr_in6->sin6_family,
                          &sock_addr_in6->sin6_addr, addr, sizeof(addr));
                g_snprintf(msg, sizeof(msg), "A connection received from %s port %d",
                           addr, ntohs(sock_addr_in6->sin6_port));
                log_message(LOG_LEVEL_INFO, "%s", msg);

                break;

            }

#endif
        }
    }

    return ret;
}

/*****************************************************************************/
int
g_sck_accept(int sck, char *addr, int addr_bytes, char *port, int port_bytes)
{
    int ret;
    char msg[256];
    union
    {
        struct sockaddr sock_addr;
        struct sockaddr_in sock_addr_in;
#if defined(XRDP_ENABLE_IPV6)
        struct sockaddr_in6 sock_addr_in6;
#endif
        struct sockaddr_un sock_addr_un;
#if defined(XRDP_ENABLE_VSOCK)
        struct sockaddr_vm sock_addr_vm;
#endif
    } sock_info;

    socklen_t sock_len = sizeof(sock_info);
    memset(&sock_info, 0, sock_len);

    ret = accept(sck, (struct sockaddr *)&sock_info, &sock_len);

    if (ret > 0)
    {
        switch(sock_info.sock_addr.sa_family)
        {
            case AF_INET:
            {
                struct sockaddr_in *sock_addr_in = &sock_info.sock_addr_in;

                g_snprintf(addr, addr_bytes, "%s", inet_ntoa(sock_addr_in->sin_addr));
                g_snprintf(port, port_bytes, "%d", ntohs(sock_addr_in->sin_port));
                g_snprintf(msg, sizeof(msg),
                           "AF_INET connection received from %s port %s",
                           addr, port);
                break;
            }

#if defined(XRDP_ENABLE_IPV6)

            case AF_INET6:
            {
                struct sockaddr_in6 *sock_addr_in6 = &sock_info.sock_addr_in6;

                inet_ntop(sock_addr_in6->sin6_family,
                          &sock_addr_in6->sin6_addr, addr, addr_bytes);
                g_snprintf(port, port_bytes, "%d", ntohs(sock_addr_in6->sin6_port));
                g_snprintf(msg, sizeof(msg),
                           "AF_INET6 connection received from %s port %s",
                           addr, port);
                break;
            }

#endif

            case AF_UNIX:
            {
                g_strncpy(addr, "", addr_bytes - 1);
                g_strncpy(port, "", port_bytes - 1);
                g_snprintf(msg, sizeof(msg), "AF_UNIX connection received");
                break;
            }

#if defined(XRDP_ENABLE_VSOCK)

            case AF_VSOCK:
            {
                struct sockaddr_vm *sock_addr_vm = &sock_info.sock_addr_vm;

                g_snprintf(addr, addr_bytes - 1, "%d", sock_addr_vm->svm_cid);
                g_snprintf(port, addr_bytes - 1, "%d", sock_addr_vm->svm_port);

                g_snprintf(msg,
                           sizeof(msg),
                           "AF_VSOCK connection received from cid: %s port: %s",
                           addr,
                           port);

                break;
            }

#endif
            default:
            {
                g_strncpy(addr, "", addr_bytes - 1);
                g_strncpy(port, "", port_bytes - 1);
                g_snprintf(msg, sizeof(msg),
                           "connection received, unknown socket family %d",
                           sock_info.sock_addr.sa_family);
                break;
            }
        }


        log_message(LOG_LEVEL_INFO, "Socket %d: %s", ret, msg);

    }

    return ret;
}

/*****************************************************************************/
/*
 * TODO: this function writes not only IP address, name is confusing
{'fraction_non_alphanumeric': 0.20396751239847624, 'fraction_numerical': 0.014835046359519873, 'mean_word_length': 2.243472584856397, 'pattern_counts': {'":': 10, '<': 103, '<?xml version=': 0, '>': 137, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 20, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 22, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2529348', 'n_tokens_mistral': 24001, 'n_tokens_neox': 22578, 'n_words': 5143}