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 static void xmulti_remove_handle(struct active_request_slot
*slot
)
172 #ifdef USE_CURL_MULTI
173 curl_multi_remove_handle(curlm
, slot
->curl
);
177 #ifdef USE_CURL_MULTI
178 static void process_curl_messages(void)
181 struct active_request_slot
*slot
;
182 CURLMsg
*curl_message
= curl_multi_info_read(curlm
, &num_messages
);
184 while (curl_message
!= NULL
) {
185 if (curl_message
->msg
== CURLMSG_DONE
) {
186 int curl_result
= curl_message
->data
.result
;
187 slot
= active_queue_head
;
188 while (slot
!= NULL
&&
189 slot
->curl
!= curl_message
->easy_handle
)
192 xmulti_remove_handle(slot
);
193 slot
->curl_result
= curl_result
;
194 finish_active_slot(slot
);
196 fprintf(stderr
, "Received DONE message for unknown request!\n");
199 fprintf(stderr
, "Unknown CURL message received: %d\n",
200 (int)curl_message
->msg
);
202 curl_message
= curl_multi_info_read(curlm
, &num_messages
);
207 static int http_options(const char *var
, const char *value
, void *cb
)
209 if (!strcmp("http.sslverify", var
)) {
210 curl_ssl_verify
= git_config_bool(var
, value
);
213 if (!strcmp("http.sslcipherlist", var
))
214 return git_config_string(&ssl_cipherlist
, var
, value
);
215 if (!strcmp("http.sslversion", var
))
216 return git_config_string(&ssl_version
, var
, value
);
217 if (!strcmp("http.sslcert", var
))
218 return git_config_string(&ssl_cert
, var
, value
);
219 #if LIBCURL_VERSION_NUM >= 0x070903
220 if (!strcmp("http.sslkey", var
))
221 return git_config_string(&ssl_key
, var
, value
);
223 #if LIBCURL_VERSION_NUM >= 0x070908
224 if (!strcmp("http.sslcapath", var
))
225 return git_config_pathname(&ssl_capath
, var
, value
);
227 if (!strcmp("http.sslcainfo", var
))
228 return git_config_pathname(&ssl_cainfo
, var
, value
);
229 if (!strcmp("http.sslcertpasswordprotected", var
)) {
230 ssl_cert_password_required
= git_config_bool(var
, value
);
233 if (!strcmp("http.ssltry", var
)) {
234 curl_ssl_try
= git_config_bool(var
, value
);
237 if (!strcmp("http.minsessions", var
)) {
238 min_curl_sessions
= git_config_int(var
, value
);
239 #ifndef USE_CURL_MULTI
240 if (min_curl_sessions
> 1)
241 min_curl_sessions
= 1;
245 #ifdef USE_CURL_MULTI
246 if (!strcmp("http.maxrequests", var
)) {
247 max_requests
= git_config_int(var
, value
);
251 if (!strcmp("http.lowspeedlimit", var
)) {
252 curl_low_speed_limit
= (long)git_config_int(var
, value
);
255 if (!strcmp("http.lowspeedtime", var
)) {
256 curl_low_speed_time
= (long)git_config_int(var
, value
);
260 if (!strcmp("http.noepsv", var
)) {
261 curl_ftp_no_epsv
= git_config_bool(var
, value
);
264 if (!strcmp("http.proxy", var
))
265 return git_config_string(&curl_http_proxy
, var
, value
);
267 if (!strcmp("http.cookiefile", var
))
268 return git_config_string(&curl_cookie_file
, var
, value
);
269 if (!strcmp("http.savecookies", var
)) {
270 curl_save_cookies
= git_config_bool(var
, value
);
274 if (!strcmp("http.postbuffer", var
)) {
275 http_post_buffer
= git_config_int(var
, value
);
276 if (http_post_buffer
< LARGE_PACKET_MAX
)
277 http_post_buffer
= LARGE_PACKET_MAX
;
281 if (!strcmp("http.useragent", var
))
282 return git_config_string(&user_agent
, var
, value
);
284 /* Fall back on the default ones */
285 return git_default_config(var
, value
, cb
);
288 static void init_curl_http_auth(CURL
*result
)
290 if (!http_auth
.username
)
293 credential_fill(&http_auth
);
295 #if LIBCURL_VERSION_NUM >= 0x071301
296 curl_easy_setopt(result
, CURLOPT_USERNAME
, http_auth
.username
);
297 curl_easy_setopt(result
, CURLOPT_PASSWORD
, http_auth
.password
);
300 static struct strbuf up
= STRBUF_INIT
;
302 * Note that we assume we only ever have a single set of
303 * credentials in a given program run, so we do not have
304 * to worry about updating this buffer, only setting its
308 strbuf_addf(&up
, "%s:%s",
309 http_auth
.username
, http_auth
.password
);
310 curl_easy_setopt(result
, CURLOPT_USERPWD
, up
.buf
);
315 static int has_cert_password(void)
317 if (ssl_cert
== NULL
|| ssl_cert_password_required
!= 1)
319 if (!cert_auth
.password
) {
320 cert_auth
.protocol
= xstrdup("cert");
321 cert_auth
.username
= xstrdup("");
322 cert_auth
.path
= xstrdup(ssl_cert
);
323 credential_fill(&cert_auth
);
328 #if LIBCURL_VERSION_NUM >= 0x071900
329 static void set_curl_keepalive(CURL
*c
)
331 curl_easy_setopt(c
, CURLOPT_TCP_KEEPALIVE
, 1);
334 #elif LIBCURL_VERSION_NUM >= 0x071000
335 static int sockopt_callback(void *client
, curl_socket_t fd
, curlsocktype type
)
339 socklen_t len
= (socklen_t
)sizeof(ka
);
341 if (type
!= CURLSOCKTYPE_IPCXN
)
344 rc
= setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (void *)&ka
, len
);
346 warning("unable to set SO_KEEPALIVE on socket %s",
349 return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
352 static void set_curl_keepalive(CURL
*c
)
354 curl_easy_setopt(c
, CURLOPT_SOCKOPTFUNCTION
, sockopt_callback
);
358 static void set_curl_keepalive(CURL
*c
)
360 /* not supported on older curl versions */
364 static CURL
*get_curl_handle(void)
366 CURL
*result
= curl_easy_init();
367 long allowed_protocols
= 0;
370 die("curl_easy_init failed");
372 if (!curl_ssl_verify
) {
373 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 0);
374 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 0);
376 /* Verify authenticity of the peer's certificate */
377 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 1);
378 /* The name in the cert must match whom we tried to connect */
379 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 2);
382 #if LIBCURL_VERSION_NUM >= 0x070907
383 curl_easy_setopt(result
, CURLOPT_NETRC
, CURL_NETRC_OPTIONAL
);
385 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
386 curl_easy_setopt(result
, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
389 if (http_proactive_auth
)
390 init_curl_http_auth(result
);
392 if (getenv("GIT_SSL_VERSION"))
393 ssl_version
= getenv("GIT_SSL_VERSION");
394 if (ssl_version
&& *ssl_version
) {
396 for (i
= 0; i
< ARRAY_SIZE(sslversions
); i
++) {
397 if (!strcmp(ssl_version
, sslversions
[i
].name
)) {
398 curl_easy_setopt(result
, CURLOPT_SSLVERSION
,
399 sslversions
[i
].ssl_version
);
403 if (i
== ARRAY_SIZE(sslversions
))
404 warning("unsupported ssl version %s: using default",
408 if (getenv("GIT_SSL_CIPHER_LIST"))
409 ssl_cipherlist
= getenv("GIT_SSL_CIPHER_LIST");
410 if (ssl_cipherlist
!= NULL
&& *ssl_cipherlist
)
411 curl_easy_setopt(result
, CURLOPT_SSL_CIPHER_LIST
,
414 if (ssl_cert
!= NULL
)
415 curl_easy_setopt(result
, CURLOPT_SSLCERT
, ssl_cert
);
416 if (has_cert_password())
417 curl_easy_setopt(result
, CURLOPT_KEYPASSWD
, cert_auth
.password
);
418 #if LIBCURL_VERSION_NUM >= 0x070903
420 curl_easy_setopt(result
, CURLOPT_SSLKEY
, ssl_key
);
422 #if LIBCURL_VERSION_NUM >= 0x070908
423 if (ssl_capath
!= NULL
)
424 curl_easy_setopt(result
, CURLOPT_CAPATH
, ssl_capath
);
426 if (ssl_cainfo
!= NULL
)
427 curl_easy_setopt(result
, CURLOPT_CAINFO
, ssl_cainfo
);
429 if (curl_low_speed_limit
> 0 && curl_low_speed_time
> 0) {
430 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_LIMIT
,
431 curl_low_speed_limit
);
432 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_TIME
,
433 curl_low_speed_time
);
436 curl_easy_setopt(result
, CURLOPT_FOLLOWLOCATION
, 1);
437 curl_easy_setopt(result
, CURLOPT_MAXREDIRS
, 20);
438 #if LIBCURL_VERSION_NUM >= 0x071301
439 curl_easy_setopt(result
, CURLOPT_POSTREDIR
, CURL_REDIR_POST_ALL
);
440 #elif LIBCURL_VERSION_NUM >= 0x071101
441 curl_easy_setopt(result
, CURLOPT_POST301
, 1);
443 #if LIBCURL_VERSION_NUM >= 0x071304
444 if (is_transport_allowed("http"))
445 allowed_protocols
|= CURLPROTO_HTTP
;
446 if (is_transport_allowed("https"))
447 allowed_protocols
|= CURLPROTO_HTTPS
;
448 if (is_transport_allowed("ftp"))
449 allowed_protocols
|= CURLPROTO_FTP
;
450 if (is_transport_allowed("ftps"))
451 allowed_protocols
|= CURLPROTO_FTPS
;
452 curl_easy_setopt(result
, CURLOPT_REDIR_PROTOCOLS
, allowed_protocols
);
454 if (transport_restrict_protocols())
455 warning("protocol restrictions not applied to curl redirects because\n"
456 "your curl version is too old (>= 7.19.4)");
459 if (getenv("GIT_CURL_VERBOSE"))
460 curl_easy_setopt(result
, CURLOPT_VERBOSE
, 1);
462 curl_easy_setopt(result
, CURLOPT_USERAGENT
,
463 user_agent
? user_agent
: git_user_agent());
465 if (curl_ftp_no_epsv
)
466 curl_easy_setopt(result
, CURLOPT_FTP_USE_EPSV
, 0);
468 #ifdef CURLOPT_USE_SSL
470 curl_easy_setopt(result
, CURLOPT_USE_SSL
, CURLUSESSL_TRY
);
473 if (curl_http_proxy
) {
474 curl_easy_setopt(result
, CURLOPT_PROXY
, curl_http_proxy
);
475 #if LIBCURL_VERSION_NUM >= 0x071800
476 if (starts_with(curl_http_proxy
, "socks5"))
477 curl_easy_setopt(result
,
478 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5
);
479 else if (starts_with(curl_http_proxy
, "socks4a"))
480 curl_easy_setopt(result
,
481 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4A
);
482 else if (starts_with(curl_http_proxy
, "socks"))
483 curl_easy_setopt(result
,
484 CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS4
);
487 #if LIBCURL_VERSION_NUM >= 0x070a07
488 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
, CURLAUTH_ANY
);
491 set_curl_keepalive(result
);
496 static void set_from_env(const char **var
, const char *envname
)
498 const char *val
= getenv(envname
);
503 void http_init(struct remote
*remote
, const char *url
, int proactive_auth
)
505 char *low_speed_limit
;
506 char *low_speed_time
;
507 char *normalized_url
;
508 struct urlmatch_config config
= { STRING_LIST_INIT_DUP
};
510 config
.section
= "http";
512 config
.collect_fn
= http_options
;
513 config
.cascade_fn
= git_default_config
;
517 normalized_url
= url_normalize(url
, &config
.url
);
519 git_config(urlmatch_config_entry
, &config
);
520 free(normalized_url
);
522 if (curl_global_init(CURL_GLOBAL_ALL
) != CURLE_OK
)
523 die("curl_global_init failed");
525 http_proactive_auth
= proactive_auth
;
527 if (remote
&& remote
->http_proxy
)
528 curl_http_proxy
= xstrdup(remote
->http_proxy
);
530 pragma_header
= curl_slist_append(pragma_header
, "Pragma: no-cache");
531 no_pragma_header
= curl_slist_append(no_pragma_header
, "Pragma:");
533 #ifdef USE_CURL_MULTI
535 char *http_max_requests
= getenv("GIT_HTTP_MAX_REQUESTS");
536 if (http_max_requests
!= NULL
)
537 max_requests
= atoi(http_max_requests
);
540 curlm
= curl_multi_init();
542 die("curl_multi_init failed");
545 if (getenv("GIT_SSL_NO_VERIFY"))
548 set_from_env(&ssl_cert
, "GIT_SSL_CERT");
549 #if LIBCURL_VERSION_NUM >= 0x070903
550 set_from_env(&ssl_key
, "GIT_SSL_KEY");
552 #if LIBCURL_VERSION_NUM >= 0x070908
553 set_from_env(&ssl_capath
, "GIT_SSL_CAPATH");
555 set_from_env(&ssl_cainfo
, "GIT_SSL_CAINFO");
557 set_from_env(&user_agent
, "GIT_HTTP_USER_AGENT");
559 low_speed_limit
= getenv("GIT_HTTP_LOW_SPEED_LIMIT");
560 if (low_speed_limit
!= NULL
)
561 curl_low_speed_limit
= strtol(low_speed_limit
, NULL
, 10);
562 low_speed_time
= getenv("GIT_HTTP_LOW_SPEED_TIME");
563 if (low_speed_time
!= NULL
)
564 curl_low_speed_time
= strtol(low_speed_time
, NULL
, 10);
566 if (curl_ssl_verify
== -1)
569 curl_session_count
= 0;
570 #ifdef USE_CURL_MULTI
571 if (max_requests
< 1)
572 max_requests
= DEFAULT_MAX_REQUESTS
;
575 if (getenv("GIT_CURL_FTP_NO_EPSV"))
576 curl_ftp_no_epsv
= 1;
579 credential_from_url(&http_auth
, url
);
580 if (!ssl_cert_password_required
&&
581 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
582 starts_with(url
, "https://"))
583 ssl_cert_password_required
= 1;
586 #ifndef NO_CURL_EASY_DUPHANDLE
587 curl_default
= get_curl_handle();
591 void http_cleanup(void)
593 struct active_request_slot
*slot
= active_queue_head
;
595 while (slot
!= NULL
) {
596 struct active_request_slot
*next
= slot
->next
;
597 if (slot
->curl
!= NULL
) {
598 xmulti_remove_handle(slot
);
599 curl_easy_cleanup(slot
->curl
);
604 active_queue_head
= NULL
;
606 #ifndef NO_CURL_EASY_DUPHANDLE
607 curl_easy_cleanup(curl_default
);
610 #ifdef USE_CURL_MULTI
611 curl_multi_cleanup(curlm
);
613 curl_global_cleanup();
615 curl_slist_free_all(pragma_header
);
616 pragma_header
= NULL
;
618 curl_slist_free_all(no_pragma_header
);
619 no_pragma_header
= NULL
;
621 if (curl_http_proxy
) {
622 free((void *)curl_http_proxy
);
623 curl_http_proxy
= NULL
;
626 if (cert_auth
.password
!= NULL
) {
627 memset(cert_auth
.password
, 0, strlen(cert_auth
.password
));
628 free(cert_auth
.password
);
629 cert_auth
.password
= NULL
;
631 ssl_cert_password_required
= 0;
633 free(cached_accept_language
);
634 cached_accept_language
= NULL
;
637 struct active_request_slot
*get_active_slot(void)
639 struct active_request_slot
*slot
= active_queue_head
;
640 struct active_request_slot
*newslot
;
642 #ifdef USE_CURL_MULTI
645 /* Wait for a slot to open up if the queue is full */
646 while (active_requests
>= max_requests
) {
647 curl_multi_perform(curlm
, &num_transfers
);
648 if (num_transfers
< active_requests
)
649 process_curl_messages();
653 while (slot
!= NULL
&& slot
->in_use
)
657 newslot
= xmalloc(sizeof(*newslot
));
658 newslot
->curl
= NULL
;
660 newslot
->next
= NULL
;
662 slot
= active_queue_head
;
664 active_queue_head
= newslot
;
666 while (slot
->next
!= NULL
)
668 slot
->next
= newslot
;
673 if (slot
->curl
== NULL
) {
674 #ifdef NO_CURL_EASY_DUPHANDLE
675 slot
->curl
= get_curl_handle();
677 slot
->curl
= curl_easy_duphandle(curl_default
);
679 curl_session_count
++;
684 slot
->results
= NULL
;
685 slot
->finished
= NULL
;
686 slot
->callback_data
= NULL
;
687 slot
->callback_func
= NULL
;
688 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEFILE
, curl_cookie_file
);
689 if (curl_save_cookies
)
690 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEJAR
, curl_cookie_file
);
691 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, pragma_header
);
692 curl_easy_setopt(slot
->curl
, CURLOPT_ERRORBUFFER
, curl_errorstr
);
693 curl_easy_setopt(slot
->curl
, CURLOPT_CUSTOMREQUEST
, NULL
);
694 curl_easy_setopt(slot
->curl
, CURLOPT_READFUNCTION
, NULL
);
695 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
, NULL
);
696 curl_easy_setopt(slot
->curl
, CURLOPT_POSTFIELDS
, NULL
);
697 curl_easy_setopt(slot
->curl
, CURLOPT_UPLOAD
, 0);
698 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
699 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 1);
700 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
701 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPAUTH
, http_auth_methods
);
703 if (http_auth
.password
)
704 init_curl_http_auth(slot
->curl
);
709 int start_active_slot(struct active_request_slot
*slot
)
711 #ifdef USE_CURL_MULTI
712 CURLMcode curlm_result
= curl_multi_add_handle(curlm
, slot
->curl
);
715 if (curlm_result
!= CURLM_OK
&&
716 curlm_result
!= CURLM_CALL_MULTI_PERFORM
) {
717 warning("curl_multi_add_handle failed: %s",
718 curl_multi_strerror(curlm_result
));
725 * We know there must be something to do, since we just added
728 curl_multi_perform(curlm
, &num_transfers
);
733 #ifdef USE_CURL_MULTI
737 struct fill_chain
*next
;
740 static struct fill_chain
*fill_cfg
;
742 void add_fill_function(void *data
, int (*fill
)(void *))
744 struct fill_chain
*new = xmalloc(sizeof(*new));
745 struct fill_chain
**linkp
= &fill_cfg
;
750 linkp
= &(*linkp
)->next
;
754 void fill_active_slots(void)
756 struct active_request_slot
*slot
= active_queue_head
;
758 while (active_requests
< max_requests
) {
759 struct fill_chain
*fill
;
760 for (fill
= fill_cfg
; fill
; fill
= fill
->next
)
761 if (fill
->fill(fill
->data
))
768 while (slot
!= NULL
) {
769 if (!slot
->in_use
&& slot
->curl
!= NULL
770 && curl_session_count
> min_curl_sessions
) {
771 curl_easy_cleanup(slot
->curl
);
773 curl_session_count
--;
779 void step_active_slots(void)
782 CURLMcode curlm_result
;
785 curlm_result
= curl_multi_perform(curlm
, &num_transfers
);
786 } while (curlm_result
== CURLM_CALL_MULTI_PERFORM
);
787 if (num_transfers
< active_requests
) {
788 process_curl_messages();
794 void run_active_slot(struct active_request_slot
*slot
)
796 #ifdef USE_CURL_MULTI
801 struct timeval select_timeout
;
804 slot
->finished
= &finished
;
809 #if LIBCURL_VERSION_NUM >= 0x070f04
811 curl_multi_timeout(curlm
, &curl_timeout
);
812 if (curl_timeout
== 0) {
814 } else if (curl_timeout
== -1) {
815 select_timeout
.tv_sec
= 0;
816 select_timeout
.tv_usec
= 50000;
818 select_timeout
.tv_sec
= curl_timeout
/ 1000;
819 select_timeout
.tv_usec
= (curl_timeout
% 1000) * 1000;
822 select_timeout
.tv_sec
= 0;
823 select_timeout
.tv_usec
= 50000;
830 curl_multi_fdset(curlm
, &readfds
, &writefds
, &excfds
, &max_fd
);
833 * It can happen that curl_multi_timeout returns a pathologically
834 * long timeout when curl_multi_fdset returns no file descriptors
835 * to read. See commit message for more details.
838 (select_timeout
.tv_sec
> 0 ||
839 select_timeout
.tv_usec
> 50000)) {
840 select_timeout
.tv_sec
= 0;
841 select_timeout
.tv_usec
= 50000;
844 select(max_fd
+1, &readfds
, &writefds
, &excfds
, &select_timeout
);
848 while (slot
->in_use
) {
849 slot
->curl_result
= curl_easy_perform(slot
->curl
);
850 finish_active_slot(slot
);
855 static void release_active_slot(struct active_request_slot
*slot
)
857 closedown_active_slot(slot
);
858 if (slot
->curl
&& curl_session_count
> min_curl_sessions
) {
859 xmulti_remove_handle(slot
);
860 curl_easy_cleanup(slot
->curl
);
862 curl_session_count
--;
864 #ifdef USE_CURL_MULTI
869 void finish_all_active_slots(void)
871 struct active_request_slot
*slot
= active_queue_head
;
875 run_active_slot(slot
);
876 slot
= active_queue_head
;
882 /* Helpers for modifying and creating URLs */
883 static inline int needs_quote(int ch
)
885 if (((ch
>= 'A') && (ch
<= 'Z'))
886 || ((ch
>= 'a') && (ch
<= 'z'))
887 || ((ch
>= '0') && (ch
<= '9'))
895 static char *quote_ref_url(const char *base
, const char *ref
)
897 struct strbuf buf
= STRBUF_INIT
;
901 end_url_with_slash(&buf
, base
);
903 for (cp
= ref
; (ch
= *cp
) != 0; cp
++)
905 strbuf_addf(&buf
, "%%%02x", ch
);
907 strbuf_addch(&buf
, *cp
);
909 return strbuf_detach(&buf
, NULL
);
912 void append_remote_object_url(struct strbuf
*buf
, const char *url
,
914 int only_two_digit_prefix
)
916 end_url_with_slash(buf
, url
);
918 strbuf_addf(buf
, "objects/%.*s/", 2, hex
);
919 if (!only_two_digit_prefix
)
920 strbuf_addf(buf
, "%s", hex
+2);
923 char *get_remote_object_url(const char *url
, const char *hex
,
924 int only_two_digit_prefix
)
926 struct strbuf buf
= STRBUF_INIT
;
927 append_remote_object_url(&buf
, url
, hex
, only_two_digit_prefix
);
928 return strbuf_detach(&buf
, NULL
);
931 static int handle_curl_result(struct slot_results
*results
)
934 * If we see a failing http code with CURLE_OK, we have turned off
935 * FAILONERROR (to keep the server's custom error response), and should
936 * translate the code into failure here.
938 if (results
->curl_result
== CURLE_OK
&&
939 results
->http_code
>= 400) {
940 results
->curl_result
= CURLE_HTTP_RETURNED_ERROR
;
942 * Normally curl will already have put the "reason phrase"
943 * from the server into curl_errorstr; unfortunately without
944 * FAILONERROR it is lost, so we can give only the numeric
947 snprintf(curl_errorstr
, sizeof(curl_errorstr
),
948 "The requested URL returned error: %ld",
952 if (results
->curl_result
== CURLE_OK
) {
953 credential_approve(&http_auth
);
955 } else if (missing_target(results
))
956 return HTTP_MISSING_TARGET
;
957 else if (results
->http_code
== 401) {
958 if (http_auth
.username
&& http_auth
.password
) {
959 credential_reject(&http_auth
);
962 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
963 http_auth_methods
&= ~CURLAUTH_GSSNEGOTIATE
;
968 #if LIBCURL_VERSION_NUM >= 0x070c00
969 if (!curl_errorstr
[0])
970 strlcpy(curl_errorstr
,
971 curl_easy_strerror(results
->curl_result
),
972 sizeof(curl_errorstr
));
978 int run_one_slot(struct active_request_slot
*slot
,
979 struct slot_results
*results
)
981 slot
->results
= results
;
982 if (!start_active_slot(slot
)) {
983 snprintf(curl_errorstr
, sizeof(curl_errorstr
),
984 "failed to start HTTP request");
985 return HTTP_START_FAILED
;
988 run_active_slot(slot
);
989 return handle_curl_result(results
);
992 static CURLcode
curlinfo_strbuf(CURL
*curl
, CURLINFO info
, struct strbuf
*buf
)
998 ret
= curl_easy_getinfo(curl
, info
, &ptr
);
1000 strbuf_addstr(buf
, ptr
);
1005 * Check for and extract a content-type parameter. "raw"
1006 * should be positioned at the start of the potential
1007 * parameter, with any whitespace already removed.
1009 * "name" is the name of the parameter. The value is appended
1012 static int extract_param(const char *raw
, const char *name
,
1015 size_t len
= strlen(name
);
1017 if (strncasecmp(raw
, name
, len
))
1025 while (*raw
&& !isspace(*raw
) && *raw
!= ';')
1026 strbuf_addch(out
, *raw
++);
1031 * Extract a normalized version of the content type, with any
1032 * spaces suppressed, all letters lowercased, and no trailing ";"
1035 * Note that we will silently remove even invalid whitespace. For
1036 * example, "text / plain" is specifically forbidden by RFC 2616,
1037 * but "text/plain" is the only reasonable output, and this keeps
1040 * If the "charset" argument is not NULL, store the value of any
1041 * charset parameter there.
1044 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1045 * "text / plain" -> "text/plain"
1047 static void extract_content_type(struct strbuf
*raw
, struct strbuf
*type
,
1048 struct strbuf
*charset
)
1053 strbuf_grow(type
, raw
->len
);
1054 for (p
= raw
->buf
; *p
; p
++) {
1061 strbuf_addch(type
, tolower(*p
));
1067 strbuf_reset(charset
);
1069 while (isspace(*p
) || *p
== ';')
1071 if (!extract_param(p
, "charset", charset
))
1073 while (*p
&& !isspace(*p
))
1077 if (!charset
->len
&& starts_with(type
->buf
, "text/"))
1078 strbuf_addstr(charset
, "ISO-8859-1");
1081 static void write_accept_language(struct strbuf
*buf
)
1084 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1085 * that, q-value will be smaller than 0.001, the minimum q-value the
1086 * HTTP specification allows. See
1087 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1089 const int MAX_DECIMAL_PLACES
= 3;
1090 const int MAX_LANGUAGE_TAGS
= 1000;
1091 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE
= 4000;
1092 char **language_tags
= NULL
;
1094 const char *s
= get_preferred_languages();
1096 struct strbuf tag
= STRBUF_INIT
;
1098 /* Don't add Accept-Language header if no language is preferred. */
1103 * Split the colon-separated string of preferred languages into
1104 * language_tags array.
1107 /* collect language tag */
1108 for (; *s
&& (isalnum(*s
) || *s
== '_'); s
++)
1109 strbuf_addch(&tag
, *s
== '_' ? '-' : *s
);
1111 /* skip .codeset, @modifier and any other unnecessary parts */
1112 while (*s
&& *s
!= ':')
1117 REALLOC_ARRAY(language_tags
, num_langs
);
1118 language_tags
[num_langs
- 1] = strbuf_detach(&tag
, NULL
);
1119 if (num_langs
>= MAX_LANGUAGE_TAGS
- 1) /* -1 for '*' */
1124 /* write Accept-Language header into buf */
1126 int last_buf_len
= 0;
1132 REALLOC_ARRAY(language_tags
, num_langs
+ 1);
1133 language_tags
[num_langs
++] = "*"; /* it's OK; this won't be freed */
1135 /* compute decimal_places */
1136 for (max_q
= 1, decimal_places
= 0;
1137 max_q
< num_langs
&& decimal_places
<= MAX_DECIMAL_PLACES
;
1138 decimal_places
++, max_q
*= 10)
1141 sprintf(q_format
, ";q=0.%%0%dd", decimal_places
);
1143 strbuf_addstr(buf
, "Accept-Language: ");
1145 for (i
= 0; i
< num_langs
; i
++) {
1147 strbuf_addstr(buf
, ", ");
1149 strbuf_addstr(buf
, language_tags
[i
]);
1152 strbuf_addf(buf
, q_format
, max_q
- i
);
1154 if (buf
->len
> MAX_ACCEPT_LANGUAGE_HEADER_SIZE
) {
1155 strbuf_remove(buf
, last_buf_len
, buf
->len
- last_buf_len
);
1159 last_buf_len
= buf
->len
;
1163 /* free language tags -- last one is a static '*' */
1164 for (i
= 0; i
< num_langs
- 1; i
++)
1165 free(language_tags
[i
]);
1166 free(language_tags
);
1170 * Get an Accept-Language header which indicates user's preferred languages.
1174 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1175 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1176 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1177 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1178 * LANGUAGE= LANG=C -> ""
1180 static const char *get_accept_language(void)
1182 if (!cached_accept_language
) {
1183 struct strbuf buf
= STRBUF_INIT
;
1184 write_accept_language(&buf
);
1186 cached_accept_language
= strbuf_detach(&buf
, NULL
);
1189 return cached_accept_language
;
1192 /* http_request() targets */
1193 #define HTTP_REQUEST_STRBUF 0
1194 #define HTTP_REQUEST_FILE 1
1196 static int http_request(const char *url
,
1197 void *result
, int target
,
1198 const struct http_get_options
*options
)
1200 struct active_request_slot
*slot
;
1201 struct slot_results results
;
1202 struct curl_slist
*headers
= NULL
;
1203 struct strbuf buf
= STRBUF_INIT
;
1204 const char *accept_language
;
1207 slot
= get_active_slot();
1208 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
1210 if (result
== NULL
) {
1211 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 1);
1213 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 0);
1214 curl_easy_setopt(slot
->curl
, CURLOPT_FILE
, result
);
1216 if (target
== HTTP_REQUEST_FILE
) {
1217 long posn
= ftell(result
);
1218 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
1221 strbuf_addf(&buf
, "Range: bytes=%ld-", posn
);
1222 headers
= curl_slist_append(headers
, buf
.buf
);
1226 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
1230 accept_language
= get_accept_language();
1232 if (accept_language
)
1233 headers
= curl_slist_append(headers
, accept_language
);
1235 strbuf_addstr(&buf
, "Pragma:");
1236 if (options
&& options
->no_cache
)
1237 strbuf_addstr(&buf
, " no-cache");
1238 if (options
&& options
->keep_error
)
1239 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 0);
1241 headers
= curl_slist_append(headers
, buf
.buf
);
1243 curl_easy_setopt(slot
->curl
, CURLOPT_URL
, url
);
1244 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, headers
);
1245 curl_easy_setopt(slot
->curl
, CURLOPT_ENCODING
, "gzip");
1247 ret
= run_one_slot(slot
, &results
);
1249 if (options
&& options
->content_type
) {
1250 struct strbuf raw
= STRBUF_INIT
;
1251 curlinfo_strbuf(slot
->curl
, CURLINFO_CONTENT_TYPE
, &raw
);
1252 extract_content_type(&raw
, options
->content_type
,
1254 strbuf_release(&raw
);
1257 if (options
&& options
->effective_url
)
1258 curlinfo_strbuf(slot
->curl
, CURLINFO_EFFECTIVE_URL
,
1259 options
->effective_url
);
1261 curl_slist_free_all(headers
);
1262 strbuf_release(&buf
);
1268 * Update the "base" url to a more appropriate value, as deduced by
1269 * redirects seen when requesting a URL starting with "url".
1271 * The "asked" parameter is a URL that we asked curl to access, and must begin
1274 * The "got" parameter is the URL that curl reported to us as where we ended
1277 * Returns 1 if we updated the base url, 0 otherwise.
1279 * Our basic strategy is to compare "base" and "asked" to find the bits
1280 * specific to our request. We then strip those bits off of "got" to yield the
1281 * new base. So for example, if our base is "http://example.com/foo.git",
1282 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1283 * with "https://other.example.com/foo.git/info/refs". We would want the
1284 * new URL to become "https://other.example.com/foo.git".
1286 * Note that this assumes a sane redirect scheme. It's entirely possible
1287 * in the example above to end up at a URL that does not even end in
1288 * "info/refs". In such a case we simply punt, as there is not much we can
1289 * do (and such a scheme is unlikely to represent a real git repository,
1290 * which means we are likely about to abort anyway).
1292 static int update_url_from_redirect(struct strbuf
*base
,
1294 const struct strbuf
*got
)
1299 if (!strcmp(asked
, got
->buf
))
1302 if (!skip_prefix(asked
, base
->buf
, &tail
))
1303 die("BUG: update_url_from_redirect: %s is not a superset of %s",
1306 tail_len
= strlen(tail
);
1308 if (got
->len
< tail_len
||
1309 strcmp(tail
, got
->buf
+ got
->len
- tail_len
))
1310 return 0; /* insane redirect scheme */
1313 strbuf_add(base
, got
->buf
, got
->len
- tail_len
);
1317 static int http_request_reauth(const char *url
,
1318 void *result
, int target
,
1319 struct http_get_options
*options
)
1321 int ret
= http_request(url
, result
, target
, options
);
1323 if (options
&& options
->effective_url
&& options
->base_url
) {
1324 if (update_url_from_redirect(options
->base_url
,
1325 url
, options
->effective_url
)) {
1326 credential_from_url(&http_auth
, options
->base_url
->buf
);
1327 url
= options
->effective_url
->buf
;
1331 if (ret
!= HTTP_REAUTH
)
1335 * If we are using KEEP_ERROR, the previous request may have
1336 * put cruft into our output stream; we should clear it out before
1337 * making our next request. We only know how to do this for
1338 * the strbuf case, but that is enough to satisfy current callers.
1340 if (options
&& options
->keep_error
) {
1342 case HTTP_REQUEST_STRBUF
:
1343 strbuf_reset(result
);
1346 die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1350 credential_fill(&http_auth
);
1352 return http_request(url
, result
, target
, options
);
1355 int http_get_strbuf(const char *url
,
1356 struct strbuf
*result
,
1357 struct http_get_options
*options
)
1359 return http_request_reauth(url
, result
, HTTP_REQUEST_STRBUF
, options
);
1363 * Downloads a URL and stores the result in the given file.
1365 * If a previous interrupted download is detected (i.e. a previous temporary
1366 * file is still around) the download is resumed.
1368 static int http_get_file(const char *url
, const char *filename
,
1369 struct http_get_options
*options
)
1372 struct strbuf tmpfile
= STRBUF_INIT
;
1375 strbuf_addf(&tmpfile
, "%s.temp", filename
);
1376 result
= fopen(tmpfile
.buf
, "a");
1378 error("Unable to open local file %s", tmpfile
.buf
);
1383 ret
= http_request_reauth(url
, result
, HTTP_REQUEST_FILE
, options
);
1386 if (ret
== HTTP_OK
&& finalize_object_file(tmpfile
.buf
, filename
))
1389 strbuf_release(&tmpfile
);
1393 int http_fetch_ref(const char *base
, struct ref
*ref
)
1395 struct http_get_options options
= {0};
1397 struct strbuf buffer
= STRBUF_INIT
;
1400 options
.no_cache
= 1;
1402 url
= quote_ref_url(base
, ref
->name
);
1403 if (http_get_strbuf(url
, &buffer
, &options
) == HTTP_OK
) {
1404 strbuf_rtrim(&buffer
);
1405 if (buffer
.len
== 40)
1406 ret
= get_sha1_hex(buffer
.buf
, ref
->old_sha1
);
1407 else if (starts_with(buffer
.buf
, "ref: ")) {
1408 ref
->symref
= xstrdup(buffer
.buf
+ 5);
1413 strbuf_release(&buffer
);
1418 /* Helpers for fetching packs */
1419 static char *fetch_pack_index(unsigned char *sha1
, const char *base_url
)
1422 struct strbuf buf
= STRBUF_INIT
;
1424 if (http_is_verbose
)
1425 fprintf(stderr
, "Getting index for pack %s\n", sha1_to_hex(sha1
));
1427 end_url_with_slash(&buf
, base_url
);
1428 strbuf_addf(&buf
, "objects/pack/pack-%s.idx", sha1_to_hex(sha1
));
1429 url
= strbuf_detach(&buf
, NULL
);
1431 strbuf_addf(&buf
, "%s.temp", sha1_pack_index_name(sha1
));
1432 tmp
= strbuf_detach(&buf
, NULL
);
1434 if (http_get_file(url
, tmp
, NULL
) != HTTP_OK
) {
1435 error("Unable to get pack index %s", url
);
1444 static int fetch_and_setup_pack_index(struct packed_git
**packs_head
,
1445 unsigned char *sha1
, const char *base_url
)
1447 struct packed_git
*new_pack
;
1448 char *tmp_idx
= NULL
;
1451 if (has_pack_index(sha1
)) {
1452 new_pack
= parse_pack_index(sha1
, sha1_pack_index_name(sha1
));
1454 return -1; /* parse_pack_index() already issued error message */
1458 tmp_idx
= fetch_pack_index(sha1
, base_url
);
1462 new_pack
= parse_pack_index(sha1
, tmp_idx
);
1467 return -1; /* parse_pack_index() already issued error message */
1470 ret
= verify_pack_index(new_pack
);
1472 close_pack_index(new_pack
);
1473 ret
= finalize_object_file(tmp_idx
, sha1_pack_index_name(sha1
));
1480 new_pack
->next
= *packs_head
;
1481 *packs_head
= new_pack
;
1485 int http_get_info_packs(const char *base_url
, struct packed_git
**packs_head
)
1487 struct http_get_options options
= {0};
1490 struct strbuf buf
= STRBUF_INIT
;
1491 unsigned char sha1
[20];
1493 end_url_with_slash(&buf
, base_url
);
1494 strbuf_addstr(&buf
, "objects/info/packs");
1495 url
= strbuf_detach(&buf
, NULL
);
1497 options
.no_cache
= 1;
1498 ret
= http_get_strbuf(url
, &buf
, &options
);
1503 while (i
< buf
.len
) {
1507 if (i
+ 52 <= buf
.len
&&
1508 starts_with(data
+ i
, " pack-") &&
1509 starts_with(data
+ i
+ 46, ".pack\n")) {
1510 get_sha1_hex(data
+ i
+ 6, sha1
);
1511 fetch_and_setup_pack_index(packs_head
, sha1
,
1517 while (i
< buf
.len
&& data
[i
] != '\n')
1528 void release_http_pack_request(struct http_pack_request
*preq
)
1530 if (preq
->packfile
!= NULL
) {
1531 fclose(preq
->packfile
);
1532 preq
->packfile
= NULL
;
1534 if (preq
->range_header
!= NULL
) {
1535 curl_slist_free_all(preq
->range_header
);
1536 preq
->range_header
= NULL
;
1543 int finish_http_pack_request(struct http_pack_request
*preq
)
1545 struct packed_git
**lst
;
1546 struct packed_git
*p
= preq
->target
;
1548 struct child_process ip
= CHILD_PROCESS_INIT
;
1549 const char *ip_argv
[8];
1551 close_pack_index(p
);
1553 fclose(preq
->packfile
);
1554 preq
->packfile
= NULL
;
1558 lst
= &((*lst
)->next
);
1559 *lst
= (*lst
)->next
;
1561 tmp_idx
= xstrdup(preq
->tmpfile
);
1562 strcpy(tmp_idx
+ strlen(tmp_idx
) - strlen(".pack.temp"),
1565 ip_argv
[0] = "index-pack";
1567 ip_argv
[2] = tmp_idx
;
1568 ip_argv
[3] = preq
->tmpfile
;
1576 if (run_command(&ip
)) {
1577 unlink(preq
->tmpfile
);
1583 unlink(sha1_pack_index_name(p
->sha1
));
1585 if (finalize_object_file(preq
->tmpfile
, sha1_pack_name(p
->sha1
))
1586 || finalize_object_file(tmp_idx
, sha1_pack_index_name(p
->sha1
))) {
1591 install_packed_git(p
);
1596 struct http_pack_request
*new_http_pack_request(
1597 struct packed_git
*target
, const char *base_url
)
1600 char range
[RANGE_HEADER_SIZE
];
1601 struct strbuf buf
= STRBUF_INIT
;
1602 struct http_pack_request
*preq
;
1604 preq
= xcalloc(1, sizeof(*preq
));
1605 preq
->target
= target
;
1607 end_url_with_slash(&buf
, base_url
);
1608 strbuf_addf(&buf
, "objects/pack/pack-%s.pack",
1609 sha1_to_hex(target
->sha1
));
1610 preq
->url
= strbuf_detach(&buf
, NULL
);
1612 snprintf(preq
->tmpfile
, sizeof(preq
->tmpfile
), "%s.temp",
1613 sha1_pack_name(target
->sha1
));
1614 preq
->packfile
= fopen(preq
->tmpfile
, "a");
1615 if (!preq
->packfile
) {
1616 error("Unable to open local file %s for pack",
1621 preq
->slot
= get_active_slot();
1622 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_FILE
, preq
->packfile
);
1623 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite
);
1624 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_URL
, preq
->url
);
1625 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_HTTPHEADER
,
1629 * If there is data present from a previous transfer attempt,
1630 * resume where it left off
1632 prev_posn
= ftell(preq
->packfile
);
1634 if (http_is_verbose
)
1636 "Resuming fetch of pack %s at byte %ld\n",
1637 sha1_to_hex(target
->sha1
), prev_posn
);
1638 sprintf(range
, "Range: bytes=%ld-", prev_posn
);
1639 preq
->range_header
= curl_slist_append(NULL
, range
);
1640 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_HTTPHEADER
,
1641 preq
->range_header
);
1652 /* Helpers for fetching objects (loose) */
1653 static size_t fwrite_sha1_file(char *ptr
, size_t eltsize
, size_t nmemb
,
1656 unsigned char expn
[4096];
1657 size_t size
= eltsize
* nmemb
;
1659 struct http_object_request
*freq
=
1660 (struct http_object_request
*)data
;
1662 ssize_t retval
= xwrite(freq
->localfile
,
1663 (char *) ptr
+ posn
, size
- posn
);
1667 } while (posn
< size
);
1669 freq
->stream
.avail_in
= size
;
1670 freq
->stream
.next_in
= (void *)ptr
;
1672 freq
->stream
.next_out
= expn
;
1673 freq
->stream
.avail_out
= sizeof(expn
);
1674 freq
->zret
= git_inflate(&freq
->stream
, Z_SYNC_FLUSH
);
1675 git_SHA1_Update(&freq
->c
, expn
,
1676 sizeof(expn
) - freq
->stream
.avail_out
);
1677 } while (freq
->stream
.avail_in
&& freq
->zret
== Z_OK
);
1681 struct http_object_request
*new_http_object_request(const char *base_url
,
1682 unsigned char *sha1
)
1684 char *hex
= sha1_to_hex(sha1
);
1685 const char *filename
;
1686 char prevfile
[PATH_MAX
];
1688 char prev_buf
[PREV_BUF_SIZE
];
1689 ssize_t prev_read
= 0;
1691 char range
[RANGE_HEADER_SIZE
];
1692 struct curl_slist
*range_header
= NULL
;
1693 struct http_object_request
*freq
;
1695 freq
= xcalloc(1, sizeof(*freq
));
1696 hashcpy(freq
->sha1
, sha1
);
1697 freq
->localfile
= -1;
1699 filename
= sha1_file_name(sha1
);
1700 snprintf(freq
->tmpfile
, sizeof(freq
->tmpfile
),
1701 "%s.temp", filename
);
1703 snprintf(prevfile
, sizeof(prevfile
), "%s.prev", filename
);
1704 unlink_or_warn(prevfile
);
1705 rename(freq
->tmpfile
, prevfile
);
1706 unlink_or_warn(freq
->tmpfile
);
1708 if (freq
->localfile
!= -1)
1709 error("fd leakage in start: %d", freq
->localfile
);
1710 freq
->localfile
= open(freq
->tmpfile
,
1711 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
1713 * This could have failed due to the "lazy directory creation";
1714 * try to mkdir the last path component.
1716 if (freq
->localfile
< 0 && errno
== ENOENT
) {
1717 char *dir
= strrchr(freq
->tmpfile
, '/');
1720 mkdir(freq
->tmpfile
, 0777);
1723 freq
->localfile
= open(freq
->tmpfile
,
1724 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
1727 if (freq
->localfile
< 0) {
1728 error("Couldn't create temporary file %s: %s",
1729 freq
->tmpfile
, strerror(errno
));
1733 git_inflate_init(&freq
->stream
);
1735 git_SHA1_Init(&freq
->c
);
1737 freq
->url
= get_remote_object_url(base_url
, hex
, 0);
1740 * If a previous temp file is present, process what was already
1743 prevlocal
= open(prevfile
, O_RDONLY
);
1744 if (prevlocal
!= -1) {
1746 prev_read
= xread(prevlocal
, prev_buf
, PREV_BUF_SIZE
);
1748 if (fwrite_sha1_file(prev_buf
,
1751 freq
) == prev_read
) {
1752 prev_posn
+= prev_read
;
1757 } while (prev_read
> 0);
1760 unlink_or_warn(prevfile
);
1763 * Reset inflate/SHA1 if there was an error reading the previous temp
1764 * file; also rewind to the beginning of the local file.
1766 if (prev_read
== -1) {
1767 memset(&freq
->stream
, 0, sizeof(freq
->stream
));
1768 git_inflate_init(&freq
->stream
);
1769 git_SHA1_Init(&freq
->c
);
1772 lseek(freq
->localfile
, 0, SEEK_SET
);
1773 if (ftruncate(freq
->localfile
, 0) < 0) {
1774 error("Couldn't truncate temporary file %s: %s",
1775 freq
->tmpfile
, strerror(errno
));
1781 freq
->slot
= get_active_slot();
1783 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_FILE
, freq
);
1784 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite_sha1_file
);
1785 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_ERRORBUFFER
, freq
->errorstr
);
1786 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_URL
, freq
->url
);
1787 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_HTTPHEADER
, no_pragma_header
);
1790 * If we have successfully processed data from a previous fetch
1791 * attempt, only fetch the data we don't already have.
1794 if (http_is_verbose
)
1796 "Resuming fetch of object %s at byte %ld\n",
1798 sprintf(range
, "Range: bytes=%ld-", prev_posn
);
1799 range_header
= curl_slist_append(range_header
, range
);
1800 curl_easy_setopt(freq
->slot
->curl
,
1801 CURLOPT_HTTPHEADER
, range_header
);
1812 void process_http_object_request(struct http_object_request
*freq
)
1814 if (freq
->slot
== NULL
)
1816 freq
->curl_result
= freq
->slot
->curl_result
;
1817 freq
->http_code
= freq
->slot
->http_code
;
1821 int finish_http_object_request(struct http_object_request
*freq
)
1825 close(freq
->localfile
);
1826 freq
->localfile
= -1;
1828 process_http_object_request(freq
);
1830 if (freq
->http_code
== 416) {
1831 warning("requested range invalid; we may already have all the data.");
1832 } else if (freq
->curl_result
!= CURLE_OK
) {
1833 if (stat(freq
->tmpfile
, &st
) == 0)
1834 if (st
.st_size
== 0)
1835 unlink_or_warn(freq
->tmpfile
);
1839 git_inflate_end(&freq
->stream
);
1840 git_SHA1_Final(freq
->real_sha1
, &freq
->c
);
1841 if (freq
->zret
!= Z_STREAM_END
) {
1842 unlink_or_warn(freq
->tmpfile
);
1845 if (hashcmp(freq
->sha1
, freq
->real_sha1
)) {
1846 unlink_or_warn(freq
->tmpfile
);
1850 finalize_object_file(freq
->tmpfile
, sha1_file_name(freq
->sha1
));
1852 return freq
->rename
;
1855 void abort_http_object_request(struct http_object_request
*freq
)
1857 unlink_or_warn(freq
->tmpfile
);
1859 release_http_object_request(freq
);
1862 void release_http_object_request(struct http_object_request
*freq
)
1864 if (freq
->localfile
!= -1) {
1865 close(freq
->localfile
);
1866 freq
->localfile
= -1;
1868 if (freq
->url
!= NULL
) {
1872 if (freq
->slot
!= NULL
) {
1873 freq
->slot
->callback_func
= NULL
;
1874 freq
->slot
->callback_data
= NULL
;
1875 release_active_slot(freq
->slot
);