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 #if LIBCURL_VERSION_NUM >= 0x070903
42 static const char *ssl_key
;
44 #if LIBCURL_VERSION_NUM >= 0x070908
45 static const char *ssl_capath
;
47 static const char *ssl_cainfo
;
48 static long curl_low_speed_limit
= -1;
49 static long curl_low_speed_time
= -1;
50 static int curl_ftp_no_epsv
;
51 static const char *curl_http_proxy
;
52 static const char *curl_cookie_file
;
53 static int curl_save_cookies
;
54 struct credential http_auth
= CREDENTIAL_INIT
;
55 static int http_proactive_auth
;
56 static const char *user_agent
;
58 #if LIBCURL_VERSION_NUM >= 0x071700
59 /* Use CURLOPT_KEYPASSWD as is */
60 #elif LIBCURL_VERSION_NUM >= 0x070903
61 #define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
63 #define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
66 static struct credential cert_auth
= CREDENTIAL_INIT
;
67 static int ssl_cert_password_required
;
68 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
69 static unsigned long http_auth_methods
= CURLAUTH_ANY
;
72 static struct curl_slist
*pragma_header
;
73 static struct curl_slist
*no_pragma_header
;
75 static struct active_request_slot
*active_queue_head
;
77 static char *cached_accept_language
;
79 size_t fread_buffer(char *ptr
, size_t eltsize
, size_t nmemb
, void *buffer_
)
81 size_t size
= eltsize
* nmemb
;
82 struct buffer
*buffer
= buffer_
;
84 if (size
> buffer
->buf
.len
- buffer
->posn
)
85 size
= buffer
->buf
.len
- buffer
->posn
;
86 memcpy(ptr
, buffer
->buf
.buf
+ buffer
->posn
, size
);
93 curlioerr
ioctl_buffer(CURL
*handle
, int cmd
, void *clientp
)
95 struct buffer
*buffer
= clientp
;
101 case CURLIOCMD_RESTARTREAD
:
106 return CURLIOE_UNKNOWNCMD
;
111 size_t fwrite_buffer(char *ptr
, size_t eltsize
, size_t nmemb
, void *buffer_
)
113 size_t size
= eltsize
* nmemb
;
114 struct strbuf
*buffer
= buffer_
;
116 strbuf_add(buffer
, ptr
, size
);
120 size_t fwrite_null(char *ptr
, size_t eltsize
, size_t nmemb
, void *strbuf
)
122 return eltsize
* nmemb
;
125 static void closedown_active_slot(struct active_request_slot
*slot
)
131 static void finish_active_slot(struct active_request_slot
*slot
)
133 closedown_active_slot(slot
);
134 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTP_CODE
, &slot
->http_code
);
136 if (slot
->finished
!= NULL
)
137 (*slot
->finished
) = 1;
139 /* Store slot results so they can be read after the slot is reused */
140 if (slot
->results
!= NULL
) {
141 slot
->results
->curl_result
= slot
->curl_result
;
142 slot
->results
->http_code
= slot
->http_code
;
143 #if LIBCURL_VERSION_NUM >= 0x070a08
144 curl_easy_getinfo(slot
->curl
, CURLINFO_HTTPAUTH_AVAIL
,
145 &slot
->results
->auth_avail
);
147 slot
->results
->auth_avail
= 0;
151 /* Run callback if appropriate */
152 if (slot
->callback_func
!= NULL
)
153 slot
->callback_func(slot
->callback_data
);
156 #ifdef USE_CURL_MULTI
157 static void process_curl_messages(void)
160 struct active_request_slot
*slot
;
161 CURLMsg
*curl_message
= curl_multi_info_read(curlm
, &num_messages
);
163 while (curl_message
!= NULL
) {
164 if (curl_message
->msg
== CURLMSG_DONE
) {
165 int curl_result
= curl_message
->data
.result
;
166 slot
= active_queue_head
;
167 while (slot
!= NULL
&&
168 slot
->curl
!= curl_message
->easy_handle
)
171 curl_multi_remove_handle(curlm
, slot
->curl
);
172 slot
->curl_result
= curl_result
;
173 finish_active_slot(slot
);
175 fprintf(stderr
, "Received DONE message for unknown request!\n");
178 fprintf(stderr
, "Unknown CURL message received: %d\n",
179 (int)curl_message
->msg
);
181 curl_message
= curl_multi_info_read(curlm
, &num_messages
);
186 static int http_options(const char *var
, const char *value
, void *cb
)
188 if (!strcmp("http.sslverify", var
)) {
189 curl_ssl_verify
= git_config_bool(var
, value
);
192 if (!strcmp("http.sslcipherlist", var
))
193 return git_config_string(&ssl_cipherlist
, var
, value
);
194 if (!strcmp("http.sslcert", var
))
195 return git_config_string(&ssl_cert
, var
, value
);
196 #if LIBCURL_VERSION_NUM >= 0x070903
197 if (!strcmp("http.sslkey", var
))
198 return git_config_string(&ssl_key
, var
, value
);
200 #if LIBCURL_VERSION_NUM >= 0x070908
201 if (!strcmp("http.sslcapath", var
))
202 return git_config_string(&ssl_capath
, var
, value
);
204 if (!strcmp("http.sslcainfo", var
))
205 return git_config_string(&ssl_cainfo
, var
, value
);
206 if (!strcmp("http.sslcertpasswordprotected", var
)) {
207 ssl_cert_password_required
= git_config_bool(var
, value
);
210 if (!strcmp("http.ssltry", var
)) {
211 curl_ssl_try
= git_config_bool(var
, value
);
214 if (!strcmp("http.minsessions", var
)) {
215 min_curl_sessions
= git_config_int(var
, value
);
216 #ifndef USE_CURL_MULTI
217 if (min_curl_sessions
> 1)
218 min_curl_sessions
= 1;
222 #ifdef USE_CURL_MULTI
223 if (!strcmp("http.maxrequests", var
)) {
224 max_requests
= git_config_int(var
, value
);
228 if (!strcmp("http.lowspeedlimit", var
)) {
229 curl_low_speed_limit
= (long)git_config_int(var
, value
);
232 if (!strcmp("http.lowspeedtime", var
)) {
233 curl_low_speed_time
= (long)git_config_int(var
, value
);
237 if (!strcmp("http.noepsv", var
)) {
238 curl_ftp_no_epsv
= git_config_bool(var
, value
);
241 if (!strcmp("http.proxy", var
))
242 return git_config_string(&curl_http_proxy
, var
, value
);
244 if (!strcmp("http.cookiefile", var
))
245 return git_config_string(&curl_cookie_file
, var
, value
);
246 if (!strcmp("http.savecookies", var
)) {
247 curl_save_cookies
= git_config_bool(var
, value
);
251 if (!strcmp("http.postbuffer", var
)) {
252 http_post_buffer
= git_config_int(var
, value
);
253 if (http_post_buffer
< LARGE_PACKET_MAX
)
254 http_post_buffer
= LARGE_PACKET_MAX
;
258 if (!strcmp("http.useragent", var
))
259 return git_config_string(&user_agent
, var
, value
);
261 /* Fall back on the default ones */
262 return git_default_config(var
, value
, cb
);
265 static void init_curl_http_auth(CURL
*result
)
267 if (!http_auth
.username
)
270 credential_fill(&http_auth
);
272 #if LIBCURL_VERSION_NUM >= 0x071301
273 curl_easy_setopt(result
, CURLOPT_USERNAME
, http_auth
.username
);
274 curl_easy_setopt(result
, CURLOPT_PASSWORD
, http_auth
.password
);
277 static struct strbuf up
= STRBUF_INIT
;
279 * Note that we assume we only ever have a single set of
280 * credentials in a given program run, so we do not have
281 * to worry about updating this buffer, only setting its
285 strbuf_addf(&up
, "%s:%s",
286 http_auth
.username
, http_auth
.password
);
287 curl_easy_setopt(result
, CURLOPT_USERPWD
, up
.buf
);
292 static int has_cert_password(void)
294 if (ssl_cert
== NULL
|| ssl_cert_password_required
!= 1)
296 if (!cert_auth
.password
) {
297 cert_auth
.protocol
= xstrdup("cert");
298 cert_auth
.username
= xstrdup("");
299 cert_auth
.path
= xstrdup(ssl_cert
);
300 credential_fill(&cert_auth
);
305 #if LIBCURL_VERSION_NUM >= 0x071900
306 static void set_curl_keepalive(CURL
*c
)
308 curl_easy_setopt(c
, CURLOPT_TCP_KEEPALIVE
, 1);
311 #elif LIBCURL_VERSION_NUM >= 0x071000
312 static int sockopt_callback(void *client
, curl_socket_t fd
, curlsocktype type
)
316 socklen_t len
= (socklen_t
)sizeof(ka
);
318 if (type
!= CURLSOCKTYPE_IPCXN
)
321 rc
= setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, (void *)&ka
, len
);
323 warning("unable to set SO_KEEPALIVE on socket %s",
326 return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
329 static void set_curl_keepalive(CURL
*c
)
331 curl_easy_setopt(c
, CURLOPT_SOCKOPTFUNCTION
, sockopt_callback
);
335 static void set_curl_keepalive(CURL
*c
)
337 /* not supported on older curl versions */
341 static CURL
*get_curl_handle(void)
343 CURL
*result
= curl_easy_init();
344 long allowed_protocols
= 0;
347 die("curl_easy_init failed");
349 if (!curl_ssl_verify
) {
350 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 0);
351 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 0);
353 /* Verify authenticity of the peer's certificate */
354 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYPEER
, 1);
355 /* The name in the cert must match whom we tried to connect */
356 curl_easy_setopt(result
, CURLOPT_SSL_VERIFYHOST
, 2);
359 #if LIBCURL_VERSION_NUM >= 0x070907
360 curl_easy_setopt(result
, CURLOPT_NETRC
, CURL_NETRC_OPTIONAL
);
362 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
363 curl_easy_setopt(result
, CURLOPT_HTTPAUTH
, CURLAUTH_ANY
);
366 if (http_proactive_auth
)
367 init_curl_http_auth(result
);
369 if (getenv("GIT_SSL_CIPHER_LIST"))
370 ssl_cipherlist
= getenv("GIT_SSL_CIPHER_LIST");
372 if (ssl_cipherlist
!= NULL
&& *ssl_cipherlist
)
373 curl_easy_setopt(result
, CURLOPT_SSL_CIPHER_LIST
,
376 if (ssl_cert
!= NULL
)
377 curl_easy_setopt(result
, CURLOPT_SSLCERT
, ssl_cert
);
378 if (has_cert_password())
379 curl_easy_setopt(result
, CURLOPT_KEYPASSWD
, cert_auth
.password
);
380 #if LIBCURL_VERSION_NUM >= 0x070903
382 curl_easy_setopt(result
, CURLOPT_SSLKEY
, ssl_key
);
384 #if LIBCURL_VERSION_NUM >= 0x070908
385 if (ssl_capath
!= NULL
)
386 curl_easy_setopt(result
, CURLOPT_CAPATH
, ssl_capath
);
388 if (ssl_cainfo
!= NULL
)
389 curl_easy_setopt(result
, CURLOPT_CAINFO
, ssl_cainfo
);
391 if (curl_low_speed_limit
> 0 && curl_low_speed_time
> 0) {
392 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_LIMIT
,
393 curl_low_speed_limit
);
394 curl_easy_setopt(result
, CURLOPT_LOW_SPEED_TIME
,
395 curl_low_speed_time
);
398 curl_easy_setopt(result
, CURLOPT_FOLLOWLOCATION
, 1);
399 curl_easy_setopt(result
, CURLOPT_MAXREDIRS
, 20);
400 #if LIBCURL_VERSION_NUM >= 0x071301
401 curl_easy_setopt(result
, CURLOPT_POSTREDIR
, CURL_REDIR_POST_ALL
);
402 #elif LIBCURL_VERSION_NUM >= 0x071101
403 curl_easy_setopt(result
, CURLOPT_POST301
, 1);
405 #if LIBCURL_VERSION_NUM >= 0x071304
406 if (is_transport_allowed("http"))
407 allowed_protocols
|= CURLPROTO_HTTP
;
408 if (is_transport_allowed("https"))
409 allowed_protocols
|= CURLPROTO_HTTPS
;
410 if (is_transport_allowed("ftp"))
411 allowed_protocols
|= CURLPROTO_FTP
;
412 if (is_transport_allowed("ftps"))
413 allowed_protocols
|= CURLPROTO_FTPS
;
414 curl_easy_setopt(result
, CURLOPT_REDIR_PROTOCOLS
, allowed_protocols
);
416 if (transport_restrict_protocols())
417 warning("protocol restrictions not applied to curl redirects because\n"
418 "your curl version is too old (>= 7.19.4)");
421 if (getenv("GIT_CURL_VERBOSE"))
422 curl_easy_setopt(result
, CURLOPT_VERBOSE
, 1);
424 curl_easy_setopt(result
, CURLOPT_USERAGENT
,
425 user_agent
? user_agent
: git_user_agent());
427 if (curl_ftp_no_epsv
)
428 curl_easy_setopt(result
, CURLOPT_FTP_USE_EPSV
, 0);
430 #ifdef CURLOPT_USE_SSL
432 curl_easy_setopt(result
, CURLOPT_USE_SSL
, CURLUSESSL_TRY
);
435 if (curl_http_proxy
) {
436 curl_easy_setopt(result
, CURLOPT_PROXY
, curl_http_proxy
);
438 #if LIBCURL_VERSION_NUM >= 0x070a07
439 curl_easy_setopt(result
, CURLOPT_PROXYAUTH
, CURLAUTH_ANY
);
442 set_curl_keepalive(result
);
447 static void set_from_env(const char **var
, const char *envname
)
449 const char *val
= getenv(envname
);
454 void http_init(struct remote
*remote
, const char *url
, int proactive_auth
)
456 char *low_speed_limit
;
457 char *low_speed_time
;
458 char *normalized_url
;
459 struct urlmatch_config config
= { STRING_LIST_INIT_DUP
};
461 config
.section
= "http";
463 config
.collect_fn
= http_options
;
464 config
.cascade_fn
= git_default_config
;
468 normalized_url
= url_normalize(url
, &config
.url
);
470 git_config(urlmatch_config_entry
, &config
);
471 free(normalized_url
);
473 if (curl_global_init(CURL_GLOBAL_ALL
) != CURLE_OK
)
474 die("curl_global_init failed");
476 http_proactive_auth
= proactive_auth
;
478 if (remote
&& remote
->http_proxy
)
479 curl_http_proxy
= xstrdup(remote
->http_proxy
);
481 pragma_header
= curl_slist_append(pragma_header
, "Pragma: no-cache");
482 no_pragma_header
= curl_slist_append(no_pragma_header
, "Pragma:");
484 #ifdef USE_CURL_MULTI
486 char *http_max_requests
= getenv("GIT_HTTP_MAX_REQUESTS");
487 if (http_max_requests
!= NULL
)
488 max_requests
= atoi(http_max_requests
);
491 curlm
= curl_multi_init();
493 die("curl_multi_init failed");
496 if (getenv("GIT_SSL_NO_VERIFY"))
499 set_from_env(&ssl_cert
, "GIT_SSL_CERT");
500 #if LIBCURL_VERSION_NUM >= 0x070903
501 set_from_env(&ssl_key
, "GIT_SSL_KEY");
503 #if LIBCURL_VERSION_NUM >= 0x070908
504 set_from_env(&ssl_capath
, "GIT_SSL_CAPATH");
506 set_from_env(&ssl_cainfo
, "GIT_SSL_CAINFO");
508 set_from_env(&user_agent
, "GIT_HTTP_USER_AGENT");
510 low_speed_limit
= getenv("GIT_HTTP_LOW_SPEED_LIMIT");
511 if (low_speed_limit
!= NULL
)
512 curl_low_speed_limit
= strtol(low_speed_limit
, NULL
, 10);
513 low_speed_time
= getenv("GIT_HTTP_LOW_SPEED_TIME");
514 if (low_speed_time
!= NULL
)
515 curl_low_speed_time
= strtol(low_speed_time
, NULL
, 10);
517 if (curl_ssl_verify
== -1)
520 curl_session_count
= 0;
521 #ifdef USE_CURL_MULTI
522 if (max_requests
< 1)
523 max_requests
= DEFAULT_MAX_REQUESTS
;
526 if (getenv("GIT_CURL_FTP_NO_EPSV"))
527 curl_ftp_no_epsv
= 1;
530 credential_from_url(&http_auth
, url
);
531 if (!ssl_cert_password_required
&&
532 getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
533 starts_with(url
, "https://"))
534 ssl_cert_password_required
= 1;
537 #ifndef NO_CURL_EASY_DUPHANDLE
538 curl_default
= get_curl_handle();
542 void http_cleanup(void)
544 struct active_request_slot
*slot
= active_queue_head
;
546 while (slot
!= NULL
) {
547 struct active_request_slot
*next
= slot
->next
;
548 if (slot
->curl
!= NULL
) {
549 #ifdef USE_CURL_MULTI
550 curl_multi_remove_handle(curlm
, slot
->curl
);
552 curl_easy_cleanup(slot
->curl
);
557 active_queue_head
= NULL
;
559 #ifndef NO_CURL_EASY_DUPHANDLE
560 curl_easy_cleanup(curl_default
);
563 #ifdef USE_CURL_MULTI
564 curl_multi_cleanup(curlm
);
566 curl_global_cleanup();
568 curl_slist_free_all(pragma_header
);
569 pragma_header
= NULL
;
571 curl_slist_free_all(no_pragma_header
);
572 no_pragma_header
= NULL
;
574 if (curl_http_proxy
) {
575 free((void *)curl_http_proxy
);
576 curl_http_proxy
= NULL
;
579 if (cert_auth
.password
!= NULL
) {
580 memset(cert_auth
.password
, 0, strlen(cert_auth
.password
));
581 free(cert_auth
.password
);
582 cert_auth
.password
= NULL
;
584 ssl_cert_password_required
= 0;
586 free(cached_accept_language
);
587 cached_accept_language
= NULL
;
590 struct active_request_slot
*get_active_slot(void)
592 struct active_request_slot
*slot
= active_queue_head
;
593 struct active_request_slot
*newslot
;
595 #ifdef USE_CURL_MULTI
598 /* Wait for a slot to open up if the queue is full */
599 while (active_requests
>= max_requests
) {
600 curl_multi_perform(curlm
, &num_transfers
);
601 if (num_transfers
< active_requests
)
602 process_curl_messages();
606 while (slot
!= NULL
&& slot
->in_use
)
610 newslot
= xmalloc(sizeof(*newslot
));
611 newslot
->curl
= NULL
;
613 newslot
->next
= NULL
;
615 slot
= active_queue_head
;
617 active_queue_head
= newslot
;
619 while (slot
->next
!= NULL
)
621 slot
->next
= newslot
;
626 if (slot
->curl
== NULL
) {
627 #ifdef NO_CURL_EASY_DUPHANDLE
628 slot
->curl
= get_curl_handle();
630 slot
->curl
= curl_easy_duphandle(curl_default
);
632 curl_session_count
++;
637 slot
->results
= NULL
;
638 slot
->finished
= NULL
;
639 slot
->callback_data
= NULL
;
640 slot
->callback_func
= NULL
;
641 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEFILE
, curl_cookie_file
);
642 if (curl_save_cookies
)
643 curl_easy_setopt(slot
->curl
, CURLOPT_COOKIEJAR
, curl_cookie_file
);
644 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, pragma_header
);
645 curl_easy_setopt(slot
->curl
, CURLOPT_ERRORBUFFER
, curl_errorstr
);
646 curl_easy_setopt(slot
->curl
, CURLOPT_CUSTOMREQUEST
, NULL
);
647 curl_easy_setopt(slot
->curl
, CURLOPT_READFUNCTION
, NULL
);
648 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
, NULL
);
649 curl_easy_setopt(slot
->curl
, CURLOPT_POSTFIELDS
, NULL
);
650 curl_easy_setopt(slot
->curl
, CURLOPT_UPLOAD
, 0);
651 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
652 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 1);
653 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
654 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPAUTH
, http_auth_methods
);
656 if (http_auth
.password
)
657 init_curl_http_auth(slot
->curl
);
662 int start_active_slot(struct active_request_slot
*slot
)
664 #ifdef USE_CURL_MULTI
665 CURLMcode curlm_result
= curl_multi_add_handle(curlm
, slot
->curl
);
668 if (curlm_result
!= CURLM_OK
&&
669 curlm_result
!= CURLM_CALL_MULTI_PERFORM
) {
676 * We know there must be something to do, since we just added
679 curl_multi_perform(curlm
, &num_transfers
);
684 #ifdef USE_CURL_MULTI
688 struct fill_chain
*next
;
691 static struct fill_chain
*fill_cfg
;
693 void add_fill_function(void *data
, int (*fill
)(void *))
695 struct fill_chain
*new = xmalloc(sizeof(*new));
696 struct fill_chain
**linkp
= &fill_cfg
;
701 linkp
= &(*linkp
)->next
;
705 void fill_active_slots(void)
707 struct active_request_slot
*slot
= active_queue_head
;
709 while (active_requests
< max_requests
) {
710 struct fill_chain
*fill
;
711 for (fill
= fill_cfg
; fill
; fill
= fill
->next
)
712 if (fill
->fill(fill
->data
))
719 while (slot
!= NULL
) {
720 if (!slot
->in_use
&& slot
->curl
!= NULL
721 && curl_session_count
> min_curl_sessions
) {
722 curl_easy_cleanup(slot
->curl
);
724 curl_session_count
--;
730 void step_active_slots(void)
733 CURLMcode curlm_result
;
736 curlm_result
= curl_multi_perform(curlm
, &num_transfers
);
737 } while (curlm_result
== CURLM_CALL_MULTI_PERFORM
);
738 if (num_transfers
< active_requests
) {
739 process_curl_messages();
745 void run_active_slot(struct active_request_slot
*slot
)
747 #ifdef USE_CURL_MULTI
752 struct timeval select_timeout
;
755 slot
->finished
= &finished
;
760 #if LIBCURL_VERSION_NUM >= 0x070f04
762 curl_multi_timeout(curlm
, &curl_timeout
);
763 if (curl_timeout
== 0) {
765 } else if (curl_timeout
== -1) {
766 select_timeout
.tv_sec
= 0;
767 select_timeout
.tv_usec
= 50000;
769 select_timeout
.tv_sec
= curl_timeout
/ 1000;
770 select_timeout
.tv_usec
= (curl_timeout
% 1000) * 1000;
773 select_timeout
.tv_sec
= 0;
774 select_timeout
.tv_usec
= 50000;
781 curl_multi_fdset(curlm
, &readfds
, &writefds
, &excfds
, &max_fd
);
784 * It can happen that curl_multi_timeout returns a pathologically
785 * long timeout when curl_multi_fdset returns no file descriptors
786 * to read. See commit message for more details.
789 (select_timeout
.tv_sec
> 0 ||
790 select_timeout
.tv_usec
> 50000)) {
791 select_timeout
.tv_sec
= 0;
792 select_timeout
.tv_usec
= 50000;
795 select(max_fd
+1, &readfds
, &writefds
, &excfds
, &select_timeout
);
799 while (slot
->in_use
) {
800 slot
->curl_result
= curl_easy_perform(slot
->curl
);
801 finish_active_slot(slot
);
806 static void release_active_slot(struct active_request_slot
*slot
)
808 closedown_active_slot(slot
);
809 if (slot
->curl
&& curl_session_count
> min_curl_sessions
) {
810 #ifdef USE_CURL_MULTI
811 curl_multi_remove_handle(curlm
, slot
->curl
);
813 curl_easy_cleanup(slot
->curl
);
815 curl_session_count
--;
817 #ifdef USE_CURL_MULTI
822 void finish_all_active_slots(void)
824 struct active_request_slot
*slot
= active_queue_head
;
828 run_active_slot(slot
);
829 slot
= active_queue_head
;
835 /* Helpers for modifying and creating URLs */
836 static inline int needs_quote(int ch
)
838 if (((ch
>= 'A') && (ch
<= 'Z'))
839 || ((ch
>= 'a') && (ch
<= 'z'))
840 || ((ch
>= '0') && (ch
<= '9'))
848 static char *quote_ref_url(const char *base
, const char *ref
)
850 struct strbuf buf
= STRBUF_INIT
;
854 end_url_with_slash(&buf
, base
);
856 for (cp
= ref
; (ch
= *cp
) != 0; cp
++)
858 strbuf_addf(&buf
, "%%%02x", ch
);
860 strbuf_addch(&buf
, *cp
);
862 return strbuf_detach(&buf
, NULL
);
865 void append_remote_object_url(struct strbuf
*buf
, const char *url
,
867 int only_two_digit_prefix
)
869 end_url_with_slash(buf
, url
);
871 strbuf_addf(buf
, "objects/%.*s/", 2, hex
);
872 if (!only_two_digit_prefix
)
873 strbuf_addf(buf
, "%s", hex
+2);
876 char *get_remote_object_url(const char *url
, const char *hex
,
877 int only_two_digit_prefix
)
879 struct strbuf buf
= STRBUF_INIT
;
880 append_remote_object_url(&buf
, url
, hex
, only_two_digit_prefix
);
881 return strbuf_detach(&buf
, NULL
);
884 static int handle_curl_result(struct slot_results
*results
)
887 * If we see a failing http code with CURLE_OK, we have turned off
888 * FAILONERROR (to keep the server's custom error response), and should
889 * translate the code into failure here.
891 if (results
->curl_result
== CURLE_OK
&&
892 results
->http_code
>= 400) {
893 results
->curl_result
= CURLE_HTTP_RETURNED_ERROR
;
895 * Normally curl will already have put the "reason phrase"
896 * from the server into curl_errorstr; unfortunately without
897 * FAILONERROR it is lost, so we can give only the numeric
900 snprintf(curl_errorstr
, sizeof(curl_errorstr
),
901 "The requested URL returned error: %ld",
905 if (results
->curl_result
== CURLE_OK
) {
906 credential_approve(&http_auth
);
908 } else if (missing_target(results
))
909 return HTTP_MISSING_TARGET
;
910 else if (results
->http_code
== 401) {
911 if (http_auth
.username
&& http_auth
.password
) {
912 credential_reject(&http_auth
);
915 #ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
916 http_auth_methods
&= ~CURLAUTH_GSSNEGOTIATE
;
921 #if LIBCURL_VERSION_NUM >= 0x070c00
922 if (!curl_errorstr
[0])
923 strlcpy(curl_errorstr
,
924 curl_easy_strerror(results
->curl_result
),
925 sizeof(curl_errorstr
));
931 int run_one_slot(struct active_request_slot
*slot
,
932 struct slot_results
*results
)
934 slot
->results
= results
;
935 if (!start_active_slot(slot
)) {
936 snprintf(curl_errorstr
, sizeof(curl_errorstr
),
937 "failed to start HTTP request");
938 return HTTP_START_FAILED
;
941 run_active_slot(slot
);
942 return handle_curl_result(results
);
945 static CURLcode
curlinfo_strbuf(CURL
*curl
, CURLINFO info
, struct strbuf
*buf
)
951 ret
= curl_easy_getinfo(curl
, info
, &ptr
);
953 strbuf_addstr(buf
, ptr
);
958 * Check for and extract a content-type parameter. "raw"
959 * should be positioned at the start of the potential
960 * parameter, with any whitespace already removed.
962 * "name" is the name of the parameter. The value is appended
965 static int extract_param(const char *raw
, const char *name
,
968 size_t len
= strlen(name
);
970 if (strncasecmp(raw
, name
, len
))
978 while (*raw
&& !isspace(*raw
) && *raw
!= ';')
979 strbuf_addch(out
, *raw
++);
984 * Extract a normalized version of the content type, with any
985 * spaces suppressed, all letters lowercased, and no trailing ";"
988 * Note that we will silently remove even invalid whitespace. For
989 * example, "text / plain" is specifically forbidden by RFC 2616,
990 * but "text/plain" is the only reasonable output, and this keeps
993 * If the "charset" argument is not NULL, store the value of any
994 * charset parameter there.
997 * "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
998 * "text / plain" -> "text/plain"
1000 static void extract_content_type(struct strbuf
*raw
, struct strbuf
*type
,
1001 struct strbuf
*charset
)
1006 strbuf_grow(type
, raw
->len
);
1007 for (p
= raw
->buf
; *p
; p
++) {
1014 strbuf_addch(type
, tolower(*p
));
1020 strbuf_reset(charset
);
1022 while (isspace(*p
) || *p
== ';')
1024 if (!extract_param(p
, "charset", charset
))
1026 while (*p
&& !isspace(*p
))
1030 if (!charset
->len
&& starts_with(type
->buf
, "text/"))
1031 strbuf_addstr(charset
, "ISO-8859-1");
1034 static void write_accept_language(struct strbuf
*buf
)
1037 * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1038 * that, q-value will be smaller than 0.001, the minimum q-value the
1039 * HTTP specification allows. See
1040 * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1042 const int MAX_DECIMAL_PLACES
= 3;
1043 const int MAX_LANGUAGE_TAGS
= 1000;
1044 const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE
= 4000;
1045 char **language_tags
= NULL
;
1047 const char *s
= get_preferred_languages();
1049 struct strbuf tag
= STRBUF_INIT
;
1051 /* Don't add Accept-Language header if no language is preferred. */
1056 * Split the colon-separated string of preferred languages into
1057 * language_tags array.
1060 /* collect language tag */
1061 for (; *s
&& (isalnum(*s
) || *s
== '_'); s
++)
1062 strbuf_addch(&tag
, *s
== '_' ? '-' : *s
);
1064 /* skip .codeset, @modifier and any other unnecessary parts */
1065 while (*s
&& *s
!= ':')
1070 REALLOC_ARRAY(language_tags
, num_langs
);
1071 language_tags
[num_langs
- 1] = strbuf_detach(&tag
, NULL
);
1072 if (num_langs
>= MAX_LANGUAGE_TAGS
- 1) /* -1 for '*' */
1077 /* write Accept-Language header into buf */
1079 int last_buf_len
= 0;
1085 REALLOC_ARRAY(language_tags
, num_langs
+ 1);
1086 language_tags
[num_langs
++] = "*"; /* it's OK; this won't be freed */
1088 /* compute decimal_places */
1089 for (max_q
= 1, decimal_places
= 0;
1090 max_q
< num_langs
&& decimal_places
<= MAX_DECIMAL_PLACES
;
1091 decimal_places
++, max_q
*= 10)
1094 sprintf(q_format
, ";q=0.%%0%dd", decimal_places
);
1096 strbuf_addstr(buf
, "Accept-Language: ");
1098 for (i
= 0; i
< num_langs
; i
++) {
1100 strbuf_addstr(buf
, ", ");
1102 strbuf_addstr(buf
, language_tags
[i
]);
1105 strbuf_addf(buf
, q_format
, max_q
- i
);
1107 if (buf
->len
> MAX_ACCEPT_LANGUAGE_HEADER_SIZE
) {
1108 strbuf_remove(buf
, last_buf_len
, buf
->len
- last_buf_len
);
1112 last_buf_len
= buf
->len
;
1116 /* free language tags -- last one is a static '*' */
1117 for (i
= 0; i
< num_langs
- 1; i
++)
1118 free(language_tags
[i
]);
1119 free(language_tags
);
1123 * Get an Accept-Language header which indicates user's preferred languages.
1127 * LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1128 * LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1129 * LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1130 * LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1131 * LANGUAGE= LANG=C -> ""
1133 static const char *get_accept_language(void)
1135 if (!cached_accept_language
) {
1136 struct strbuf buf
= STRBUF_INIT
;
1137 write_accept_language(&buf
);
1139 cached_accept_language
= strbuf_detach(&buf
, NULL
);
1142 return cached_accept_language
;
1145 /* http_request() targets */
1146 #define HTTP_REQUEST_STRBUF 0
1147 #define HTTP_REQUEST_FILE 1
1149 static int http_request(const char *url
,
1150 void *result
, int target
,
1151 const struct http_get_options
*options
)
1153 struct active_request_slot
*slot
;
1154 struct slot_results results
;
1155 struct curl_slist
*headers
= NULL
;
1156 struct strbuf buf
= STRBUF_INIT
;
1157 const char *accept_language
;
1160 slot
= get_active_slot();
1161 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPGET
, 1);
1163 if (result
== NULL
) {
1164 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 1);
1166 curl_easy_setopt(slot
->curl
, CURLOPT_NOBODY
, 0);
1167 curl_easy_setopt(slot
->curl
, CURLOPT_FILE
, result
);
1169 if (target
== HTTP_REQUEST_FILE
) {
1170 long posn
= ftell(result
);
1171 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
1174 strbuf_addf(&buf
, "Range: bytes=%ld-", posn
);
1175 headers
= curl_slist_append(headers
, buf
.buf
);
1179 curl_easy_setopt(slot
->curl
, CURLOPT_WRITEFUNCTION
,
1183 accept_language
= get_accept_language();
1185 if (accept_language
)
1186 headers
= curl_slist_append(headers
, accept_language
);
1188 strbuf_addstr(&buf
, "Pragma:");
1189 if (options
&& options
->no_cache
)
1190 strbuf_addstr(&buf
, " no-cache");
1191 if (options
&& options
->keep_error
)
1192 curl_easy_setopt(slot
->curl
, CURLOPT_FAILONERROR
, 0);
1194 headers
= curl_slist_append(headers
, buf
.buf
);
1196 curl_easy_setopt(slot
->curl
, CURLOPT_URL
, url
);
1197 curl_easy_setopt(slot
->curl
, CURLOPT_HTTPHEADER
, headers
);
1198 curl_easy_setopt(slot
->curl
, CURLOPT_ENCODING
, "gzip");
1200 ret
= run_one_slot(slot
, &results
);
1202 if (options
&& options
->content_type
) {
1203 struct strbuf raw
= STRBUF_INIT
;
1204 curlinfo_strbuf(slot
->curl
, CURLINFO_CONTENT_TYPE
, &raw
);
1205 extract_content_type(&raw
, options
->content_type
,
1207 strbuf_release(&raw
);
1210 if (options
&& options
->effective_url
)
1211 curlinfo_strbuf(slot
->curl
, CURLINFO_EFFECTIVE_URL
,
1212 options
->effective_url
);
1214 curl_slist_free_all(headers
);
1215 strbuf_release(&buf
);
1221 * Update the "base" url to a more appropriate value, as deduced by
1222 * redirects seen when requesting a URL starting with "url".
1224 * The "asked" parameter is a URL that we asked curl to access, and must begin
1227 * The "got" parameter is the URL that curl reported to us as where we ended
1230 * Returns 1 if we updated the base url, 0 otherwise.
1232 * Our basic strategy is to compare "base" and "asked" to find the bits
1233 * specific to our request. We then strip those bits off of "got" to yield the
1234 * new base. So for example, if our base is "http://example.com/foo.git",
1235 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1236 * with "https://other.example.com/foo.git/info/refs". We would want the
1237 * new URL to become "https://other.example.com/foo.git".
1239 * Note that this assumes a sane redirect scheme. It's entirely possible
1240 * in the example above to end up at a URL that does not even end in
1241 * "info/refs". In such a case we simply punt, as there is not much we can
1242 * do (and such a scheme is unlikely to represent a real git repository,
1243 * which means we are likely about to abort anyway).
1245 static int update_url_from_redirect(struct strbuf
*base
,
1247 const struct strbuf
*got
)
1252 if (!strcmp(asked
, got
->buf
))
1255 if (!skip_prefix(asked
, base
->buf
, &tail
))
1256 die("BUG: update_url_from_redirect: %s is not a superset of %s",
1259 tail_len
= strlen(tail
);
1261 if (got
->len
< tail_len
||
1262 strcmp(tail
, got
->buf
+ got
->len
- tail_len
))
1263 return 0; /* insane redirect scheme */
1266 strbuf_add(base
, got
->buf
, got
->len
- tail_len
);
1270 static int http_request_reauth(const char *url
,
1271 void *result
, int target
,
1272 struct http_get_options
*options
)
1274 int ret
= http_request(url
, result
, target
, options
);
1276 if (options
&& options
->effective_url
&& options
->base_url
) {
1277 if (update_url_from_redirect(options
->base_url
,
1278 url
, options
->effective_url
)) {
1279 credential_from_url(&http_auth
, options
->base_url
->buf
);
1280 url
= options
->effective_url
->buf
;
1284 if (ret
!= HTTP_REAUTH
)
1288 * If we are using KEEP_ERROR, the previous request may have
1289 * put cruft into our output stream; we should clear it out before
1290 * making our next request. We only know how to do this for
1291 * the strbuf case, but that is enough to satisfy current callers.
1293 if (options
&& options
->keep_error
) {
1295 case HTTP_REQUEST_STRBUF
:
1296 strbuf_reset(result
);
1299 die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1303 credential_fill(&http_auth
);
1305 return http_request(url
, result
, target
, options
);
1308 int http_get_strbuf(const char *url
,
1309 struct strbuf
*result
,
1310 struct http_get_options
*options
)
1312 return http_request_reauth(url
, result
, HTTP_REQUEST_STRBUF
, options
);
1316 * Downloads a URL and stores the result in the given file.
1318 * If a previous interrupted download is detected (i.e. a previous temporary
1319 * file is still around) the download is resumed.
1321 static int http_get_file(const char *url
, const char *filename
,
1322 struct http_get_options
*options
)
1325 struct strbuf tmpfile
= STRBUF_INIT
;
1328 strbuf_addf(&tmpfile
, "%s.temp", filename
);
1329 result
= fopen(tmpfile
.buf
, "a");
1331 error("Unable to open local file %s", tmpfile
.buf
);
1336 ret
= http_request_reauth(url
, result
, HTTP_REQUEST_FILE
, options
);
1339 if (ret
== HTTP_OK
&& move_temp_to_file(tmpfile
.buf
, filename
))
1342 strbuf_release(&tmpfile
);
1346 int http_fetch_ref(const char *base
, struct ref
*ref
)
1348 struct http_get_options options
= {0};
1350 struct strbuf buffer
= STRBUF_INIT
;
1353 options
.no_cache
= 1;
1355 url
= quote_ref_url(base
, ref
->name
);
1356 if (http_get_strbuf(url
, &buffer
, &options
) == HTTP_OK
) {
1357 strbuf_rtrim(&buffer
);
1358 if (buffer
.len
== 40)
1359 ret
= get_sha1_hex(buffer
.buf
, ref
->old_sha1
);
1360 else if (starts_with(buffer
.buf
, "ref: ")) {
1361 ref
->symref
= xstrdup(buffer
.buf
+ 5);
1366 strbuf_release(&buffer
);
1371 /* Helpers for fetching packs */
1372 static char *fetch_pack_index(unsigned char *sha1
, const char *base_url
)
1375 struct strbuf buf
= STRBUF_INIT
;
1377 if (http_is_verbose
)
1378 fprintf(stderr
, "Getting index for pack %s\n", sha1_to_hex(sha1
));
1380 end_url_with_slash(&buf
, base_url
);
1381 strbuf_addf(&buf
, "objects/pack/pack-%s.idx", sha1_to_hex(sha1
));
1382 url
= strbuf_detach(&buf
, NULL
);
1384 strbuf_addf(&buf
, "%s.temp", sha1_pack_index_name(sha1
));
1385 tmp
= strbuf_detach(&buf
, NULL
);
1387 if (http_get_file(url
, tmp
, NULL
) != HTTP_OK
) {
1388 error("Unable to get pack index %s", url
);
1397 static int fetch_and_setup_pack_index(struct packed_git
**packs_head
,
1398 unsigned char *sha1
, const char *base_url
)
1400 struct packed_git
*new_pack
;
1401 char *tmp_idx
= NULL
;
1404 if (has_pack_index(sha1
)) {
1405 new_pack
= parse_pack_index(sha1
, sha1_pack_index_name(sha1
));
1407 return -1; /* parse_pack_index() already issued error message */
1411 tmp_idx
= fetch_pack_index(sha1
, base_url
);
1415 new_pack
= parse_pack_index(sha1
, tmp_idx
);
1420 return -1; /* parse_pack_index() already issued error message */
1423 ret
= verify_pack_index(new_pack
);
1425 close_pack_index(new_pack
);
1426 ret
= move_temp_to_file(tmp_idx
, sha1_pack_index_name(sha1
));
1433 new_pack
->next
= *packs_head
;
1434 *packs_head
= new_pack
;
1438 int http_get_info_packs(const char *base_url
, struct packed_git
**packs_head
)
1440 struct http_get_options options
= {0};
1443 struct strbuf buf
= STRBUF_INIT
;
1444 unsigned char sha1
[20];
1446 end_url_with_slash(&buf
, base_url
);
1447 strbuf_addstr(&buf
, "objects/info/packs");
1448 url
= strbuf_detach(&buf
, NULL
);
1450 options
.no_cache
= 1;
1451 ret
= http_get_strbuf(url
, &buf
, &options
);
1456 while (i
< buf
.len
) {
1460 if (i
+ 52 <= buf
.len
&&
1461 starts_with(data
+ i
, " pack-") &&
1462 starts_with(data
+ i
+ 46, ".pack\n")) {
1463 get_sha1_hex(data
+ i
+ 6, sha1
);
1464 fetch_and_setup_pack_index(packs_head
, sha1
,
1470 while (i
< buf
.len
&& data
[i
] != '\n')
1481 void release_http_pack_request(struct http_pack_request
*preq
)
1483 if (preq
->packfile
!= NULL
) {
1484 fclose(preq
->packfile
);
1485 preq
->packfile
= NULL
;
1487 if (preq
->range_header
!= NULL
) {
1488 curl_slist_free_all(preq
->range_header
);
1489 preq
->range_header
= NULL
;
1496 int finish_http_pack_request(struct http_pack_request
*preq
)
1498 struct packed_git
**lst
;
1499 struct packed_git
*p
= preq
->target
;
1501 struct child_process ip
= CHILD_PROCESS_INIT
;
1502 const char *ip_argv
[8];
1504 close_pack_index(p
);
1506 fclose(preq
->packfile
);
1507 preq
->packfile
= NULL
;
1511 lst
= &((*lst
)->next
);
1512 *lst
= (*lst
)->next
;
1514 tmp_idx
= xstrdup(preq
->tmpfile
);
1515 strcpy(tmp_idx
+ strlen(tmp_idx
) - strlen(".pack.temp"),
1518 ip_argv
[0] = "index-pack";
1520 ip_argv
[2] = tmp_idx
;
1521 ip_argv
[3] = preq
->tmpfile
;
1529 if (run_command(&ip
)) {
1530 unlink(preq
->tmpfile
);
1536 unlink(sha1_pack_index_name(p
->sha1
));
1538 if (move_temp_to_file(preq
->tmpfile
, sha1_pack_name(p
->sha1
))
1539 || move_temp_to_file(tmp_idx
, sha1_pack_index_name(p
->sha1
))) {
1544 install_packed_git(p
);
1549 struct http_pack_request
*new_http_pack_request(
1550 struct packed_git
*target
, const char *base_url
)
1553 char range
[RANGE_HEADER_SIZE
];
1554 struct strbuf buf
= STRBUF_INIT
;
1555 struct http_pack_request
*preq
;
1557 preq
= xcalloc(1, sizeof(*preq
));
1558 preq
->target
= target
;
1560 end_url_with_slash(&buf
, base_url
);
1561 strbuf_addf(&buf
, "objects/pack/pack-%s.pack",
1562 sha1_to_hex(target
->sha1
));
1563 preq
->url
= strbuf_detach(&buf
, NULL
);
1565 snprintf(preq
->tmpfile
, sizeof(preq
->tmpfile
), "%s.temp",
1566 sha1_pack_name(target
->sha1
));
1567 preq
->packfile
= fopen(preq
->tmpfile
, "a");
1568 if (!preq
->packfile
) {
1569 error("Unable to open local file %s for pack",
1574 preq
->slot
= get_active_slot();
1575 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_FILE
, preq
->packfile
);
1576 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite
);
1577 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_URL
, preq
->url
);
1578 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_HTTPHEADER
,
1582 * If there is data present from a previous transfer attempt,
1583 * resume where it left off
1585 prev_posn
= ftell(preq
->packfile
);
1587 if (http_is_verbose
)
1589 "Resuming fetch of pack %s at byte %ld\n",
1590 sha1_to_hex(target
->sha1
), prev_posn
);
1591 sprintf(range
, "Range: bytes=%ld-", prev_posn
);
1592 preq
->range_header
= curl_slist_append(NULL
, range
);
1593 curl_easy_setopt(preq
->slot
->curl
, CURLOPT_HTTPHEADER
,
1594 preq
->range_header
);
1605 /* Helpers for fetching objects (loose) */
1606 static size_t fwrite_sha1_file(char *ptr
, size_t eltsize
, size_t nmemb
,
1609 unsigned char expn
[4096];
1610 size_t size
= eltsize
* nmemb
;
1612 struct http_object_request
*freq
=
1613 (struct http_object_request
*)data
;
1615 ssize_t retval
= xwrite(freq
->localfile
,
1616 (char *) ptr
+ posn
, size
- posn
);
1620 } while (posn
< size
);
1622 freq
->stream
.avail_in
= size
;
1623 freq
->stream
.next_in
= (void *)ptr
;
1625 freq
->stream
.next_out
= expn
;
1626 freq
->stream
.avail_out
= sizeof(expn
);
1627 freq
->zret
= git_inflate(&freq
->stream
, Z_SYNC_FLUSH
);
1628 git_SHA1_Update(&freq
->c
, expn
,
1629 sizeof(expn
) - freq
->stream
.avail_out
);
1630 } while (freq
->stream
.avail_in
&& freq
->zret
== Z_OK
);
1634 struct http_object_request
*new_http_object_request(const char *base_url
,
1635 unsigned char *sha1
)
1637 char *hex
= sha1_to_hex(sha1
);
1638 const char *filename
;
1639 char prevfile
[PATH_MAX
];
1641 char prev_buf
[PREV_BUF_SIZE
];
1642 ssize_t prev_read
= 0;
1644 char range
[RANGE_HEADER_SIZE
];
1645 struct curl_slist
*range_header
= NULL
;
1646 struct http_object_request
*freq
;
1648 freq
= xcalloc(1, sizeof(*freq
));
1649 hashcpy(freq
->sha1
, sha1
);
1650 freq
->localfile
= -1;
1652 filename
= sha1_file_name(sha1
);
1653 snprintf(freq
->tmpfile
, sizeof(freq
->tmpfile
),
1654 "%s.temp", filename
);
1656 snprintf(prevfile
, sizeof(prevfile
), "%s.prev", filename
);
1657 unlink_or_warn(prevfile
);
1658 rename(freq
->tmpfile
, prevfile
);
1659 unlink_or_warn(freq
->tmpfile
);
1661 if (freq
->localfile
!= -1)
1662 error("fd leakage in start: %d", freq
->localfile
);
1663 freq
->localfile
= open(freq
->tmpfile
,
1664 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
1666 * This could have failed due to the "lazy directory creation";
1667 * try to mkdir the last path component.
1669 if (freq
->localfile
< 0 && errno
== ENOENT
) {
1670 char *dir
= strrchr(freq
->tmpfile
, '/');
1673 mkdir(freq
->tmpfile
, 0777);
1676 freq
->localfile
= open(freq
->tmpfile
,
1677 O_WRONLY
| O_CREAT
| O_EXCL
, 0666);
1680 if (freq
->localfile
< 0) {
1681 error("Couldn't create temporary file %s: %s",
1682 freq
->tmpfile
, strerror(errno
));
1686 git_inflate_init(&freq
->stream
);
1688 git_SHA1_Init(&freq
->c
);
1690 freq
->url
= get_remote_object_url(base_url
, hex
, 0);
1693 * If a previous temp file is present, process what was already
1696 prevlocal
= open(prevfile
, O_RDONLY
);
1697 if (prevlocal
!= -1) {
1699 prev_read
= xread(prevlocal
, prev_buf
, PREV_BUF_SIZE
);
1701 if (fwrite_sha1_file(prev_buf
,
1704 freq
) == prev_read
) {
1705 prev_posn
+= prev_read
;
1710 } while (prev_read
> 0);
1713 unlink_or_warn(prevfile
);
1716 * Reset inflate/SHA1 if there was an error reading the previous temp
1717 * file; also rewind to the beginning of the local file.
1719 if (prev_read
== -1) {
1720 memset(&freq
->stream
, 0, sizeof(freq
->stream
));
1721 git_inflate_init(&freq
->stream
);
1722 git_SHA1_Init(&freq
->c
);
1725 lseek(freq
->localfile
, 0, SEEK_SET
);
1726 if (ftruncate(freq
->localfile
, 0) < 0) {
1727 error("Couldn't truncate temporary file %s: %s",
1728 freq
->tmpfile
, strerror(errno
));
1734 freq
->slot
= get_active_slot();
1736 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_FILE
, freq
);
1737 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_WRITEFUNCTION
, fwrite_sha1_file
);
1738 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_ERRORBUFFER
, freq
->errorstr
);
1739 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_URL
, freq
->url
);
1740 curl_easy_setopt(freq
->slot
->curl
, CURLOPT_HTTPHEADER
, no_pragma_header
);
1743 * If we have successfully processed data from a previous fetch
1744 * attempt, only fetch the data we don't already have.
1747 if (http_is_verbose
)
1749 "Resuming fetch of object %s at byte %ld\n",
1751 sprintf(range
, "Range: bytes=%ld-", prev_posn
);
1752 range_header
= curl_slist_append(range_header
, range
);
1753 curl_easy_setopt(freq
->slot
->curl
,
1754 CURLOPT_HTTPHEADER
, range_header
);
1765 void process_http_object_request(struct http_object_request
*freq
)
1767 if (freq
->slot
== NULL
)
1769 freq
->curl_result
= freq
->slot
->curl_result
;
1770 freq
->http_code
= freq
->slot
->http_code
;
1774 int finish_http_object_request(struct http_object_request
*freq
)
1778 close(freq
->localfile
);
1779 freq
->localfile
= -1;
1781 process_http_object_request(freq
);
1783 if (freq
->http_code
== 416) {
1784 warning("requested range invalid; we may already have all the data.");
1785 } else if (freq
->curl_result
!= CURLE_OK
) {
1786 if (stat(freq
->tmpfile
, &st
) == 0)
1787 if (st
.st_size
== 0)
1788 unlink_or_warn(freq
->tmpfile
);
1792 git_inflate_end(&freq
->stream
);
1793 git_SHA1_Final(freq
->real_sha1
, &freq
->c
);
1794 if (freq
->zret
!= Z_STREAM_END
) {
1795 unlink_or_warn(freq
->tmpfile
);
1798 if (hashcmp(freq
->sha1
, freq
->real_sha1
)) {
1799 unlink_or_warn(freq
->tmpfile
);
1803 move_temp_to_file(freq
->tmpfile
, sha1_file_name(freq
->sha1
));
1805 return freq
->rename
;
1808 void abort_http_object_request(struct http_object_request
*freq
)
1810 unlink_or_warn(freq
->tmpfile
);
1812 release_http_object_request(freq
);
1815 void release_http_object_request(struct http_object_request
*freq
)
1817 if (freq
->localfile
!= -1) {
1818 close(freq
->localfile
);
1819 freq
->localfile
= -1;
1821 if (freq
->url
!= NULL
) {
1825 if (freq
->slot
!= NULL
) {
1826 freq
->slot
->callback_func
= NULL
;
1827 freq
->slot
->callback_data
= NULL
;
1828 release_active_slot(freq
->slot
);