1
0

download.cpp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  1. #include "arg.h"
  2. #include "common.h"
  3. #include "gguf.h" // for reading GGUF splits
  4. #include "log.h"
  5. #include "download.h"
  6. #define JSON_ASSERT GGML_ASSERT
  7. #include <nlohmann/json.hpp>
  8. #include <algorithm>
  9. #include <filesystem>
  10. #include <fstream>
  11. #include <future>
  12. #include <regex>
  13. #include <string>
  14. #include <thread>
  15. #include <vector>
  16. #if defined(LLAMA_USE_CURL)
  17. #include <curl/curl.h>
  18. #include <curl/easy.h>
  19. #elif defined(LLAMA_USE_HTTPLIB)
  20. #include "http.h"
  21. #endif
  22. #ifdef __linux__
  23. #include <linux/limits.h>
  24. #elif defined(_WIN32)
  25. # if !defined(PATH_MAX)
  26. # define PATH_MAX MAX_PATH
  27. # endif
  28. #elif defined(_AIX)
  29. #include <sys/limits.h>
  30. #else
  31. #include <sys/syslimits.h>
  32. #endif
  33. #define LLAMA_MAX_URL_LENGTH 2084 // Maximum URL Length in Chrome: 2083
  34. // isatty
  35. #if defined(_WIN32)
  36. #include <io.h>
  37. #else
  38. #include <unistd.h>
  39. #endif
  40. using json = nlohmann::ordered_json;
  41. //
  42. // downloader
  43. //
  44. // validate repo name format: owner/repo
  45. static bool validate_repo_name(const std::string & repo) {
  46. static const std::regex repo_regex(R"(^[A-Za-z0-9_.\-]+\/[A-Za-z0-9_.\-]+$)");
  47. return std::regex_match(repo, repo_regex);
  48. }
  49. static std::string get_manifest_path(const std::string & repo, const std::string & tag) {
  50. // we use "=" to avoid clashing with other component, while still being allowed on windows
  51. std::string fname = "manifest=" + repo + "=" + tag + ".json";
  52. if (!validate_repo_name(repo)) {
  53. throw std::runtime_error("error: repo name must be in the format 'owner/repo'");
  54. }
  55. string_replace_all(fname, "/", "=");
  56. return fs_get_cache_file(fname);
  57. }
  58. static std::string read_file(const std::string & fname) {
  59. std::ifstream file(fname);
  60. if (!file) {
  61. throw std::runtime_error(string_format("error: failed to open file '%s'\n", fname.c_str()));
  62. }
  63. std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
  64. file.close();
  65. return content;
  66. }
  67. static void write_file(const std::string & fname, const std::string & content) {
  68. const std::string fname_tmp = fname + ".tmp";
  69. std::ofstream file(fname_tmp);
  70. if (!file) {
  71. throw std::runtime_error(string_format("error: failed to open file '%s'\n", fname.c_str()));
  72. }
  73. try {
  74. file << content;
  75. file.close();
  76. // Makes write atomic
  77. if (rename(fname_tmp.c_str(), fname.c_str()) != 0) {
  78. LOG_ERR("%s: unable to rename file: %s to %s\n", __func__, fname_tmp.c_str(), fname.c_str());
  79. // If rename fails, try to delete the temporary file
  80. if (remove(fname_tmp.c_str()) != 0) {
  81. LOG_ERR("%s: unable to delete temporary file: %s\n", __func__, fname_tmp.c_str());
  82. }
  83. }
  84. } catch (...) {
  85. // If anything fails, try to delete the temporary file
  86. if (remove(fname_tmp.c_str()) != 0) {
  87. LOG_ERR("%s: unable to delete temporary file: %s\n", __func__, fname_tmp.c_str());
  88. }
  89. throw std::runtime_error(string_format("error: failed to write file '%s'\n", fname.c_str()));
  90. }
  91. }
  92. static void write_etag(const std::string & path, const std::string & etag) {
  93. const std::string etag_path = path + ".etag";
  94. write_file(etag_path, etag);
  95. LOG_DBG("%s: file etag saved: %s\n", __func__, etag_path.c_str());
  96. }
  97. static std::string read_etag(const std::string & path) {
  98. std::string none;
  99. const std::string etag_path = path + ".etag";
  100. if (std::filesystem::exists(etag_path)) {
  101. std::ifstream etag_in(etag_path);
  102. if (!etag_in) {
  103. LOG_ERR("%s: could not open .etag file for reading: %s\n", __func__, etag_path.c_str());
  104. return none;
  105. }
  106. std::string etag;
  107. std::getline(etag_in, etag);
  108. return etag;
  109. }
  110. // no etag file, but maybe there is an old .json
  111. // remove this code later
  112. const std::string metadata_path = path + ".json";
  113. if (std::filesystem::exists(metadata_path)) {
  114. std::ifstream metadata_in(metadata_path);
  115. try {
  116. nlohmann::json metadata_json;
  117. metadata_in >> metadata_json;
  118. LOG_DBG("%s: previous metadata file found %s: %s\n", __func__, metadata_path.c_str(),
  119. metadata_json.dump().c_str());
  120. if (metadata_json.contains("etag") && metadata_json.at("etag").is_string()) {
  121. std::string etag = metadata_json.at("etag");
  122. write_etag(path, etag);
  123. if (!std::filesystem::remove(metadata_path)) {
  124. LOG_WRN("%s: failed to delete old .json metadata file: %s\n", __func__, metadata_path.c_str());
  125. }
  126. return etag;
  127. }
  128. } catch (const nlohmann::json::exception & e) {
  129. LOG_ERR("%s: error reading metadata file %s: %s\n", __func__, metadata_path.c_str(), e.what());
  130. }
  131. }
  132. return none;
  133. }
  134. #ifdef LLAMA_USE_CURL
  135. //
  136. // CURL utils
  137. //
  138. using curl_ptr = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>;
  139. // cannot use unique_ptr for curl_slist, because we cannot update without destroying the old one
  140. struct curl_slist_ptr {
  141. struct curl_slist * ptr = nullptr;
  142. ~curl_slist_ptr() {
  143. if (ptr) {
  144. curl_slist_free_all(ptr);
  145. }
  146. }
  147. };
  148. static CURLcode common_curl_perf(CURL * curl) {
  149. CURLcode res = curl_easy_perform(curl);
  150. if (res != CURLE_OK) {
  151. LOG_ERR("%s: curl_easy_perform() failed\n", __func__);
  152. }
  153. return res;
  154. }
  155. // Send a HEAD request to retrieve the etag and last-modified headers
  156. struct common_load_model_from_url_headers {
  157. std::string etag;
  158. std::string last_modified;
  159. std::string accept_ranges;
  160. };
  161. struct FILE_deleter {
  162. void operator()(FILE * f) const { fclose(f); }
  163. };
  164. static size_t common_header_callback(char * buffer, size_t, size_t n_items, void * userdata) {
  165. common_load_model_from_url_headers * headers = (common_load_model_from_url_headers *) userdata;
  166. static std::regex header_regex("([^:]+): (.*)\r\n");
  167. static std::regex etag_regex("ETag", std::regex_constants::icase);
  168. static std::regex last_modified_regex("Last-Modified", std::regex_constants::icase);
  169. static std::regex accept_ranges_regex("Accept-Ranges", std::regex_constants::icase);
  170. std::string header(buffer, n_items);
  171. std::smatch match;
  172. if (std::regex_match(header, match, header_regex)) {
  173. const std::string & key = match[1];
  174. const std::string & value = match[2];
  175. if (std::regex_match(key, match, etag_regex)) {
  176. headers->etag = value;
  177. } else if (std::regex_match(key, match, last_modified_regex)) {
  178. headers->last_modified = value;
  179. } else if (std::regex_match(key, match, accept_ranges_regex)) {
  180. headers->accept_ranges = value;
  181. }
  182. }
  183. return n_items;
  184. }
  185. static size_t common_write_callback(void * data, size_t size, size_t nmemb, void * fd) {
  186. return std::fwrite(data, size, nmemb, static_cast<FILE *>(fd));
  187. }
  188. // helper function to hide password in URL
  189. static std::string llama_download_hide_password_in_url(const std::string & url) {
  190. // Use regex to match and replace the user[:password]@ pattern in URLs
  191. // Pattern: scheme://[user[:password]@]host[...]
  192. static const std::regex url_regex(R"(^(?:[A-Za-z][A-Za-z0-9+.-]://)(?:[^/@]+@)?.$)");
  193. std::smatch match;
  194. if (std::regex_match(url, match, url_regex)) {
  195. // match[1] = scheme (e.g., "https://")
  196. // match[2] = user[:password]@ part
  197. // match[3] = rest of URL (host and path)
  198. return match[1].str() + "********@" + match[3].str();
  199. }
  200. return url; // No credentials found or malformed URL
  201. }
  202. static void common_curl_easy_setopt_head(CURL * curl, const std::string & url) {
  203. // Set the URL, allow to follow http redirection
  204. curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  205. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  206. # if defined(_WIN32)
  207. // CURLSSLOPT_NATIVE_CA tells libcurl to use standard certificate store of
  208. // operating system. Currently implemented under MS-Windows.
  209. curl_easy_setopt(curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA);
  210. # endif
  211. curl_easy_setopt(curl, CURLOPT_NOBODY, 1L); // will trigger the HEAD verb
  212. curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L); // hide head request progress
  213. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, common_header_callback);
  214. }
  215. static void common_curl_easy_setopt_get(CURL * curl) {
  216. curl_easy_setopt(curl, CURLOPT_NOBODY, 0L);
  217. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, common_write_callback);
  218. // display download progress
  219. curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
  220. }
  221. static bool common_pull_file(CURL * curl, const std::string & path_temporary) {
  222. if (std::filesystem::exists(path_temporary)) {
  223. const std::string partial_size = std::to_string(std::filesystem::file_size(path_temporary));
  224. LOG_INF("%s: server supports range requests, resuming download from byte %s\n", __func__, partial_size.c_str());
  225. const std::string range_str = partial_size + "-";
  226. curl_easy_setopt(curl, CURLOPT_RANGE, range_str.c_str());
  227. }
  228. // Always open file in append mode could be resuming
  229. std::unique_ptr<FILE, FILE_deleter> outfile(fopen(path_temporary.c_str(), "ab"));
  230. if (!outfile) {
  231. LOG_ERR("%s: error opening local file for writing: %s\n", __func__, path_temporary.c_str());
  232. return false;
  233. }
  234. common_curl_easy_setopt_get(curl);
  235. curl_easy_setopt(curl, CURLOPT_WRITEDATA, outfile.get());
  236. return common_curl_perf(curl) == CURLE_OK;
  237. }
  238. static bool common_download_head(CURL * curl,
  239. curl_slist_ptr & http_headers,
  240. const std::string & url,
  241. const std::string & bearer_token) {
  242. if (!curl) {
  243. LOG_ERR("%s: error initializing libcurl\n", __func__);
  244. return false;
  245. }
  246. http_headers.ptr = curl_slist_append(http_headers.ptr, "User-Agent: llama-cpp");
  247. // Check if hf-token or bearer-token was specified
  248. if (!bearer_token.empty()) {
  249. std::string auth_header = "Authorization: Bearer " + bearer_token;
  250. http_headers.ptr = curl_slist_append(http_headers.ptr, auth_header.c_str());
  251. }
  252. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, http_headers.ptr);
  253. common_curl_easy_setopt_head(curl, url);
  254. return common_curl_perf(curl) == CURLE_OK;
  255. }
  256. // download one single file from remote URL to local path
  257. static bool common_download_file_single_online(const std::string & url,
  258. const std::string & path,
  259. const std::string & bearer_token) {
  260. static const int max_attempts = 3;
  261. static const int retry_delay_seconds = 2;
  262. for (int i = 0; i < max_attempts; ++i) {
  263. std::string etag;
  264. // Check if the file already exists locally
  265. const auto file_exists = std::filesystem::exists(path);
  266. if (file_exists) {
  267. etag = read_etag(path);
  268. } else {
  269. LOG_INF("%s: no previous model file found %s\n", __func__, path.c_str());
  270. }
  271. bool head_request_ok = false;
  272. bool should_download = !file_exists; // by default, we should download if the file does not exist
  273. // Initialize libcurl
  274. curl_ptr curl(curl_easy_init(), &curl_easy_cleanup);
  275. common_load_model_from_url_headers headers;
  276. curl_easy_setopt(curl.get(), CURLOPT_HEADERDATA, &headers);
  277. curl_slist_ptr http_headers;
  278. const bool was_perform_successful = common_download_head(curl.get(), http_headers, url, bearer_token);
  279. if (!was_perform_successful) {
  280. head_request_ok = false;
  281. }
  282. long http_code = 0;
  283. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &http_code);
  284. if (http_code == 200) {
  285. head_request_ok = true;
  286. } else {
  287. LOG_WRN("%s: HEAD invalid http status code received: %ld\n", __func__, http_code);
  288. head_request_ok = false;
  289. }
  290. // if head_request_ok is false, we don't have the etag or last-modified headers
  291. // we leave should_download as-is, which is true if the file does not exist
  292. bool should_download_from_scratch = false;
  293. if (head_request_ok) {
  294. // check if ETag or Last-Modified headers are different
  295. // if it is, we need to download the file again
  296. if (!etag.empty() && etag != headers.etag) {
  297. LOG_WRN("%s: ETag header is different (%s != %s): triggering a new download\n", __func__, etag.c_str(),
  298. headers.etag.c_str());
  299. should_download = true;
  300. should_download_from_scratch = true;
  301. }
  302. }
  303. const bool accept_ranges_supported = !headers.accept_ranges.empty() && headers.accept_ranges != "none";
  304. if (should_download) {
  305. if (file_exists &&
  306. !accept_ranges_supported) { // Resumable downloads not supported, delete and start again.
  307. LOG_WRN("%s: deleting previous downloaded file: %s\n", __func__, path.c_str());
  308. if (remove(path.c_str()) != 0) {
  309. LOG_ERR("%s: unable to delete file: %s\n", __func__, path.c_str());
  310. return false;
  311. }
  312. }
  313. const std::string path_temporary = path + ".downloadInProgress";
  314. if (should_download_from_scratch) {
  315. if (std::filesystem::exists(path_temporary)) {
  316. if (remove(path_temporary.c_str()) != 0) {
  317. LOG_ERR("%s: unable to delete file: %s\n", __func__, path_temporary.c_str());
  318. return false;
  319. }
  320. }
  321. if (std::filesystem::exists(path)) {
  322. if (remove(path.c_str()) != 0) {
  323. LOG_ERR("%s: unable to delete file: %s\n", __func__, path.c_str());
  324. return false;
  325. }
  326. }
  327. }
  328. if (head_request_ok) {
  329. write_etag(path, headers.etag);
  330. }
  331. // start the download
  332. LOG_INF("%s: trying to download model from %s to %s (server_etag:%s, server_last_modified:%s)...\n",
  333. __func__, llama_download_hide_password_in_url(url).c_str(), path_temporary.c_str(),
  334. headers.etag.c_str(), headers.last_modified.c_str());
  335. const bool was_pull_successful = common_pull_file(curl.get(), path_temporary);
  336. if (!was_pull_successful) {
  337. if (i + 1 < max_attempts) {
  338. const int exponential_backoff_delay = std::pow(retry_delay_seconds, i) * 1000;
  339. LOG_WRN("%s: retrying after %d milliseconds...\n", __func__, exponential_backoff_delay);
  340. std::this_thread::sleep_for(std::chrono::milliseconds(exponential_backoff_delay));
  341. } else {
  342. LOG_ERR("%s: curl_easy_perform() failed after %d attempts\n", __func__, max_attempts);
  343. }
  344. continue;
  345. }
  346. long http_code = 0;
  347. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &http_code);
  348. if (http_code < 200 || http_code >= 400) {
  349. LOG_ERR("%s: invalid http status code received: %ld\n", __func__, http_code);
  350. return false;
  351. }
  352. if (rename(path_temporary.c_str(), path.c_str()) != 0) {
  353. LOG_ERR("%s: unable to rename file: %s to %s\n", __func__, path_temporary.c_str(), path.c_str());
  354. return false;
  355. }
  356. } else {
  357. LOG_INF("%s: using cached file: %s\n", __func__, path.c_str());
  358. }
  359. break;
  360. }
  361. return true;
  362. }
  363. std::pair<long, std::vector<char>> common_remote_get_content(const std::string & url, const common_remote_params & params) {
  364. curl_ptr curl(curl_easy_init(), &curl_easy_cleanup);
  365. curl_slist_ptr http_headers;
  366. std::vector<char> res_buffer;
  367. curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());
  368. curl_easy_setopt(curl.get(), CURLOPT_NOPROGRESS, 1L);
  369. curl_easy_setopt(curl.get(), CURLOPT_FOLLOWLOCATION, 1L);
  370. curl_easy_setopt(curl.get(), CURLOPT_VERBOSE, 1L);
  371. typedef size_t(*CURLOPT_WRITEFUNCTION_PTR)(void * ptr, size_t size, size_t nmemb, void * data);
  372. auto write_callback = [](void * ptr, size_t size, size_t nmemb, void * data) -> size_t {
  373. auto data_vec = static_cast<std::vector<char> *>(data);
  374. data_vec->insert(data_vec->end(), (char *)ptr, (char *)ptr + size * nmemb);
  375. return size * nmemb;
  376. };
  377. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, static_cast<CURLOPT_WRITEFUNCTION_PTR>(write_callback));
  378. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &res_buffer);
  379. #if defined(_WIN32)
  380. curl_easy_setopt(curl.get(), CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA);
  381. #endif
  382. if (params.timeout > 0) {
  383. curl_easy_setopt(curl.get(), CURLOPT_TIMEOUT, params.timeout);
  384. }
  385. if (params.max_size > 0) {
  386. curl_easy_setopt(curl.get(), CURLOPT_MAXFILESIZE, params.max_size);
  387. }
  388. http_headers.ptr = curl_slist_append(http_headers.ptr, "User-Agent: llama-cpp");
  389. for (const auto & header : params.headers) {
  390. http_headers.ptr = curl_slist_append(http_headers.ptr, header.c_str());
  391. }
  392. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, http_headers.ptr);
  393. CURLcode res = curl_easy_perform(curl.get());
  394. if (res != CURLE_OK) {
  395. std::string error_msg = curl_easy_strerror(res);
  396. throw std::runtime_error("error: cannot make GET request: " + error_msg);
  397. }
  398. long res_code;
  399. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &res_code);
  400. return { res_code, std::move(res_buffer) };
  401. }
  402. #elif defined(LLAMA_USE_HTTPLIB)
  403. static bool is_output_a_tty() {
  404. #if defined(_WIN32)
  405. return _isatty(_fileno(stdout));
  406. #else
  407. return isatty(1);
  408. #endif
  409. }
  410. static void print_progress(size_t current, size_t total) {
  411. if (!is_output_a_tty()) {
  412. return;
  413. }
  414. if (!total) {
  415. return;
  416. }
  417. size_t width = 50;
  418. size_t pct = (100 * current) / total;
  419. size_t pos = (width * current) / total;
  420. std::cout << "["
  421. << std::string(pos, '=')
  422. << (pos < width ? ">" : "")
  423. << std::string(width - pos, ' ')
  424. << "] " << std::setw(3) << pct << "% ("
  425. << current / (1024 * 1024) << " MB / "
  426. << total / (1024 * 1024) << " MB)\r";
  427. std::cout.flush();
  428. }
  429. static bool common_pull_file(httplib::Client & cli,
  430. const std::string & resolve_path,
  431. const std::string & path_tmp,
  432. bool supports_ranges,
  433. size_t existing_size,
  434. size_t & total_size) {
  435. std::ofstream ofs(path_tmp, std::ios::binary | std::ios::app);
  436. if (!ofs.is_open()) {
  437. LOG_ERR("%s: error opening local file for writing: %s\n", __func__, path_tmp.c_str());
  438. return false;
  439. }
  440. httplib::Headers headers;
  441. if (supports_ranges && existing_size > 0) {
  442. headers.emplace("Range", "bytes=" + std::to_string(existing_size) + "-");
  443. }
  444. std::atomic<size_t> downloaded{existing_size};
  445. auto res = cli.Get(resolve_path, headers,
  446. [&](const httplib::Response &response) {
  447. if (existing_size > 0 && response.status != 206) {
  448. LOG_WRN("%s: server did not respond with 206 Partial Content for a resume request. Status: %d\n", __func__, response.status);
  449. return false;
  450. }
  451. if (existing_size == 0 && response.status != 200) {
  452. LOG_WRN("%s: download received non-successful status code: %d\n", __func__, response.status);
  453. return false;
  454. }
  455. if (total_size == 0 && response.has_header("Content-Length")) {
  456. try {
  457. size_t content_length = std::stoull(response.get_header_value("Content-Length"));
  458. total_size = existing_size + content_length;
  459. } catch (const std::exception &e) {
  460. LOG_WRN("%s: invalid Content-Length header: %s\n", __func__, e.what());
  461. }
  462. }
  463. return true;
  464. },
  465. [&](const char *data, size_t len) {
  466. ofs.write(data, len);
  467. if (!ofs) {
  468. LOG_ERR("%s: error writing to file: %s\n", __func__, path_tmp.c_str());
  469. return false;
  470. }
  471. downloaded += len;
  472. print_progress(downloaded, total_size);
  473. return true;
  474. },
  475. nullptr
  476. );
  477. std::cout << "\n";
  478. if (!res) {
  479. LOG_ERR("%s: error during download. Status: %d\n", __func__, res ? res->status : -1);
  480. return false;
  481. }
  482. return true;
  483. }
  484. // download one single file from remote URL to local path
  485. static bool common_download_file_single_online(const std::string & url,
  486. const std::string & path,
  487. const std::string & bearer_token) {
  488. static const int max_attempts = 3;
  489. static const int retry_delay_seconds = 2;
  490. auto [cli, parts] = common_http_client(url);
  491. httplib::Headers default_headers = {{"User-Agent", "llama-cpp"}};
  492. if (!bearer_token.empty()) {
  493. default_headers.insert({"Authorization", "Bearer " + bearer_token});
  494. }
  495. cli.set_default_headers(default_headers);
  496. const bool file_exists = std::filesystem::exists(path);
  497. std::string last_etag;
  498. if (file_exists) {
  499. last_etag = read_etag(path);
  500. } else {
  501. LOG_INF("%s: no previous model file found %s\n", __func__, path.c_str());
  502. }
  503. for (int i = 0; i < max_attempts; ++i) {
  504. auto head = cli.Head(parts.path);
  505. bool head_ok = head && head->status >= 200 && head->status < 300;
  506. if (!head_ok) {
  507. LOG_WRN("%s: HEAD invalid http status code received: %d\n", __func__, head ? head->status : -1);
  508. if (file_exists) {
  509. LOG_INF("%s: Using cached file (HEAD failed): %s\n", __func__, path.c_str());
  510. return true;
  511. }
  512. }
  513. std::string etag;
  514. if (head_ok && head->has_header("ETag")) {
  515. etag = head->get_header_value("ETag");
  516. }
  517. size_t total_size = 0;
  518. if (head_ok && head->has_header("Content-Length")) {
  519. try {
  520. total_size = std::stoull(head->get_header_value("Content-Length"));
  521. } catch (const std::exception& e) {
  522. LOG_WRN("%s: Invalid Content-Length in HEAD response: %s\n", __func__, e.what());
  523. }
  524. }
  525. bool supports_ranges = false;
  526. if (head_ok && head->has_header("Accept-Ranges")) {
  527. supports_ranges = head->get_header_value("Accept-Ranges") != "none";
  528. }
  529. bool should_download_from_scratch = false;
  530. if (!last_etag.empty() && !etag.empty() && last_etag != etag) {
  531. LOG_WRN("%s: ETag header is different (%s != %s): triggering a new download\n", __func__,
  532. last_etag.c_str(), etag.c_str());
  533. should_download_from_scratch = true;
  534. }
  535. if (file_exists) {
  536. if (!should_download_from_scratch) {
  537. LOG_INF("%s: using cached file: %s\n", __func__, path.c_str());
  538. return true;
  539. }
  540. LOG_WRN("%s: deleting previous downloaded file: %s\n", __func__, path.c_str());
  541. if (remove(path.c_str()) != 0) {
  542. LOG_ERR("%s: unable to delete file: %s\n", __func__, path.c_str());
  543. return false;
  544. }
  545. }
  546. const std::string path_temporary = path + ".downloadInProgress";
  547. size_t existing_size = 0;
  548. if (std::filesystem::exists(path_temporary)) {
  549. if (supports_ranges && !should_download_from_scratch) {
  550. existing_size = std::filesystem::file_size(path_temporary);
  551. } else if (remove(path_temporary.c_str()) != 0) {
  552. LOG_ERR("%s: unable to delete file: %s\n", __func__, path_temporary.c_str());
  553. return false;
  554. }
  555. }
  556. // start the download
  557. LOG_INF("%s: trying to download model from %s to %s (etag:%s)...\n",
  558. __func__, common_http_show_masked_url(parts).c_str(), path_temporary.c_str(), etag.c_str());
  559. const bool was_pull_successful = common_pull_file(cli, parts.path, path_temporary, supports_ranges, existing_size, total_size);
  560. if (!was_pull_successful) {
  561. if (i + 1 < max_attempts) {
  562. const int exponential_backoff_delay = std::pow(retry_delay_seconds, i) * 1000;
  563. LOG_WRN("%s: retrying after %d milliseconds...\n", __func__, exponential_backoff_delay);
  564. std::this_thread::sleep_for(std::chrono::milliseconds(exponential_backoff_delay));
  565. } else {
  566. LOG_ERR("%s: download failed after %d attempts\n", __func__, max_attempts);
  567. }
  568. continue;
  569. }
  570. if (std::rename(path_temporary.c_str(), path.c_str()) != 0) {
  571. LOG_ERR("%s: unable to rename file: %s to %s\n", __func__, path_temporary.c_str(), path.c_str());
  572. return false;
  573. }
  574. if (!etag.empty()) {
  575. write_etag(path, etag);
  576. }
  577. break;
  578. }
  579. return true;
  580. }
  581. std::pair<long, std::vector<char>> common_remote_get_content(const std::string & url,
  582. const common_remote_params & params) {
  583. auto [cli, parts] = common_http_client(url);
  584. httplib::Headers headers = {{"User-Agent", "llama-cpp"}};
  585. for (const auto & header : params.headers) {
  586. size_t pos = header.find(':');
  587. if (pos != std::string::npos) {
  588. headers.emplace(header.substr(0, pos), header.substr(pos + 1));
  589. } else {
  590. headers.emplace(header, "");
  591. }
  592. }
  593. if (params.timeout > 0) {
  594. cli.set_read_timeout(params.timeout, 0);
  595. cli.set_write_timeout(params.timeout, 0);
  596. }
  597. std::vector<char> buf;
  598. auto res = cli.Get(parts.path, headers,
  599. [&](const char *data, size_t len) {
  600. buf.insert(buf.end(), data, data + len);
  601. return params.max_size == 0 ||
  602. buf.size() <= static_cast<size_t>(params.max_size);
  603. },
  604. nullptr
  605. );
  606. if (!res) {
  607. throw std::runtime_error("error: cannot make GET request");
  608. }
  609. return { res->status, std::move(buf) };
  610. }
  611. #endif // LLAMA_USE_CURL
  612. #if defined(LLAMA_USE_CURL) || defined(LLAMA_USE_HTTPLIB)
  613. static bool common_download_file_single(const std::string & url,
  614. const std::string & path,
  615. const std::string & bearer_token,
  616. bool offline) {
  617. if (!offline) {
  618. return common_download_file_single_online(url, path, bearer_token);
  619. }
  620. if (!std::filesystem::exists(path)) {
  621. LOG_ERR("%s: required file is not available in cache (offline mode): %s\n", __func__, path.c_str());
  622. return false;
  623. }
  624. LOG_INF("%s: using cached file (offline mode): %s\n", __func__, path.c_str());
  625. return true;
  626. }
  627. // download multiple files from remote URLs to local paths
  628. // the input is a vector of pairs <url, path>
  629. static bool common_download_file_multiple(const std::vector<std::pair<std::string, std::string>> & urls, const std::string & bearer_token, bool offline) {
  630. // Prepare download in parallel
  631. std::vector<std::future<bool>> futures_download;
  632. for (auto const & item : urls) {
  633. futures_download.push_back(std::async(std::launch::async, [bearer_token, offline](const std::pair<std::string, std::string> & it) -> bool {
  634. return common_download_file_single(it.first, it.second, bearer_token, offline);
  635. }, item));
  636. }
  637. // Wait for all downloads to complete
  638. for (auto & f : futures_download) {
  639. if (!f.get()) {
  640. return false;
  641. }
  642. }
  643. return true;
  644. }
  645. bool common_download_model(
  646. const common_params_model & model,
  647. const std::string & bearer_token,
  648. bool offline) {
  649. // Basic validation of the model.url
  650. if (model.url.empty()) {
  651. LOG_ERR("%s: invalid model url\n", __func__);
  652. return false;
  653. }
  654. if (!common_download_file_single(model.url, model.path, bearer_token, offline)) {
  655. return false;
  656. }
  657. // check for additional GGUFs split to download
  658. int n_split = 0;
  659. {
  660. struct gguf_init_params gguf_params = {
  661. /*.no_alloc = */ true,
  662. /*.ctx = */ NULL,
  663. };
  664. auto * ctx_gguf = gguf_init_from_file(model.path.c_str(), gguf_params);
  665. if (!ctx_gguf) {
  666. LOG_ERR("\n%s: failed to load input GGUF from %s\n", __func__, model.path.c_str());
  667. return false;
  668. }
  669. auto key_n_split = gguf_find_key(ctx_gguf, LLM_KV_SPLIT_COUNT);
  670. if (key_n_split >= 0) {
  671. n_split = gguf_get_val_u16(ctx_gguf, key_n_split);
  672. }
  673. gguf_free(ctx_gguf);
  674. }
  675. if (n_split > 1) {
  676. char split_prefix[PATH_MAX] = {0};
  677. char split_url_prefix[LLAMA_MAX_URL_LENGTH] = {0};
  678. // Verify the first split file format
  679. // and extract split URL and PATH prefixes
  680. {
  681. if (!llama_split_prefix(split_prefix, sizeof(split_prefix), model.path.c_str(), 0, n_split)) {
  682. LOG_ERR("\n%s: unexpected model file name: %s n_split=%d\n", __func__, model.path.c_str(), n_split);
  683. return false;
  684. }
  685. if (!llama_split_prefix(split_url_prefix, sizeof(split_url_prefix), model.url.c_str(), 0, n_split)) {
  686. LOG_ERR("\n%s: unexpected model url: %s n_split=%d\n", __func__, model.url.c_str(), n_split);
  687. return false;
  688. }
  689. }
  690. std::vector<std::pair<std::string, std::string>> urls;
  691. for (int idx = 1; idx < n_split; idx++) {
  692. char split_path[PATH_MAX] = {0};
  693. llama_split_path(split_path, sizeof(split_path), split_prefix, idx, n_split);
  694. char split_url[LLAMA_MAX_URL_LENGTH] = {0};
  695. llama_split_path(split_url, sizeof(split_url), split_url_prefix, idx, n_split);
  696. if (std::string(split_path) == model.path) {
  697. continue; // skip the already downloaded file
  698. }
  699. urls.push_back({split_url, split_path});
  700. }
  701. // Download in parallel
  702. common_download_file_multiple(urls, bearer_token, offline);
  703. }
  704. return true;
  705. }
  706. common_hf_file_res common_get_hf_file(const std::string & hf_repo_with_tag, const std::string & bearer_token, bool offline) {
  707. auto parts = string_split<std::string>(hf_repo_with_tag, ':');
  708. std::string tag = parts.size() > 1 ? parts.back() : "latest";
  709. std::string hf_repo = parts[0];
  710. if (string_split<std::string>(hf_repo, '/').size() != 2) {
  711. throw std::invalid_argument("error: invalid HF repo format, expected <user>/<model>[:quant]\n");
  712. }
  713. std::string url = get_model_endpoint() + "v2/" + hf_repo + "/manifests/" + tag;
  714. // headers
  715. std::vector<std::string> headers;
  716. headers.push_back("Accept: application/json");
  717. if (!bearer_token.empty()) {
  718. headers.push_back("Authorization: Bearer " + bearer_token);
  719. }
  720. // Important: the User-Agent must be "llama-cpp" to get the "ggufFile" field in the response
  721. // User-Agent header is already set in common_remote_get_content, no need to set it here
  722. // make the request
  723. common_remote_params params;
  724. params.headers = headers;
  725. long res_code = 0;
  726. std::string res_str;
  727. bool use_cache = false;
  728. std::string cached_response_path = get_manifest_path(hf_repo, tag);
  729. if (!offline) {
  730. try {
  731. auto res = common_remote_get_content(url, params);
  732. res_code = res.first;
  733. res_str = std::string(res.second.data(), res.second.size());
  734. } catch (const std::exception & e) {
  735. LOG_WRN("error: failed to get manifest at %s: %s\n", url.c_str(), e.what());
  736. }
  737. }
  738. if (res_code == 0) {
  739. if (std::filesystem::exists(cached_response_path)) {
  740. LOG_WRN("trying to read manifest from cache: %s\n", cached_response_path.c_str());
  741. res_str = read_file(cached_response_path);
  742. res_code = 200;
  743. use_cache = true;
  744. } else {
  745. throw std::runtime_error(
  746. offline ? "error: failed to get manifest (offline mode)"
  747. : "error: failed to get manifest (check your internet connection)");
  748. }
  749. }
  750. std::string ggufFile;
  751. std::string mmprojFile;
  752. if (res_code == 200 || res_code == 304) {
  753. try {
  754. auto j = json::parse(res_str);
  755. if (j.contains("ggufFile") && j["ggufFile"].contains("rfilename")) {
  756. ggufFile = j["ggufFile"]["rfilename"].get<std::string>();
  757. }
  758. if (j.contains("mmprojFile") && j["mmprojFile"].contains("rfilename")) {
  759. mmprojFile = j["mmprojFile"]["rfilename"].get<std::string>();
  760. }
  761. } catch (const std::exception & e) {
  762. throw std::runtime_error(std::string("error parsing manifest JSON: ") + e.what());
  763. }
  764. if (!use_cache) {
  765. // if not using cached response, update the cache file
  766. write_file(cached_response_path, res_str);
  767. }
  768. } else if (res_code == 401) {
  769. throw std::runtime_error("error: model is private or does not exist; if you are accessing a gated model, please provide a valid HF token");
  770. } else {
  771. throw std::runtime_error(string_format("error from HF API, response code: %ld, data: %s", res_code, res_str.c_str()));
  772. }
  773. // check response
  774. if (ggufFile.empty()) {
  775. throw std::runtime_error("error: model does not have ggufFile");
  776. }
  777. return { hf_repo, ggufFile, mmprojFile };
  778. }
  779. //
  780. // Docker registry functions
  781. //
  782. static std::string common_docker_get_token(const std::string & repo) {
  783. std::string url = "https://auth.docker.io/token?service=registry.docker.io&scope=repository:" + repo + ":pull";
  784. common_remote_params params;
  785. auto res = common_remote_get_content(url, params);
  786. if (res.first != 200) {
  787. throw std::runtime_error("Failed to get Docker registry token, HTTP code: " + std::to_string(res.first));
  788. }
  789. std::string response_str(res.second.begin(), res.second.end());
  790. nlohmann::ordered_json response = nlohmann::ordered_json::parse(response_str);
  791. if (!response.contains("token")) {
  792. throw std::runtime_error("Docker registry token response missing 'token' field");
  793. }
  794. return response["token"].get<std::string>();
  795. }
  796. std::string common_docker_resolve_model(const std::string & docker) {
  797. // Parse ai/smollm2:135M-Q4_0
  798. size_t colon_pos = docker.find(':');
  799. std::string repo, tag;
  800. if (colon_pos != std::string::npos) {
  801. repo = docker.substr(0, colon_pos);
  802. tag = docker.substr(colon_pos + 1);
  803. } else {
  804. repo = docker;
  805. tag = "latest";
  806. }
  807. // ai/ is the default
  808. size_t slash_pos = docker.find('/');
  809. if (slash_pos == std::string::npos) {
  810. repo.insert(0, "ai/");
  811. }
  812. LOG_INF("%s: Downloading Docker Model: %s:%s\n", __func__, repo.c_str(), tag.c_str());
  813. try {
  814. // --- helper: digest validation ---
  815. auto validate_oci_digest = [](const std::string & digest) -> std::string {
  816. // Expected: algo:hex ; start with sha256 (64 hex chars)
  817. // You can extend this map if supporting other algorithms in future.
  818. static const std::regex re("^sha256:([a-fA-F0-9]{64})$");
  819. std::smatch m;
  820. if (!std::regex_match(digest, m, re)) {
  821. throw std::runtime_error("Invalid OCI digest format received in manifest: " + digest);
  822. }
  823. // normalize hex to lowercase
  824. std::string normalized = digest;
  825. std::transform(normalized.begin()+7, normalized.end(), normalized.begin()+7, [](unsigned char c){
  826. return std::tolower(c);
  827. });
  828. return normalized;
  829. };
  830. std::string token = common_docker_get_token(repo); // Get authentication token
  831. // Get manifest
  832. // TODO: cache the manifest response so that it appears in the model list
  833. const std::string url_prefix = "https://registry-1.docker.io/v2/" + repo;
  834. std::string manifest_url = url_prefix + "/manifests/" + tag;
  835. common_remote_params manifest_params;
  836. manifest_params.headers.push_back("Authorization: Bearer " + token);
  837. manifest_params.headers.push_back(
  838. "Accept: application/vnd.docker.distribution.manifest.v2+json,application/vnd.oci.image.manifest.v1+json");
  839. auto manifest_res = common_remote_get_content(manifest_url, manifest_params);
  840. if (manifest_res.first != 200) {
  841. throw std::runtime_error("Failed to get Docker manifest, HTTP code: " + std::to_string(manifest_res.first));
  842. }
  843. std::string manifest_str(manifest_res.second.begin(), manifest_res.second.end());
  844. nlohmann::ordered_json manifest = nlohmann::ordered_json::parse(manifest_str);
  845. std::string gguf_digest; // Find the GGUF layer
  846. if (manifest.contains("layers")) {
  847. for (const auto & layer : manifest["layers"]) {
  848. if (layer.contains("mediaType")) {
  849. std::string media_type = layer["mediaType"].get<std::string>();
  850. if (media_type == "application/vnd.docker.ai.gguf.v3" ||
  851. media_type.find("gguf") != std::string::npos) {
  852. gguf_digest = layer["digest"].get<std::string>();
  853. break;
  854. }
  855. }
  856. }
  857. }
  858. if (gguf_digest.empty()) {
  859. throw std::runtime_error("No GGUF layer found in Docker manifest");
  860. }
  861. // Validate & normalize digest
  862. gguf_digest = validate_oci_digest(gguf_digest);
  863. LOG_DBG("%s: Using validated digest: %s\n", __func__, gguf_digest.c_str());
  864. // Prepare local filename
  865. std::string model_filename = repo;
  866. std::replace(model_filename.begin(), model_filename.end(), '/', '_');
  867. model_filename += "_" + tag + ".gguf";
  868. std::string local_path = fs_get_cache_file(model_filename);
  869. const std::string blob_url = url_prefix + "/blobs/" + gguf_digest;
  870. if (!common_download_file_single(blob_url, local_path, token, false)) {
  871. throw std::runtime_error("Failed to download Docker Model");
  872. }
  873. LOG_INF("%s: Downloaded Docker Model to: %s\n", __func__, local_path.c_str());
  874. return local_path;
  875. } catch (const std::exception & e) {
  876. LOG_ERR("%s: Docker Model download failed: %s\n", __func__, e.what());
  877. throw;
  878. }
  879. }
  880. #else
  881. common_hf_file_res common_get_hf_file(const std::string &, const std::string &, bool) {
  882. throw std::runtime_error("download functionality is not enabled in this build");
  883. }
  884. bool common_download_model(const common_params_model &, const std::string &, bool) {
  885. throw std::runtime_error("download functionality is not enabled in this build");
  886. }
  887. std::string common_docker_resolve_model(const std::string &) {
  888. throw std::runtime_error("download functionality is not enabled in this build");
  889. }
  890. #endif // LLAMA_USE_CURL || LLAMA_USE_HTTPLIB
  891. std::vector<common_cached_model_info> common_list_cached_models() {
  892. std::vector<common_cached_model_info> models;
  893. const std::string cache_dir = fs_get_cache_directory();
  894. const std::vector<common_file_info> files = fs_list_files(cache_dir);
  895. for (const auto & file : files) {
  896. if (string_starts_with(file.name, "manifest=") && string_ends_with(file.name, ".json")) {
  897. common_cached_model_info model_info;
  898. model_info.manifest_path = file.path;
  899. std::string fname = file.name;
  900. string_replace_all(fname, ".json", ""); // remove extension
  901. auto parts = string_split<std::string>(fname, '=');
  902. if (parts.size() == 4) {
  903. // expect format: manifest=<user>=<model>=<tag>=<other>
  904. model_info.user = parts[1];
  905. model_info.model = parts[2];
  906. model_info.tag = parts[3];
  907. } else {
  908. // invalid format
  909. continue;
  910. }
  911. model_info.size = 0; // TODO: get GGUF size, not manifest size
  912. models.push_back(model_info);
  913. }
  914. }
  915. return models;
  916. }