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