THIS IS A TEST INSTANCE ONLY! REPOSITORIES CAN BE DELETED AT ANY TIME!

Git Source Code Mirror - This is a publish-only repository and all pull requests are ignored. Please follow Documentation/SubmittingPatches procedure for any of your improvements.
git
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2543 lines
65KB

  1. #include "git-compat-util.h"
  2. #include "http.h"
  3. #include "config.h"
  4. #include "pack.h"
  5. #include "sideband.h"
  6. #include "run-command.h"
  7. #include "url.h"
  8. #include "urlmatch.h"
  9. #include "credential.h"
  10. #include "version.h"
  11. #include "pkt-line.h"
  12. #include "gettext.h"
  13. #include "transport.h"
  14. #include "packfile.h"
  15. #include "protocol.h"
  16. #include "string-list.h"
  17. #include "object-store.h"
  18. static struct trace_key trace_curl = TRACE_KEY_INIT(CURL);
  19. static int trace_curl_data = 1;
  20. static struct string_list cookies_to_redact = STRING_LIST_INIT_DUP;
  21. #if LIBCURL_VERSION_NUM >= 0x070a08
  22. long int git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
  23. #else
  24. long int git_curl_ipresolve;
  25. #endif
  26. int active_requests;
  27. int http_is_verbose;
  28. ssize_t http_post_buffer = 16 * LARGE_PACKET_MAX;
  29. #if LIBCURL_VERSION_NUM >= 0x070a06
  30. #define LIBCURL_CAN_HANDLE_AUTH_ANY
  31. #endif
  32. static int min_curl_sessions = 1;
  33. static int curl_session_count;
  34. #ifdef USE_CURL_MULTI
  35. static int max_requests = -1;
  36. static CURLM *curlm;
  37. #endif
  38. #ifndef NO_CURL_EASY_DUPHANDLE
  39. static CURL *curl_default;
  40. #endif
  41. #define PREV_BUF_SIZE 4096
  42. char curl_errorstr[CURL_ERROR_SIZE];
  43. static int curl_ssl_verify = -1;
  44. static int curl_ssl_try;
  45. static const char *curl_http_version = NULL;
  46. static const char *ssl_cert;
  47. static const char *ssl_cipherlist;
  48. static const char *ssl_version;
  49. static struct {
  50. const char *name;
  51. long ssl_version;
  52. } sslversions[] = {
  53. { "sslv2", CURL_SSLVERSION_SSLv2 },
  54. { "sslv3", CURL_SSLVERSION_SSLv3 },
  55. { "tlsv1", CURL_SSLVERSION_TLSv1 },
  56. #if LIBCURL_VERSION_NUM >= 0x072200
  57. { "tlsv1.0", CURL_SSLVERSION_TLSv1_0 },
  58. { "tlsv1.1", CURL_SSLVERSION_TLSv1_1 },
  59. { "tlsv1.2", CURL_SSLVERSION_TLSv1_2 },
  60. #endif
  61. #if LIBCURL_VERSION_NUM >= 0x073400
  62. { "tlsv1.3", CURL_SSLVERSION_TLSv1_3 },
  63. #endif
  64. };
  65. #if LIBCURL_VERSION_NUM >= 0x070903
  66. static const char *ssl_key;
  67. #endif
  68. #if LIBCURL_VERSION_NUM >= 0x070908
  69. static const char *ssl_capath;
  70. #endif
  71. #if LIBCURL_VERSION_NUM >= 0x071304
  72. static const char *curl_no_proxy;
  73. #endif
  74. #if LIBCURL_VERSION_NUM >= 0x072c00
  75. static const char *ssl_pinnedkey;
  76. #endif
  77. static const char *ssl_cainfo;
  78. static long curl_low_speed_limit = -1;
  79. static long curl_low_speed_time = -1;
  80. static int curl_ftp_no_epsv;
  81. static const char *curl_http_proxy;
  82. static const char *http_proxy_authmethod;
  83. static struct {
  84. const char *name;
  85. long curlauth_param;
  86. } proxy_authmethods[] = {
  87. { "basic", CURLAUTH_BASIC },
  88. { "digest", CURLAUTH_DIGEST },
  89. { "negotiate", CURLAUTH_GSSNEGOTIATE },
  90. { "ntlm", CURLAUTH_NTLM },
  91. #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
  92. { "anyauth", CURLAUTH_ANY },
  93. #endif
  94. /*
  95. * CURLAUTH_DIGEST_IE has no corresponding command-line option in
  96. * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
  97. * here, too
  98. */
  99. };
  100. #ifdef CURLGSSAPI_DELEGATION_FLAG
  101. static const char *curl_deleg;
  102. static struct {
  103. const char *name;
  104. long curl_deleg_param;
  105. } curl_deleg_levels[] = {
  106. { "none", CURLGSSAPI_DELEGATION_NONE },
  107. { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG },
  108. { "always", CURLGSSAPI_DELEGATION_FLAG },
  109. };
  110. #endif
  111. static struct credential proxy_auth = CREDENTIAL_INIT;
  112. static const char *curl_proxyuserpwd;
  113. static const char *curl_cookie_file;
  114. static int curl_save_cookies;
  115. struct credential http_auth = CREDENTIAL_INIT;
  116. static int http_proactive_auth;
  117. static const char *user_agent;
  118. static int curl_empty_auth = -1;
  119. enum http_follow_config http_follow_config = HTTP_FOLLOW_INITIAL;
  120. #if LIBCURL_VERSION_NUM >= 0x071700
  121. /* Use CURLOPT_KEYPASSWD as is */
  122. #elif LIBCURL_VERSION_NUM >= 0x070903
  123. #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
  124. #else
  125. #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
  126. #endif
  127. static struct credential cert_auth = CREDENTIAL_INIT;
  128. static int ssl_cert_password_required;
  129. #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
  130. static unsigned long http_auth_methods = CURLAUTH_ANY;
  131. static int http_auth_methods_restricted;
  132. /* Modes for which empty_auth cannot actually help us. */
  133. static unsigned long empty_auth_useless =
  134. CURLAUTH_BASIC
  135. #ifdef CURLAUTH_DIGEST_IE
  136. | CURLAUTH_DIGEST_IE
  137. #endif
  138. | CURLAUTH_DIGEST;
  139. #endif
  140. static struct curl_slist *pragma_header;
  141. static struct curl_slist *no_pragma_header;
  142. static struct string_list extra_http_headers = STRING_LIST_INIT_DUP;
  143. static struct active_request_slot *active_queue_head;
  144. static char *cached_accept_language;
  145. static char *http_ssl_backend;
  146. static int http_schannel_check_revoke = 1;
  147. /*
  148. * With the backend being set to `schannel`, setting sslCAinfo would override
  149. * the Certificate Store in cURL v7.60.0 and later, which is not what we want
  150. * by default.
  151. */
  152. static int http_schannel_use_ssl_cainfo;
  153. size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
  154. {
  155. size_t size = eltsize * nmemb;
  156. struct buffer *buffer = buffer_;
  157. if (size > buffer->buf.len - buffer->posn)
  158. size = buffer->buf.len - buffer->posn;
  159. memcpy(ptr, buffer->buf.buf + buffer->posn, size);
  160. buffer->posn += size;
  161. return size / eltsize;
  162. }
  163. #ifndef NO_CURL_IOCTL
  164. curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
  165. {
  166. struct buffer *buffer = clientp;
  167. switch (cmd) {
  168. case CURLIOCMD_NOP:
  169. return CURLIOE_OK;
  170. case CURLIOCMD_RESTARTREAD:
  171. buffer->posn = 0;
  172. return CURLIOE_OK;
  173. default:
  174. return CURLIOE_UNKNOWNCMD;
  175. }
  176. }
  177. #endif
  178. size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
  179. {
  180. size_t size = eltsize * nmemb;
  181. struct strbuf *buffer = buffer_;
  182. strbuf_add(buffer, ptr, size);
  183. return nmemb;
  184. }
  185. size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
  186. {
  187. return nmemb;
  188. }
  189. static void closedown_active_slot(struct active_request_slot *slot)
  190. {
  191. active_requests--;
  192. slot->in_use = 0;
  193. }
  194. static void finish_active_slot(struct active_request_slot *slot)
  195. {
  196. closedown_active_slot(slot);
  197. curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
  198. if (slot->finished != NULL)
  199. (*slot->finished) = 1;
  200. /* Store slot results so they can be read after the slot is reused */
  201. if (slot->results != NULL) {
  202. slot->results->curl_result = slot->curl_result;
  203. slot->results->http_code = slot->http_code;
  204. #if LIBCURL_VERSION_NUM >= 0x070a08
  205. curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
  206. &slot->results->auth_avail);
  207. #else
  208. slot->results->auth_avail = 0;
  209. #endif
  210. curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
  211. &slot->results->http_connectcode);
  212. }
  213. /* Run callback if appropriate */
  214. if (slot->callback_func != NULL)
  215. slot->callback_func(slot->callback_data);
  216. }
  217. static void xmulti_remove_handle(struct active_request_slot *slot)
  218. {
  219. #ifdef USE_CURL_MULTI
  220. curl_multi_remove_handle(curlm, slot->curl);
  221. #endif
  222. }
  223. #ifdef USE_CURL_MULTI
  224. static void process_curl_messages(void)
  225. {
  226. int num_messages;
  227. struct active_request_slot *slot;
  228. CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
  229. while (curl_message != NULL) {
  230. if (curl_message->msg == CURLMSG_DONE) {
  231. int curl_result = curl_message->data.result;
  232. slot = active_queue_head;
  233. while (slot != NULL &&
  234. slot->curl != curl_message->easy_handle)
  235. slot = slot->next;
  236. if (slot != NULL) {
  237. xmulti_remove_handle(slot);
  238. slot->curl_result = curl_result;
  239. finish_active_slot(slot);
  240. } else {
  241. fprintf(stderr, "Received DONE message for unknown request!\n");
  242. }
  243. } else {
  244. fprintf(stderr, "Unknown CURL message received: %d\n",
  245. (int)curl_message->msg);
  246. }
  247. curl_message = curl_multi_info_read(curlm, &num_messages);
  248. }
  249. }
  250. #endif
  251. static int http_options(const char *var, const char *value, void *cb)
  252. {
  253. if (!strcmp("http.version", var)) {
  254. return git_config_string(&curl_http_version, var, value);
  255. }
  256. if (!strcmp("http.sslverify", var)) {
  257. curl_ssl_verify = git_config_bool(var, value);
  258. return 0;
  259. }
  260. if (!strcmp("http.sslcipherlist", var))
  261. return git_config_string(&ssl_cipherlist, var, value);
  262. if (!strcmp("http.sslversion", var))
  263. return git_config_string(&ssl_version, var, value);
  264. if (!strcmp("http.sslcert", var))
  265. return git_config_pathname(&ssl_cert, var, value);
  266. #if LIBCURL_VERSION_NUM >= 0x070903
  267. if (!strcmp("http.sslkey", var))
  268. return git_config_pathname(&ssl_key, var, value);
  269. #endif
  270. #if LIBCURL_VERSION_NUM >= 0x070908
  271. if (!strcmp("http.sslcapath", var))
  272. return git_config_pathname(&ssl_capath, var, value);
  273. #endif
  274. if (!strcmp("http.sslcainfo", var))
  275. return git_config_pathname(&ssl_cainfo, var, value);
  276. if (!strcmp("http.sslcertpasswordprotected", var)) {
  277. ssl_cert_password_required = git_config_bool(var, value);
  278. return 0;
  279. }
  280. if (!strcmp("http.ssltry", var)) {
  281. curl_ssl_try = git_config_bool(var, value);
  282. return 0;
  283. }
  284. if (!strcmp("http.sslbackend", var)) {
  285. free(http_ssl_backend);
  286. http_ssl_backend = xstrdup_or_null(value);
  287. return 0;
  288. }
  289. if (!strcmp("http.schannelcheckrevoke", var)) {
  290. http_schannel_check_revoke = git_config_bool(var, value);
  291. return 0;
  292. }
  293. if (!strcmp("http.schannelusesslcainfo", var)) {
  294. http_schannel_use_ssl_cainfo = git_config_bool(var, value);
  295. return 0;
  296. }
  297. if (!strcmp("http.minsessions", var)) {
  298. min_curl_sessions = git_config_int(var, value);
  299. #ifndef USE_CURL_MULTI
  300. if (min_curl_sessions > 1)
  301. min_curl_sessions = 1;
  302. #endif
  303. return 0;
  304. }
  305. #ifdef USE_CURL_MULTI
  306. if (!strcmp("http.maxrequests", var)) {
  307. max_requests = git_config_int(var, value);
  308. return 0;
  309. }
  310. #endif
  311. if (!strcmp("http.lowspeedlimit", var)) {
  312. curl_low_speed_limit = (long)git_config_int(var, value);
  313. return 0;
  314. }
  315. if (!strcmp("http.lowspeedtime", var)) {
  316. curl_low_speed_time = (long)git_config_int(var, value);
  317. return 0;
  318. }
  319. if (!strcmp("http.noepsv", var)) {
  320. curl_ftp_no_epsv = git_config_bool(var, value);
  321. return 0;
  322. }
  323. if (!strcmp("http.proxy", var))
  324. return git_config_string(&curl_http_proxy, var, value);
  325. if (!strcmp("http.proxyauthmethod", var))
  326. return git_config_string(&http_proxy_authmethod, var, value);
  327. if (!strcmp("http.cookiefile", var))
  328. return git_config_pathname(&curl_cookie_file, var, value);
  329. if (!strcmp("http.savecookies", var)) {
  330. curl_save_cookies = git_config_bool(var, value);
  331. return 0;
  332. }
  333. if (!strcmp("http.postbuffer", var)) {
  334. http_post_buffer = git_config_ssize_t(var, value);
  335. if (http_post_buffer < 0)
  336. warning(_("negative value for http.postbuffer; defaulting to %d"), LARGE_PACKET_MAX);
  337. if (http_post_buffer < LARGE_PACKET_MAX)
  338. http_post_buffer = LARGE_PACKET_MAX;
  339. return 0;
  340. }
  341. if (!strcmp("http.useragent", var))
  342. return git_config_string(&user_agent, var, value);
  343. if (!strcmp("http.emptyauth", var)) {
  344. if (value && !strcmp("auto", value))
  345. curl_empty_auth = -1;
  346. else
  347. curl_empty_auth = git_config_bool(var, value);
  348. return 0;
  349. }
  350. if (!strcmp("http.delegation", var)) {
  351. #ifdef CURLGSSAPI_DELEGATION_FLAG
  352. return git_config_string(&curl_deleg, var, value);
  353. #else
  354. warning(_("Delegation control is not supported with cURL < 7.22.0"));
  355. return 0;
  356. #endif
  357. }
  358. if (!strcmp("http.pinnedpubkey", var)) {
  359. #if LIBCURL_VERSION_NUM >= 0x072c00
  360. return git_config_pathname(&ssl_pinnedkey, var, value);
  361. #else
  362. warning(_("Public key pinning not supported with cURL < 7.44.0"));
  363. return 0;
  364. #endif
  365. }
  366. if (!strcmp("http.extraheader", var)) {
  367. if (!value) {
  368. return config_error_nonbool(var);
  369. } else if (!*value) {
  370. string_list_clear(&extra_http_headers, 0);
  371. } else {
  372. string_list_append(&extra_http_headers, value);
  373. }
  374. return 0;
  375. }
  376. if (!strcmp("http.followredirects", var)) {
  377. if (value && !strcmp(value, "initial"))
  378. http_follow_config = HTTP_FOLLOW_INITIAL;
  379. else if (git_config_bool(var, value))
  380. http_follow_config = HTTP_FOLLOW_ALWAYS;
  381. else
  382. http_follow_config = HTTP_FOLLOW_NONE;
  383. return 0;
  384. }
  385. /* Fall back on the default ones */
  386. return git_default_config(var, value, cb);
  387. }
  388. static int curl_empty_auth_enabled(void)
  389. {
  390. if (curl_empty_auth >= 0)
  391. return curl_empty_auth;
  392. #ifndef LIBCURL_CAN_HANDLE_AUTH_ANY
  393. /*
  394. * Our libcurl is too old to do AUTH_ANY in the first place;
  395. * just default to turning the feature off.
  396. */
  397. #else
  398. /*
  399. * In the automatic case, kick in the empty-auth
  400. * hack as long as we would potentially try some
  401. * method more exotic than "Basic" or "Digest".
  402. *
  403. * But only do this when this is our second or
  404. * subsequent request, as by then we know what
  405. * methods are available.
  406. */
  407. if (http_auth_methods_restricted &&
  408. (http_auth_methods & ~empty_auth_useless))
  409. return 1;
  410. #endif
  411. return 0;
  412. }
  413. static void init_curl_http_auth(CURL *result)
  414. {
  415. if (!http_auth.username || !*http_auth.username) {
  416. if (curl_empty_auth_enabled())
  417. curl_easy_setopt(result, CURLOPT_USERPWD, ":");
  418. return;
  419. }
  420. credential_fill(&http_auth);
  421. #if LIBCURL_VERSION_NUM >= 0x071301
  422. curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
  423. curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
  424. #else
  425. {
  426. static struct strbuf up = STRBUF_INIT;
  427. /*
  428. * Note that we assume we only ever have a single set of
  429. * credentials in a given program run, so we do not have
  430. * to worry about updating this buffer, only setting its
  431. * initial value.
  432. */
  433. if (!up.len)
  434. strbuf_addf(&up, "%s:%s",
  435. http_auth.username, http_auth.password);
  436. curl_easy_setopt(result, CURLOPT_USERPWD, up.buf);
  437. }
  438. #endif
  439. }
  440. /* *var must be free-able */
  441. static void var_override(const char **var, char *value)
  442. {
  443. if (value) {
  444. free((void *)*var);
  445. *var = xstrdup(value);
  446. }
  447. }
  448. static void set_proxyauth_name_password(CURL *result)
  449. {
  450. #if LIBCURL_VERSION_NUM >= 0x071301
  451. curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
  452. proxy_auth.username);
  453. curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
  454. proxy_auth.password);
  455. #else
  456. struct strbuf s = STRBUF_INIT;
  457. strbuf_addstr_urlencode(&s, proxy_auth.username,
  458. is_rfc3986_unreserved);
  459. strbuf_addch(&s, ':');
  460. strbuf_addstr_urlencode(&s, proxy_auth.password,
  461. is_rfc3986_unreserved);
  462. curl_proxyuserpwd = strbuf_detach(&s, NULL);
  463. curl_easy_setopt(result, CURLOPT_PROXYUSERPWD, curl_proxyuserpwd);
  464. #endif
  465. }
  466. static void init_curl_proxy_auth(CURL *result)
  467. {
  468. if (proxy_auth.username) {
  469. if (!proxy_auth.password)
  470. credential_fill(&proxy_auth);
  471. set_proxyauth_name_password(result);
  472. }
  473. var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
  474. #if LIBCURL_VERSION_NUM >= 0x070a07 /* CURLOPT_PROXYAUTH and CURLAUTH_ANY */
  475. if (http_proxy_authmethod) {
  476. int i;
  477. for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
  478. if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
  479. curl_easy_setopt(result, CURLOPT_PROXYAUTH,
  480. proxy_authmethods[i].curlauth_param);
  481. break;
  482. }
  483. }
  484. if (i == ARRAY_SIZE(proxy_authmethods)) {
  485. warning("unsupported proxy authentication method %s: using anyauth",
  486. http_proxy_authmethod);
  487. curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
  488. }
  489. }
  490. else
  491. curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
  492. #endif
  493. }
  494. static int has_cert_password(void)
  495. {
  496. if (ssl_cert == NULL || ssl_cert_password_required != 1)
  497. return 0;
  498. if (!cert_auth.password) {
  499. cert_auth.protocol = xstrdup("cert");
  500. cert_auth.username = xstrdup("");
  501. cert_auth.path = xstrdup(ssl_cert);
  502. credential_fill(&cert_auth);
  503. }
  504. return 1;
  505. }
  506. #if LIBCURL_VERSION_NUM >= 0x071900
  507. static void set_curl_keepalive(CURL *c)
  508. {
  509. curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
  510. }
  511. #elif LIBCURL_VERSION_NUM >= 0x071000
  512. static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
  513. {
  514. int ka = 1;
  515. int rc;
  516. socklen_t len = (socklen_t)sizeof(ka);
  517. if (type != CURLSOCKTYPE_IPCXN)
  518. return 0;
  519. rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
  520. if (rc < 0)
  521. warning_errno("unable to set SO_KEEPALIVE on socket");
  522. return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
  523. }
  524. static void set_curl_keepalive(CURL *c)
  525. {
  526. curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
  527. }
  528. #else
  529. static void set_curl_keepalive(CURL *c)
  530. {
  531. /* not supported on older curl versions */
  532. }
  533. #endif
  534. static void redact_sensitive_header(struct strbuf *header)
  535. {
  536. const char *sensitive_header;
  537. if (skip_prefix(header->buf, "Authorization:", &sensitive_header) ||
  538. skip_prefix(header->buf, "Proxy-Authorization:", &sensitive_header)) {
  539. /* The first token is the type, which is OK to log */
  540. while (isspace(*sensitive_header))
  541. sensitive_header++;
  542. while (*sensitive_header && !isspace(*sensitive_header))
  543. sensitive_header++;
  544. /* Everything else is opaque and possibly sensitive */
  545. strbuf_setlen(header, sensitive_header - header->buf);
  546. strbuf_addstr(header, " <redacted>");
  547. } else if (cookies_to_redact.nr &&
  548. skip_prefix(header->buf, "Cookie:", &sensitive_header)) {
  549. struct strbuf redacted_header = STRBUF_INIT;
  550. char *cookie;
  551. while (isspace(*sensitive_header))
  552. sensitive_header++;
  553. /*
  554. * The contents of header starting from sensitive_header will
  555. * subsequently be overridden, so it is fine to mutate this
  556. * string (hence the assignment to "char *").
  557. */
  558. cookie = (char *) sensitive_header;
  559. while (cookie) {
  560. char *equals;
  561. char *semicolon = strstr(cookie, "; ");
  562. if (semicolon)
  563. *semicolon = 0;
  564. equals = strchrnul(cookie, '=');
  565. if (!equals) {
  566. /* invalid cookie, just append and continue */
  567. strbuf_addstr(&redacted_header, cookie);
  568. continue;
  569. }
  570. *equals = 0; /* temporarily set to NUL for lookup */
  571. if (string_list_lookup(&cookies_to_redact, cookie)) {
  572. strbuf_addstr(&redacted_header, cookie);
  573. strbuf_addstr(&redacted_header, "=<redacted>");
  574. } else {
  575. *equals = '=';
  576. strbuf_addstr(&redacted_header, cookie);
  577. }
  578. if (semicolon) {
  579. /*
  580. * There are more cookies. (Or, for some
  581. * reason, the input string ends in "; ".)
  582. */
  583. strbuf_addstr(&redacted_header, "; ");
  584. cookie = semicolon + strlen("; ");
  585. } else {
  586. cookie = NULL;
  587. }
  588. }
  589. strbuf_setlen(header, sensitive_header - header->buf);
  590. strbuf_addbuf(header, &redacted_header);
  591. }
  592. }
  593. static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
  594. {
  595. struct strbuf out = STRBUF_INIT;
  596. struct strbuf **headers, **header;
  597. strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
  598. text, (long)size, (long)size);
  599. trace_strbuf(&trace_curl, &out);
  600. strbuf_reset(&out);
  601. strbuf_add(&out, ptr, size);
  602. headers = strbuf_split_max(&out, '\n', 0);
  603. for (header = headers; *header; header++) {
  604. if (hide_sensitive_header)
  605. redact_sensitive_header(*header);
  606. strbuf_insert((*header), 0, text, strlen(text));
  607. strbuf_insert((*header), strlen(text), ": ", 2);
  608. strbuf_rtrim((*header));
  609. strbuf_addch((*header), '\n');
  610. trace_strbuf(&trace_curl, (*header));
  611. }
  612. strbuf_list_free(headers);
  613. strbuf_release(&out);
  614. }
  615. static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
  616. {
  617. size_t i;
  618. struct strbuf out = STRBUF_INIT;
  619. unsigned int width = 60;
  620. strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
  621. text, (long)size, (long)size);
  622. trace_strbuf(&trace_curl, &out);
  623. for (i = 0; i < size; i += width) {
  624. size_t w;
  625. strbuf_reset(&out);
  626. strbuf_addf(&out, "%s: ", text);
  627. for (w = 0; (w < width) && (i + w < size); w++) {
  628. unsigned char ch = ptr[i + w];
  629. strbuf_addch(&out,
  630. (ch >= 0x20) && (ch < 0x80)
  631. ? ch : '.');
  632. }
  633. strbuf_addch(&out, '\n');
  634. trace_strbuf(&trace_curl, &out);
  635. }
  636. strbuf_release(&out);
  637. }
  638. static int curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
  639. {
  640. const char *text;
  641. enum { NO_FILTER = 0, DO_FILTER = 1 };
  642. switch (type) {
  643. case CURLINFO_TEXT:
  644. trace_printf_key(&trace_curl, "== Info: %s", data);
  645. break;
  646. case CURLINFO_HEADER_OUT:
  647. text = "=> Send header";
  648. curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
  649. break;
  650. case CURLINFO_DATA_OUT:
  651. if (trace_curl_data) {
  652. text = "=> Send data";
  653. curl_dump_data(text, (unsigned char *)data, size);
  654. }
  655. break;
  656. case CURLINFO_SSL_DATA_OUT:
  657. if (trace_curl_data) {
  658. text = "=> Send SSL data";
  659. curl_dump_data(text, (unsigned char *)data, size);
  660. }
  661. break;
  662. case CURLINFO_HEADER_IN:
  663. text = "<= Recv header";
  664. curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
  665. break;
  666. case CURLINFO_DATA_IN:
  667. if (trace_curl_data) {
  668. text = "<= Recv data";
  669. curl_dump_data(text, (unsigned char *)data, size);
  670. }
  671. break;
  672. case CURLINFO_SSL_DATA_IN:
  673. if (trace_curl_data) {
  674. text = "<= Recv SSL data";
  675. curl_dump_data(text, (unsigned char *)data, size);
  676. }
  677. break;
  678. default: /* we ignore unknown types by default */
  679. return 0;
  680. }
  681. return 0;
  682. }
  683. void setup_curl_trace(CURL *handle)
  684. {
  685. if (!trace_want(&trace_curl))
  686. return;
  687. curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
  688. curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
  689. curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
  690. }
  691. #ifdef CURLPROTO_HTTP
  692. static long get_curl_allowed_protocols(int from_user)
  693. {
  694. long allowed_protocols = 0;
  695. if (is_transport_allowed("http", from_user))
  696. allowed_protocols |= CURLPROTO_HTTP;
  697. if (is_transport_allowed("https", from_user))
  698. allowed_protocols |= CURLPROTO_HTTPS;
  699. if (is_transport_allowed("ftp", from_user))
  700. allowed_protocols |= CURLPROTO_FTP;
  701. if (is_transport_allowed("ftps", from_user))
  702. allowed_protocols |= CURLPROTO_FTPS;
  703. return allowed_protocols;
  704. }
  705. #endif
  706. #if LIBCURL_VERSION_NUM >=0x072f00
  707. static int get_curl_http_version_opt(const char *version_string, long *opt)
  708. {
  709. int i;
  710. static struct {
  711. const char *name;
  712. long opt_token;
  713. } choice[] = {
  714. { "HTTP/1.1", CURL_HTTP_VERSION_1_1 },
  715. { "HTTP/2", CURL_HTTP_VERSION_2 }
  716. };
  717. for (i = 0; i < ARRAY_SIZE(choice); i++) {
  718. if (!strcmp(version_string, choice[i].name)) {
  719. *opt = choice[i].opt_token;
  720. return 0;
  721. }
  722. }
  723. warning("unknown value given to http.version: '%s'", version_string);
  724. return -1; /* not found */
  725. }
  726. #endif
  727. static CURL *get_curl_handle(void)
  728. {
  729. CURL *result = curl_easy_init();
  730. if (!result)
  731. die("curl_easy_init failed");
  732. if (!curl_ssl_verify) {
  733. curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
  734. curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
  735. } else {
  736. /* Verify authenticity of the peer's certificate */
  737. curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
  738. /* The name in the cert must match whom we tried to connect */
  739. curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
  740. }
  741. #if LIBCURL_VERSION_NUM >= 0x072f00 // 7.47.0
  742. if (curl_http_version) {
  743. long opt;
  744. if (!get_curl_http_version_opt(curl_http_version, &opt)) {
  745. /* Set request use http version */
  746. curl_easy_setopt(result, CURLOPT_HTTP_VERSION, opt);
  747. }
  748. }
  749. #endif
  750. #if LIBCURL_VERSION_NUM >= 0x070907
  751. curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
  752. #endif
  753. #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
  754. curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
  755. #endif
  756. #ifdef CURLGSSAPI_DELEGATION_FLAG
  757. if (curl_deleg) {
  758. int i;
  759. for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
  760. if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
  761. curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
  762. curl_deleg_levels[i].curl_deleg_param);
  763. break;
  764. }
  765. }
  766. if (i == ARRAY_SIZE(curl_deleg_levels))
  767. warning("Unknown delegation method '%s': using default",
  768. curl_deleg);
  769. }
  770. #endif
  771. if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
  772. !http_schannel_check_revoke) {
  773. #if LIBCURL_VERSION_NUM >= 0x072c00
  774. curl_easy_setopt(result, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
  775. #else
  776. warning(_("CURLSSLOPT_NO_REVOKE not supported with cURL < 7.44.0"));
  777. #endif
  778. }
  779. if (http_proactive_auth)
  780. init_curl_http_auth(result);
  781. if (getenv("GIT_SSL_VERSION"))
  782. ssl_version = getenv("GIT_SSL_VERSION");
  783. if (ssl_version && *ssl_version) {
  784. int i;
  785. for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
  786. if (!strcmp(ssl_version, sslversions[i].name)) {
  787. curl_easy_setopt(result, CURLOPT_SSLVERSION,
  788. sslversions[i].ssl_version);
  789. break;
  790. }
  791. }
  792. if (i == ARRAY_SIZE(sslversions))
  793. warning("unsupported ssl version %s: using default",
  794. ssl_version);
  795. }
  796. if (getenv("GIT_SSL_CIPHER_LIST"))
  797. ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
  798. if (ssl_cipherlist != NULL && *ssl_cipherlist)
  799. curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
  800. ssl_cipherlist);
  801. if (ssl_cert != NULL)
  802. curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
  803. if (has_cert_password())
  804. curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
  805. #if LIBCURL_VERSION_NUM >= 0x070903
  806. if (ssl_key != NULL)
  807. curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
  808. #endif
  809. #if LIBCURL_VERSION_NUM >= 0x070908
  810. if (ssl_capath != NULL)
  811. curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
  812. #endif
  813. #if LIBCURL_VERSION_NUM >= 0x072c00
  814. if (ssl_pinnedkey != NULL)
  815. curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
  816. #endif
  817. if (http_ssl_backend && !strcmp("schannel", http_ssl_backend) &&
  818. !http_schannel_use_ssl_cainfo) {
  819. curl_easy_setopt(result, CURLOPT_CAINFO, NULL);
  820. #if LIBCURL_VERSION_NUM >= 0x073400
  821. curl_easy_setopt(result, CURLOPT_PROXY_CAINFO, NULL);
  822. #endif
  823. } else if (ssl_cainfo != NULL)
  824. curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
  825. if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
  826. curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
  827. curl_low_speed_limit);
  828. curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
  829. curl_low_speed_time);
  830. }
  831. curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
  832. #if LIBCURL_VERSION_NUM >= 0x071301
  833. curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
  834. #elif LIBCURL_VERSION_NUM >= 0x071101
  835. curl_easy_setopt(result, CURLOPT_POST301, 1);
  836. #endif
  837. #ifdef CURLPROTO_HTTP
  838. curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
  839. get_curl_allowed_protocols(0));
  840. curl_easy_setopt(result, CURLOPT_PROTOCOLS,
  841. get_curl_allowed_protocols(-1));
  842. #else
  843. warning(_("Protocol restrictions not supported with cURL < 7.19.4"));
  844. #endif
  845. if (getenv("GIT_CURL_VERBOSE"))
  846. curl_easy_setopt(result, CURLOPT_VERBOSE, 1L);
  847. setup_curl_trace(result);
  848. if (getenv("GIT_TRACE_CURL_NO_DATA"))
  849. trace_curl_data = 0;
  850. if (getenv("GIT_REDACT_COOKIES")) {
  851. string_list_split(&cookies_to_redact,
  852. getenv("GIT_REDACT_COOKIES"), ',', -1);
  853. string_list_sort(&cookies_to_redact);
  854. }
  855. curl_easy_setopt(result, CURLOPT_USERAGENT,
  856. user_agent ? user_agent : git_user_agent());
  857. if (curl_ftp_no_epsv)
  858. curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
  859. #ifdef CURLOPT_USE_SSL
  860. if (curl_ssl_try)
  861. curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  862. #endif
  863. /*
  864. * CURL also examines these variables as a fallback; but we need to query
  865. * them here in order to decide whether to prompt for missing password (cf.
  866. * init_curl_proxy_auth()).
  867. *
  868. * Unlike many other common environment variables, these are historically
  869. * lowercase only. It appears that CURL did not know this and implemented
  870. * only uppercase variants, which was later corrected to take both - with
  871. * the exception of http_proxy, which is lowercase only also in CURL. As
  872. * the lowercase versions are the historical quasi-standard, they take
  873. * precedence here, as in CURL.
  874. */
  875. if (!curl_http_proxy) {
  876. if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
  877. var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
  878. var_override(&curl_http_proxy, getenv("https_proxy"));
  879. } else {
  880. var_override(&curl_http_proxy, getenv("http_proxy"));
  881. }
  882. if (!curl_http_proxy) {
  883. var_override(&curl_http_proxy, getenv("ALL_PROXY"));
  884. var_override(&curl_http_proxy, getenv("all_proxy"));
  885. }
  886. }
  887. if (curl_http_proxy && curl_http_proxy[0] == '\0') {
  888. /*
  889. * Handle case with the empty http.proxy value here to keep
  890. * common code clean.
  891. * NB: empty option disables proxying at all.
  892. */
  893. curl_easy_setopt(result, CURLOPT_PROXY, "");
  894. } else if (curl_http_proxy) {
  895. #if LIBCURL_VERSION_NUM >= 0x071800
  896. if (starts_with(curl_http_proxy, "socks5h"))
  897. curl_easy_setopt(result,
  898. CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
  899. else if (starts_with(curl_http_proxy, "socks5"))
  900. curl_easy_setopt(result,
  901. CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
  902. else if (starts_with(curl_http_proxy, "socks4a"))
  903. curl_easy_setopt(result,
  904. CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
  905. else if (starts_with(curl_http_proxy, "socks"))
  906. curl_easy_setopt(result,
  907. CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  908. #endif
  909. #if LIBCURL_VERSION_NUM >= 0x073400
  910. else if (starts_with(curl_http_proxy, "https"))
  911. curl_easy_setopt(result,
  912. CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
  913. #endif
  914. if (strstr(curl_http_proxy, "://"))
  915. credential_from_url(&proxy_auth, curl_http_proxy);
  916. else {
  917. struct strbuf url = STRBUF_INIT;
  918. strbuf_addf(&url, "http://%s", curl_http_proxy);
  919. credential_from_url(&proxy_auth, url.buf);
  920. strbuf_release(&url);
  921. }
  922. if (!proxy_auth.host)
  923. die("Invalid proxy URL '%s'", curl_http_proxy);
  924. curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
  925. #if LIBCURL_VERSION_NUM >= 0x071304
  926. var_override(&curl_no_proxy, getenv("NO_PROXY"));
  927. var_override(&curl_no_proxy, getenv("no_proxy"));
  928. curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
  929. #endif
  930. }
  931. init_curl_proxy_auth(result);
  932. set_curl_keepalive(result);
  933. return result;
  934. }
  935. static void set_from_env(const char **var, const char *envname)
  936. {
  937. const char *val = getenv(envname);
  938. if (val)
  939. *var = val;
  940. }
  941. void http_init(struct remote *remote, const char *url, int proactive_auth)
  942. {
  943. char *low_speed_limit;
  944. char *low_speed_time;
  945. char *normalized_url;
  946. struct urlmatch_config config = { STRING_LIST_INIT_DUP };
  947. config.section = "http";
  948. config.key = NULL;
  949. config.collect_fn = http_options;
  950. config.cascade_fn = git_default_config;
  951. config.cb = NULL;
  952. http_is_verbose = 0;
  953. normalized_url = url_normalize(url, &config.url);
  954. git_config(urlmatch_config_entry, &config);
  955. free(normalized_url);
  956. string_list_clear(&config.vars, 1);
  957. #if LIBCURL_VERSION_NUM >= 0x073800
  958. if (http_ssl_backend) {
  959. const curl_ssl_backend **backends;
  960. struct strbuf buf = STRBUF_INIT;
  961. int i;
  962. switch (curl_global_sslset(-1, http_ssl_backend, &backends)) {
  963. case CURLSSLSET_UNKNOWN_BACKEND:
  964. strbuf_addf(&buf, _("Unsupported SSL backend '%s'. "
  965. "Supported SSL backends:"),
  966. http_ssl_backend);
  967. for (i = 0; backends[i]; i++)
  968. strbuf_addf(&buf, "\n\t%s", backends[i]->name);
  969. die("%s", buf.buf);
  970. case CURLSSLSET_NO_BACKENDS:
  971. die(_("Could not set SSL backend to '%s': "
  972. "cURL was built without SSL backends"),
  973. http_ssl_backend);
  974. case CURLSSLSET_TOO_LATE:
  975. die(_("Could not set SSL backend to '%s': already set"),
  976. http_ssl_backend);
  977. case CURLSSLSET_OK:
  978. break; /* Okay! */
  979. }
  980. }
  981. #endif
  982. if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
  983. die("curl_global_init failed");
  984. http_proactive_auth = proactive_auth;
  985. if (remote && remote->http_proxy)
  986. curl_http_proxy = xstrdup(remote->http_proxy);
  987. if (remote)
  988. var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
  989. pragma_header = curl_slist_append(http_copy_default_headers(),
  990. "Pragma: no-cache");
  991. no_pragma_header = curl_slist_append(http_copy_default_headers(),
  992. "Pragma:");
  993. #ifdef USE_CURL_MULTI
  994. {
  995. char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
  996. if (http_max_requests != NULL)
  997. max_requests = atoi(http_max_requests);
  998. }
  999. curlm = curl_multi_init();
  1000. if (!curlm)
  1001. die("curl_multi_init failed");
  1002. #endif
  1003. if (getenv("GIT_SSL_NO_VERIFY"))
  1004. curl_ssl_verify = 0;
  1005. set_from_env(&ssl_cert, "GIT_SSL_CERT");
  1006. #if LIBCURL_VERSION_NUM >= 0x070903
  1007. set_from_env(&ssl_key, "GIT_SSL_KEY");
  1008. #endif
  1009. #if LIBCURL_VERSION_NUM >= 0x070908
  1010. set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
  1011. #endif
  1012. set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
  1013. set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
  1014. low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
  1015. if (low_speed_limit != NULL)
  1016. curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
  1017. low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
  1018. if (low_speed_time != NULL)
  1019. curl_low_speed_time = strtol(low_speed_time, NULL, 10);
  1020. if (curl_ssl_verify == -1)
  1021. curl_ssl_verify = 1;
  1022. curl_session_count = 0;
  1023. #ifdef USE_CURL_MULTI
  1024. if (max_requests < 1)
  1025. max_requests = DEFAULT_MAX_REQUESTS;
  1026. #endif
  1027. if (getenv("GIT_CURL_FTP_NO_EPSV"))
  1028. curl_ftp_no_epsv = 1;
  1029. if (url) {
  1030. credential_from_url(&http_auth, url);
  1031. if (!ssl_cert_password_required &&
  1032. getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
  1033. starts_with(url, "https://"))
  1034. ssl_cert_password_required = 1;
  1035. }
  1036. #ifndef NO_CURL_EASY_DUPHANDLE
  1037. curl_default = get_curl_handle();
  1038. #endif
  1039. }
  1040. void http_cleanup(void)
  1041. {
  1042. struct active_request_slot *slot = active_queue_head;
  1043. while (slot != NULL) {
  1044. struct active_request_slot *next = slot->next;
  1045. if (slot->curl != NULL) {
  1046. xmulti_remove_handle(slot);
  1047. curl_easy_cleanup(slot->curl);
  1048. }
  1049. free(slot);
  1050. slot = next;
  1051. }
  1052. active_queue_head = NULL;
  1053. #ifndef NO_CURL_EASY_DUPHANDLE
  1054. curl_easy_cleanup(curl_default);
  1055. #endif
  1056. #ifdef USE_CURL_MULTI
  1057. curl_multi_cleanup(curlm);
  1058. #endif
  1059. curl_global_cleanup();
  1060. string_list_clear(&extra_http_headers, 0);
  1061. curl_slist_free_all(pragma_header);
  1062. pragma_header = NULL;
  1063. curl_slist_free_all(no_pragma_header);
  1064. no_pragma_header = NULL;
  1065. if (curl_http_proxy) {
  1066. free((void *)curl_http_proxy);
  1067. curl_http_proxy = NULL;
  1068. }
  1069. if (proxy_auth.password) {
  1070. memset(proxy_auth.password, 0, strlen(proxy_auth.password));
  1071. FREE_AND_NULL(proxy_auth.password);
  1072. }
  1073. free((void *)curl_proxyuserpwd);
  1074. curl_proxyuserpwd = NULL;
  1075. free((void *)http_proxy_authmethod);
  1076. http_proxy_authmethod = NULL;
  1077. if (cert_auth.password != NULL) {
  1078. memset(cert_auth.password, 0, strlen(cert_auth.password));
  1079. FREE_AND_NULL(cert_auth.password);
  1080. }
  1081. ssl_cert_password_required = 0;
  1082. FREE_AND_NULL(cached_accept_language);
  1083. }
  1084. struct active_request_slot *get_active_slot(void)
  1085. {
  1086. struct active_request_slot *slot = active_queue_head;
  1087. struct active_request_slot *newslot;
  1088. #ifdef USE_CURL_MULTI
  1089. int num_transfers;
  1090. /* Wait for a slot to open up if the queue is full */
  1091. while (active_requests >= max_requests) {
  1092. curl_multi_perform(curlm, &num_transfers);
  1093. if (num_transfers < active_requests)
  1094. process_curl_messages();
  1095. }
  1096. #endif
  1097. while (slot != NULL && slot->in_use)
  1098. slot = slot->next;
  1099. if (slot == NULL) {
  1100. newslot = xmalloc(sizeof(*newslot));
  1101. newslot->curl = NULL;
  1102. newslot->in_use = 0;
  1103. newslot->next = NULL;
  1104. slot = active_queue_head;
  1105. if (slot == NULL) {
  1106. active_queue_head = newslot;
  1107. } else {
  1108. while (slot->next != NULL)
  1109. slot = slot->next;
  1110. slot->next = newslot;
  1111. }
  1112. slot = newslot;
  1113. }
  1114. if (slot->curl == NULL) {
  1115. #ifdef NO_CURL_EASY_DUPHANDLE
  1116. slot->curl = get_curl_handle();
  1117. #else
  1118. slot->curl = curl_easy_duphandle(curl_default);
  1119. #endif
  1120. curl_session_count++;
  1121. }
  1122. active_requests++;
  1123. slot->in_use = 1;
  1124. slot->results = NULL;
  1125. slot->finished = NULL;
  1126. slot->callback_data = NULL;
  1127. slot->callback_func = NULL;
  1128. curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
  1129. if (curl_save_cookies)
  1130. curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
  1131. curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
  1132. curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
  1133. curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
  1134. curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
  1135. curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
  1136. curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
  1137. curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
  1138. curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
  1139. curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
  1140. curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
  1141. /*
  1142. * Default following to off unless "ALWAYS" is configured; this gives
  1143. * callers a sane starting point, and they can tweak for individual
  1144. * HTTP_FOLLOW_* cases themselves.
  1145. */
  1146. if (http_follow_config == HTTP_FOLLOW_ALWAYS)
  1147. curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
  1148. else
  1149. curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
  1150. #if LIBCURL_VERSION_NUM >= 0x070a08
  1151. curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
  1152. #endif
  1153. #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
  1154. curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
  1155. #endif
  1156. if (http_auth.password || curl_empty_auth_enabled())
  1157. init_curl_http_auth(slot->curl);
  1158. return slot;
  1159. }
  1160. int start_active_slot(struct active_request_slot *slot)
  1161. {
  1162. #ifdef USE_CURL_MULTI
  1163. CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
  1164. int num_transfers;
  1165. if (curlm_result != CURLM_OK &&
  1166. curlm_result != CURLM_CALL_MULTI_PERFORM) {
  1167. warning("curl_multi_add_handle failed: %s",
  1168. curl_multi_strerror(curlm_result));
  1169. active_requests--;
  1170. slot->in_use = 0;
  1171. return 0;
  1172. }
  1173. /*
  1174. * We know there must be something to do, since we just added
  1175. * something.
  1176. */
  1177. curl_multi_perform(curlm, &num_transfers);
  1178. #endif
  1179. return 1;
  1180. }
  1181. #ifdef USE_CURL_MULTI
  1182. struct fill_chain {
  1183. void *data;
  1184. int (*fill)(void *);
  1185. struct fill_chain *next;
  1186. };
  1187. static struct fill_chain *fill_cfg;
  1188. void add_fill_function(void *data, int (*fill)(void *))
  1189. {
  1190. struct fill_chain *new_fill = xmalloc(sizeof(*new_fill));
  1191. struct fill_chain **linkp = &fill_cfg;
  1192. new_fill->data = data;
  1193. new_fill->fill = fill;
  1194. new_fill->next = NULL;
  1195. while (*linkp)
  1196. linkp = &(*linkp)->next;
  1197. *linkp = new_fill;
  1198. }
  1199. void fill_active_slots(void)
  1200. {
  1201. struct active_request_slot *slot = active_queue_head;
  1202. while (active_requests < max_requests) {
  1203. struct fill_chain *fill;
  1204. for (fill = fill_cfg; fill; fill = fill->next)
  1205. if (fill->fill(fill->data))
  1206. break;
  1207. if (!fill)
  1208. break;
  1209. }
  1210. while (slot != NULL) {
  1211. if (!slot->in_use && slot->curl != NULL
  1212. && curl_session_count > min_curl_sessions) {
  1213. curl_easy_cleanup(slot->curl);
  1214. slot->curl = NULL;
  1215. curl_session_count--;
  1216. }
  1217. slot = slot->next;
  1218. }
  1219. }
  1220. void step_active_slots(void)
  1221. {
  1222. int num_transfers;
  1223. CURLMcode curlm_result;
  1224. do {
  1225. curlm_result = curl_multi_perform(curlm, &num_transfers);
  1226. } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
  1227. if (num_transfers < active_requests) {
  1228. process_curl_messages();
  1229. fill_active_slots();
  1230. }
  1231. }
  1232. #endif
  1233. void run_active_slot(struct active_request_slot *slot)
  1234. {
  1235. #ifdef USE_CURL_MULTI
  1236. fd_set readfds;
  1237. fd_set writefds;
  1238. fd_set excfds;
  1239. int max_fd;
  1240. struct timeval select_timeout;
  1241. int finished = 0;
  1242. slot->finished = &finished;
  1243. while (!finished) {
  1244. step_active_slots();
  1245. if (slot->in_use) {
  1246. #if LIBCURL_VERSION_NUM >= 0x070f04
  1247. long curl_timeout;
  1248. curl_multi_timeout(curlm, &curl_timeout);
  1249. if (curl_timeout == 0) {
  1250. continue;
  1251. } else if (curl_timeout == -1) {
  1252. select_timeout.tv_sec = 0;
  1253. select_timeout.tv_usec = 50000;
  1254. } else {
  1255. select_timeout.tv_sec = curl_timeout / 1000;
  1256. select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
  1257. }
  1258. #else
  1259. select_timeout.tv_sec = 0;
  1260. select_timeout.tv_usec = 50000;
  1261. #endif
  1262. max_fd = -1;
  1263. FD_ZERO(&readfds);
  1264. FD_ZERO(&writefds);
  1265. FD_ZERO(&excfds);
  1266. curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
  1267. /*
  1268. * It can happen that curl_multi_timeout returns a pathologically
  1269. * long timeout when curl_multi_fdset returns no file descriptors
  1270. * to read. See commit message for more details.
  1271. */
  1272. if (max_fd < 0 &&
  1273. (select_timeout.tv_sec > 0 ||
  1274. select_timeout.tv_usec > 50000)) {
  1275. select_timeout.tv_sec = 0;
  1276. select_timeout.tv_usec = 50000;
  1277. }
  1278. select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
  1279. }
  1280. }
  1281. #else
  1282. while (slot->in_use) {
  1283. slot->curl_result = curl_easy_perform(slot->curl);
  1284. finish_active_slot(slot);
  1285. }
  1286. #endif
  1287. }
  1288. static void release_active_slot(struct active_request_slot *slot)
  1289. {
  1290. closedown_active_slot(slot);
  1291. if (slot->curl) {
  1292. xmulti_remove_handle(slot);
  1293. if (curl_session_count > min_curl_sessions) {
  1294. curl_easy_cleanup(slot->curl);
  1295. slot->curl = NULL;
  1296. curl_session_count--;
  1297. }
  1298. }
  1299. #ifdef USE_CURL_MULTI
  1300. fill_active_slots();
  1301. #endif
  1302. }
  1303. void finish_all_active_slots(void)
  1304. {
  1305. struct active_request_slot *slot = active_queue_head;
  1306. while (slot != NULL)
  1307. if (slot->in_use) {
  1308. run_active_slot(slot);
  1309. slot = active_queue_head;
  1310. } else {
  1311. slot = slot->next;
  1312. }
  1313. }
  1314. /* Helpers for modifying and creating URLs */
  1315. static inline int needs_quote(int ch)
  1316. {
  1317. if (((ch >= 'A') && (ch <= 'Z'))
  1318. || ((ch >= 'a') && (ch <= 'z'))
  1319. || ((ch >= '0') && (ch <= '9'))
  1320. || (ch == '/')
  1321. || (ch == '-')
  1322. || (ch == '.'))
  1323. return 0;
  1324. return 1;
  1325. }
  1326. static char *quote_ref_url(const char *base, const char *ref)
  1327. {
  1328. struct strbuf buf = STRBUF_INIT;
  1329. const char *cp;
  1330. int ch;
  1331. end_url_with_slash(&buf, base);
  1332. for (cp = ref; (ch = *cp) != 0; cp++)
  1333. if (needs_quote(ch))
  1334. strbuf_addf(&buf, "%%%02x", ch);
  1335. else
  1336. strbuf_addch(&buf, *cp);
  1337. return strbuf_detach(&buf, NULL);
  1338. }
  1339. void append_remote_object_url(struct strbuf *buf, const char *url,
  1340. const char *hex,
  1341. int only_two_digit_prefix)
  1342. {
  1343. end_url_with_slash(buf, url);
  1344. strbuf_addf(buf, "objects/%.*s/", 2, hex);
  1345. if (!only_two_digit_prefix)
  1346. strbuf_addstr(buf, hex + 2);
  1347. }
  1348. char *get_remote_object_url(const char *url, const char *hex,
  1349. int only_two_digit_prefix)
  1350. {
  1351. struct strbuf buf = STRBUF_INIT;
  1352. append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
  1353. return strbuf_detach(&buf, NULL);
  1354. }
  1355. void normalize_curl_result(CURLcode *result, long http_code,
  1356. char *errorstr, size_t errorlen)
  1357. {
  1358. /*
  1359. * If we see a failing http code with CURLE_OK, we have turned off
  1360. * FAILONERROR (to keep the server's custom error response), and should
  1361. * translate the code into failure here.
  1362. *
  1363. * Likewise, if we see a redirect (30x code), that means we turned off
  1364. * redirect-following, and we should treat the result as an error.
  1365. */
  1366. if (*result == CURLE_OK && http_code >= 300) {
  1367. *result = CURLE_HTTP_RETURNED_ERROR;
  1368. /*
  1369. * Normally curl will already have put the "reason phrase"
  1370. * from the server into curl_errorstr; unfortunately without
  1371. * FAILONERROR it is lost, so we can give only the numeric
  1372. * status code.
  1373. */
  1374. xsnprintf(errorstr, errorlen,
  1375. "The requested URL returned error: %ld",
  1376. http_code);
  1377. }
  1378. }
  1379. static int handle_curl_result(struct slot_results *results)
  1380. {
  1381. normalize_curl_result(&results->curl_result, results->http_code,
  1382. curl_errorstr, sizeof(curl_errorstr));
  1383. if (results->curl_result == CURLE_OK) {
  1384. credential_approve(&http_auth);
  1385. if (proxy_auth.password)
  1386. credential_approve(&proxy_auth);
  1387. return HTTP_OK;
  1388. } else if (missing_target(results))
  1389. return HTTP_MISSING_TARGET;
  1390. else if (results->http_code == 401) {
  1391. if (http_auth.username && http_auth.password) {
  1392. credential_reject(&http_auth);
  1393. return HTTP_NOAUTH;
  1394. } else {
  1395. #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
  1396. http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
  1397. if (results->auth_avail) {
  1398. http_auth_methods &= results->auth_avail;
  1399. http_auth_methods_restricted = 1;
  1400. }
  1401. #endif
  1402. return HTTP_REAUTH;
  1403. }
  1404. } else {
  1405. if (results->http_connectcode == 407)
  1406. credential_reject(&proxy_auth);
  1407. #if LIBCURL_VERSION_NUM >= 0x070c00
  1408. if (!curl_errorstr[0])
  1409. strlcpy(curl_errorstr,
  1410. curl_easy_strerror(results->curl_result),
  1411. sizeof(curl_errorstr));
  1412. #endif
  1413. return HTTP_ERROR;
  1414. }
  1415. }
  1416. int run_one_slot(struct active_request_slot *slot,
  1417. struct slot_results *results)
  1418. {
  1419. slot->results = results;
  1420. if (!start_active_slot(slot)) {
  1421. xsnprintf(curl_errorstr, sizeof(curl_errorstr),
  1422. "failed to start HTTP request");
  1423. return HTTP_START_FAILED;
  1424. }
  1425. run_active_slot(slot);
  1426. return handle_curl_result(results);
  1427. }
  1428. struct curl_slist *http_copy_default_headers(void)
  1429. {
  1430. struct curl_slist *headers = NULL;
  1431. const struct string_list_item *item;
  1432. for_each_string_list_item(item, &extra_http_headers)
  1433. headers = curl_slist_append(headers, item->string);
  1434. return headers;
  1435. }
  1436. static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
  1437. {
  1438. char *ptr;
  1439. CURLcode ret;
  1440. strbuf_reset(buf);
  1441. ret = curl_easy_getinfo(curl, info, &ptr);
  1442. if (!ret && ptr)
  1443. strbuf_addstr(buf, ptr);
  1444. return ret;
  1445. }
  1446. /*
  1447. * Check for and extract a content-type parameter. "raw"
  1448. * should be positioned at the start of the potential
  1449. * parameter, with any whitespace already removed.
  1450. *
  1451. * "name" is the name of the parameter. The value is appended
  1452. * to "out".
  1453. */
  1454. static int extract_param(const char *raw, const char *name,
  1455. struct strbuf *out)
  1456. {
  1457. size_t len = strlen(name);
  1458. if (strncasecmp(raw, name, len))
  1459. return -1;
  1460. raw += len;
  1461. if (*raw != '=')
  1462. return -1;
  1463. raw++;
  1464. while (*raw && !isspace(*raw) && *raw != ';')
  1465. strbuf_addch(out, *raw++);
  1466. return 0;
  1467. }
  1468. /*
  1469. * Extract a normalized version of the content type, with any
  1470. * spaces suppressed, all letters lowercased, and no trailing ";"
  1471. * or parameters.
  1472. *
  1473. * Note that we will silently remove even invalid whitespace. For
  1474. * example, "text / plain" is specifically forbidden by RFC 2616,
  1475. * but "text/plain" is the only reasonable output, and this keeps
  1476. * our code simple.
  1477. *
  1478. * If the "charset" argument is not NULL, store the value of any
  1479. * charset parameter there.
  1480. *
  1481. * Example:
  1482. * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
  1483. * "text / plain" -> "text/plain"
  1484. */
  1485. static void extract_content_type(struct strbuf *raw, struct strbuf *type,
  1486. struct strbuf *charset)
  1487. {
  1488. const char *p;
  1489. strbuf_reset(type);
  1490. strbuf_grow(type, raw->len);
  1491. for (p = raw->buf; *p; p++) {
  1492. if (isspace(*p))
  1493. continue;
  1494. if (*p == ';') {
  1495. p++;
  1496. break;
  1497. }
  1498. strbuf_addch(type, tolower(*p));
  1499. }
  1500. if (!charset)
  1501. return;
  1502. strbuf_reset(charset);
  1503. while (*p) {
  1504. while (isspace(*p) || *p == ';')
  1505. p++;
  1506. if (!extract_param(p, "charset", charset))
  1507. return;
  1508. while (*p && !isspace(*p))
  1509. p++;
  1510. }
  1511. if (!charset->len && starts_with(type->buf, "text/"))
  1512. strbuf_addstr(charset, "ISO-8859-1");
  1513. }
  1514. static void write_accept_language(struct strbuf *buf)
  1515. {
  1516. /*
  1517. * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
  1518. * that, q-value will be smaller than 0.001, the minimum q-value the
  1519. * HTTP specification allows. See
  1520. * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
  1521. */
  1522. const int MAX_DECIMAL_PLACES = 3;
  1523. const int MAX_LANGUAGE_TAGS = 1000;
  1524. const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
  1525. char **language_tags = NULL;
  1526. int num_langs = 0;
  1527. const char *s = get_preferred_languages();
  1528. int i;
  1529. struct strbuf tag = STRBUF_INIT;
  1530. /* Don't add Accept-Language header if no language is preferred. */
  1531. if (!s)
  1532. return;
  1533. /*
  1534. * Split the colon-separated string of preferred languages into
  1535. * language_tags array.
  1536. */
  1537. do {
  1538. /* collect language tag */
  1539. for (; *s && (isalnum(*s) || *s == '_'); s++)
  1540. strbuf_addch(&tag, *s == '_' ? '-' : *s);
  1541. /* skip .codeset, @modifier and any other unnecessary parts */
  1542. while (*s && *s != ':')
  1543. s++;
  1544. if (tag.len) {
  1545. num_langs++;
  1546. REALLOC_ARRAY(language_tags, num_langs);
  1547. language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
  1548. if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
  1549. break;
  1550. }
  1551. } while (*s++);
  1552. /* write Accept-Language header into buf */
  1553. if (num_langs) {
  1554. int last_buf_len = 0;
  1555. int max_q;
  1556. int decimal_places;
  1557. char q_format[32];
  1558. /* add '*' */
  1559. REALLOC_ARRAY(language_tags, num_langs + 1);
  1560. language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
  1561. /* compute decimal_places */
  1562. for (max_q = 1, decimal_places = 0;
  1563. max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
  1564. decimal_places++, max_q *= 10)
  1565. ;
  1566. xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
  1567. strbuf_addstr(buf, "Accept-Language: ");
  1568. for (i = 0; i < num_langs; i++) {
  1569. if (i > 0)
  1570. strbuf_addstr(buf, ", ");
  1571. strbuf_addstr(buf, language_tags[i]);
  1572. if (i > 0)
  1573. strbuf_addf(buf, q_format, max_q - i);
  1574. if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
  1575. strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
  1576. break;
  1577. }
  1578. last_buf_len = buf->len;
  1579. }
  1580. }
  1581. /* free language tags -- last one is a static '*' */
  1582. for (i = 0; i < num_langs - 1; i++)
  1583. free(language_tags[i]);
  1584. free(language_tags);
  1585. }
  1586. /*
  1587. * Get an Accept-Language header which indicates user's preferred languages.
  1588. *
  1589. * Examples:
  1590. * LANGUAGE= -> ""
  1591. * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
  1592. * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
  1593. * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
  1594. * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
  1595. * LANGUAGE= LANG=C -> ""
  1596. */
  1597. static const char *get_accept_language(void)
  1598. {
  1599. if (!cached_accept_language) {
  1600. struct strbuf buf = STRBUF_INIT;
  1601. write_accept_language(&buf);
  1602. if (buf.len > 0)
  1603. cached_accept_language = strbuf_detach(&buf, NULL);
  1604. }
  1605. return cached_accept_language;
  1606. }
  1607. static void http_opt_request_remainder(CURL *curl, off_t pos)
  1608. {
  1609. char buf[128];
  1610. xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
  1611. curl_easy_setopt(curl, CURLOPT_RANGE, buf);
  1612. }
  1613. /* http_request() targets */
  1614. #define HTTP_REQUEST_STRBUF 0
  1615. #define HTTP_REQUEST_FILE 1
  1616. static int http_request(const char *url,
  1617. void *result, int target,
  1618. const struct http_get_options *options)
  1619. {
  1620. struct active_request_slot *slot;
  1621. struct slot_results results;
  1622. struct curl_slist *headers = http_copy_default_headers();
  1623. struct strbuf buf = STRBUF_INIT;
  1624. const char *accept_language;
  1625. int ret;
  1626. slot = get_active_slot();
  1627. curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
  1628. if (result == NULL) {
  1629. curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
  1630. } else {
  1631. curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
  1632. curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
  1633. if (target == HTTP_REQUEST_FILE) {
  1634. off_t posn = ftello(result);
  1635. curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
  1636. fwrite);
  1637. if (posn > 0)
  1638. http_opt_request_remainder(slot->curl, posn);
  1639. } else
  1640. curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
  1641. fwrite_buffer);
  1642. }
  1643. accept_language = get_accept_language();
  1644. if (accept_language)
  1645. headers = curl_slist_append(headers, accept_language);
  1646. strbuf_addstr(&buf, "Pragma:");
  1647. if (options && options->no_cache)
  1648. strbuf_addstr(&buf, " no-cache");
  1649. if (options && options->initial_request &&
  1650. http_follow_config == HTTP_FOLLOW_INITIAL)
  1651. curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
  1652. headers = curl_slist_append(headers, buf.buf);
  1653. /* Add additional headers here */
  1654. if (options && options->extra_headers) {
  1655. const struct string_list_item *item;
  1656. for_each_string_list_item(item, options->extra_headers) {
  1657. headers = curl_slist_append(headers, item->string);
  1658. }
  1659. }
  1660. curl_easy_setopt(slot->curl, CURLOPT_URL, url);
  1661. curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
  1662. curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
  1663. curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
  1664. ret = run_one_slot(slot, &results);
  1665. if (options && options->content_type) {
  1666. struct strbuf raw = STRBUF_INIT;
  1667. curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
  1668. extract_content_type(&raw, options->content_type,
  1669. options->charset);
  1670. strbuf_release(&raw);
  1671. }
  1672. if (options && options->effective_url)
  1673. curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
  1674. options->effective_url);
  1675. curl_slist_free_all(headers);
  1676. strbuf_release(&buf);
  1677. return ret;
  1678. }
  1679. /*
  1680. * Update the "base" url to a more appropriate value, as deduced by
  1681. * redirects seen when requesting a URL starting with "url".
  1682. *
  1683. * The "asked" parameter is a URL that we asked curl to access, and must begin
  1684. * with "base".
  1685. *
  1686. * The "got" parameter is the URL that curl reported to us as where we ended
  1687. * up.
  1688. *
  1689. * Returns 1 if we updated the base url, 0 otherwise.
  1690. *
  1691. * Our basic strategy is to compare "base" and "asked" to find the bits
  1692. * specific to our request. We then strip those bits off of "got" to yield the
  1693. * new base. So for example, if our base is "http://example.com/foo.git",
  1694. * and we ask for "http://example.com/foo.git/info/refs", we might end up
  1695. * with "https://other.example.com/foo.git/info/refs". We would want the
  1696. * new URL to become "https://other.example.com/foo.git".
  1697. *
  1698. * Note that this assumes a sane redirect scheme. It's entirely possible
  1699. * in the example above to end up at a URL that does not even end in
  1700. * "info/refs". In such a case we die. There's not much we can do, such a
  1701. * scheme is unlikely to represent a real git repository, and failing to
  1702. * rewrite the base opens options for malicious redirects to do funny things.
  1703. */
  1704. static int update_url_from_redirect(struct strbuf *base,
  1705. const char *asked,
  1706. const struct strbuf *got)
  1707. {
  1708. const char *tail;
  1709. size_t new_len;
  1710. if (!strcmp(asked, got->buf))
  1711. return 0;
  1712. if (!skip_prefix(asked, base->buf, &tail))
  1713. BUG("update_url_from_redirect: %s is not a superset of %s",
  1714. asked, base->buf);
  1715. new_len = got->len;
  1716. if (!strip_suffix_mem(got->buf, &new_len, tail))
  1717. die(_("unable to update url base from redirection:\n"
  1718. " asked for: %s\n"
  1719. " redirect: %s"),
  1720. asked, got->buf);
  1721. strbuf_reset(base);
  1722. strbuf_add(base, got->buf, new_len);
  1723. return 1;
  1724. }
  1725. static int http_request_reauth(const char *url,
  1726. void *result, int target,
  1727. struct http_get_options *options)
  1728. {
  1729. int ret = http_request(url, result, target, options);
  1730. if (ret != HTTP_OK && ret != HTTP_REAUTH)
  1731. return ret;
  1732. if (options && options->effective_url && options->base_url) {
  1733. if (update_url_from_redirect(options->base_url,
  1734. url, options->effective_url)) {
  1735. credential_from_url(&http_auth, options->base_url->buf);
  1736. url = options->effective_url->buf;
  1737. }
  1738. }
  1739. if (ret != HTTP_REAUTH)
  1740. return ret;
  1741. /*
  1742. * The previous request may have put cruft into our output stream; we
  1743. * should clear it out before making our next request.
  1744. */
  1745. switch (target) {
  1746. case HTTP_REQUEST_STRBUF:
  1747. strbuf_reset(result);
  1748. break;
  1749. case HTTP_REQUEST_FILE:
  1750. if (fflush(result)) {
  1751. error_errno("unable to flush a file");
  1752. return HTTP_START_FAILED;
  1753. }
  1754. rewind(result);
  1755. if (ftruncate(fileno(result), 0) < 0) {
  1756. error_errno("unable to truncate a file");
  1757. return HTTP_START_FAILED;
  1758. }
  1759. break;
  1760. default:
  1761. BUG("Unknown http_request target");
  1762. }
  1763. credential_fill(&http_auth);
  1764. return http_request(url, result, target, options);
  1765. }
  1766. int http_get_strbuf(const char *url,
  1767. struct strbuf *result,
  1768. struct http_get_options *options)
  1769. {
  1770. return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
  1771. }
  1772. /*
  1773. * Downloads a URL and stores the result in the given file.
  1774. *
  1775. * If a previous interrupted download is detected (i.e. a previous temporary
  1776. * file is still around) the download is resumed.
  1777. */
  1778. static int http_get_file(const char *url, const char *filename,
  1779. struct http_get_options *options)
  1780. {
  1781. int ret;
  1782. struct strbuf tmpfile = STRBUF_INIT;
  1783. FILE *result;
  1784. strbuf_addf(&tmpfile, "%s.temp", filename);
  1785. result = fopen(tmpfile.buf, "a");
  1786. if (!result) {
  1787. error("Unable to open local file %s", tmpfile.buf);
  1788. ret = HTTP_ERROR;
  1789. goto cleanup;
  1790. }
  1791. ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
  1792. fclose(result);
  1793. if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
  1794. ret = HTTP_ERROR;
  1795. cleanup:
  1796. strbuf_release(&tmpfile);
  1797. return ret;
  1798. }
  1799. int http_fetch_ref(const char *base, struct ref *ref)
  1800. {
  1801. struct http_get_options options = {0};
  1802. char *url;
  1803. struct strbuf buffer = STRBUF_INIT;
  1804. int ret = -1;
  1805. options.no_cache = 1;
  1806. url = quote_ref_url(base, ref->name);
  1807. if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
  1808. strbuf_rtrim(&buffer);
  1809. if (buffer.len == the_hash_algo->hexsz)
  1810. ret = get_oid_hex(buffer.buf, &ref->old_oid);
  1811. else if (starts_with(buffer.buf, "ref: ")) {
  1812. ref->symref = xstrdup(buffer.buf + 5);
  1813. ret = 0;
  1814. }
  1815. }
  1816. strbuf_release(&buffer);
  1817. free(url);
  1818. return ret;
  1819. }
  1820. /* Helpers for fetching packs */
  1821. static char *fetch_pack_index(unsigned char *hash, const char *base_url)
  1822. {
  1823. char *url, *tmp;
  1824. struct strbuf buf = STRBUF_INIT;
  1825. if (http_is_verbose)
  1826. fprintf(stderr, "Getting index for pack %s\n", hash_to_hex(hash));
  1827. end_url_with_slash(&buf, base_url);
  1828. strbuf_addf(&buf, "objects/pack/pack-%s.idx", hash_to_hex(hash));
  1829. url = strbuf_detach(&buf, NULL);
  1830. strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(hash));
  1831. tmp = strbuf_detach(&buf, NULL);
  1832. if (http_get_file(url, tmp, NULL) != HTTP_OK) {
  1833. error("Unable to get pack index %s", url);
  1834. FREE_AND_NULL(tmp);
  1835. }
  1836. free(url);
  1837. return tmp;
  1838. }
  1839. static int fetch_and_setup_pack_index(struct packed_git **packs_head,
  1840. unsigned char *sha1, const char *base_url)
  1841. {
  1842. struct packed_git *new_pack;
  1843. char *tmp_idx = NULL;
  1844. int ret;
  1845. if (has_pack_index(sha1)) {
  1846. new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
  1847. if (!new_pack)
  1848. return -1; /* parse_pack_index() already issued error message */
  1849. goto add_pack;
  1850. }
  1851. tmp_idx = fetch_pack_index(sha1, base_url);
  1852. if (!tmp_idx)
  1853. return -1;
  1854. new_pack = parse_pack_index(sha1, tmp_idx);
  1855. if (!new_pack) {
  1856. unlink(tmp_idx);
  1857. free(tmp_idx);
  1858. return -1; /* parse_pack_index() already issued error message */
  1859. }
  1860. ret = verify_pack_index(new_pack);
  1861. if (!ret) {
  1862. close_pack_index(new_pack);
  1863. ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
  1864. }
  1865. free(tmp_idx);
  1866. if (ret)
  1867. return -1;
  1868. add_pack:
  1869. new_pack->next = *packs_head;
  1870. *packs_head = new_pack;
  1871. return 0;
  1872. }
  1873. int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
  1874. {
  1875. struct http_get_options options = {0};
  1876. int ret = 0;
  1877. char *url;
  1878. const char *data;
  1879. struct strbuf buf = STRBUF_INIT;
  1880. struct object_id oid;
  1881. end_url_with_slash(&buf, base_url);
  1882. strbuf_addstr(&buf, "objects/info/packs");
  1883. url = strbuf_detach(&buf, NULL);
  1884. options.no_cache = 1;
  1885. ret = http_get_strbuf(url, &buf, &options);
  1886. if (ret != HTTP_OK)
  1887. goto cleanup;
  1888. data = buf.buf;
  1889. while (*data) {
  1890. if (skip_prefix(data, "P pack-", &data) &&
  1891. !parse_oid_hex(data, &oid, &data) &&
  1892. skip_prefix(data, ".pack", &data) &&
  1893. (*data == '\n' || *data == '\0')) {
  1894. fetch_and_setup_pack_index(packs_head, oid.hash, base_url);
  1895. } else {
  1896. data = strchrnul(data, '\n');
  1897. }
  1898. if (*data)
  1899. data++; /* skip past newline */
  1900. }
  1901. cleanup:
  1902. free(url);
  1903. return ret;
  1904. }
  1905. void release_http_pack_request(struct http_pack_request *preq)
  1906. {
  1907. if (preq->packfile != NULL) {
  1908. fclose(preq->packfile);
  1909. preq->packfile = NULL;
  1910. }
  1911. preq->slot = NULL;
  1912. strbuf_release(&preq->tmpfile);
  1913. free(preq->url);
  1914. free(preq);
  1915. }
  1916. int finish_http_pack_request(struct http_pack_request *preq)
  1917. {
  1918. struct packed_git **lst;
  1919. struct packed_git *p = preq->target;
  1920. char *tmp_idx;
  1921. size_t len;
  1922. struct child_process ip = CHILD_PROCESS_INIT;
  1923. close_pack_index(p);
  1924. fclose(preq->packfile);
  1925. preq->packfile = NULL;
  1926. lst = preq->lst;
  1927. while (*lst != p)
  1928. lst = &((*lst)->next);
  1929. *lst = (*lst)->next;
  1930. if (!strip_suffix(preq->tmpfile.buf, ".pack.temp", &len))
  1931. BUG("pack tmpfile does not end in .pack.temp?");
  1932. tmp_idx = xstrfmt("%.*s.idx.temp", (int)len, preq->tmpfile.buf);
  1933. argv_array_push(&ip.args, "index-pack");
  1934. argv_array_pushl(&ip.args, "-o", tmp_idx, NULL);
  1935. argv_array_push(&ip.args, preq->tmpfile.buf);
  1936. ip.git_cmd = 1;
  1937. ip.no_stdin = 1;
  1938. ip.no_stdout = 1;
  1939. if (run_command(&ip)) {
  1940. unlink(preq->tmpfile.buf);
  1941. unlink(tmp_idx);
  1942. free(tmp_idx);
  1943. return -1;
  1944. }
  1945. unlink(sha1_pack_index_name(p->hash));
  1946. if (finalize_object_file(preq->tmpfile.buf, sha1_pack_name(p->hash))
  1947. || finalize_object_file(tmp_idx, sha1_pack_index_name(p->hash))) {
  1948. free(tmp_idx);
  1949. return -1;
  1950. }
  1951. install_packed_git(the_repository, p);
  1952. free(tmp_idx);
  1953. return 0;
  1954. }
  1955. struct http_pack_request *new_http_pack_request(
  1956. struct packed_git *target, const char *base_url)
  1957. {
  1958. off_t prev_posn = 0;
  1959. struct strbuf buf = STRBUF_INIT;
  1960. struct http_pack_request *preq;
  1961. preq = xcalloc(1, sizeof(*preq));
  1962. strbuf_init(&preq->tmpfile, 0);
  1963. preq->target = target;
  1964. end_url_with_slash(&buf, base_url);
  1965. strbuf_addf(&buf, "objects/pack/pack-%s.pack",
  1966. hash_to_hex(target->hash));
  1967. preq->url = strbuf_detach(&buf, NULL);
  1968. strbuf_addf(&preq->tmpfile, "%s.temp", sha1_pack_name(target->hash));
  1969. preq->packfile = fopen(preq->tmpfile.buf, "a");
  1970. if (!preq->packfile) {
  1971. error("Unable to open local file %s for pack",
  1972. preq->tmpfile.buf);
  1973. goto abort;
  1974. }
  1975. preq->slot = get_active_slot();
  1976. curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
  1977. curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
  1978. curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
  1979. curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
  1980. no_pragma_header);
  1981. /*
  1982. * If there is data present from a previous transfer attempt,
  1983. * resume where it left off
  1984. */
  1985. prev_posn = ftello(preq->packfile);
  1986. if (prev_posn>0) {
  1987. if (http_is_verbose)
  1988. fprintf(stderr,
  1989. "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
  1990. hash_to_hex(target->hash),
  1991. (uintmax_t)prev_posn);
  1992. http_opt_request_remainder(preq->slot->curl, prev_posn);
  1993. }
  1994. return preq;
  1995. abort:
  1996. strbuf_release(&preq->tmpfile);
  1997. free(preq->url);
  1998. free(preq);
  1999. return NULL;
  2000. }
  2001. /* Helpers for fetching objects (loose) */
  2002. static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
  2003. void *data)
  2004. {
  2005. unsigned char expn[4096];
  2006. size_t size = eltsize * nmemb;
  2007. int posn = 0;
  2008. struct http_object_request *freq = data;
  2009. struct active_request_slot *slot = freq->slot;
  2010. if (slot) {
  2011. CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
  2012. &slot->http_code);
  2013. if (c != CURLE_OK)
  2014. BUG("curl_easy_getinfo for HTTP code failed: %s",
  2015. curl_easy_strerror(c));
  2016. if (slot->http_code >= 300)
  2017. return nmemb;
  2018. }
  2019. do {
  2020. ssize_t retval = xwrite(freq->localfile,
  2021. (char *) ptr + posn, size - posn);
  2022. if (retval < 0)
  2023. return posn / eltsize;
  2024. posn += retval;
  2025. } while (posn < size);
  2026. freq->stream.avail_in = size;
  2027. freq->stream.next_in = (void *)ptr;
  2028. do {
  2029. freq->stream.next_out = expn;
  2030. freq->stream.avail_out = sizeof(expn);
  2031. freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
  2032. the_hash_algo->update_fn(&freq->c, expn,
  2033. sizeof(expn) - freq->stream.avail_out);
  2034. } while (freq->stream.avail_in && freq->zret == Z_OK);
  2035. return nmemb;
  2036. }
  2037. struct http_object_request *new_http_object_request(const char *base_url,
  2038. const struct object_id *oid)
  2039. {
  2040. char *hex = oid_to_hex(oid);
  2041. struct strbuf filename = STRBUF_INIT;
  2042. struct strbuf prevfile = STRBUF_INIT;
  2043. int prevlocal;
  2044. char prev_buf[PREV_BUF_SIZE];
  2045. ssize_t prev_read = 0;
  2046. off_t prev_posn = 0;
  2047. struct http_object_request *freq;
  2048. freq = xcalloc(1, sizeof(*freq));
  2049. strbuf_init(&freq->tmpfile, 0);
  2050. oidcpy(&freq->oid, oid);
  2051. freq->localfile = -1;
  2052. loose_object_path(the_repository, &filename, oid);
  2053. strbuf_addf(&freq->tmpfile, "%s.temp", filename.buf);
  2054. strbuf_addf(&prevfile, "%s.prev", filename.buf);
  2055. unlink_or_warn(prevfile.buf);
  2056. rename(freq->tmpfile.buf, prevfile.buf);
  2057. unlink_or_warn(freq->tmpfile.buf);
  2058. strbuf_release(&filename);
  2059. if (freq->localfile != -1)
  2060. error("fd leakage in start: %d", freq->localfile);
  2061. freq->localfile = open(freq->tmpfile.buf,
  2062. O_WRONLY | O_CREAT | O_EXCL, 0666);
  2063. /*
  2064. * This could have failed due to the "lazy directory creation";
  2065. * try to mkdir the last path component.
  2066. */
  2067. if (freq->localfile < 0 && errno == ENOENT) {
  2068. char *dir = strrchr(freq->tmpfile.buf, '/');
  2069. if (dir) {
  2070. *dir = 0;
  2071. mkdir(freq->tmpfile.buf, 0777);
  2072. *dir = '/';
  2073. }
  2074. freq->localfile = open(freq->tmpfile.buf,
  2075. O_WRONLY | O_CREAT | O_EXCL, 0666);
  2076. }
  2077. if (freq->localfile < 0) {
  2078. error_errno("Couldn't create temporary file %s",
  2079. freq->tmpfile.buf);
  2080. goto abort;
  2081. }
  2082. git_inflate_init(&freq->stream);
  2083. the_hash_algo->init_fn(&freq->c);
  2084. freq->url = get_remote_object_url(base_url, hex, 0);
  2085. /*
  2086. * If a previous temp file is present, process what was already
  2087. * fetched.
  2088. */
  2089. prevlocal = open(prevfile.buf, O_RDONLY);
  2090. if (prevlocal != -1) {
  2091. do {
  2092. prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
  2093. if (prev_read>0) {
  2094. if (fwrite_sha1_file(prev_buf,
  2095. 1,
  2096. prev_read,
  2097. freq) == prev_read) {
  2098. prev_posn += prev_read;
  2099. } else {
  2100. prev_read = -1;
  2101. }
  2102. }
  2103. } while (prev_read > 0);
  2104. close(prevlocal);
  2105. }
  2106. unlink_or_warn(prevfile.buf);
  2107. strbuf_release(&prevfile);
  2108. /*
  2109. * Reset inflate/SHA1 if there was an error reading the previous temp
  2110. * file; also rewind to the beginning of the local file.
  2111. */
  2112. if (prev_read == -1) {
  2113. memset(&freq->stream, 0, sizeof(freq->stream));
  2114. git_inflate_init(&freq->stream);
  2115. the_hash_algo->init_fn(&freq->c);
  2116. if (prev_posn>0) {
  2117. prev_posn = 0;
  2118. lseek(freq->localfile, 0, SEEK_SET);
  2119. if (ftruncate(freq->localfile, 0) < 0) {
  2120. error_errno("Couldn't truncate temporary file %s",
  2121. freq->tmpfile.buf);
  2122. goto abort;
  2123. }
  2124. }
  2125. }
  2126. freq->slot = get_active_slot();
  2127. curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
  2128. curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
  2129. curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
  2130. curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
  2131. curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
  2132. curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
  2133. /*
  2134. * If we have successfully processed data from a previous fetch
  2135. * attempt, only fetch the data we don't already have.
  2136. */
  2137. if (prev_posn>0) {
  2138. if (http_is_verbose)
  2139. fprintf(stderr,
  2140. "Resuming fetch of object %s at byte %"PRIuMAX"\n",
  2141. hex, (uintmax_t)prev_posn);
  2142. http_opt_request_remainder(freq->slot->curl, prev_posn);
  2143. }
  2144. return freq;
  2145. abort:
  2146. strbuf_release(&prevfile);
  2147. free(freq->url);
  2148. free(freq);
  2149. return NULL;
  2150. }
  2151. void process_http_object_request(struct http_object_request *freq)
  2152. {
  2153. if (freq->slot == NULL)
  2154. return;
  2155. freq->curl_result = freq->slot->curl_result;
  2156. freq->http_code = freq->slot->http_code;
  2157. freq->slot = NULL;
  2158. }
  2159. int finish_http_object_request(struct http_object_request *freq)
  2160. {
  2161. struct stat st;
  2162. struct strbuf filename = STRBUF_INIT;
  2163. close(freq->localfile);
  2164. freq->localfile = -1;
  2165. process_http_object_request(freq);
  2166. if (freq->http_code == 416) {
  2167. warning("requested range invalid; we may already have all the data.");
  2168. } else if (freq->curl_result != CURLE_OK) {
  2169. if (stat(freq->tmpfile.buf, &st) == 0)
  2170. if (st.st_size == 0)
  2171. unlink_or_warn(freq->tmpfile.buf);
  2172. return -1;
  2173. }
  2174. git_inflate_end(&freq->stream);
  2175. the_hash_algo->final_fn(freq->real_oid.hash, &freq->c);
  2176. if (freq->zret != Z_STREAM_END) {
  2177. unlink_or_warn(freq->tmpfile.buf);
  2178. return -1;
  2179. }
  2180. if (!oideq(&freq->oid, &freq->real_oid)) {
  2181. unlink_or_warn(freq->tmpfile.buf);
  2182. return -1;
  2183. }
  2184. loose_object_path(the_repository, &filename, &freq->oid);
  2185. freq->rename = finalize_object_file(freq->tmpfile.buf, filename.buf);
  2186. strbuf_release(&filename);
  2187. return freq->rename;
  2188. }
  2189. void abort_http_object_request(struct http_object_request *freq)
  2190. {
  2191. unlink_or_warn(freq->tmpfile.buf);
  2192. release_http_object_request(freq);
  2193. }
  2194. void release_http_object_request(struct http_object_request *freq)
  2195. {
  2196. if (freq->localfile != -1) {
  2197. close(freq->localfile);
  2198. freq->localfile = -1;
  2199. }
  2200. FREE_AND_NULL(freq->url);
  2201. if (freq->slot != NULL) {
  2202. freq->slot->callback_func = NULL;
  2203. freq->slot->callback_data = NULL;
  2204. release_active_slot(freq->slot);
  2205. freq->slot = NULL;
  2206. }
  2207. strbuf_release(&freq->tmpfile);
  2208. }