]> git.ipfire.org Git - thirdparty/git.git/blame - http.c
Merge branch 'ew/http-walker' into jk/http-walker-limit-redirect
[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
BB
585#else
586 if (transport_restrict_protocols())
587 warning("protocol restrictions not applied to curl redirects because\n"
588 "your curl version is too old (>= 7.19.4)");
589#endif
11979b98 590
7982d74e
MW
591 if (getenv("GIT_CURL_VERBOSE"))
592 curl_easy_setopt(result, CURLOPT_VERBOSE, 1);
593
b1d1058c 594 curl_easy_setopt(result, CURLOPT_USERAGENT,
745c7c8e 595 user_agent ? user_agent : git_user_agent());
20fc9bc5 596
3ea099d4
SK
597 if (curl_ftp_no_epsv)
598 curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
599
4bc444eb
MV
600#ifdef CURLOPT_USE_SSL
601 if (curl_ssl_try)
602 curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
603#endif
604
372370f1
KF
605 /*
606 * CURL also examines these variables as a fallback; but we need to query
607 * them here in order to decide whether to prompt for missing password (cf.
608 * init_curl_proxy_auth()).
609 *
610 * Unlike many other common environment variables, these are historically
611 * lowercase only. It appears that CURL did not know this and implemented
612 * only uppercase variants, which was later corrected to take both - with
613 * the exception of http_proxy, which is lowercase only also in CURL. As
614 * the lowercase versions are the historical quasi-standard, they take
615 * precedence here, as in CURL.
616 */
617 if (!curl_http_proxy) {
618 if (!strcmp(http_auth.protocol, "https")) {
619 var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
620 var_override(&curl_http_proxy, getenv("https_proxy"));
621 } else {
622 var_override(&curl_http_proxy, getenv("http_proxy"));
623 }
624 if (!curl_http_proxy) {
625 var_override(&curl_http_proxy, getenv("ALL_PROXY"));
626 var_override(&curl_http_proxy, getenv("all_proxy"));
627 }
628 }
629
dd613997 630 if (curl_http_proxy) {
9c5665aa 631 curl_easy_setopt(result, CURLOPT_PROXY, curl_http_proxy);
6d7afe07 632#if LIBCURL_VERSION_NUM >= 0x071800
87f8a0b2
JH
633 if (starts_with(curl_http_proxy, "socks5h"))
634 curl_easy_setopt(result,
635 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
636 else if (starts_with(curl_http_proxy, "socks5"))
6d7afe07
PT
637 curl_easy_setopt(result,
638 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
639 else if (starts_with(curl_http_proxy, "socks4a"))
640 curl_easy_setopt(result,
641 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
642 else if (starts_with(curl_http_proxy, "socks"))
643 curl_easy_setopt(result,
644 CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
645#endif
372370f1
KF
646 if (strstr(curl_http_proxy, "://"))
647 credential_from_url(&proxy_auth, curl_http_proxy);
648 else {
649 struct strbuf url = STRBUF_INIT;
650 strbuf_addf(&url, "http://%s", curl_http_proxy);
651 credential_from_url(&proxy_auth, url.buf);
652 strbuf_release(&url);
653 }
654
655 curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
d445fda4
JX
656#if LIBCURL_VERSION_NUM >= 0x071304
657 var_override(&curl_no_proxy, getenv("NO_PROXY"));
658 var_override(&curl_no_proxy, getenv("no_proxy"));
659 curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
660#endif
5841520b 661 }
ef976395 662 init_curl_proxy_auth(result);
9c5665aa 663
47ce1153 664 set_curl_keepalive(result);
a15d069a 665
11979b98
JH
666 return result;
667}
668
7059cd99
JH
669static void set_from_env(const char **var, const char *envname)
670{
671 const char *val = getenv(envname);
672 if (val)
673 *var = val;
674}
675
a4ddbc33 676void http_init(struct remote *remote, const char *url, int proactive_auth)
29508e1e
NH
677{
678 char *low_speed_limit;
679 char *low_speed_time;
6a56993b
KM
680 char *normalized_url;
681 struct urlmatch_config config = { STRING_LIST_INIT_DUP };
682
683 config.section = "http";
684 config.key = NULL;
685 config.collect_fn = http_options;
686 config.cascade_fn = git_default_config;
687 config.cb = NULL;
29508e1e 688
e9176745 689 http_is_verbose = 0;
6a56993b 690 normalized_url = url_normalize(url, &config.url);
e9176745 691
6a56993b
KM
692 git_config(urlmatch_config_entry, &config);
693 free(normalized_url);
7059cd99 694
faa3807c
BR
695 if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
696 die("curl_global_init failed");
29508e1e 697
a4ddbc33
JK
698 http_proactive_auth = proactive_auth;
699
9fc6440d
MH
700 if (remote && remote->http_proxy)
701 curl_http_proxy = xstrdup(remote->http_proxy);
702
ef976395
KF
703 if (remote)
704 var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
705
8cb01e2f
JS
706 pragma_header = curl_slist_append(http_copy_default_headers(),
707 "Pragma: no-cache");
708 no_pragma_header = curl_slist_append(http_copy_default_headers(),
709 "Pragma:");
29508e1e
NH
710
711#ifdef USE_CURL_MULTI
712 {
713 char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
714 if (http_max_requests != NULL)
715 max_requests = atoi(http_max_requests);
716 }
717
718 curlm = curl_multi_init();
8837eb47
JK
719 if (!curlm)
720 die("curl_multi_init failed");
29508e1e
NH
721#endif
722
723 if (getenv("GIT_SSL_NO_VERIFY"))
724 curl_ssl_verify = 0;
725
7059cd99 726 set_from_env(&ssl_cert, "GIT_SSL_CERT");
ef52aafa 727#if LIBCURL_VERSION_NUM >= 0x070903
7059cd99 728 set_from_env(&ssl_key, "GIT_SSL_KEY");
29508e1e
NH
729#endif
730#if LIBCURL_VERSION_NUM >= 0x070908
7059cd99 731 set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
29508e1e 732#endif
7059cd99 733 set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
29508e1e 734
b1d1058c
SO
735 set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
736
29508e1e
NH
737 low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
738 if (low_speed_limit != NULL)
739 curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
740 low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
741 if (low_speed_time != NULL)
742 curl_low_speed_time = strtol(low_speed_time, NULL, 10);
743
29508e1e
NH
744 if (curl_ssl_verify == -1)
745 curl_ssl_verify = 1;
746
ad75ebe5 747 curl_session_count = 0;
29508e1e
NH
748#ifdef USE_CURL_MULTI
749 if (max_requests < 1)
750 max_requests = DEFAULT_MAX_REQUESTS;
751#endif
752
3ea099d4
SK
753 if (getenv("GIT_CURL_FTP_NO_EPSV"))
754 curl_ftp_no_epsv = 1;
755
deba4937 756 if (url) {
148bb6a7 757 credential_from_url(&http_auth, url);
754ae192
ML
758 if (!ssl_cert_password_required &&
759 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
59556548 760 starts_with(url, "https://"))
30dd9163
ML
761 ssl_cert_password_required = 1;
762 }
c33976cb 763
29508e1e
NH
764#ifndef NO_CURL_EASY_DUPHANDLE
765 curl_default = get_curl_handle();
766#endif
767}
768
769void http_cleanup(void)
770{
771 struct active_request_slot *slot = active_queue_head;
29508e1e
NH
772
773 while (slot != NULL) {
3278cd0a 774 struct active_request_slot *next = slot->next;
f23d1f76 775 if (slot->curl != NULL) {
29508e1e 776#ifdef USE_CURL_MULTI
f23d1f76 777 curl_multi_remove_handle(curlm, slot->curl);
29508e1e 778#endif
29508e1e 779 curl_easy_cleanup(slot->curl);
f23d1f76 780 }
3278cd0a
SP
781 free(slot);
782 slot = next;
29508e1e 783 }
3278cd0a 784 active_queue_head = NULL;
29508e1e
NH
785
786#ifndef NO_CURL_EASY_DUPHANDLE
787 curl_easy_cleanup(curl_default);
788#endif
789
790#ifdef USE_CURL_MULTI
791 curl_multi_cleanup(curlm);
792#endif
793 curl_global_cleanup();
b3ca4e4e 794
8cb01e2f
JS
795 curl_slist_free_all(extra_http_headers);
796 extra_http_headers = NULL;
797
b3ca4e4e 798 curl_slist_free_all(pragma_header);
3278cd0a 799 pragma_header = NULL;
9fc6440d 800
e9176745
TRC
801 curl_slist_free_all(no_pragma_header);
802 no_pragma_header = NULL;
803
9fc6440d 804 if (curl_http_proxy) {
e4a80ecf 805 free((void *)curl_http_proxy);
9fc6440d
MH
806 curl_http_proxy = NULL;
807 }
30dd9163 808
372370f1
KF
809 if (proxy_auth.password) {
810 memset(proxy_auth.password, 0, strlen(proxy_auth.password));
811 free(proxy_auth.password);
812 proxy_auth.password = NULL;
813 }
814
815 free((void *)curl_proxyuserpwd);
816 curl_proxyuserpwd = NULL;
817
ef976395
KF
818 free((void *)http_proxy_authmethod);
819 http_proxy_authmethod = NULL;
820
148bb6a7
JK
821 if (cert_auth.password != NULL) {
822 memset(cert_auth.password, 0, strlen(cert_auth.password));
823 free(cert_auth.password);
824 cert_auth.password = NULL;
30dd9163
ML
825 }
826 ssl_cert_password_required = 0;
f18604bb
YE
827
828 free(cached_accept_language);
829 cached_accept_language = NULL;
29508e1e
NH
830}
831
29508e1e
NH
832struct active_request_slot *get_active_slot(void)
833{
834 struct active_request_slot *slot = active_queue_head;
835 struct active_request_slot *newslot;
836
837#ifdef USE_CURL_MULTI
838 int num_transfers;
839
840 /* Wait for a slot to open up if the queue is full */
841 while (active_requests >= max_requests) {
842 curl_multi_perform(curlm, &num_transfers);
4251ccbd 843 if (num_transfers < active_requests)
29508e1e 844 process_curl_messages();
29508e1e
NH
845 }
846#endif
847
4251ccbd 848 while (slot != NULL && slot->in_use)
29508e1e 849 slot = slot->next;
4251ccbd 850
29508e1e
NH
851 if (slot == NULL) {
852 newslot = xmalloc(sizeof(*newslot));
853 newslot->curl = NULL;
854 newslot->in_use = 0;
855 newslot->next = NULL;
856
857 slot = active_queue_head;
858 if (slot == NULL) {
859 active_queue_head = newslot;
860 } else {
4251ccbd 861 while (slot->next != NULL)
29508e1e 862 slot = slot->next;
29508e1e
NH
863 slot->next = newslot;
864 }
865 slot = newslot;
866 }
867
868 if (slot->curl == NULL) {
869#ifdef NO_CURL_EASY_DUPHANDLE
870 slot->curl = get_curl_handle();
871#else
872 slot->curl = curl_easy_duphandle(curl_default);
873#endif
ad75ebe5 874 curl_session_count++;
29508e1e
NH
875 }
876
877 active_requests++;
878 slot->in_use = 1;
c8568e13 879 slot->results = NULL;
baa7b67d 880 slot->finished = NULL;
29508e1e
NH
881 slot->callback_data = NULL;
882 slot->callback_func = NULL;
bcfb95dd 883 curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
912b2acf
DB
884 if (curl_save_cookies)
885 curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
29508e1e 886 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
29508e1e 887 curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
9094950d
NH
888 curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
889 curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
890 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1e41827d 891 curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
9094950d
NH
892 curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
893 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
b793acf1 894 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
835c4d36 895 curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
c915f11e 896
50d34137
JK
897 /*
898 * Default following to off unless "ALWAYS" is configured; this gives
899 * callers a sane starting point, and they can tweak for individual
900 * HTTP_FOLLOW_* cases themselves.
901 */
902 if (http_follow_config == HTTP_FOLLOW_ALWAYS)
903 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
904 else
905 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
906
c915f11e
EW
907#if LIBCURL_VERSION_NUM >= 0x070a08
908 curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
909#endif
4dbe6646 910#ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
911 curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
912#endif
121061f6 913 if (http_auth.password || curl_empty_auth)
dfa1725a 914 init_curl_http_auth(slot->curl);
29508e1e
NH
915
916 return slot;
917}
918
919int start_active_slot(struct active_request_slot *slot)
920{
921#ifdef USE_CURL_MULTI
922 CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
45c17412 923 int num_transfers;
29508e1e
NH
924
925 if (curlm_result != CURLM_OK &&
926 curlm_result != CURLM_CALL_MULTI_PERFORM) {
927 active_requests--;
928 slot->in_use = 0;
929 return 0;
930 }
45c17412
DB
931
932 /*
933 * We know there must be something to do, since we just added
934 * something.
935 */
936 curl_multi_perform(curlm, &num_transfers);
29508e1e
NH
937#endif
938 return 1;
939}
940
941#ifdef USE_CURL_MULTI
fc57b6aa
DB
942struct fill_chain {
943 void *data;
944 int (*fill)(void *);
945 struct fill_chain *next;
946};
947
4251ccbd 948static struct fill_chain *fill_cfg;
fc57b6aa
DB
949
950void add_fill_function(void *data, int (*fill)(void *))
951{
e8eec71d 952 struct fill_chain *new = xmalloc(sizeof(*new));
fc57b6aa
DB
953 struct fill_chain **linkp = &fill_cfg;
954 new->data = data;
955 new->fill = fill;
956 new->next = NULL;
957 while (*linkp)
958 linkp = &(*linkp)->next;
959 *linkp = new;
960}
961
45c17412
DB
962void fill_active_slots(void)
963{
964 struct active_request_slot *slot = active_queue_head;
965
fc57b6aa
DB
966 while (active_requests < max_requests) {
967 struct fill_chain *fill;
968 for (fill = fill_cfg; fill; fill = fill->next)
969 if (fill->fill(fill->data))
970 break;
971
972 if (!fill)
45c17412 973 break;
fc57b6aa 974 }
45c17412
DB
975
976 while (slot != NULL) {
ad75ebe5
TRC
977 if (!slot->in_use && slot->curl != NULL
978 && curl_session_count > min_curl_sessions) {
45c17412
DB
979 curl_easy_cleanup(slot->curl);
980 slot->curl = NULL;
ad75ebe5 981 curl_session_count--;
45c17412
DB
982 }
983 slot = slot->next;
984 }
985}
986
29508e1e
NH
987void step_active_slots(void)
988{
989 int num_transfers;
990 CURLMcode curlm_result;
991
992 do {
993 curlm_result = curl_multi_perform(curlm, &num_transfers);
994 } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
995 if (num_transfers < active_requests) {
996 process_curl_messages();
997 fill_active_slots();
998 }
999}
1000#endif
1001
1002void run_active_slot(struct active_request_slot *slot)
1003{
1004#ifdef USE_CURL_MULTI
29508e1e
NH
1005 fd_set readfds;
1006 fd_set writefds;
1007 fd_set excfds;
1008 int max_fd;
1009 struct timeval select_timeout;
baa7b67d 1010 int finished = 0;
29508e1e 1011
baa7b67d
NH
1012 slot->finished = &finished;
1013 while (!finished) {
29508e1e
NH
1014 step_active_slots();
1015
df26c471 1016 if (slot->in_use) {
eb56c821
MF
1017#if LIBCURL_VERSION_NUM >= 0x070f04
1018 long curl_timeout;
1019 curl_multi_timeout(curlm, &curl_timeout);
1020 if (curl_timeout == 0) {
1021 continue;
1022 } else if (curl_timeout == -1) {
1023 select_timeout.tv_sec = 0;
1024 select_timeout.tv_usec = 50000;
1025 } else {
1026 select_timeout.tv_sec = curl_timeout / 1000;
1027 select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1028 }
1029#else
1030 select_timeout.tv_sec = 0;
1031 select_timeout.tv_usec = 50000;
1032#endif
29508e1e 1033
6f9dd67f 1034 max_fd = -1;
29508e1e
NH
1035 FD_ZERO(&readfds);
1036 FD_ZERO(&writefds);
1037 FD_ZERO(&excfds);
6f9dd67f 1038 curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
eb56c821 1039
7202b81f
SZ
1040 /*
1041 * It can happen that curl_multi_timeout returns a pathologically
1042 * long timeout when curl_multi_fdset returns no file descriptors
1043 * to read. See commit message for more details.
1044 */
1045 if (max_fd < 0 &&
1046 (select_timeout.tv_sec > 0 ||
1047 select_timeout.tv_usec > 50000)) {
1048 select_timeout.tv_sec = 0;
1049 select_timeout.tv_usec = 50000;
1050 }
1051
6f9dd67f 1052 select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
29508e1e
NH
1053 }
1054 }
1055#else
1056 while (slot->in_use) {
1057 slot->curl_result = curl_easy_perform(slot->curl);
1058 finish_active_slot(slot);
1059 }
1060#endif
1061}
1062
83e41e2e 1063static void release_active_slot(struct active_request_slot *slot)
53f31389
MW
1064{
1065 closedown_active_slot(slot);
ad75ebe5 1066 if (slot->curl && curl_session_count > min_curl_sessions) {
b3ca4e4e 1067#ifdef USE_CURL_MULTI
53f31389 1068 curl_multi_remove_handle(curlm, slot->curl);
b3ca4e4e 1069#endif
53f31389
MW
1070 curl_easy_cleanup(slot->curl);
1071 slot->curl = NULL;
ad75ebe5 1072 curl_session_count--;
53f31389 1073 }
b3ca4e4e 1074#ifdef USE_CURL_MULTI
53f31389 1075 fill_active_slots();
b3ca4e4e 1076#endif
53f31389
MW
1077}
1078
29508e1e
NH
1079void finish_all_active_slots(void)
1080{
1081 struct active_request_slot *slot = active_queue_head;
1082
1083 while (slot != NULL)
1084 if (slot->in_use) {
1085 run_active_slot(slot);
1086 slot = active_queue_head;
1087 } else {
1088 slot = slot->next;
1089 }
1090}
d7e92806 1091
5ace994f 1092/* Helpers for modifying and creating URLs */
d7e92806
MH
1093static inline int needs_quote(int ch)
1094{
1095 if (((ch >= 'A') && (ch <= 'Z'))
1096 || ((ch >= 'a') && (ch <= 'z'))
1097 || ((ch >= '0') && (ch <= '9'))
1098 || (ch == '/')
1099 || (ch == '-')
1100 || (ch == '.'))
1101 return 0;
1102 return 1;
1103}
1104
d7e92806
MH
1105static char *quote_ref_url(const char *base, const char *ref)
1106{
113106e0 1107 struct strbuf buf = STRBUF_INIT;
d7e92806 1108 const char *cp;
113106e0 1109 int ch;
d7e92806 1110
5ace994f 1111 end_url_with_slash(&buf, base);
113106e0
TRC
1112
1113 for (cp = ref; (ch = *cp) != 0; cp++)
d7e92806 1114 if (needs_quote(ch))
113106e0 1115 strbuf_addf(&buf, "%%%02x", ch);
d7e92806 1116 else
113106e0 1117 strbuf_addch(&buf, *cp);
d7e92806 1118
113106e0 1119 return strbuf_detach(&buf, NULL);
d7e92806
MH
1120}
1121
5424bc55
TRC
1122void append_remote_object_url(struct strbuf *buf, const char *url,
1123 const char *hex,
1124 int only_two_digit_prefix)
1125{
800324c3
TRC
1126 end_url_with_slash(buf, url);
1127
1128 strbuf_addf(buf, "objects/%.*s/", 2, hex);
5424bc55 1129 if (!only_two_digit_prefix)
bc57b9c0 1130 strbuf_addstr(buf, hex + 2);
5424bc55
TRC
1131}
1132
1133char *get_remote_object_url(const char *url, const char *hex,
1134 int only_two_digit_prefix)
1135{
1136 struct strbuf buf = STRBUF_INIT;
1137 append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1138 return strbuf_detach(&buf, NULL);
1139}
1140
b90a3d7b 1141static int handle_curl_result(struct slot_results *results)
88097030 1142{
6d052d78
JK
1143 /*
1144 * If we see a failing http code with CURLE_OK, we have turned off
1145 * FAILONERROR (to keep the server's custom error response), and should
1146 * translate the code into failure here.
50d34137
JK
1147 *
1148 * Likewise, if we see a redirect (30x code), that means we turned off
1149 * redirect-following, and we should treat the result as an error.
6d052d78
JK
1150 */
1151 if (results->curl_result == CURLE_OK &&
50d34137 1152 results->http_code >= 300) {
6d052d78
JK
1153 results->curl_result = CURLE_HTTP_RETURNED_ERROR;
1154 /*
1155 * Normally curl will already have put the "reason phrase"
1156 * from the server into curl_errorstr; unfortunately without
1157 * FAILONERROR it is lost, so we can give only the numeric
1158 * status code.
1159 */
1160 snprintf(curl_errorstr, sizeof(curl_errorstr),
1161 "The requested URL returned error: %ld",
1162 results->http_code);
1163 }
1164
88097030
JK
1165 if (results->curl_result == CURLE_OK) {
1166 credential_approve(&http_auth);
372370f1
KF
1167 if (proxy_auth.password)
1168 credential_approve(&proxy_auth);
88097030
JK
1169 return HTTP_OK;
1170 } else if (missing_target(results))
1171 return HTTP_MISSING_TARGET;
1172 else if (results->http_code == 401) {
1173 if (http_auth.username && http_auth.password) {
1174 credential_reject(&http_auth);
1175 return HTTP_NOAUTH;
1176 } else {
4dbe6646 1177#ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1178 http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1179#endif
88097030
JK
1180 return HTTP_REAUTH;
1181 }
1182 } else {
372370f1
KF
1183 if (results->http_connectcode == 407)
1184 credential_reject(&proxy_auth);
3503e9ab 1185#if LIBCURL_VERSION_NUM >= 0x070c00
88097030
JK
1186 if (!curl_errorstr[0])
1187 strlcpy(curl_errorstr,
1188 curl_easy_strerror(results->curl_result),
1189 sizeof(curl_errorstr));
3503e9ab 1190#endif
88097030
JK
1191 return HTTP_ERROR;
1192 }
1193}
1194
beed336c
JK
1195int run_one_slot(struct active_request_slot *slot,
1196 struct slot_results *results)
1197{
1198 slot->results = results;
1199 if (!start_active_slot(slot)) {
1200 snprintf(curl_errorstr, sizeof(curl_errorstr),
1201 "failed to start HTTP request");
1202 return HTTP_START_FAILED;
1203 }
1204
1205 run_active_slot(slot);
1206 return handle_curl_result(results);
1207}
1208
8cb01e2f
JS
1209struct curl_slist *http_copy_default_headers(void)
1210{
1211 struct curl_slist *headers = NULL, *h;
1212
1213 for (h = extra_http_headers; h; h = h->next)
1214 headers = curl_slist_append(headers, h->data);
1215
1216 return headers;
1217}
1218
132b70a2
JK
1219static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1220{
1221 char *ptr;
1222 CURLcode ret;
1223
1224 strbuf_reset(buf);
1225 ret = curl_easy_getinfo(curl, info, &ptr);
1226 if (!ret && ptr)
1227 strbuf_addstr(buf, ptr);
1228 return ret;
1229}
1230
e3131626
JK
1231/*
1232 * Check for and extract a content-type parameter. "raw"
1233 * should be positioned at the start of the potential
1234 * parameter, with any whitespace already removed.
1235 *
1236 * "name" is the name of the parameter. The value is appended
1237 * to "out".
1238 */
1239static int extract_param(const char *raw, const char *name,
1240 struct strbuf *out)
1241{
1242 size_t len = strlen(name);
1243
1244 if (strncasecmp(raw, name, len))
1245 return -1;
1246 raw += len;
1247
1248 if (*raw != '=')
1249 return -1;
1250 raw++;
1251
f34a655d 1252 while (*raw && !isspace(*raw) && *raw != ';')
e3131626
JK
1253 strbuf_addch(out, *raw++);
1254 return 0;
1255}
1256
bf197fd7
JK
1257/*
1258 * Extract a normalized version of the content type, with any
1259 * spaces suppressed, all letters lowercased, and no trailing ";"
1260 * or parameters.
1261 *
1262 * Note that we will silently remove even invalid whitespace. For
1263 * example, "text / plain" is specifically forbidden by RFC 2616,
1264 * but "text/plain" is the only reasonable output, and this keeps
1265 * our code simple.
1266 *
e3131626
JK
1267 * If the "charset" argument is not NULL, store the value of any
1268 * charset parameter there.
1269 *
bf197fd7 1270 * Example:
e3131626 1271 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
bf197fd7
JK
1272 * "text / plain" -> "text/plain"
1273 */
e3131626
JK
1274static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1275 struct strbuf *charset)
bf197fd7
JK
1276{
1277 const char *p;
1278
1279 strbuf_reset(type);
1280 strbuf_grow(type, raw->len);
1281 for (p = raw->buf; *p; p++) {
1282 if (isspace(*p))
1283 continue;
e3131626
JK
1284 if (*p == ';') {
1285 p++;
bf197fd7 1286 break;
e3131626 1287 }
bf197fd7
JK
1288 strbuf_addch(type, tolower(*p));
1289 }
e3131626
JK
1290
1291 if (!charset)
1292 return;
1293
1294 strbuf_reset(charset);
1295 while (*p) {
f34a655d 1296 while (isspace(*p) || *p == ';')
e3131626
JK
1297 p++;
1298 if (!extract_param(p, "charset", charset))
1299 return;
1300 while (*p && !isspace(*p))
1301 p++;
1302 }
c553fd1c
JK
1303
1304 if (!charset->len && starts_with(type->buf, "text/"))
1305 strbuf_addstr(charset, "ISO-8859-1");
bf197fd7
JK
1306}
1307
f18604bb
YE
1308static void write_accept_language(struct strbuf *buf)
1309{
1310 /*
1311 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1312 * that, q-value will be smaller than 0.001, the minimum q-value the
1313 * HTTP specification allows. See
1314 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1315 */
1316 const int MAX_DECIMAL_PLACES = 3;
1317 const int MAX_LANGUAGE_TAGS = 1000;
1318 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1319 char **language_tags = NULL;
1320 int num_langs = 0;
1321 const char *s = get_preferred_languages();
1322 int i;
1323 struct strbuf tag = STRBUF_INIT;
1324
1325 /* Don't add Accept-Language header if no language is preferred. */
1326 if (!s)
1327 return;
1328
1329 /*
1330 * Split the colon-separated string of preferred languages into
1331 * language_tags array.
1332 */
1333 do {
1334 /* collect language tag */
1335 for (; *s && (isalnum(*s) || *s == '_'); s++)
1336 strbuf_addch(&tag, *s == '_' ? '-' : *s);
1337
1338 /* skip .codeset, @modifier and any other unnecessary parts */
1339 while (*s && *s != ':')
1340 s++;
1341
1342 if (tag.len) {
1343 num_langs++;
1344 REALLOC_ARRAY(language_tags, num_langs);
1345 language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1346 if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1347 break;
1348 }
1349 } while (*s++);
1350
1351 /* write Accept-Language header into buf */
1352 if (num_langs) {
1353 int last_buf_len = 0;
1354 int max_q;
1355 int decimal_places;
1356 char q_format[32];
1357
1358 /* add '*' */
1359 REALLOC_ARRAY(language_tags, num_langs + 1);
1360 language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1361
1362 /* compute decimal_places */
1363 for (max_q = 1, decimal_places = 0;
1364 max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1365 decimal_places++, max_q *= 10)
1366 ;
1367
5096d490 1368 xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
f18604bb
YE
1369
1370 strbuf_addstr(buf, "Accept-Language: ");
1371
1372 for (i = 0; i < num_langs; i++) {
1373 if (i > 0)
1374 strbuf_addstr(buf, ", ");
1375
1376 strbuf_addstr(buf, language_tags[i]);
1377
1378 if (i > 0)
1379 strbuf_addf(buf, q_format, max_q - i);
1380
1381 if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1382 strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1383 break;
1384 }
1385
1386 last_buf_len = buf->len;
1387 }
1388 }
1389
1390 /* free language tags -- last one is a static '*' */
1391 for (i = 0; i < num_langs - 1; i++)
1392 free(language_tags[i]);
1393 free(language_tags);
1394}
1395
1396/*
1397 * Get an Accept-Language header which indicates user's preferred languages.
1398 *
1399 * Examples:
1400 * LANGUAGE= -> ""
1401 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1402 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1403 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1404 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1405 * LANGUAGE= LANG=C -> ""
1406 */
1407static const char *get_accept_language(void)
1408{
1409 if (!cached_accept_language) {
1410 struct strbuf buf = STRBUF_INIT;
1411 write_accept_language(&buf);
1412 if (buf.len > 0)
1413 cached_accept_language = strbuf_detach(&buf, NULL);
1414 }
1415
1416 return cached_accept_language;
1417}
1418
835c4d36
DT
1419static void http_opt_request_remainder(CURL *curl, off_t pos)
1420{
1421 char buf[128];
1422 xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1423 curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1424}
1425
e929cd20
MH
1426/* http_request() targets */
1427#define HTTP_REQUEST_STRBUF 0
1428#define HTTP_REQUEST_FILE 1
1429
1bbcc224
JK
1430static int http_request(const char *url,
1431 void *result, int target,
1432 const struct http_get_options *options)
e929cd20
MH
1433{
1434 struct active_request_slot *slot;
1435 struct slot_results results;
8cb01e2f 1436 struct curl_slist *headers = http_copy_default_headers();
e929cd20 1437 struct strbuf buf = STRBUF_INIT;
f18604bb 1438 const char *accept_language;
e929cd20
MH
1439 int ret;
1440
1441 slot = get_active_slot();
e929cd20
MH
1442 curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1443
1444 if (result == NULL) {
1445 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1446 } else {
1447 curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1448 curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
1449
1450 if (target == HTTP_REQUEST_FILE) {
f8117f55 1451 off_t posn = ftello(result);
e929cd20
MH
1452 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1453 fwrite);
835c4d36
DT
1454 if (posn > 0)
1455 http_opt_request_remainder(slot->curl, posn);
e929cd20
MH
1456 } else
1457 curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1458 fwrite_buffer);
1459 }
1460
f18604bb
YE
1461 accept_language = get_accept_language();
1462
1463 if (accept_language)
1464 headers = curl_slist_append(headers, accept_language);
1465
e929cd20 1466 strbuf_addstr(&buf, "Pragma:");
1bbcc224 1467 if (options && options->no_cache)
e929cd20 1468 strbuf_addstr(&buf, " no-cache");
1bbcc224 1469 if (options && options->keep_error)
6d052d78 1470 curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
50d34137
JK
1471 if (options && options->initial_request &&
1472 http_follow_config == HTTP_FOLLOW_INITIAL)
1473 curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
e929cd20
MH
1474
1475 headers = curl_slist_append(headers, buf.buf);
1476
1477 curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1478 curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
aa90b969 1479 curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
e929cd20 1480
beed336c 1481 ret = run_one_slot(slot, &results);
e929cd20 1482
bf197fd7
JK
1483 if (options && options->content_type) {
1484 struct strbuf raw = STRBUF_INIT;
1485 curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
e3131626
JK
1486 extract_content_type(&raw, options->content_type,
1487 options->charset);
bf197fd7
JK
1488 strbuf_release(&raw);
1489 }
4656bf47 1490
78868962
JK
1491 if (options && options->effective_url)
1492 curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1493 options->effective_url);
4656bf47 1494
e929cd20
MH
1495 curl_slist_free_all(headers);
1496 strbuf_release(&buf);
1497
1498 return ret;
1499}
1500
c93c92f3
JK
1501/*
1502 * Update the "base" url to a more appropriate value, as deduced by
1503 * redirects seen when requesting a URL starting with "url".
1504 *
1505 * The "asked" parameter is a URL that we asked curl to access, and must begin
1506 * with "base".
1507 *
1508 * The "got" parameter is the URL that curl reported to us as where we ended
1509 * up.
1510 *
1511 * Returns 1 if we updated the base url, 0 otherwise.
1512 *
1513 * Our basic strategy is to compare "base" and "asked" to find the bits
1514 * specific to our request. We then strip those bits off of "got" to yield the
1515 * new base. So for example, if our base is "http://example.com/foo.git",
1516 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1517 * with "https://other.example.com/foo.git/info/refs". We would want the
1518 * new URL to become "https://other.example.com/foo.git".
1519 *
1520 * Note that this assumes a sane redirect scheme. It's entirely possible
1521 * in the example above to end up at a URL that does not even end in
6628eb41
JK
1522 * "info/refs". In such a case we die. There's not much we can do, such a
1523 * scheme is unlikely to represent a real git repository, and failing to
1524 * rewrite the base opens options for malicious redirects to do funny things.
c93c92f3
JK
1525 */
1526static int update_url_from_redirect(struct strbuf *base,
1527 const char *asked,
1528 const struct strbuf *got)
1529{
1530 const char *tail;
986d7f4d 1531 size_t new_len;
c93c92f3
JK
1532
1533 if (!strcmp(asked, got->buf))
1534 return 0;
1535
de8118e1 1536 if (!skip_prefix(asked, base->buf, &tail))
c93c92f3
JK
1537 die("BUG: update_url_from_redirect: %s is not a superset of %s",
1538 asked, base->buf);
1539
986d7f4d
JK
1540 new_len = got->len;
1541 if (!strip_suffix_mem(got->buf, &new_len, tail))
6628eb41
JK
1542 die(_("unable to update url base from redirection:\n"
1543 " asked for: %s\n"
1544 " redirect: %s"),
1545 asked, got->buf);
c93c92f3
JK
1546
1547 strbuf_reset(base);
986d7f4d 1548 strbuf_add(base, got->buf, new_len);
6628eb41 1549
c93c92f3
JK
1550 return 1;
1551}
1552
4656bf47 1553static int http_request_reauth(const char *url,
4656bf47 1554 void *result, int target,
1bbcc224 1555 struct http_get_options *options)
8d677edc 1556{
1bbcc224 1557 int ret = http_request(url, result, target, options);
c93c92f3
JK
1558
1559 if (options && options->effective_url && options->base_url) {
1560 if (update_url_from_redirect(options->base_url,
1561 url, options->effective_url)) {
1562 credential_from_url(&http_auth, options->base_url->buf);
1563 url = options->effective_url->buf;
1564 }
1565 }
1566
8d677edc
JK
1567 if (ret != HTTP_REAUTH)
1568 return ret;
6d052d78
JK
1569
1570 /*
1571 * If we are using KEEP_ERROR, the previous request may have
1572 * put cruft into our output stream; we should clear it out before
1573 * making our next request. We only know how to do this for
1574 * the strbuf case, but that is enough to satisfy current callers.
1575 */
1bbcc224 1576 if (options && options->keep_error) {
6d052d78
JK
1577 switch (target) {
1578 case HTTP_REQUEST_STRBUF:
1579 strbuf_reset(result);
1580 break;
1581 default:
1582 die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1583 }
1584 }
2501aff8
JK
1585
1586 credential_fill(&http_auth);
1587
1bbcc224 1588 return http_request(url, result, target, options);
8d677edc
JK
1589}
1590
4656bf47 1591int http_get_strbuf(const char *url,
1bbcc224
JK
1592 struct strbuf *result,
1593 struct http_get_options *options)
e929cd20 1594{
1bbcc224 1595 return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
e929cd20
MH
1596}
1597
83e41e2e 1598/*
a7793a74 1599 * Downloads a URL and stores the result in the given file.
83e41e2e
JH
1600 *
1601 * If a previous interrupted download is detected (i.e. a previous temporary
1602 * file is still around) the download is resumed.
1603 */
1bbcc224
JK
1604static int http_get_file(const char *url, const char *filename,
1605 struct http_get_options *options)
e929cd20
MH
1606{
1607 int ret;
1608 struct strbuf tmpfile = STRBUF_INIT;
1609 FILE *result;
1610
1611 strbuf_addf(&tmpfile, "%s.temp", filename);
1612 result = fopen(tmpfile.buf, "a");
3d1fb769 1613 if (!result) {
e929cd20
MH
1614 error("Unable to open local file %s", tmpfile.buf);
1615 ret = HTTP_ERROR;
1616 goto cleanup;
1617 }
1618
1bbcc224 1619 ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
e929cd20
MH
1620 fclose(result);
1621
cb5add58 1622 if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
e929cd20
MH
1623 ret = HTTP_ERROR;
1624cleanup:
1625 strbuf_release(&tmpfile);
1626 return ret;
1627}
1628
c13b2633 1629int http_fetch_ref(const char *base, struct ref *ref)
d7e92806 1630{
1bbcc224 1631 struct http_get_options options = {0};
d7e92806
MH
1632 char *url;
1633 struct strbuf buffer = STRBUF_INIT;
0d5896e1 1634 int ret = -1;
d7e92806 1635
1bbcc224
JK
1636 options.no_cache = 1;
1637
c13b2633 1638 url = quote_ref_url(base, ref->name);
1bbcc224 1639 if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
0d5896e1
MH
1640 strbuf_rtrim(&buffer);
1641 if (buffer.len == 40)
f4e54d02 1642 ret = get_oid_hex(buffer.buf, &ref->old_oid);
59556548 1643 else if (starts_with(buffer.buf, "ref: ")) {
0d5896e1
MH
1644 ref->symref = xstrdup(buffer.buf + 5);
1645 ret = 0;
d7e92806 1646 }
d7e92806
MH
1647 }
1648
1649 strbuf_release(&buffer);
1650 free(url);
1651 return ret;
1652}
b8caac2b
TRC
1653
1654/* Helpers for fetching packs */
750ef425 1655static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
b8caac2b 1656{
750ef425 1657 char *url, *tmp;
b8caac2b 1658 struct strbuf buf = STRBUF_INIT;
b8caac2b 1659
b8caac2b 1660 if (http_is_verbose)
162eb5f8 1661 fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
b8caac2b
TRC
1662
1663 end_url_with_slash(&buf, base_url);
162eb5f8 1664 strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
b8caac2b
TRC
1665 url = strbuf_detach(&buf, NULL);
1666
750ef425
SP
1667 strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
1668 tmp = strbuf_detach(&buf, NULL);
1669
70900eda 1670 if (http_get_file(url, tmp, NULL) != HTTP_OK) {
82247e9b 1671 error("Unable to get pack index %s", url);
750ef425
SP
1672 free(tmp);
1673 tmp = NULL;
1674 }
b8caac2b 1675
b8caac2b 1676 free(url);
750ef425 1677 return tmp;
b8caac2b
TRC
1678}
1679
1680static int fetch_and_setup_pack_index(struct packed_git **packs_head,
1681 unsigned char *sha1, const char *base_url)
1682{
1683 struct packed_git *new_pack;
750ef425
SP
1684 char *tmp_idx = NULL;
1685 int ret;
b8caac2b 1686
750ef425 1687 if (has_pack_index(sha1)) {
8b9c2dd4 1688 new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
750ef425
SP
1689 if (!new_pack)
1690 return -1; /* parse_pack_index() already issued error message */
1691 goto add_pack;
1692 }
1693
1694 tmp_idx = fetch_pack_index(sha1, base_url);
1695 if (!tmp_idx)
b8caac2b
TRC
1696 return -1;
1697
750ef425
SP
1698 new_pack = parse_pack_index(sha1, tmp_idx);
1699 if (!new_pack) {
1700 unlink(tmp_idx);
1701 free(tmp_idx);
1702
b8caac2b 1703 return -1; /* parse_pack_index() already issued error message */
750ef425
SP
1704 }
1705
1706 ret = verify_pack_index(new_pack);
1707 if (!ret) {
1708 close_pack_index(new_pack);
cb5add58 1709 ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
750ef425
SP
1710 }
1711 free(tmp_idx);
1712 if (ret)
1713 return -1;
1714
1715add_pack:
b8caac2b
TRC
1716 new_pack->next = *packs_head;
1717 *packs_head = new_pack;
1718 return 0;
1719}
1720
1721int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
1722{
1bbcc224 1723 struct http_get_options options = {0};
b8caac2b
TRC
1724 int ret = 0, i = 0;
1725 char *url, *data;
1726 struct strbuf buf = STRBUF_INIT;
1727 unsigned char sha1[20];
1728
1729 end_url_with_slash(&buf, base_url);
1730 strbuf_addstr(&buf, "objects/info/packs");
1731 url = strbuf_detach(&buf, NULL);
1732
1bbcc224
JK
1733 options.no_cache = 1;
1734 ret = http_get_strbuf(url, &buf, &options);
b8caac2b
TRC
1735 if (ret != HTTP_OK)
1736 goto cleanup;
1737
1738 data = buf.buf;
1739 while (i < buf.len) {
1740 switch (data[i]) {
1741 case 'P':
1742 i++;
1743 if (i + 52 <= buf.len &&
59556548
CC
1744 starts_with(data + i, " pack-") &&
1745 starts_with(data + i + 46, ".pack\n")) {
b8caac2b
TRC
1746 get_sha1_hex(data + i + 6, sha1);
1747 fetch_and_setup_pack_index(packs_head, sha1,
1748 base_url);
1749 i += 51;
1750 break;
1751 }
1752 default:
1753 while (i < buf.len && data[i] != '\n')
1754 i++;
1755 }
1756 i++;
1757 }
1758
1759cleanup:
1760 free(url);
1761 return ret;
1762}
2264dfa5
TRC
1763
1764void release_http_pack_request(struct http_pack_request *preq)
1765{
1766 if (preq->packfile != NULL) {
1767 fclose(preq->packfile);
1768 preq->packfile = NULL;
2264dfa5 1769 }
2264dfa5
TRC
1770 preq->slot = NULL;
1771 free(preq->url);
826aed50 1772 free(preq);
2264dfa5
TRC
1773}
1774
1775int finish_http_pack_request(struct http_pack_request *preq)
1776{
2264dfa5 1777 struct packed_git **lst;
021ab6f0 1778 struct packed_git *p = preq->target;
fe72d420 1779 char *tmp_idx;
9ae97018 1780 size_t len;
d3180279 1781 struct child_process ip = CHILD_PROCESS_INIT;
fe72d420 1782 const char *ip_argv[8];
2264dfa5 1783
fe72d420 1784 close_pack_index(p);
2264dfa5 1785
3065274c
SP
1786 fclose(preq->packfile);
1787 preq->packfile = NULL;
2264dfa5
TRC
1788
1789 lst = preq->lst;
021ab6f0 1790 while (*lst != p)
2264dfa5
TRC
1791 lst = &((*lst)->next);
1792 *lst = (*lst)->next;
1793
9ae97018
JK
1794 if (!strip_suffix(preq->tmpfile, ".pack.temp", &len))
1795 die("BUG: pack tmpfile does not end in .pack.temp?");
1796 tmp_idx = xstrfmt("%.*s.idx.temp", (int)len, preq->tmpfile);
fe72d420
SP
1797
1798 ip_argv[0] = "index-pack";
1799 ip_argv[1] = "-o";
1800 ip_argv[2] = tmp_idx;
1801 ip_argv[3] = preq->tmpfile;
1802 ip_argv[4] = NULL;
1803
fe72d420
SP
1804 ip.argv = ip_argv;
1805 ip.git_cmd = 1;
1806 ip.no_stdin = 1;
1807 ip.no_stdout = 1;
1808
1809 if (run_command(&ip)) {
1810 unlink(preq->tmpfile);
1811 unlink(tmp_idx);
1812 free(tmp_idx);
2264dfa5 1813 return -1;
fe72d420
SP
1814 }
1815
1816 unlink(sha1_pack_index_name(p->sha1));
2264dfa5 1817
cb5add58
JH
1818 if (finalize_object_file(preq->tmpfile, sha1_pack_name(p->sha1))
1819 || finalize_object_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
fe72d420 1820 free(tmp_idx);
2264dfa5 1821 return -1;
fe72d420 1822 }
2264dfa5 1823
fe72d420
SP
1824 install_packed_git(p);
1825 free(tmp_idx);
2264dfa5
TRC
1826 return 0;
1827}
1828
1829struct http_pack_request *new_http_pack_request(
1830 struct packed_git *target, const char *base_url)
1831{
f8117f55 1832 off_t prev_posn = 0;
2264dfa5
TRC
1833 struct strbuf buf = STRBUF_INIT;
1834 struct http_pack_request *preq;
1835
ec99c9a8 1836 preq = xcalloc(1, sizeof(*preq));
2264dfa5 1837 preq->target = target;
2264dfa5
TRC
1838
1839 end_url_with_slash(&buf, base_url);
1840 strbuf_addf(&buf, "objects/pack/pack-%s.pack",
1841 sha1_to_hex(target->sha1));
bb99190e 1842 preq->url = strbuf_detach(&buf, NULL);
2264dfa5 1843
90d05713
TRC
1844 snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
1845 sha1_pack_name(target->sha1));
2264dfa5
TRC
1846 preq->packfile = fopen(preq->tmpfile, "a");
1847 if (!preq->packfile) {
1848 error("Unable to open local file %s for pack",
1849 preq->tmpfile);
1850 goto abort;
1851 }
1852
1853 preq->slot = get_active_slot();
2264dfa5
TRC
1854 curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
1855 curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
bb99190e 1856 curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2264dfa5
TRC
1857 curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1858 no_pragma_header);
1859
1860 /*
1861 * If there is data present from a previous transfer attempt,
1862 * resume where it left off
1863 */
f8117f55 1864 prev_posn = ftello(preq->packfile);
2264dfa5
TRC
1865 if (prev_posn>0) {
1866 if (http_is_verbose)
1867 fprintf(stderr,
838ecf0b
RJ
1868 "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
1869 sha1_to_hex(target->sha1), (uintmax_t)prev_posn);
835c4d36 1870 http_opt_request_remainder(preq->slot->curl, prev_posn);
2264dfa5
TRC
1871 }
1872
1873 return preq;
1874
1875abort:
bb99190e 1876 free(preq->url);
5ae9ebfd 1877 free(preq);
2264dfa5
TRC
1878 return NULL;
1879}
5424bc55
TRC
1880
1881/* Helpers for fetching objects (loose) */
a04ff3ec 1882static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
5424bc55
TRC
1883 void *data)
1884{
1885 unsigned char expn[4096];
1886 size_t size = eltsize * nmemb;
1887 int posn = 0;
17966c0a
EW
1888 struct http_object_request *freq = data;
1889 struct active_request_slot *slot = freq->slot;
1890
1891 if (slot) {
1892 CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
1893 &slot->http_code);
1894 if (c != CURLE_OK)
1895 die("BUG: curl_easy_getinfo for HTTP code failed: %s",
1896 curl_easy_strerror(c));
1897 if (slot->http_code >= 400)
1898 return size;
1899 }
1900
5424bc55
TRC
1901 do {
1902 ssize_t retval = xwrite(freq->localfile,
1903 (char *) ptr + posn, size - posn);
1904 if (retval < 0)
1905 return posn;
1906 posn += retval;
1907 } while (posn < size);
1908
1909 freq->stream.avail_in = size;
a04ff3ec 1910 freq->stream.next_in = (void *)ptr;
5424bc55
TRC
1911 do {
1912 freq->stream.next_out = expn;
1913 freq->stream.avail_out = sizeof(expn);
1914 freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
1915 git_SHA1_Update(&freq->c, expn,
1916 sizeof(expn) - freq->stream.avail_out);
1917 } while (freq->stream.avail_in && freq->zret == Z_OK);
5424bc55
TRC
1918 return size;
1919}
1920
1921struct http_object_request *new_http_object_request(const char *base_url,
1922 unsigned char *sha1)
1923{
1924 char *hex = sha1_to_hex(sha1);
30d6c6ea 1925 const char *filename;
5424bc55 1926 char prevfile[PATH_MAX];
5424bc55 1927 int prevlocal;
a04ff3ec 1928 char prev_buf[PREV_BUF_SIZE];
5424bc55 1929 ssize_t prev_read = 0;
f8117f55 1930 off_t prev_posn = 0;
5424bc55
TRC
1931 struct http_object_request *freq;
1932
ec99c9a8 1933 freq = xcalloc(1, sizeof(*freq));
5424bc55
TRC
1934 hashcpy(freq->sha1, sha1);
1935 freq->localfile = -1;
1936
1937 filename = sha1_file_name(sha1);
5424bc55
TRC
1938 snprintf(freq->tmpfile, sizeof(freq->tmpfile),
1939 "%s.temp", filename);
1940
1941 snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
1942 unlink_or_warn(prevfile);
1943 rename(freq->tmpfile, prevfile);
1944 unlink_or_warn(freq->tmpfile);
1945
1946 if (freq->localfile != -1)
1947 error("fd leakage in start: %d", freq->localfile);
1948 freq->localfile = open(freq->tmpfile,
1949 O_WRONLY | O_CREAT | O_EXCL, 0666);
1950 /*
1951 * This could have failed due to the "lazy directory creation";
1952 * try to mkdir the last path component.
1953 */
1954 if (freq->localfile < 0 && errno == ENOENT) {
1955 char *dir = strrchr(freq->tmpfile, '/');
1956 if (dir) {
1957 *dir = 0;
1958 mkdir(freq->tmpfile, 0777);
1959 *dir = '/';
1960 }
1961 freq->localfile = open(freq->tmpfile,
1962 O_WRONLY | O_CREAT | O_EXCL, 0666);
1963 }
1964
1965 if (freq->localfile < 0) {
d2e255ee 1966 error_errno("Couldn't create temporary file %s", freq->tmpfile);
5424bc55
TRC
1967 goto abort;
1968 }
1969
5424bc55
TRC
1970 git_inflate_init(&freq->stream);
1971
1972 git_SHA1_Init(&freq->c);
1973
bb99190e 1974 freq->url = get_remote_object_url(base_url, hex, 0);
5424bc55
TRC
1975
1976 /*
1977 * If a previous temp file is present, process what was already
1978 * fetched.
1979 */
1980 prevlocal = open(prevfile, O_RDONLY);
1981 if (prevlocal != -1) {
1982 do {
1983 prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
1984 if (prev_read>0) {
1985 if (fwrite_sha1_file(prev_buf,
1986 1,
1987 prev_read,
1988 freq) == prev_read) {
1989 prev_posn += prev_read;
1990 } else {
1991 prev_read = -1;
1992 }
1993 }
1994 } while (prev_read > 0);
1995 close(prevlocal);
1996 }
1997 unlink_or_warn(prevfile);
1998
1999 /*
2000 * Reset inflate/SHA1 if there was an error reading the previous temp
2001 * file; also rewind to the beginning of the local file.
2002 */
2003 if (prev_read == -1) {
2004 memset(&freq->stream, 0, sizeof(freq->stream));
2005 git_inflate_init(&freq->stream);
2006 git_SHA1_Init(&freq->c);
2007 if (prev_posn>0) {
2008 prev_posn = 0;
2009 lseek(freq->localfile, 0, SEEK_SET);
0c4f21e4 2010 if (ftruncate(freq->localfile, 0) < 0) {
d2e255ee
NTND
2011 error_errno("Couldn't truncate temporary file %s",
2012 freq->tmpfile);
0c4f21e4
JL
2013 goto abort;
2014 }
5424bc55
TRC
2015 }
2016 }
2017
2018 freq->slot = get_active_slot();
2019
2020 curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
17966c0a 2021 curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
5424bc55
TRC
2022 curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2023 curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
bb99190e 2024 curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
5424bc55
TRC
2025 curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
2026
2027 /*
2028 * If we have successfully processed data from a previous fetch
2029 * attempt, only fetch the data we don't already have.
2030 */
2031 if (prev_posn>0) {
2032 if (http_is_verbose)
2033 fprintf(stderr,
838ecf0b
RJ
2034 "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2035 hex, (uintmax_t)prev_posn);
835c4d36 2036 http_opt_request_remainder(freq->slot->curl, prev_posn);
5424bc55
TRC
2037 }
2038
2039 return freq;
2040
5424bc55 2041abort:
bb99190e 2042 free(freq->url);
5424bc55
TRC
2043 free(freq);
2044 return NULL;
2045}
2046
2047void process_http_object_request(struct http_object_request *freq)
2048{
2049 if (freq->slot == NULL)
2050 return;
2051 freq->curl_result = freq->slot->curl_result;
2052 freq->http_code = freq->slot->http_code;
2053 freq->slot = NULL;
2054}
2055
2056int finish_http_object_request(struct http_object_request *freq)
2057{
2058 struct stat st;
2059
2060 close(freq->localfile);
2061 freq->localfile = -1;
2062
2063 process_http_object_request(freq);
2064
2065 if (freq->http_code == 416) {
bd757c18 2066 warning("requested range invalid; we may already have all the data.");
5424bc55
TRC
2067 } else if (freq->curl_result != CURLE_OK) {
2068 if (stat(freq->tmpfile, &st) == 0)
2069 if (st.st_size == 0)
2070 unlink_or_warn(freq->tmpfile);
2071 return -1;
2072 }
2073
2074 git_inflate_end(&freq->stream);
2075 git_SHA1_Final(freq->real_sha1, &freq->c);
2076 if (freq->zret != Z_STREAM_END) {
2077 unlink_or_warn(freq->tmpfile);
2078 return -1;
2079 }
2080 if (hashcmp(freq->sha1, freq->real_sha1)) {
2081 unlink_or_warn(freq->tmpfile);
2082 return -1;
2083 }
2084 freq->rename =
cb5add58 2085 finalize_object_file(freq->tmpfile, sha1_file_name(freq->sha1));
5424bc55
TRC
2086
2087 return freq->rename;
2088}
2089
2090void abort_http_object_request(struct http_object_request *freq)
2091{
2092 unlink_or_warn(freq->tmpfile);
2093
2094 release_http_object_request(freq);
2095}
2096
2097void release_http_object_request(struct http_object_request *freq)
2098{
2099 if (freq->localfile != -1) {
2100 close(freq->localfile);
2101 freq->localfile = -1;
2102 }
2103 if (freq->url != NULL) {
2104 free(freq->url);
2105 freq->url = NULL;
2106 }
4b9fa0e3
TRC
2107 if (freq->slot != NULL) {
2108 freq->slot->callback_func = NULL;
2109 freq->slot->callback_data = NULL;
2110 release_active_slot(freq->slot);
2111 freq->slot = NULL;
2112 }
5424bc55 2113}