1
0

download.cpp 42 KB

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