bool InitializeProxyOptions()

in src/utils/url_utils/src/https_proxy_utils.c [94:221]


bool InitializeProxyOptions(HTTP_PROXY_OPTIONS* proxyOptions)
{
    bool success = false;
    char* proxy_copy = NULL;
    char* start = NULL;
    char* end = NULL;

    if (proxyOptions == NULL)
    {
        Log_Error("proxyOptions is NULL.");
        goto done;
    }

    proxyOptions->host_address = NULL;
    proxyOptions->username = NULL;
    proxyOptions->password = NULL;
    proxyOptions->port = 0;

    char* httpsProxyEnvVar = getenv("https_proxy");
    if (httpsProxyEnvVar == NULL)
    {
        httpsProxyEnvVar = getenv("HTTPS_PROXY");
    }
    if (httpsProxyEnvVar == NULL)
    {
        goto done;
    }

    // Create read-write copy of environment variable.
    proxy_copy = strdupe(httpsProxyEnvVar);
    if (proxy_copy == NULL)
    {
        goto done;
    }

    start = proxy_copy;

    end = strstr(start, "://");
    if (end == NULL)
    {
        // Can't find "://"
        goto done;
    }

    end += 3; // past ""://""

    start = end;

    end = strchr(start, '@');
    if (end != NULL)
    {
        // Left of '@' is username[:password]
        *end = '\0';
        char* after_at = end + 1; // after '@'

        end = strchr(start, ':');
        if (end != NULL)
        {
            *end = '\0';

            // Check for no username
            if (*start != '\0')
            {
                if (!unescape_data_string(start))
                {
                    goto done;
                }

                proxyOptions->username = strdupe(start);
                if (proxyOptions->username == NULL)
                {
                    goto done;
                }
            }

            start = end + 1;

            // Check for no password
            if (*start != '\0')
            {
                if (!unescape_data_string(start))
                {
                    goto done;
                }

                proxyOptions->password = strdupe(start);
                if (proxyOptions->password == NULL)
                {
                    goto done;
                }
            }
        }

        start = after_at;
    }

    end = strchr(start, ':');
    if (end != NULL)
    {
        *end = '\0';

        proxyOptions->port = atoi(end + 1);
    }

    if (!unescape_data_string(start))
    {
        goto done;
    }

    proxyOptions->host_address = strdupe(start);
    if (proxyOptions->host_address == NULL)
    {
        goto done;
    }

    success = true;

done:

    free(proxy_copy);

    if (!success)
    {
        UninitializeProxyOptions(proxyOptions);
    }

    return success;
}