1 #include "git-compat-util.h"
5 #include "run-command.h"
8 #include "credential.h"
12 #include "transport.h"
16 size_t http_post_buffer
= 16 * LARGE_PACKET_MAX
;
18 #if LIBCURL_VERSION_NUM >= 0x070a06
19 #define LIBCURL_CAN_HANDLE_AUTH_ANY
22 static int min_curl_sessions
= 1;
23 static int curl_session_count
;
25 static int max_requests
= -1;
28 #ifndef NO_CURL_EASY_DUPHANDLE
29 static CURL
*curl_default
;
32 #define PREV_BUF_SIZE 4096
33 #define RANGE_HEADER_SIZE 30
35 char curl_errorstr
[CURL_ERROR_SIZE
];
37 static int curl_ssl_verify
= -1;
38 static int curl_ssl_try
;
39 static const char *ssl_cert
;
40 static const char *ssl_cipherlist
;
41 static const char *ssl_version
;
46 { "sslv2", CURL_SSLVERSION_SSLv2
},
47 { "sslv3", CURL_SSLVERSION_SSLv3
},
48 { "tlsv1", CURL_SSLVERSION_TLSv1
},
49 #if LIBCURL_VERSION_NUM >= 0x072200
50 { "tlsv1.0", CURL_SSLVERSION_TLSv1_0
},
51 { "tlsv1.1", CURL_SSLVERSION_TLSv1_1
},
52 { "tlsv1.2", CURL_SSLVERSION_TLSv1_2
},
55 #if LIBCURL_VERSION_NUM >= 0x070903
56 static const char *ssl_key
;
58 #if LIBCURL_VERSION_NUM >= 0x070908
59 static const char *ssl_capath
;
61 static const char *ssl_cainfo
;
62 static long curl_low_speed_limit
= -1;
63 static long curl_low_speed_time
= -1;
64 static int curl_ftp_no_epsv
;
65 static const char *curl_http_proxy
;
66 static const char *curl_cookie_file
;
67 static int curl_save_cookies
;
68 struct credential http_auth
= CREDENTIAL_INIT
;
69 static int http_proactive_auth
;
70 static const char *user_agent
;
72 #if LIBCURL_VERSION_NUM >= 0x071700
73 /* Use CURLOPT_KEYPASSWD as is */
74 #elif LIBCURL_VERSION_NUM >= 0x070903
75 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
77 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
80 static struct credential cert_auth
= CREDENTIAL_INIT
;
81 static int ssl_cert_password_required
;
82 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
83 static unsigned long http_auth_methods
= CURLAUTH_ANY
;
86 static struct curl_slist
*pragma_header
;
87 static struct curl_slist
*no_pragma_header
;
89 static struct active_request_slot
*active_queue_head
;
91 static char *cached_accept_language
;
93 size_t fread_buffer(char *ptr
, size_t eltsize
, size_t nmemb
, void *buffer_
)
95 size_t size
= eltsize
* nmemb
;
96 struct buffer
*buffer
= buffer_
;
98 if (size
> buffer
->buf
.len
- buffer
->posn
)
99 size
= buffer
->buf
.len
- buffer
->posn
;
100 memcpy(ptr
, buffer
->buf
.buf
+ buffer
->posn
, size
);
101 buffer
->posn
+= size
;
106 #ifndef NO_CURL_IOCTL
107 curlioerr
ioctl_buffer(CURL
*handle
, int cmd
, void *clientp
)
109 struct buffer
*buffer
= clientp
;
115 case CURLIOCMD_RESTARTREAD
:
120 return CURLIOE_UNKNOWNCMD
;
125 size_t fwrite_buffer(char *ptr
, size_t eltsize
, size_t nmemb
, void *buffer_
)
127 size_t size
= eltsize
* nmemb
;
128 struct strbuf
*buffer
= buffer_
;
130 strbuf_add(buffer
, ptr
, size
);
134 size_t fwrite_null(char *ptr
, size_t eltsize
, size_t nmemb
, void *strbuf
)
136 return eltsize
* nmemb
;
139 static void closedown_active_slot(struct active_request_slot
*slot
)
145 static void finish_active_slot(struct active_request_slot
*slot
)
147 closedown_active_slot(slot
);
148 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CODE
, &slot
->http_code
);
150 if (slot
->finished
!= NULL
)
151 (*slot
->finished
) = 1;
153 /* Store slot results so they can be read after the slot is reused */
154 if (slot
->results
!= NULL
) {
155 slot
->results
->curl_result
= slot
->curl_result
;
156 slot
->results
->http_code
= slot
->http_code
;
157 #if LIBCURL_VERSION_NUM >= 0x070a08
158 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTPAUTH_AVAIL
,
159 &slot
->results
->auth_avail
);
161 slot
->results
->auth_avail
= 0;
165 /* Run callback if appropriate */
166 if (slot
->callback_func
!= NULL
)
167 slot
->callback_func(slot
->callback_data
);
170 #ifdef USE_CURL_MULTI
171 static void process_curl_messages(void)
174 struct active_request_slot
*slot
;
175 CURLMsg
*curl_message
= curl_multi_info_read(curlm
, &num_messages
);
177 while (curl_message
!= NULL
) {
178 if (curl_message
->msg
== CURLMSG_DONE
) {
179 int curl_result
= curl_message
->data
.result
;
180 slot
= active_queue_head
;
181 while (slot
!= NULL
&&
182 slot
->curl
!= curl_message
->easy_handle
)
185 curl_multi_remove_handle(curlm
, slot
->curl
);
186 slot
->curl_result
= curl_result
;
187 finish_active_slot(slot
);
189 fprintf(stderr
, "Received DONE message for unknown request!\n");
192 fprintf(stderr
, "Unknown CURL message received: %d\n",
193 (int)curl_message
->msg
);
195 curl_message
= curl_multi_info_read(curlm
, &num_messages
);
200 static int http_options(const char *var
, const char *value
, void *cb
)
202 if (!strcmp("http.sslverify", var
)) {
203 curl_ssl_verify
= git_config_bool(var
, value
);
206 if (!strcmp("http.sslcipherlist", var
))
207 return git_config_string(&ssl_cipherlist
, var
, value
);
208 if (!strcmp("http.sslversion", var
))
209 return git_config_string(&ssl_version
, var
, value
);
210 if (!strcmp("http.sslcert", var
))
211 return git_config_string(&ssl_cert
, var
, value
);
212 #if LIBCURL_VERSION_NUM >= 0x070903
213 if (!strcmp("http.sslkey", var
))
214 return git_config_string(&ssl_key
, var
, value
);
216 #if LIBCURL_VERSION_NUM >= 0x070908
217 if (!strcmp("http.sslcapath", var
))
218 return git_config_pathname(&ssl_capath
, var
, value
);
220 if (!strcmp("http.sslcainfo", var
))
221 return git_config_pathname(&ssl_cainfo
, var
, value
);
222 if (!strcmp("http.sslcertpasswordprotected", var
)) {
223 ssl_cert_password_required
= git_config_bool(var
, value
);
226 if (!strcmp("http.ssltry", var
)) {
227 curl_ssl_try
= git_config_bool(var
, value
);
230 if (!strcmp("http.minsessions", var
)) {
231 min_curl_sessions
= git_config_int(var
, value
);
232 #ifndef USE_CURL_MULTI
233 if (min_curl_sessions
> 1)
234 min_curl_sessions
= 1;
238 #ifdef USE_CURL_MULTI
239 if (!strcmp("http.maxrequests", var
)) {
240 max_requests
= git_config_int(var
, value
);
244 if (!strcmp("http.lowspeedlimit", var
)) {
245 curl_low_speed_limit
= (long)git_config_int(var
, value
);
248 if (!strcmp("http.lowspeedtime", var
)) {
249 curl_low_speed_time
= (long)git_config_int(var
, value
);
253 if (!strcmp("http.noepsv", var
)) {
254 curl_ftp_no_epsv
= git_config_bool(var
, value
);
257 if (!strcmp("http.proxy", var
))
258 return git_config_string(&curl_http_proxy
, var
, value
);
260 if (!strcmp("http.cookiefile", var
))
261 return git_config_string(&curl_cookie_file
, var
, value
);
262 if (!strcmp("http.savecookies", var
)) {
263 curl_save_cookies
= git_config_bool(var
, value
);
267 if (!strcmp("http.postbuffer", var
)) {
268 http_post_buffer
= git_config_int(var
, value
);
269 if (http_post_buffer
< LARGE_PACKET_MAX
)
270 http_post_buffer
= LARGE_PACKET_MAX
;
274 if (!strcmp("http.useragent", var
))
275 return git_config_string(&user_agent
, var
, value
);
277 /* Fall back on the default ones */
278 return git_default_config(var
, value
, cb
);
281 static void init_curl_http_auth(CURL
*result
)
283 if (!http_auth
.username
)
286 credential_fill(&http_auth
);
288 #if LIBCURL_VERSION_NUM >= 0x071301
289 curl_easy_setopt(result
, CURLOPT_USERNAME
, http_auth
.username
);
290 curl_easy_setopt(result
, CURLOPT_PASSWORD
, http_auth
.password
);
293 static struct strbuf up
= STRBUF_INIT
;
295 * Note that we assume we only ever have a single set of
296 * credentials in a given program run, so we do not have
297 * to worry about updating this buffer, only setting its
301 strbuf_addf(&up
, "%s:%s",
302 http_auth
.username
, http_auth
.password
);
303 curl_easy_setopt(result
, CURLOPT_USERPWD
, up
.buf
);
308 static int has_cert_password(void)
310 if (ssl_cert
== NULL
|| ssl_cert_password_required
!= 1)
312 if (!cert_auth
.password
) {
313 cert_auth
.protocol
= xstrdup("cert");
314 cert_auth
.username
= xstrdup("");
315 cert_auth
.path
= xstrdup(ssl_cert
);
316 credential_fill(&cert_auth
);
321 #if LIBCURL_VERSION_NUM >= 0x071900
322 static void set_curl_keepalive(CURL
*c
)
324 curl_easy_setopt(c
, CURLOPT_TCP_KEEPALIVE
, 1);
327 #elif LIBCURL_VERSION_NUM >= 0x071000
328 static int sockopt_callback(void *client
, curl_socket_t fd
, curlsocktype type
)
332 socklen_t len
= (socklen_t
)sizeof(ka
);
334 if (type
!= CURLSOCKTYPE_IPCXN
)
337 rc
= setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (void *)&ka
, len
);
339 warning("unable to set SO_KEEPALIVE on socket %s",
342 return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
345 static void set_curl_keepalive(CURL
*c
)
347 curl_easy_setopt(c
, CURLOPT_SOCKOPTFUNCTION
, sockopt_callback
);
351 static void set_curl_keepalive(CURL
*c
)
353 /* not supported on older curl versions */
357 static CURL
*get_curl_handle(void)
359 CURL
*result
= curl_easy_init();
360 long allowed_protocols
= 0;
363 die("curl_easy_init failed");
365 if (!curl_ssl_verify
) {
366 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 0);
367 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 0);
369 /* Verify authenticity of the peer's certificate */
370 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 1);
371 /* The name in the cert must match whom we tried to connect */
372 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 2);
375 #if LIBCURL_VERSION_NUM >= 0x070907
376 curl_easy_setopt(result
, CURLOPT_NETRC
, CURL_NETRC_OPTIONAL
);
378 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
379 curl_easy_setopt(result
, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
382 if (http_proactive_auth
)
383 init_curl_http_auth(result
);
385 if (getenv("GIT_SSL_VERSION"))
386 ssl_version
= getenv("GIT_SSL_VERSION");
387 if (ssl_version
&& *ssl_version
) {
389 for (i
= 0; i
< ARRAY_SIZE(sslversions
); i
++) {
390 if (!strcmp(ssl_version
, sslversions
[i
].name
)) {
391 curl_easy_setopt(result
, CURLOPT_SSLVERSION
,
392 sslversions
[i
].ssl_version
);
396 if (i
== ARRAY_SIZE(sslversions
))
397 warning("unsupported ssl version %s: using default",
401 if (getenv("GIT_SSL_CIPHER_LIST"))
402 ssl_cipherlist
= getenv("GIT_SSL_CIPHER_LIST");
403 if (ssl_cipherlist
!= NULL
&& *ssl_cipherlist
)
404 curl_easy_setopt(result
, CURLOPT_SSL_CIPHER_LIST
,
407 if (ssl_cert
!= NULL
)
408 curl_easy_setopt(result
, CURLOPT_SSLCERT
, ssl_cert
);
409 if (has_cert_password())
410 curl_easy_setopt(result
, CURLOPT_KEYPASSWD
, cert_auth
.password
);
411 #if LIBCURL_VERSION_NUM >= 0x070903
413 curl_easy_setopt(result
, CURLOPT_SSLKEY
, ssl_key
);
415 #if LIBCURL_VERSION_NUM >= 0x070908
416 if (ssl_capath
!= NULL
)
417 curl_easy_setopt(result
, CURLOPT_CAPATH
, ssl_capath
);
419 if (ssl_cainfo
!= NULL
)
420 curl_easy_setopt(result
, CURLOPT_CAINFO
, ssl_cainfo
);
422 if (curl_low_speed_limit
> 0 && curl_low_speed_time
> 0) {
423 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_LIMIT
,
424 curl_low_speed_limit
);
425 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_TIME
,
426 curl_low_speed_time
);
429 curl_easy_setopt(result
, CURLOPT_FOLLOWLOCATION
, 1);
430 curl_easy_setopt(result
, CURLOPT_MAXREDIRS
, 20);
431 #if LIBCURL_VERSION_NUM >= 0x071301
432 curl_easy_setopt(result
, CURLOPT_POSTREDIR
, CURL_REDIR_POST_ALL
);
433 #elif LIBCURL_VERSION_NUM >= 0x071101
434 curl_easy_setopt(result
, CURLOPT_POST301
, 1);
436 #if LIBCURL_VERSION_NUM >= 0x071304
437 if (is_transport_allowed("http"))
438 allowed_protocols
|= CURLPROTO_HTTP
;
439 if (is_transport_allowed("https"))
440 allowed_protocols
|= CURLPROTO_HTTPS
;
441 if (is_transport_allowed("ftp"))
442 allowed_protocols
|= CURLPROTO_FTP
;
443 if (is_transport_allowed("ftps"))
444 allowed_protocols
|= CURLPROTO_FTPS
;
445 curl_easy_setopt(result
, CURLOPT_REDIR_PROTOCOLS
, allowed_protocols
);
447 if (transport_restrict_protocols())
448 warning("protocol restrictions not applied to curl redirects because\n"
449 "your curl version is too old (>= 7.19.4)");
452 if (getenv("GIT_CURL_VERBOSE"))
453 curl_easy_setopt(result
, CURLOPT_VERBOSE
, 1);
455 curl_easy_setopt(result
, CURLOPT_USERAGENT
,
456 user_agent
? user_agent
: git_user_agent());
458 if (curl_ftp_no_epsv
)
459 curl_easy_setopt(result
, CURLOPT_FTP_USE_EPSV
, 0);
461 #ifdef CURLOPT_USE_SSL
463 curl_easy_setopt(result
, CURLOPT_USE_SSL
, CURLUSESSL_TRY
);
466 if (curl_http_proxy
) {
467 curl_easy_setopt(result
, CURLOPT_PROXY
, curl_http_proxy
);
468 #if LIBCURL_VERSION_NUM >= 0x071800
469 if (starts_with(curl_http_proxy
, "socks5"))
470 curl_easy_setopt(result
,
471 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5
);
472 else if (starts_with(curl_http_proxy
, "socks4a"))
473 curl_easy_setopt(result
,
474 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4A
);
475 else if (starts_with(curl_http_proxy
, "socks"))
476 curl_easy_setopt(result
,
477 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4
);
480 #if LIBCURL_VERSION_NUM >= 0x070a07
481 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
, CURLAUTH_ANY
);
484 set_curl_keepalive(result
);
489 static void set_from_env(const char **var
, const char *envname
)
491 const char *val
= getenv(envname
);
496 void http_init(struct remote
*remote
, const char *url
, int proactive_auth
)
498 char *low_speed_limit
;
499 char *low_speed_time
;
500 char *normalized_url
;
501 struct urlmatch_config config
= { STRING_LIST_INIT_DUP
};
503 config
.section
= "http";
505 config
.collect_fn
= http_options
;
506 config
.cascade_fn
= git_default_config
;
510 normalized_url
= url_normalize(url
, &config
.url
);
512 git_config(urlmatch_config_entry
, &config
);
513 free(normalized_url
);
515 if (curl_global_init(CURL_GLOBAL_ALL
) != CURLE_OK
)
516 die("curl_global_init failed");
518 http_proactive_auth
= proactive_auth
;
520 if (remote
&& remote
->http_proxy
)
521 curl_http_proxy
= xstrdup(remote
->http_proxy
);
523 pragma_header
= curl_slist_append(pragma_header
, "Pragma: no-cache");
524 no_pragma_header
= curl_slist_append(no_pragma_header
, "Pragma:");
526 #ifdef USE_CURL_MULTI
528 char *http_max_requests
= getenv("GIT_HTTP_MAX_REQUESTS");
529 if (http_max_requests
!= NULL
)
530 max_requests
= atoi(http_max_requests
);
533 curlm
= curl_multi_init();
535 die("curl_multi_init failed");
538 if (getenv("GIT_SSL_NO_VERIFY"))
541 set_from_env(&ssl_cert
, "GIT_SSL_CERT");
542 #if LIBCURL_VERSION_NUM >= 0x070903
543 set_from_env(&ssl_key
, "GIT_SSL_KEY");
545 #if LIBCURL_VERSION_NUM >= 0x070908
546 set_from_env(&ssl_capath
, "GIT_SSL_CAPATH");
548 set_from_env(&ssl_cainfo
, "GIT_SSL_CAINFO");
550 set_from_env(&user_agent
, "GIT_HTTP_USER_AGENT");
552 low_speed_limit
= getenv("GIT_HTTP_LOW_SPEED_LIMIT");
553 if (low_speed_limit
!= NULL
)
554 curl_low_speed_limit
= strtol(low_speed_limit
, NULL
, 10);
555 low_speed_time
= getenv("GIT_HTTP_LOW_SPEED_TIME");
556 if (low_speed_time
!= NULL
)
557 curl_low_speed_time
= strtol(low_speed_time
, NULL
, 10);
559 if (curl_ssl_verify
== -1)
562 curl_session_count
= 0;
563 #ifdef USE_CURL_MULTI
564 if (max_requests
< 1)
565 max_requests
= DEFAULT_MAX_REQUESTS
;
568 if (getenv("GIT_CURL_FTP_NO_EPSV"))
569 curl_ftp_no_epsv
= 1;
572 credential_from_url(&http_auth
, url
);
573 if (!ssl_cert_password_required
&&
574 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
575 starts_with(url
, "https://"))
576 ssl_cert_password_required
= 1;
579 #ifndef NO_CURL_EASY_DUPHANDLE
580 curl_default
= get_curl_handle();
584 void http_cleanup(void)
586 struct active_request_slot
*slot
= active_queue_head
;
588 while (slot
!= NULL
) {
589 struct active_request_slot
*next
= slot
->next
;
590 if (slot
->curl
!= NULL
) {
591 #ifdef USE_CURL_MULTI
592 curl_multi_remove_handle(curlm
, slot
->curl
);
594 curl_easy_cleanup(slot
->curl
);
599 active_queue_head
= NULL
;
601 #ifndef NO_CURL_EASY_DUPHANDLE
602 curl_easy_cleanup(curl_default
);
605 #ifdef USE_CURL_MULTI
606 curl_multi_cleanup(curlm
);
608 curl_global_cleanup();
610 curl_slist_free_all(pragma_header
);
611 pragma_header
= NULL
;
613 curl_slist_free_all(no_pragma_header
);
614 no_pragma_header
= NULL
;
616 if (curl_http_proxy
) {
617 free((void *)curl_http_proxy
);
618 curl_http_proxy
= NULL
;
621 if (cert_auth
.password
!= NULL
) {
622 memset(cert_auth
.password
, 0, strlen(cert_auth
.password
));
623 free(cert_auth
.password
);
624 cert_auth
.password
= NULL
;
626 ssl_cert_password_required
= 0;
628 free(cached_accept_language
);
629 cached_accept_language
= NULL
;
632 struct active_request_slot
*get_active_slot(void)
634 struct active_request_slot
*slot
= active_queue_head
;
635 struct active_request_slot
*newslot
;
637 #ifdef USE_CURL_MULTI
640 /* Wait for a slot to open up if the queue is full */
641 while (active_requests
>= max_requests
) {
642 curl_multi_perform(curlm
, &num_transfers
);
643 if (num_transfers
< active_requests
)
644 process_curl_messages();
648 while (slot
!= NULL
&& slot
->in_use
)
652 newslot
= xmalloc(sizeof(*newslot
));
653 newslot
->curl
= NULL
;
655 newslot
->next
= NULL
;
657 slot
= active_queue_head
;
659 active_queue_head
= newslot
;
661 while (slot
->next
!= NULL
)
663 slot
->next
= newslot
;
668 if (slot
->curl
== NULL
) {
669 #ifdef NO_CURL_EASY_DUPHANDLE
670 slot
->curl
= get_curl_handle();
672 slot
->curl
= curl_easy_duphandle(curl_default
);
674 curl_session_count
++;
679 slot
->results
= NULL
;
680 slot
->finished
= NULL
;
681 slot
->callback_data
= NULL
;
682 slot
->callback_func
= NULL
;
683 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEFILE
, curl_cookie_file
);
684 if (curl_save_cookies
)
685 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEJAR
, curl_cookie_file
);
686 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, pragma_header
);
687 curl_easy_setopt(slot
->curl
, CURLOPT_ERRORBUFFER
, curl_errorstr
);
688 curl_easy_setopt(slot
->curl
, CURLOPT_CUSTOMREQUEST
, NULL
);
689 curl_easy_setopt(slot
->curl
, CURLOPT_READFUNCTION
, NULL
);
690 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
, NULL
);
691 curl_easy_setopt(slot
->curl
, CURLOPT_POSTFIELDS
, NULL
);
692 curl_easy_setopt(slot
->curl
, CURLOPT_UPLOAD
, 0);
693 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
694 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 1);
695 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
696 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPAUTH
, http_auth_methods
);
698 if (http_auth
.password
)
699 init_curl_http_auth(slot
->curl
);
704 int start_active_slot(struct active_request_slot
*slot
)
706 #ifdef USE_CURL_MULTI
707 CURLMcode curlm_result
= curl_multi_add_handle(curlm
, slot
->curl
);
710 if (curlm_result
!= CURLM_OK
&&
711 curlm_result
!= CURLM_CALL_MULTI_PERFORM
) {
718 * We know there must be something to do, since we just added
721 curl_multi_perform(curlm
, &num_transfers
);
726 #ifdef USE_CURL_MULTI
730 struct fill_chain
*next
;
733 static struct fill_chain
*fill_cfg
;
735 void add_fill_function(void *data
, int (*fill
)(void *))
737 struct fill_chain
*new = xmalloc(sizeof(*new));
738 struct fill_chain
**linkp
= &fill_cfg
;
743 linkp
= &(*linkp
)->next
;
747 void fill_active_slots(void)
749 struct active_request_slot
*slot
= active_queue_head
;
751 while (active_requests
< max_requests
) {
752 struct fill_chain
*fill
;
753 for (fill
= fill_cfg
; fill
; fill
= fill
->next
)
754 if (fill
->fill(fill
->data
))
761 while (slot
!= NULL
) {
762 if (!slot
->in_use
&& slot
->curl
!= NULL
763 && curl_session_count
> min_curl_sessions
) {
764 curl_easy_cleanup(slot
->curl
);
766 curl_session_count
--;
772 void step_active_slots(void)
775 CURLMcode curlm_result
;
778 curlm_result
= curl_multi_perform(curlm
, &num_transfers
);
779 } while (curlm_result
== CURLM_CALL_MULTI_PERFORM
);
780 if (num_transfers
< active_requests
) {
781 process_curl_messages();
787 void run_active_slot(struct active_request_slot
*slot
)
789 #ifdef USE_CURL_MULTI
794 struct timeval select_timeout
;
797 slot
->finished
= &finished
;
802 #if LIBCURL_VERSION_NUM >= 0x070f04
804 curl_multi_timeout(curlm
, &curl_timeout
);
805 if (curl_timeout
== 0) {
807 } else if (curl_timeout
== -1) {
808 select_timeout
.tv_sec
= 0;
809 select_timeout
.tv_usec
= 50000;
811 select_timeout
.tv_sec
= curl_timeout
/ 1000;
812 select_timeout
.tv_usec
= (curl_timeout
% 1000) * 1000;
815 select_timeout
.tv_sec
= 0;
816 select_timeout
.tv_usec
= 50000;
823 curl_multi_fdset(curlm
, &readfds
, &writefds
, &excfds
, &max_fd
);
826 * It can happen that curl_multi_timeout returns a pathologically
827 * long timeout when curl_multi_fdset returns no file descriptors
828 * to read. See commit message for more details.
831 (select_timeout
.tv_sec
> 0 ||
832 select_timeout
.tv_usec
> 50000)) {
833 select_timeout
.tv_sec
= 0;
834 select_timeout
.tv_usec
= 50000;
837 select(max_fd
+1, &readfds
, &writefds
, &excfds
, &select_timeout
);
841 while (slot
->in_use
) {
842 slot
->curl_result
= curl_easy_perform(slot
->curl
);
843 finish_active_slot(slot
);
848 static void release_active_slot(struct active_request_slot
*slot
)
850 closedown_active_slot(slot
);
851 if (slot
->curl
&& curl_session_count
> min_curl_sessions
) {
852 #ifdef USE_CURL_MULTI
853 curl_multi_remove_handle(curlm
, slot
->curl
);
855 curl_easy_cleanup(slot
->curl
);
857 curl_session_count
--;
859 #ifdef USE_CURL_MULTI
864 void finish_all_active_slots(void)
866 struct active_request_slot
*slot
= active_queue_head
;
870 run_active_slot(slot
);
871 slot
= active_queue_head
;
877 /* Helpers for modifying and creating URLs */
878 static inline int needs_quote(int ch
)
880 if (((ch
>= 'A') && (ch
<= 'Z'))
881 || ((ch
>= 'a') && (ch
<= 'z'))
882 || ((ch
>= '0') && (ch
<= '9'))
890 static char *quote_ref_url(const char *base
, const char *ref
)
892 struct strbuf buf
= STRBUF_INIT
;
896 end_url_with_slash(&buf
, base
);
898 for (cp
= ref
; (ch
= *cp
) != 0; cp
++)
900 strbuf_addf(&buf
, "%%%02x", ch
);
902 strbuf_addch(&buf
, *cp
);
904 return strbuf_detach(&buf
, NULL
);
907 void append_remote_object_url(struct strbuf
*buf
, const char *url
,
909 int only_two_digit_prefix
)
911 end_url_with_slash(buf
, url
);
913 strbuf_addf(buf
, "objects/%.*s/", 2, hex
);
914 if (!only_two_digit_prefix
)
915 strbuf_addf(buf
, "%s", hex
+2);
918 char *get_remote_object_url(const char *url
, const char *hex
,
919 int only_two_digit_prefix
)
921 struct strbuf buf
= STRBUF_INIT
;
922 append_remote_object_url(&buf
, url
, hex
, only_two_digit_prefix
);
923 return strbuf_detach(&buf
, NULL
);
926 static int handle_curl_result(struct slot_results
*results
)
929 * If we see a failing http code with CURLE_OK, we have turned off
930 * FAILONERROR (to keep the server's custom error response), and should
931 * translate the code into failure here.
933 if (results
->curl_result
== CURLE_OK
&&
934 results
->http_code
>= 400) {
935 results
->curl_result
= CURLE_HTTP_RETURNED_ERROR
;
937 * Normally curl will already have put the "reason phrase"
938 * from the server into curl_errorstr; unfortunately without
939 * FAILONERROR it is lost, so we can give only the numeric
942 snprintf(curl_errorstr
, sizeof(curl_errorstr
),
943 "The requested URL returned error: %ld",
947 if (results
->curl_result
== CURLE_OK
) {
948 credential_approve(&http_auth
);
950 } else if (missing_target(results
))
951 return HTTP_MISSING_TARGET
;
952 else if (results
->http_code
== 401) {
953 if (http_auth
.username
&& http_auth
.password
) {
954 credential_reject(&http_auth
);
957 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
958 http_auth_methods
&= ~CURLAUTH_GSSNEGOTIATE
;
963 #if LIBCURL_VERSION_NUM >= 0x070c00
964 if (!curl_errorstr
[0])
965 strlcpy(curl_errorstr
,
966 curl_easy_strerror(results
->curl_result
),
967 sizeof(curl_errorstr
));
973 int run_one_slot(struct active_request_slot
*slot
,
974 struct slot_results
*results
)
976 slot
->results
= results
;
977 if (!start_active_slot(slot
)) {
978 snprintf(curl_errorstr
, sizeof(curl_errorstr
),
979 "failed to start HTTP request");
980 return HTTP_START_FAILED
;
983 run_active_slot(slot
);
984 return handle_curl_result(results
);
987 static CURLcode
curlinfo_strbuf(CURL
*curl
, CURLINFO info
, struct strbuf
*buf
)
993 ret
= curl_easy_getinfo(curl
, info
, &ptr
);
995 strbuf_addstr(buf
, ptr
);
1000 * Check for and extract a content-type parameter. "raw"
1001 * should be positioned at the start of the potential
1002 * parameter, with any whitespace already removed.
1004 * "name" is the name of the parameter. The value is appended
1007 static int extract_param(const char *raw
, const char *name
,
1010 size_t len
= strlen(name
);
1012 if (strncasecmp(raw
, name
, len
))
1020 while (*raw
&& !isspace(*raw
) && *raw
!= ';')
1021 strbuf_addch(out
, *raw
++);
1026 * Extract a normalized version of the content type, with any
1027 * spaces suppressed, all letters lowercased, and no trailing ";"
1030 * Note that we will silently remove even invalid whitespace. For
1031 * example, "text / plain" is specifically forbidden by RFC 2616,
1032 * but "text/plain" is the only reasonable output, and this keeps
1035 * If the "charset" argument is not NULL, store the value of any
1036 * charset parameter there.
1039 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1040 * "text / plain" -> "text/plain"
1042 static void extract_content_type(struct strbuf
*raw
, struct strbuf
*type
,
1043 struct strbuf
*charset
)
1048 strbuf_grow(type
, raw
->len
);
1049 for (p
= raw
->buf
; *p
; p
++) {
1056 strbuf_addch(type
, tolower(*p
));
1062 strbuf_reset(charset
);
1064 while (isspace(*p
) || *p
== ';')
1066 if (!extract_param(p
, "charset", charset
))
1068 while (*p
&& !isspace(*p
))
1072 if (!charset
->len
&& starts_with(type
->buf
, "text/"))
1073 strbuf_addstr(charset
, "ISO-8859-1");
1076 static void write_accept_language(struct strbuf
*buf
)
1079 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1080 * that, q-value will be smaller than 0.001, the minimum q-value the
1081 * HTTP specification allows. See
1082 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1084 const int MAX_DECIMAL_PLACES
= 3;
1085 const int MAX_LANGUAGE_TAGS
= 1000;
1086 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE
= 4000;
1087 char **language_tags
= NULL
;
1089 const char *s
= get_preferred_languages();
1091 struct strbuf tag
= STRBUF_INIT
;
1093 /* Don't add Accept-Language header if no language is preferred. */
1098 * Split the colon-separated string of preferred languages into
1099 * language_tags array.
1102 /* collect language tag */
1103 for (; *s
&& (isalnum(*s
) || *s
== '_'); s
++)
1104 strbuf_addch(&tag
, *s
== '_' ? '-' : *s
);
1106 /* skip .codeset, @modifier and any other unnecessary parts */
1107 while (*s
&& *s
!= ':')
1112 REALLOC_ARRAY(language_tags
, num_langs
);
1113 language_tags
[num_langs
- 1] = strbuf_detach(&tag
, NULL
);
1114 if (num_langs
>= MAX_LANGUAGE_TAGS
- 1) /* -1 for '*' */
1119 /* write Accept-Language header into buf */
1121 int last_buf_len
= 0;
1127 REALLOC_ARRAY(language_tags
, num_langs
+ 1);
1128 language_tags
[num_langs
++] = "*"; /* it's OK; this won't be freed */
1130 /* compute decimal_places */
1131 for (max_q
= 1, decimal_places
= 0;
1132 max_q
< num_langs
&& decimal_places
<= MAX_DECIMAL_PLACES
;
1133 decimal_places
++, max_q
*= 10)
1136 sprintf(q_format
, ";q=0.%%0%dd", decimal_places
);
1138 strbuf_addstr(buf
, "Accept-Language: ");
1140 for (i
= 0; i
< num_langs
; i
++) {
1142 strbuf_addstr(buf
, ", ");
1144 strbuf_addstr(buf
, language_tags
[i
]);
1147 strbuf_addf(buf
, q_format
, max_q
- i
);
1149 if (buf
->len
> MAX_ACCEPT_LANGUAGE_HEADER_SIZE
) {
1150 strbuf_remove(buf
, last_buf_len
, buf
->len
- last_buf_len
);
1154 last_buf_len
= buf
->len
;
1158 /* free language tags -- last one is a static '*' */
1159 for (i
= 0; i
< num_langs
- 1; i
++)
1160 free(language_tags
[i
]);
1161 free(language_tags
);
1165 * Get an Accept-Language header which indicates user's preferred languages.
1169 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1170 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1171 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1172 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1173 * LANGUAGE= LANG=C -> ""
1175 static const char *get_accept_language(void)
1177 if (!cached_accept_language
) {
1178 struct strbuf buf
= STRBUF_INIT
;
1179 write_accept_language(&buf
);
1181 cached_accept_language
= strbuf_detach(&buf
, NULL
);
1184 return cached_accept_language
;
1187 /* http_request() targets */
1188 #define HTTP_REQUEST_STRBUF 0
1189 #define HTTP_REQUEST_FILE 1
1191 static int http_request(const char *url
,
1192 void *result
, int target
,
1193 const struct http_get_options
*options
)
1195 struct active_request_slot
*slot
;
1196 struct slot_results results
;
1197 struct curl_slist
*headers
= NULL
;
1198 struct strbuf buf
= STRBUF_INIT
;
1199 const char *accept_language
;
1202 slot
= get_active_slot();
1203 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
1205 if (result
== NULL
) {
1206 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 1);
1208 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 0);
1209 curl_easy_setopt(slot
->curl
, CURLOPT_FILE
, result
);
1211 if (target
== HTTP_REQUEST_FILE
) {
1212 long posn
= ftell(result
);
1213 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
1216 strbuf_addf(&buf
, "Range: bytes=%ld-", posn
);
1217 headers
= curl_slist_append(headers
, buf
.buf
);
1221 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
1225 accept_language
= get_accept_language();
1227 if (accept_language
)
1228 headers
= curl_slist_append(headers
, accept_language
);
1230 strbuf_addstr(&buf
, "Pragma:");
1231 if (options
&& options
->no_cache
)
1232 strbuf_addstr(&buf
, " no-cache");
1233 if (options
&& options
->keep_error
)
1234 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 0);
1236 headers
= curl_slist_append(headers
, buf
.buf
);
1238 curl_easy_setopt(slot
->curl
, CURLOPT_URL
, url
);
1239 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, headers
);
1240 curl_easy_setopt(slot
->curl
, CURLOPT_ENCODING
, "gzip");
1242 ret
= run_one_slot(slot
, &results
);
1244 if (options
&& options
->content_type
) {
1245 struct strbuf raw
= STRBUF_INIT
;
1246 curlinfo_strbuf(slot
->curl
, CURLINFO_CONTENT_TYPE
, &raw
);
1247 extract_content_type(&raw
, options
->content_type
,
1249 strbuf_release(&raw
);
1252 if (options
&& options
->effective_url
)
1253 curlinfo_strbuf(slot
->curl
, CURLINFO_EFFECTIVE_URL
,
1254 options
->effective_url
);
1256 curl_slist_free_all(headers
);
1257 strbuf_release(&buf
);
1263 * Update the "base" url to a more appropriate value, as deduced by
1264 * redirects seen when requesting a URL starting with "url".
1266 * The "asked" parameter is a URL that we asked curl to access, and must begin
1269 * The "got" parameter is the URL that curl reported to us as where we ended
1272 * Returns 1 if we updated the base url, 0 otherwise.
1274 * Our basic strategy is to compare "base" and "asked" to find the bits
1275 * specific to our request. We then strip those bits off of "got" to yield the
1276 * new base. So for example, if our base is "http://example.com/foo.git",
1277 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1278 * with "https://other.example.com/foo.git/info/refs". We would want the
1279 * new URL to become "https://other.example.com/foo.git".
1281 * Note that this assumes a sane redirect scheme. It's entirely possible
1282 * in the example above to end up at a URL that does not even end in
1283 * "info/refs". In such a case we simply punt, as there is not much we can
1284 * do (and such a scheme is unlikely to represent a real git repository,
1285 * which means we are likely about to abort anyway).
1287 static int update_url_from_redirect(struct strbuf
*base
,
1289 const struct strbuf
*got
)
1294 if (!strcmp(asked
, got
->buf
))
1297 if (!skip_prefix(asked
, base
->buf
, &tail
))
1298 die("BUG: update_url_from_redirect: %s is not a superset of %s",
1301 tail_len
= strlen(tail
);
1303 if (got
->len
< tail_len
||
1304 strcmp(tail
, got
->buf
+ got
->len
- tail_len
))
1305 return 0; /* insane redirect scheme */
1308 strbuf_add(base
, got
->buf
, got
->len
- tail_len
);
1312 static int http_request_reauth(const char *url
,
1313 void *result
, int target
,
1314 struct http_get_options
*options
)
1316 int ret
= http_request(url
, result
, target
, options
);
1318 if (options
&& options
->effective_url
&& options
->base_url
) {
1319 if (update_url_from_redirect(options
->base_url
,
1320 url
, options
->effective_url
)) {
1321 credential_from_url(&http_auth
, options
->base_url
->buf
);
1322 url
= options
->effective_url
->buf
;
1326 if (ret
!= HTTP_REAUTH
)
1330 * If we are using KEEP_ERROR, the previous request may have
1331 * put cruft into our output stream; we should clear it out before
1332 * making our next request. We only know how to do this for
1333 * the strbuf case, but that is enough to satisfy current callers.
1335 if (options
&& options
->keep_error
) {
1337 case HTTP_REQUEST_STRBUF
:
1338 strbuf_reset(result
);
1341 die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1345 credential_fill(&http_auth
);
1347 return http_request(url
, result
, target
, options
);
1350 int http_get_strbuf(const char *url
,
1351 struct strbuf
*result
,
1352 struct http_get_options
*options
)
1354 return http_request_reauth(url
, result
, HTTP_REQUEST_STRBUF
, options
);
1358 * Downloads a URL and stores the result in the given file.
1360 * If a previous interrupted download is detected (i.e. a previous temporary
1361 * file is still around) the download is resumed.
1363 static int http_get_file(const char *url
, const char *filename
,
1364 struct http_get_options
*options
)
1367 struct strbuf tmpfile
= STRBUF_INIT
;
1370 strbuf_addf(&tmpfile
, "%s.temp", filename
);
1371 result
= fopen(tmpfile
.buf
, "a");
1373 error("Unable to open local file %s", tmpfile
.buf
);
1378 ret
= http_request_reauth(url
, result
, HTTP_REQUEST_FILE
, options
);
1381 if (ret
== HTTP_OK
&& finalize_object_file(tmpfile
.buf
, filename
))
1384 strbuf_release(&tmpfile
);
1388 int http_fetch_ref(const char *base
, struct ref
*ref
)
1390 struct http_get_options options
= {0};
1392 struct strbuf buffer
= STRBUF_INIT
;
1395 options
.no_cache
= 1;
1397 url
= quote_ref_url(base
, ref
->name
);
1398 if (http_get_strbuf(url
, &buffer
, &options
) == HTTP_OK
) {
1399 strbuf_rtrim(&buffer
);
1400 if (buffer
.len
== 40)
1401 ret
= get_sha1_hex(buffer
.buf
, ref
->old_sha1
);
1402 else if (starts_with(buffer
.buf
, "ref: ")) {
1403 ref
->symref
= xstrdup(buffer
.buf
+ 5);
1408 strbuf_release(&buffer
);
1413 /* Helpers for fetching packs */
1414 static char *fetch_pack_index(unsigned char *sha1
, const char *base_url
)
1417 struct strbuf buf
= STRBUF_INIT
;
1419 if (http_is_verbose
)
1420 fprintf(stderr
, "Getting index for pack %s\n", sha1_to_hex(sha1
));
1422 end_url_with_slash(&buf
, base_url
);
1423 strbuf_addf(&buf
, "objects/pack/pack-%s.idx", sha1_to_hex(sha1
));
1424 url
= strbuf_detach(&buf
, NULL
);
1426 strbuf_addf(&buf
, "%s.temp", sha1_pack_index_name(sha1
));
1427 tmp
= strbuf_detach(&buf
, NULL
);
1429 if (http_get_file(url
, tmp
, NULL
) != HTTP_OK
) {
1430 error("Unable to get pack index %s", url
);
1439 static int fetch_and_setup_pack_index(struct packed_git
**packs_head
,
1440 unsigned char *sha1
, const char *base_url
)
1442 struct packed_git
*new_pack
;
1443 char *tmp_idx
= NULL
;
1446 if (has_pack_index(sha1
)) {
1447 new_pack
= parse_pack_index(sha1
, sha1_pack_index_name(sha1
));
1449 return -1; /* parse_pack_index() already issued error message */
1453 tmp_idx
= fetch_pack_index(sha1
, base_url
);
1457 new_pack
= parse_pack_index(sha1
, tmp_idx
);
1462 return -1; /* parse_pack_index() already issued error message */
1465 ret
= verify_pack_index(new_pack
);
1467 close_pack_index(new_pack
);
1468 ret
= finalize_object_file(tmp_idx
, sha1_pack_index_name(sha1
));
1475 new_pack
->next
= *packs_head
;
1476 *packs_head
= new_pack
;
1480 int http_get_info_packs(const char *base_url
, struct packed_git
**packs_head
)
1482 struct http_get_options options
= {0};
1485 struct strbuf buf
= STRBUF_INIT
;
1486 unsigned char sha1
[20];
1488 end_url_with_slash(&buf
, base_url
);
1489 strbuf_addstr(&buf
, "objects/info/packs");
1490 url
= strbuf_detach(&buf
, NULL
);
1492 options
.no_cache
= 1;
1493 ret
= http_get_strbuf(url
, &buf
, &options
);
1498 while (i
< buf
.len
) {
1502 if (i
+ 52 <= buf
.len
&&
1503 starts_with(data
+ i
, " pack-") &&
1504 starts_with(data
+ i
+ 46, ".pack\n")) {
1505 get_sha1_hex(data
+ i
+ 6, sha1
);
1506 fetch_and_setup_pack_index(packs_head
, sha1
,
1512 while (i
< buf
.len
&& data
[i
] != '\n')
1523 void release_http_pack_request(struct http_pack_request
*preq
)
1525 if (preq
->packfile
!= NULL
) {
1526 fclose(preq
->packfile
);
1527 preq
->packfile
= NULL
;
1529 if (preq
->range_header
!= NULL
) {
1530 curl_slist_free_all(preq
->range_header
);
1531 preq
->range_header
= NULL
;
1538 int finish_http_pack_request(struct http_pack_request
*preq
)
1540 struct packed_git
**lst
;
1541 struct packed_git
*p
= preq
->target
;
1543 struct child_process ip
= CHILD_PROCESS_INIT
;
1544 const char *ip_argv
[8];
1546 close_pack_index(p
);
1548 fclose(preq
->packfile
);
1549 preq
->packfile
= NULL
;
1553 lst
= &((*lst
)->next
);
1554 *lst
= (*lst
)->next
;
1556 tmp_idx
= xstrdup(preq
->tmpfile
);
1557 strcpy(tmp_idx
+ strlen(tmp_idx
) - strlen(".pack.temp"),
1560 ip_argv
[0] = "index-pack";
1562 ip_argv
[2] = tmp_idx
;
1563 ip_argv
[3] = preq
->tmpfile
;
1571 if (run_command(&ip
)) {
1572 unlink(preq
->tmpfile
);
1578 unlink(sha1_pack_index_name(p
->sha1
));
1580 if (finalize_object_file(preq
->tmpfile
, sha1_pack_name(p
->sha1
))
1581 || finalize_object_file(tmp_idx
, sha1_pack_index_name(p
->sha1
))) {
1586 install_packed_git(p
);
1591 struct http_pack_request
*new_http_pack_request(
1592 struct packed_git
*target
, const char *base_url
)
1595 char range
[RANGE_HEADER_SIZE
];
1596 struct strbuf buf
= STRBUF_INIT
;
1597 struct http_pack_request
*preq
;
1599 preq
= xcalloc(1, sizeof(*preq
));
1600 preq
->target
= target
;
1602 end_url_with_slash(&buf
, base_url
);
1603 strbuf_addf(&buf
, "objects/pack/pack-%s.pack",
1604 sha1_to_hex(target
->sha1
));
1605 preq
->url
= strbuf_detach(&buf
, NULL
);
1607 snprintf(preq
->tmpfile
, sizeof(preq
->tmpfile
), "%s.temp",
1608 sha1_pack_name(target
->sha1
));
1609 preq
->packfile
= fopen(preq
->tmpfile
, "a");
1610 if (!preq
->packfile
) {
1611 error("Unable to open local file %s for pack",
1616 preq
->slot
= get_active_slot();
1617 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_FILE
, preq
->packfile
);
1618 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite
);
1619 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_URL
, preq
->url
);
1620 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_HTTPHEADER
,
1624 * If there is data present from a previous transfer attempt,
1625 * resume where it left off
1627 prev_posn
= ftell(preq
->packfile
);
1629 if (http_is_verbose
)
1631 "Resuming fetch of pack %s at byte %ld\n",
1632 sha1_to_hex(target
->sha1
), prev_posn
);
1633 sprintf(range
, "Range: bytes=%ld-", prev_posn
);
1634 preq
->range_header
= curl_slist_append(NULL
, range
);
1635 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_HTTPHEADER
,
1636 preq
->range_header
);
1647 /* Helpers for fetching objects (loose) */
1648 static size_t fwrite_sha1_file(char *ptr
, size_t eltsize
, size_t nmemb
,
1651 unsigned char expn
[4096];
1652 size_t size
= eltsize
* nmemb
;
1654 struct http_object_request
*freq
=
1655 (struct http_object_request
*)data
;
1657 ssize_t retval
= xwrite(freq
->localfile
,
1658 (char *) ptr
+ posn
, size
- posn
);
1662 } while (posn
< size
);
1664 freq
->stream
.avail_in
= size
;
1665 freq
->stream
.next_in
= (void *)ptr
;
1667 freq
->stream
.next_out
= expn
;
1668 freq
->stream
.avail_out
= sizeof(expn
);
1669 freq
->zret
= git_inflate(&freq
->stream
, Z_SYNC_FLUSH
);
1670 git_SHA1_Update(&freq
->c
, expn
,
1671 sizeof(expn
) - freq
->stream
.avail_out
);
1672 } while (freq
->stream
.avail_in
&& freq
->zret
== Z_OK
);
1676 struct http_object_request
*new_http_object_request(const char *base_url
,
1677 unsigned char *sha1
)
1679 char *hex
= sha1_to_hex(sha1
);
1680 const char *filename
;
1681 char prevfile
[PATH_MAX
];
1683 char prev_buf
[PREV_BUF_SIZE
];
1684 ssize_t prev_read
= 0;
1686 char range
[RANGE_HEADER_SIZE
];
1687 struct curl_slist
*range_header
= NULL
;
1688 struct http_object_request
*freq
;
1690 freq
= xcalloc(1, sizeof(*freq
));
1691 hashcpy(freq
->sha1
, sha1
);
1692 freq
->localfile
= -1;
1694 filename
= sha1_file_name(sha1
);
1695 snprintf(freq
->tmpfile
, sizeof(freq
->tmpfile
),
1696 "%s.temp", filename
);
1698 snprintf(prevfile
, sizeof(prevfile
), "%s.prev", filename
);
1699 unlink_or_warn(prevfile
);
1700 rename(freq
->tmpfile
, prevfile
);
1701 unlink_or_warn(freq
->tmpfile
);
1703 if (freq
->localfile
!= -1)
1704 error("fd leakage in start: %d", freq
->localfile
);
1705 freq
->localfile
= open(freq
->tmpfile
,
1706 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
1708 * This could have failed due to the "lazy directory creation";
1709 * try to mkdir the last path component.
1711 if (freq
->localfile
< 0 && errno
== ENOENT
) {
1712 char *dir
= strrchr(freq
->tmpfile
, '/');
1715 mkdir(freq
->tmpfile
, 0777);
1718 freq
->localfile
= open(freq
->tmpfile
,
1719 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
1722 if (freq
->localfile
< 0) {
1723 error("Couldn't create temporary file %s: %s",
1724 freq
->tmpfile
, strerror(errno
));
1728 git_inflate_init(&freq
->stream
);
1730 git_SHA1_Init(&freq
->c
);
1732 freq
->url
= get_remote_object_url(base_url
, hex
, 0);
1735 * If a previous temp file is present, process what was already
1738 prevlocal
= open(prevfile
, O_RDONLY
);
1739 if (prevlocal
!= -1) {
1741 prev_read
= xread(prevlocal
, prev_buf
, PREV_BUF_SIZE
);
1743 if (fwrite_sha1_file(prev_buf
,
1746 freq
) == prev_read
) {
1747 prev_posn
+= prev_read
;
1752 } while (prev_read
> 0);
1755 unlink_or_warn(prevfile
);
1758 * Reset inflate/SHA1 if there was an error reading the previous temp
1759 * file; also rewind to the beginning of the local file.
1761 if (prev_read
== -1) {
1762 memset(&freq
->stream
, 0, sizeof(freq
->stream
));
1763 git_inflate_init(&freq
->stream
);
1764 git_SHA1_Init(&freq
->c
);
1767 lseek(freq
->localfile
, 0, SEEK_SET
);
1768 if (ftruncate(freq
->localfile
, 0) < 0) {
1769 error("Couldn't truncate temporary file %s: %s",
1770 freq
->tmpfile
, strerror(errno
));
1776 freq
->slot
= get_active_slot();
1778 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_FILE
, freq
);
1779 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite_sha1_file
);
1780 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_ERRORBUFFER
, freq
->errorstr
);
1781 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_URL
, freq
->url
);
1782 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_HTTPHEADER
, no_pragma_header
);
1785 * If we have successfully processed data from a previous fetch
1786 * attempt, only fetch the data we don't already have.
1789 if (http_is_verbose
)
1791 "Resuming fetch of object %s at byte %ld\n",
1793 sprintf(range
, "Range: bytes=%ld-", prev_posn
);
1794 range_header
= curl_slist_append(range_header
, range
);
1795 curl_easy_setopt(freq
->slot
->curl
,
1796 CURLOPT_HTTPHEADER
, range_header
);
1807 void process_http_object_request(struct http_object_request
*freq
)
1809 if (freq
->slot
== NULL
)
1811 freq
->curl_result
= freq
->slot
->curl_result
;
1812 freq
->http_code
= freq
->slot
->http_code
;
1816 int finish_http_object_request(struct http_object_request
*freq
)
1820 close(freq
->localfile
);
1821 freq
->localfile
= -1;
1823 process_http_object_request(freq
);
1825 if (freq
->http_code
== 416) {
1826 warning("requested range invalid; we may already have all the data.");
1827 } else if (freq
->curl_result
!= CURLE_OK
) {
1828 if (stat(freq
->tmpfile
, &st
) == 0)
1829 if (st
.st_size
== 0)
1830 unlink_or_warn(freq
->tmpfile
);
1834 git_inflate_end(&freq
->stream
);
1835 git_SHA1_Final(freq
->real_sha1
, &freq
->c
);
1836 if (freq
->zret
!= Z_STREAM_END
) {
1837 unlink_or_warn(freq
->tmpfile
);
1840 if (hashcmp(freq
->sha1
, freq
->real_sha1
)) {
1841 unlink_or_warn(freq
->tmpfile
);
1845 finalize_object_file(freq
->tmpfile
, sha1_file_name(freq
->sha1
));
1847 return freq
->rename
;
1850 void abort_http_object_request(struct http_object_request
*freq
)
1852 unlink_or_warn(freq
->tmpfile
);
1854 release_http_object_request(freq
);
1857 void release_http_object_request(struct http_object_request
*freq
)
1859 if (freq
->localfile
!= -1) {
1860 close(freq
->localfile
);
1861 freq
->localfile
= -1;
1863 if (freq
->url
!= NULL
) {
1867 if (freq
->slot
!= NULL
) {
1868 freq
->slot
->callback_func
= NULL
;
1869 freq
->slot
->callback_data
= NULL
;
1870 release_active_slot(freq
->slot
);