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.

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