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