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