101 lines
2.2 KiB
C
101 lines
2.2 KiB
C
#include "error.h"
|
|
#include "intl.h"
|
|
#include "util.h"
|
|
#include <curl/curl.h>
|
|
#include <dirent.h>
|
|
#include <stdbool.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <unistd.h>
|
|
|
|
#define HUB_URL "https://matterlinux.xyz/hub"
|
|
|
|
bool url_is_name(char *name) {
|
|
for (char *c = name; *c != '\0'; c++) {
|
|
if (*c == '/' || *c == '.')
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
bool url_is_local(char *url) {
|
|
bool ret = false;
|
|
if (startswith(url, "http://") || startswith(url, "https://"))
|
|
return ret;
|
|
|
|
DIR *dir = NULL;
|
|
if (access(url, F_OK) == 0 && (dir = opendir(url)) != NULL)
|
|
ret = true;
|
|
|
|
closedir(dir);
|
|
return ret;
|
|
}
|
|
|
|
char *url_complete(char *name) {
|
|
char url[strlen(name) + strlen(HUB_URL) + 1];
|
|
sprintf(url, "%s/%s", HUB_URL, name);
|
|
|
|
char *location = NULL;
|
|
long code = 0;
|
|
|
|
CURL *curl = curl_easy_init();
|
|
if (NULL == curl) {
|
|
error_set(_("Failed to init curl"));
|
|
errno = UrlCurlFail;
|
|
return NULL;
|
|
}
|
|
|
|
curl_easy_setopt(curl, CURLOPT_URL, url);
|
|
curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl/mp");
|
|
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 0L);
|
|
CURLcode res = curl_easy_perform(curl);
|
|
|
|
if (res != CURLE_OK) {
|
|
error_set(_("Request failed"));
|
|
errno = UrlReqFail;
|
|
goto CLEANUP;
|
|
}
|
|
|
|
res = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);
|
|
if (res != CURLE_OK) {
|
|
error_set(_("Failed to get the response code"));
|
|
errno = UrlReqCodeFail;
|
|
goto CLEANUP;
|
|
}
|
|
|
|
if ((code / 100) != 3) {
|
|
error_set(_("Response is not a redirect"));
|
|
errno = UrlReqBadCode;
|
|
goto CLEANUP;
|
|
}
|
|
|
|
res = curl_easy_getinfo(curl, CURLINFO_REDIRECT_URL, &location);
|
|
if (res != CURLE_OK) {
|
|
error_set(_("Failed to get the location header"));
|
|
errno = UrlLocationFail;
|
|
goto CLEANUP;
|
|
}
|
|
|
|
if (NULL == location) {
|
|
error_set(_("Invalid location header"));
|
|
errno = UrlLocationBad;
|
|
goto CLEANUP;
|
|
}
|
|
|
|
location = strdup(location);
|
|
|
|
CLEANUP:
|
|
curl_easy_cleanup(curl);
|
|
return location;
|
|
}
|
|
|
|
char *url_ensure_protocol(char *url) {
|
|
if (startswith(url, "http://") || startswith(url, "https://"))
|
|
return strdup(url);
|
|
|
|
char *full = malloc(strlen("https://") + strlen(url) + 1);
|
|
join(full, "https://", url);
|
|
return full;
|
|
}
|